text stringlengths 37 1.41M |
|---|
#48 FAÇA UM PROGRAMA QUE CALCULE A SOMA ENTRE TODOS OS NUMEROS IMPARES QUE SAO MULTIPLOS DE TRES
#E QUE SE ENCONTRAM NO INTERVALO DE 1 ATE 500.
from time import sleep
cores = {
'limpa':'\033[m',
'sublinhado':'\033[4m',
'azul':'\033[4;34m'
}
#IMPAR = DIVIDE POR 2 E RESTA 1
#DIVISIVEL POR 3 E QUANDO SE DIVIDE POR TRES E FICA COM O RESTO = 0
print('VAMOS DESCOBRIR QUAIS SAO OS NUMEROS IMPARES DIVISIVEIS POR 3 NO INTERVALO SELECIONADO')
inter1 = int(input('Selecione o inicio do intervalo: '))
inter2 = int(input('Selecione o final do intervalo:'))
for c in range(inter1, inter2):
i = c % 2
d = c % 3
if i == 1:
if d == 0:
print('{}{}{}'.format(cores['azul'],c,cores['limpa']))
sleep(0.5)
print('Estes sao os numeros impares e multiplos de 3')
|
#54 CRIE UM PROGRAMA QUE LEIA O ANO NASCIMENTO DE SETE PESSOAS.
# NO FINAL MOSTRE QUANTAS PESSOAS AINDA NAO ATINGIRAM A MAIORIDADE E QUANTAS JA SAO MAIORES (21 ANOS).
from datetime import date
anoatual = date.today().year
print('-=-' * 20)
print('{:^50}'.format('VAMOS BRINCAR COM IDADES!'))
print('-=-' * 20)
totmenor = 0
totmaior = 0
for c in range(1, 8):
idade = int(input('EM QUE ANO A {}º PESSOA NASCEU: '.format(c)))
contagem = anoatual - idade
if contagem <= 21:
totmenor += 1
else:
totmaior += 1
print('O numero de pessoas com menos de 21 anos é {}'.format(totmenor))
print('O numero de pessoas com idade supediror a 21 é {}'.format(totmaior))
|
#34 FAÇA UM PROGRAMA QUE PERGUNTE O SALARIO DE UM FUNCIONARIO E CALCULE O VALOR DO AUMENTO
# (PARA SALARIOS SUPERIORES A R$ 1250,00 CALCULE 10% E PARA INFERIORES 15%)
print('Vamos ter uma serie de aumentos na empresa!')
print('Desta forma vamos precisar saber o seu salario para calcular seu aumento.')
salario = float(input('Qual é o seu salario? R$ '))
aumento = (salario * 10) / 100
aumento2 = (salario * 15)/ 100
if salario <= 1250:
print('O Seu salario atual é de R${:.2f} e com o aumento vai para R${:.2f}'.format(salario, aumento2 + salario))
else:
print('O seu salario atual é de R${:.2f} e com o aumento vai para R${:.2f}'.format(salario, aumento + salario))
|
#25 CRIE UM PROGRAMA QUE LEIA O NOME DE UMA PESSOA E RETORNE SE ELA TEM SILVA NO NOME
nome = str(input('Digite o seu nome: ')).strip()
print('O Seu nome tem Silva? {}'.format('SILVA' in nome.upper()))
|
# criar um conversor de temperaturas
temp = float(input('Informe a temperatura em ºC: '))
convertf = ((temp * 9) / 5) + 32
print('A temperatura atual é {}ºC e se convertermos em Fahrenheit sera {}ºF.'.format(temp, convertf))
#(oC x 9) / 5) + 32
|
#69 crie um programa que leia a idade e o sexo de varias pessoas,
# a cada pessoa cadastrada o programa devera perguntar se o
# usuario quer ou nao quer continuar, no final mostre:
#A Quantas pessoas tem mais de 18 anos.
#B Quantos homens foram cadastrados.
#C Quantas mulheres tem menos de 20 anos.
from time import sleep
from datetime import date
anoatual = date.today().year
CORES = {'LIMPA':'\033[m',
'AMARELO':'\033[4;33m',
'VERDE':'\033[4:32m',
'VERMELHO':'\033[4;31m'}
print("-*"* 20)
print('Bem vindo ao cadastros de clientes da loja do IGOR!')
cont = cont2 = cont3 = idade = contagem_ini =0
while True:
print("-*" * 20)
print('CADASTRE UMA PESSOA!')
nome = str(input('Nome: '))
idade = int(input('Idade: '))
sexo = ' '
while sexo not in 'MF':
sexo = str(input('Sexo: [M/F]: ')).strip().upper()[0]
print('Digite novamente')
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Deseja Continuar? [S/N]')).strip().upper()[0]
print('{}C A D A S T R A N D O . . .{}'.format(CORES['VERMELHO'], CORES['LIMPA']))
sleep(1)
contagem_ini += 1
if idade >= 18:
cont += 1
if sexo == 'M':
cont2 += 1
if sexo == 'F':
if idade <= 20:
cont3 += 1
#if sexo == 'F' and idade <= 20:
# cont2 +=1
if continuar == 'N':
print('{}E\nF I N A L I Z A N D O . . . {}'.format(CORES['VERMELHO'], CORES['LIMPA']))
sleep(1)
break
print(f'Tivemos um total de {cont} pessoas com mais de 18 anos!')
print(f'E ao todo tivemos {cont2} homens cadastrados e {cont3} mulheres com menos de 20 anos!')
|
#47 CRIE UM PROGRAMA QUE MSOTRE NA TELA TODOS OS NUMEROS PARES QUE ESTAO EM UM INTERVALO DE 1 E 50.
print('Vamos descobrir quais os numeros sao pares entre 0 e 50!')
for c in range(0,50):
p = c % 2
if p == 1:
print(c)
print('TEMOS A LISTAGEM DE NUMEROS PARES ACIMA!')
|
#57 FAÇA UM PROGRAMA QUE LEIA O SEXO DE UMA PESSOA (M OU F),CASO ESTEHA ERRADO PEÇA A DIGITAÇÃO NOVAMENTE.
sexo = str(input('Informe seu sexo[M/F]: ')).strip().upper()[0]
while sexo not in 'MmFf':
sexo = str(input('Dados invalidos, por favor informe seu sexo: ')).strip().upper()[0]
print('Sexo {} registrado com sucesso!'.format(sexo))
|
#9 faça um programa que leia o seu numero e fale a tabuada do mesmo
tab = int(input('Digite um numero e descubra a tabuada: '))
print('-' *12)
print('{} x {:2} = {}'.format(tab,1, tab * 1))
print('{} x {:2} = {}'.format(tab,2, tab * 2))
print('{} x {:2} = {}'.format(tab,3, tab * 3))
print('{} x {:2} = {}'.format(tab,4, tab * 4))
print('{} x {:2} = {}'.format(tab,5, tab * 5))
print('{} x {:2} = {}'.format(tab,6, tab * 6))
print('{} x {:2} = {}'.format(tab,7, tab * 7))
print('{} x {:2} = {}'.format(tab,8, tab * 8))
print('{} x {:2} = {}'.format(tab,9, tab * 9))
print('{} x {:2} = {}'.format(tab,10, tab * 10))
print('-' *12)
|
import random
def UpAndDown():
num1=random.randrange(0,100)
for i in range(0,20):
num2=int(input("Try and guess a number between 1~100 : "))
if num1<num2:
print "Down"
elif num1>num2:
print "Up"
elif num1==num2:
print "You are right!"
break
UpAndDown() |
"""
@author j.Kim
@since 160406
"""
import random
"""
This is for Up and down game at wk6
"""
def m35():
result = 0
for i in range(1,1000):
if i%3 == 0 or i%5==0:
result +=i
return result
def a():
year = float(input("year:"))
if(year%4==0)and(year%100!=0 or year%400==0):
print "Good! It is a leap year."
else:
print "It is not a leap year."
def UpAndDown():
num1=random.randrange(0,100)
for i in range(0,20):
num2=int(input("Try and guess a number between 1~100 : "))
if num1<num2:
print "Down"
elif num1>num2:
print "Up"
elif num1==num2:
print "You are right!"
break
def lab6():
print m35()
a()
UpAndDown()
def main():
lab6()
if __name__=="__main__":
main()
|
'''
Created on Sep 25, 2015
@author: gaurav
'''
from Smoothing.Perplexity import getUnigramPerplexity, getBigramPerplexity
def classifyBooksWithUnigram():
'''
Find the perplexities of the test books using the bigram model and classify
the book into the respective genres using these value
'''
#Calculate the perpexities of the test books using the unigram model
perplexity_test_books = getUnigramPerplexity()
print("\n Classifying books with the unigram model")
#The genre of a book is the model with which it produced the lowest perplexity
for book, perplexities in perplexity_test_books.iteritems():
genre = [key for key, value in perplexities.iteritems() if value == min(perplexities.values())][0]
print("Genre of {0} is {1}".format(book, genre))
def classifyBooksWithBigram():
'''
Find the perplexities of the test books using the bigram model and classify
the book into the respective genres using these value
'''
#Calculate the perpexities of the test books using the bigram model
perplexity_test_books = getBigramPerplexity()
print("\n Classifying books with the bigram model")
#The genre of a book is the model with which it produced the lowest perplexity
for book, perplexities in perplexity_test_books.iteritems():
genre = [key for key, value in perplexities.iteritems() if value == min(perplexities.values())][0]
print("Genre of {0} is {1}".format(book, genre))
if __name__ == '__main__':
classifyBooksWithUnigram()
classifyBooksWithBigram() |
# Given the participants' score sheet for your University Sports Day,
# you are required to find the runner-up score. You are given N scores.
# Store them in a list and find the score of the runner-up.
# The first line contains N. The second line contains an array A[] of integers each separated by a space.
# Print the runner-up score. i.e. second maximum number
if __name__ == '__main__':
def array_maker(arr):
for x in arr:
a1.append(x)
n = int(input())
arr = map(int, input().split())
a1 = []
array_maker(arr)
output = 0
max_val = max(a1)
arr_val = -100
for i in range(len(a1)):
if arr_val < a1[i] < max_val:
arr_val = a1[i]
output = a1[i]
print(output)
|
import math
import os
import random
import re
import sys
#
# Complete the 'stringAnagram' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. STRING_ARRAY dictionary
# 2. STRING_ARRAY query
#
def stringAnagram(dictionary, query):
# Write your code here
yoyo = []
for i in range(len(query)):
count = 0
for j in range(len(dictionary)):
if sorted(query[i]) == sorted(dictionary[j]):
count = count + 1
yoyo.append(count)
return yoyo
if __name__ == '__main__':
dictionary_count = int(input().strip())
dictionary = []
for _ in range(dictionary_count):
dictionary_item = input()
dictionary.append(dictionary_item)
query_count = int(input().strip())
query = []
for _ in range(query_count):
query_item = input()
query.append(query_item)
result = stringAnagram(dictionary, query)
print(result)
|
import string
import random
import time
import sqlite3
import hashlib, binascii
import os
#variables
chars = string.ascii_letters + string.digits
salt = string.punctuation
word = ''
hase = ''
#directory change
os.chdir('random-g') #change here
#sqilite database lol
conn = sqlite3.connect('ranwords.sqlite')
cur = conn.cursor()
cur.executescript('''
CREATE TABLE IF NOT EXISTS Words (
ran TEXT UNIQUE,
hash_id TEXT UNIQUE
);
''')
#inputs!!
select = input("use special characters ? Y OR N ")
num = input("how many strings ?")
length = input('how many letters ?')
#num-default
try:
num = int(num)
length = int(length)
except:
num = 64
length = 64
def words(num,selector,width,word):
# words creation
for i in range(0,num):
if (str.upper(selector) == 'Y' or selector == ''):
word = ''.join(random.choice(chars+salt) for i in range(0,width))
else:
word = ''.join(random.choice(chars) for i in range(0,width))
# encryptor sha256 (you can change the enpcrytion to md5, sha1 ...etc , just change the first paramter)
lol = hashlib.pbkdf2_hmac('sha256', word.encode('utf-8'), salt.encode('utf-8'), 1000000)
hase = binascii.hexlify(lol)
hase = str(hase)
# putting everything in a .txt
with open('words.txt', 'a+') as fale:
fale.write(word + ' ' + hase + '/n')
# database save and commit
cur.execute(''' INSERT INTO Words (ran, hash_id) VALUES (?, ?)''',(word,hase))
conn.commit()
return 0
#bodyprogram
while True:
words(num,select,length,word)
break
print(time.process_time())
|
# Week 2 - Files
# This script provides two simple examples of writing and reading files
# This block will open a file that already exists and write 500
# random numbers
file_loc = "C:\\DSA_OU\\boomerNumbers.txt"
import random
f = open(file_loc, 'w')
for count in range(500):
number = random.randint(1, 500)
f.write(str(number) + '\n')
f.close()
# Now lets read the file but 1st
# go back and save some typing
f = open(file_loc, 'r')
theSum = 0
for line in f:
line = line.strip()
number = int(line)
theSum += number
f.close()
print("The sum is", theSum)
|
import decimal
import visualiser as vis
import random
def hillclimber (self, results):
"""
This is the algorithm used for a hillclimber on a random configuration
"""
# initialize the values
total_distance = results[0]
connections = results[1]
distances_total = dict()
key = 1
# Hillclimber with 10000 iterations
for i in range(10000):
# Adds the distance to a dict with the number of run as its key
distances_total[key] = total_distance
key += 1
new_distance = None
# Find neighbouring solution
while new_distance == None:
# Pick random connection
connection1 = random.randint(0,149)
connection2 = random.randint(0,149)
# Check if not same connection
if connection1 != connection2:
# Check if not same battery
battery1 = connections[connection1]['battery']
battery2 = connections[connection2]['battery']
if battery1 != battery2:
# Check if switch would be possible:
max_output1 = connections[connection1]['max_output_house']
max_output2 = connections[connection2]['max_output_house']
new_cap1 = self.batteries[battery1].currentCapacity - max_output1 + max_output2
new_cap2 = self.batteries[battery2].currentCapacity - max_output2 + max_output1
if new_cap1 <= self.batteries[battery1].capacity and new_cap2 <= self.batteries[battery2].capacity:
# Calculate new distance
houseN1 = connections[connection1]['house']
houseN2 = connections[connection2]['house']
old_distance1 = connections[connection1]['distance']
old_distance2 = connections[connection2]['distance']
new_distance1 = self.distances[houseN1 - 1][battery2 - 1]
new_distance2 = self.distances[houseN2 - 1][battery1 - 1]
new_distance = total_distance - old_distance1 - old_distance2
new_distance = new_distance + new_distance1 + new_distance2
# Check if it is a better solution
delta = total_distance - new_distance
if delta >= 0 :
total_distance = new_distance
# Switch batteries
# Adapt current capacity batteries
self.batteries[battery1].currentCapacity -= max_output1
self.batteries[battery2].currentCapacity -= max_output2
self.batteries[battery1].currentCapacity += max_output2
self.batteries[battery2].currentCapacity += max_output1
#Adapt connections
connections[connection1]['battery'] = battery2
connections[connection1]['distance'] = new_distance1
connections[connection2]['battery'] = battery1
connections[connection2]['distance'] = new_distance2
# Saves the dict to a csv
algorithm = "hillclimber"
vis.dict_to_csv(distances_total, algorithm)
return [total_distance, connections]
|
class Battery(object):
"""
Representation of a battery in SmartGrid
"""
def __init__(self, id, name, capacity, price):
"""
Initiazes a Battery
"""
self.id = id
self.name = name
self.price = price
self.capacity = capacity
self.currentCapacity = 0
self.xpos = None
self.ypos = None
def __str__(self):
return f"Battery: {self.id}\nName: {self.name}, x_position: {self.xpos},y_position: {self.ypos}, capcity: {self.capacity}, price: {self.price}, current_capacity: {self.currentCapacity}"
|
"""
This module contains the `Hat` class.
The class takes a variable number of arguments that specify
the number of balls of each color that are in the hat. For example,
a class object could be created in any of these ways:
```python
hat1 = Hat(yellow=3, blue=2, green=6)
hat2 = Hat(red=5, orange=4)
hat3 = Hat(red=5, orange=4, black=1, blue=0, pink=2, striped=9)
```
"""
import copy
import random
class Hat:
"""Represents a hat that is filled with different colored balls.
Also it has a method that can draw a random ball from the hat.
"""
def __init__(self, **kwargs) -> None:
# for the __repr__ method
self.kwargs: dict[str, int] = kwargs
self.contents: list[str] = []
# loop through the keyword arguments
for color in kwargs.keys():
# the index is not needed so `_` is sufficient
# epeat the loop as often as the value in the keyword argument
# and append the key as much
for _ in range(kwargs[color]):
self.contents.append(color)
def draw(self, num_of_balls: int) -> list[str]:
"""Draw balls from the hat by random.
Args:
num_of_balls (int): A number of balls to draw from the hat.
Returns:
list[str]: Drawn balls.
"""
# safety or the pop() method
# so that pop can't pop from an empty list
# and raise an `IndexError`
if num_of_balls >= len(self.contents):
return self.contents
balls: list[str] = []
# repeat the loop for every ball wanted
for _ in range(num_of_balls):
# choose a random ball out of the list
# to get a int value `random.randint` is the perfect function
# ref:
# https://github.com/timgrossmann/InstaPy/issues/2208#issuecomment-396048533
choice: int = random.randint(0, abs(len(self.contents) - 1))
# `pop()` removes the item from the list so it can not be drawn again
balls.append(self.contents.pop(choice))
return balls
def __repr__(self) -> str:
"""For the `print` representation of the Hat.
Because I like to look at stuff...
Returns:
str: Str representation of the Hat class with the instance variables.
"""
return __class__.__qualname__ + f"({self.kwargs})"
# ref:
# https://medium.com/i-math/can-you-solve-this-intro-probability-problem-807c59543c32
# https://en.wikipedia.org/wiki/Urn_problem
def experiment(
hat: Hat,
expected_balls: dict[str, int],
num_balls_drawn: int,
num_experiments: int,
) -> float:
"""Calculate the probability of specific balls been drawn.
Args:
hat (Hat): An instantiation of a Hat object.
expected_balls (dict[str, int]): Representation of what balls should
be drawn and how many.
num_balls_drawn (int): A number of balls that are drawn per experiment.
num_experiments (int): How many experiments should be performed.
Returns:
float: Probability that the requested balls are drawn.
"""
# variable to count successful draws
num_successes: int = 0
for _ in range(num_experiments):
# grab a new, fresh copy of the hat everytime the loop is run through
# https://docs.python.org/3/library/copy.html
# using the `copy` method is not suffcient
# so we use the `deepcopy` method instead
hat_copy: Hat = copy.deepcopy(hat)
# draw balls
balls: list[str] = hat_copy.draw(num_balls_drawn)
# variable to indicate a successful draw
successful_draws: bool = True
for color in expected_balls.keys():
# ref:
# https://docs.python.org/3/library/stdtypes.html?highlight=count#str.count
if balls.count(color) < expected_balls[color]:
successful_draws = False
continue
if successful_draws:
num_successes += 1
return float(num_successes / num_experiments)
|
class Screen(object):
# __slots__ = ('width','height') 好像不能再定义
#用property装饰器来定义 setter函数,等同于建立一个获取属性的方法
@property
def width(self):
return self._width
@width.setter
def width(self,w):
self._width = w
@property
def height(self):
return self._height
@height.setter
def height(self,h):
self._height = h
@property
def resolution(self):
return 'assert s.resolution = %d * %d = %d' % (self._width,self._height,self._width*self._height)
#用__slots__来限制类的额外属性名称选项
# __slots__ = ('width','height') 好像不能和@property一起用
s = Screen()
s.width = 1024
s.height = 768
print(s.resolution) |
# n1 = int(input('Entre com um número: '))
# if n1 > 10:
# print('Este número é maior que 10!')
# elif n1 >= 1:
# print('Este número é menor que 10!')
# elif n1 < 1:
# print('Você digitou um número menor que 1!')
# else:
# print('Fim')
# for c in range(1, 1001, 98):
# print(c +1)
# print('FIM!')
# n = int(input('Digite um numero: '))
# for c in range(12, n+1):
# print(c)
# print('FIM!')
# i = int(input('Inicio: '))
# f = int(input('Fim: '))
# p = int(input('Passo: '))
# for c in range(i, f+1, p):
# print(c)
# print('FIM!')
# soma = 1000
# for c in range(0, 6):
# n = int(input('Digite um número: '))
# s = soma + n
# print('O somatório de todos os valores foi {}'.format(s))
def main():
print('Hello World')
|
#imports
import numpy as np
import pandas as pd
#using Numpy
a = np.array([1,2,3,4,5,6,7,8])
#this will print out elements of a that are > 4
print(a[a>4])
#print(a)
#should print out the array.
print(a.dtype)
items = [1,2,3,4,5]
def inc(x): return x+1
list(map(inc,items))
#print(items)
#using Pandas
#here, I will create a series
#You can define a new series starting with NumPy arrays or with an existing series .
series = pd.Series([12,-4,7,9,9,9,7], index=['a','b','c','d','e','f','g'])
#print(series.index)
#print(series.values)
series['b'] = -456
#print(series)
pdsimple=pd.Series(series)
#print(pdsimple)
series[series > 0]
#print(np.log(series))
#print(series.unique())
#print("-----")
#print(series.value_counts())
serd = pd.Series([1,0,2,1,2,3], index=['white','white','blue','green','green','yellow'])
testisin = serd.isin([0,3])
print(testisin)
print("---------------")
snull = pd.Series([6,5,4,np.NaN,14])
print(snull.isnull())
print("-------------")
print(snull.notnull())
# define a dataframe.
dfdata = {'color' : ['blue', 'green', 'yellow', 'red', 'white'],\
'object' : ['ball','pen','pencil','paper','mug'],\
'price' : [1.2,1.0,2.2,0.9,1.7]}
mydf = pd.DataFrame(dfdata)
print (mydf) |
# Given a binary tree, return the preorder traversal of its nodes' values.
#
# Example
# Example 1:
#
# Input:{1,2,3}
# Output:[1,2,3]
# Explanation:
# 1
# / \
# 2 3
# it will be serialized {1,2,3}
# Preorder traversal
# Example 2:
#
# Input:{1,#,2,3}
# Output:[1,2,3]
# Explanation:
# 1
# \
# 2
# /
# 3
# it will be serialized {1,#,2,3}
# Preorder traversal
# Challenge
# Can you do it without recursion?
#
# Notice
# The first data is the root node, followed by the value of the left and right son nodes, and "#" indicates that there is no child node.
# The number of nodes does not exceed 20.
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Preorder in ArrayList which contains node values.
"""
def preorderTraversal(self, root):
# write your code here
result = []
self.recursive(root, result)
return result
def recursive(self, root, result):
if root is None:
return
result.append(root.val)
self.recursive(root.left, result)
self.recursive(root.right, result) |
# Given a binary tree, return all root-to-leaf paths.
#
# Example
# Example 1:
#
# Input:{1,2,3,#,5}
# Output:["1->2->5","1->3"]
# Explanation:
# 1
# / \
# 2 3
# \
# 5
# Example 2:
#
# Input:{1,2}
# Output:["1->2"]
# Explanation:
# 1
# /
# 2
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code here
if root is None:
return []
current_path = ""
total_paths = []
self.traversal(root, total_paths, current_path)
return total_paths
def traversal(self, root, total_paths, current_path):
if root is None:
return
current_path = '->'.join([current_path, str(root.val)])
# current_path += (str(root.val) + "->")
if root.left is None and root.right is None:
current_path = current_path[2:]
total_paths.append(current_path)
return
self.traversal(root.left, total_paths, current_path[:])
self.traversal(root.right, total_paths, current_path[:])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 18:13:50 2020
@author: master
Walled In
A turtle bounces around the screen 5 times using the same function from
bounceTurt.py
Another turtle draws a line behind it, which turns into a wall.
isCollision to detect interactions.
HOW TO USE THIS CODE:
1. You can run it! And see how it works!
2. You can import it, and use the methods inside the library!
import boundary, turtle
turt = turtle.Turtle()
boundary.bounce(turt)
"""
import turtle, random, time
class Boundary:
def __init__(self):
self.lead = turtle.Turtle(shape='square')
self.lead.color('red')
self.segments=[]
# from bounceTurt.py
def bounce(self,turt):
'''bounces the turtle if it is past a boundary.
turt = Turtle object to be passed in
if the turtle does bounce, it returns a True, otherwise it returns a False'''
# get coordinates
x = turt.xcor()
y = turt.ycor()
heading = turt.heading() #the angle that it's facing
if x < -w/2: # left side boundary
AOI = 0 - 2*heading # calculate angle of incidence (AOI)
turt.seth(AOI)
turt.goto(-w/2+1,y)
return True
elif x > w/2: # right side boundary
AOI = 180 - 2*heading
turt.seth(AOI)
turt.goto(w/2-1,y)
return True
elif y < -h/2: # top side boundary
AOI = 270 - 2*heading
turt.goto(x,-h/2+1)
turt.seth(AOI)
return True
elif y > h/2: # bottom side boundary
AOI = 90 - 2*heading
turt.goto(x,h/2-1)
turt.seth(AOI)
return True
else:
return False
def addSegment(self,color='black', shape='square',width=4):
self.segments.append(turtle.Turtle(shape=shape))
self.segments[-1].color(color)
self.segments[-1].up()
self.segments[-1].goto(self.lead.pos())
def clear(self):
self.segments = []
def isCollision(self, turt,target,buffer=30):
'''Detects collision with an object or list of objects.
turt is the main object
target = the collision target (can be turtle or list of turtles)
buffer = area surrounding turt center that counts as a collision. Default value is 30 pixels.
Returns true or false statement if the two items have collided'''
target = target[:]
x = turt.xcor()
y = turt.ycor()
if type(target)==list:
# If it's a list, step through each value and check
if turt in target: #is the turtle we're colliding in the list?
idx = target.index(turt) # find out where it is
target.pop(idx) # remove it (just for the function)
for i in range(len(target)):
targX = target[i].xcor()
targY = target[i].ycor()
if round(targX)-buffer<=round(x)<=round(targX)+buffer and round(targY)-buffer<=round(y)<=round(targY)+buffer:
return True
else:
return False
elif type(target)== turtle.Turtle:
# If it's a turtle, get its position and checks for collision
targX = target[i].xcor()
targY = target[i].ycor()
if round(targX)-buffer<=round(x)<=round(targX)+buffer and round(targY)-buffer<=round(y)<=round(targY)+buffer:
return True
else:
return False
if __name__=='__main__':
turtle.tracer(0) # animations are turned off
panel = turtle.Screen()
w = 500
h = 500
panel.setup()
running = True
bounder = Boundary()
bouncy = turtle.Turtle(shape='circle')
def move(turt):
if random.randint(0,20)<5:
turt.left(90)
turt.forward(10)
else:
turt.forward(10)
def gameOver(bounder):
global running
hit = bounder.isCollision(bounder.lead,bounder.segments,buffer=5)
if hit:
bounder.segments[-1].color('blue')
for seg in bounder.segments:
seg.color('red')
panel.update()
running=False
bouncy.up()
bouncy.color('blue')
bouncy.seth(random.randint(0,360))
count = 0
while count<5:
bouncy.forward(10)
hit = bounder.bounce(bouncy) #ahaha I'm terrible at naming things.
if hit:
count += 1
time.sleep(0.03)
panel.update()
while running:
bounder.addSegment()
move(bounder.lead)
gameOver(bounder)
panel.update()
|
import pygame
class Button:
name = ""
# rect (top left corner), (width, height)
rect = pygame.Rect((10, 10), (50, 20))
color = (255, 255, 255)
def notify(self):
for i in self.listeners:
i.get_event(self.name)
def __init__(self, name, rect, color):
self.name = name
self.rect = pygame.Rect(rect)
self.color = color
self.listeners = []
def add_listener(self, listener):
self.listeners.append(listener)
def draw_button(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
|
#How are all leaves of a binary search tree printed?#
#Given a BST print all the leaf nodes from left to right (all the leaf nodes)
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def PrintLeafnodes(root: node) -> None:
if(not root):
return
if (not root.left and not root.right):
print(root.data, end = " ")
return
if root.left:
PrintLeafnodes(root.left)
if root.right:
PrintLeafnodes(root.right)
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(8)
root.right.left.left = Node(6)
root.right.left.right = Node(7)
root.right.right.left = Node(9)
root.right.right.right = Node(10)
PrintLeafnodes(root) |
import numpy as np
def cal_cost(theta,X,y):
'''
Calculates the cost function given X and Y.
x = Row of x's np.zeros((2,j))
y = Actual y's np.zeros((2,1))
where:
j is the no of features
'''
m = len(y)
predictions = X.dot(theta)
cost = (1/2*m)* np.sum(np.square(predictions=y))
return cost |
def is_even(numb):
# return False if numb%2 else True
return numb%2 == 0
def test_is_even():
assert is_even(2) == True
assert is_even(3) == False
assert is_even(80) == True
print('Even is correct')
test_is_even()
def string_lenght(string):
return len(string)
print(string_lenght('hellop'))
def last_letter(string):
return string[-1]
def test_last_letter():
assert last_letter('hello!') == '!'
assert last_letter('101') == '1'
print('Last_letter is correct')
test_last_letter()
race = {
'Usain' : 1,
'Me' : 2,
'Qazi' : 3
}
def choice_to_number(numb):
race = {1 : 'Usain', 2 : 'Me', 3 : 'Qazi'}
return race[numb]
def number_to_choice(name):
race = {'Usain' : 1, 'Me' : 2, 'Qazi' : 3}
return race[name]
print(choice_to_number(1))
print(number_to_choice('Me'))
|
def reverse(lst):
empty_list = list() # use this!
for item in lst:
empty_list.insert(0,item)
return empty_list
assert reverse(list([1,None,14,"two"])) == ["two",14,None,1]
|
import pandas as pd
### ways of reading different types of files
df = pd.read_csv('../../pandas-master/pokemon_data.csv')
df_xlsx = pd.read_excel('../../pandas-master/pokemon_data.xlsx')
df_txt = pd.read_csv('../../pandas-master/pokemon_data.txt', delimiter='\t')
### show only 5 rows
# print(df_txt.head(3))
### read headers
# print(df.columns)
### read each column
# print(df['Name'][0:5])
# print(df.Name[0:5])
# print(df[['Name', 'HP']])
### read each row
# print(df.iloc[0:5])
# for index, row in df.iterrows(): ## helps reformat view
# print(index, row['Name'])
# print(index, row)
#print(df.loc[df['Type 1']== 'Fire']) ## with some conditions
### some stat.info abot data
# print(df.describe())
### sorting
# print(df.sort_values(['Name', 'HP'], ascending=False))
# print(df.sort_values(['Name', 'HP'], ascending=[0,1])) ##the same
### read a srecific location (R,C)
# print(df.iloc[2,1]) #[row, column]
### making changes to the data
# df['Total'] = df['HP'] + df['Attack'] + df['Defense'] + df['Sp. Atk'] + df['Sp. Def'] + df['Speed']
# df = df.drop(columns=['Total']) ## deleting the column
# df['Total'] = df.iloc[:, 4:10].sum(axis=1) ## another way of sum
# cols = list(df.columns.values) ## variable with list of columns to shorter inserting line
# df = df[cols[0:4] + [cols[-1]] + cols[4:12]] ## inserting column in the "middle"
### saving to files
# df.to_csv('modified.csv', index=False) ## save to csv
# df.to_excel('modified.xlsx', index=False) ## save to excel
# df.to_csv('modified.txt', index=False, sep='\t') ## save to txt
### filtering data
# df = df.loc[(df['Type 1'] == 'Grass') & (df['Type 2'] == 'Poison')] ## cond1 and cond2
# new_df = df.loc[(df['Type 1'] == 'Grass') | (df['Type 2'] == 'Poison')] ## cond1 OR cond2
# new_df = new_df.reset_index() ## reseting old index with new quatity of data. it is adding new column with old index
# new_df = new_df.reset_index(drop=True) ## reseting old index without column 'old index'
# new_df = df.loc[df['Name'].str.contains('Mega')] ## filter all data that contains smth
# new_df = df.loc[~df['Name'].str.contains('Mega')] ## all data that doen't contain smth
import re ## importing regular expressions
df.loc[df['Type 1'].str.contains('fire|grass', flags=re.I, regex=True)] ## contains cond1 or cond2, flags for ignoring the register
# print(df.loc[df['Name'].str.contains('^pi[a-z]*', flags=re.I, regex=True)]) ## filtering data that starts with 'pi'. ^ means that it starts with smth, [a-z]* means that all letters contain
df.loc[df['Type 1'] == 'Fire', 'Type 1'] = 'Flamer' ## change smth on smth else
df.loc[df['Type 1'] == 'Flamer', 'Type 1'] = 'Fire' ## change it back
df.loc[df['Type 1'] == 'Grass', 'Speed'] = 500 ## also we can change another field based on this filter
df = pd.read_csv('modified.csv')
### conditional changes
# df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = 'TEST' ## change both columns with one value
# df.loc[df['Total'] > 500, ['Generation', 'Legendary']] = ['TEST', 'TEST 2'] ## change both columns with diff values
### aggregate statistics
# df = df.groupby(['Type 1']).mean() ## group by type 1 with average values
# df = df.groupby(['Type 1']).mean().sort_values('HP', ascending=True) ## sort the values
# df = df.groupby(['Type 1']).sum() ## group by type 1 with sum of values
# df = df.groupby(['Type 1']).count() ## counts by type 1
# df['count'] = 1
# df.groupby(['Type 1', 'Type 2']).count()['count'] ## shows only one column with count and sort by type 1 and then by type 2
## working with large amount of data
# for df in pd.read_csv('modified.csv', chunksize=5): ## spliting on chunks with 5 rows
# print('Chunks')
# print(df)
new_df = pd.DataFrame(columns=df.columns)
for df in pd.read_csv('modified.csv', chunksize=5):
results = df.groupby(['Type 1']).count()
new_df = pd.concat([new_df, results]) ## count data by chunks
print(new_df)
# print(df)
# print(df)
# print(new_df)
|
def zero(oper=''): return 0 if oper=='' else operation(0, oper)
def one(oper=''): return 1 if oper=='' else operation(1, oper)
def two(oper=''): return 2 if oper=='' else operation(2, oper)
def three(oper=''): return 3 if oper=='' else operation(3, oper)
def four(oper=''): return 4 if oper=='' else operation(4, oper)
def five(oper=''): return 5 if oper=='' else operation(5, oper)
def six(oper=''): return 6 if oper=='' else operation(6, oper)
def seven(oper=''): return 7 if oper=='' else operation(7, oper)
def eight(oper=''): return 8 if oper=='' else operation(8, oper)
def nine(oper=''): return 9 if oper=='' else operation(9, oper)
def operation(numb, oper):
if oper[0]=='*':
return numb*int(oper[1])
elif oper[0]=='+':
return numb+int(oper[1])
elif oper[0]=='-':
return numb-int(oper[1])
elif oper[0]=='/':
return int(numb/int(oper[1]))
def plus(numb): return '+'+str(numb)
def minus(numb): return '-'+str(numb)
def times(numb): return '*'+str(numb)
def divided_by(numb): return '/'+str(numb)
assert seven(times(five())) == 35
## Not mine solution
# def zero(f = None): return 0 if not f else f(0)
# def one(f = None): return 1 if not f else f(1)
# def two(f = None): return 2 if not f else f(2)
# def three(f = None): return 3 if not f else f(3)
# def four(f = None): return 4 if not f else f(4)
# def five(f = None): return 5 if not f else f(5)
# def six(f = None): return 6 if not f else f(6)
# def seven(f = None): return 7 if not f else f(7)
# def eight(f = None): return 8 if not f else f(8)
# def nine(f = None): return 9 if not f else f(9)
# def plus(y): return lambda x: x+y
# def minus(y): return lambda x: x-y
# def times(y): return lambda x: x*y
# def divided_by(y): return lambda x: x/y
|
# solution("camelCasing") == "camel Casing"
def solution(s):
#transform to array
sol = list(s)
length = len(sol)
i = 0
#finding the breaking point
while i <= length-1:
if sol[i].isupper() and sol[i-1] != ' ':
break_point = i
sol.insert(break_point, ' ')
length = len(sol)
i+=2
else:
i+=1
#transform to str
s = ''.join(sol)
print(s)
solution('camelCasing')
solution("helloWorld")
solution("breakCamelCase")
solution('make Eye Old GiveSee')
solution('dayVerbsRightHaveSee')
# Not mine solution
# def solution(s):
# newStr = ""
# for letter in s:
# if letter.isupper():
# newStr += " "
# newStr += letter
# return newStr |
# matplotlib是绘图库
# 功能:生产可发布的、可视化内容,如折线图、直方图、散点图
import matplotlib.pyplot as plt
import numpy as np
# 在-10和10之间生成一个数列,共100个数
x = np.linspace(-10,10,100)
# 用正弦函数创建第二个数组
y = np.sin(x)
# plot函数绘制一个数组关于另一个数组的折线图
plt.plot(x,y,marker="x")
plt.show() |
# NumPy是Python科学计算的基础包
# 功能:多维数组、高等数学函数(线性代数、傅里叶变换)、伪随机数生成器
# NumPy核心功能:ndarray类,即多维数组。(多维数组的所有元素必须是同一类型)
# scikit-learn用到的所有数据必须转成NumPy数组。
import numpy as np
x = np.array([[1,2,3],[4,5,6]])
print("x:\n{}".format(x))
|
#Counting Sort
def counting_sort(A):
m = max(A)
count = [0] * (m+1)
for x in A:
count[x] += 1
A=[]
for i in range(m+1):
A += [i] * count[i]
return A
input_str = input('Enter "non negetive"!!! numbers (Use Comma to separate the numbers)\nExample: 9,5,6,44,50\nNumbers: ')
input_str = input_str.replace(' ', '')
try:
A = list(map(int, input_str.split(',')))
print(counting_sort(A))
except:
print("input is not valid")
|
class BankAccount:
Allinstances = []
def __init__ (self, balance = 0.0, int_rate = 0.01):
self.balance = balance
self.int_rate = int_rate
BankAccount.Allinstances.append(self)
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
if self.balance > amount:
self.balance -= amount
else:
print(f"Your balance is not sufficient to withdraw ${amount}.")
return self
def display_account_info(self):
print(f"Balace: ${self.balance}.")
return self
def yield_interest(self):
interest = self.balance * self.int_rate
self.balance = self.balance + interest
print(f"Interest: ${interest}.")
return self
@classmethod
def instances(cls):
for instance in cls.Allinstances:
instance.display_account_info()
|
import numpy as np
from random import shuffle
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
return np.exp(x) / np.sum(np.exp(x) , axis = -1 , keepdims = True)
def get_one_hot(targets, nb_classes):
res = np.eye(nb_classes)[np.array(targets).reshape(-1)]
return res.reshape(list(targets.shape)+[nb_classes])
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
return softmax_loss_vectorized(W, X, y, reg)
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
N, D = X.shape
num_classes = W.shape[1]
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
scores = X.dot(W)
scores = softmax(scores)
# regularization loss
reg_loss = reg * np.sum(np.multiply(W, W))
# cross-entropy-loss
one_hot = get_one_hot(y, num_classes)
# maximum loss = (-1/N) * sum over N samples ([0000 1 000] * [1/N 1/N ......])
# which will be -1 * np.log(0.1)
loss = - 1/N * np.sum( one_hot * np.log(scores) )
loss += reg_loss
# gradient
dldz2 = scores - one_hot
dz2dw2 = X
dW = 1/N * np.dot(dz2dw2.T, dldz2) + 2 * reg * W
return loss, dW
|
#!/usr/bin/env python3
from sklearn import tree
from sklearn.datasets import load_iris
from utils import exportDecisionTree
def main():
# 1. Minimal dataset
# Create a tree classifier with a very simple dataset. A classifier stores
# the results into different classes. In this example, the data is an array
# of shape (size, weight). And the class are "man" and "women".
classifier = createDecisionTreeClassifier(
[[173, 75], [165, 55], [180, 93]],
["man", "woman", "man"],
)
exportDecisionTree("simple.pdf", classifier, ["man", "woman"], ["size", "weight"])
# Create a sample to use as an example
sample = [[179, 80]]
# Try to predict if the couple (179, 80) is a "man" or a "woman"
print(
f"Simple dataset - Values: {sample}, decision: {classifier.predict(sample)}, probabilities: {classifier.predict_proba(sample)}"
)
# 2. Iris dataset
# Load the Iris dataset. This dataset is way more bigger than the previous
# one.
iris_dataset = load_iris()
# Create a tree classifier with the Iris dataset
classifier = createDecisionTreeClassifier(
iris_dataset.data,
iris_dataset.target,
)
exportDecisionTree(
"iris.pdf", classifier, iris_dataset.target_names, iris_dataset.feature_names
)
# Use the first item of the dataset as an example for predictions
sample = iris_dataset.data[[55]]
print(
f"Iris dataset - Target names: {iris_dataset.target_names}, sample target: {iris_dataset.target[[55]]}"
)
print(
f"Iris dataset - Values: {sample}, decision: {classifier.predict(sample)}, probabilities: {classifier.predict_proba(sample)}"
)
# 3. Tweak the DecisionTreeClassifier
# Create a tree classifier with the Iris dataset and custom max_depth parameter
classifier = createDecisionTreeClassifier(
iris_dataset.data,
iris_dataset.target,
max_depth=2,
)
exportDecisionTree(
"iris-custom-max-depth.pdf",
classifier,
iris_dataset.target_names,
iris_dataset.feature_names,
)
print(
f"Iris dataset (max_depth) - Values: {sample}, decision: {classifier.predict(sample)}, probabilities: {classifier.predict_proba(sample)}"
)
# Create a tree classifier with the Iris dataset and custom min_samples_leaf parameter
classifier = createDecisionTreeClassifier(
iris_dataset.data,
iris_dataset.target,
min_samples_leaf=5,
)
exportDecisionTree(
"iris-custom-min-samples-leaf.pdf",
classifier,
iris_dataset.target_names,
iris_dataset.feature_names,
)
print(
f"Iris dataset (min_samples_leaf=5) - Values: {sample}, decision: {classifier.predict(sample)}, probabilities: {classifier.predict_proba(sample)}"
)
# Build a decision tree classifier from the training set (X, y)
# X: The training input samples of shape (n_samples, n_features).
# y: The target values (class labels) as integers or strings.
# max_depth: The maximum depth of the tree.
# min_samples_leaf: The minimum number of samples required to be at a leaf node.
def createDecisionTreeClassifier(data, target, max_depth=None, min_samples_leaf=1):
classifier = tree.DecisionTreeClassifier(
max_depth=max_depth,
min_samples_leaf=min_samples_leaf,
)
return classifier.fit(data, target)
if __name__ == "__main__":
main()
|
def compare(x,y):
if x > y:
return 1
if x < y:
return -1
else:
return 0
def is_between(x,y,z):
if x <= y and y <=z:
print 'ok'
else:
print 'not ok'
|
def histogram(word):
d=dict()
for letter in word:
d[letter]=d.get(letter,0)+1
return d
|
# function to check whether the given two strings are anagrams
def is_anagram(word1,word2):
if len(word1)!=len(word2): # if words are of different length return false
return False
else: # if words are of same length convert the string into lists and sort them in ascending order
word_a=list(word1)
word_a.sort()
word_b=list(word2)
word_b.sort()
if word_a == word_b: # if lists are equal return true....else false
return True
else:
return False
|
from point1 import *
import math
import copy
def distance_between_points(p1,p2):
'''To calculate the distance between 2 points'''
distance = math.sqrt(((p1.x - p2.x)**2) + ((p1.y - p2.y)**2))
return distance
def move_rectangle(rect,dx,dy):
'''To move the rectangle by its corner'''
new_rect = copy.deepcopy(rect)
new_rect.width = rect.width
new_rect.height = rect.height
new_rect.corner = Point()
new_rect.corner.x = rect.corner.x + dx
new_rect.corner.y = rect.corner.y + dy
print_point(new_rect.corner)
return new_rect
|
# Program for scanning a wordlist and returning the most frequently used lettersin descending order
import operator
# Defining a function for accepting a word & returning a list of tuples with letters used and its frequency
def most_frequent(wrd):
d={}
for letter in wrd:
d[letter] = d.get(letter,0)+1
letter_freq = d.items()
letter_freq.sort(key = operator.itemgetter(1),reverse=True)
return letter_freq
# Opening the file containing the word list
fin = open("/home/dheeraj/repos/think-python/words.txt")
total_freq = {}
# Loop for scanning each word in the file and building a histogram
for line in fin:
word = line.strip()
freq_list = most_frequent(word)
freq_dict = dict(freq_list)
for i in freq_dict:
total_freq[i]=total_freq.get(i,0)+freq_dict[i]
# Sorting the histogram in descending order
letter_list = total_freq.items()
letter_list.sort(key=operator.itemgetter(1),reverse = True)
# Loop for printing the histogram
print 'letter ---- frequency'
for i in letter_list:
print ' ',i[0],' ',i[1]
|
# Binary search
# Creating the sorted word list
wordlist =sorted([x.strip() for x in open('/home/dheeraj/repos/think-python/words.txt')])
# Function for binary search
def binary(word):
# first = 1st index in the list..initially 0
first = 0
# last = last index in the list..initially len(list)
last = len(wordlist)
# loop for changing first and last index
while first < last:
middle = (first + last)/2
midval = wordlist[middle]
# first index changed to middle index if word is in the second half of list
if midval < word:
first = middle + 1
# last index changed to middle index if word is in the first half of list
elif midval > word:
last = middle
# if first index == last index return the index
else:
return middle
# if not in the list...
return "not in the list"
print(binary('hello'))
print(binary('world'))
print(binary('fsdmfbsnm'))
|
def inverse_dict(d):
inverse=dict()
for key in d:
value=d[key]
inverse.setdefault(value,[]).append(key)
return inverse
print(inverse_dict({'a':1,'b':1,'c':2}))
|
# https://www.codewars.com/kata/530e15517bc88ac656000716
def rot13(message):
output = ''
for c in message:
if not c.isalpha():
output += c
continue
# Nth alphabet (lowercase)
alphabet_n = ord(c.lower()) - ord('a')
# == 26
alphabet_count = ord('z') - ord('a') + 1
# add rot
rot = (alphabet_n + 13) % alphabet_count
# get rotted alphabet
char = chr(rot + ord('a'))
# apply original letter case
output += char if c.islower() else char.upper()
return output
print(rot13("test") == "grfg")
print(rot13("Test") == "Grfg")
|
def datacollect(mathmode):
modus=mathmode
value1 = input("Please enter the first number of your {} ".format(modus))
value2 = input("Please enter the second number of the calculation ")
return value1, value2
def addition(value1,value2):
added = int(value1) + int(value2)
return added
def subtraction(value1,value2):
subtracted = int(value1)-int(value2)
return subtracted
def multiplication(value1,value2):
multiplied = int(value1)*int(value2)
return multiplied
def division(value1,value2):
divided = int(value1)/int(value2)
return divided
def printresult(value):
print("The result of the calculation is {}".format(value))
print("Welcomme to the basic calculator,")
counting = True
while counting == True:
modus=input("Please input mode of calculation, pick between 'add'(+), 'sub'(-), 'mult'(*), or 'div'(/). To quit input quit ")
if modus == "add":
firstvalue,secondvalue = datacollect("addition")
result=addition(firstvalue,secondvalue)
printresult(result)
elif modus == "sub":
firstvalue,secondvalue = datacollect("subtraction")
result=subtraction(firstvalue,secondvalue)
printresult(result)
elif modus == "mult":
firstvalue,secondvalue = datacollect("multiplication")
result=multiplication(firstvalue,secondvalue)
printresult(result)
elif modus == "div":
firstvalue,secondvalue = datacollect("division")
result=division(firstvalue,secondvalue)
printresult(result)
elif modus == "quit":
counting = False
else:
print("You've entered the mode incorrectly, please try again")
print("Thank you for using basic calculator by Hanna Johansson")
quit() |
import turtle, random
turtle.bgcolor("black")
benny = turtle.Turtle()
colors = ["red","green","blue","orange","purple","pink","yellow","purple","blue"] #List of colors
benny.width(1)
benny.hideturtle()
for i in range(250):
color = random.choice(colors)
benny.circle(25+i*2.5)
benny.forward(-i)
benny.left(10)
benny.width(1+i/10)
benny.color(color)
|
def test_recipe(food_1, food_2):
foodcombo=("{} with {}".format(food_1,food_2))
return foodcombo
food1=input("Please input a food ")
food2=input("please input a side ")
dishname=test_recipe(food1,food2)
print("Today the restuarant is serving {}.".format(dishname)) |
list = []
def countbetween(start,end,step):
for i in range(start,(end+step),step):
list.append(i)
return list
print("This program will help you count!")
num1=int(input("Where should we start? "))
numn=int(input("When should we stop? "))
print("Ok!")
if num1<numn:
counting=countbetween(num1,numn,1)
elif num1>numn:
counting=countbetween(num1,numn,-1)
else:
counting=[num1]
print(*counting, sep=', ') |
#This is most basic and simplesr ,use of matplotlib
#W import matplotlib as my_plt for easy reference
from matplotlib import pyplot as my_plt
#Here we are manually feeding data for x and Y a
#my_plt.plot([1,2,3,4,5],[1,3,5,7,9],)
#Here we add lables (that tell us what are values of X and Y ) to x and y axis
my_plt.xlabel('X - Axis')
my_plt.ylabel('Y - Axis')
#Here we add the title of the graph (Tells us what to do)
my_plt.title('Title of Graph')
#Here we plot a bar graph
my_plt.bar([1,2,3,4,5,6,7,8,9],[1,3,5,7,9,7,5,3,1])
my_plt.show()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 16 17:05:37 2017
@author: KingDash
"""
Error="N"
try:
x=int(input('Enter an integer:'))
except ValueError:
print('invalid entry')
Error="Y"
except NameError:
print('undefined entry')
Error="Y"
if Error=="N":
if x<0:
y=x
print(y, 'is a negetive number and converted to zero',x)
elif x==0:
print(x, 'is zero')
elif x==1:
print(x, 'is single')
else:
print(x, 'greater than zero and one') |
# Code To convert Hinglish text to Hindi.
consonant=['b','c','C','d','D','f','g','h','j','k',\
'l','m','n','N','p','q','r','R','s','S','t','T','v','w','x','y','z']
vowels=['a', 'e', 'i', 'o', 'u']
def dumb_seg(g):
listee=[]
pntr=0
for x in g:
if(x in consonant or pntr==0):
pntr+=1;
listee.append(x)
# if(pntr>0 and x=='i' and listee[pntr-1][0]=='R'):
# pntr+=1
# listee[pntr-1]= listee[pntr-1]+x
elif(x in vowels and x==listee[pntr-1][-1] and len(listee[pntr-1])==3 ):
pntr+=1;
listee.append(x)
elif(x in vowels and x!=listee[pntr-1][-1] and (listee[pntr-1][-1] in vowels) ):
pntr+=1;
listee.append(x)
else:
#print(listee[pntr-1])
if(x==listee[pntr-1][-1] and x in vowels) :
listee[pntr-1]= listee[pntr-1]+x
if(listee[pntr-1][-1] in consonant and x in vowels):
listee[pntr-1]= listee[pntr-1]+x
return listee
#join t,ha to tha :s,h to sha etc
def dumb_joiner_ha(listee):
pntr=0
jo_list=[]
tempo_list=['k','g','c','C','j','t','T','d','D','p','b','s','S']
for i in range(0,len(listee)):
if(listee[i] in tempo_list and i!=len(listee)-1):
if(listee[i+1][0]=="h"):
jo_list.append(listee[i]+listee[i+1])
pntr+=1
listee[i+1]="zorran"
else:
jo_list.append(listee[i])
pntr+=1
else:
if(listee[i]=="zorran"):
a=0
else:
jo_list.append(listee[i])
pntr+=1
return jo_list
#------------------------------------------------------
def splitts(listee):
splitter=[]
for i in range(0,len(listee)):
if(i==0):
if(listee[i][0] in vowels):
splitter.append([listee[i]])
else:
tempora=[]
for j in range(0,len(listee[0])):
if(listee[i][j] in vowels):
tempora.append(listee[i][0:j])
tempora.append(listee[i][j:])
break
if(tempora!=[]):
splitter.append(tempora)
if(tempora==[]):
splitter.append([listee[0]])
if(i>0):
tempora=[]
for j in range(0,len(listee[i])):
if(listee[i][j] not in consonant):
if(listee[i][0:j]!=''):
tempora.append(listee[i][0:j])
tempora.append(listee[i][j:])
break
#print tempora
if(tempora==[]):
tempora.append(listee[i])
splitter.append(tempora)
return splitter
h_dict = { \
"a" :u'\u0905',
"aa" :u'\u0906',
"i" :u'\u0907',
"ii" :u'\u0908',
"u" :u'\u0909',
"uu" :u'\u090a',
####
"Ri" :u'\u090b',
####
"e" :u'\u090f',
"ee" :u'\u0910',
"o" :u'\u0913',
"oo" :u'\u0914',
#
"ka" :u'\u0915',
"kha" :u'\u0916',
"ga" :u'\u0917',
"gha" :u'\u0918',
#
"cha" :u'\u091a',
"Cha" :u'\u091b',
"ja" :u'\u091c',
"jha" :u'\u091d',
#
"Ta" :u'\u091f',
"Tha" :u'\u0920',
"Da" :u'\u0921',
"Dha" :u'\u0922',
"Na" :u'\u0923',
#
"ta" :u'\u0924',
"tha" :u'\u0925',
"da" :u'\u0926',
"dha" :u'\u0927',
"na" :u'\u0928',
#
"pa" :u'\u092a',
"fa" :u'\u092b',
"ba" :u'\u092c',
"bha" :u'\u092d',
"ma" :u'\u092e',
#
"ya" :u'\u092f',
"ra" :u'\u0930',
"la" :u'\u0932',
"va" :u'\u0935',
#
"sha" :u'\u0936',
"Sha" :u'\u0937',
"sa" :u'\u0938',
"ha" :u'\u0939',
#
"hlnt" :u'\u094d',
#
"za" :u'\u095b',
#
"aX" :u'\u093e',
"aaX" :u'\u093e',
"iX" :u'\u093f',
"iiX" :u'\u0940',
"uX" :u'\u0941',
"uuX" :u'\u0942',
"eX" :u'\u0947',
"eeX" :u'\u0948',
"oX" :u'\u094b',
"ooX" :u'\u094c',
#####
"rrX" :u'\u0943'
}
vowels = [ 'a', 'aa',\
'i', 'ii','u', 'uu',\
'e', 'ee','o', 'oo']
def hindi(inp):
holder=dumb_seg(inp)
tempo= dumb_joiner_ha(holder)
l= splitts(tempo)
s= ""
i=0
try:
while i<len(l):
if len(l[i])==1:
if l[i][0] in vowels:
s += h_dict[l[i][0]]
if(l[i][0] not in vowels):
if(i<len(l)-1 and l[i+1][0]=='r' and l[i]!=['r']):
if(len(l[i+1])==2):#kram
s += h_dict[l[i][0]+"a"]+h_dict["rrX"]
if(l[i+1][1]!='a'):
s+=h_dict[l[i+1][1]+"X"]
i+=2
continue
if(len(l[i+1])==1):
s += h_dict[l[i][0]+"a"]+h_dict["hlnt"]
else:
#print ('dido')
s += h_dict[l[i][0]+"a"]+h_dict["hlnt"]
# ----------------------
elif len(l[i])==2:
if(l[i][0]=='R'):
s += h_dict["Ri"]
elif l[i][1] == "a":
s += h_dict[l[i][0]+"a"]
else:
s += h_dict[l[i][0]+"a"] + h_dict[l[i][1]+"X"]
i+=1
return s
except:
return (None)
|
raw_input("Enter a word:")
original = raw_input()
if len(original) > 0 and original.isalpha(): #isalpha() checks if the string contains non-letter characters
word = original.lower()
first = word[0]
print original
else:
print "empty"
hobbies = []
for i in range(3):
hobby = str(raw_input("Your hobby: "))
hobbies.append(hobby)
|
import sys
def binary_search(target, low, high):
if target > high:
print "too big dude!"
elif target < low:
print "too small dude! ;p"
else:
if low > high:
return False
else:
mid = (low+high)//2
if target == mid:
return True
elif target < mid:
return binary_search(target, low, mid-1)
else:
return binary_search(target, mid+1, high)
def main():
try:
print "Please enter a low value: "
lower = int(input())
print "Please enter a high value: "
higher = int(input())
print "Please enter a number you would like to search..."
user_input = int(input())
print binary_search(user_input, lower, higher)
except ValueError:
print "Please enter a positive number."
except NameError:
print "Please enter a valid number, not any other type!"
except SyntaxError:
print "Please enter a valid number!!!"
except UnboundLocalError:
print "Low value and High value not entered correctly!"
except KeyboardInterrupt:
sys.exit()
if __name__=='__main__':
main()
|
def find_unique_character(string: str) -> str:
chars = string.lower()
size = len(chars)
for target_index in range(size):
current = chars[target_index]
if chars.index(current) == chars.rindex(current):
return chars[target_index]
return '{} has no unique character'.format(chars)
result = find_unique_character('PopularStar')
print(result)
|
import sys
#Создайте функцию, принимающую на вход имя, возраст и город проживания человека. Функция должна возвращать строку вида «Василий, 21 год(а), проживает в городе Москва»************************
def person_info(name, age, city):
print('{}, {} years old, living in {}'.format(name, age, city))
return '{}, {} years old, living in {}'.format(name, age, city)
person_info('Ivan', 21, 'LA')
# person_info(sys.argv[1], sys.argv[2], sys.argv[3])
#Создайте функцию, принимающую на вход 3 числа и возвращающую наибольшее из них.
def max_of_three(*args):
print(max(args))
# max_of_three(sys.argv[1], sys.argv[2], sys.argv[3])
max_of_three(2, 10, 4)
# Давайте опишем пару сущностей player и enemy через словарь, который будет иметь ключи и значения:
# name - строка полученная от пользователя,
# health = 100,
# damage = 50.
### Поэкспериментируйте с значениями урона и жизней по желанию.
### Теперь надо создать функцию attack(person1, person2). Примечание: имена аргументов можете указать свои.
### Функция в качестве аргумента будет принимать атакующего и атакуемого.
### В теле функция должна получить параметр damage атакующего и отнять это количество от health атакуемого. Функция должна сама работать со словарями и изменять их значения.
def attack(person_1, person_2):
print(person_1, person_2)
person_1['health'] -= person_2['damage']
print(person_1, person_2)
dict_person_1 = {'name': 'Leo', 'health': 100, 'damage': 50}
dict_person_2 = {'name': 'Max', 'health': 150, 'damage': 50}
attack(dict_person_1, dict_person_2)
# Давайте усложним предыдущее задание. Измените сущности, добавив новый параметр - armor = 1.2 (величина брони персонажа)
# Теперь надо добавить новую функцию, которая будет вычислять и возвращать полученный урон по формуле damage / armor
# Следовательно, у вас должно быть 2 функции:
# Наносит урон. Это улучшенная версия функции из задачи 3.
# Вычисляет урон по отношению к броне.
def attack(person_1, person_2):
print(person_1, person_2)
person_1['health'] -= armor_damage(person_1, person_2)
print(person_1, person_2)
def armor_damage(person_1, person_2):
return person_2['damage'] / person_1['armor']
dict_person_1 = {'name': 'Leo', 'health': 100, 'damage': 50, 'armor': 1.2}
dict_person_2 = {'name': 'Max', 'health': 150, 'damage': 50, 'armor': 1.2}
attack(dict_person_1, dict_person_2)
|
# print print print
# In gujarat,India day name be like this :D
days = "Somvar Mangalvar Budhvar Gurvar Shukravar Shanivar Ravivar"
'''
don't worry its like
Somvar = Monday
Mangalvar = Tuesday
Budhvar = Wednusday
Gurvar = Thursday
Shukravar = Friday
Shanivar = Saturday
Ravivar = Sunday
note: If you want to learn gujarati language please contact me ;)
Actually I want to lear also french, Spanish, German, Italy,
'''
# ok back to the points
months = "Jan\nFab\nMarch\nApril\nMay\nJun\nJuly\nAugust\nSeptember\nOctober\nNovember\nDecember"
print "Here are the days:", days
#print "Here are the days: %s" %days # don't worry both are valid. Just uncomment this and check it out
print "Here are the months: ", months
'''
Her you see that in output every months name are in new line , hmmmmmmm
do you knnow why???
just check the month line where we add all the months
have you check it???
have you found something new??? yesssss???
hmmm it's '\n' between the month name
yuup '\n' represent new line
when ever you write \n in string interpritor give output in new line
note: '\n' is literal in python there are also some other pthon like below
>>>> \n \t \b \a \f
'''
# nooooooooow we print paragraph
print '''
Hello everyone!!!!
Tell me about your self
I like to make a new friends
Do you know python use interpreter not compiler??
''' |
from sklearn import datasets
iris = datasets.load_iris()
# X = features, y = target_label
X = iris.data
y = iris.target
# Partition the data set using train_test_split
from sklearn.model_selection import train_test_split
# Here we are saying we will split the X into half and do the same with the y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .5)
# Training using a tree
from sklearn import tree
my_classifier = tree.DecisionTreeClassifier()
my_classifier.fit(X_train, y_train)
predictions = my_classifier.predict(X_test)
# Prints predictions of the trained classifier as compared to the test data
#print(predictions)
# Print accuracy of the model using the target labels in our test data
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, predictions))
#Using k neighbors
from sklearn.neighbors import KNeighborsClassifier
my_classifier = KNeighborsClassifier()
my_classifier.fit(X_train, y_train)
predictions = my_classifier.predict(X_test)
print(accuracy_score(y_test, predictions))
# NOTE: we can change the classifiers quickly by just changing two lines
# from sklearn.<The Classifier you wish to use> import <classifier>
# my_classifier = <Classifier>
# Check out http://playground.tensorflow.org/ |
# 2(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 2(1000)?
def digit_sum(num):
sum = 0
while(num > 0):
mod = int(num % 10)
sum += mod
num = num // 10
return sum
n = 2 ** 1000
print(digit_sum(n))
|
import math
def simplify(x, y):
# Quick and dirty gcf
ax, ay = abs(x), abs(y)
if ax == 0:
return 0, y//ay
if ay == 0:
return x//ax, 0
for n in range(2, min(ax, ay)+1):
if x % n == 0 and y % n == 0:
return simplify(x // n, y // n)
return x, y
def get_line(src, dest):
"""
return a line of sight
direction is important and 1, 0 is different from -1,0
"""
ax, ay = src
bx, by = dest
dx, dy = bx-ax, by-ay
return simplify(dx, dy)
def group_by_line(base, coords):
lines = {}
for c in coords:
if c != base:
line = get_line(base, c)
lines.setdefault(line, []).append(c)
return lines
def num_lines(base, coords):
return len(group_by_line(base, coords))
def angle(line):
# return the clockwise angle of a line, starting straight up
v = math.pi/2 - math.atan2(-line[1], line[0])
return v % (2*math.pi)
def parse(s):
coords = []
for y, l in enumerate(s.split("\n")):
for x, c in enumerate(l):
if c == "#":
coords.append((x, y))
return coords
def solve1(s):
m = parse(s)
res = max(num_lines(base, m) for base in m)
return res
def solve2(s):
m = parse(s)
def order(b):
return num_lines(b, m)
best = sorted(m, key=order, reverse=True)[0]
lines = group_by_line(best, m)
ordered_lines = sorted(lines.keys(), key=angle)
def dist_to_best(c):
return abs(c[0]-best[0]) + abs(c[1]-best[1])
i = 0
while i < 200:
idx = ordered_lines[i % len(ordered_lines)]
coords = lines[idx]
if coords:
closest = sorted(coords, key=dist_to_best)[0]
coords.remove(closest)
i += 1
return closest[0]*100 + closest[1]
def main():
with open("input") as f:
print(solve1(f.read()))
with open("input") as f:
print(solve2(f.read()))
main()
|
def read():
with open("input") as f:
a, b, _ = f.read().split("\n")
return a.split(","), b.split(",")
def dist(p):
return abs(p[0]) + abs(p[1])
def make_path(steps):
path = {}
x = 0
y = 0
i = 1
for step in steps:
d = step[0]
dist = int(step[1:])
dx, dy = 0, 0
if d == "R":
dx = 1
elif d == "L":
dx = -1
elif d == "U":
dy = 1
elif d == "D":
dy = -1
for _ in range(dist):
x += dx
y += dy
if (x, y) not in path:
path[(x, y)] = i
i += 1
return path
def closest_cross_manhattan(steps1, steps2):
set1 = set(make_path(steps1).keys())
set2 = set(make_path(steps2).keys())
crosses = set1.intersection(set2)
best = sorted(crosses, key=dist)[0]
return dist(best)
def closest_cross_steps(steps1, steps2):
path1 = make_path(steps1)
path2 = make_path(steps2)
set1 = set(path1.keys())
set2 = set(path2.keys())
crosses = set1.intersection(set2)
best = sorted(crosses, key=lambda pos: path1[pos] + path2[pos])[0]
return path1[best] + path2[best]
def solve1():
steps1, steps2 = read()
print(closest_cross_manhattan(steps1, steps2))
def solve2():
steps1, steps2 = read()
print(closest_cross_steps(steps1, steps2))
solve1()
solve2()
|
"""
This module defines the function that we want to try to learn with NNs.
"""
import random
# The actual functions to learn
def f_identity(seq):
return seq
def f_reverse(seq):
t = [0]*len(seq)
for j in range(len(seq)):
t[len(seq)-j-1] = seq[j]
return t
def f_swap01(seq):
t = []
for j in range(len(seq)):
if seq[j] == 0:
t.append(0)
else:
t.append(1)
return t
def f1(seq):
t = []
for j in range(len(seq)):
if seq[j] == 1 and j > 0 and seq[j-1] == 1:
if j > 3:
t.append(seq[j-2])
else:
t.append(0)
else:
t.append(1)
return t
def f_skiprepeat(seq):
t = []
for j in range(len(seq)):
if j % 2 == 0:
t.append(seq[j])
else:
t.append(seq[j-1])
return t
def f_zeromeansrepeat(seq):
t = []
for j in range(len(seq)):
if j > 0 and seq[j-1] == 0:
t.append(1)
else:
t.append(seq[j])
return t
# an example of a pattern is [1,0,0,2,0,3,0,1,1,1]
def f_repetitionpattern(seq, pattern):
t = []
i = 0
j = 0
while(j < len(seq)):
t.append(seq[j])
j = j + pattern[i % len(pattern)]
i = i + 1
return t
def f_multpattern(seq,patterns,div_symbol):
# We parse the sequence and create a list of lists,
# of the form [n, L] where n = 0,1 is the pattern
# to use and L is a list of integers to which it should
# be applied
parse_list = []
curr_subseq = []
curr_pattern = 0
j = 0
while(j < len(seq)):
if(seq[j] != div_symbol):
curr_subseq.append(seq[j])
if(seq[j] == div_symbol or j == len(seq)-1):
if( len(curr_subseq) != 0 ):
parse_list.append([curr_pattern,curr_subseq])
if(seq[j] == div_symbol):
curr_pattern = (curr_pattern + 1) % len(patterns)
curr_subseq = []
j = j + 1
t = []
for q in parse_list:
t = t + f_repetitionpattern(q[1],patterns[q[0]])
return t
def f_varpattern(seq, init_symbol):
# We parse seq into A.S.B where "." stands for concatentation,
# A, B are sequences and S is the init_symbol. Then we run A
# as a pattern on B using f_repetitionpattern
A = []
B = []
Sfound = False
for x in seq:
if( x == init_symbol ):
Sfound = True
else:
if( Sfound == False ):
A.append(x)
else:
B.append(x)
t = f_repetitionpattern(B,A)
return t
##################
# DEFINING TASKS
##################
# Default sampling from space of inputs
def generate_input_seq_default(max_symbol,input_length):
return [random.randint(0,max_symbol) for k in range(input_length)]
###########
# COPY TASK
#
# In this task the input is simply copied to the output (although we
# require the RNN to output the first output symbol after the last
# input symbol has been read, so this effectively requires the system
# to store the input and later retrieve it)
def get_task_copy(N, Ntest):
generate_input_seq = generate_input_seq_default
func_to_learn = f_identity
N_out = N - 2
Ntest_out = Ntest - 2
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
##################
# REPEAT COPY TASK
#
# In this task every digit of the input is repeated.
#
# put n zeros before the 1, for a copy task with n + 1 copies
def get_task_repeat_copy(N, Ntest):
generate_input_seq = generate_input_seq_default
no_of_copies = 2
pattern = [0]*(no_of_copies - 1) + [1]
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = no_of_copies * (N - 2)
Ntest_out = no_of_copies * (Ntest - 2)
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
################
# PATTERN TASK 1
def get_task_pattern_1(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern = [0,1,1] # so (a,b,c,d,e,f,...) goes to (a,a,b,c,c,d,e,e,...)
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = (N - 2) + divmod(N - 2, 2)[0] # N - 2 plus the number of times 2 divides N - 2
Ntest_out = (Ntest - 2) + divmod(Ntest - 2, 2)[0]
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
################
# PATTERN TASK 2
def get_task_pattern_2(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern = [0,2] # so (a,b,c,d,e,f,...) goes to (a,a,c,c,e,e,...)
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = N - 2 + divmod(N - 2, 2)[0]
Ntest_out = Ntest - 2 + divmod(Ntest - 2, 2)[0]
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
################
# PATTERN TASK 3
def get_task_pattern_3(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern = [0,2,-1] # so (a,b,c,d,e,f,...) goes to (a,a,c,b,b,d,c,c,e,d,d,...)
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = 4 + (N - 2 - 2) * 3
Ntest_out = 4 + (Ntest - 2 - 2) * 3
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
################
# PATTERN TASK 4
def get_task_pattern_4(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern = [0,2,1,2,-2,-1] # so (a,b,c,d,e,f,...) goes to (a,a,c,d,f,d,c,c,e,f,h,f,e,e,...)
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = len(func_to_learn([0]*(N-2)))
Ntest_out = len(func_to_learn([0]*(Ntest-2)))
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
################
# PATTERN TASK 5
def get_task_pattern_5(N, Ntest):
pattern = [4,1,1,-4] # so (a,b,c,d,e,f,...) goes to (a,e,f,g,k,...)
func_to_learn = lambda s: f_repetitionpattern(s,pattern)
N_out = len(func_to_learn([0]*(N-2)))
Ntest_out = len(func_to_learn([0]*(Ntest-2)))
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# MULTIPLE PATTERN TASK 1
def get_task_mult_pattern_1(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern1 = [1] # so (a,b,c,d,e,f,...) goes to (a,b,c,d,e,f,...)
pattern2 = [0,1] # so (a,b,c,d,e,f,...) goes to (a,a,b,b,...)
func_to_learn = lambda s: f_multpattern(s,[pattern1,pattern2],div_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# MULTIPLE PATTERN TASK 2
def get_task_mult_pattern_2(N, Ntest):
# Almost everything is the same as mult pattern 1, but in pattern 2 we
# make sure there is a div symbol somewhere in the sequence
func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq = get_task_mult_pattern_1()
def generate_input_seq_forcediv(max_symbol,input_length):
t = [random.randint(0,max_symbol) for k in range(input_length)]
div_pos = random.randint(0,len(t)-1)
t[div_pos] = div_symbol
return t
generate_input_seq = generate_input_seq_forcediv
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# MULTIPLE PATTERN TASK 3
def get_task_mult_pattern_3(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern1 = [1] # so (a,b,c,d,e,f,...) goes to (a,b,c,d,e,f,...)
pattern2 = [0,1] # so (a,b,c,d,e,f,...) goes to (a,a,b,b,...)
pattern3 = [0,2] # so (a,b,c,d,e,f,...) goes to (a,a,c,c,...)
func_to_learn = lambda s: f_multpattern(s,[pattern1,pattern2,pattern3],div_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# MULTIPLE PATTERN TASK 4
def get_task_mult_pattern_4(N, Ntest):
generate_input_seq = generate_input_seq_default
pattern1 = [0,1] # so (a,b,c,d,e,f,...) goes to (a,a,b,b,...)
pattern2 = [2,-1] # so (a,b,c,d,e,f,...) goes to (a,c,b,d,c,...)
func_to_learn = lambda s: f_multpattern(s,[pattern1,pattern2],div_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 7
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# VARIABLE PATTERN TASK 1
#
# The input is a pattern together with a string to which we are supposed to apply the
# pattern, separated by an initial symbol. There is no division symbol.
def generate_input_seq_varpattern1(max_symbol,input_length):
varpatterns = [[1],[2],[0,1],[0,2],[1,2]]
vp = varpatterns[random.randint(0,len(varpatterns)-1)]
t = vp + [init_symbol] + [random.randint(0,max_symbol) for k in range(input_length-len(vp)-1)]
return t
def get_task_var_pattern_1(N, Ntest):
generate_input_seq = generate_input_seq_varpattern1
func_to_learn = lambda s: f_varpattern(s,init_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 10
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# VARIABLE PATTERN TASK 2
def generate_input_seq_varpattern2(max_symbol,input_length):
varpatterns = [[1],[2]]
varpatterns = varpatterns + [[0,1],[0,2],[1,2]]
varpatterns = varpatterns + [[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,1,2],[1,2,2]]
varpatterns = varpatterns + [[0,0,0,1],[0,0,0,2],[0,0,1,2],[0,1,1,2],[0,1,0,2],[0,2,0,2]]
vp = varpatterns[random.randint(0,len(varpatterns)-1)]
t = vp + [init_symbol] + [random.randint(0,max_symbol) for k in range(input_length-len(vp)-1)]
return t
def get_task_var_pattern_2(N, Ntest):
generate_input_seq = generate_input_seq_varpattern2
func_to_learn = lambda s: f_varpattern(s,init_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 13
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# VARIABLE PATTERN TASK 3
#
# In this task we randomly generate the pattern from the alphabet 0,1,2
# We also generate longer sequences than in task 1 or 2. By default
# we generate patterns between length 1 and 8
def generate_input_seq_varpattern3(max_symbol,input_length):
vp_length = random.randint(1,max_pattern_length)
while( True ):
vp = [random.randint(0,2) for k in range(vp_length)]
# We cannot allow patterns that are all zeros
if( reduce( lambda x,y : x + y, vp) > 0 ):
break
t = vp + [init_symbol] + [random.randint(0,max_symbol) for k in range(input_length-len(vp)-1)]
return t
def get_task_var_pattern_3(N, Ntest):
generate_input_seq = generate_input_seq_varpattern3
func_to_learn = lambda s: f_varpattern(s,init_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 20
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
#########################
# VARIABLE PATTERN TASK 4
#
# In this task we randomly generate the pattern from the alphabet -2,-1,0,1,2
def generate_input_seq_varpattern4(max_symbol,input_length):
vp_length = random.randint(1,max_pattern_length)
while( True ):
vp = [random.randint(-2,2) for k in range(vp_length)]
# We cannot allow patterns that add up to a non-positive integer
if( reduce( lambda x,y : x + y, vp) > 0 ):
break
t = vp + [init_symbol] + [random.randint(0,max_symbol) for k in range(input_length-len(vp)-1)]
return t
def get_task_var_pattern_4(N, Ntest):
generate_input_seq = generate_input_seq_varpattern4
func_to_learn = lambda s: f_varpattern(s,init_symbol)
N_out = 2*(N-2)
Ntest_out = 2*(Ntest-2)
seq_length_min = 20
return func_to_learn, N_out, Ntest_out, seq_length_min, generate_input_seq
def get_task(task, N, Ntest):
if( task == 'copy' ):
return( get_task_copy(N, Ntest) )
if( task == 'repeat copy' ):
return( get_task_repeat_copy(N, Ntest) )
if( task == 'pattern 1' ):
return( get_task_pattern_1(N, Ntest) )
if( task == 'pattern 2' ):
return( get_task_pattern_2(N, Ntest) )
if( task == 'pattern 3' ):
return( get_task_pattern_3(N, Ntest) )
if( task == 'pattern 4' ):
return( get_task_pattern_4(N, Ntest) )
if( task == 'pattern 5' ):
return( get_task_pattern_5(N, Ntest) )
if( task == 'mult pattern 1' ):
return( get_task_mult_pattern_1(N, Ntest) )
if( task == 'mult pattern 2' ):
return( get_task_mult_pattern_2(N, Ntest) )
if( task == 'mult pattern 3' ):
return( get_task_mult_pattern_3(N, Ntest) )
if( task == 'mult pattern 4' ):
return( get_task_mult_pattern_4(N, Ntest) )
if( task == 'variable pattern 1' ):
return( get_task_var_pattern_1(N, Ntest) )
if( task == 'variable pattern 2' ):
return( get_task_var_pattern_2(N, Ntest) )
if( task == 'variable pattern 3' ):
return( get_task_var_pattern_3(N, Ntest) )
if( task == 'variable pattern 4' ):
return( get_task_var_pattern_4(N, Ntest) ) |
#getcofreqs.py
#USAGE: python getcofreqs [token file]
#EXAMPLE: python getcofreqs tokens.txt
#The token file must contain one token per line.
#_______
import sys
win_one_side=int(sys.argv[2]) #How many words on either side of the target? i.e. 5 corresponds to a 11_word window
win_both_sides=int(win_one_side) * 2
win_full=win_both_sides + 1
cofreqs_dict = {}
freqs_dict = {}
#Shift window by one word
def shiftwindow(w,i,tokens):
for c in range(win_both_sides):
w[c]=w[c+1] #Shift window up to last element, which remains the same (to be replaced by reading new line in lemma file)
w[win_both_sides]=tokens[i+win_one_side+1] #Replace last element in window
return w
#Get cofreqs, and while we're at it, count words
def getcofreqs(w):
for c in range(win_full):
if c is not win_one_side: #We don't count co-occurrences of the word with itself
co=w[win_one_side]+" "+w[c]
#print co
if co in cofreqs_dict:
cofreqs_dict[co]+=1
else:
cofreqs_dict[co] = 1
else:
if w[c] in freqs_dict:
freqs_dict[w[c]]+=1
else:
freqs_dict[w[c]]=1
#open the token file (one token per line)
filename=sys.argv[1]
#Token array needs padding with non-words at beginning and end
tokens=[]
for c in range(win_one_side):
tokens.append('#')
lines=open(filename,"r")
for t in lines:
tokens.append(t.rstrip('\n'))
lines.close()
for c in range(win_one_side):
tokens.append('#')
#Initialise window
window=tokens[0:win_full]
for i in range(win_one_side,len(tokens)-win_one_side):
#print "Processing",tokens[i],"..."
#print window
getcofreqs(window)
if i+win_one_side+1<len(tokens):
window=shiftwindow(window,i,tokens)
#print window
fcofreqs=open(sys.argv[1]+".sm",'w')
for el in cofreqs_dict:
fcofreqs.write(el+" "+str(cofreqs_dict[el])+"\n")
fcofreqs.close()
ffreqs=open(sys.argv[1]+".freqs",'w')
for w in sorted(freqs_dict, key=freqs_dict.get, reverse=True):
ffreqs.write(str(freqs_dict[w])+" "+w+"\n")
ffreqs.close()
|
import unittest
from daily.d6_reverse_linked_list.solution import ListNode, reverse_iterative, reverse_recursive
class MyTestCase(unittest.TestCase):
def test_iterative(self):
head = self._get_test_list()
new_head = reverse_iterative(head)
self.assertEqual('0 1 2 3 4 ', str(new_head))
def test_recursive(self):
head = self._get_test_list()
new_head = reverse_recursive(head)
self.assertEqual('0 1 2 3 4 ', str(new_head))
@staticmethod
def _get_test_list():
head = ListNode(4)
head.next = ListNode(3)
head.next.next = ListNode(2)
head.next.next.next = ListNode(1)
head.next.next.next.next = tail = ListNode(0)
return head
if __name__ == '__main__':
unittest.main()
|
"""
[Daily Problem] Add two numbers as a linked list
You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and
each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
r = ''
curr = self
while curr:
r += str(curr.val)
curr = curr.next
return r
def add(self, other):
return add_two_numbers(self, other)
def add_two_numbers(l1, l2, carry=0):
op1 = 0 if l1 is None else l1.val
op2 = 0 if l2 is None else l2.val
t = op1 + op2 + carry
if t == 0:
return None
new_carry = int(t / 10)
curr = t % 10
r = ListNode(curr)
r.next = add_two_numbers(
None if l1 is None else l1.next,
None if l2 is None else l2.next,
new_carry
)
return r
|
import database
import scraping
import testing
import visualization
prompt = '''Please choose from the following:\n
database
Reinitializes the database/cache.\n
scraping
Makes a call to the API and dynamically scrapes stories from BBC.\n
testing
Runs a few unit tests to ensure the database is initialized properly and data is properly stored.\n
visualization
Starts the Flask in a local environment, allowing for some data visualization.\n
quit
Quit the program.
Make your selection now: '''
if __name__ == '__main__':
user_input = input(prompt)
while user_input.lower() != 'quit':
if user_input.lower() == 'database':
database.db_main()
elif user_input.lower() == 'scraping':
user_decision = input('Are you sure you want to scrape? This will take some time! (y/n): ')
if user_decision.lower() == 'y':
scraping.sc_main()
else:
pass
elif user_input.lower() == 'testing':
user_decision = input('Are you sure you want to test? This will take around 20 seconds, depending on hardware speed. (y/n): ')
if user_decision.lower() == 'y':
testing.te_main()
else:
pass
elif user_input.lower() == 'visualization':
visualization.vi_main()
else:
print('Invalid input, please try again!')
print()
user_input = input(prompt) |
def gcd(a,b):
if b==0:
return a
return gcd(b,a%b)
def leftRotate(arr,d):
n=len(arr)
for i in range(0,gcd(n,d)):
t=arr[i]
j=i
while True:
k=j+d
if k>=n:
k=k-n
if k==i:
break
arr[j]=arr[k]
j=k
arr[j]=t
arr=[3,2,1,4,5,3,6]
d=3
leftRotate(arr,d)
print(arr,end=" ")
|
words=s.split(' ')
res=[]
for word in words:
r="".join(reversed(word))
res.append(r)
re=""
for i in res:
re=re+str(i)+" "
return re.rstrip()
|
"""
(This problem is an interactive problem.)
A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).
BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.
Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.
Example 1:
Input: mat = [[0,0],[1,1]]
Output: 0
Example 2:
Input: mat = [[0,0],[0,1]]
Output: 1
Example 3:
Input: mat = [[0,0],[0,0]]
Output: -1
Example 4:
Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
Output: 1
Constraints:
1 <= mat.length, mat[i].length <= 100
mat[i][j] is either 0 or 1.
mat[i] is sorted in a non-decreasing way.
"""
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x, y):
# """
# :type x : int, y : int
# :rtype int
# """
#
# def dimensions:
# """
# :rtype list[]
# """
class Solution(object):
def leftMostColumnWithOne(self, binaryMatrix):
"""
:type binaryMatrix: BinaryMatrix
:rtype: int
"""
l=binaryMatrix.dimensions()
n,m=l[0],l[1]
def f_pos(i,s,e):
while s<=e:
mid=(s+e)//2
if (mid==0 or binaryMatrix.get(i,mid-1)==0) and binaryMatrix.get(i,mid)==1:
return mid
elif binaryMatrix.get(i,mid)==1:
e=mid-1
else:
s=mid+1
return m
ans=m
low=None
e=m-1
for r in range(n):
if binaryMatrix.get(r,e)==0:
continue
a=f_pos(r,0,e)
if a==0:
return 0
e=min(e,a-1)
ans=min(ans,a)
if ans!=m:
return ans
return -1
# Alternate Solution
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x, y):
# """
# :type x : int, y : int
# :rtype int
# """
#
# def dimensions:
# """
# :rtype list[]
# """
class Solution(object):
def leftMostColumnWithOne(self, binaryMatrix):
"""
:type binaryMatrix: BinaryMatrix
:rtype: int
"""
l=binaryMatrix.dimensions()
n,m=l[0],l[1]
r,c=0,m-1
ans=-1
while r<n and c>=0:
if binaryMatrix.get(r,c)==1:
ans=c
c-=1
else:
r+=1
return ans
|
arr=[-2, -3, 4, -1, -2, 1, 5, -3]
max_sum=arr[0]
curr_sum=arr[0]
for i in range(1,len(arr)):
curr_sum=max(curr_sum+arr[i],arr[i])
max_sum=max(max_sum,curr_sum)
print(max_sum)
|
a=[2, 3, 10, 6, 4, 8, 1]
max_diff=a[1]-a[0]
min_element=a[0]
for i in range(1,len(a)):
max_diff=max(max_diff,a[i]-min_element)
min_element=min(min_element,a[i])
print(max_diff)
|
# Maria Ali
# Machine Learning Assignment 3
# Regression on the Data of monthly experience and income distribution of different employees
# Importing the libraries and the dataset for evaluation
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
dataset = pd.read_csv('monthlyexp vs incom.csv')
# Assembling the values for "p" and "q":
p = dataset.iloc[:, 0:1].values
q = dataset.iloc[:, 1:2].values
# Splitting the dataset into the Training set and Test set
"""from sklearn.cross_validation import train_test_split
p_train, p_test, q_train, q_test = train_test_split(p, q, test_size = 0.2, random_state = 0)"""
# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(p, q)
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
p_poly = poly_reg.fit_transform(p)
poly_reg.fit(p_poly, q)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(p_poly, q)
# Fitting Decision Tree Regression to the dataset
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state = 0)
regressor.fit(p, q)
# Visualising the Linear Regression results
plt.scatter(p, q, color = 'orange') # Creating Scatter Plot
plt.plot(p, lin_reg.predict(p), color = 'brown', label='Best Fit Line') # Creating Best Fit Line
tnrfont = {'fontname':'Times New Roman'} # Setting the font "Times New Roman"
plt.title('Linear Regression for Monthly Experience vs. Income Distribution',**tnrfont) # Setting the Title
plt.xlabel('Monthly Experience',**tnrfont) # Labelling x-axis
plt.ylabel('Income Distribution',**tnrfont) #Labelling y-axis
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) # Creating Grid
leg = plt.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1); # Creating Legend
plt.show()
# Visualising the Polynomial Regression results
p_grid = np.arange(min(p), max(p), 0.1)
p_grid = p_grid.reshape((len(p_grid), 1))
plt.scatter(p, q, color = 'orange') # Creating Scatter Plot
plt.plot(p_grid, lin_reg_2.predict(poly_reg.fit_transform(p_grid)), color = 'brown', label='Best Fit Line') # Creating Best Fit Line
tnrfont = {'fontname':'Times New Roman'} # Setting the font "Times New Roman"
plt.title('Polynomial Regression for Monthly Experience vs. Income Distribution',**tnrfont) # Setting the Title
plt.xlabel('Monthly Experience',**tnrfont) # Labelling x-axis
plt.ylabel('Income Distribution',**tnrfont) #Labelling y-axis
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) # Creating Grid
leg = plt.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1); # Creating Legend
plt.show()
# Visualising the Decision Tree Regression results
p_grid = np.arange(min(p), max(q), 0.01)
p_grid = p_grid.reshape((len(p_grid), 1))
plt.scatter(p, q, color = 'orange') # Creating Scatter Plot
plt.plot(p_grid, regressor.predict(p_grid), color = 'brown', label='Best Fit Line') # Creating Best Fit Line
tnrfont = {'fontname':'Times New Roman'} # Setting the font "Times New Roman"
plt.title('Decision Tree Regression for Monthly Experience vs. Income Distribution',**tnrfont) # Setting the Title
plt.xlabel('Monthly Experience',**tnrfont) # Labelling x-axis
plt.ylabel('Income Distribution',**tnrfont) #Labelling y-axis
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5) # Creating Grid
leg = plt.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1); # Creating Legend
plt.show() |
def sequentialSearch(aList, item):
pos = 0
found = False
while pos < len(aList) and not found:
if aList[pos] == item:
found = True
else:
pos = pos + 1
return found
l = [1,2,5,134,23412312,3213,4523,12,3213,123123123123123123,123123123,123123123]
print(sequentialSearch(l, 123123123))
def orderedSequentialSearch(aList, item):
pos = 0
found = False
stop = False
while pos < len(aList) and not found and not stop:
if aList[pos] == item:
found = True
else:
if aList[pos] > item:
stop = True
else:
pos += 1
return found
def binarySearch(aList, item):
first = 0
last = len(aList) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if aList[mid] == item:
found = True
else:
if item < aList[mid]:
last = mid - 1
else:
first = mid + 1
return found
l = [1,3,7,12,22,99,233,9239,213213123,123123584359123]
print(binarySearch(l, 213213123))
# Binary Search with Recursion
def recursiveBinarySearch(aList, item):
first = 0
last = len(aList) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if aList[mid] == item:
return True
else:
if item < aList[mid]:
return recursiveBinarySearch(aList[:mid], item)
else:
return recursiveBinarySearch(aList[mid + 1:], item)
l = [1,3,6,22,221,553,1233,123123,123543212,1231243512,3123123123123123123,45435345435345435345345345]
print(recursiveBinarySearch(l, 3123123123123123123))
def interpolationSearch(aList, item):
min = 0
max = len(aList) - 1
while min <= max:
scale = (item - aList[min]) // (aList[max] - aList[min])
mid = min + (max-min) * scale
if aList[mid] == item:
return mid
elif aList[mid] < item:
min = mid + 1
else:
max = mid - 1
return -1
l = [1,3,6,22,221,553,1233,123123,123543212,1231243512,3123123123123123123,45435345435345435345345345]
print(interpolationSearch(l, 45435345435345435345345345)) |
numero_ganador = 5
numero_usuario = int(input("Adivine el numero(1-10): "))
if numero_usuario == numero_ganador: print("¡Has ganado!")
else: print("Has perdido, el número ganador era {} y has escogido el número {}".format(numero_ganador, numero_usuario)) |
agenda = dict()
confirmacion = False
while True:
accion = input("Que desea hacer? (Añadir[A] / Consultar[C] / Salir[S]) ")
if accion.upper() == "A":
print("Se añadirá un año de nacimiento al sistema.")
print("+++++++++++++++++++++++++++++++++++++++++++\n")
nombre = input("Nombre: ")
anio = input("Año de nacimiento: ")
agenda[nombre] = anio
print("El año de nacimiento de {} se ha añadido correctamente.".format(nombre))
elif accion.upper() == "C":
if len(agenda) != 0:
print("Se consultará un año de nacimiento de los almacenados en el sistema.")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")
nombre_consulta = input("¿De quién quiere consultar el año de nacimiento? ")
if nombre_consulta in agenda:
print("El año de nacimiento de {} es {}.".format(nombre_consulta, agenda[nombre_consulta]))
else:
print("La persona que ha seleccionado no está en el sistema.")
else:
print("No se puede consultar ningún año de nacimiento, la agenda está vacía.")
elif accion.upper() == "S":
print("Ha salido del programa, hasta la próxima.")
exit() |
lista_numeros = [1, 2, 3, 45, 83, 95, 24, 642, 567, 24]
multiplos_dos = []
multiplos_tres = []
multiplos_cinco = []
multiplos_siete = []
print("Lista inicial: {}".format(lista_numeros))
for numero in lista_numeros:
if numero % 2 == 0:
multiplos_dos.append(numero)
if numero % 3 == 0:
multiplos_tres.append(numero)
if numero % 5 == 0:
multiplos_cinco.append(numero)
if numero % 7 == 0:
multiplos_siete.append(numero)
print("Múltiplos de 2: {}".format(multiplos_dos))
print("Múltiplos de 3: {}".format(multiplos_tres))
print("Múltiplos de 5: {}".format(multiplos_cinco))
print("Múltiplos de 7: {}".format(multiplos_siete)) |
# 1
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def personlnfo(self):
print(self.name + ' ' + str(self.age), self.sex)
class Student(Person):
def __init__(self, name, age, sex, college, clas):
super().__init__(name, age, sex, )
self.college = college
self.clas = clas
def __str__(self):
return self.name + str(self.age) + self.sex + self.college + self.clas
def personlnfo(self):
super().personlnfo()
print(self.college, self.clas)
def syudy(self, teacher):
teacher.teachObj()
print(teacher.name + "老师我学会了")
class Teacher(Person):
def __init__(self, name, age, sex, college, professional):
super().__init__(name, age, sex)
self.college = college
self.professional = professional
def personlnfo(self):
super().personlnfo()
print(self.college, self.professional)
def teachObj(self):
print('今天学会了如何用面向对象设计程序')
CaoYi = Teacher("曹懿", 23, '男', '汽车电子技术', '电子')
# CaoYi.personlnfo()
GanLi = Student('淦丽', 22, '女', '数学与运用', '数学')
# GanLi.personlnfo()
GanLi.syudy(CaoYi)
print(GanLi)
GanLi1 = Student("曹懿", 23, '男', '汽车电子技术', '电子')
GanLi2 = Student("曹懿", 23, '男', '汽车电子技术', '电子')
GanLi3 = Student("曹懿", 23, '男', '汽车电子技术', '电子')
i = []
i.append(GanLi1)
i.append(GanLi2)
i.append(GanLi3)
for i in i:
print(i)
|
""" This Example will use Classes with List , Dictionary and Linq expression
1. Empty Check for List or Dictionary
2. Checking Key in Dictionary
3. Dictionary Initialization
4. pass keyword
"""
""" "pass" keyword (a statement) to indicate that nothing happens—the function, class or loop is empty.
With pass, we indicate a "null" block. Pass can be placed on the same line, or on a separate line.
Pass can be used to quickly add things that are unimplemented."""
class Shape(object):
def __init__(self):
pass
def show(self):
raise Exception("Not Implemented Exception")
class A(Shape):
def show(self):
print("I am A !!")
class B(Shape):
def show(self):
print("I am B !!")
class IfCaseScenario(object):
List_Class_Instances = []
def __init__(self):
self.ListInitialization1("A Class")
def ListInitialization1(self, ShObj):
if ShObj == 'A Class':
self.List_Class_Instances.append(A())
self.List_Class_Instances.append(B())
elif type(ShObj) is B:
self.List_Class_Instances.append(B())
def PrintList(self):
print("Number of Class Instances are : " , len(self.List_Class_Instances))
print("List Instances are : " , self.List_Class_Instances)
class RefactoredIfCaseScenario(object):
List_Class_Instances = []
Dictionary_Class_Instances = { 'A Class':'A()' , 'B Class':'B()' , 'C Class':'C()', 'D Class':'D()'}
""" In this constructer we are just passing AObj """
def __init__(self):
self.ListInitialization1("A Class")
""" In this method we are just passing AObj from above and checking in for loop against dictionary to load the conditions """
def ListInitialization1(self, ShObj):
if ShObj in self.Dictionary_Class_Instances.keys():
self.List_Class_Instances.append(A())
self.List_Class_Instances.append(B())
self.List_Class_Instances.append("C String Value")
self.List_Class_Instances.append(4)
""" Prints the initialized data in a list"""
def PrintList(self):
print("Number of List Instances are : " , len(self.List_Class_Instances))
if not self.List_Class_Instances:
print("Nothing here Empty List")
else:
print("List Instances are : " , self.List_Class_Instances)
if __name__ == "__main__":
Aobj = A()
Bobj = B()
""" Print the List """
IfCaseobj = IfCaseScenario()
IfCaseobj.PrintList()
""" Refactored Class Sceanrio """
RObj = RefactoredIfCaseScenario()
RObj.PrintList() |
# import unit test module of python
import unittest
from Examples import Example
class MyTestCase (unittest.TestCase):
#method should be prefixed with keyword 'test'
@classmethod #Use annotation @classmethod
def setUpClass(cls):
print("This will run before all the methods")
@classmethod
def tearDownClass(cls):
print("This will run once after all the method ")
def setUp(self):
print("This will run before every method")
def tearDown(self):
print("This will after every method")
def test_add(self):
result = Example.add(self,10,20)
self.assertEqual(result,30)
def test_sub(self):
result = Example.sub(self,30,20)
self.assertEqual(Example.sub(self,30,20),10)
self.assertEqual(Example.sub(self,50,60),-10)
# if __name__ == '__main__':
# unittest.main ()
|
# Tuple is created using circular brackets (), Ordered ,Indexed,unchangeable,duplicates
my_tuple = ("Tokyo", "Lisbon", "New York")
print ( my_tuple ) # ('Tokyo', 'Lisbon', 'New York')
print ( my_tuple[2] ) # New York
print ( my_tuple[-1] ) # New York
print ( my_tuple[0:2] ) # ('Tokyo', 'Lisbon')
for val in my_tuple:
print ( val ) # Tokyo Lisbon New York
# Unchangeable : cannot add or delete any object in Tuple
# my_tuple[1] = "Paris" # TypeError: 'tuple' object does not support item assignment
# length
print ( len ( my_tuple ) ) # 3
# Multiple data Type
my_tuple_2 = ("Paris", (1, 2, 3), ["banana", "apple"])
print ( my_tuple_2 ) # ('Paris', (1, 2, 3), ['banana', 'apple'])
print ( my_tuple_2[2][0] ) # banana
print ( my_tuple_2[2] ) # ['banana', 'apple']
my_tuple_2[2][1] = "grapes"
print ( my_tuple_2 ) # ('Paris', (1, 2, 3), ['banana', 'grapes'])
print ( "Paris" in my_tuple_2 ) # True
print ( "NewYork" in my_tuple_2 ) # False
|
dict = {}
naam = input('enter name: ')
while naam != '':
if naam in dict:
dict[naam] += 1
else:
dict[naam] = 1
naam = input('enter name: ')
for naam,value in dict.items():
if value == 1:
print('Er is {} student met de naam {}'.format(value, naam))
else:
print('Er zijn {} studenten met de naam {}'.format(value, naam))
|
from datetime import datetime as dt # import date time Module
t1=input('enter date in HH:MM:SS:')
t2=input('enter date in HH:MM:SS:')
format= "%H:%M:%S" # format Time
def timedifference(time1, time2):
try:
t1 = dt .strptime(time2,format)-dt.strptime(time1, format)
return t1
except Exception as e:
print(e)
return e
return (t2 - t1)
print(timedifference(t1,t2))
|
#interest calculation
money=int(input('enter principal amount:'))
rate=float(input('enter the rate of interst per 100:'))
time=int(input('enter time period in months:'))
interest=money*rate*time/100 # formula=P*T*R/100; P= Principal Amount, T=TimePeriod, R=Rate Of Interest
print('interest amount',interest,'\n','total amount',money,'+',interest,'=',money+interest)
|
class Solution:
def two_sum_sorted(self, numbers, target):
left = 0
right = len(numbers) - 1
while left < right:
result = numbers[left] + numbers[right]
if result == target:
return [left + 1, right + 1]
elif result < target:
left += 1
else:
right -= 1
return []
|
from BST import Searchtree
from Intervaltree import Intervaltree
__author__ = 'Ward Schodts en Robin Goots'
class Algo1(object):
circle_list = list()
intersection_list = list()
def __init__(self, circle_list):
self.circle_list = circle_list
def execute(self):
"""
Voer het algoritme uit.
"""
while len(self.circle_list) != 0:
# Haal de eerste cirkel van de lijst.
cirkel = self.circle_list.pop(0)
# Itereer over de andere cirkels en check dat ze overlappen.
for c in self.circle_list:
if cirkel.check_overlap(c):
temp = cirkel.calculate_intersections(c)
for t in temp:
self.intersection_list.append(t)
def get_intersections(self):
"""
Geef de lijst met snijpunten terug.
"""
return self.intersection_list
class Algo2(object):
intersection_list = list()
def __init__(self, circle_list):
self.circle_list = circle_list
def execute(self):
self.sort_circle_list()
circle = list()
while not self.bst.is_empty():
temp = self.bst.pop()
if temp.hand == 0:
for c in circle:
if temp.circle.check_overlap(c):
intersections = temp.circle.calculate_intersections(c)
for t in intersections:
self.intersection_list.append(t)
circle.append(temp.circle)
else:
circle.remove(temp.circle)
def get_intersections(self):
return self.intersection_list
def sort_circle_list(self):
self.bst = Searchtree()
for c in self.circle_list:
self.bst.insert(c.linksPunt)
self.bst.insert(c.rechtsPunt)
class Algo3(object):
intersection_list = list()
def __init__(self, circle_list):
self.circle_list = circle_list
def execute(self):
self.sort_circle_list()
circleTree = Intervaltree()
while not self.bst.is_empty():
temp = self.bst.pop()
if temp.hand == 0:
for circle in circleTree.searchOverlap(temp.segment):
if circle.check_overlap(temp.circle):
intersections = circle.calculate_intersections(temp.segment.circle)
for i in intersections:
self.intersection_list.append(i)
circleTree.insert(temp.segment)
else:
circleTree.delete(temp.segment)
def get_intersections(self):
return self.intersection_list
def sort_circle_list(self):
self.bst = Searchtree()
for c in self.circle_list:
self.bst.insert(c.linksPunt)
self.bst.insert(c.rechtsPunt) |
from random import random
from Cirkel import Cirkel
def generate_cirkels(amount, radius = 1):
cirkels = list()
for a in range(amount):
cirkels.append(Cirkel(1*random(), 1*random(), 1*random()))
return cirkels
def write_to_file(cirkels):
with open('input.txt', 'w') as f:
f.write("3\n")
f.write(str(len(cirkels)))
f.write('\n')
for c in cirkels:
f.write(str(c.getXco()) + " ")
f.write(str(c.getYco()) + " ")
f.write(str(c.getR()) + "\n")
c = generate_cirkels(1000)
write_to_file(c)
|
# def operation(b, a, op):
# if op == '+':
# return int(a) + int(b)
# if op == '-':
# return int(a) - int(b)
# if op == '*':
# return int(a) * int(b)
# else:
# return int(int(a) // int(b))
def evalRPN(A):
polish_list = []
for op in A:
# if op not in ['+', '-', '*', '/']:
if op not in '+-*/':
polish_list.append(op)
else:
polish_list.append(int(eval('{2}{1}{0}'.format(polish_list.pop(), op, polish_list.pop()))))
return polish_list[0]
A = ["5", "1", "2", "+", "4", "*", "+", "3", "-"]
print(evalRPN(A))
|
from collections import deque
from binarytree import bst, heap
from queue import LifoQueue
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def minDepth(self, A):
# Stack for DFS
stack = LifoQueue()
# Put the root node
stack.put((A,1))
# Initialize mindepth to a large value
mindepth = sys.maxsize
# While the stack is not empty
while not stack.empty():
# Get the node and the depth
node, depth = stack.get()
# Push left and right children and their depths to the stack (if they exist)
if node.left is not None:
stack.put((node.left, depth+1))
if node.right is not None:
stack.put((node.right, depth+1))
# If the popped node is a leaf node and has lesser depth than mindepth then update mindepth
if node.left is None and node.right is None:
if depth<mindepth:
mindepth = depth
return mindepth
def minDepth(A):
q = deque()
q.append(A)
curr, nest, level = 1, 0, 1
while q:
item = q.popleft()
curr -= 1
if not item.right and not item.left:
return level
if item.right:
q.append(item.right)
nest += 1
if item.left:
q.append(item.left)
nest += 1
if curr == 0:
curr, nest = nest, curr
level += 1
a = bst()
print(a)
#a= {3, 1, -1, -1}
print(minDepth(a))
b = heap()
print(b) |
def compare(num, aDeviner, nbEssais):
if num < aDeviner:
print("plus")
return(0)
elif num > aDeviner:
print("moins")
return(0)
else:
print("Il vous a falu", nbEssais, "coups")
return(1)
aDeviner = int(input("Entrez un nombre entre 1 et 100\n"))
nbEssais = 1
num = 101
a = 0
while a != 1:
num = int(input("Votre nombre\n"))
a = compare(num, aDeviner, nbEssais)
nbEssais = nbEssais+1
a = input()
|
'''
def tri(tab):
tabtrie=[]
ind=-1
for i in range(len(tab)):
min=tab[0]
for j in range(len(tab)):
if min<tab[j] and j!=ind:
min=tab[j]
ind=j
tabtrie[i]=min
return tabtrie
'''
def select_tri(tab):
min=tab[0]
for j in range(len(tab)):
if min>tab[j]:
min=tab[j]
ind=j
x=tab[ind]
tab[ind]=tab[0]
tab[0]=x
if len(tab)!=1:
tab=tab[0]+select_tri(tab[1:])
return tab
print(select_tri([6, 5, 4, 2, 1]))
|
"""Задание на execute_script
В данной задаче вам нужно будет снова преодолеть капчу для роботов и справиться с ужасным и огромным футером,
который дизайнер всё никак не успевает переделать. Вам потребуется написать код, чтобы:
Открыть страницу http://SunInJuly.github.io/execute_script.html.
Считать значение для переменной x.
Посчитать математическую функцию от x.
Проскроллить страницу вниз.
Ввести ответ в текстовое поле.
Выбрать checkbox "I'm the robot".
Переключить radiobutton "Robots rule!".
Нажать на кнопку "Submit"."""
import math
from selenium import webdriver
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
browser = webdriver.Chrome()
link = "https://SunInJuly.github.io/execute_script.html"
browser.get(link)
browser.find_element_by_id('input_value')
browser.find_element_by_id('answer').send_keys(calc(browser.find_element_by_id('input_value').text))
robotCheckbox = browser.find_element_by_id('robotCheckbox')
browser.execute_script("window.scrollBy(0, 100);")
robotCheckbox.click()
robotsRule = browser.find_element_by_id('robotsRule')
robotsRule.click()
button = browser.find_element_by_tag_name('button')
button.click()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 19:46:36 2018
@author: dinesh
"""
import math as mat
# the input for 'radians' function is degrees
def app(x):
x = mat.radians(x)
num = (16*(mat.pi-float(x)))*float(x)
denom = (5*(mat.pi)**2)-((4*(mat.pi-float(x)))*float(x))
return abs(num)/abs(denom)
print("Approximated sine value")
print(app(20))
print("Actual sine value")
print(mat.sin(mat.radians(90)))
# the input for 'degrees' function is radians
y = mat.degrees(mat.pi)
print("pi radians is 180 degrees")
print(y)
|
enter='Enter your CA grade for week ', ' <A/B/C/D/F/X/LOA> : ','A - 4.0, B - 3.0, C - 2.0, D - 1.0, F - 0.0, X - 0.0, LOA - Not counted towards average total'
wk01 = raw_input(enter[0] + '1' + enter[1])
wk02 = raw_input(enter[0] + '2' + enter[1])
wk03 = raw_input(enter[0] + '3' + enter[1])
wk04 = raw_input(enter[0] + '4' + enter[1])
wk05 = raw_input(enter[0] + '5' + enter[1])
wk06 = raw_input(enter[0] + '6' + enter[1])
wk07 = raw_input(enter[0] + '7' + enter[1])
wk08 = raw_input(enter[0] + '8' + enter[1])
wk09 = raw_input(enter[0] + '9' + enter[1])
wk10 = raw_input(enter[0] + '10' + enter[1])
wk11 = raw_input(enter[0] + '11' + enter[1])
wk12 = raw_input(enter[0] + '12' + enter[1])
wk13 = raw_input(enter[0] + '13' + enter[1])
print enter[2]
con = 'Your daily grade for 13 weeks: ', 'Your daily score for 13 weeks: '
show_grade = [wk01, wk02,wk03,wk04,wk05,wk06,wk07,wk08,wk09,wk10,wk11,wk12,wk13]
print con[0], show_grade
copy = show_grade
n = 0
while n < 13:
if copy[n] == 'A':
copy[n] = 4.0
elif copy[n] == 'B':
copy[n] = 3.0
elif copy[n] == 'C':
copy[n] = 2.0
elif copy[n] == 'D':
copy[n] = 1.0
elif copy[n] == 'F':
copy[n] = 0.0
elif copy[n] == 'X':
copy[n] = 0.0
elif copy[n] == 'LOA':
copy[n] = "LOA"
else:
copy[n] = 0.0
n=n+1
show_score = copy
print con[1], show_score
raw_input()
|
def power(x,y):
result=1
i=0
while i<y:
result=result*x
i=i+1
return result
def fact(n):
i=1
fact = 1
while i <= n:
fact=fact*i
i=i+1
return fact
list=[]
sum=0
i=0
while i == 0:
if i == 0:
n=input('input n: ')
r=input('input r: ')
p=input('input p: ')
perRep = power(n,r)
perWR = fact(n) / fact(n-r)
comWR = (perWR) / fact(r)
comRep = fact(n+r-1) / fact(n-r) / fact(r)
n=float(n)
r=float(r)
bd = p**r * (1-p)**(n-r)
bd = bd * comWR
list.append(bd)
sum=sum+bd
print "answer is ",bd
print "past history is ",list
print "sum of all records is ", sum
if n == 0:
i=1
raw_input('exit')
|
joinedCodeList = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'
codeList = list(joinedCodeList)
pointList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
pointList = pointList + pointList
i=0
while i == 0:
rawMsg = raw_input('Type in the word or q to exit: ')
if rawMsg == 'q':
i=1
msg = list(rawMsg)
points=0
n=0
while n < len(msg):
o=0
while o < len(codeList):
if msg[n] == codeList[o]:
points=points+pointList[o]
print 'The letter '+msg[n]+" is "+str(pointList[o])+" points."
o=o+1
n=n+1
print "The word "+rawMsg+" is "+str(points)+" points."
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Lesson 3.2: Use Functions
# Mini-Project: Secret Message
# Your friend has hidden your keys! To find out where they are,
# you have to remove all numbers from the files in a folder
# called prank. But this will be so tedious to do!
# Get Python to do it for you!
# Use this space to describe your approach to the problem.
#
###My solution
#import osx functions
#
#liste de fichiers
#for every elements in list :
# if un des deux premiers caractère est un chiffre, retire
# OU retir les deux premiers
#
import os
import sys
def rename_files():
# (1) get file names from a folder
file_list_before = os.listdir("/Users/camille/Google Drive/Udacity/Stage 3_Use other people code/3.2.2_images")
file_list_after = []
print (file_list_before)
# (2) for each file, rename filename
os.chdir("/Users/camille/Google Drive/Udacity/Stage 3_Use other people code/3.2.2_images")
for file_name in file_list_before:
print "name before : " + str(file_name)
renamed = file_name.translate(None,"0123456789")
os.rename(file_name,renamed)
print "name after : " + str(renamed)
print (file_list_after)
rename_files() |
"""
matrix transform with successive blocks of columns
"""
def matrixElementsSum(matrix):
def matrix_transform(matrix):
idx_blk = []
for i in range(0, len(matrix)):
for j in range(0, len(matrix[0])):
#print(matrix[i][j])
if matrix[i][j] == 0:
idx_blk.append(j)
if j in idx_blk:
matrix[i][j] = 0
return matrix
transform = matrix_transform(matrix)
return sum(map(sum,transform))
if __name__ == "__main__":
def test(value, expect):
test = matrixElementsSum(value);
if test != expect:
print("MISTAKE %s != %s (value was %s)"%(test, expect, value))
else:
print("CORRECT %s == %s (value was %s)"%(test, expect, value))
print("TESTS:")
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
test(matrix, 9)
matrix = [[1, 1, 1, 0],
[0, 5, 0, 1],
[2, 1, 3, 10]]
test(matrix, 9)
"""
test([1, 3, 2, 1], False)
test([3], True)
test([1, 3, 2], True)
test([10, 1, 2, 3, 4, 5], True)
test([0, -2, 5, 6], True)
test([1, 2, 3, 4, 5, 3, 5, 6], False)
test([40, 50, 60, 10, 20, 30], False)
test([1, 2, 5, 3, 5], True)
test([1, 2, 3, 4, 99, 5, 6], True)
test([1, 2, 3, 4, 3, 6], True)
test([3, 5, 67, 98, 3], True)
test([1, 1, 2, 3, 4, 4], False)
""" |
"""
ThreeLetters
Given two integers A and B, return a string which contains A letters "a"
and B letters "b" with no three consecutive letters being the same.
"""
def threeletters(A,B):
str = []
while A > 0 and B > 0:
return "".join(str)
if __name__ == "__main__":
def test(value, expect):
test = firstunique(value)
if test != expect:
print("MISTAKE %s != %s (value was %s)"%(test, expect, value))
else:
print("CORRECT %s == %s (value was %s)"%(test, expect, value))
print("TESTS:")
test(0,0, "")
test(3,5, "")
test(1,3, "")
test(0,3, "")
test(1,1, "")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.