text
stringlengths 37
1.41M
|
---|
# Дан словарь. Добавить каждому ключу число равное длине этого ключа
# решение №1
dictionary = {'test': 'test_value', 'europe': 'eur', 'dollar': 'usd', 'ruble': 'rub'}
print(dictionary)
for key in list(dictionary.keys()): # проходим циклом по списку ключей
dictionary[f'{key}{len(key)}'] = dictionary.pop(key)
print(dictionary)
# решение №2
new_dictionary = {'test': 'test_value', 'europe': 'eur', 'dollar': 'usd', 'ruble': 'rub'}
print(new_dictionary)
i = 0 # счетчик для цикла
keys = list(new_dictionary.keys()) # список ключей
while i < len(keys):
new_dictionary[f'{keys[i]}{len(keys[i])}'] = new_dictionary.pop(keys[i])
i += 1
print(new_dictionary)
|
"""Создать класс Car. Атрибуты: марка, модель, год выпуска, скорость(по умолчанию 0).
Методы: увеличить скорости(скорость + 5), уменьшение скорости(скорость - 5), стоп(сброс скорости на 0),
отображение скорости, разворот(изменение знака скорости). Все атрибуты приватные."""
class Car:
def __init__(self, brand, model, year, speed=0):
self.__brand = brand
self.__model = model
self.__year = year
self.__speed = speed
def __str__(self):
return f'{self.__brand}, {self.__model}, {self.__year}, {self.__speed}'
def up_speed(self):
self.__speed += 5
def down_speed(self):
self.__speed -= 5
def stop(self):
self.__speed = 0
@property
def speed(self):
return self.__speed
@speed.setter
def speed(self, speed):
self.__speed = speed
new_car = Car('Мерседес', 's600', 2020)
print(new_car)
new_car.up_speed()
new_car.up_speed()
new_car.up_speed()
print(new_car.speed)
new_car.speed = 10
print(new_car.speed)
new_car.stop()
print(new_car.speed)
|
""" Дана целочисленная квадратная матрица. Найти в каждой строке
наи- больший элемент и поменять его местами с элементом главной диагонали."""
import random
n = 5 # размер матрицы
m = [[random.randint(1, 10) for i in range(n)] for i in range(n)]
for row in m:
print(row)
max = 0
diagonal = 0
index_max_number = 0
for row in range(len(m)):
max = 0
stolb = 0
for el in range(len(m[row])):
if m[row][el] > max:
max = m[row][el]
index_max_number = el # запоминаем индекс максимального значения из строки
m[row][index_max_number] = m[row][diagonal] # минаем максимальное значение из строки на число из диагонали
diagonal += 1 # счетчик для диагонали
print()
print()
for row in m:
print(row)
|
""" Создать lambda функцию, которая принимает на вход
неопределенное количество именных аргументов и выводит
словарь с ключами удвоенной длины. {‘abc’: 5} -> {‘abcabc’: 5} """
double = lambda **kwargs: {k * 2: v for k, v in kwargs.items()}
print(double(hello=5, goodbye=7, howareyou=9))
|
#! /usr/bin/python
import sys
import math
import time
def foo(x):
return math.log1p(x)
num1 = input("Enter first number: \n")
num2 = input("Enter second number: \n")
print "Adding ",num1," and ",num2," equals: ",num1+num2,"\n"
time.sleep(1)
print "Subtracting ",num1," and ",num2," equals: ",num1-num2,"\n"
time.sleep(1)
print "Multiplying ",num1," and ",num2," equals: ",num1*num2,"\n"
time.sleep(1)
print "Dividing ",num1," by ",num2," equals: ",num1/float(num2),"\n"
time.sleep(1)
print "The natural log of ",num1," is ",foo(num1),"\n"
time.sleep(1)
print "The sqiare of ",num1," is ",num1*num1
|
class Writer:
def __init__(self, file):
self.__file = file
def write(self, persons):
fout = open(self.__file, 'a+', encoding='utf-8')
for person in persons:
fout.write(str(person) + '\n')
fout.close
|
__author__ = 'liuhuiping'
#PI
def GetPI(index = 3):
return round(355/113,index)
if __name__ =="__main__":
print('date strunct test')
print("list's method example" )
a = [665.3,443,45,23,665.3]
print(a.count(333),a.count(665.3),a.count('x'))
a.insert(2,-1)
a.append(333)
print(a)
print(a.index(333))
a.remove(333)
a.reverse()
print(a)
a.sort()
print(a)
#把列表当堆栈使用
stack = [3,4,5]
stack.append(6)
stack.append(7)
print(stack)
for i in range(len(stack)):
print(stack.pop(),end=',')
print()
#把列表当队列使用
from collections import deque
queue = deque(['Eric','john','Michael'])
queue.append('Terry')
queue.append('Grahm')
for i in range(len(queue)):
print(queue.popleft(),end=',')
print()
#列表推导式
vec = [2,3,4]
vec2 = [3 * x for x in vec]
print(vec2)
vec3 = [[x, x **2] for x in vec]
print(vec3)
freshfruit = [' banana','loganberry ',' passion fruit']
print(freshfruit)
test = [weap.strip() for weap in freshfruit]
print(test)
vec4 = [3 * x for x in vec if x > 3]
vec5 = [3 * x for x in vec if x < 2]
print(vec4)
print(vec5)
#这里是一些循环的嵌套和其它技巧的演示:
vecX = [2,4,6]
vecY = [4,3,-9]
vecXY = [x * y for x in vecX for y in vecY]
print('vecXY: ',vecXY)
vecXplusY = [x + y for x in vecX for y in vecY]
print('vecXplusY: ',vecXplusY)
vecXY2 = [vecX[i] * vecY[i] for i in range(len(vecX))]
print('vecXY2: ',vecXY2)
print([str(round(355/113,i)) for i in range(1,6)]) # PI 的值
print(GetPI(10))
#嵌套列表推导
mat = [
[1,2,3],
[4,5,6],
[7,8,9]
]
print([[row[i] for row in mat] for i in [0,1,2]])
#上句的冗长表达式
for i in [0,1,2]:
for row in mat:
print(row[i],end=" ")
print()
#现实中, 你应当选择内建函式来处理复杂流程. 这里, 函式 zip() 就非常好用.
print(list(zip(*mat)))
#del 语句
a = [-1,1,43.4,333,456,1234.5]
del a[0]
print(a)
del a[-1]
print(a)
del a[2:3]
print(a)
del a
# print(a) # exception a has been deleted
#元组 序列 tuple
t = 12345,54321,'hello' #元组打包
print(t)
print(t[0])
u = t,(1,2,3,4)
print(u)
u += (6,7,8,9)
print(u)
x,y,z = t #序列解包
print(z,y,x,sep='|')
#集合 Set 集合是种无序不重复的元素集
# 集合对象也支持合 (union),交 (intersection), 差 (difference), 和对称差 (sysmmetric difference) 等数学操作.
basket = {'apple','orange','apple','apple','pear'}
print(basket) #重复的被移除
#集合操作
a = set('badadebdeade')
b = set('edefohde')
print(a)
print(b)
print(a-b) #交集
print(a|b) #并集
print(a&b) #同或
print(a^b) #异或
a ={x for x in 'abracadabra' if x not in 'abc'}
print(a)
#字典 Mapping types - dict key-value
tel = {'jack':4098,'sape':9832}
tel['guilo'] = 4271
print(tel)
del tel['sape']
print(tel)
tel['Iris'] = 8451
print(tel)
lst = list(tel.keys())
print(lst)
sorted(tel.keys())
print(tel)
print('jack' in tel)
tel2 = dict(jack=1024,sape=2048,Iris=8983,guilo=4343)
print(tel2)
#遍历技巧
knights = {'gallahad':'the pure','robin':'the brave'}
for k,v in knights.items():
print(k,v,sep=':')
for i, v in enumerate(['tic','tac','toel']):
print(i,v)
print()
row = ['jack','broc','sepx']
for i,v in enumerate(row):
print(i,v)
print()
question = ['name','quest','favorite color']
answer = ['lancelot','the holy grail','blue']
for q,a in zip(question,answer):
print('what is your {0} ? It is {1}'.format(q,a))
print()
for i in reversed(range(1,20,2)):
print(i,end=',')
print()
for f in sorted(set(basket)):
print(f)
print() |
"""
Parses a text file with config variables to a dictionary
"""
def read_config_file(filename, delimiter='='):
# Open file
with open(filename, 'r') as f:
lines = f.readlines()
output = {}
# Iterate through file
for l, line in enumerate(lines):
if line[0] == '#' or line[0] == '\n':
continue
# Remove white space and new line char
line = line.replace(' ', '').replace('\n', '')
# Get key/value
try:
element = line.split(delimiter)
if len(element) != 2:
raise ValueError(
("line %d has invalid format. Use one single delimiter '%c'.") % (l+1, delimiter))
key, value = element
except ValueError as v:
print("Error reading '%s':" % filename, v)
exit(1)
# Add pair to dict
output[key] = value
return output
|
# -*- coding: utf-8
from __future__ import unicode_literals
import random
from components.card import Card
class Deck(object):
# How many cards to print before a line break happens.
linebreak_index = 5
# Map the suit to a textual representation.
#suits = {'heart': '\u2665',
# 'diamond': '\u2666',
# 'club': '\u2667',
# 'spade': '\u2664',}
suits = {'heart': '♥',
'diamond': '♦',
'club': '♧',
'spade': '♤',}
def __init__(self, name='Deck', cards=None):
"""Initialization."""
self.name = name
self.cards = cards
if not cards:
self.generate_deck()
def generate_deck(self, shuffled=True):
"""Generate a deck of 52 unshuffled cards."""
self.cards = []
for suit in self.suits.values():
for value in range(1, 14):
card = Card(suit, value)
self.cards.append(card)
if shuffled:
self.shuffle_deck()
def shuffle_deck(self):
"""Shuffle the deck in place."""
random.shuffle(self.cards)
def __str__(self):
"""String representation."""
output = []
i = 0
for card in self.cards:
if i and i % self.linebreak_index == 0:
output.append('\n')
i += 1
card = str(card).ljust(7, ' ')
output.append(card)
return ''.join(output)
|
#all work and no play makes Jack a dull boy
w1="all"
#w2="work"
w3="and"
w4="no"
w5="play"
w6="makes"
w7="Jack"
w8="a"
w9="dull"
w10="boy"
s=" "
#print(w1+w2+w3+w4+w5+w6+w7+w8 + w9 + s+w10)
print(w1,w2,w3,w4,w5,w6,w7,w8,w9,w10)
# hey I got this error please help
#Traceback (most recent call last):
# File "C:\Users\Admin\Documents\GitHub\chapter-2-exercises-justishawkins\Sentence.py", line 15, in <module>
# print(w1,w2,w3,w4,w5,w6,w7,w8,w9,w10)
#NameError: name 'w2' is not defined |
apostas =[]
nomes =[]
import random
num = 0
def menu () :
print ("==========================================")
print ("Opções: ")
print ("1 - Adicionar aposta")
print ("2 - Listar apostas")
print ("3 - Sortear um número")
print ("4 - Apresentar o ganhador")
print ("5 - Sair")
def addAposta():
aposta = int(input("Digite a sua aposta, entre 1 e 20: "))
apostas.append (aposta)
print (aposta)
def addNome():
nome = (input("Digite o seu nome: "))
nomes.append (nome)
print (nome)
def lista():
for i in range (len(apostas)) :
aposta = apostas[i]
nome = nomes [i]
print (f"Nome: {nome}, Aposta: {aposta}")
def aleatorio():
sorteio = random.randrange(1, 3)
print (f"Número sorteado: {sorteio}")
return sorteio
def ganhador() :
teveGanhador = 0
print (num)
for i in range (len(apostas)) :
aposta = apostas[i]
nome = nomes [i]
if num == aposta :
print (f"O ganhador é {nome}")
teveGanhador = 1
if teveGanhador == 0 :
print (f"Ninguém ganhou o sorteio!")
opcao = 0
while opcao !=5:
menu()
opcao = int(input("Digite a opção: "))
if opcao == 1:
addAposta()
addNome()
if opcao == 2:
lista()
if opcao == 3:
num = aleatorio()
if opcao == 4:
ganhador()
print("Acabou o sorteio") |
numeros = [10,20,30,40,50]
nomes = ["marcos", "jose", "julia"]
for numero in numeros :
print (numero)
for nome in nomes:
print (nome)
#########################
numeros = [10,20,30,40,50]
soma = 0
for numero in numeros :
soma = soma + numero
print (soma)
#######################
numeros = [10,20,30,40,50]
for i in range (len(numeros)) :
numero = numeros[i]
print (numero)
for i in range (len(numeros)) :
print (i)
#---------------------------------------
numeros = [10,20,30,40,50]
for i in range (len(numeros)) :
numero = numeros[i]
print (numero)
#---------------------------------------
for numero in numeros :
print (numero)
##########################
for i in range (len(numeros)) :
numero = numeros[i]
print (f"Número {i}: {numero}")
#-------------------------------------------
numeros = [2,5]
print (len(numeros))
numeros.append(10)
numeros.append(20)
numeros.append(30)
print (len(numeros))
for numero in numeros:
print (numero) |
from fighters.classes import Fighter
from typing import List
import time
class Combat:
def __init__(self, final_boss: Fighter, fighters: List[Fighter]):
self.final_boss = final_boss
self.fighters = fighters
@property
def fighters_still_alive(self):
return all([
fighter.is_alive for fighter in self.fighters
])
@staticmethod
def _print_combat_result(final_boss: Fighter, fighters: List[Fighter], final_boss_won: bool):
print(
"""
______ _ _
| ___ \ | | | _
| |_/ /___ ___ _ _| | |_ ___(_)
| // _ \/ __| | | | | __/ __|
| |\ \ __/\__ \ |_| | | |_\__ \_
\_| \_\___||___/\__,_|_|\__|___(_)
"""
)
print('Boss stats:', final_boss)
print('==========================')
for fighter in fighters:
print('Fighter: ', fighter)
if final_boss_won:
print('Sorry, bad guys won this time :(')
else:
print('Yaaaaay! Good guys won again!')
def print_results(self):
self._print_combat_result(
final_boss=self.final_boss,
fighters=self.fighters,
final_boss_won=self.final_boss.is_alive
)
def start(self):
"""
Simulate a turn based combat. First, the fighters will attack the final boss.
If the final boss is alive after the fighters attack, the final boss will attack the fighters.
"""
while self.final_boss.is_alive and self.fighters_still_alive:
# First, the fighters attack the final boss
for fighter in self.fighters:
print('\nFighters are starting their attack!!')
print('Fighter {} attacked final boss {}'.format(fighter.name, self.final_boss.name))
fighter.attack(self.final_boss)
print('Boss health: ', self.final_boss.health)
time.sleep(0.5)
# Then, if the final boss is alive he attacks the fighters
if self.final_boss.is_alive:
print('\nFinal boss is starting his attack!!')
for fighter in self.fighters:
if fighter.is_alive:
print('Boss {} attacked fighter {}'.format(self.final_boss.name, fighter.name))
self.final_boss.attack(fighter)
print('Fighter health: ', fighter.health)
time.sleep(0.5)
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
# In[9]:
def flipBit(s, prob):
assert s in ["0", "1"]
assert prob in [0,1]
if prob==1:
return '1' if s=='0' else '0'
return s
def applyIndividualBounds(x, lower = -1, upper = 1):
#x (float)
x = max(x,lower)
x = min(x, upper)
return x
def applyBounds(x):
#x = np.divide(x, max(x))
new=[]
for i in range(len(x)):
new.append(applyIndividualBounds(x[i]))
return np.around(new, 2)
def float2binary(parent, nvar, ndec=2, chromosome_size=11):
"""
Converts each of the nvar values of the parent to binary of size "chromosome_size" and concatenates them
to 1 string
Args:
parent (list) - list of nvar floating values
nvar (int) - no. of variables, the size of parent
ndec (int) - max no. of decimal points of each values in parent
chromosome_size (int) - no. of bits to which each value in parent is converted
Return:
parent_bin (str) - binary no. string made by concatenating each value's binary equivalent
"""
parent_bin = ""
for i in range(nvar):
val = int(parent[i]*10**ndec) #converting from float to int, later will be converted back
if val<0:
val=-1*val
binary = bin(val)[2:]
binary = "0"*(chromosome_size-len(binary)) + binary
parent_bin = parent_bin + binary
return parent_bin
def binary2float(child, nvar, ndec=2, chromosome_size=11):
"""
Converts the child string to nvar float values by reversin the effect of float2binary
Args:
child (str) - binary no. string made by concatenating each value's binary equivalent,
size - nvar*chromosome_size
nvar (int) - no. of variables whose binary are concatenated in child
ndec (int) - max no. of decimal points of each values
chromosome_size (int) - no. of bits of each value in child
Return:
child (list) - list of nvar floating values
"""
child_float = []
for i in range(nvar):
val = child[i*chromosome_size:(i+1)*chromosome_size]
val = int(val, 2)/10**ndec #converting to float, reversing the effect of binary conversion
child_float.append(val)
return child_float
def tournament_selection(npop, cost, population):
"""
Selects a parent for mating besed on touranment selection
Args:
npop (int)- population size
rank (dict) - a dictionary containing the ranks of each member from current population
"""
parent1 = np.random.randint(0, npop)
parent2 = np.random.randint(0, npop)
p1 = population[parent1]
p2 = population[parent2]
return (parent1 if cost(p1)<cost(p2) else parent2)
def crossover(parent1, parent2, nvar=2, ndec=2, prob = 0.95, chromosome_size = 11):
"""
Perfroms two point genetic crossover and returns the new children
NOTE - Does not apply bouds to new child here!
Args:
parent1, parent2 (list) - parents each containing nvar values
ndec (int) - max no. of decimal points in values contained in parents
prob (float) - the probabilty for doing crossover
chromosome_size (int)- the size of the binary equivalent of largest no. in var_size
Return:
child1, child2 (list)
"""
parent1_ = float2binary(parent1, nvar, ndec, chromosome_size)
parent2_ = float2binary(parent2, nvar, ndec, chromosome_size)
crossover_point1 = np.random.randint(2,chromosome_size*nvar//2)
crossover_point2 = np.random.randint(1+chromosome_size*nvar//2, chromosome_size*nvar-1)
if np.random.rand()<=prob:
child1 = parent1_[:crossover_point1] + parent2_[crossover_point1:crossover_point2] + parent1_[crossover_point2:]
child2 = parent2_[:crossover_point1] + parent1_[crossover_point1:crossover_point2] + parent2_[crossover_point2:]
child1 = binary2float(child1, nvar, ndec, chromosome_size)
child2 = binary2float(child2, nvar, ndec, chromosome_size)
for i in range(nvar):
if parent1[i]<0:
child1[i]*=-1
if parent2[i]<0:
child2[i]*=-1
return child1, child2
return parent1, parent2
def mutation(child, nvar = 2, ndec = 2, chromosome_size = 11, mutRate = 0.005):
"""
Performs mutation on the child by converting it to binary and flipping each bit on prob = mutRate
NOTE - Does not do applyBounds
"""
childBin = float2binary(child, nvar, ndec, chromosome_size)
flip = np.int32(np.random.randn(chromosome_size*nvar)<=mutRate)
mutChild = ''
for i in range(chromosome_size*nvar):
mutChild = mutChild + flipBit(childBin[i], flip[i])
mutChild = binary2float(mutChild, nvar, ndec, chromosome_size)
for i in range(nvar):
mutChild[i]=mutChild[i]*np.random.choice([-1,1])
return mutChild
# In[11]:
def Optimizer(evalcost, paramInitialiser, param2list, npop = 10, niter = 200,nvar = 2,
crossoverProb = 0.85, mutationRate = 0.5):
"""
Genetic algorithm optimiser
cost - cost function as a function of params (list)
params - list
pramInitialiser - function
param2list - function
"""
population = []
costs = []
params = None
cache = []
#initialize_params
for i in range(npop):
params = paramInitialiser()
params = param2list(params)
population.append(params)
nvar = len(params)
for i in range(niter):
params = population[0]
costs.append(evalcost(params))
cache.append(params)
for j in range(npop//2):
#selection
p1 = tournament_selection(npop, evalcost, population)
p2 = tournament_selection(npop, evalcost, population)
#crossover & mutaion
c1, c2 = crossover(population[p1], population[p2],nvar = nvar, prob=crossoverProb)
c1, c2 = mutation(c1, nvar = nvar, mutRate= mutationRate), mutation(c2, nvar = nvar,mutRate=mutationRate)
#applying bounds
c1, c2 = applyBounds(c1), applyBounds(c2)
#adding childrent to the population
population.append(c1)
population.append(c2)
population = list(sorted(population, key=lambda x:evalcost(x)))
population = population[:npop]
return (population[0], costs, cache)
# In[ ]:
|
import unittest
import Judge
import Board
class JudgeTest(unittest.TestCase):
def setUp(self):
self.winners = [['X', 'X', 'X', ' ', ' ', ' ', ' ', ' ', ' ']
,[' ', ' ', ' ', 'X', 'X', 'X', ' ', ' ', ' ']
,[' ', ' ', ' ', ' ', ' ', ' ', 'X', 'X', 'X']
,['X', ' ', ' ', 'X', ' ', ' ', 'X', ' ', ' ']
,[' ', 'X', ' ', ' ', 'X', ' ', ' ', 'X', ' ']
,[' ', ' ', 'X', ' ', ' ', 'X', ' ', ' ', 'X']
,['X', ' ', ' ', ' ', 'X', ' ', ' ', ' ', 'X']
,[' ', ' ', 'X', ' ', 'X', ' ', 'X', ' ', ' ']]
def test_Winners(self):
"""Do all winning boards evaluate as a winner?"""
for w in self.winners:
board = Board.Board()
board.tokens = w
judge = Judge.Judge(board)
result = judge.isWinner()
self.assertEqual(result, "X")
def test_notWinnerNotDone(self):
"""Do we get the correct response for an unfinished game?"""
tokens = ['X', 'O', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
board = Board.Board()
board.tokens = tokens
judge = Judge.Judge(board)
result = judge.isWinner()
self.assertEqual(result, None)
def test_draw(self):
"""Do we get the correct response for a draw game?"""
tokens = ['X', 'O', 'X', 'X', 'O', 'X', 'O', 'X', 'O']
board = Board.Board()
board.tokens = tokens
judge = Judge.Judge(board)
result = judge.isWinner()
self.assertEqual(result, None)
def test_evalGame(self):
"""Is the game still going?"""
board = Board.Board()
judge = Judge.Judge(board)
result = judge.evalGame()
self.assertEqual(result, [None, None])
def test_evalGameWinner(self):
"""Is the game Over with a winner?"""
board = Board.Board()
board.tokens = ['X', 'X', 'X', 'O', 'X', 'O', 'O', 'X', 'O']
judge = Judge.Judge(board)
result = judge.evalGame()
self.assertEqual(result, ['X','done'])
def test_evalGameDraw(self):
"""Is the game Over with a draw?"""
board = Board.Board()
board.tokens = ['X', 'O', 'X', 'O', 'X', 'O', 'O', 'X', 'O']
judge = Judge.Judge(board)
result = judge.evalGame()
self.assertEqual(result, [None,'done'])
|
import unittest
from Mars import *
# Goal for these tests is to make sure that if the user input is valid, the Mars Landing Area object is created successfully
class mars_tests(unittest.TestCase):
def test_create_mars_landing_area_coordinate_input(self):
landing_area = create_mars_landing_area(5, 5)
x = landing_area.x
y = landing_area.y
landing_area_coordinates = str(x) + " " + str(y)
expected_landing_area_coordinates = "5 5"
self.assertEqual(landing_area_coordinates, expected_landing_area_coordinates)
def testCreateMarsLandingAreaEmpyTakentList(self):
landing_area = create_mars_landing_area(5, 5)
intial_taken_list = landing_area.taken
empty_list = []
self.assertEqual(intial_taken_list, empty_list)
if __name__ == '__main__':
unittest.main() |
import urllib2
import json
#import os
word = raw_input("Enter word to search ")
print("Word: "+ word)
url = 'http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=' + word + '&pretty=true'
#url stores the json formatted output from Glosbe
result = json.load(urllib2.urlopen(url)) #json representation of url
print("Meanings: ")
i = 1
for mean in result['tuc'][0]['meanings']:
print(str(i) + ". " + mean['text'] + "\n")
i += 1
|
import csv
import os
#file_to_load = os.path.join("Election_Analysis", "election_results.csv")
#with open(file_to_load) as election_data:
#print(election_data)
file_to_save = os.path.join("analysis", "election.analysis.txt")
open(file_to_save, "w")
with open(file_to_save, "w") as txt_file:
#outfile.write("Hello World!")
#outfile.close()
#outfile.write("Arapahoe")
#outfile.write("Denver")
#outfile.write("Jefferson")
txt_file.write("Arapahoe, Denver, Jefferson")
txt_file.write("Arapahoe\nDenver\nJefferson")
# Add our dependencies.
import csv
import os
# Assign a variable to load a file from a path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")
print("Hello World!")
# Open the election results and read the file.
with open(file_to_load) as election_data:
#to do: read and analyze data here.
#file_reader = csv.reader(election_data)
#for row in file_reader:
#print(row)
file_reader = csv.reader(election_data)
#print the header row
headers = next(file_reader)
print(headers) |
import numpy as np
def example(x):
return np.sum(x**2)
def example_grad(x):
return 2*x
def foo(x):
result = 1
λ = 4 # this is here to make sure you're using Python 3
for x_i in x:
result += x_i**λ
return result
def foo_grad(x):
return 4*x**3
def bar(x):
return np.prod(x)
def bar_grad(x):
lenX = len(x)
grad = np.ones(lenX)
for i in range(lenX):
for j in range(lenX):
if i != j:
grad[i] *= x[j]
return grad
|
# Heaviside step function
numbers = [-4,-3.5,-3,-2.5,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,2.5,3,3.5,4]
for x in numbers:
def heaviside(x):
"""Heaviside step function"""
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
return theta
theta = heaviside(x)
print(theta)
|
#def greet():
# print('hello world')
# greet()
def area(radius):
return 3.142 * radius * radius
def vol(area, length):
print(area * length)
l = int(input('enter a length:'))
r = int(input('enter a radius: '))
areacalc = area(r)
vol(areacalc, l) |
a = int(input())
b = int(input())
print(a//b)
print(a%b)
print("({0}, {1})".format(a//b, a%b)) |
#Binary Tree is :
# - One node is marked as Root node
# - Every node other than the root is associated with one parent node
# - Each node can have an arbiatry number of child node
# tree
# ----
# j < -- root
# / \
# f k
# / \ \
# a h z <-- leaves
#Creating Node
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
#Insert
def insert(self, data):
#Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
#Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
root = Node(16)
root.insert(10)
root.insert(20)
root.insert(5)
root.insert(15)
root.insert(22)
root.insert(8)
root.PrintTree()
|
#Mo dau ve Tuple
#duoc gioi han boi cap ngoac ()
#cac phan tu cua tuple duoc ngan cach boi dau ,
#tuple co kha nang chu moi gia tri
#toc do truy xuat cua tuple nhanh hon list
#dung luong chiem trong bo nho nho hon list
#bao ve du lieu cua ban se khong thay doi
#co the dung lam key cua dictionary
tup = (1,1,2,5,6,'Kteam', 7,7, (2,5,6))
tup1 = (1) #Khong duoc tinh la mot tuple, la mot int
tup2 = (1,)
print(tup1, tup2)
print('------------------------------')
tup = (i for i in range(10)) #generator object from 0 ->9
a = tuple(tup)
print(tup)
print(a)
#=============================================
#Cac toan tu cua tuple giong voi chuoi
tup1 = (1,2,3)
a = tup1 + (2,4,6)
print(a)
#nhan tuple voi mot so
a = tup1*3
print(a)
# in : kiem tra mot phan tu co trong tuple hay ko
a = 3 in tup1
print(a)
#truy xuat toi mot phan tu
a = tup1[0]
b = tup1[2]
c = tup1[-1]
print(a, b, c)
#do dai tuple
a = len(tup1)
print(a)
a = tup1[:-1]
print(a)
tup = [1,5,9,4]
tup[0] = 'Kteam'
tup = (1,5,9,4)
#ma tran
tup = ((1,2,3,4), (4,5,6,7),(7,8,9,10))
#Hash object : kieu du lieu ko the thay doi du lieu ben trong
#Tuple ko cho phep ban sua chua noi dung ben trong nos, khac voi list
#=============================================
#Cac phuong thuc cua Tuple
# count : Tim so lan suat hien cua 1 phan tu trong tuple
tup = (1,2,3,4,4,5,6,4,7)
a = tup.count(4)
print(a)
# index : tra ve vi tri xuat hien dau tien cua phan tu
a = tup.index(6)
print(a)
print('------------------------------')
#=============================================
#Cac ham lien quan den Tuple
# map(): Tra ve mot list dua tren mot dieu kien cho truoc
tuple = (1, 2, 3, 4, 5)
def square(x):
return x ** 2
result = map(square, tuple)
print(result)
# filter(): Tra ve mot List duoc loc theo mot dieu kien cho truoc
tuple = ('Anh', 'Thu', 'Son', 'Dung', 'An', 'Quynh', '1', '2', '8')
#tao ham loc chuoi la cac chu cai
def filter_Alphabet(elem):
return elem.isalpha()
#tao ham loc chuoi la cac chu so
def filter_Digit(elem):
return elem.isdigit()
res1 = filter(filter_Digit, tuple)
res2 = filter(filter_Alphabet, tuple)
print(res1)
print(res2)
print(type(res1))
# enumerate() : Tra ve mot enumerate Object
#(la mot lis chua cac phan tu tuple moi,
# tuple moi bao gom gia tri cua phan tu
# tuple ban dau va gia tri chi muc cua no)
#Thuong sd khi muon sd ca gia tri va chi muc trong tuple
shoes = ('Addidas', 'Nike', 'Puma', 'Lining')
print(list(enumerate(shoes)))
# reversed(): Tra ve mot reverse Object trong do cac phan tu da duoc dao nguoc vi tri
fishes = ('Tuna', 'LargeMouth', 'Carp', 'RedFish')
print(type(fishes))
res = list(reversed(fishes)) #co the thay list = tuple
print(res)
# zip(): Nhom cac phan tu trong cac tuple o vi tri co chi muc tuong ung,
#moi nhom tro thanh mot tuple dong thoi la mot phan tu tuong ung cua mot list moi
equiqments = ('computer', 'video display', 'typerwritter')
rooms = ('living room', 'kitchen', 'guest room', 'bath room')
result = zip(equiqments, rooms)
print(result)
# sorted(): Tra ve mot list ma trong do cac phan tu duoc sap sep theo ky tu dau tien
actions = ('pack', 'stand', 'throw', 'tie', 'run', 'jump', 'hug', 'shave', 'eat', 'drink')
print(sorted(actions))
# sum():
#Tra ve tong cac phan tu co trong tuple
#Throw error neu mot phan tu trong tuple khong phai dang so
tup1 = (1, 2, 3, 5, 10)
tup2 = (1,2,3, 'a', 'chris')
print(sum(tup1))
print(sum(tup2))
|
'''
1. Pick an element, called a pivot, from the original list
2. Rearrange the list so that:
- All elements less than pivot come before the pivot
- All elements greater or equal to pivot com after pivot
3. Here, pivot is in the right position in the final sorted list(it is fixed)
4. Recursively sort the sub-list before pivot and thee sub-list after pivot
'''
import timeit
def partition(arr, l, r, indexPivot):
pivot = arr[indexPivot]
arr[indexPivot], arr[r] = arr[r], arr[indexPivot]
storeIndex = l
i = l
while i <= r - 1:
if arr[i] < pivot:
arr[storeIndex], arr[i] = arr[i], arr[storeIndex]
storeIndex += 1
i += 1
arr[storeIndex], arr[r] = arr[r], arr[storeIndex]
return storeIndex
def quickSort(arr, l, r):
if l < r:
index = (l + r) / 2
index = partition(arr, l, r, index)
if l < index:
quickSort(arr, l, index - 1)
if index < r:
quickSort(arr, index + 1, r)
arr = [1, 9, 10, 23, 3, 45, 6, 7, 13, 60, 8]
n = len(arr)
print('Original array is: ')
print(arr)
start = timeit.default_timer()
quickSort(arr, 0, n - 1)
stop = timeit.default_timer()
print('\nSorted array is: ')
print(arr)
print('Time to process is: ', stop-start)
|
#Heap Sort
import timeit
def Heapify(a, i, n):
#array to be heapified is a[i....n]
L = 2 * i #Left child
R = 2 * i + 1 #Right child
max = i
if L < n and a[L] > a[i]:
max = L
if R < n and a[R] > a[max]:
max = R
if max != i:
a[i], a[max] = a[max], a[i]
Heapify(a, max, n)
def heapSort(a, n):
n = len(a)
#Build a maxheap:
for i in range(n, -1, -1):
Heapify(a, i, n)
#One by one axtract elements
for i in range(n - 1, 0, -1):
a[i], a[0] = a[0], a[i]
Heapify(a, 0, i)
arr = [1, 9, 10, 23, 3, 45, 6, 7, 13, 60, 8]
n = len(arr)
print('Original array is: ')
print(arr)
start = timeit.default_timer()
heapSort(arr, n)
stop = timeit.default_timer()
print('\nSorted array is: ')
print(arr)
print('Time to process is: ', stop-start)
|
import random
# 电脑随机出拳
computer = random.randint(1, 3)
user = int(input('请出拳:1/拳头,2/剪刀,3/布'))
if computer == 1:
computer = '拳头'
elif computer == 2:
computer = '剪刀'
else:
computer = '布'
if user == 1:
user = '拳头'
elif user == 2:
user = '剪刀'
else:
user = '布'
print('电脑出的是{},沙雕余鹏出的是{}'.format(computer, user))
if (user < computer ):
print('沙雕余鹏胜出~_~');
elif (user > computer):
print('电脑胜出!');
elif(user == computer ):
print('好吧,平局@_@');
|
def get_left(i):
return 2*i
def get_right(i):
return 2*i+1
def max_heapify(a, i, n):
largest = i
left = get_left(i)
right = get_right(i)
if left<=n and a[left]>a[largest]:
largest = left
if right<=n and a[right]>a[largest]:
largest = right
if largest!=i:
a[largest], a[i]= a[i], a[largest]
max_heapify(a,largest,n)
def build_heap(a, n):
for i in range(n//2,0,-1):
max_heapify(a, i, n)
print(a)
def heap_sort(a,n):
for i in range(n,1,-1):
a[i], a[1] = a[1], a[i]
n-=1
max_heapify(a,1,n)
arr = list(map(int, input().strip().split()))
n = len(arr)
arr.insert(0,0)
print(arr)
print('build_heap------')
build_heap(arr,n)
print(arr)
print('heap_sort------')
heap_sort(arr, n)
print(arr)
print(n) |
print("APP")
a = input("enter a Number : ")
print(float(a)*5)
|
import sys
# Edge class
class Edge:
def __init__(self, destination, weight=1):
self.destination = destination
self.weight = weight
#Vertex class
class Vertex:
def __init__(self,value='vertex', color="white", parent=None):
self.value = value
self.edges = []
self.color = color
self.parent = parent
#Graph class
class Graph:
def __init__(self):
self.vertices = []
'''
* function looks through all the vertices in the graph and returns the
* first one it finds that matches the value parameter.
*
* Used from the main code to look up the verts passed in on the command
* line.
*
* @param: {*} value: The value of the Vertex to find
*
* @return None if not found.
* return {Vertex} the found vertex
*
'''
def find_vertex(self, value):
#!!! IMPLEMENT ME
vert = [v for v in self.vertices if v.value == value]
return vert[0]
'''
* Breadth-First search from a starting vertex. self should keep parent
* pointers back from neighbors to their parent.
*
* @param:Vertex start The starting vertex for the BFS
'''
def bfs(self, start):
"""Search the graph using BFS or DFS."""
start.color = 'gray'
queue = [start]
#init func already doing this
"""
for vertex in self.vertices:
vertex.color = 'white'
vertex.parent = None
"""
# refactor
"""
start.color = 'gray'
queue.append(start)
"""
while queue:
current = queue.pop(0)
for edge in current.edges:
vertex = edge.destination
if vertex.color == 'white':
vertex.color = 'gray'
vertex.parent = current
queue.append(vertex)
current.color = 'black'
'''
* Print out the route from the start vert back along the parent
* pointers(self,set in the previous BFS)
*
* @param:Vertex start The starting vertex to follow parent
* pointers from
'''
def output_route(self, start):
#!!! IMPLEMENT ME
vertex = start
output = ''
while (vertex):
output += vertex.value
if (vertex.parent):
output += ' --> '
vertex = vertex.parent
print(output)
# Show the route from a starting vert to an ending vert.
def route(self, start, end):
#Do BFS and build parent pointer tree
self.bfs(end)
#Show the route from the start
self.output_route(start)
# Helper function to add bidirectional edges
def add_edge(v0, v1):
v0.edges.append(Edge(v1))
v1.edges.append(Edge(v0))
#Main
"""
```
pseudocode
BFS(graph, startVert):
for v of graph.vertices:
v.color = white
v.parent = null // <-- Add parent initialization
startVert.color = gray
queue.enqueue(startVert)
while !queue.isEmpty():
u = queue[0]
for v of u.neighbors:
if v.color == white:
v.color = gray
v.parent = u // <-- Keep a parent link
queue.enqueue(v)
queue.dequeue()
u.color = black
```
## Procedure
1. Perform a BFS from the _ending vert_(host). self will set up all the
`parent` pointers across the graph.
2. Output the route by following the parent pointers from the _starting_ vert
printing the values as you go.
## Sample Run
```
$ node routing.js HostA HostD
HostA - -> HostB - -> HostD
$ node routing.js HostA HostH
HostA - -> HostC - -> HostF - -> HostH
$ node routing.js HostA HostA
HostA
$ node routing.js HostE HostB
HostE - -> HostF - -> HostC - -> HostA - -> HostB
```
"""
|
#221
def print_reverse(string):
print(string[::-1])
print_reverse("python")
#222
def print_score(list_):
sum = 0
for i in list_:
sum += i
print(sum / len(list_))
print_score([1, 2, 3])
#223
def print_even(list_):
for i in list_:
if i % 2 == 0:
print(i)
print_even([1, 3, 2, 10, 12, 11, 15])
#224
def print_keys(dict_):
for i in dict_:
print(i)
print_keys({"이름":"김말똥", "나이":30, "성별":0})
#225
my_dict = {"10/26" : [100, 130, 100, 100],
"10/27" : [10, 12, 10, 11]}
def print_value_by_key(dict_, key_):
print(dict_[key_])
print_value_by_key(my_dict, "10/26")
#226
def print_5xn(string):
for i in range(len(string)):
if i % 5 == 0:
print("\n", end="")
print(string[i], end="")
print_5xn("아이엠어보이유알어걸")
#227
def print_mxn(string, index):
for i in range(len(string)):
if i % index == 0:
print("\n", end = "")
print(string[i], end = "")
print_mxn("아이엠어보이유알어걸", 3)
print()
#228
def calc_monthly_salary(annual_salary):
print(int(annual_salary / 12))
calc_monthly_salary(12000000)
#229
def my_print(a, b):
print("왼쪽:", a)
print("오른쪽:", b)
my_print(a = 100, b = 200)
#230
def my_print(a, b):
print("왼쪽:", a)
print("오른쪽:", b)
my_print(b = 100, a = 200) |
#101
#true 또는 flase의 데이터 타입은 bool이다.
#102
print(3 == 5)
#103
print(3 < 5)
#104
x = 4
print(1 < x < 5)
#105
print((3 == 3) and (4 != 3))
#106
print(3 >= 4)
# 부등호 모양이 틀릴 경우 오류 발생
#107
if 4 < 3:
print("Hello World")
#108
if 4 < 3:
print("Hello World.")
else:
print("Hi, there.")
#109
if True:
print("1")
print("2")
else:
print("3")
print("4")
#110
if True:
if False:
print("1")
print("2")
else:
print("3")
else:
print("4")
print("5") |
# coding: utf-8
# In[2]:
from matplotlib import pyplot as plt
import numpy as np
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
See full source and example:
http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
def most_informative_feature_for_binary_classification(vectorizer, classifier, n=100):
"""
See: https://stackoverflow.com/a/26980472
Identify most important features if given a vectorizer and binary classifier. Set n to the number
of weighted features you would like to show. (Note: current implementation merely prints and does not
return top classes.)
"""
class_labels = classifier.classes_
feature_names = vectorizer.get_feature_names()
topn_class1 = sorted(zip(classifier.coef_[0], feature_names))[:n]
topn_class2 = sorted(zip(classifier.coef_[0], feature_names))[-n:]
for coef, feat in topn_class1:
print(class_labels[0], coef, feat)
print()
for coef, feat in reversed(topn_class2):
print(class_labels[1], coef, feat)
def plot_history_2win(history):
plt.subplot(211)
plt.title('Accuracy')
plt.plot(history.history['acc'], color='g', label='Train')
plt.plot(history.history['val_acc'], color='b', label='Validation')
plt.legend(loc='best')
plt.subplot(212)
plt.title('Loss')
plt.plot(history.history['loss'], color='g', label='Train')
plt.plot(history.history['val_loss'], color='b', label='Validation')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
def create_history_plot(history, model_name, metrics=None):
plt.title('Accuracy and Loss (' + model_name + ')')
if metrics is None:
metrics = {'acc', 'loss'}
if 'acc' in metrics:
plt.plot(history.history['acc'], color='g', label='Train Accuracy')
plt.plot(history.history['val_acc'], color='b', label='Validation Accuracy')
if 'loss' in metrics:
plt.plot(history.history['loss'], color='r', label='Train Loss')
plt.plot(history.history['val_loss'], color='m', label='Validation Loss')
plt.legend(loc='best')
plt.tight_layout()
def plot_history(history, model_name):
create_history_plot(history, model_name)
plt.show()
def plot_and_save_history(history, model_name, file_path, metrics=None):
if metrics is None:
metrics = {'acc', 'loss'}
create_history_plot(history, model_name, metrics)
plt.savefig(file_path)
# In[3]:
from collections import Counter
MAX_INPUT_SEQ_LENGTH = 500
MAX_TARGET_SEQ_LENGTH = 50
MAX_INPUT_VOCAB_SIZE = 5000
MAX_TARGET_VOCAB_SIZE = 2000
def fit_text(X, Y, input_seq_max_length=None, target_seq_max_length=None):
if input_seq_max_length is None:
input_seq_max_length = MAX_INPUT_SEQ_LENGTH
if target_seq_max_length is None:
target_seq_max_length = MAX_TARGET_SEQ_LENGTH
input_counter = Counter()
target_counter = Counter()
max_input_seq_length = 0
max_target_seq_length = 0
for line in X:
text = [word.lower() for word in line.split(' ')]
seq_length = len(text)
if seq_length > input_seq_max_length:
text = text[0:input_seq_max_length]
seq_length = len(text)
for word in text:
input_counter[word] += 1
max_input_seq_length = max(max_input_seq_length, seq_length)
for line in Y:
line2 = 'START ' + line.lower() + ' END'
text = [word for word in line2.split(' ')]
seq_length = len(text)
if seq_length > target_seq_max_length:
text = text[0:target_seq_max_length]
seq_length = len(text)
for word in text:
target_counter[word] += 1
max_target_seq_length = max(max_target_seq_length, seq_length)
input_word2idx = dict()
for idx, word in enumerate(input_counter.most_common(MAX_INPUT_VOCAB_SIZE)):
input_word2idx[word[0]] = idx + 2
input_word2idx['PAD'] = 0
input_word2idx['UNK'] = 1
input_idx2word = dict([(idx, word) for word, idx in input_word2idx.items()])
target_word2idx = dict()
for idx, word in enumerate(target_counter.most_common(MAX_TARGET_VOCAB_SIZE)):
target_word2idx[word[0]] = idx + 1
target_word2idx['UNK'] = 0
target_idx2word = dict([(idx, word) for word, idx in target_word2idx.items()])
num_input_tokens = len(input_word2idx)
num_target_tokens = len(target_word2idx)
config = dict()
config['input_word2idx'] = input_word2idx
config['input_idx2word'] = input_idx2word
config['target_word2idx'] = target_word2idx
config['target_idx2word'] = target_idx2word
config['num_input_tokens'] = num_input_tokens
config['num_target_tokens'] = num_target_tokens
config['max_input_seq_length'] = max_input_seq_length
config['max_target_seq_length'] = max_target_seq_length
return config
# In[4]:
from __future__ import print_function
from keras.models import Model
from keras.layers import Embedding, Dense, Input
from keras.layers.recurrent import LSTM
from keras.preprocessing.sequence import pad_sequences
from keras.callbacks import ModelCheckpoint
#from keras_text_summarization.library.utility.glove_loader import load_glove, GLOVE_EMBEDDING_SIZE
import numpy as np
import os
HIDDEN_UNITS = 100
DEFAULT_BATCH_SIZE = 64
VERBOSE = 1
DEFAULT_EPOCHS = 10
class Seq2SeqSummarizer(object):
model_name = 'seq2seq'
def __init__(self, config):
self.num_input_tokens = config['num_input_tokens']
self.max_input_seq_length = config['max_input_seq_length']
self.num_target_tokens = config['num_target_tokens']
self.max_target_seq_length = config['max_target_seq_length']
self.input_word2idx = config['input_word2idx']
self.input_idx2word = config['input_idx2word']
self.target_word2idx = config['target_word2idx']
self.target_idx2word = config['target_idx2word']
self.config = config
self.version = 0
if 'version' in config:
self.version = config['version']
encoder_inputs = Input(shape=(None,), name='encoder_inputs')
encoder_embedding = Embedding(input_dim=self.num_input_tokens, output_dim=HIDDEN_UNITS,
input_length=self.max_input_seq_length, name='encoder_embedding')
encoder_lstm = LSTM(units=HIDDEN_UNITS, return_state=True, name='encoder_lstm')
encoder_outputs, encoder_state_h, encoder_state_c = encoder_lstm(encoder_embedding(encoder_inputs))
encoder_states = [encoder_state_h, encoder_state_c]
decoder_inputs = Input(shape=(None, self.num_target_tokens), name='decoder_inputs')
decoder_lstm = LSTM(units=HIDDEN_UNITS, return_state=True, return_sequences=True, name='decoder_lstm')
decoder_outputs, decoder_state_h, decoder_state_c = decoder_lstm(decoder_inputs,
initial_state=encoder_states)
decoder_dense = Dense(units=self.num_target_tokens, activation='softmax', name='decoder_dense')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
self.model = model
self.encoder_model = Model(encoder_inputs, encoder_states)
decoder_state_inputs = [Input(shape=(HIDDEN_UNITS,)), Input(shape=(HIDDEN_UNITS,))]
decoder_outputs, state_h, state_c = decoder_lstm(decoder_inputs, initial_state=decoder_state_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
self.decoder_model = Model([decoder_inputs] + decoder_state_inputs, [decoder_outputs] + decoder_states)
def load_weights(self, weight_file_path):
if os.path.exists(weight_file_path):
self.model.load_weights(weight_file_path)
def transform_input_text(self, texts):
temp = []
for line in texts:
x = []
for word in line.lower().split(' '):
wid = 1
if word in self.input_word2idx:
wid = self.input_word2idx[word]
x.append(wid)
if len(x) >= self.max_input_seq_length:
break
temp.append(x)
temp = pad_sequences(temp, maxlen=self.max_input_seq_length)
print(temp.shape)
return temp
def transform_target_encoding(self, texts):
temp = []
for line in texts:
x = []
line2 = 'START ' + line.lower() + ' END'
for word in line2.split(' '):
x.append(word)
if len(x) >= self.max_target_seq_length:
break
temp.append(x)
temp = np.array(temp)
print(temp.shape)
return temp
def generate_batch(self, x_samples, y_samples, batch_size):
num_batches = len(x_samples) // batch_size
while True:
for batchIdx in range(0, num_batches):
start = batchIdx * batch_size
end = (batchIdx + 1) * batch_size
encoder_input_data_batch = pad_sequences(x_samples[start:end], self.max_input_seq_length)
decoder_target_data_batch = np.zeros(shape=(batch_size, self.max_target_seq_length, self.num_target_tokens))
decoder_input_data_batch = np.zeros(shape=(batch_size, self.max_target_seq_length, self.num_target_tokens))
for lineIdx, target_words in enumerate(y_samples[start:end]):
for idx, w in enumerate(target_words):
w2idx = 0 # default [UNK]
if w in self.target_word2idx:
w2idx = self.target_word2idx[w]
if w2idx != 0:
decoder_input_data_batch[lineIdx, idx, w2idx] = 1
if idx > 0:
decoder_target_data_batch[lineIdx, idx - 1, w2idx] = 1
yield [encoder_input_data_batch, decoder_input_data_batch], decoder_target_data_batch
@staticmethod
def get_weight_file_path(model_dir_path):
return model_dir_path + '/' + Seq2SeqSummarizer.model_name + '-weights.h5'
@staticmethod
def get_config_file_path(model_dir_path):
return model_dir_path + '/' + Seq2SeqSummarizer.model_name + '-config.npy'
@staticmethod
def get_architecture_file_path(model_dir_path):
return model_dir_path + '/' + Seq2SeqSummarizer.model_name + '-architecture.json'
def fit(self, Xtrain, Ytrain, Xtest, Ytest, epochs=None, batch_size=None, model_dir_path=None):
if epochs is None:
epochs = DEFAULT_EPOCHS
if model_dir_path is None:
model_dir_path = './'
if batch_size is None:
batch_size = DEFAULT_BATCH_SIZE
self.version += 1
self.config['version'] = self.version
config_file_path = Seq2SeqSummarizer.get_config_file_path(model_dir_path)
weight_file_path = Seq2SeqSummarizer.get_weight_file_path(model_dir_path)
checkpoint = ModelCheckpoint(weight_file_path)
np.save(config_file_path, self.config)
architecture_file_path = Seq2SeqSummarizer.get_architecture_file_path(model_dir_path)
open(architecture_file_path, 'w').write(self.model.to_json())
Ytrain = self.transform_target_encoding(Ytrain)
Ytest = self.transform_target_encoding(Ytest)
Xtrain = self.transform_input_text(Xtrain)
Xtest = self.transform_input_text(Xtest)
train_gen = self.generate_batch(Xtrain, Ytrain, batch_size)
test_gen = self.generate_batch(Xtest, Ytest, batch_size)
train_num_batches = len(Xtrain) // batch_size
test_num_batches = len(Xtest) // batch_size
history = self.model.fit_generator(generator=train_gen, steps_per_epoch=train_num_batches,
epochs=epochs,
verbose=VERBOSE, validation_data=test_gen, validation_steps=test_num_batches,
callbacks=[checkpoint])
self.model.save_weights(weight_file_path)
return history
def summarize(self, input_text):
input_seq = []
input_wids = []
for word in input_text.lower().split(' '):
idx = 1 # default [UNK]
if word in self.input_word2idx:
idx = self.input_word2idx[word]
input_wids.append(idx)
input_seq.append(input_wids)
input_seq = pad_sequences(input_seq, self.max_input_seq_length)
states_value = self.encoder_model.predict(input_seq)
target_seq = np.zeros((1, 1, self.num_target_tokens))
target_seq[0, 0, self.target_word2idx['START']] = 1
target_text = ''
target_text_len = 0
terminated = False
while not terminated:
output_tokens, h, c = self.decoder_model.predict([target_seq] + states_value)
sample_token_idx = np.argmax(output_tokens[0, -1, :])
sample_word = self.target_idx2word[sample_token_idx]
target_text_len += 1
if sample_word != 'START' and sample_word != 'END':
target_text += ' ' + sample_word
if sample_word == 'END' or target_text_len >= self.max_target_seq_length:
terminated = True
target_seq = np.zeros((1, 1, self.num_target_tokens))
target_seq[0, 0, sample_token_idx] = 1
states_value = [h, c]
return target_text.strip()
# In[ ]:
from __future__ import print_function
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
LOAD_EXISTING_WEIGHTS = False
np.random.seed(42)
data_dir_path = './'
model_dir_path = './'
print('loading csv file ...')
df = pd.read_csv(data_dir_path + "/fake_or_real_news.csv")
print('extract configuration from input texts ...')
Y = df.title
X = df['text']
config = fit_text(X, Y)
summarizer = Seq2SeqSummarizer(config)
if LOAD_EXISTING_WEIGHTS:
summarizer.load_weights(weight_file_path=Seq2SeqSummarizer.get_weight_file_path(model_dir_path=model_dir_path))
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, Y, test_size=0.2, random_state=42)
history = summarizer.fit(Xtrain, Ytrain, Xtest, Ytest, epochs=80)
# In[8]:
report_dir_path = './'
LOAD_EXISTING_WEIGHTS = True
history_plot_file_path = report_dir_path + '/' + Seq2SeqSummarizer.model_name + '-history.png'
if LOAD_EXISTING_WEIGHTS:
history_plot_file_path = report_dir_path + '/' + Seq2SeqSummarizer.model_name + '-history-v' + str(summarizer.version) + '.png'
plot_and_save_history(history, summarizer.model_name, history_plot_file_path, metrics={'loss', 'acc'})
# In[12]:
import pandas as pd
import numpy as np
np.random.seed(42)
data_dir_path = './' # refers to the demo/data folder
model_dir_path = './' # refers to the demo/models folder
print('loading csv file ...')
df = pd.read_csv("./fake_or_real_news.csv")
X = df['text']
Y = df.title
config = np.load(Seq2SeqSummarizer.get_config_file_path(model_dir_path=model_dir_path)).item()
summarizer = Seq2SeqSummarizer(config)
summarizer.load_weights(weight_file_path=Seq2SeqSummarizer.get_weight_file_path(model_dir_path=model_dir_path))
print('start predicting ...')
for i in range(5):
x = X[i]
actual_headline = Y[i]
headline = summarizer.summarize(x)
print('Article: ', x)
print('Generated : ', headline)
print('Original Summary: ', actual_headline)
# In[ ]:
|
16.1
class Time(object):
"""Represents the time of day.
attributes: hour, minute, second
"""
def print_time(t):
print '%.2d' : '%.2d' : '%.2d' (t.hour, t.minute, t.second)
def is_after(t1, t2)
if t1.hour
17.6
class Point(x,y):
def __init__(self, x=0, y=0,):
self.x = x
self.y = y
|
#!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
import re
import sys
from dictionaries import *
############################################################
# Parser Class
# Encapsulates access to the input code. Reads an assembly language command,
# parses it, and provides convenient access to the command’s components
# (fields and symbols). In addition, removes all white space and comments.
############################################################
class parser():
def constructor():
"""opens the file and returns a list containing each command as a seperate element
in string format."""
assembly_file = sys.stdin.readlines()
assembly_file = parser.clean_up_file(assembly_file)
return(assembly_file)
def clean_up_file(file):
"""calls the function that removes all characters which are not part of a command
and afterwards removes empty list elements"""
commands = []
for lines in file:
commands.append(parser.remove_comments(lines))
commands = list(filter(None, commands))
return(commands)
def remove_comments(string):
"""removes sections of the string with // and removes \n and whitespaces from the string"""
string = re.sub(re.compile("//.*?\n" ) ,"" ,string)
string = re.sub(re.compile("\n" ) ,"" ,string)
string = string.strip()
return(string)
def command_type(command):
"""Returns the type of the current command"""
if command[0] == '@':
return("a_command")
elif "=" in command or ";" in command:
return("c_command")
else:
return("l_command")
def a_instruction(a_command, dict, RAM):
""" Returns the binary code corresponding to an a_command"""
address = dict.get(a_command,'not found')
if address == 'not found':
if parser.has_numbers(a_command[0]) == True:
return(parser.symbol(int(a_command[0:])),RAM)
else:
bin = parser.symbol(RAM)
RAM +=1
return (bin,RAM)
else:
address = parser.symbol(address)
return (address,RAM)
def has_numbers(input_string):
return bool(re.search(r'\d', input_string))
def c_instruction(c_command):
""" Returns the binary code corresponding to an a_command"""
list = ['111']
if '=' in c_command:
c_command = c_command.split('=')
list.append(code.translation_into_binary(c_command[1],comp_dict))
list.append(code.translation_into_binary(c_command[0],dest_dict))
list.append('000')
else:
c_command = c_command.split(';')
list.append(code.translation_into_binary(c_command[0],comp_dict))
list.append('000')
list.append(code.translation_into_binary(c_command[1],jump_dict))
list = ''.join(list)
return(list)
def symbol(decimal_number):
return("0{:015b}".format(decimal_number))
############################################################
# Code Class
# Translates Hack assembly language mnemonics into binary codes.
############################################################
class code():
def translation_into_binary(mnemonic, dict):
"""Returns the binary code of the mnemonic. Dictionaries used are imported from the
file dictionaries.py"""
return(dict.get(mnemonic, '000'))
############################################################
# Assembler
############################################################
def ROM_values(first_pass_list,dict):
"""each time a pseudocommand (xxx) is encountered, a new entry is added to the symbol table (which is a
dictionary) associating xxx with the ROM address."""
ROM = 0
for element in first_pass_list:
type_of_command = parser.command_type(element)
if type_of_command == "c_command" or type_of_command == "a_command":
ROM = ROM + 1
else:
element = element.strip("()")
dict[element] = ROM
return(dict)
def first_pass():
first_pass_list = parser.constructor()
return(ROM_values(first_pass_list, predef_dict),first_pass_list)
def second_pass(list_of_commands,dict):
binary_list = []
RAM = 16
for element in list_of_commands:
type_of_command = parser.command_type(element)
if type_of_command == "a_command":
(bin,RAM) = (parser.a_instruction(element[1:],dict,RAM))
binary_list.append(bin)
elif type_of_command == "c_command":
binary_list.append(parser.c_instruction(element))
return binary_list
def write_file(lines):
for line in lines:
print(line)
############################################################
# Commands to run the file
############################################################
ROM_list, command_list = first_pass()
write_file(second_pass(command_list, ROM_list))
|
from time import clock
tiempo_inicial = clock()
def heap(arr, n, i):
mgrande = i # Inicializamos
l = 2 * i + 1 # Izquierda = 2*i + 1
r = 2 * i + 2 # Derecha = 2*i + 2
# si es el mas grande
if l < n and arr[i] < arr[l]:
mgrande = l
# Si hijo derecho es más grande que la más grande hasta el momento
if r < n and arr[mgrande] < arr[r]:
mgrande = r
# Si es mas grande y no es la raiz
if mgrande != i:
arr[i],arr[mgrande] = arr[mgrande],arr[i] # swap
# Heap la raiz
heap(arr, n, mgrande)
# Función principal de ordenar una matriz de tamaño dado
def heapSort(arr):
n = len(arr)
for i in range(n, -1, -1):
heap(arr, n, i)
# Mueve la raiz actual y pone fin
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heap(arr, i, 0)
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print (arr),
tiempo_final = clock()
print (tiempo_final - tiempo_inicial) |
print("Olá, seja bem vindo!") # Exibe mensagem de boas vindas
nome = input("Digite seu nome: ") # Recebe dado do usuario
print( 'Olá ', nome, ", seja bem vindo!", sep="" ) # Exibe o nome do usuário
# Descobrindo o tipo da variável nome
type( nome ) # str é string
# Caixa alta de string
nome_maisculo = nome.upper()
print(nome_maisculo)
# Caixa baixa de string
nome_minusculo = nome.lower()
print(nome_minusculo)
# replace substring
nome.replace( "Teo", "Lara" ) #substitui todas ocorrencias
###### POSICOES DA STRING
qtde_caracteres = len(nome) # quantidade de caracteres
# Ultima letra do meu nome
nome = "Teodoro Calvo"
nome[-1]
# Fatiamento - Slice
nome[0] # Primeira posicao
nome[0:3] # nome[start:stop]
nome[:3] # mesma coisa que o de cima
nome[:: ] # nome[start:stop:step] sintaxe completa de fatiamento
nome[::2]
nome.find( ' ' )
nome[7]
nome[:3] + nome[ 7+1 : 7+1+3 ]
nome[:3] + nome[ nome.find(" ")+1 : nome.find(" ")+1+3 ]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 5 00:14:40 2018
@author: shawon
uva : 10340 - All in All
#=====================================================
"""
def main():
while True:
try:
substring,string = map(str,input().split())
n,m=len(substring),len(string)
# n = substring len
# m = string len
if m<n:
print("No")
else:
i=0
for j in range(0,m):
if i == n:
break
if substring[i]==string[j]:
i+=1
if i==n:
print("Yes")
else:
print("No")
except EOFError:
break
if __name__=="__main__":
main() |
s="django";
print(s[0]);
print(s[5]);
print(s[:4]);
print(s[1:4]);
print(s[4:]);
print(s[::-1]);
l=[3,7,[1,4,"hello"]];
l[2][2]="goodbye";
print(l);
d1={"simple_key":"hello"};
d2={"k1":{"k2":"hello"}};
d3={"k1":[{"nest_key":["this is deep",["hello"]]}]};
print(d1["simple_key"]);
print(d2["k1"]["k2"]);
print(d3["k1"][0]["nest_key"][1][0]);
my_list=[1,1,1,1,1,2,2,2,2,3,3,3,3];
converted=set(my_list)
print(converted);
age=4;
name="sammy";
a="Hello my dog's name is {name} and he is {age} years old".format(age=age,name=name)
print(a);
|
#problem 1
arraycheck1=[1,1,2,3,1]
arraycheck2=[1,1,2,4,1]
arraycheck3=[1,1,2,1,2,3]
def arrayCheck(nums):
for i in range(len(nums)-2):
if nums[i]==1 and nums[i+2]==2 and nums[i+2]==3:
return True
return False
#Problem 2
def stringBits(str):
result=""
for i in range(len(mystring)):
if i%2==0:
result=result+mystring[i]
return result
#problem 3
a=a.lower()
b=b.lower()
#return(b.endswith(a)or a.endswith(b))
return a[-(len(b)):]==b or a==b[-len(a):]
#problem 4
result=" "
for char in mystring:
result += char*2
return result
#problem 5
def no_teen_sum(a,b,c):
return fix_teen(a)+fix_teen(b)+fix_teen(c)
def fix_teen(n):
if n[13,14,17,18,19]:
return 0
return n
#problem 6
count =0
for element in nums:
if element%2==0:
count +=1
return count
|
# card game
from random import shuffle
#two useful variables for creating cards.
SUITE="H D S C".split()
RANKS="2 3 4 5 6 7 8 9 10 J Q K A".split()
# mycards=[(s,r) for s SUITE for r in RANKS] same as below
#
# mycards=[]
# for r in RANKS:
# for s in SUITE:
# mycards.append((s,r))
class Deck:
"""
This is a deck class. This object will create a deck of cards to initaite
play. You can then use this Deck list of cards to split in half and give
to the players. It will use SUITE and RANKS to create the deck. It should
also have a method for splitting/cutting the deck in half and shuffling
the deck.
"""
def __init__(self):
print("creating new order deck!")
self.allcards=[(s,r) for s in SUITE for r in RANKS]
def shuffle(self):
print("shuffling deck")
shuffle(self.allcards)
def split_in_half(self):
return(self.allcards[:26],self.allcards[26:])
class Hand(object):
"""
This is hand class. Each player has a hand andd can add or remove
cards from that hand. There should be an add and remove card method here.
"""
def __init__(self,cards):
self.cards=cards
def __str__(self):
return "contains {} cards".format(len(self.cards))
def add(self):
self.cards.extend(added_cards)
def remove_cards(self):
return self.cards.pop()
class Player:
"""
This is player class, which takes in a name and an instance of a hand
class object.The player can then play cards and check if they still hace cards.
"""
def __init__(self,name,hand):
self.name=name
self.hand=hand
def play_card(self):
drawn_card=self.hand.remove_cards()
print("{} has placed: ".format(self.name,drawn_card))
print("\n")
return drawn_card
def remove_war_card(self):
war_cards=[]
if len(self.hand.cards)<3:
return self.hand.cards
else:
for x in range(3):
war_cards.append(self.hand.cards.pop())
return war_cards
def still_has_cards(self):
"""
Return true if player still has cards left
"""
return len(self.hand.cards)!=0
##########################################################
print("Welcome to war, lets begin...")
#create new deck and split it in half:
d=Deck()
d.shuffle()
half1,half2=d.split_in_half()
#create both players!
comp=Player("computer",Hand(half1))
name=input("what is your name?")
user=Player(name,Hand(half2))
total_rounds=0
war_count=0
while user.still_has_cards() and comp.still_has_cards():
total_rounds +=1
print("time for new round!")
print("here are he current standings")
print(user.name+"has the count: "+str(len(user.hand.cards)))
print(comp.name+"has the count: "+str(len(comp.hand.cards)))
print("play a card!")
print("\n")
table_cards=[]
c_card=comp.play_card()
p_card=user.play_card()
table_cards.append(c_card)
table_cards.append(p_card)
if c_card[1]==p_card[1]:
war_count +=1
print("war!")
table_cards.extend(user.remove_war_card())
table_cards.extend(comp.remove_war_card())
if RANKS.index(c_card[1])<RANKS.index(p_card[1]):
user.hand.add(table_cards)
else:
comp.hand.add(table_cards)
else:
if RANKS.index(c_card[1])<RANKS.index(p_card[1]):
user.hand.add(table_cards)
else:
comp.hand.add(table_cards)
print("game over, number of rounds:"+str(total_rounds))
print("a war happened"+str(war_count)+"times")
print("Does the computer still has cards? ")
print(str(comp.still_has_cards()))
print("Does the human still has cards? ")
print(str(user.still_has_cards()))
|
import cv2 as cv
import numpy as np
def roi(cfg, height, width):
"""
Creates the rectangular region of interest
Args:
cfg: {obj} -- representing specified config-parameters in config.py / myconfig.py
height: {int} -- height of rectangle
width: {int} -- width of rectangle
Returns:
np.array -- coordinates of each point of the rectangle
"""
return np.array([[(0, height), (width, height),
(width, cfg.CV_ROI_Y_UPPER_EDGE), (0, cfg.CV_ROI_Y_UPPER_EDGE)]])
def make_coordinates(image, line_parameters, cfg):
"""
Converts the given slope and intercept of a line into pixel points
Args:
image: {np.array} -- original image
line_parameters: {np.array} -- array containing (slope,intercept) of line
cfg: {obj} -- representing specified config-parameters in config.py / myconfig.py
Returns:
np.array -- pixel points on the line specified by the given slope and intercept
"""
slope, intercept = line_parameters
y1 = image.shape[0]
y2 = int(y1 * cfg.CV_MAKE_COORDINATES_UPPER_LIMIT)
x1 = int((y1 - intercept)/slope)
x2 = int((y2 - intercept)/slope)
return np.array([x1, y1, x2, y2])
def average_slope_intercept(image, lines, cfg):
"""
Takes in coordinates of lines, gets the slope and intercept, decide if it is a right or left lane line
depending on slope, and return an averaged coordinates for left and right lane line
Args:
image: {np.array} -- original image
lines: {np.array} -- contains points on a line
cfg: {obj} -- representing specified config-parameters in config.py / myconfig.py
Returns:
np.array -- contains the averaged coordinates for a left and right lane line
"""
left_fit = []
right_fit = []
for line in lines:
x1, y1, x2, y2 = line.reshape(4)
parameters = np.polyfit((x1, x2), (y1, y2), 1)
slope = parameters[0]
intercept = parameters[1]
if slope < 0:
left_fit.append((slope, intercept))
else:
right_fit.append((slope, intercept))
left_fit_average = np.average(left_fit, axis=0)
right_fit_average = np.average(right_fit, axis=0)
left_line = make_coordinates(image, left_fit_average, cfg)
right_line = make_coordinates(image, right_fit_average, cfg)
return np.array([left_line, right_line])
def bgr_to_hls(image):
'''Convert BRG image to HLS color space
Arguments:
image {np array} -- original image in BGR color space
Returns:
np array -- converted image in HLS color space
'''
return cv.cvtColor(image, cv.COLOR_BGR2HLS)
def bgr_to_hsv(image):
'''Convert bgr image to hsv color space
Arguments:
image {np array} -- original BGR image
Returns:
np array -- image in BGR color space
'''
return cv.cvtColor(image, cv.COLOR_BGR2HSV)
def rgb_to_hls(image):
"""
Convert RGB image to HLS color space
Arguments:
image {np array} -- original RGB image
Returns:
nd array -- converted image in HLS color space
"""
return cv.cvtColor(image, cv.COLOR_RGB2HLS)
def rgb_to_hsv(image):
"""
Convert image to hsv color space
Arguments:
image {np array} -- original RGB image
Returns:
nd array -- converted image in HSV color space
"""
return cv.cvtColor(image, cv.COLOR_RGB2HSV)
def create_color_mask(img, col_lower, col_upper):
"""
Threshold the image to specific color ranges
Args:
img: {np.array} -- HLS color space image to be used
col_lower: {int} -- number value of low color threshold
col_upper: {int} -- number value of upper color threshold
Returns:
mask: image with pixel values in the range specified by col_lower and col_upper
"""
mask = cv.inRange(img, col_lower, col_upper)
return mask
def create_line_image(image, lines, cfg):
"""
Draws lines identified in the image onto a black background
Args:
image: {np.array} -- image that the lines come from
lines: {np.array} -- coordinates of the lines (edges) in image
cfg: {obj} -- representing specified config-parameters in config.py / myconfig.py
Returns:
line_image: {np.array} -- black background image with lines representing the edges of the original image drawn on it
"""
line_image = np.zeros_like(image)
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line.reshape(4)
cv.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), cfg.CV_HOUGH_LINE_THICKNESS)
return line_image
def visualize_edges(img, edges):
"""
Show the edges in the image
Args:
img: {np.array} -- original image
edges: {?} -- edges in the image
Returns:
edges overlayed with the image
"""
# cv.imshow('edges', edges)
combo_image = cv.addWeighted(img, 0.8, cv.cvtColor(edges, cv.COLOR_GRAY2BGR), 1, 1)
cv.imshow('edges-combo', combo_image)
def visualize_segmentation(img, mask, mask_2=None):
"""
Shows the HSV yellow and orange lanes
Args:
image: {np.array} -- image to be shown
mask: {?} --
mask_2: {?}
Returns:
2 images showing the segmented regions and the segmented region overlayed with the image
"""
if mask_2 is not None:
cv.imshow('segmented_lane_white', cv.bitwise_and(img, img, mask=mask))
cv.imshow('segmented_lane_orange', cv.bitwise_and(img, img, mask=mask_2))
else:
# cv.imshow('segmented_region', mask)
cv.imshow('segmented_lane_combo', cv.bitwise_and(img, img, mask=mask))
def apply_canny(image, cfg):
"""
Perform canny on image to detect edge with high contrast
You can tone the cv2.Canny(blur, 50,150) parameter. 50 is low
threshold and 150 is high threshold
:param image: {np array} -- original image
:param cfg: obj -- {obj} representing specified config-parameters in config.py / myconfig.py
:return: canny: {np array} -- image after canny function
"""
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
blur = cv.GaussianBlur(gray, cfg.CV_GAUSSIAN_KERNEL, cfg.CV_GAUSSIAN_SIGMA)
canny = cv.Canny(blur, cfg.CV_CANNY_MIN, cfg.CV_CANNY_MAX)
return canny
def region_of_interest(image, cfg):
"""
Only displays the region of interest in the image. Everything not in the region is blacked out.
Args:
image: {np.array} -- image you want to get region of interest on
cfg: {obj} representing specified config-parameters in config.py / myconfig.py
Returns:
masked_image: {np.array} -- image containing only everything from the original image inside the region of interest
"""
height = image.shape[0]
width = image.shape[1]
polygons = roi(cfg, height, width)
if len(image.shape) == 2:
mask = np.zeros_like(image)
cv.fillPoly(mask, polygons, 255)
masked_image = cv.bitwise_and(image, mask)
else:
mask = np.zeros_like(image[:, :, 0])
cv.fillPoly(mask, polygons, 255)
channels = image.shape[2]
masked_image = np.zeros_like(image)
for c in range(channels):
masked_image[:, :, c] = cv.bitwise_and(image[:, :, c], mask)
return masked_image
|
import csv
import os
from tkinter.filedialog import askopenfilename
#get input from user
fileToOpen = 'C:\\...\\YoloRecord.csv' #askopenfilename()
def csvToList(csvFile):
csvList = []
with open(csvFile) as csvfile:
fileReader = csv.reader(csvfile)
for row in fileReader:
csvList.append(row)
print(csvList)
return csvList
#narrow down all order to only the orders that match the users input
def returnMatchingOrders(csvFile, expiration, ticker, optionType, strike):
matchingOrders = []
for row in csvToList(csvFile):
if row[1] == expiration and row[2] == ticker and row[3] == optionType and row[7] == strike:
matchingOrders.append(row)
print(matchingOrders)
return matchingOrders
#arrange orders that match criteria into buy or sell buckets, also aggregate number of contracts
def sortOrderList(orderList):
contractList = []
buyList = []
sellList = []
for order in orderList:
buyOrSell = order[4]
extension = float(order[8])
contracts = int(order[5])
if buyOrSell == 'Buy':
buyList.append(extension)
contractList.append(contracts)
elif buyOrSell == 'Sell':
sellList.append(extension)
else:
print('data corrupt')
pass
return {'contractList': contractList, 'buyList': buyList, 'sellList': sellList}
#perform math and give main dictionary of info to print
def returnTotals(sortedOrderList):
totalContracts = sum(sortedOrderList['contractList'])
averageBuy = (sum(sortedOrderList['buyList']) / totalContracts) / 100
averageSell = (sum(sortedOrderList['sellList']) / totalContracts) / 100
return {'totalContracts': totalContracts, 'averageBuy': averageBuy, 'averageSell': averageSell}
def yoloRecordSearch(fileToOpen):
expiration = str(input("Expiration date? "))
ticker = (input("Ticker? ")).upper()
optionType = str(input("Put or Call? "))
strike = str(input("Strike? "))
#sanitize inputs
if expiration[-4:] != 2020:
expiration = expiration + '/2020'
if optionType != 'Put' and optionType != 'Call':
if optionType == 'P' or optionType == 'p':
optionType = 'Put'
elif optionType == 'C' or optionType == 'c':
optionType = 'Call'
if strike[-3:] != ('.00' or '.50'):
strike = strike + '.00'
try:
matchingOrders = returnMatchingOrders(fileToOpen, expiration, ticker, optionType, strike)
sortedOrderList = sortOrderList(matchingOrders)
totals = returnTotals(sortedOrderList)
print(f"\n Total Contracts: {totals['totalContracts']}")
print(f"Average Buy Price: {totals['averageBuy']}")
print(f"Average Sell Price: {totals['averageSell']}")
except ZeroDivisionError:
print("No contracts found matching descriptors")
print("\n Press enter to close or r to repeat")
closeOrRepeat = input()
if closeOrRepeat == 'r':
yoloRecordSearch(fileToOpen)
yoloRecordSearch(fileToOpen)
|
import numpy as np
a = np.array([[30,17,15],[19,90,16],[69,53,21]])
print 'Our array is:'
print a
print '\n'
print 'Applying sort() function:'
print np.sort(a)
print '\n'
print np.sort(a,axis=1)
print np.sort(a,axis=0)
# Order parameter in sort function
dt = np.dtype([('name', 'S10'),('age', int)])
a = np.array([("Karan",21),("Arpit",25),("Ashish", 17), ("Sam",27),("Robin",22)], dtype = dt)
print 'Our array is:'
print a
print '\n'
print 'Order by name:'
print np.sort(a, order = 'name')
print 'Order by age:'
print np.sort(a, order = 'age')
|
import numpy as np
a = np.array([[1,2,3],[3,4,5],[5,6,7]])
print 'First array:'
print a
print '\n'
b = np.array([[5,6,7],[7,8,9],[10,11,12]])
print 'Second array:'
print b
print '\n'
# both the arrays are of same dimensions
print 'Joining the two arrays along axis 0:'
print np.concatenate((a,b))
print '\n'
print 'Joining the two arrays along axis 1:'
print np.concatenate((a,b),axis = 1)
|
import numpy as np
a = np.array([1,2,3,4])
print 'Our array is:'
print a
print '\n'
print 'Applying average() function:'
print np.average(a)
print '\n'
# this is same as mean when weight is not specified
wts = np.array([4,3,2,1])
print 'Applying average() function again:'
print np.average(a,weights = wts)
print '\n'
# Returns the sum of weights, if the returned parameter is set to True.
print 'Sum of weights'
print np.average([4,3,2,1],weights = [1,2,3,4], returned = True)
#4*1 + 3*2 + 2*3 + 1*4 / sum of weight = 1+2+3+4
|
import random
import os
my_dict = {
"What is the base-2 number system called" : "binary",
"What is the number system that uses the characters 0-F called" : "hexadecimal",
"What is the 7-bit text encoding standard called" : "ascii",
"What is the 16-bit text encoding standard called" : "unicode",
"What is it called when a number is bigger than the maximum number that can be stored" : "overflow",
"What are 8 bits refered to" : "byte",
"What is 1024 bytes refered to" : "kilobyte",
"A Picture Element. This is the smallest component of a bitmapped image" : "pixel",
"What is a continuously changing wave, such as natural sound called" : "analog",
"What is the number of times per second that a wave is measured called" : "sample rate",
"What is a binary representation of a program called" : "machine code",
"What does CPU stand for" : "central processing unit",
"What is the MOST commonly used Object-Oriented programming language in the world" : "C",
"What computer program is used to convert assembly language into machine language" : "compiler",
"What is the time required for the fetching and execution of data of a simple machine instruction called" : "CPU cycle",
"What access method is used for obtaining a record from a cassette tape" : "sequential",
"The term referring to the evacuation of content or data to some part of the machine is called" : "dump",
"What is the common boundary between two systems is called" : "interface"
}
print("=======================")
print("Computer Revision quiz")
print("=======================")
playing = True
while playing == True:
score = 0
print("There are " + str(len(my_dict)) + " questions.")
num = int(input("\nHow many questions would you like? : "))
print("\n(all answers should be typed in lowercase!)")
for i in range(num):
question = (random.choice(list(my_dict.keys())))
answer = my_dict[question]
print("\nQuestion " + str(i+1) )
print(question + "?")
guess = input("> ") #this is just your attempts at the question
if guess.lower() == answer.lower():
print("Correct!")
score += 1 #adds to your score
else:
print("Nope!")
print("\nYour final score was " + str(score))
again = input("Enter any key to play again, or 'q' to quit.")
if again.lower() == 'q':
playing = False
|
import heapq as hq
num=[25, 35, 22, 85, 14, 65, 75, 22, 58]
print('Original list : ',str(num))
largest=hq.nlargest(3,num)
print("\nThree largest numbers are : ",largest)
|
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def isKey(x):
if x in d:
print('Key is present in dictionary')
else:
print('Key is not present in dictionary')
x=int(input('Enter the numbers to check : '))
print(isKey(x))
|
import heapq as hq
def heapsort(i):
li=[]
for value in i:
hq.heappush(li,value)
return [hq.heappop(li) for i in range(len(li))]
print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
|
def Email(F_name,L_name,email):
print(' {} {}, you are sucessfully done our registration work with your Email id : {} '.format(F_name,L_name,email))
F_name=input('Enter first name : ')
L_name=input('Enter last name : ')
email=input('Enter the email : ')
Email(F_name,L_name,email)
|
from collections import deque
from queue import LifoQueue
stack1=LifoQueue(maxsize=2)
stack=deque()
stack=[]
stack.append('a')
stack.append('b')
print(stack)
stack.append(1)
stack.append(2)
stack.append(3)
stack.pop()
print(stack)
print("Size ",stack1.qsize())
stack1.put('a')
stack1.put('b')
print("Full : ",stack1.full())
print("Size : ",stack1.qsize())
print("Element popped")
print(stack1.get())
|
class Student:
def __init__(self,name,age):
self.name=name
self.age=age
def myFunct(self):
print("Hello my name is " + self.name)
p1=Student('Priyanshu Singh',19)
p1.age=19
print(p1.age)
p1.myFunct()
|
n=int(input("Enter the number to find fact : "))
factorial=1
if n<0:
print("Input is wrong")
elif n==0:
print("Factorial is 1")
else:
for i in range(1,n+1):
factorial=factorial*i
print("factorial is " + str(factorial))
|
from array import *
def dupli(n):
n_set=set()
n_dupli=-1
for i in range(len(n)):
if n[i] in n_set:
return n[i]
else:
n_set.add(n[i])
return n_dupli
n=array('i',[1,3,5,4,32,65,53,243,3])
print(dupli(n))
|
# Importing Modules
import random
import sys
# A Function to ask if the player would like to play again
def playAgain():
answer = input("Would you like to play again? Yes/No ")
answer = answer.lower()
if answer == 'yes' or answer == 'y':
game()
if answer == 'no' or answer == 'n':
print('Thank you for playing. Please come again!')
sys.exit()
else:
print('I\'m not quite sure what you said')
playAgain()
# MAIN GAME FUNCTION
def game():
# Creating Variables
suits = ['Spades','Hearts','Diamonds','Clubs']
computerCards = []
computerValue = 0
playerCards = []
playerValue = 0
# A Function for Getting a Card
def getCards():
card = random.randint(1,13)
if card > 10:
card = 10
return card
# A Function For Adding Cards in Blackjack
def sumOfCards(cards, value):
value = 0
if 1 in cards:
for card in cards:
if card == 1 and value < 21:
value += 11
else:
value += card
if value > 21:
value = sum(cards)
else:
value = sum(cards)
return value
# A Function to Deal Cards to the Computer
def computerDeal():
computerCards.append(getCards())
computerCards.append(getCards())
# A Function to Deal Cards to the Player
def playerDeal():
playerCards.append(getCards())
playerCards.append(getCards())
# A Function to Print the Player's Cards and the Computer's First Card
def printPlayerCards(player, computer):
print("Your Cards: ", end = '')
print('%s' % ', '.join(map(str, player)))
print("Computer Cards: ", end = '')
print(computer[0], end = '')
print(", X")
# A Function to Print the Player's Cards and the Computer's Cards
def printAllCards(player, computer):
print("Your Cards: ", end = '')
print('%s' % ', '.join(map(str, player)))
print("Computer's Cards: ", end = '')
print('%s' % ', '.join(map(str, computer)))
# Dealing and setting the Value
computerDeal()
playerDeal()
playerValue = sumOfCards(playerCards, playerValue)
computerValue = sumOfCards(computerCards, computerValue)
printPlayerCards(playerCards, computerCards)
# Allows the Player to Draw Cards
while True:
# Exits if the Player Has Busted
if playerValue > 21:
print("You've gone over 21! You lost!")
playAgain()
# Asking the Player to Hit or Stand
action = input("Hit or Stand? ")
action = action.lower()
# Carrying out the Commands of the Player
if action == "hit" or action == "h":
playerCards.append(getCards())
if playerValue > 21:
printAllCards(playerCards, computerCards)
print("You've gone over 21! You lost!")
playAgain()
playerValue = sumOfCards(playerCards, playerValue)
printPlayerCards(playerCards, computerCards)
elif action == "stand" or action == "s":
break
else:
print("I'm not sure what you said, try again!")
# Allowing the Computer to Draw Cards Until It's Busted or It's Score is Higher Than the Player's
while (computerValue < playerValue):
computerCards.append(getCards())
computerValue = sumOfCards(computerCards, computerValue)
if computerValue > 21 and playerValue <= 21:
printAllCards(playerCards, computerCards)
print("You Win! The computer has busted.")
playAgain()
# Evaluating The Outcome of the Game
printAllCards(playerCards, computerCards)
if playerValue > computerValue and playerValue <= 21:
print("You Win!")
playAgain()
elif playerValue == computerValue and playerValue <= 21:
print("It's a Tie!")
playAgain()
elif playerValue < computerValue and playerValue <= 21 and computerValue <= 21:
print("The computer got a higher score, you lost!")
playAgain()
# Introduction, Includes Title, Names, Description and Directions
print("Welcome to Blackjack! The goal of the game is to get as close to 21 as possible, without going over. Type 'h' or 'hit' to draw a card, and type 's' or 'stand' when you're done")
print("Made by Tony and Jia Ming")
game()
|
# 给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
#
# 你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
#
# 请你计算并返回达到楼梯顶部的最低花费。
#
from typing import List
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
n = len(cost)
dp = [0] * (n+2)
dp[0] = 0
dp[1] = 0
for i in range(2, n+1):
dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2])
return dp[n]
if __name__ == '__main__':
s=Solution()
cost = [10, 15, 20]
res = s.minCostClimbingStairs(cost)
print(res)
|
a=[1,5,7,8,9,5,88,7,4,5,82,3,5,1,2,3,5]
a.sort()
y=a[-1]
for x in range(len(a)-2,-1,-1):
if y==a[x]:
a.remove(a[x])
else:
y=a[x]
print(a)
|
from create_acc import *
os.chdir(os.path.dirname(os.path.abspath(__file__)))
db = sqlite3.connect("data.db")
cr = db.cursor()
def commit():
db.commit()
db.close()
def create():
global create
os.system('clear')
print("-"*50)
print(
'''
Warning !!
If you entered any wrong input or wrong data, Everything will be returned from the beginning
''')
print("-"*50)
try:
ID = int(input("Enter your national ID \n\n>>> "))
time.sleep(1)
os.system('clear')
print("-"*50)
cr.execute("select id from customers")
Ids = cr.fetchall() # select all ids from row
length = len(Ids)
i = 0
while i < length: # check if input id is exist in row
if ID == (Ids[i][0]): # Ith tuple in list and 0th in the tuple (the value of id)
print ("this ID is already exist. please make sure from your ID")
print ("-"*50)
raise
# ^^^ this is deliberated error to exited from the function and move to except and call function from beginning
i += 1
#--------------------------------------------------------------------
else:
fullname = str(input("Enter your name \n\n>>> "))
user = ''.join(fullname[:3]) + ''.join(str(random.randrange(1000))) # create random user name by first 3 character of name
time.sleep(1)
os.system('clear')
print("-"*50)
#--------------------------------------------
phone = int(input("Enter your phone number \n\n>>> "))
time.sleep(1)
os.system('clear')
print("-"*50)
#--------------------------------------------
letters = string.ascii_lowercase # all characters as lower case
passw = ''.join(random.choice(letters) for i in range(3)) + ''.join(str(random.randrange(20)) for i in range(3)) # random password
#===================================================================================================================
cr.execute(f"insert into customers values('{ID}', '{fullname}', '{phone}', '{user}','{passw}')")
commit()
print("please wait, your data are uploading now")
for i in range(3):
print(". ")
time.sleep(1)
print("-"*50)
print(
f"""
hello {fullname} the registering has been successful
your user_name is >> {user}
your password is >> {passw}
""")
print("-"*50)
print("-"*50)
time.sleep(1)
print("do you need create an account now?")
print("1- Yes \n2- Not now")
create = int(input("Enter choice : "))
time.sleep(1)
os.system('clear')
print("-"*50)
if create == 1:
create_account(ID)
else:
return 0
except:
print("-"*50)
print("-"*50)
print("there is an error.please try again")
print(".\n"*3)
time.sleep(2)
create()
if __name__ == '__main__':
create() |
#!/usr/bin/python
#Python program to discover print function
'''
print syntax:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
'''
#print without any parameters
print()
#Print a static message
print( "Welcome to discover python3 print function" )
#Print value stored in variable
string1 = "This is a simple line to print"
print( string1 )
#Print two variables
#The default parameters for sep is ' ', end is '\n'
string2 = "Printing another line adjacent to first line"
print( string1, string2 )
#printing two variables by modifying default sep, end parameters
string3 = "This is the another line printing using separator '. '"
print( string1, string3, sep = '. ',end = '\n' )
#printing static message along with variables
print('\n#Printing static message along with variables')
name = "Ram"
print( "Howdy", name, "!! How are you doing" )
print( "All the best " + name + '!' )
|
"""
CPLab_14.1: Box
-----------
This is the object class for lab 14.1. It
should create a Box object.
"""
class Box:
"""Constructor"""
def __init__(self, wrd=""):
self.word = wrd
"""Modifier"""
def setWord(self, wrd):
self.word = wrd
def getWord(self):
return self.word
"""for loop: from i = 0 - length of word
print word each time the loop runs."""
def __str__(self):
return str(self.getWord())
#for na in range (4, 0, -1):
# print("Na")
#print()
#print("Remember this song?")
#or na in range (len(s), 0, -1):
# print("Na")
#print()
|
__author__ = 'Surya'
class GetSs:
def __init__(self, chk):
self.check = chk
self.count = 0
def setCheck(self, chk):
self.check = chk
self.count = 0
def countSs(self):
for i in range(0, len(self.check)):
if self.check[i] == "s":
self.count += 1
def __str__(self):
self.countSs()
return "The String " + self.check + " contains " + str(self.count) + " s's." |
"""
Lab 22.2 List Count
---------
In this lab, you will write a program that counts the
number of instances of an input number in an array. for
example, the array [3, 5, 3, 4] contains 2 instances of
the number 3.
"""
from ListCount import *
def main():
nums = [7, 7, 1, 7, 8, 7, 4, 3, 7, 9, 8]
val = 7
object = ListCount(nums, val)
print(object)
main() |
"""================================================================
* Lab_13.3
*
* Lab Goal :
* -----------
* This lab was designed to teach you more about objects and
* the String class.
*
* Lab Description :
* -----------------
* One person is going to marry another person and take his or
* her last name. You will write a program that allows you to
* enter the full name of the person getting married, and his or
* her potential spouse, and return the full name of the person
* getting married, including his or her new last name.
*
*
* Sample Data : Sample Output :
* ------------ ---------------
* Sally Baker If Sally Baker marries Arnold Palmer.....
* Arnold Palmer Sally's name wil be Sally Palmer
*
==================================================================="""
from Marriage import*
def main():
"""Test Cases"""
spouse1 = "Sally Baker"
spouse2 = "Arnold Palmer"
marry = Marriage(spouse1, spouse2)
print(marry)
newspouse1 = input("Who is your spouse 1(this is the girl who is getting married: ")
newspouse2 = input("Who is your spouse 2(this is the boy who is getting married: ")
object = Marriage(newspouse1,newspouse2)
print(object)
"""Now take user input for spouse1 and spouse2. You should know by
* now that you don't need to make another Marriage object. Use the
* modifier in marry to add new data
*
* 1. Add new Scanner object
* 2. Add user inputs for spouse1 and spouse2
* 3. Place input data into the modifier
* 4. print the object's toString()"""
main()
|
"""
* APLab_14.4: Factorial
*------------
* This is the object class for lab 14.4. It
* should create a Factorial object.
"""
class Factorial:
"""Constructor"""
def __init__(self, num):
self.number = num
self.Factorial = 1
"""Modifier"""
def setNum(self, num):
self.number = num
"""Accessor"""
def getNum(self):
return self.number
"""Calculate the factorial value:
* Start with a variable "factorial" to hold the factorial value.
* for loop: from i = 1 to number+1 (exclusive). Multiply the
* factorial by i each time the loop runs."""
def getFactorial(self):
for i in range(self.number,0,-1):
self.Factorial = self.Factorial * i
return self.Factorial
"""__str___() function"""
def __str__(self):
return "!" + str(self.getNum()) + " = " + str(self.getFactorial()) |
import math
class Circle:
def __init__(self, r=0):
self.radius = r
self.pi = math.pi
def setValues(self, r1=0):
self.r = r1
def calcCircle(self):
self.circle = self.pi * self.radius**2
def getCircle(self):
return self.circle |
"""
Lab 23.2 List Fun House
--------
In this lab, you will write a program takes an array and...
- prints the sum of values from @ start to @ stop
- counts the number of times val occurs in the list
- returns a copy of the list with all occurrences of val removed
"""
from ListFunHouse import *
def main():
one = [7, 4, 10, 0, 1, 7, 6, 5, 3, 2, 9, 7]
print(one)
lfh = ListFunHouse(one)
print("Sum of spots 3-6 = " + str(lfh.getSum(3, 6)))
print("Sum of spots 2-9 = " + str(lfh.getSum(2, 9)))
print("# of 4s = " + str(lfh.getCount(4)))
print("# of 4s = " + str(lfh.getCount(7)))
print("The list without 7s: " + str(lfh.removeVals(7)))
two = [4,2,3,4,6,7,8,9,0,10,0,1,7,6,5,3,2,9,9,8,7]
print (two)
lfh.setList(two)
print("Sum of spots 3-6 = " + str(lfh.getSum(3, 16)))
print("Sum of spots 2-9 = " + str(lfh.getSum(2, 9)))
print("# of 4s = " + str(lfh.getCount(0)))
print("# of 4s = " + str(lfh.getCount(4)))
print("The list without 7s: " + str(lfh.removeVals(7)))
main() |
"""
CPLab_15.3: Vowel Counter
-----------
This is the object class for the VowelCounter lab.
"""
class VowelCounter:
"""Constructor"""
def __init__(self, wrd):
self.word = wrd
self.found = 0
self.vowels = "aeiouAEIOU"
"""Modifier"""
def setWord(self, wrd):
self.word = wrd
self.found = 0
"""for loop: from 0 to length of [word]. For each letter (word[i]),
check if it is contained in [vowels]. Add 1 to [found] every letter
found in [vowels]"""
def getNumberVowels(self):
for i in range(0, len(self.word)):
if self.word[i] in self.vowels:
self.found += 1
return self.found
"""__str__(): return "The String [word] contains [found] vowels. """
def __str__(self):
return "There are " + str(self.getNumberVowels()) + " vowels in the word you entered." |
from Circle import*
""" Declare your class and main() method """
def main():
r = int(input("What is the radius: "))
newUser = Circle(r)
newUser.calcCircle()
area = 22/7 * r
print("Your circle is ", newUser.getCircle())
""" take user input for the radius of a circle"""
""" Create a new object of the class Circle
Enter parameters"""
"""Print the return value of calcArea()"""
main() |
"""
================================================================
Lab_24.2 Sorry Game
---------
In this lab, you will be writing a program that emulates
the classic came "Sorry". You will move 5 pieces around
a track that is 18 spaces long against a second player. The
program simulates a dice roll to move pieces. If a player
lands on a spot where your piece is, your piece will be moved
back to square 0. The player that completes 5 laps first wins.
================================================================
"""
from Sorry import *
s = Sorry()
print(s)
while s.play():
print(s)
print("\n\nAnd the Winner Is........" + s.getWinner())
|
"""Question 5: Missing a letter..."""
from Five import *
word = input("Please enter a word: ")
down = Down(word)
down.turnDown()
print(down)
|
"""
Ex_03
In this exercise, you will create a shopping list for
a party. You will list at least 4 items that you need
and print the results.
"""
class ShoppingList:
def __init__(self, i1, i2, i3, i4):
self.item1 = i1
self.item2 = i2
self.item3 = i3
self.item4 = i4
def getitem1(self):
return self.item1
def getitem2(self):
return self.item2
def getitem3(self):
return self.item3
def getitem(self):
return self.item4
def main():
i1 = input("What is your item1?: ")
i2 = input("What is your item2?: ")
i3 = input("What is your item3?: ")
i4 = input("What is your item4?: ")
print ("1. item1 = ", i1)
print ("2. item2 = ", i2)
print ("3. item3 = ", i3)
print ("4. item4 = ", i4)
main()
|
"""Question 3: Division by Zero error.."""
class FactorCounter:
def __init__(self, num):
self.number = num
self.count = 0
def setNum(self, num):
self.number = num
self.count = 0
def countFactors(self):
for i in range(1, self.number):
if self.number % i == 0:
self.count += 1
def __str__(self):
return "The number " + str(self.number) + " has " + str(self.count) + " factors." |
"""
* APLab_15.2: Greatest Common Denominator
* -----------
* In this lab, you will create a program that takes two input
* numbers, and finds their greatest common denominator. Your
* finished program should take two input numbers, and print the
* gcd of the two inputs. """
from GCD import*
from GCD import*
"""Test Case:
* Use these to help get your object class working" """
def main():
test = GCD(5, 25)
test.getGCD()
print(test)
Number1 = int(input("Select a number: "))
Number2 = int(input("Select another number: "))
test.setNums(Number1,Number2)
test.getGCD()
print("The greatest common denominator is...." + str(test))
main()
|
"""========================================================================================
* EX_01: if-else statements
*
* Objectives: The purpose of this lab is for you to demonstrate you have learned to use
* if-else statements to compare numerical data. You will be creating a
* program that returns the smallest and largest of two numbers.
*
* Instructions: Use the existing test case below to test your NumberCompare class. Then
* create a new test class with user inputs for the numbers. Try out some
* different numbers to see how it works.
*
========================================================================================"""
import random
from NumberCompare import*
n1 = input("What is your first number: ")
n2 = input("What is your second number: ")
Surya = NumberCompare(n1, n2)
Surya = Surya.__str__()
print(Surya)
#now add a new test case with user inputs....
#Then test 3 more sets of numbers with the modifier |
srepair = "0000fixed!"
print(srepair)
print(srepair.strip("0"))
sides = " <--I would love to touch the sides--> "
#original: nothing removed
print("|" + sides + "|")
#removes leading whitespace....
print("|" + sides.lstrip() + "|")
#removes trailning whitespace...
print("|" + sides.rstrip() + "|")
print("|" + sides.strip(" ") + "|")
name = "pRofesSor haNdSome"
name = name.upper()
print(name)
name = name.lower()
print(name)
name = name.title()
print(name)
name = "pRofesSor haNdSome"
name = name.swapcase()
print(name)
print (name.replace("s", "$"))
sentence = "Many grannies ran to catch the aardvark"
print (sentence.replace ("a", "@"))
word = "aardvark"
do = "zebra"
print(word<do)
if word > do:
print("Word comes first")
if word < do:
print("Do comes first")
name = str("James")
print(name)
|
import torch
import torch.nn as nn
import io
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
from pathlib import Path
path = Path('app/pretrained.pt')
#Define the shape/architecture of the model since pre-trained model can be further worked upon, or an test image can be used to find label
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#CNN
self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
#Max pool
self.pool = nn.MaxPool2d(2, 2)
#Neural Network
self.fc1 = nn.Linear(64 * 7 * 7, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, 64)
self.fc4 = nn.Linear(64, 10)
#Dropout Layer, with p=0.5
self.dropout = nn.Dropout(p=.5)
def forward(self, ans): #Once we have our test data, run it through the forward function - it takes the input through all the layers of the network
ans = self.pool(F.relu(self.conv1(ans)))
ans = self.pool(F.relu(self.conv2(ans)))
ans = ans.view(-1, 64 * 7 * 7)
ans = self.dropout(F.relu(self.fc1(ans))) #Relu helps normalise by making all negative equate to 0
ans = self.dropout(F.relu(self.fc2(ans)))
ans = self.dropout(F.relu(self.fc3(ans)))
ans = F.log_softmax(self.fc4(ans), dim=1)
return ans
#By defining a Net instance, we are now referring to a single Neural Network Net - one set of all layers layed one after the otjer
model_load = Net()
model_load.load_state_dict(torch.load(path, map_location='cpu'), strict=False)
model_load.eval()
#How to predict - run image_bytes through the model once
def predict(image_bytes):
transform = transforms.Compose([transforms.Resize((28,28)),
transforms.ToTensor()])
image = Image.open(io.BytesIO(image_bytes)).convert('L')
tensor = transform(image).unsqueeze(0)
output = model_load.forward(tensor) #actual prediction!
_, pred = torch.max(output, 1)
return pred.item()
|
#Create a function that shows the incomplete word/phrase that includes the letter(s) that have been guessed correctly
#Do an double if in the else
#mixed case letter: not str.islower() and not str.isupper()
name = "Dod"
if "X" in name:
print('Yes')
else:
print("no") |
A = int(input("Enter the principal amount : "))
B = int(input("Enter the number of years : "))
C = int(input("Enter the rate of interest : "))
SI = (A * B * C)/100.
print("Simple interest : {}". format(SI)) |
#!/usr/bin/env python
import argparse
def main():
# parse CLI args
parser = argparse.ArgumentParser(description="Computes profit/loss of a PokerStars HomeGame.")
parser.add_argument("-b", "--buy-in", type=float, default=5, help="buy in (€)")
parser.add_argument("players", metavar="PLAYER BALANCE", nargs="*", help="player names with chip balances")
args = parser.parse_args()
if len(args.players) % 2 != 0:
parser.error("odd number of player arguments")
# parse players and balances
players = [args.players[k] for k in range(0, len(args.players), 2)]
balances = [int(args.players[k+1]) for k in range(0, len(args.players), 2)]
# compute profits
profits = []
for player, balance in zip(players, balances):
profit = balance / sum(balances) * len(players) * args.buy_in - args.buy_in
profits.append(profit)
zero = sum(profits)
# sort by profit
profits, players, balances = zip(*sorted(zip(profits, players, balances), reverse=True))
# print profits
print("PokerStars HomeGame Calculator")
print("==============================")
for player, balance, profit in zip(players, balances, profits):
print(f"{profit:+.2f}€ {player} ({balance})")
print("------------------------------")
print(f"{zero:+.2f}€")
if __name__ == "__main__":
main()
|
'''
Using while loop , if else , for, break
Divisible by 3 - Fizz
Divisible by 5 - Buzz
Divisible by 3 and 5 - Fizz Buzz
Prime number - Prime
'''
count=1
while(count<=100):
if(count%3==0 and count%5==0):
print(count ,"-","Fizz Buzz")
elif(count==1 or count==2 or count==3 or count==5):
print(count ,"-","Prime")
elif(count%5==0 and count!=5):
print(count, "-","Buzz")
elif(count%3==0 and count!=3):
print(count ,"-","Fizz")
elif(count%2 != 0):
for i in range(3, 100):
if (count % i) != 0:
print(count ,"-","Prime")
break
else:
print(count)
count=count+1
|
class Node:
# Initialize the class
def __init__(self, position: (), parent: ()):
self.position = position
self.parent = parent
self.g = 0 # Distance to start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
# Compare nodes
def __eq__(self, other):
return self.position == other.position
# Sort nodes
def __lt__(self, other):
return self.f < other.f
# Print node
def __repr__(self):
return '({0},{1})'.format(self.position, self.f)
class MapManager:
open_nodes = None
closed_nodes = None
plateau = None
def __init__(self, plat):
self.open_nodes = []
self.closed_nodes = []
self.plateau = plat
@staticmethod
def astar_distance(start, end):
return abs(start[0] - end[0]) + abs(start[1] - end[1])
def astar_search(self, start, end):
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
self.open_nodes.append(start_node)
# Loop until the open list is empty
while len(self.open_nodes) > 0:
# Sort the open list to get the node with the lowest cost first
self.open_nodes.sort()
# Get the node with the lowest cost
current_node = self.open_nodes.pop(0)
# Add the current node to the closed list
self.closed_nodes.append(current_node)
# Check if we have reached the goal, return the path
if current_node == goal_node:
path = []
while current_node != start_node:
path.append(current_node.position)
current_node = current_node.parent
# Return reversed path
self.open_nodes = []
self.closed_nodes = []
return path[::-1]
# Unzip the current node position
(x, y) = current_node.position
# Get neighbors
neighbors = []
if x - 1 >= 0:
neighbors.append((x - 1, y))
if x + 1 <= 30:
neighbors.append((x + 1, y))
if y - 1 >= 0:
neighbors.append((x, y - 1))
if y + 1 <= 30:
neighbors.append((x, y + 1))
# Loop neighbors
for next_node in neighbors:
# Get value from plat
map_value = self.plateau[next_node[0]][next_node[1]]
# Check if the node is a wall
if map_value != "R":
continue
# Create a neighbor node
neighbor = Node(next_node, current_node)
# Check if the neighbor is in the closed list
if neighbor in self.closed_nodes:
continue
# Generate heuristics (Manhattan distance)
neighbor.g = abs(neighbor.position[0] - start_node.position[0]) + abs(
neighbor.position[1] - start_node.position[1])
# neighbor.h = abs(neighbor.position[0] - goal_node.position[0]) + abs(neighbor.position[1] - goal_node.position[1])
neighbor.f = neighbor.g # +neighbor.h
# Check if neighbor is in open list and if it has a lower f value
if self.add_to_open(neighbor):
# Everything is green, add neighbor to open list
self.open_nodes.append(neighbor)
# Return None, no path is found
return None
# Check if a neighbor should be added to open list
#def add_to_open(self, neighbor):
# for node in self.open_nodes:
# if neighbor == node and neighbor.f >= node.f:
# return False
# return True
# #
## ##
###### ######
## ##
def add_to_open(self, neighbor): #
# #
for node in self.open_nodes: #
# # # #
# # # # #
# # # # #
# # # # #
# # #### # #
# ##### ## # #
# ##### # # #
#### # # #
# # #
# # #
# # # #
# # # #
# # # #
if neighbor == node and neighbor.f >= node.f:
# # # #
return False ## ## #
# # # ### # #
# # # # ####
# # # ###
# # #
return True #
# # #
# # #
# # |
#Задача 4. Вариант 5.
#Напишите программу, которая выводит имя "Жан Батист Поклен", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Dzhariashvili D. G.
#15.04.2016
real_name = "Фредерик Аустерлиц"
imaginary_name = "Фред Астер"
interests = ("Актер", "Танцор")
born_place = "США"
born_year = 1899
death_year = 1987
death_oldness = death_year - born_year
print(real_name + " \nболее известный под псевдонимом "
+ imaginary_name + ".")
print("""
Нажмите чтобы вывести на экран:
1 - Место рождения,
2 - Год рождения,
3 - Возраст при смерти,
4 - Область интересов,
5 - Выход из программы\n\n""")
while True:
try:
choose = int(input("Ввод: "))
except:
print("Неправильный ввод")
choose = 0
if choose == 1:
print("Место рождения: " + str(born_place))
elif choose == 2:
print("Год рождения: " + str(born_year))
elif choose == 3:
print("Возраст при смерти: " + str(death_oldness))
elif choose == 4:
print("Область интересов: " + " ".join(interests))
elif choose == 5:
break
input("\nНажмите Enter для выхода") |
# PONG Gone Wild
# Date: Aug 30, 2018
# By: Kavan Lam
######################################################################################################################
# The following is an independent game project. The game is called 'PONG Gone Wild' and is a twist to the classic #
# arcade game, 'PONG'. This version features many new features and visuals. This is for non-commercial use only. #
######################################################################################################################
# GUI will take care of all the visuals from pygame
import pygame
import math
# initiate pygame
pygame.mixer.pre_init(22050, -16, 15, 512)
pygame.init()
# defining all game colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 150, 0)
blue = (0, 0, 255)
orange = (255, 165, 0)
purple = (147, 112, 219)
orchid = (218, 112, 214)
yellow = (255, 255, 0)
skyblue = (135, 206, 235)
teal = (0, 128, 128)
class GUI:
def __init__(self):
self.width = 1150
self.height = 650
self.game_screen = pygame.display.set_mode([self.width, self.height])
pygame.display.set_caption("PONG Gone Wild")
def prepare_text(self, text_list):
prepared_text = []
for tup in text_list:
font_galaxy = pygame.font.Font("./font_styles/Galaxy Force.ttf", tup[1])
prepared_text.append(font_galaxy.render(tup[0], True, tup[2]))
return prepared_text
def draw_dashed_line(self, pos1, pos2, color):
if pos1[0] != pos2[0]: # if not a vertical line
slope = (pos2[1] - pos1[1]) / (pos2[0] - pos1[0])
y_int = pos1[1] - (slope * pos1[0])
x = min(pos1[0], pos2[0])
while x <= max(pos1[0], pos2[0]):
y1 = int((slope * x) + y_int)
y2 = int((slope * (x + 10)) + y_int)
pygame.draw.line(self.game_screen, color, [x, y1], [x + 10, y2], 2)
x += 20
else: # if a vertical line
y = min(pos1[1], pos2[1])
x = pos1[0]
while y <= max(pos1[1], pos2[1]):
pygame.draw.line(self.game_screen, color, [x, y], [x, y + 10], 2)
y += 20
def draw_time_ray_icon(self, x, y):
pygame.draw.line(self.game_screen, purple, [x - 20, y], [x - 10, y - 10], 2)
pygame.draw.line(self.game_screen, purple, [x - 20, y], [x - 10, y + 10], 2)
pygame.draw.line(self.game_screen, orchid, [x - 20, y], [x + 19, y], 2)
pygame.draw.circle(self.game_screen, green, [x, y], 20, 2)
def draw_time_ray_use(self, p_use_num, p_use):
x = p_use.pad_x
y = p_use.pad_y
if p_use_num == 1:
f = -1
else:
f = 1
pygame.draw.line(self.game_screen, purple, [x, y], [x - (70 * f), y - 30], 2)
pygame.draw.line(self.game_screen, purple, [x, y], [x - (70 * f), y + 30], 2)
pygame.draw.line(self.game_screen, orchid, [x, y], [x - (1090 * f), y], 2)
def draw_afterburner_icon(self, x, y):
pygame.draw.line(self.game_screen, yellow, [x, y - 10], [x, y + 10], 2)
pygame.draw.line(self.game_screen, yellow, [x, y - 10], [x - 7, y - 5], 2)
pygame.draw.line(self.game_screen, yellow, [x, y - 10], [x + 7, y - 5], 2)
pygame.draw.circle(self.game_screen, green, [x, y], 20, 2)
def draw_afterburner_use(self, p_use_num, p_use):
x = p_use.pad_x
y = p_use.pad_y
rec = (x - 30, y - 50, 60, 100)
if p_use_num == 1:
pygame.draw.arc(self.game_screen, yellow, rec, math.radians(90), math.radians(270), 2)
pygame.draw.arc(self.game_screen, orange, rec, math.radians(45), math.radians(90), 2)
pygame.draw.arc(self.game_screen, orange, rec, math.radians(270), math.radians(315), 2)
pygame.draw.arc(self.game_screen, red, rec, math.radians(315), math.radians(405), 2)
else:
pygame.draw.arc(self.game_screen, yellow, rec, math.radians(270), math.radians(450), 2)
pygame.draw.arc(self.game_screen, orange, rec, math.radians(90), math.radians(135), 2)
pygame.draw.arc(self.game_screen, orange, rec, math.radians(225), math.radians(270), 2)
pygame.draw.arc(self.game_screen, red, rec, math.radians(135), math.radians(225), 2)
def draw_quantum_icon(self, x, y, fac):
pygame.draw.line(self.game_screen, skyblue, [x - (1 * fac), y - (5 * fac)], [x - (1 * fac), y - (15 * fac)], 2)
pygame.draw.line(self.game_screen, skyblue, [x - (1 * fac), y + (5 * fac)], [x - (1 * fac), y + (15 * fac)], 2)
pygame.draw.line(self.game_screen, skyblue, [x - (5 * fac), y], [x - (15 * fac), y], 2)
pygame.draw.line(self.game_screen, skyblue, [x + (5 * fac), y], [x + (15 * fac), y], 2)
pygame.draw.line(self.game_screen, skyblue, [x + (6 * fac), y + (6 * fac)], [x - (6 * fac), y - (6 * fac)], 1)
pygame.draw.line(self.game_screen, skyblue, [x + (6 * fac), y - (6 * fac)], [x - (6 * fac), y + (6 * fac)], 1)
pygame.draw.circle(self.game_screen, teal, [x, y], 3, 0)
if fac == 1: # if fac is one then we are only drawing the icon so include this circle
pygame.draw.circle(self.game_screen, green, [x, y], 20, 2)
def draw_quantum_use(self, p_use):
self.draw_quantum_icon(int(p_use.pad_x), int(p_use.pad_y), 5)
def clear_screen(self):
self.game_screen.fill(black)
def draw_game_menu(self):
# prepare text to be displayed
text = [("PONG Gone Wild", 100, green), ("Play", 100, green), ("Instructions", 40, green),
("Credits", 60, green), ("A", 60, green), ("B", 60, green), ("C", 60, green)]
menu_text = self.prepare_text(text)
# displaying all main menu visuals #
# title
pygame.draw.line(self.game_screen, green, [240, 110], [910, 110], 2)
self.game_screen.blit(menu_text[0], (self.width // 4.5, 0))
# play button
pygame.draw.rect(self.game_screen, blue, [170, 400, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [270, 400], [270, 310], 2)
pygame.draw.line(self.game_screen, red, [270, 310], [210, 310], 2)
pygame.draw.circle(self.game_screen, red, [180, 310], 30, 2)
self.game_screen.blit(menu_text[1], (190, 385))
self.game_screen.blit(menu_text[4], (166, 275))
# instruction button
pygame.draw.rect(self.game_screen, blue, [470, 400, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [570, 400], [570, 340], 2)
pygame.draw.circle(self.game_screen, red, [570, 310], 30, 2)
self.game_screen.blit(menu_text[2], (479, 415))
self.game_screen.blit(menu_text[5], (560, 275))
# credits button
pygame.draw.rect(self.game_screen, blue, [770, 400, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [870, 400], [870, 310], 2)
pygame.draw.line(self.game_screen, red, [870, 310], [930, 310], 2)
pygame.draw.circle(self.game_screen, red, [960, 310], 30, 2)
self.game_screen.blit(menu_text[3], (793, 405))
self.game_screen.blit(menu_text[6], (949, 275))
def draw_game_play(self, p1, p2, ball):
# prepare text to be displayed
text = [("Player 1", 30, orange), ("Player 2", 30, blue), (str(p1.score), 50, orange),
(str(p2.score), 50, blue)]
play_text = self.prepare_text(text)
# display all the game play visuals
# border --- The exact dimensions are 15 <= x <= 1135 and 2 <= y <= 580
pygame.draw.line(self.game_screen, red, [0, 2], [1150, 2], 3)
pygame.draw.line(self.game_screen, red, [0, 582], [1150, 582], 3)
pygame.draw.line(self.game_screen, red, [2, 0], [2, 580], 3)
pygame.draw.line(self.game_screen, red, [1148, 0], [1148, 580], 3)
pygame.draw.line(self.game_screen, red, [575, 0], [575, 580], 3)
# player 1
pygame.draw.line(self.game_screen, p1.color, [round(p1.pad_x), round(p1.pad_y) - 30], [round(p1.pad_x),
round(p1.pad_y) + 30], 4)
self.game_screen.blit(play_text[0], (15, 600))
self.game_screen.blit(play_text[2], (500, 585))
self.draw_dashed_line([15, 10], [15, 570], orange)
if p1.powers[0] == 1:
self.draw_time_ray_icon(200, 615)
if p1.powers[1] == 1:
self.draw_afterburner_icon(270, 615)
if p1.powers[2] == 1:
self.draw_quantum_icon(340, 615, 1)
# player 2
pygame.draw.line(self.game_screen, p2.color, [round(p2.pad_x), round(p2.pad_y) - 30], [round(p2.pad_x),
round(p2.pad_y) + 30], 4)
self.game_screen.blit(play_text[1], (1035, 600))
self.game_screen.blit(play_text[3], (630, 585))
self.draw_dashed_line([1135, 10], [1135, 570], blue)
if p2.powers[0] == 1:
self.draw_time_ray_icon(800, 615)
if p2.powers[1] == 1:
self.draw_afterburner_icon(870, 615)
if p2.powers[2] == 1:
self.draw_quantum_icon(940, 615, 1)
# ball
pygame.draw.circle(self.game_screen, ball.color, [round(ball.ball_x), round(ball.ball_y)], ball.ball_radius, 0)
def draw_game_instructions(self):
# prepare text to be displayed
text = [("Instructions", 100, green), ("Back", 70, green), ("A", 60, green), ("Movement", 40, green),
("Player1 (Left)", 30, orange), ("Player2 (Right)", 30, blue), ("Up = W", 26, orange),
("Down = S", 26, orange), ("Up = up arrow key ", 26, blue), ("Down = down arrow key", 26, blue),
("Powers", 40, green), ("Time Ray = C", 26, orange), ("Afterburner = V", 26, orange),
("Quantum Repulser = B", 26, orange), ("Time Ray = 1", 26, blue), ("Afterburner = 2", 26, blue),
("Quantum Repulser = 3", 26, blue),
("Time Ray: Shoot a high power laser at your foe to slow their movement", 26, green),
("Afterburner: Temporarily increases your movement speed", 26, green),
("Quantum Repulser: Emit a shock wave to vigorously knock the ball back towards your foe ", 26, green),
("To return to main menu when playing press ESC key", 26, green)]
instruction_text = self.prepare_text(text)
# displaying all instruction visuals #
# title
pygame.draw.line(self.game_screen, green, [345, 110], [820, 110], 2)
self.game_screen.blit(instruction_text[0], (self.width // 3.2, 0))
# movement instructions
pygame.draw.line(self.game_screen, red, [100, 160], [100, 190], 2)
pygame.draw.line(self.game_screen, red, [100, 190], [260, 190], 2)
pygame.draw.line(self.game_screen, red, [450, 190], [600, 190], 2)
self.game_screen.blit(instruction_text[3], (30, 120))
self.game_screen.blit(instruction_text[4], (273, 175))
self.game_screen.blit(instruction_text[5], (613, 175))
self.game_screen.blit(instruction_text[6], (273, 220))
self.game_screen.blit(instruction_text[7], (273, 250))
self.game_screen.blit(instruction_text[8], (613, 220))
self.game_screen.blit(instruction_text[9], (613, 250))
# powers instructions
pygame.draw.line(self.game_screen, red, [100, 310], [100, 340], 2)
pygame.draw.line(self.game_screen, red, [100, 340], [260, 340], 2)
pygame.draw.line(self.game_screen, red, [450, 340], [600, 340], 2)
self.game_screen.blit(instruction_text[10], (30, 270))
self.game_screen.blit(instruction_text[4], (273, 325))
self.game_screen.blit(instruction_text[5], (613, 325))
self.game_screen.blit(instruction_text[11], (273, 370))
self.game_screen.blit(instruction_text[12], (273, 400))
self.game_screen.blit(instruction_text[13], (273, 430))
self.game_screen.blit(instruction_text[14], (613, 370))
self.game_screen.blit(instruction_text[15], (613, 400))
self.game_screen.blit(instruction_text[16], (613, 430))
# powers descriptions
self.draw_time_ray_icon(50, 497)
self.draw_afterburner_icon(50, 540)
self.draw_quantum_icon(50, 583, 1)
self.game_screen.blit(instruction_text[17], (90, 480))
self.game_screen.blit(instruction_text[18], (90, 523))
self.game_screen.blit(instruction_text[19], (90, 566))
# exit game instruction
self.game_screen.blit(instruction_text[20], (90, 610))
# back button
pygame.draw.rect(self.game_screen, blue, [930, 20, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [1030, 110], [1030, 180], 2)
pygame.draw.circle(self.game_screen, red, [1030, 210], 30, 2)
self.game_screen.blit(instruction_text[1], (970, 23))
self.game_screen.blit(instruction_text[2], (1016, 173))
def draw_game_credits(self):
# prepare text to be displayed
text = [("Credits", 100, green), ("Back", 70, green), ("A", 60, green), ("Programming", 40, green),
("Kavan Lam (Using Python and Pygame)", 30, green), ("Visuals", 40, green),
("Galaxy Force by Pixel Sagas (font style)", 30, green), ("Kavan Lam (Using Pygame)", 30, green),
("Sounds", 40, green), ("Epic Night (Main Menu) by Kavan Lam (Using GarageBand)", 30, green),
("In game sound effects by Kavan Lam (Using GarageBand)", 30, green),
("End Game (Win Screen) by Kavan Lam (Using GarageBand)", 30, green),
("Deep Logic (In game) by Kavan Lam (Using GarageBand)", 30, green)]
credits_text = self.prepare_text(text)
# displaying all credit visuals #
# title
pygame.draw.line(self.game_screen, green, [440, 110], [710, 110], 2)
self.game_screen.blit(credits_text[0], (self.width // 2.55, 0))
# back button
pygame.draw.rect(self.game_screen, blue, [930, 20, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [1030, 110], [1030, 180], 2)
pygame.draw.circle(self.game_screen, red, [1030, 210], 30, 2)
self.game_screen.blit(credits_text[1], (970, 23))
self.game_screen.blit(credits_text[2], (1016, 173))
# programming section
pygame.draw.line(self.game_screen, red, [120, 160], [120, 190], 2)
pygame.draw.line(self.game_screen, red, [120, 190], [240, 190], 2)
self.game_screen.blit(credits_text[3], (30, 120))
self.game_screen.blit(credits_text[4], (250, 170))
# visuals section
pygame.draw.line(self.game_screen, red, [120, 260], [120, 290], 2)
pygame.draw.line(self.game_screen, red, [120, 290], [240, 290], 2)
self.game_screen.blit(credits_text[5], (65, 220))
self.game_screen.blit(credits_text[6], (250, 270))
self.game_screen.blit(credits_text[7], (250, 310))
# Sounds section
pygame.draw.line(self.game_screen, red, [120, 360], [120, 390], 2)
pygame.draw.line(self.game_screen, red, [120, 390], [240, 390], 2)
self.game_screen.blit(credits_text[8], (65, 320))
self.game_screen.blit(credits_text[9], (250, 370))
self.game_screen.blit(credits_text[11], (250, 400))
self.game_screen.blit(credits_text[12], (250, 430))
self.game_screen.blit(credits_text[10], (250, 460))
def draw_game_end(self, message):
# prepare text to be displayed
text = [(message[0], 100, green), (message[1], 70, green), ("Back", 70, green), ("A", 60, green)]
end_text = self.prepare_text(text)
# displaying all credit visuals #
# winner
self.game_screen.blit(end_text[0], (300, 50))
self.game_screen.blit(end_text[1], (300, 200))
# back button
pygame.draw.rect(self.game_screen, blue, [930, 20, 200, 90], 0)
pygame.draw.line(self.game_screen, red, [1030, 110], [1030, 180], 2)
pygame.draw.circle(self.game_screen, red, [1030, 210], 30, 2)
self.game_screen.blit(end_text[2], (970, 23))
self.game_screen.blit(end_text[3], (1016, 173))
|
import prompt
tries_count = 3
def flow_game(get_quiz, case):
print("Welcome to the Brain Games!")
print(case, end="\n\n")
user_name = prompt.string("May I have your name? ")
print("Hello, {}!".format(user_name))
for i in range(tries_count):
question, correct_answer = get_quiz()
print("Question: {}".format(question))
user_answer = input("Your answer: ")
if correct_answer == user_answer:
print("Correct!")
else:
print(
"'{}' is wrong answer ;(. Correct answer was '{}'.".format(
user_answer, correct_answer
)
)
print("Let's try again, {}!".format(user_name))
return
print("Congratulations, {}!".format(user_name))
|
# name="fngksjlxmzadkkdkf"
# print(name[0]) #数组第一位
# print(len(name)) #数组长度
# print(name[2:5]) #数组第三位到第五位
# my_List=["你好",2018,2019,2020,"许桐","许桐"]
# print(my_List[0]) #第一位
# my_List.append("大哥") #将对象追加到列表末尾
# print(my_List)
# print(my_List.count("许桐"))#返回值出现的次数,许桐出现两次
# help(my_List)
# mylist=[1,2,3,4,5]
# mytuple=(1,2,3,4,5)
# # print(type(mylist))
# #list is mutable 数据类型可变
# #tuple is inmutable 数据类型不可变
# #For example
# print(dir(mylist))
# print(".............")
# print(dir(mytuple))
# mylist.remove(2)
# print(mylist)
'''dictionary'''
# myDictionary={"key":"value","key2":"value"}
# myphone={"Iphone x":1000,"Huawei":10000}
# Iphone_price=myphone["Iphone x"]
# print("Iphone price:"+str(Iphone_price))
# #"Iphone price"是字符串不能直接与价格相加,需要将价格转换为字符串类
# myphone["Iphone x"]=100#降价到100
# print(myphone)
# myphone.clear()
# a=10
# b=20
# if a<b:
# print('hello')
# if b<30:
# print("mmm")
age=int(input("please enter your age:"))
if age<21:
print("you can not smoke")
elif age==100:
print("you are 100 years old,please quit smoking")
else:
print("you can smoke")
|
import sqlite3
def main():
with sqlite3.connect("Database.db") as db:
cursor=db.cursor()
sql="""create table User
(UserName text,
Password text,
FirstName text,
LastName text,
Email text,
StartFavourite text,
FinishFavourite text,
StartLast text,
FinishLast text,
primary key(UserName))
"""
cursor.execute(sql)
sql="""create table Location
(LocationID interger,
LocationName text,
Latitude text,
Longitude text,
Link text,
primary key(LocationID))
"""
cursor.execute(sql)
db.commit()
if __name__=="__main__":
choice=input("do you wish to make a new database? (y/n)").lower()
if choice =="y":
main()
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 15:30:06 2021
@author: sangliping
"""
num = input('请输入一个数字:')
if int(num)<10:
print(num)
if 3: #整数作为条件表达式
print('ok')
a = [] #列表作为表达式 空列表为False
if a:
print('空列表 False')
s = 'False' #非空字符串
if s:
print('非空字符串')
c = 9
if 3<c and c<20:
print("3<c and c<20")
if True: #布尔值
print("True")
num = input('请输入一个数字')
if int(num)<10:
print(num)
else:
print('数字太大')
num = input('请输入一个数字')
print(num if int(num)<10 else '数字太大')
score = int(input('请输入分数'))
grade = ''
if score<60:
grade = '不及格'
elif score>=60 and score<70:
grade='及格'
elif score>=70 and score<80:
grade = '良好'
else:
grade = '优秀'
print('分数是{0},等级是{1}'.format(score,grade))
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))
for x in list('slp'):
print(x)
d = {'name':'slp','age':18,'address':'bj'}
for x in d: #遍历所有的key
print(x)
for x in d.keys():#遍历字典所有的key
print(x)
for x in d.values():#遍历字典所有的value
print(x)
for x in d.items():#遍历字典所有的键值对
print(x)
sum_all=0
sum_even=0
sum_odd=0
for num in range(101):
sum_all +=num
if num%2 ==0:
sum_even+=num
else:
sum_odd+=num
print(sum_all,sum_even,sum_odd)
for m in range(1,10):
for n in range(1,m+1):
print(m,'*',n,'=',m*n ,end='\t')
print('')
while True:
a = input('输入Q退出')
if a.upper() == 'Q':
print('退出')
break
else:
print('继续')
empNum = 0
salarySum = 0;
salarys = []
while True:
s = input('请输入员工的工资(q或Q结束)')
if s.upper() =='Q':
print('录入完成 退出')
break;
if float(s)<0:
continue;
empNum+=1
salarys.append(float(s))
salarySum +=float(s)
print('员工数{0}'.format(empNum))
print('录入薪资',salarys)
print('平均薪资{0}'.format(salarySum/empNum))
[print(x) for x in range(1,5)]
[print(x*2) for x in range(1,5)]
[print(x*2) for x in range(1,20) if x%5==0]
cells = [(row,col) for row in range(1,10) for col in range(1,10)]
print(cells)
my_text = 'i love you i love s i love t'
char_count={c:my_text.count(c) for c in my_text}
print(char_count)
{x for x in range(1,100) if x%9==0}
(x for x in range(1,100)) |
import _thread
import time
# 为线程定义一个函数
def print_time(threadName,delay):
count = 0
while count < 3:
time.sleep(delay)
count += 1
print(threadName,time.ctime())
_thread.start_new_thread(print_time,('Thread-1',1))
_thread.start_new_thread(print_time,('Thread-2',2))
#time.sleep(5)
print('Main Finished') |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 08:44:58 2020
@author: sangliping
"""
import numpy as np
x = np.arange(8)
print(x) #[0 1 2 3 4 5 6 7]
print(np.append(x,8)) #是在副本上添加 [0 1 2 3 4 5 6 7 8]
print(np.append(x,[9,10])) #[ 0 1 2 3 4 5 6 7 9 10]
print(np.insert(x,1,8)) #[0 8 1 2 3 4 5 6 7]
x[3]=8
print(x) #[0 1 2 8 4 5 6 7]
"""
[[1 2 3]
[4 5 6]
[7 8 9]]
"""
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(x)
"""
[[1 2 4]
[4 5 6]
[7 8 9]]
"""
x[0,2] = 4 # 修改第一行 第三列
print(x)
"""
[[1 2 4]
[4 1 1]
[7 1 1]]
"""
x[1:,1:]=1 #行下标和列下表大于等于1 的都设置为1
print(x)
"""
[[1 2 4]
[4 1 2]
[7 1 2]]
"""
x[1:,1:]=[1,2]
print(x)
"""
[[1 2 4]
[4 1 2]
[7 3 4]]
"""
x[1:,1:]=[[1,2],[3,4]]
print(x) |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 23:14:02 2020
@author: sanglp
"""
print(60 in [70,60,50,80])
print('abc' in 'abcwqwe')
print([3] in [[3],[4],[5]])
print('3' in map(str,range(5)))
print(5 in range(5))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 15 14:06:22 2021
@author: sangliping
"""
r1 = {'name':'高小一','age':18,'salary':30000,'city':'北京'}
r2 = {'name':'高小二','age':19,'salary':10000,'city':'上海'}
r3 = {'name':'高小五','age':20,'salary':10000,'city':'深圳'}
tb = [r1,r2,r3]
print(tb)
# 获得第二行人的薪资
print(tb[1].get('salary'))
#打印表中所有的薪资
for i in range(len(tb)):
print(tb[i].get('salary'))
# 打印表的所有数据
for i in range(len(tb)):
print(tb[i].get('name'),tb[i].get('age'),tb[i].get('salary'),tb[i].get('city'))
|
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, or_, and_
from sqlalchemy.orm import sessionmaker
import requests
"""ACCESSING A TABLE"""
engine = create_engine('sqlite:///homework_sql.db', echo=True)
Base = declarative_base()
class Books(Base):
"""TURNING A DATABASE INTO AN OBJECT"""
__tablename__ = 'Books'
books_id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
author = Column(String)
publisher = Column(String)
description = Column(String, nullable=False)
edition = Column(Integer)
year = Column(Integer, nullable=False)
quantity = Column(Integer, nullable=False)
price = Column(Float)
def __repr__(self) -> str:
# return f'{self.books_id}, {self.title}, {self.author}, {self.publisher}, {self.description}, {self.edition}, {self.year}, {self.quantity}, {self.price}' # list
return f'({self.books_id}, {self.title}, {self.author}, {self.publisher}, {self.description}, {self.edition}, {self.year}, {self.quantity}, {self.price})' # tuple list
"""CREATING A TABLE"""
# Books.__table__.create(engine)
""" FILTERING A COLUMN """
def one(session):
""" 1. Title and Description of all books written by “J.K. Rowling” """
results = session.query(Books.title, Books.author).filter_by(
author='J.K. Rowling').all()
print(results)
def two(session):
""" 2. Title, Publisher and Edition of all books printed last decade (in the 2010s) """
results = session.query(Books.title, Books.publisher,
Books.edition, Books.year).filter(Books.year >= 2010).all()
print(results)
def three(session):
""" 3. All information about books that are not in stock """
results = session.query(Books).filter_by(quantity=0).all()
print(results)
def four(session):
""" 4. All books in stock without a price """
results = session.query(Books).filter(Books.price == 0).all()
print(results)
def five(session):
""" 5. All books containing the word “Cooking” or “Food”, in stock that were written by either “Gordon Ramsay” or “Jamie Oliver” """
results = session.query(Books.title, Books.author).filter(and_(Books.quantity != 0, or_(Books.title.like(
'%Cooking%'), Books.title.like('%Food%'), (Books.author == 'Gordon Ramsay'), (Books.author == 'Jamie Oliver')))).all()
print(results)
def six(session):
""" 6. All authors whose name starts with a vowel """
results = session.query(Books.author).filter(or_(
Books.author.like('a%'), Books.author.like('e%'), Books.author.like('i%'), Books.author.like('o%'), Books.author.like('u%'))).all()
print(results)
def seven(session):
""" 7. All book titles that have the letter “a” at least 3 times in. """
results = session.query(Books.title).filter(
Books.title.like('%a%a%a%')).all()
print(results)
def eight(session):
""" 8. Book titles composed of exactly 4 characters. """
results = session.query(Books.title).filter(
Books.title.like('____')).all()
print(results)
def nine(session):
""" 9. Books with the title same as the name of the author """
results = session.query(Books.title, Books.author).filter(
Books.title == Books.author).all()
print(results)
def ten(session):
""" 10. Books in stock, written by an author whose name does not end with the letter a, with a description that is either empty or has at least 5 characters """
results = session.query(Books).filter(Books.author.notlike(
'%a') & (Books.quantity > 0) & ((Books.description == "") | (Books.description.like('_____%')))).all() # can also use '&' as AND (and_) OPERATOR and '|' as OR (or_) OPERATOR
for result in results:
print(result)
def inserting_books(session):
requested_books = requests.get(
"https://www.googleapis.com/books/v1/volumes?q=+inauthor:rowling&printType=books")
books = requested_books.json()
book_id = int(session.query(Books.books_id).order_by(
Books.books_id.desc()).first()[0]) + 1
for each in books['items']:
"""INSERTING INTO TABLE"""
books = Books(books_id=book_id, title=each['volumeInfo']['title'], author=each['volumeInfo']['authors'][0], publisher="Penguin House", description=str(each['volumeInfo']['description']), edition=1,
year=int(each['volumeInfo']['publishedDate'][0:4]), quantity=10, price=(each['saleInfo'].get('retailPrice', {})).get('amount', 0.0))
book_id += 1
session.add(books)
session.commit()
if __name__ == "__main__":
"""STARTING A SESSION"""
Session = sessionmaker(bind=engine)
session = Session()
# one(session)
# two(session)
# three(session)
# four(session)
# five(session)
# six(session)
# seven(session)
# eight(session)
# nine(session)
# ten(session)
book_id = list(session.query(Books.books_id).order_by(
Books.books_id.desc()).limit(1)[0])
print(book_id)
|
'''
Moataz Khallaf A.K.A Hackerman
main
2/20/2019
'''
###___imports___###
import csv, time, random
###___vars/arrays/dicts___###
#useless and overcomplicated. I'm just too proud to take it out
DvM = { #Disney vs Marvel ....
"D" : 1,
"M" : 2
}
char = 1
###___Subs___###
###input
def menu():
x = int(input('''
yo yo yo... gang gang you tryna search for some heroes???
if you tryna do it fast and you are in a rush to get something done
please type 1 and press enter.
If you want to do it the slow and boring way please type 2 and press
enter.
>:(
'''))
return x
def getRawData(fileName):
import csv
tempLi = []
fil = open(fileName) #thanks for the code boss
text = csv.reader(fil)
for line in text:
tempLi.append(line)
var = tempLi.pop(0)
return tempLi, var
###proc
def binSearch(li, val): #this is just the code you gave us for bin search I'm pretty sure, slightly changed to fit 2D
start = 0 #Lowest index value to calc midpoint
end = len(li) - 1 #highest index value to calc midpoint
while start <= end:
midP = (start + end) // 2 #midpoint calc
if li[midP][0] == val: #found test
return li[midP]
elif val > li[midP][0]: #if value is greater than the midpoint, redefine the lowest index value to be one higher
#than the midpoint index value
start = midP + 1
else: #if value is less than the midpoint, redefine so it's 1 lower than midpoint index value
end = midP - 1
return False
def insertSort(li): #view insertion sort manual for in depth explanation, however; the gist is just that
for i in range(len(li)): #its the fastest sorting method by inserting the smallest num in the list at the front
for j in range(i, len(li)): #everytime as it goes through the list from the right. explanation in read.md
if li[j][0] < li[i][0]:
li.insert(i, li.pop(j))
return li
###output
def charDisplay(char):
print(", ".join(char))
###___main___###
###input
searchPick = menu()
if searchPick == 1: #inputs required to start the searches eg: name or id
super = input('''
ello mate, you ready to search and sort through some heroes????
Well boi oh boi do I have the program for you partner.
Just need you to enter the her's universe
eg. D or M (doesn't even need to be capital letters ;))
''')
ID = input('''
Now you need the ID
eg. 001
''')
super = super[0].upper()
superID = super + ID
if searchPick == 2:
print('''
wow... you must be crazy this will take a minute but at least you get to search by name.
''')
name = input('''
Please enter the character's name I guess...
''')
###proc
rawArr, headers = getRawData('comicBookCharData_mixed.csv')
if searchPick == 1:
startTime = time.perf_counter()
rawArr = insertSort(rawArr)
char = (binSearch(rawArr, superID))
endTime = time.perf_counter()
if searchPick == 2: #This uses linSearch to figure out if the name of the char is in the list
startTime = time.perf_counter()
for i in range(len(rawArr)): #I would split it into two separate lists beforehand to make it faster
if name == rawArr[i][1]: #but that would take too much effort when you can just use the way faster method
char = rawArr[i]
endTime = time.perf_counter()
else:
print(name, "is not in the list sorry chief")
###output
charDisplay(char)
print(endTime - startTime)
print("was the time it took to finish the search") |
import tensorflow as tf
# step 1: pre-process the data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("mnist", one_hot=True)
X_train = mnist.train.images
y_train = mnist.train.labels
X_test = mnist.test.images
y_test = mnist.test.labels
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
W = tf.Variable(tf.truncated_normal([784, 10], stddev=0.1))
b = tf.Variable(tf.truncated_normal([10], stddev=0.1))
# step 2: setup the model
yhat = tf.nn.softmax(tf.matmul(x, W) + b)
# step 3: define the loss function
loss = -tf.reduce_sum(y * tf.log(yhat))
# step 4: define the optimiser
train = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
# step 5: train the mode
is_correct = tf.equal(tf.argmax(y, 1), tf.argmax(yhat, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
batch_X, batch_y = mnist.train.next_batch(100)
train_data = {x: batch_X, y: batch_y}
sess.run(train, feed_dict=train_data)
print(i + 1, "Training Accuracy = ", sess.run(accuracy, feed_dict=train_data))
# step 6:evaulate the model
test_data = {x: X_test, y: y_test}
print("Testing accuracy =", sess.run(accuracy, feed_dict=test_data))
# step 7: save the model
|
## time clock ##
# In/Out Low Value In/Out High Value Rounded Value Hours
# :0 :7 :00 0.00
# :8 :22 :15 0.25
# :23 :37 :30 0.50
# :38 :53 :45 0.75
# :54 :59 :60 1.00
def main():
week=[]
workweek=["Monday","Tuesday","Wendsday","Thursday","Friday"]
#get all the hours for the week and put them in a list called week
print ("put time in military or with an a or p at end ex: 07:00 or 7:00a")
for day in workweek:
time_in=input(day+" in:")
if day=="Friday":
week.append(time_in)
continue
else:
time_out=input(day+" out:")
week.append(time_in)
week.append(time_out)
for x in week:
pass
print (week)
print(convert_to_mil_time("7:42a"))
def convert_to_mil_time(time_to_convert):
converted = time_to_convert.replace(":","")
length_of_time=len(converted)
#convert standard time to military time, add 1200 to any time from 1:00pm to 11:00pm
if converted[length_of_time-1:] =="a":
print("if a")
converted=converted.zfill(length_of_time+1)
converted=converted[:4]
elif int(converted[:2]) > 12:
converted=str(int(converted[:2])-2)+converted[2:]
converted = converted.zfill(4)
return converted
def round_to_15(num):
pass
main()
|
# This is my first program
print ("Hello World")
myName = input("What is your name?\n")
print ("Your name is " + myName)
print("Hello World again!")
|
"""
Sets are unordered collection os unique elementss
Meaning there can only be onr representative of the same object
Lets see some examples
"""
myset=set()
myset.add(1)
print (myset)
myset.add(2)
print (myset)
myset.add(2)
print (myset)
mylist=[1,1,1,1,1,3,3,3,3,3,4,4,4,34,3,3,3,3,22,2,2,2,2]
setk=set(mylist)
print (setk) |
print ('hello')
print (len('hello'))
mystring="hello World"
print (mystring[0])
print (mystring[5])
print (mystring[-5])
print (mystring[9])
print (mystring[2:])
print (mystring[:])
print (mystring[:3])
print (mystring[1:3])
print (mystring[::])
print (mystring[::2])
print (mystring[2:7:2])
print (mystring[::-1]) |
some_value="100"
print (some_value.isdigit())
def user_choice():
choice="WRONG"
while choice.isdigit()==False:
choice=input("Please enter a number(0-10): ")
if choice.isdigit() == False:
print ("Sorry that is not a digit")
print (int(choice))
user_choice()
result="WRONG"
accetable_values =[0,21,2,4]
print (result in accetable_values)
print (result not in accetable_values)
def user_choice1():
choice="WRONG"
acceptable_range=range(10)
within_range=False
while choice.isdigit()==False or within_range==False:
choice=input("Please enter a number(0-10): ")
if choice.isdigit() == False:
print ("Sorry that is not a digit11")
if choice.isdigit()==True:
if int(choice) in acceptable_range:
within_range=True
else:
within_range=False
print (int(choice))
user_choice1() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.