text stringlengths 37 1.41M |
|---|
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
print(d)
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
print(d)
from collections import OrderedDict
def ordered_dict():
d = OrderedDict()
d['foo'] = 2
d['bar'] = 1
d['spam'] = 3
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
print(key, d[key])
ordered_dict() |
def mergesort(arr):
if len(arr) > 1:
mid=len(arr)//2
L=arr[:mid]
R=arr[mid:]
mergesort(L)
mergesort(R)
i = j = k =0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i+= 1
k+= 1
while j < len(R):
arr[k] = R[j]
j+= 1
k+= 1
n=7
a="38 27 43 3 9 82 10"
arr=list(map(int,a.split()))
print("Given:", arr)
mergesort(arr)
print("Sorted:", arr)
|
Problem: https://www.hackerrank.com/challenges/median/problem
import math
import bisect
def print_median(f):
mid = math.floor(len(f) / 2)
if len(f) % 2 == 0:
val=sum(f[mid-1:mid+1]) / 2
print("{:.0f}".format(val) if val.is_integer() else val)
else:
print(f[mid])
def median(op, x):
if op == "a":
bisect.insort(f,x)
print_median(f)
else:
position = bisect.bisect_left(f, x)
if (position >= len(f) or f[position] != x):
print("Wrong!")
else:
del f[position]
print("Wrong!") if len(f) == 0 else print_median(f)
N = int(input())
f = []
for i in range(0, N):
a,num = input().strip().split(' ')
median(a, int(num))
|
a=int(input("enter a"))
try:
b=a/(a-3)
if a==3:
raise ZeroDivisionError
elif a>3:
raise NameError
except ZeroDivisionError:
print("division by 0 is not allowed")
except NameError:
print("type error")
else:
print(b) |
# Created by Jordan Leich on 10/8/2020
# Imports
import colors
import restart
# Global variables # TODO Add more food items here with the correct calorie amounts please
pizza = 275
apple = 95
banana = 105
potato = 165
wing = 102
spaghetti = 221
burger = 354
grilled_cheese = 700
pie = 95
cake = 129
rice = 216
calories = 0
total_cals = 0
user_weight = 0
def counter():
"""Main calorie counter that loops based on the number of food items the user has ate"""
global total_cals, calories
user_items = int(input('How many different food items have you ate today? '))
print()
if user_items <= 0:
print(colors.red + 'Error! Please enter a valid number!\n', colors.reset)
counter()
else:
i = 0
while i < user_items:
food_item = str(input('Enter the name of an item you ate today or type help for a list of valid food '
'names: '))
print()
if food_item.lower() == 'help':
print(colors.yellow + '''pizza = 275 calories
apple = 95 calories
banana = 105 calories
potato = 165 calories
wing = 102 calories
spaghetti = 221 calories
burger = 354 calories
grilled_cheese = 700 calories
pie = 95 calories
cake = 129 calories
rice = 216 calories\n''', colors.reset)
counter()
food_quantity = int(input('Quantity of this item ate: '))
print()
i += 1
if food_item.lower() == 'pizza':
calories = pizza * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'apple':
calories = apple * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'banana':
calories = banana * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'potato':
calories = potato * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'wing' or food_item.lower() == 'wings':
calories = wing * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'spaghetti':
calories = spaghetti * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'hamburger' or food_item.lower() == 'burger':
calories = burger * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'grilled cheese':
calories = grilled_cheese * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'pie':
calories = pie * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'cake':
calories = cake * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
elif food_item.lower() == 'rice':
calories = rice * food_quantity
total_cals = total_cals + calories
if total_cals >= 3500:
print(colors.red + 'Be careful! Your calorie total for the day is getting too high: ' + str(
total_cals), '\n', colors.reset)
else:
print(colors.green + 'Calories total: ' + str(total_cals), '\n', colors.reset)
else:
print(colors.red + 'Invalid food name provided! Hint: you can type hint for a list of valid food '
'names.\n', colors.reset)
counter()
print(colors.green + 'Your final calorie total is: ', str(total_cals), '\n', colors.reset)
restart.restart()
def user_weights():
"""Used to display the avg and recommended amounts of calories to the user"""
print(colors.green + 'The average and healthy amount of calories for a person is about 2100 or less calories per '
'day.\n',
colors.reset)
if '124' >= str(user_weight) >= '1':
print('Your recommended amount of calories to consume per day is 1,600 or less calories per day.\n')
counter()
elif str(user_weight) >= '125' or str(user_weight) <= '200':
print('Your recommended amount of calories to consume per day is 2700 or less calories per day.\n')
counter()
elif str(user_weight) >= '300':
print('Your recommended amount of calories to consume per day is 3764 or less calories per day.\n')
counter()
else:
print(colors.red + 'User weight error found! Restarting...\n' + colors.reset)
restart.restart()
def start():
"""Beginning of the program"""
weight = int(input('How much do you weigh in pounds? '))
print()
if weight <= 0:
print(colors.red + 'Error! Please enter a valid weight!\n', colors.reset)
restart.restart()
elif weight >= 400:
print(colors.red + 'Sorry! This weight amount is too high to record right now!\n', colors.reset)
restart.restart()
else:
user_weights()
"""starts the beginning of the program"""
start()
|
import random
def multiple(var1, var2, var5, n):
if n % 10 == 1:
return var1
if n % 10 in [2, 3, 4]:
return var2
if n % 10 in [5, 6, 7, 8, 9, 0]:
return var5
def palochka(n):
if n % 4 == 1:
z = random.randint(1, 3)
else:
z = (n % 4 + 4 - 1) % 4
return z
n = random.randint(15, 170)
while n > 0:
n -= palochka(n)
if n <= 0:
print('вы победили')
exit(0)
print("осталось ", n, " ", multiple("палочка", "палочки", "палочек", n), ". ваш ход:")
n -= int(input())
print('вы проиграли')
|
import tkinter
from math import *
SCREEN_SIZE = (600, 600)
def xs(x):
return SCREEN_SIZE[0] // 2 + x
def ys(y):
return SCREEN_SIZE[1] // 2 - y
main = tkinter.Tk()
canvas = tkinter.Canvas(main, bg='white', height=600, width=600)
a = int(input())
alpha = int(input())
def square(alpha,x1,y1):
r=2*a*(1-cos(alpha))
x=r*cos(alpha)
y=r*sin(alpha)
canvas.create_line((xs(x1), ys(y1)), xs(x), ys(y), fill='black')
alpha+=0.05
main.after(10, square, alpha,x,y)
square(alpha,0,0)
canvas.pack()
main.mainloop() |
sqr = []
for x in range(5):
sqr.append(x**2)
print(sqr)
cubes = list(map(lambda x: x*3, range(5)))
print(cubes)
cubes2 = [x**3 for x in range(10)]
print(cubes2)
|
def isPrime(num):
k = 0
if num > 1:
for i in range(2, num):
if num % i == 0:
k += 1
if k > 0:
print("No Prime")
else:
print("prime")
else:
print("invalid no.")
isPrime(int(input("Enter an integer:")))
|
"""Everything related with the network."""
from typing import Iterable
from .auxiliary_functions import print_with_asterisks
from .node import Node, SimulationNode
from .link import Link, SimulationLink
class Network:
"""Represents a Wireless Sensor Network formed by nodes and links."""
def __init__(self, nodes: Iterable[Node], links: Iterable[Link]) -> None:
self.nodes = sorted(nodes, key=lambda node: node.address)
self.links = links
@print_with_asterisks
def display_summary(self) -> None:
"""Shows a description of the network."""
print('>> Network summary')
print('> Nodes [node address, node name]:')
for node in self.nodes:
print(f'{node.address}, {node.name}')
print('> Links [address node 1, address node 2]:')
for link in self.links:
print(f'{link.nodes[0].address}, {link.nodes[1].address}')
class SimulationNetwork(Network):
"""Extends Network class in order to simulate."""
def __init__(self, simulation_nodes: Iterable[SimulationNode], simulation_links: Iterable[SimulationLink]):
super().__init__(simulation_nodes, simulation_links)
|
from math import floor
valor = float(input())
dias_atraso = int(input())
multa = valor * 0.02
juros = valor * (0.033/100) * dias_atraso
valor_total = valor + multa + juros
pag_min = valor_total * 0.1 # incoerencia com exemplo
print("Valor: R$", format(valor,".2f"))
print("Multa: R$", format(multa,".2f"))
print("Juros: R$", format(juros,".2f"))
print("Valor total: R$", format(valor_total,".2f") )
#print("Valor minimo para renegociacao: R$", pag_min)
#print("Valor minimo para renegociacao: R$", format(floor(pag_min),".2f"))
print("Valor minimo para renegociacao: R$", format((pag_min),".2f"))
|
def mars():
a=[1,2,3,4,5,6,7,8,9,10]
dup=[]
sack=[]
sack2=[]
b=[i for i in a if i not in dup]
print("All stones on Mars : ",a)
print("")
n = int(input("Enter number of elements : "))
print("")
for i in range(0, n):
ele = int(input("Duplicate stone no. {} : ".format(i+1)))
dup.append(ele)
b=[i for i in a if i not in dup]
print("")
print("Duplicate stones on Earth : ",dup)
print("")
print("Remaining stones : ",b)
m=max(b)
for i in b:
for j in b[1:]:
for k in b[2:]:
for x in b[3:]:
if i+j+k+x<m:
sack.extend(([[i,j,k,x]]))
elif i+j+k<=m:
sack.extend(([[i,j,k]]))
elif i+j<=m:
sack.extend(([[i,j]]))
print("")
max_cap=max(sack, key=len)
for p in sack:
if len(max_cap)==len(p):
suck.append(p)
res=[]
for i in sack2:
if i not in res:
res.append(i)
print ("Maximum possible combinations of stones : ",str(res))
return res
mars()
|
# Example 1, Import a python module with python interpreter:
# Put this in /home/el/foo/fox.py:
def what_does_the_fox_say():
print("vixens cry")
# Get into the python interpreter:
# dkm@glitch:/home/el/foo$ python
# Python 2.7.3 (default, Sep 26 2013, 20:03:06)
# >>> import fox
# >>> fox.what_does_the_fox_say()
# vixens cry
# >>>
# You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within fox.py.
# -------------------------------------------------------
# Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:
# Put this in /home/el/foo2/mylib.py:
def moobar():
print("hi")
# Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py")
moobar()
# run the file:
# el@apollo:/home/el/foo$ python main.py
# hi
# The function moobar was imported from mylib.py and made available in main.py
# -------------------------------------------------------
# Example 3, Use from ... import ... functionality:
# Put this in /home/el/foo3/chekov.py:
def question():
print "where are the nuclear wessels?"
# Put this in /home/el/foo3/main.py:
from chekov import question
question()
# Run it like this:
# el@apollo:/home/el/foo3$ python main.py
# where are the nuclear wessels?
# If you defined other functions in chekov.py, they would not be available unless you import *
# -------------------------------------------------------
# Example 4, Import riaa.py if it's in a different file location from where it is imported
# Put this in /home/el/foo4/stuff/riaa.py:
def watchout():
print("computers are transforming into a noose and a yoke for humans")
# Put this in /home/el/foo4/main.py:
import sys
import os
sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
from riaa import *
watchout()
# Run it:
# el@apollo:/home/el/foo4$ python main.py
# computers are transforming into a noose and a yoke for humans
# That imports everything in the foreign file from a different directory.
# -------------------------------------------------------
# Example 5, use os.system("python yourfile.py")
import os
os.system("python yourfile.py")
# -------------------------------------------------------
# Example 6, import your file via piggybacking the python startuphook:
# Update: This example used to work for both python2 and 3, but now only works for python2.
# python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers,
# using it to impolitely inject their code into the global namespace, before all user-defined programs.
# If you want this to work for python3, you'll have to get more creative.
# If I tell you how to do it, python developers will disable that feature set as well, so you're on your own.
# See: https://docs.python.org/2/library/user.html
# Put this code into your home directory in ~/.pythonrc.py
class secretclass:
def secretmessage(cls, myarg):
return myarg + " is if.. up in the sky, the sky"
secretmessage = classmethod( secretmessage )
def skycake(cls):
return "cookie and sky pie people can't go up and "
skycake = classmethod( skycake )
# Put this code into your main.py (can be anywhere):
import user
msg = "The only way skycake tates good"
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")
# Run it, you should get this:
# $ python main.py
# The only way skycake tates good is if.. up in the sky,
# the skycookie and sky pie people can't go up and have the sky pie! SKYCAKE!
# If you get an error here: ModuleNotFoundError: No module named 'user' then it means you're using python3,
# startuphooks are disabled there by default.
# Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py Send along your up-boats.
# -------------------------------------------------------
# Example 7, Most Robust: Import files in python with the bare import command:
# Make a new directory /home/el/foo5/
# Make a new directory /home/el/foo5/herp
# Make an empty file named __init__.py under herp:
# el@apollo:/home/el/foo5/herp$ touch __init__.py
# el@apollo:/home/el/foo5/herp$ ls
# __init__.py
# Make a new directory /home/el/foo5/herp/derp
# Under derp, make another __init__.py file:
# el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
# el@apollo:/home/el/foo5/herp/derp$ ls
# __init__.py
# Under /home/el/foo5/herp/derp make a new file called yolo.py Put this in there:
def skycake():
print("SkyCake evolves to stay just beyond the cognitive reach of " + "the bulk of men. SKYCAKE!!")
# The moment of truth, Make the new file /home/el/foo5/main.py, put this in there;
from herp.derp.yolo import skycake
skycake()
# Run it:
# el@apollo:/home/el/foo5$ python main.py
# SkyCake evolves to stay just beyond the cognitive reach of the bulk of men. SKYCAKE!!
# The empty __init__.py file communicates to the python interpreter that the developer intends this directory to be an importable package.
# If you want to see my post on how to include ALL .py files under a directory see here: https://stackoverflow.com/a/20753073/445131
|
def solution(s):
answer = True
bracketlist = []
for bracket in s:
if bracket == "(":
bracketlist.append(bracket)
continue
if bracket == ")":
if len(bracketlist) == 0:
answer = False
continue
else:
bracketlist.pop()
continue
if len(bracketlist) != 0:
answer = False
if answer == True:
return True
else:
return False
print('Hello Python')
print(solution("(())")) |
def isExpansable(board, level):
next = False
nextBoard = [[0 for x in range(len(board[0]) - 1)] for y in range(len(board) - 1)]
for y in range(len(board) - 1):
for x in range(len(board[0]) - 1):
if board[y][x] == 1 and board[y+1][x] == 1 and board[y][x+1] == 1 and board[y+1][x+1] == 1:
next = True
nextBoard[y][x] = 1
if next:
return isExpansable(nextBoard, level + 1)
else:
return level*level
def solution(board):
sum = 0
for y in range(len(board)):
for x in range(len(board[0])):
sum += board[y][x]
if sum == 0:
answer = 0
else:
answer = isExpansable(board, 1)
return answer
|
#Faça um Programa para uma loja de tintas.
# O programa deverá pedir o tamanho em metros quadrados
# da área a ser pintada. Considere que a cobertura
# da tinta é de 1 litro para cada 6 metros quadrados
# e que a tinta é vendida em latas de 18 litros,
# que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00.
# Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações:
# comprar apenas latas de 18 litros;
# comprar apenas galões de 3,6 litros;
# misturar latas e galões, de forma que o desperdício de tinta seja menor.
# Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias.
def menu_inicial():
print('Programa para Loja de Tintas')
print('1. Apenas latas de 18 litros')
print('2. Apenas galões de 3,6 litros')
print('3. Mistura de latas e galões')
def latas():
metros = float(input("Valor tamanho em metros quadrados: "))
litros = round(metros / 6)
latas = round(litros / 18)
#litros = round(metros / 6)
#latas = round(litros / 18)
valorlatas = latas * 80
print(f"Devera utilizar {latas:.2f} latas")
print(f'Valor de latas equivale a R$:{valorlatas:.2f}')
def galoes():
metros = float(input("Valor tamanho em metros quadrados: "))
litros = round(metros / 6)
galao = round(litros / 3.6)
#litros = round(metros/6)
#galao = round(litros / 3.6)
valorgalao = galao * 25
print(f"Devera utilizar {galao::.2f} latas")
print(f'Valor de galões equivale a R$:{valorgalao:.2f}')
def mistura():
metros = float(input("Valor tamanho em metros quadrados: "))
litros = round(metros/6)
mistura = round(litros * 0.10)
#mistura = round((litros / 18) + (litros))
print(f'Devera utilizar {mistura:.2f} de latas')
if __name__=='__main__':
menu_inicial()
escolha = input('Escolha o tipo de compra que deseja realizar: ')
if escolha == '1':
latas()
if escolha == '2':
galoes()
if escolha == '3':
mistura()
|
#Escreva um programa que mostre de 1 até 50 na tela.
''' x=1 #contador
while x<=50:
print(x)
x+=1 #incrementamos o nosso contador a cada laço
'''
for num in range(1,51):
print(num) |
#Faça um programa para a leitura de duas notas parciais de um aluno.
#O programa deve calcular a média alcançada por aluno e apresentar:
#A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
#A mensagem "Reprovado", se a média for menor do que sete;
#A mensagem "Aprovado com Distinção", se a média for igual a dez.
''' nota1=float(input('Nota 1: \n'))
nota2=float(input('Nota 2: \n'))
media=(nota1+nota2)/2
print(f'A média das notas {nota1} e {nota2} é {media}')
Solução 2
nota1=float(input('Nota 1: \n'))
nota2=float(input('Nota 2: \n'))
print(f'A média das notas {nota1} e {nota2} é {(nota1+nota2)/2}')
'''
valor1 = float(input("Digite a primeira nota : "))
valor2 = float(input("Digite a segunda nota : "))
media = (valor1 + valor2) /2
if media >= 7 and media < 10:
print ("Aluno aprovado")
elif media == 10:
print ("Aluno aprovado com Distinção")
else:
print ("Aluno reprovado")
|
#Faça um programa que peça a base
#e a altura de um retângulo e calcule
#e mostre na tela a área e o perímetro.
base=float(input('Digite a base: '))
altura=float(input('Digite a altura: '))
area=base*altura
perimetro=2*base+2*altura
print(f'O retângulo digitado tem base {base} e altura {altura}.')
print(f'A área deste retângulo é: {area}')
print(f'O perímetro deste retângulo é: {perimetro}')
|
var = float( input("Digite um numero: ") )
enesimo = (var * (var + 1) * (var + 2 ))
print(enesimo) |
n=int (input("Digite um valor : "))
for i in range (1,11):
print(f"{i} x {n} = {i*n}")
#O range faz a repeticao |
cedulas = [200.0, 100.0, 50.0, 20.0, 10.0, 5.0, 2.0, 1.0, 0.50, 0.25, 0.10, 0.05, 0.01]
def qnt_cedulas(valor: float) -> None:
'''Função que imprime a quantidade de cédulas para um dado valor.
Argumentos:
-- valor (float): valor informado para o cálculo da quantidade de cédulas.
'''
for cedula in cedulas:
qnt, resto = int(valor/cedula), valor % cedula
print(f'A quantidade em {"moedas" if cedula < 1 else "cédulas"} seria: {qnt} com resto {resto}')
def menu_principal():
'''Função que imprime o menu principal'''
valor = float(input('Digite um valor a ser calculado: '))
qnt_cedulas(valor)
if __name__ == '__main__':
menu_principal() |
'''Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c.
O programa deverá pedir os valores de a, b e c e fazer as consistências,
informando ao usuário nas seguintes situações:
Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;
Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;
O primeiro teste que fazemos é em relação ao coeficiente a. Se for 0, não é uma equação do segundo grau e acaba o programa.
Se for diferente de 0, cai no else, que é onde todo nosso programa vai funcionar. Primeiro, dentro do else, pedimos o valor dos coeficientes b e c.
Agora, vamos calcular o delta.
Em Python, fica assim: delta = b*b - (4*a*c)
Agora vamos testar o delta, dentro de um if aninhado no else anterior.
Se for menor que 0, encerramos o programa dizendo que as raízes são imaginárias.
Em seguida, usamos um elif para testar se delta for 0, se sim valor da raiz será:raiz = -b / (2*a)
Por fim, se não é menor que 0 e o delta não é 0, é porque vai ser sempre maior que 0. Essa condição cai no else aninhado, onde calculamos as raízes assim:
raiz1 = (-b + math.sqrt(delta) ) / (2*a)
raiz2 = (-b - math.sqrt(delta) ) / (2*a)
'''
import math
print('Equaçao do 2o grau da forma: ax² + bx + c')
def menu_inicial():
a = int( input('Coeficiente a: ') )
if(a==0):
print('Se a=0, não é equação do segundo grau.')
else:
b = int( input('Coeficiente b: ') )
c = int( input('Coeficiente c: ') )
delta = b*b - (4*a*c)
if delta<0:
print('Delta menor que 0. Raízes inexistentes. ')
elif delta==0:
raiz = -b / (2*a)
print('Delta=0 , raiz = ',raiz)
else:
raiz1 = (-b + math.sqrt(delta) ) / (2*a)
raiz2 = (-b - math.sqrt(delta) ) / (2*a)
print('Raizes: ',raiz1,' e ',raiz2)
|
#Faça um programa para uma loja de tintas.
#O programa deverá pedir o tamanho em metros quadrados
#da área a ser pintada. Considere que a cobertura
#da tinta é de 1 litro para cada 3 metros quadrados
#e que a tinta é vendida em latas de 18 litros,
#que custam R$ 80,00. Informe ao usuário a quantidades
#de latas de tinta a serem compradas e o preço total.
#% == resto
#round = arredondamento
#
metros = float(input("Valor tamanho em metros quadrados: "))
litros = round(metros/3)
latas = round(litros / 18)
if latas % 18 != 0:
latas += 1
total = latas * 80
print (f"Sera utilizado: {latas} o preco total sera de R$: {total:.2f}")
#print(f'+ Salario Bruto : R$ {salariobruto:.2f}') |
valor1 = float(input("Digite o primeiro valor: "))
valor2 = float(input("Digite o segundo valor: "))
valor3 = float(input("Digite o terceiro valor: "))
if valor1 > valor2 and valor3:
print("O primeiro número digitado é o maior: ", valor1)
elif valor2 > valor1 and valor3:
print("O segundo número digitado é o maior: ", valor2)
elif valor3 > valor1 and valor2:
print("O terceiro número digitado é o maior: ", valor3)
|
import RPi.GPIO as GPIO
import time
sensor_input = 36
led = 40
ledstate = False
#set numbering mode for the program
# GPIO.setmode(GPIO.BOARD)
# GPIO.setup(sensor_input, GPIO.IN,initial=0)
# GPIO.setup(led, GPIO.OUT,initial=0)
#this method will be invoked when the event occurs
def switchledstate(channel):
global ledstate
global led
ledstate = not(ledstate)
GPIO.output(led,ledstate)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor_input ,GPIO.IN, GPIO.PUD_UP)
GPIO.setup(led, GPIO.OUT, initial=ledstate)
# adding event detect to the switch pin
GPIO.add_event_detect(sensor_input, GPIO.BOTH, switchledstate, 600)
try:
while(True):
#to avoid 100% CPU usage
time.sleep(1)
except KeyboardInterrupt:
#cleanup GPIO settings before exiting
GPIO.cleanup() |
#!/usr/bin/python3
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self = self + other
return self
def __sub__(self, other):
if type(other) == Vector:
return Point(self.x - other.x, self.y - other.y)
if type(other) == Point:
return Vector(self.x - other.x, self.y - other.y)
raise TypeError(type(other) + " cannot be subtracted from a Point")
def __isub__(self, other):
if type(other) == Vector:
self = self - other
return self
raise TypeError("Point - " + {type(other)} + " would not return a Point")
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
self.magnitude = sqrt(x ** 2 + y ** 2)
def __add__(self, other):
if type(other) == Vector:
return Vector(self.x + other.x, self.y + other.y)
raise TypeError("Only a Vector can be added to another Vector")
def __radd__(self, other):
return self + other
def __iadd__(self, other):
self = self + other
return self
def __sub__(self, other):
if type(other) == Vector:
return Vector(self.x - other.x, other.y - self.y)
raise TypeError("Only a Vector can be subtracted from another Vector")
def __rsub__(self, other):
if type(other) == Point:
return Point(other.x - self.x, other.y - self.y)
if type(other) == Vector:
return Vector(other.x - self.x, other.y - self.y)
raise TypeError("A Vector can only be subtracted from another Vector or a Point")
def __isub__(self, other):
if type(other) == Vector:
self = self - other
return self
raise TypeError("Only a Vector can be subtracted from another Vector")
def __mul__(self, other):
if type(other) == int or type(other) == float:
return Vector(self.x * other, self.y * other)
raise TypeError("Only a number can be multiplied with a Vector")
def __rmul__(self, other):
return self * other
def __imul__(self, other):
self = self * other
return self
def __neg__(self):
return Vector(-self.x, -self.y)
def __abs__(self):
return Vector(abs(self.x), abs(self.y))
def __invert__(self):
return -self
def unitVect(self):
return Vector(self.x / self.magnitude, self.y / self.magnitude)
class Circle:
def __init__(self, pos, r):
self.pos = pos
self.r = r
def __add__(self, other):
return Circle(self.pos + other, self.r)
def __iadd__(self, other):
self = self + other
return self
def __sub__(self, other):
if type(other) == Vector:
return Circle(self.pos - other, self.r)
if type(other) == int or type(other) == float:
return Circle(self.pos, self.r - other)
raise TypeError(type(other) + " cannot be subtracted from a Circle")
def __isub__(self, other):
self = self - other
return self
def __mul__(self, other):
if type(other) == int or type(other) == float:
return Circle(self.pos, self.r * other)
raise TypeError("Circle cannot be multiplied by " + type(other))
def __rmul__(self, other):
return self * other
def __imul__(self, other):
self = self * other
return self
class Rectangle:
def __init__(self, pos, height, width):
self.pos = pos
self.height = height
self.width = width
self.left = pos.x
self.right = pos.x + width
self.top = pos.y
self.bottom = pos.y + height
def __add__(self, other):
if type(other) == Vector:
return Rectangle(self.pos + other, self.length, self.width)
raise TypeError(type(other) + " cannot be added to Rectangle")
def __iadd__(self, other):
self = self + other
return self
def __sub__(self, other):
if type(other) == Vector:
return Rectangle(self.pos - other, self.length, self.width)
raise TypeError(type(other) + " cannot be subtracted from Rectangle")
def __isub__(self, other):
self = self - other
return self
def __mul__(self, other):
if type(other) == int or type(other) == float:
return Rectangle(self.pos, self.length * other, self.width * other)
raise TypeError("Rectangle cannot be multiplied by " + type(other))
def __imul__(self, other):
self = self * other
return self
|
"""
Greg Lundberg
94283312
1/23/20
truffle manager is state of the art inventory management for the truffle
industry - disguised as exercise in functional decomposition.
parallel arrays of items and corresponding quantities are passed in. a main
menu is displayed, prompting the user to select among options to Order, Restock
or View the inventory. inventory data is used to generate submenus in which
item quantities are adjusted.
a set of base functions is created to handle menu display, user input,
input validation. these are composed in get_opt(), which provides the menus
with a single function to display their options and return a valid selection
from the user.
"""
items = ['Milk chocolate', 'Dark chocolate', 'Hazelnut']
quantities = [1000, 1000, 1000]
def truffle_man(items,quantities):
options = ['ORDER', ' RESTOCK', ' PRINT', ' QUIT']
opt = get_opt(options, lambda x: 0 <= x <= len(options))
if opt == 1:
order(items, quantities)
elif opt == 2:
restock(items, quantities)
elif opt == 3:
print_inventory(items, quantities)
else:
return items, quantities
# subtract quantity per order
def order(items, quantities):
opt = get_opt(items, lambda x: 1 <= x <= len(items)) - 1
num = get_opt(None, lambda x: 1 <= x, f'How many of {items[opt]}? ')
if num <= quantities[opt]:
quantities[opt] -= num
print('Your order was successfully placed.\n')
else:
print("I'm sorry, your order could not be placed.\n")
truffle_man(items, quantities)
# replenish quantity per order
def restock(items, quantities):
opt = get_opt(items, lambda x: 1 <= x <= len(items)) - 1
num = get_opt(None, lambda x: 1 <= x, f'How many of {items[opt]}? ')
quantities[opt] += num
print('That item has been restocked.\n')
truffle_man(items, quantities)
# print table of inventory
def print_inventory(items, quantities):
print('\n{:<20}{:<20}'.format('Item', 'Quantity'))
for i in range(len(items)):
print(f'{items[i]:20}{quantities[i]:<20}')
truffle_man(items, quantities)
# composed function to handle menu display, input, validation
# returns 1-based index of menu options
def get_opt(options, validate_func, text='Please enter the number of your choice: '):
if options:
display(options)
# prompt until valid selection
opt = False
while opt is False:
opt = validate(prompt(text), validate_func)
return opt
# prints n string args one per line
# list args passed to menu generator
def display(*args):
for i in args:
if type(i) == list:
display_menu(i)
else:
print(i)
# prints numbered list as menu (1, 2...)
def display_menu(options):
for i in range(len(options)):
print(f'{i + 1}) {options[i]}')
# requests input from user
def prompt(text='Please enter the number of your choice: '):
return input(text)
# check validity of input. return valid integer, otherwise False
def validate(val, func):
val = int(val)
if func(val):
return val
else:
return False
truffle_man(items, quantities) |
def ReadHighScores():
with open("HighScores.txt", "r") as f:
lines = f.read().splitlines()
HighScoreLine = lines[-1]
f.close()
return(HighScoreLine)
def ReadPseudocodeGuide():
file = open("pseudocodeguide.txt", "r")
lines = file.readlines()
for line in lines:
print(line)
file.close()
def ReadWords():
file = open("words.txt", "r")
words = [word.strip() for word in file]
file.close()
return(words)
|
def find_message(text):
"""Find a secret message"""
message = ""
for n in range(0, len(text)):
if text[n].isupper():
message += text[n]
return message
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"
assert find_message("hello world!") == "", "Nothing"
assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"
assert find_message("A") == "A", "Letter A"
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import argparse
import pandas as pd
from lib.programme_data import *
def filter_data(all_data):
"""
Takes the data from SIMS and removes all students not in
block 1 of the current academic year.
This should remove any students on placement (block 1S),
doing a dissertation (block D1/D2) or repeating something (block 2)
"""
# Remove all students not from this academic year
YEAR_COLUMN = 'Acad Year'
THIS_YEAR = '2017/8'
filtered_data = all_data.loc[all_data[YEAR_COLUMN] == THIS_YEAR]
# Remove all students not currently in block 1 (so those doing placement or dissertation)
BLOCK_COLUMN = 'Block'
filtered_data = filtered_data.loc[filtered_data[BLOCK_COLUMN] == '1']
return filtered_data
def filter_students_by_status(all_data, status):
"""
Filter the data to all students with the given status
"""
# Select all students with the given registration status
STATUS_COLUMN = ' Reg Status'
return all_data.loc[all_data[STATUS_COLUMN] == status]
def group_and_count_by_status(all_data):
"""
Group by programme code and registration status and then
count how many of each combination there are
"""
grouped = all_data.groupby(['Course', ' Reg Status']).size()
grouped = grouped.sort_index()
return grouped
def print_full_breakdown(grouped_data, statuses_to_print):
"""
Dump a count of each programme and status to command line
"""
for prog_name in prog_names_short:
prog_codes = prog_name_short_2_prog_codes[prog_name]
total = 0
for prog_code in prog_codes:
if prog_code in grouped_data.index:
for status in statuses_to_print:
if status in grouped_data.loc[prog_code]:
total += grouped_data.loc[prog_code][status]
print('%s: %d - %s' % (prog_codes_2_prog_name_long[prog_code], grouped_data.loc[prog_code][status], status))
print('-----------------------------------------------------')
print('%s (all): %d' % (prog_name, total))
print('-----------------------------------------------------')
def print_full_breakdown_all_statuses(grouped_data):
print_full_breakdown(grouped_data, enrolment_statuses)
def print_full_breakdown_only_registered(grouped_data):
print_full_breakdown(grouped_data, ['Registered'])
def print_full_breakdown_only_registered_and_registered_no_id(grouped_data):
print_full_breakdown(grouped_data, ['Registered', 'Registered - Not Collected ID Card'])
def print_no_breakdown(grouped_data, statuses_to_print):
"""
Dump a count of each programme (grouped by 'real' programme)
and status to command line
"""
for prog_name in prog_names_short:
prog_codes = prog_name_short_2_prog_codes[prog_name]
total = 0
for status in statuses_to_print:
for prog_code in prog_codes:
if prog_code in grouped_data.index:
if status in grouped_data.loc[prog_code]:
total += grouped_data.loc[prog_code][status]
print('-----------------------------------------------------')
print('%s (all): %d' % (prog_name, total))
print('-----------------------------------------------------')
def print_no_breakdown_all_statuses(grouped_data):
print_no_breakdown(grouped_data, enrolment_statuses)
def print_no_breakdown_only_registered_and_registered_no_id(grouped_data):
print_no_breakdown(grouped_data, ['Registered', 'Registered - Not Collected ID Card'])
def print_no_breakdown_only_registered(grouped_data):
print_no_breakdown(grouped_data, ['Registered'])
def output_csvs(all_data):
"""
Write out csv files containing the registration status counts for
each programme code and also grouped by course title
"""
grouped = all_data.groupby('Course')[' Reg Status'].value_counts()
csv_data = grouped.unstack(fill_value=0)
csv_data = csv_data.reindex(prog_codes, fill_value=0)
breakdown_data = csv_data.rename(prog_codes_2_prog_name_long)
with open('enrolled_student_status_per_programme_breakdown_from_losop.csv', 'w') as output_file:
breakdown_data.to_csv(output_file)
no_breakdown_data = csv_data.groupby(prog_codes_2_prog_name_short).sum()
with open('enrolled_student_status_per_programme_from_losop.csv', 'w') as output_file:
no_breakdown_data.to_csv(output_file)
def create_breakdown_graphic(grouped_data):
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcdefaults()
mpl.rcParams['font.size'] = 16
mpl.rcParams['figure.figsize'] = (14,10)
mpl.rcParams['axes.grid'] = True
index = list(range(len(prog_codes)))
data = {}
for status in enrolment_statuses:
data[status] = []
for prog_code in prog_codes:
if prog_code in grouped_data.index:
if status in grouped_data.loc[prog_code]:
data[status].append(grouped_data.loc[prog_code][status])
else:
data[status].append(0)
else:
data[status].append(0)
fig, ax = plt.subplots()
bottom = [0]*len(prog_codes)
for i, status in enumerate(enrolment_statuses):
ax.bar(index, data[status], label=status, bottom=bottom)
bottom = [sum(v) for v in zip(bottom, data[status])]
ax.set_xticks(list(range(len(prog_codes))))
ax.set_xticklabels([prog_codes_2_prog_name_long[p] for p in prog_codes], rotation=90)
ax.set_ylim(top=max(bottom)+10)
ax.legend(loc='upper left', bbox_to_anchor=(0.1, 1.0), framealpha=0.5)
plt.savefig('enrolled_student_status_per_programme_breakdown_from_losop.png', bbox_inches='tight')
def create_no_breakdown_graphic(grouped_data):
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcdefaults()
mpl.rcParams['font.size'] = 16
mpl.rcParams['figure.figsize'] = (14,10)
mpl.rcParams['axes.grid'] = True
index = list(range(len(prog_names_short)))
data = {}
for status in enrolment_statuses:
data[status] = []
for prog_name in prog_names_short:
prog_codes = prog_name_short_2_prog_codes[prog_name]
total = 0
for prog_code in prog_codes:
if prog_code in grouped_data.index:
if status in grouped_data.loc[prog_code]:
total += grouped_data.loc[prog_code][status]
data[status].append(total)
fig, ax = plt.subplots()
bottom = [0]*len(prog_names_short)
for i, status in enumerate(enrolment_statuses):
ax.bar(index, data[status], label=status, bottom=bottom)
bottom = [sum(v) for v in zip(bottom, data[status])]
ax.set_xticks(list(range(len(prog_names_short))))
ax.set_xticklabels(prog_names_short, rotation=90)
ax.set_ylim(top=max(bottom)+10)
ax.legend(loc='upper left', bbox_to_anchor=(0.2, 1.0), framealpha=0.5)
plt.savefig('enrolled_student_status_per_programme_from_losop.png', bbox_inches='tight')
def main():
# read in filename as command line argument
parser = argparse.ArgumentParser(description='Analysing MSc numbers in SIMS')
parser.add_argument('-i', '--input', help='Input file to be analysed', required=True, action='store')
parser.add_argument('-b', '--breakdown', help='Breakdown by part/time & placement programme', action='store_true')
parser.add_argument('-r', '--registered', help='show fully registered students only', action='store_true')
parser.add_argument('-l', '--loose', help='show fully registered students and those who have registered but not collected ID card (if -r also provided)', action='store_true')
parser.add_argument('-g', '--graphics', help='create visualisations of the data', action='store_true')
parser.add_argument('-c', '--csv', help='output csv of enrolled status per programme', action='store_true')
args = parser.parse_args()
# open and read the input file
input_file = os.path.join(os.getcwd(), args.input)
with open(input_file, 'r') as raw_data_file:
sims_data = pd.read_csv(raw_data_file, header=5, index_col=False)
# restrict it to this academic year block 1
filtered_data = filter_data(sims_data)
grouped = group_and_count_by_status(filtered_data)
if not args.breakdown and not args.registered:
print_no_breakdown_all_statuses(grouped)
elif args.breakdown and not args.registered:
print_full_breakdown_all_statuses(grouped)
elif args.breakdown and args.registered and not args.loose:
print_full_breakdown_only_registered(grouped)
elif args.breakdown and args.registered and args.loose:
print_full_breakdown_only_registered_and_registered_no_id(grouped)
elif not args.breakdown and args.registered and not args.loose:
print_no_breakdown_only_registered(grouped)
elif not args.breakdown and args.registered and args.loose:
print_no_breakdown_only_registered_and_registered_no_id(grouped)
if args.graphics and args.breakdown:
create_breakdown_graphic(grouped)
elif args.graphics and not args.breakdown:
create_no_breakdown_graphic(grouped)
if args.csv:
output_csvs(filtered_data)
if __name__ == '__main__':
main()
|
# Question 6 Write a program that can output the following shape to the console:
# xxxxx
# xxxxx
# xxxxx
# xxxxx
# xxxxx
# Please ensure that you only have the following print statements within your application:
# print("x", end='')
# print("")
# You will need to use two loops for this to work.
rows = int(input("Please enter the number of rows for the rectangle:" + " " ))
columns = int(input("Please enter the number of columns for the rectangle:" + " "))
if rows == columns:
print("That's a square, try again")
rows = int(input("Please enter the number of rows for the rectangle:" + " " ))
columns = int(input("Please enter the number of columns for the rectangle:" + " "))
if rows != columns:
for x in range(rows):
for y in range(columns):
print('*', end = ' ')
print()
|
# Write a program to ask the user for numbers, and then print any repeating numbers in a list. Example:
# Enter a number: 5
# Enter a number: 2
# Enter a number: 6
# Enter a number: 98
# Enter a number: 7
# Enter a number: 6
# Enter a number: 5
# Enter a number: x
# Repeating numbers: [5, 6]
nums = []
while True:
num = input("Enter a number (press x to stop): ")
if num == 'x':
break
else:
nums.append(num)
repeat = []
for x in nums:
if nums.count(x) > 1:
repeat.append(x)
print("Repeating Numbers: ", repeat) |
# Take guesses from user for number between 1 and 25 and disply if greater/less than random number. User has 7 guesses.
# If number guessed correct, stop asking and show user the numbers they guessed
# If number less/more than then tell that add guess to list and tell how many guesses left
# num = 17 # user trying to guess (can this be a random generated number? - Yes found a random inbuilt option via google)
import random # random number generator
num = random.randint(1, 25)
guesslist = [] # list to hold guesses
guesses = 0 # number of guesses/chances
# get guess from user
print("Let's play a guessing game. I'm thinking of a number between 1 and 25, you have 7 chances to guess the number.")
guess = int(input("Enter your Guess: "))
guesslist.append(guess) #add guess to guesslist - before commencing while loop
guesses += 1 # add guess to guesses count - before commencing while loop
# while loop to commence the guessing game and compare each guess to the random number
while guesses < 7:
if guess == num: # if guess by user is same as num, break from loop, print win and tell how many guesses it took and what guesses were
print("Damn. You win!",'\n'"The number was indeed", num,'\n'"You guessed in",len(guesslist) ,"guesses",'\n'"Your guess log:",'\n',guesslist)
break
elif guess < num: # check if guess is less than num, if is, ask for another guess and tell how many guesses left
print("Nope, its greater than that",'\n'"You have ",str(7-(len(guesslist))), "guesses left!")
guess = (int(input("Enter your Guess: ")))
elif guess > num: # check if guess is more than num,if is, ask for another guess and tell how many guesses left
print("Nope, its less than that",'\n'"You have ",str(7-(len(guesslist))), "guesses left!")
guess = (int(input("Enter your Guess: ")))
guesslist.append(guess) # add guess to guesslist after each pass through the loop
guesses += 1 # add 1 to each guess try after each pass through the loop
if guesses == 7: # if 7 guesses used, ends loop with cheeky text and provides the correct num and what is in the guesslist
print("You have 0 guesses left!",'\n'"Ah Ha Ha Ha YOU LOSE!",'\n'"The number was",num, "you fool.",'\n'"Your guess log: ",'\n',guesslist)
|
import sys
def sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [i for i in arr if i < pivot]
equal = [ i for i in arr if i == pivot]
right = [ i for i in arr if i > pivot]
return sort(left) + equal + sort(right)
def trader(days, prices):
cost = 0
shares = 0
arr = sys.stdin.readlines()
tc = int(arr[0])
inputs = [i for i in arr[1:]]
# 2 lines per TC
for i in range(tc):
index = i * 2
days = inputs[index]
prices = [ int(x) for x in inputs[index+1].split(' ')]
print trader(days, prices)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 09:49:36 2018
@author: saras
"""
###Task 1 & 2#
#
#salary = {} #creates an empty directory
#
#salary['al'] = 20000
#salary['Sarika'] = 800000
#salary['Jenny'] = 700000
#print(salary)
#
#
###Task 2 - create own dictionary
#tel = {}
#tel = {'alf':111, 'bobby':222, 'calvin':333}
#print(tel)
#
##adding new entries
#tel['Martiena'] = 145
#tel['Mag'] = '281'
#print(tel)
#
##updating existing values
#tel['Mag'] = 2812
#print(tel)
#
#tel['Martiena'] = 821
#print(tel)
#
#
###Task 3 - accessing the dictionary
#print(tel['Mag'])
#
##deleting a key value pair
#del tel['bobby']
#print(tel)
#
#
###Task 4 - getting keys and values from a dictionary
#print(tel.keys())
#print(tel.values())
#
#
##cast to standardised list, looks the same when printed but can now do operations to it#
#list_of_tel_keys=list(tel.keys())
#
#list(tel.keys())[0]
#
#list_of_tel_values=list(tel.values())
#list(tel.keys())[0]
#
#
###Task 6 - how to avoid key errors, best to run tests like below:
#
#k = 'Sam'
#
#if k in tel:
# print(k, ':', tel[k])
#
#else:
# print(k, 'not found!')
#
##Mag is in the dictionary so her data will be printed#
#k = 'Mag'
#
#if k in tel:
# print(k, ':', tel[k])
#
#else:
# print(k, 'not found!')
#
#
###Task 7
#counts = {'a': 3, 'c': 1, 'b': 5}
#labels = list(counts.keys())
#labels.sort(key=lambda k:counts[k])
#print(labels)
#print(counts)
#counts['g']=8
#counts['f']=10
#counts['o']=20
#print(counts)
#
##Another example#
#tel = {}
#tel = {'alf':('March', 111), 'bobby':('June', 222), 'calvin':('Sept', 333), 'Martiena':('May', 821), 'Mag':('Nov', 281)}
#print(tel)
#
#labels = list(tel.keys())
#
#labels.sort(key=lambda k:tel[k])
#print(labels)
#
#tel_keys = list(tel.keys())
#
#tel_keys.sort(key=lambda k:tel[k][1])
#print (tel_keys)
#
#print(sorted(tel.items(), key=lambda kv:kv[1]))
#
#print(sorted(tel.items(), key=lambda kv:kv[0]))
#More examples#
metals = {'iron':(7.8, 12.5, 498), 'gold':(19.3, 32.1, 230), 'zinc':(7.13, 84.8, 879), 'lead':(11.4, 98.1, 384)}
print(metals)
#turns the tuples into lists#
metals_keys = list(metals.keys())
#
##sorts by share price accending#
#print(sorted(metals.items(), key=lambda kv:kv[1][1]))
#
###sorts by share price in reverse order#
#print(sorted(metals.items(), key=lambda kv:kv[1][1],reverse=True))
##
###sorts by share price in reverse order but only showing the keys#
#metals_keys.sort(key=lambda k:metals[k][1],reverse=True)
#print(metals_keys)
#
##sorting by experiment ascending#
#print(sorted(metals.items(), key=lambda kv:kv[1][2]))
#sorted(metals.items(),key=lambda kv:kv[1][1],reverse=True)
#sorted(metals.items(),key=lambda kv:kv[1][1],reverse=True)[2] |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 7 09:59:29 2019
@author: saras
"""
#Task 1
class Person:
def __init__(self,name,age,gender):
self.name = name
self.age = age
if gender == 'm':
self.isMale = True
elif gender == 'f':
self.isMale = False
else:
print("Gender not recognised!")
#Task 2
def greetingInformal(self):
print('Hi', self.name)
def greetingFormal(self):
if self.isMale:
print('Welcome, Mr', self.name)
else:
print('Welcome, Ms', self.name)
#Task 3
def greetingAgeBased(self):
if self.age < 18:
print('Welcome, young', self.name)
elif self.age > 60:
print('Welcome, venerable', self.name)
else:
self.greetingFormal()
#Task4
#class Wizard(Person):
# def greetingFormal(self):
# print('Welcome, Mr', self.name, end=' ')
# print('- you\’re a fine wizard!')
#Task 5 & 6
class Wizard(Person):
def __init__(self,name,age,gender):
Person.__init__(self,name,age,'m')
def greetingFormal(self):
print('Welcome, Mr', self.name, end=' ')
print('- you\’re a fine wizard!')
def spell(self):
print('Expelliarmus!')
p1 = Person('Harry',12,'m')
p2 = Person('Jean',22,'f')
p3 = Person('David',61,'m')
p1.greetingInformal()
p2.greetingInformal()
p3.greetingInformal()
p1.greetingFormal()
p2.greetingFormal()
p3.greetingFormal()
p1.greetingAgeBased()
p2.greetingAgeBased()
p3.greetingAgeBased()
p1 = Wizard('Harry',12,'m')
p1.greetingFormal()
p1.spell()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 15:38:15 2018
@author: saras
"""
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh? ")
print ("So, you're %r years old, %r tall and %r heavy." % (age, height, weight)) |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 8 17:05:23 2018
@author: Sara
"""
print ("You enter a dark room with two doors. Do you go through door #1, door #2 or door #3?")
door = input("> ")
if door == "1":
print ("There's a giant bear here eating a cheese cake. What do you do?")
print ("1. Take the cake.")
print ("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print ("The bear eats your face off. Good job!")
elif bear == "2":
print ("The bear eats your legs off. Good job!")
else:
print ("Well, doing %s is probably better. Bear runs away." % bear)
elif door == "2":
print ("You stare into the endless abyss at Cthulhu's retina.")
print ("1. Blueberries.")
print ("2. Yellow jacket clothespins.")
print ("3. Understanding revolvers yelling melodies.")
insanity = input("> ")
if insanity == "1" or insanity == "2":
print ("Your body survives powered by a mind of jello. Good job!")
else:
print ("The insanity rots your eyes into a pool of muck. Good job!")
elif door == "3":
print ("What do you think of this story?")
print ("1. It's so crazy I love it!")
print ("2. It's so strange what is the author on?!")
opinion = input("> ")
if opinion == "1":
print ("Ha ha you are just as crazy as the author - go home and get some rest!")
elif opinion == "2":
print ("Plot twist- you are the author mwahhhhaaa!!!")
else:
print ("Ah you are one of those who sits on the fence - that must hurt")
else:
print ("You stumble around and fall on a knife and die. Good job!") |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 5 16:33:16 2018
@author: saras
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 09:36:11 2018
@author: saras
"""
#Task 1 - Simple operations#
5 - 6
8 * 9
6 / 2
5 / 2
5.0 / 2
5%2
2 * (10 + 3)
2**4
#Task 2 - Variable practice#
age = 5
age = "almost three"
age = 29.5
age = "I really don't know!"
print(age)
age = "I don't know"
typeAge = type(age)
print(typeAge)
#Task 3 - Basic string manipulation#
print('hello' + 'world')
print("Joke" * 3)
print("Chen" + "3")
print("hello".upper())
print("GOODBYE".lower())
print("the lord of the rings".title())
print("Bob " * 3)
#print("Bob" + 3) #will produce an error as can only concatenate str (not "int") to str#
print("hello".upper())
print("GOODBYE".lower())
print("the lord of the rings".title())
print(("Bob \n") * 3)
print('\n')
print(("Bob \n") * 3)
s1='hello'+'world'
s2="Joke"*3
s3="5"
s1 = 'hello' + s2
s1 + s2 + s3
strExample = 'a-b-b-d-happy'
SplitStr = strExample.split('-')
print(SplitStr)
#Task 4 - Formatting#
age = 6
like = "painting"
age_discription = "My age is {} and I like {}.".format(age,like)
print("hello".upper())
print("hello".lower())
print("hello".title())
test = """s The 3 quote marks will hide this text
gffh
fhfhf
"""
print(10/3)
print(10%3)
#Homework#
a=1
a=a+1
print(a)
b = "hello"
print (b)
c = b.title()
print(b)
print(c)
d = "hello"
e = d.title()
print (d)
print (e)
name = "Dave"
f="Hello{0}!".format(name)
print (f)
name="Sarah"
print (f)
print (f*5)
print ("Hello World!")
print ("Hello Again")
print ("I like typing this.")
print ("This is fun.")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
|
class Circle:
def __init__(self,r_circle):
self.R = r_circle
def S_Circle(self):
print(self.R**2*3.14)
Circle_a = Circle(5)
Circle_a.S_Circle() |
list1=["flower","flight","flow"]
shortest_str = min(list1,key=len)
def prefix(list1):
for i,char in enumerate(shortest_str):
for other in list1:
if other[i]!=char:
return(shortest_str[:i])
print(prefix(list1))
|
list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i=0
j=1
score=0
n=len(list)
while n>0:
if list[i]>score:
print(list[i],"list[i]")
score=list[i]
print(list[i])
for number in list:
print(number, "number", list[j], "list[j]")
if number!=list[j]:
score+=number
print("score",score)
i+=1
n-=1
|
def practice():
string1 = "good"
string2 = "ogdo"
dict = {}
for char1 in string1:
if char1 in dict:
dict[char1] += 1
else:
dict[char1]=1
print(dict)
for char2 in string2:
if char2 not in dict:
return "false"
else:
dict[char2] -=1
print(dict)
for key,value in dict.items():
if value is 0:
print("True")
break
practice() |
nums=[1,2,3,4,5,6,7]
k=3
left=0
right=len(nums)-1
for i in range(k):
nums.insert(0,nums.pop())
print(nums)
# while k>0:
# print("left",nums[left])
# print("right",nums[right])
|
#First Section of Chapter
'''
def hello():
print('Howdy!')
print('Howdy!!!!!!')
print('Hello there.')
hello()
hello()
hello()
def hello(name, age, gender):
print('Hello, '+ name + age + gender)
hello('Cody', ' 24 ', ' Male')
hello('Emilee', ' 25 ', ' Female')
'''
#Second Section of Chapter
#1
import random
#2
def getAnswer(answerNumber):
#3
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidely so.'
elif answerNumber == 3:
return 'Yes.'
elif answerNumber == 4:
return 'Reply hazy, try again.'
elif answerNumber == 5:
return 'Ask again later.'
elif answerNumber == 6:
return 'Concentrate and ask again.'
elif answerNumber == 7:
return 'My replay is no.'
elif answerNumber == 8:
return 'Outlook not so good.'
elif answerNumber == 9:
return 'Very doubtful.'
elif answerNumber == 10:
return 'Hard No.'
#4
'''r = random.randint(1,10)
#5
fortune = getAnswer(r)
#6
print(fortune)
'''
print(getAnswer(random.randint(1,9)))
spam = print("Hello! ", end='')
None == spam
print(spam)
print("Cats", 'Dogs', 'mice')
print("Cats", 'Dogs', 'mice')
|
from spillebrett import Spillebrett
def main():
print("Oppgi dimensjoner på spillebrettet")
kolonner = int( input("Antall kolonner: ") )
rader = int( input("Antall rader: ") )
nyttSpill = Spillebrett(rader,kolonner)
nyttSpill.tegnBrett()
#naboer = nyttSpill.finnNabo(1,0)
while( input("Trykk [q] for aa avslutte\nTrykk [enter] for aa fortsette\n").lower() != "q" ):
nyttSpill.oppdatering()
nyttSpill.tegnBrett()
main()
|
def minFunksjon():
for x in range(2):
c = 2
print(c)
c += 1
b =10
b += a
print(b)
return(b)
def hovedprogram():
a = 42
b = 0
print(b)
b = a
a = minFunksjon()
print(b)
print(a)
hovedprogram()
'''
Først defineres funksjonen "minFunksjon" som ikke tar parameter.
Deretter defineres prosedyren "hovedprogram" som ikke tar parameter.
Så kalles "hovedprogram".
I "hovedprogram" opprettes variablene "a" og "b" med verdiene 42 og 0.
Variabelen "b" skrives så ut ved bruk av print før "b" settes lik "a".
Deretter kalles "minFunksjon".
"minFunksjon" starter med en for-løkke som vil eksekvere for hver "x" i rekken 0-1, altså 2 ganger.
Inne i løkken defineres variabelen "c" med verdien 2 og skrives deretter ut ved bruk av print.
Videre inkrementeres "c" med 1 og variabelen "b" defineres med verdien 10.
"b" førsøkes inkrementert med "a" som kun er definert i "hovedprogram". Dette vil generere en kjøretidsfeil.
'''
|
import math
def primeNumbers(n):
a=[]
bol=[]
for i in range(2,n+1):
a.append(i)
bol.append(1)
b=math.sqrt(n)
for i in a:
if i>b:
break
for j in range(i*i,n+1,i):
if bol[j-2]==1:
a.remove(j)
bol[j-2]=0
return a
#driver code
n=int(input("find prime numbers in range of :"))
print(primeNumbers(n))
|
from tkinter import *
import time
import random
tk = Tk()
canvas = Canvas(tk, width=1920, height=1080, background="grey")
canvas.pack()
def xy(event):
xm, ym = event.x, event.y
def task():
w=random.randint(1,1000)
h=random.randint(1,1000)
canvas.create_rectangle(w,h,w+150,h+150)
def callback(event):
if True:
print("clicked2")
# 'solve' is used here to stop the after... methods.
tk.after_cancel(solve)
canvas.bind("<Button-1>",callback)
solve = tk.after(1000,task)
# above and below tk.after is set to 'solve' a variable.
solve = tk.after(1000,task)
tk.mainloop()
|
def Knapsack(value, weight, count, maxWeight):
table = [[0]*(maxWeight+1) for i in range(count+1)]
#print(table)
for w in range( 1, maxWeight+1 ):
#print(w)
for i in range( 1, count+1 ):
one = table[i-1][w]
two = 0
if(w - weight[i-1] >= 0 ):
two = table[i-1][w-weight[i-1]] + value[i-1]
if one>two:
table[i][w] = one
else:
table[i][w] = two
#print(table)
return(table[count][maxWeight])
a = Knapsack([1,3,6,2],[4,2,6,1],4,8)
print(a)
|
#Sintaxe do dicionário
# Chave: Valor
meuDicionario = {
"nome": "francine",
"idade": 26
}
print("Mostrando o dicionário: ", meuDicionario)
#Acessando valor pela chave
print("Mostrando valor pela chave: ", meuDicionario['nome'])
#Acessando valor pelo método get()
print("Mostrando valor pela chave usando get(): ", meuDicionario.get('idade'))
#Alterando valor de um item específico
meuDicionario['nome'] = 'Fran'
print("Novo valor da chave nome: ", meuDicionario['nome'])
#Percorrendo um dicionário para retornar as chaves
for x in meuDicionario:
print("Percorrendo o dicionário para retornar chaves: ", x)
#Percorrendo um dicionário para retornar os valores
for x in meuDicionario:
print("Percorrendo o dicionário para retornar o valor: ", meuDicionario[x])
#Percorrendo um dicionário para retornar o valor com values()
for x in meuDicionario.values():
print("Percorrendo o dicionário para retornar o valor com values(): ", x)
#Percorrendo dicionário, mostrando chave e valor.
for x in meuDicionario:
print(x, meuDicionario[x])
#Verificar se existe a chave no dicionário
if 'idade' in meuDicionario:
print("Sim tem a chave idade no dicionário")
print("tamanho do dicionário: ",len(meuDicionario))
#Adicionando novo item no dicionário
meuDicionario['cpf'] = '22222222222'
print("Adicionando novo item: (chave e valor) ", meuDicionario)
#Removendo item com a função pop()
meuDicionario.pop('cpf')
print("Removendo item com função pop(): ", meuDicionario)
#Deletando item com a função pop()
del meuDicionario['idade']
print("Deletando item pela chave usando del: ", meuDicionario)
|
#while usamos enquanto a condição for verdadeira (loop infinito)
#comentei pq fica infinito, pode zikar teu computador.
#while i <= 6:
# print("loop infinito",i)
#while loop finito (com parada se satisfaz a condição)
i=0
while i<6:
print("loop elegante", i)
i=i+1
#while com loop finito e if com break para quebrar o laço de repetição(while)
x=0
while x<5:
print("loop mais elegante ainda", x)
if x==3:
break
x=x+1
|
from .task2utils import *
def task2(firstname, lastname, email, phone, birth, address, apt, city, state, zipcode):
phone = phone.split('-')
birth = birth.split('/')
email = email.split('@')
email = email[0].split('_')
phone1 = str(phone[0])
phone2 = str(phone[1])
phone3 = str(phone[2])
month = str(birth[0])
day = str(birth[1])
year = str(birth[2])
short_year = str(year[2]) + str(year[3])
address = address.split(' ')
numbers = [
[month, "birth month"],
[day, "birth day"],
[year, "birth year"],
[short_year, "birth year"],
[phone1, "phone"],
[phone2, "phone"],
[phone3, "phone"],
[zipcode, "zip code"]
]
words = [
[firstname.lower(), "first name"],
[lastname.lower(), "last name"],
[city.lower(), "city"],
[state.lower(), "state"]
]
email.extend(["email"])
words.append(email)
temp = []
for item in address:
item = str(item)
if item.isdigit():
numbers.append([item, "address"])
else:
temp.append(item.lower())
temp = ''.join(temp)
words.append([temp, "address"])
if apt != '':
numbers.append([apt, "apt #"])
passwords = create_list_of_passwords(words)
passwords.append(numbers)
return passwords
if __name__ == "__main__":
print('Please enter the following details to create your account.')
email = input('Email address: ')
firstname = input('First name: ')
lastname = input('Last name: ')
birth = input('Date of Birth (Format MM/DD/YYYY): ')
phone = input('Phone number (Format XXX-XXX-XXXX): ')
print('Mailing Address')
address = input('Street Information (Street number and name): ')
apt = input('Apartment Number (if applicable, else hit \'enter\' key): ')
city = input('City: ')
state = input('State: ')
zipcode = input('Zip Code: ')
passwords = task2(firstname, lastname, email, phone, birth, address, apt, city, state, zipcode)
#print(passwords)
for i in range(len(passwords) - 2):
print(passwords[i][0])
print("Any password which contains the following numbers:", passwords[len(passwords) - 1],
"(will be checked with Python's 'in' keyword)")
|
from HangmanTest import Game
game = Game()
while True:
print(game.play())
play_again = input("GAME FINISHED\nWould you like to try again? (T / F): ")
if play_again is "F":
break
elif play_again is "T":
continue
else:
print("That was not a valid answer")
# solution = "blablabla"
# display = []
# for char in solution:
# display.append(Letter(char))
#
# count = 0
# while display != solution:
#
# for letter in display:
# print(letter, end="")
#
# char = input("Guess a letter or the word: ")
# if char is solution:
# break
# if char < "a" or char > "z" or len(char) != 1:
# print("That is not a valid input")
# continue
#
# for letter in display:
# if char is letter.get_value():
# letter.discover()
# count += 1
#
# if count == len(solution):
# break
#
# print(solution, "was the word!!")
# print("YOU WIN") |
import sys
import numpy.linalg as linalg
def solve_matrix(A, b):
""" This will call the built in matrix solving utility in numpy and solve
the matrix equation A.x=b for x.
inputs
- A: The matrix generated in a separate function with coefficients of
temperature at each node
- b: The array of constants generated by a separate function
outputs
- temperature_array: The value of temperatures at each node at a given time
"""
temperature_array = linalg.solve(A, b)
return temperature_array
|
def counting_while(x):
i = 1
numbers = []
while i <= 500:
print "At the top i is %d" % i
numbers.append(i)
i += i
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
x = int(raw_input("Number?: "))
numbers = counting_while(x)
print "The numbers: "
for num in numbers:
print num
#extra credit
def counting_for(x):
i = 1
numbers = []
for i in range(x,8):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
x = int(raw_input("Number?: "))
numbers = counting_for(x)
print "The numbers: "
for num in numbers:
print num
|
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["They rally around the family",
"With pockets full of shells"])
my_sunshine = Song(["You are my sunshine",
"my only sunshine"])
d = my_sunshine
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
my_sunshine.sing_me_a_song()
d.sing_me_a_song()
|
#! /usr/bin/env python
"""
Author: Gary Foreman
Last Modified: January 18, 2015
Solution to Exercise 9 of Andrew Ng's Machine Learning course on OpenClassroom
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import os
K = 16 #number of means used for k-means algorithm
DATA_DIR = 'ex9Data/'
BIRD_SMALL = DATA_DIR + 'bird_small.tiff'
BIRD_LARGE = DATA_DIR + 'bird_large.tiff'
class K_Means(object):
def __init__(self, image_file_name):
self.image = plt.imread(image_file_name)
self.k_means = np.random.randint(0, 255, (K, 3))
def _nearest_means(self, image):
"""
Creates array c of size image containing the index of the nearest mean
"""
n = len(image)
c = np.empty((n, n), np.int8)
for i in xrange(n):
for j in xrange(n):
distances = np.empty(K)
for k in xrange(K):
distances[k] = np.linalg.norm(image[i,j] -
self.k_means[k])
c[i,j] = np.argmin(distances)
return c
def _means_update(self, c):
"""
Updates self.k_means by averaging the colors from self.image and their
nearest means given in c.
"""
for i in xrange(K):
c_i = c == i
n_i = np.sum(c_i)
if n_i > 0:
self.k_means[i] = np.sum(self.image *
np.dstack((c_i, c_i, c_i)),
axis=(0,1)) / n_i
def run(self, iter_max=100, atol=1e-7):
"""
Runs the k-means algorithm until convergence or until iter_max is
reached
"""
i = 0
epsilon = atol * 100.
while(epsilon > atol and i < iter_max):
k_means_old = np.copy(self.k_means)
c = self._nearest_means(self.image)
self._means_update(c)
epsilon = np.linalg.norm(np.sum(self.k_means - k_means_old, axis=1))
i += 1
def image_compress(self, image_file_name):
"""
Converts colors of image_file_name to colors in self.k_means. Use only
after running K_Means.run, otherwise, solution will be nonsensical.
"""
im_comp = plt.imread(image_file_name)
plt.imshow(im_comp)
plt.show()
plt.clf()
n = len(im_comp)
c = self._nearest_means(im_comp)
for i in xrange(n):
for j in xrange(n):
im_comp[i,j] = self.k_means[c[i,j]]
plt.imshow(im_comp)
plt.show()
plt.clf()
fn, ext = os.path.splitext(image_file_name)
outfile = '%s_kmeans%s' % (fn, ext)
plt.imsave(outfile, im_comp)
if __name__ == '__main__':
k_means = K_Means(BIRD_SMALL)
k_means.run()
k_means.image_compress(BIRD_LARGE)
|
"""This file implement generic Graph class and method.
The method naming convention follows princeton algorithm course (java) rather than PEP8.
"""
from collections import defaultdict
class Graph(object):
def __init__(self, v):
if not isinstance(v, int):
raise TypeError("v must be int.")
if v <= 0:
raise ValueError("v must be positive.")
self._v = v
self._e = 0
self._adj = defaultdict(set)
def addEdge(self, v, w):
for x in {v, w}:
if x >= self._v:
raise ValueError("Vertice {} is not in the Graph.".format(x))
if w not in self._adj[v]:
self._e += 1
self._adj[v].add(w)
self._adj[w].add(v)
def adj(self, v):
if v >= self.V:
raise ValueError("vertice not in Graph")
return list(self._adj[v])
@property
def V(self):
return self._v
@property
def E(self):
return self._e
def __str__(self):
for _, e in self._adj.items():
print(str(e))
@staticmethod
def degree(G, v):
"""
return the degree of vertex
Args:
G (Graph):
v (int):
Returns:
(int)
"""
return len(G.adj(v))
@staticmethod
def maxDegree(G):
return max(Graph.degree(G, v) for v in range(G.V))
@staticmethod
def averageDegree(G):
from statistics import mean
return mean(Graph.degree(G, v) for v in range(G.V))
@staticmethod
def numberOfSelfLoops(G):
count = 0
for v in range(G.V):
if v in G.adj(v):
count += 1
return count
class Digraph(Graph):
"""Directed Graph API"""
def __init__(self, v):
super(Digraph, self).__init__(v)
def addEdge(self, v, w):
for x in {v, w}:
if x >= self._v:
raise ValueError("Vertice {} is not in the Graph.".format(x))
if w not in self._adj[v]:
self._e += 1
self._adj[v].add(w)
class DepthFirstOrder(object):
"""Impletment Depth-first order (Topological Sorting)"""
def __init__(self, G):
"""
Args:
G (Digraph):
"""
from week2.dequeue import Deque
import numpy as np
self._reversePost = Deque()
self._visited = np.repeat(False, G.V)
for i in range(G.V):
if not self._visited[i]:
self.dfs(G, i)
def dfs(self, G, v):
"""
Args:
G (Digraph):
v (int):
Returns:
None
"""
self._visited[v] = True
for w in G.adj(v):
if not self._visited[w]:
self.dfs(G, w)
self._reversePost.add_last(v)
def reversePost(self):
return self._reversePost
|
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import load_breast_cancer
#loads the dataset
data = load_breast_cancer()
#Splits dataset into training and test set
x_train, x_test, y_train, y_test = train_test_split(data['data'],data['target'], random_state=0)
#Creates a gradient boosting regression tree with default parameters
gb = GradientBoostingClassifier(random_state=0)
gb.fit(x_train, y_train)
print("The training set accuracy is " + str(gb.score(x_train,y_train)) )
print("The training set accuracy is " + str(gb.score(x_test,y_test)) )
#Creates a gradient boosting regression tree with max depth 1
#max depth usually set lower than 5
gb2 = GradientBoostingClassifier(random_state=0, max_depth=1)
gb2.fit(x_train, y_train)
print("The training set accuracy, with depth 1, is " + str(gb2.score(x_train,y_train)) )
print("The training set accuracy, with depth 1, is " + str(gb2.score(x_test,y_test)) )
#Creates a gradient boosting regression tree with learning rate 0.01
#learning rate is the degree of which the next tree corrects the mistake of the previous tree
gb3 = GradientBoostingClassifier(random_state=0, learning_rate=0.01)
gb3.fit(x_train, y_train)
print("The training set accuracy, with learning rate 0.01, is " + str(gb3.score(x_train,y_train)) )
print("The training set accuracy, with learning rate 0.01, is " + str(gb3.score(x_test,y_test)) ) |
class Event:
"""
Class that represents an event that happened on a processor.
The event can be instantaneous or continuous (for one unit of time).
"""
class Type:
"""
Enum all the possible types of events.
"""
IDLE = 0
RUNNING = 1
RELEASE = 2
DEADLINE = 3
def __init__(self, eventType, job=None):
"""
Construct the event.
:param eventType: the type of the event
:param job: the job (can be omitted, for example an idle event)
"""
self.eventType = eventType
self.job = job
def getType(self):
"""
Return the type of the event.
"""
return self.eventType
def getValue(self):
"""
Return the job linked to the event.
"""
return self.job
def asString(self):
"""
Return the event as a string.
"""
if self.eventType == Event.Type.IDLE:
return "Nothing is running"
elif self.eventType == Event.Type.RUNNING:
return self.job.asString() + " is running"
elif self.eventType == Event.Type.RELEASE:
return self.job.asString() + " is released"
elif self.eventType == Event.Type.DEADLINE:
return "Deadline of " + self.job.asString() + " reached"
else:
return "Unknown event"
|
def dividir(A,B):
resultado=A/B
return resultado
print("Ingrese los dos numeros a dividir\n\n")
A=float(input("Ingrese el primer numero "))
B=float(input("Ingrese el primer numero "))
division=dividir(A, B)
print(f"\n{A}/{B}={division}") |
operation = raw_input("Input the math operation you wish to perform (x,+,-,/):")
num1 = raw_input("Input the first number of the maths:")
num2 = raw_input("Input the second number of the maths:")
if operation == "x":
print(float(num1) * float(num2))
elif operation == "+":
print(float(num1) + float(num2))
elif operation == "-":
print(float(num1) - float(num2))
elif operation == "/":
print(float(num1) / float(num2))
else:
print("Error.") |
# Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 5 for the task.
# Please do provide function calls that test/demonstrate your
# function.
'''Returns the word with each of its characters rotated n times.'''
def rotate_word(word, n):
result = '' # Result string
for letter in word:
new_letter_num = ord(letter) + n
if letter.islower():
if new_letter_num < 97:
new_letter_num = 123 - (97 - new_letter_num)
result += chr(new_letter_num)
else:
if new_letter_num < 64:
new_letter_num = 91 - (65 - new_letter_num)
result += chr(new_letter_num)
return result
def main():
rotate_word('Python', 1)
rotate_word('cheer', 7)
rotate_word('melon', -10)
rotate_word('MELON', -10)
if __name__ == '__main__':
main() |
"""var1 = 20
var2 = 30
print("Hello {} World {}".format(var1, var2))"""
arr = [1, 2]
if "1" in (num for num in str(arr)):
print("true")
else:
print("false")
print(" ".join(str(x) for x in arr))
arr.append(3)
print(arr)
arr.remove(3) #remove will delete the first matching argument parsed. pop will delete the value at the index parsed
print(arr)
class A(object):
h, z = 1, 2
def __init__(self, x, y): #or remove constructor as not needed in this instance
self.x = x
self.y = y
def increment(self):
self.x+=1
return self.x
def add(self, a, b):
return a+b
def sub(self, a, b):
return a-b
method = A(1, 2)
print("Addition of {} + {}: {}".format(method.x, method.y, method.add(method.x, method.y)))
print("Before: {} After: {}".format(method.x, method.increment()))
#access class variable as method.z
#print(method.add(1, 2))
#print(method.sub(1, 2))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import prop
import math
import re
# Združljivost za Python 2 in Python 3
try:
basestring
except NameError:
basestring = str
def iff(p, q):
"""Vrne logično ekvivalenco izrazov p in q kot konjunkcijo dveh implikacij."""
return prop.And(prop.Implies(p, q), prop.Implies(q, p))
def sudoku(s, abc):
"""Vrne logični izraz, ki opisuje sudoku s z abecedo abc"""
n = len(abc)
r = int(math.sqrt(n))
if isinstance(abc, basestring):
s = [[None if s[i][j] in [None, ""] else str(s[i][j]) for j in range(n)] for i in range(n)]
assert all([all([x == None or (len(x) == 1 and x in abc) for x in l]) for l in s]), "Sudoku vsebuje neveljavne simbole!"
else:
assert None not in abc, "Abeceda ne sme vsebovati None!"
assert all([all([x == None or x in abc for x in l]) for l in s]), "Sudoku vsebuje neveljavne simbole!"
assert n == r*r, "Velikost abecede ni popoln kvadrat!"
assert len(s) == n, "Število vrstic se ne ujema s številom znakov!"
assert all([len(l) == n for l in s]), "Število stolpcev se ne ujema s številom znakov!"
l = []
for i in range(n):
for j in range(n):
if s[i][j] != None:
# Obstoječa števila
t = abc.index(s[i][j])
for k in range(n):
if k == t:
l.append("r%dc%dv%d" % (i, j, k))
else:
l.append(prop.Not("r%dc%dv%d" % (i, j, k)))
else:
# Vsako polje ima natanko eno vrednost
l.append(prop.Or([prop.And([("r%dc%dv%d" % (i, j, x) if x == y else prop.Not("r%dc%dv%d" % (i, j, x))) for x in range(n)]) for y in range(n)]))
# V vsaki vrstici se pojavi vsaka vrednost
l.append(prop.Or(["r%dc%dv%d" % (j, x, i) for x in range(n)]))
# V vsakem stolpcu se pojavi vsaka vrednost
l.append(prop.Or(["r%dc%dv%d" % (x, j, i) for x in range(n)]))
# V vsakem kvadratu se pojavi vsaka vrednost
for j in range(r):
for k in range(r):
l.append(prop.Or(sum([["r%dc%dv%d" % (r*j+x, r*k+y, i) for x in range(r)] for y in range(r)], [])))
return prop.And(l)
def solveSudoku(abc, d):
"""Reši sudoku z abecedo abc pri prireditvi logičnih spremenljivk,
podani s slovarjem d."""
n = len(abc)
s = [[None]*n for i in range(n)]
for k, v in d.items():
if not v:
continue
i, j, c = [int(x) for x in re.match('^r([0-9]+)c([0-9]+)v([0-9]+)', k).groups()]
s[i][j] = abc[c]
return s
# Primer sudokuja - težavnost easy :)
sudoku = \
[[None, '8', None, '1', '6', None, None, None, '7'],
['1', None, '7', '4', None, '3', '6', None, None],
['3', None, None, '5', None, None, '4', '2', None],
[None, '9', None, None, '3', '2', '7', None, '4'],
[None, None, None, None, None, None, None, None, None],
['2', None, '4', '8', '1', None, None, '6', None],
[None, '4', '1', None, None, '8', None, None, '6'],
[None, None, '6', '7', None, '1', '9', None, '3'],
['7', None, None, None, '9', '6', None, '4', None]]
def hadamard(n):
"""Vrne logični izraz, ki je izpolnljiv, ko obstaja Hadamardova matrika
reda n"""
if n % 2 == 1:
return prop.Fls()
# Prva vrstica in stolpec
l = ["r0c0"]
for i in range(1, n):
l.append("r0c%d" % i)
l.append("r%dc0" % i)
# Štejemo resnične vrednosti XORa i-te in j-te vrstice
for i in range(n):
for j in range(i+1, n):
# Resničnih je n/2
l.append("r%dr%df%dn%d" % (i, j, n, n//2))
# Pravili za prvega
l.append("r%dr%df1n0" % (i, j))
l.append(prop.Not("r%dr%df1n1" % (i, j)))
for k in range(1, n):
# Ali do indeksa k ni nobenega resničnega?
l.append(iff("r%dr%df%dn0" % (i, j, k+1), prop.And("r%dr%df%dn0" % (i, j, k), iff("r%dc%d" % (i, k), "r%dc%d" % (j, k)))))
if k < n//2:
# Ali so do indeksa k vsi resnični?
l.append(iff("r%dr%df%dn%d" % (i, j, k+1, k+1), prop.And("r%dr%df%dn%d" % (i, j, k, k), prop.Not(iff("r%dc%d" % (i, k), "r%dc%d" % (j, k))))))
for m in range(min(k, n//2)):
# Ali je do indeksa k m+1 resničnih?
l.append(iff("r%dr%df%dn%d" % (i, j, k+1, m+1), prop.Or(prop.And("r%dr%df%dn%d" % (i, j, k, m), prop.Not(iff("r%dc%d" % (i, k), "r%dc%d" % (j, k)))), prop.And("r%dr%df%dn%d" % (i, j, k, m+1), iff("r%dc%d" % (i, k), "r%dc%d" % (j, k))))))
return prop.And(l)
def makeHadamard(n, d):
"""Iz spremenljivk naredi Hadamardovo matriko."""
return [[1 if d["r%dc%d" % (i, j)] else 0 for j in range(n)] for i in range(n)]
|
import statistics
def getSum(coverted_numbers):
summation = 0
for number in converted_numbers:
summation += number
return summation
def getCount(converted_numbers):
count = 0
for number in converted_numbers:
count += 1
return count
def getLines(converted_numbers):
num_lines = len(converted_numbers)
return num_lines
def getAverage(converted_numbers):
sumn = getSum(converted_numbers)
avg = sumn/getLines(converted_numbers)
return avg
def getMax(converted_numbers):
_max = 0
for i in converted_numbers:
if i >= _max:
_max = i
return _max
def getMin(converted_numbers):
_min = 9999
for i in converted_numbers:
if i <= _min:
_min = i
return _min
def getRange(converted_numbers):
_max = getMax(converted_numbers)
_min = getMin(converted_numbers)
_range = _max - _min
return _range
def getMedian(converted_numbers):
converted_numbers.sort()
lstlen = len(converted_numbers)
index = (lstlen - 1) // 2
if(lstlen % 2):
return converted_numbers[index]
else:
return (converted_numbers[index] + converted_numbers[index + 1])/2.0
def getMode(converted_numbers):
number_counts = {}
for number in converted_numbers:
if number in number_counts:
number_counts[number] += 1
else:
number_counts[number] = 1
count = number_counts[number]
for number in number_counts:
if number_counts[number] >= count:
count = number_counts[number]
modeList = []
for number in number_counts:
if number_counts[number] == count:
modeList.append(int(number))
return modeList
# Loop the program
while (True):
try:
number_file_name = input("Enter the name of the file you would like to process: ")
number_file = open(number_file_name, "r")
unconverted_numbers = number_file.readlines()
converted_numbers = []
for number in unconverted_numbers:
try:
number = int(number)
converted_numbers.append(int(number))
except ValueError:
converted_numbers.append(float(number))
# Close the file
number_file.close()
except Exception as err:
print ('An error occurred reading', number_file_name)
print ('The error is', err)
else:
if getLines(converted_numbers) == 0:
print ('Empty file ->', number_file_name)
break
print("File name:", number_file_name)
print("Sum:", getSum(converted_numbers))
print("Count:", getCount(converted_numbers))
print("Average:" + ' %.1f' % getAverage(converted_numbers))
print("Maximum:", getMax(converted_numbers))
print("Minimum:", getMin(converted_numbers))
print("Range:", getRange(converted_numbers))
print("Median:", getMedian(converted_numbers))
print("Mode:", getMode(converted_numbers))
_max = getMax(converted_numbers)
_min = getMin(converted_numbers)
if _max <= 100 and _min >= 0:
_a = 0
_b = 0
_c = 0
_d = 0
_f = 0
for i in converted_numbers:
if i > 90:
_a+=1
elif i > 80 and i < 90:
_b+=1
elif i > 70 and i < 80:
_c+=1
elif i > 60 and i < 70:
_d+=1
else:
_f+=1
print("Grade Distribution:")
print("A's:", _a)
print("B's:", _b)
print("C's:", _c)
print("D's:", _d)
print("F's:", _f)
calculate_again = input("Would you like to evaluate another file? (y/n) ")
if (calculate_again != "y"):
break
|
import os
import csv
csvpath = os.path.join('Resources', 'election_data.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#print(csvreader)
csv_header = next(csvreader)
#print(f"CSV Header: {csv_header}")
candidates = {}
total_votes = 0
max_votes = 0
name = "does not exist"
for row in csvreader:
# print(row)
total_votes += 1
candidate = row[2]
candidates[candidate] = 1 + candidates.get(candidate,0)
result = ("Election Results\n")
result+=("----------------------\n")
result+=(f"Total Votes: {total_votes}\n")
result+=("----------------------\n")
for candidate, votes in candidates.items():
result+=(f"{candidate}: {round(votes*100/total_votes,3):.3f}% ({votes})\n")
if votes > max_votes:
max_votes = votes
name = candidate
result+=("---------------------\n")
result+=(f"Winner: {name}\n")
result+=("---------------------\n")
result+=("---\n")
print(result)
with open("result.txt", "w") as text_file:
text_file.write(result) |
from game import Board
from Player import Player
import random
class RandomPlayer(Player):
"""
This player can play a game of Tic Tac Toe by randomly choosing a free spot on the board.
It does not learn or get better.
"""
def __init__(self):
"""
Getting ready for playing tic tac toe.
"""
self.me = None
super().__init__()
def move(self, board):
"""
Making a random move
:param board: The board to make a move on
:return: The result of the move
"""
#
# print('making random move')
# if board.myTurn:
# options = board.getMyAvailable()
# else:
# options = board.getOpAvailable()
# foundOne = False
# while not foundOne:
# trial = random.randint(0,5)
# if trial in options:
# foundOne = True
# board.makeMove(trial)
# return board.getState(), board.isOver()
if board.myMarbles == [4,4,4,4,4,4]:
board.makeMove(2)
return
if board.myMarbles == [4,4,0,5,5,5]:
board.makeMove(5)
return
move = board.randomPossibleMove()
board.makeMove(move)
def final_result(self, result):
"""
Does nothing.
:param result: The result of the game that i finished
:return:
"""
pass
def new_game(self, me):
"""
Setting the side for the game to come. Noting else to do.
:param side: The side this player will be playing
"""
self.me = me
def typeRep(self):
return ' random ' |
# '''
# Linked List hash table key/value pair
# '''
class LinkedPair:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
def __repr__(self):
return f"<{self.key}, {self.value}>"
class HashTable:
'''
A hash table that with `capacity` buckets
that accepts string keys
'''
def __init__(self, capacity):
self.capacity = capacity # Number of buckets in the hash table
self.storage = [None] * capacity
self.entries = 0
def _hash(self, key):
'''
Hash an arbitrary key and return an integer.
You may replace the Python hash with DJB2 as a stretch goal.
'''
return hash(key)
def _hash_djb2(self, key):
'''
Hash an arbitrary key using DJB2 hash
OPTIONAL STRETCH: Research and implement DJB2
'''
pass
def _hash_mod(self, key):
'''
Take an arbitrary key and return a valid integer index
within the storage capacity of the hash table.
'''
return self._hash(key) % self.capacity
def insert(self, key, value):
'''
Store the value with the given key.
# Part 1: Hash collisions should be handled with an error warning. (Think about and
# investigate the impact this will have on the tests)
# Part 2: Change this so that hash collisions are handled with Linked List Chaining.
Fill this in.
'''
# Create LinkedPair obj
obj = LinkedPair(key, value)
# Increment entries
self.entries += 1
# Linked List Chaining
index = self._hash_mod(key)
pair = self.storage[index]
current_node = pair
# MVP 2 - Hash Collisions Implemented
# Check if a pair already exists in the bucket
if pair is not None and pair.key == key:
# Overwrite value
pair.value = value
# If so, check if it is the right key and if right key overwrite
elif pair is not None and pair.key != key:
# loop through until end
while current_node:
# If key is found, overwrite value
if current_node.key == key:
current_node.value = value
break
# If no key found, append to tail
elif current_node.next == None:
current_node.next = obj
break
current_node = current_node.next
else:
# If not, Create a new LinkedPair and place it in the bucket
self.storage[index] = obj
def remove(self, key):
'''
Remove the value stored with the given key.
Print a warning if the key is not found.
Fill this in.
'''
self.entries -= 1
index = self._hash_mod(key)
# check if pair exists in the bucket with matching keys
# Linked List Traveral
current_node = self.storage[index]
# If the node to be deleted is the head
if self.storage[index] is not None and self.storage[index].key == key:
# If so remove that pair by setting it to the linked list next value
self.storage[index] = self.storage[index].next
return current_node
elif self.storage[index] is not None and self.storage[index].key != key:
while current_node.next:
# If the next node is the node to be deleted
if current_node.next.key == key:
# save deleted node
deleting = current_node.next
# Replace current nodes next to the one after deleted
current_node.next = deleting.next
return deleting
current_node = current_node.next
else:
# Else print warning
print("Warning: Key does not exist")
def retrieve(self, key):
'''
Retrieve the value stored with the given key.
Returns None if the key is not found.
Fill this in.
'''
# Get index from hashmode
index = self._hash_mod(key)
# Linked List Traveral
current_node = self.storage[index]
# Check if a pair exists in the bucket with matching keys
if self.storage[index] is not None and self.storage[index].key == key:
# if so, return the value
return self.storage[index].value
elif self.storage[index] is not None and self.storage[index].key != key:
while current_node:
if current_node.key == key:
return current_node.value
current_node = current_node.next
else:
return None
def resize(self):
'''
Doubles the capacity of the hash table and
rehash all key/value pairs.
Fill this in.
'''
load_factor = self.entries / self.capacity
# Save previous storage
old_storage = self.storage
# Increase storage by 2x
self.capacity = self.capacity * 2
self.storage = [None] * self.capacity
if load_factor >= 0.7:
# Loop through storage
for pair in old_storage:
if pair != None:
current_node = pair
# Traverse current node
while current_node:
# Save next node
next_node = current_node.next
# Rehash and place current_node in new table
# If current index is filled traverse new_table linked list
self.insert(current_node.key, current_node.value)
# Set current_node -> next_node
current_node = next_node
if __name__ == "__main__":
ht = HashTable(2)
ht.insert("line_1", "Tiny hash table")
ht.insert("line_1", "Tiny hash")
ht.insert("line_2", "Filled beyond capacity")
ht.insert("line_3", "Linked list saves the day!")
print("")
print(ht.storage)
# Test storing beyond capacity
print(ht.retrieve("line_1"))
print(ht.retrieve("line_2"))
print(ht.retrieve("line_3"))
# Test resizing
old_capacity = len(ht.storage)
ht.resize()
new_capacity = len(ht.storage)
print(f"\nResized from {old_capacity} to {new_capacity}.\n")
# Test if data intact after resizing
print(ht.retrieve("line_1"))
print(ht.retrieve("line_2"))
print(ht.retrieve("line_3"))
print(ht.storage)
print("")
|
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import run
def is_valid_day(x):
try:
x = int(x)
if(x >= 0 and x <= 365):
return True
return False
except:
return False
def clicked():
#check for invalid inputs
if(not is_valid_day(daySelector.get())):
messagebox.showerror('Error', 'Please input valid day.')
return
#run code
run.predict(int(yearSelector.get()), int(daySelector.get()))
def outputResult(result):
messagebox.showinfo("Result", result)
window = Tk()
window.title("Weather Forcastatron 9000")
#window.geometry('500x350')
yearLabel = Label(window, text="Forecast Year:", width=20, font=18)
yearLabel.grid(column=0, row=0)
yearSelector = Combobox(window, width=15, font=18)
yearSelector['values']=(2016, 2017, 2018, 2019, 2020)
yearSelector.current(0)
yearSelector.grid(column=1, row=0)
dayLabel = Label(window, text="Forecast Day:", width=20, font=18)
dayLabel.grid(column=0, row=1)
daySelector = Spinbox(window, from_=0, to=365, width=15, font=18)
daySelector.grid(column=1, row=1)
btn = Button(window, text="Forecast!", command=clicked)
btn.grid(column=0, row=2)
window.mainloop()
|
处理哈希冲突的几种方法:
开放定址法
开放定址法就是产生冲突之后去寻找下一个空闲的空间,其中又包括下面两种:
线性探测法:di= i ,或者其他线性函数。相当于逐个探测存放地址的表,直到查找到一个空单元,然后放置在该单元。
平方探测法:(https://python123.io/index/topics/data_structure/hash_table)
链表法
这是另外一种类型解决冲突的办法,散列到同一位置的元素,不是继续往下探测,而是在这个位置是一个链表,这些元素则都放到这一个链表上。
再散列
如果一次不够,就再来一次,直到冲突不再发生。
建立公共溢出区
将哈希表分为基本表和溢出表两部分,凡是和基本表发生冲突的元素,一律填入溢出表(注意:在这个方法里面是把元素分开两个表来存储)。
下面是常用链表法实现的源码,加深哈希表的理解
hash_table= [None] * 10
def hash_func(key):
return key % len(hash_table)
def insert(hash_table,key,value):
hash_key = hash_func(key)
hash_table[hash_key] = value
insert(hash_table,10,'Martin')
insert(hash_table,25,'Iulian')
insert(hash_table,35,'Adriana')
print(hash_table) #due to collision, we can't see Iulian there
#resolve such collision
hash_table = [[] for _ in range(10)]
print(hash_table)
def insert(hash_table,key,value):
hash_key = hash_func(key)
hash_table[hash_key].append(value)
insert(hash_table,10,'Martin')
insert(hash_table,25,'Iulian')
insert(hash_table,35,'Adriana')
print(hash_table) #due to collision, we can't see Iulian there
#Python’s built-in “hash” function is used to create a hash value of any key.
#This function is useful as it creates an integer hash value for both string and integer key.
#The hash value for integer will be same as it is, i.e. hash(10) will be 10, hash(20) will be 20, and so on.
#In the below code, note the difference in output while using 10 and ’10’.
#10 (without quote) is treated as an integer and ’10’ (with quote) is treated as a string.
print(hash('xyz'))
print(hash('10'))
print(hash(10))
hash_table = [[] for _ in range(10)]
#so we replace our own hash_func with hash
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = ((key, value))#note: i can be find in the lastest scope
else:
bucket.append((key, value))
insert(hash_table,10,'Martin')
insert(hash_table,25,'Iulian')
insert(hash_table,35,'Adriana')
print(hash_table)
def search(hash_table,key):
hash_key = hash(key) % len(hash_table)
bucket = hash_table[hash_key]
for i,kv in enumerate(bucket):
k,v = kv
if(k==key):
return v
print(search(hash_table,25))
def delete(hash_table, key):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
del bucket[i]
print ('Key {} deleted'.format(key))
else:
print ('Key {} not found'.format(key))
delete(hash_table, 25)
delete(hash_table, 125)
print (hash_table)
|
'''
基本的排序算法:冒泡 插入
常见排序算法:归并 快排(面试题40) 拓扑(主要用来解决依赖问题,比如abcde五门课的学习之间有依赖关系,最后决定学习顺序以顺利完成学业等)
其他排序算法 桶排序、堆排序
'''
def bubblesort(arr):
for i in range(1,len(arr)):
for j in range(0, len(arr)-i):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
def insertionSort2(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergeSort(arr,l,r):
if l < r:
m = int((l+(r-1))/2)
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
#快速排序可以打印出具体变化
def partition(arr,low,high):
i = (low-1)
pivot = arr[high]
for j in range(low , high):
if arr[j] <= pivot:
#print('i=',i,';j=',j)
i = i+1
#print('i=',i,';j=',j)
#print(arr)
arr[i],arr[j] = arr[j],arr[i]
#print(arr)
arr[i+1],arr[high] = arr[high],arr[i+1]
#print(arr)
return (i+1)
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
print(quickSort([3,1,7,4,5,2,8,6],0,7))
#快排的另外一种好理解的算法
def quicksort(arr):
if len(arr) < 2:
return arr
mid = arr[len(arr)//2]
left,right = [],[]
arr.remove(mid)
for i in arr:
if i <= mid:
left.append(i)
else:
right.append(i)
return quicksort(left)+[mid]+quicksort(right)
#掌握快排之后 做面试题40如鱼得水 https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
#可以轻松解决前k小问题
class Solution:
def partition(self,arr,low,high):
i = low-1
pivot = arr[high]
for j in range(low,high):
if arr[j] < pivot:
i += 1
arr[i],arr[j] = arr[j],arr[i]
arr[high],arr[i+1] = arr[i+1],arr[high]
return (i+1)
def getLeastNumbers(self, arr: List[int], k: int) -> List[int]:
if len(arr) < k:
return arr
else:
low = 0
high = len(arr)-1
while(low < high):
m = self.partition(arr, low, high)
if m == k:
break
elif m > k:
high = m - 1
else:
low = m + 1
return arr[:k]
|
Series:One-dimensional ndarray with axis labels (including time series).
Construction:class pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
data : array-like, Iterable, dict, or scalar value->Contains data stored in Series.
eg1:Series(ndarray,index = [id1,id2,id3])
eg2:Series([1,2,3],index = [id1,id2,id3])
value_counts() #Return a Series containing counts of unique values.->NaN exclued as default
child_series = s[[col1,col2,col3]]
Series.loc
Access a group of rows and columns by label(s) or a boolean array.
.loc[] is primarily label based, but may also be used with a boolean array.
Allowed inputs are:
A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
A list or array of labels, e.g. ['a', 'b', 'c'].
A slice object with labels, e.g. 'a':'f'.
A boolean array of the same length as the axis being sliced, e.g. [True, False, True].
A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)
##从dataframe中取符合条件的数据输出series 然后用values输出ndarray
#known_age = age_df[age_df.Age.notnull()].values
#unknown_age = age_df[age_df.Age.isnull()].values
#y = known_age[:,0]
#x = known_age[:,1:]
#rfr = RandomForestRegressor(random_state=0,n_estimators=2000,n_jobs=-1)
#rfr.fit(x,y)
#predicted_ages = rfr.predict(unknown_age[:,1:])
#data.loc[(data.Age.isnull()),'Age'] = predicted_ages
##print(data.Age)
#做特征转化的典型例子 性别本来是一个特征,但是如果做线性回归的话 要展开两个特征 然后分析权重
dummies_sex = pd.get_dummies(data['Sex'],prefix='sex')
print(dummies_sex)
new_data = pd.concat([data,dummies_sex],axis=1) #注意默认是行廉洁,要加axis
new_data.drop(['Sex'],axis=1,inplace=True)
#用法:DataFrame.drop(labels=None,axis=0, index=None, columns=None, inplace=False)
#
#参数说明:
#labels 就是要删除的行列的名字,用列表给定
#axis 默认为0,指删除行,因此删除columns时要指定axis=1;
#index 直接指定要删除的行
#columns 直接指定要删除的列
#inplace=False,默认该删除操作不改变原数据,而是返回一个执行删除操作后的新dataframe;
#inplace=True,则会直接在原数据上进行删除操作,删除后无法返回。
#
#因此,删除行列有两种方式:
#1)labels=None,axis=0 的组合
#2)index或columns直接指定要删除的行或列
print(new_data.head())
import pandas as pd
import numpy as np
from numpy import nan as NA
from pandas import DataFrame, Series
from matplotlib import pyplot as plt
#%matplotlib inline
#obj = Series([4,7,-5,3])
#print(obj)
#obj2 = Series([4,7,-5,3],index=['a','b','c','d'])
#print(obj2['a'])
#
#print('b' in obj2)
#print(obj2[obj2>0])
#
#print(np.exp(obj))
#
#status = ['e','a','b','c']
#obj3 = Series(obj2,index=status)
#print(obj3)
#
#print(pd.isnull(obj3))
#
#obj = Series(['Bob','Steven','Linq','Spanish'], index = ['China','US','Shit','Xcode'])
#obj2 = obj.reindex(['US','China','Shit','Xcode','Emmy','Long'],fill_value = 0) #可以用于对缺失值进行填充
#print(obj2)
#
#obj3 = Series(['blue','red','purple','green'], index=[0,2,4,6])
#obj4 = obj3.reindex(range(10),method='ffill') #forward fill利用前面的值填充
#print(obj4)
#
#obj3.sort_index()
#obj3.sort_values()
#
##DataFrame和Series里面的切片是引用的, 所以比正常使用数组效率要高???为什么要这么设计?
#obj = Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#x = obj[1:2]
#x[1] = 100
#print(x)
#
##通过索引访问时时全闭的
#x = obj['a':'c'] #1,2,3
####################################################DataFrame#########################################
#pandas frame 模块从操作角度考虑 设置为列优先,通常情况下都是行优先
data = {'city':['beijing','shanghai','guangdong','datong','guangling'],
'year':[2016,2017,2018,2019,2020],
'GDP':[2030.5,44321.09,31243.43,4310.431,43243.88]}
frame = DataFrame(data, columns=['year','city','GDP','delt'])
frame.set_index('year')
#print(frame.city)
#print(frame['year'])
#print(frame,'\n')
#print(frame.iloc[1,],'\n') #访问第一行
#print(frame.iloc[:,2],'\n') #访问第二列
#print(frame.iloc[1:3,1:2],'\n')#切片访问第一二行 第一列
#print(frame.loc[1,'city']) #loc使用户可以通过名字访问
frame['debt'] = Series([-1.2,-1.5,-1.8,-1.7],index = [0,1,2,4])
#print(frame)
frame['pool'] = (frame['debt']<-1.6)
#print(frame) #在特征工程中用的多,可以轻松赋值 0 1
data = DataFrame(np.arange(-5,11).reshape([4,4]),
index = ['Ohio','Colorado','Utah','New York'],
columns = ['one','two','three','four'])
#print(data)
#print(data.drop(['Colorado','Ohio']))
#print(data.drop('two',axis = 1))
#print(data.drop(['two','four'],axis = 1))
#print(data.loc[data.three>10])
data[data>10] = 0
#print(data)
#print(data+100)
s = data.iloc[0]
#print(s)
#print(data-s) #每一行减去对应的s的值
s2 = data.three
#print(data.sub(s2,axis = 0))
#print(np.abs(data))
f = lambda x:x.max()-x.min()
#print(data.apply(f))
#print(data.apply(f,axis=1))
def f2(x):
return Series([x.min(),x.max()],index = ['min','max'])
#print(data.apply(f2))
#print(data.apply(f2,axis=1))
data = data + 0.347
#print(data)
format1 = lambda x: '%.2f' % x
#print(data.applymap(format1))
#print(data['four'].map(format1))
#print(data.sort_index())
#print(data.sort_index(axis=1,ascending=False))
df = DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]],index=['a', 'b', 'c', 'd'],columns=['one', 'two'])
#print(df,'\n')
#print(df.sum(),'\n')
#print(df.cumsum(),'\n')
#print(df.describe(),'\n')
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],'data1': range(7)})
df2 = DataFrame({'key': ['a', 'b', 'd'],'data2': range(3)})
#print(df1)
#print(df2)
#print(pd.merge(df1,df2))
#print(pd.merge(df1,df2,on='key'))
df3 = DataFrame({'lkey': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],'data1': range(7)})
df4 = DataFrame({'rkey': ['a', 'b', 'd'],'data2': range(3)})
#print(df3)
#print(df4)
#print(pd.merge(df3,df4))
#print(pd.merge(df3,df4,left_on='lkey',right_on='rkey'))
#print(pd.merge(df1,df2,how='outer'))
left = DataFrame({'key': ['foo', 'foo', 'bar'],
'_key': ['one', 'two', 'one'],
'val': [1, 2, 3]})
right = DataFrame({'key': ['foo', 'foo', 'bar', 'bar'],
'_key': ['one', 'one', 'one', 'two'],
'val': [4, 5, 6, 7]})
#print(left)
#print(right)
#print(pd.merge(left, right, on=['key', '_key'], how='outer')) # 基于多个列的合并"
#print(pd.merge(left, right, on='key', suffixes=('_left', '_right'))) # 重名列可以指定合并后的后缀"
left1 = DataFrame({'key': ['a', 'b', 'a', 'a', 'b', 'c'],'value': range(6)})
right1 = DataFrame({'group_val': [3.5, 7]}, index=['a', 'b'])
#print(left1)
#print(right1)
#print(pd.merge(left1, right1, left_on='key', right_index=True)) # 使用right的索引参与合并"
left2 = DataFrame([[1., 2.], [3., 4.], [5., 6.]],
index=['a', 'c', 'e'],
columns=['Ohio', 'Nevada'])
right2 = DataFrame([[7., 8.], [9., 10.], [11., 12.], [13, 14]],
index=['b', 'c', 'd', 'e'],
columns=['Missouri', 'Alabama'])
#print(left2)
#print(right2)
#print(left2.join(right2, how='outer')) # join默认使用索引合并"
another = DataFrame([[7., 8.], [9., 10.], [11., 12.], [16., 17.]],
index=['a', 'c', 'e', 'f'],
columns=['New York', 'Oregon'])
#print(left2.join([right2, another])) # 一次合并多个DataFrame,默认使用全连接。"
s1 = Series([0, 1], index=['a', 'b'])
s2 = Series([2, 3, 4], index=['c', 'd', 'e'])
s3 = Series([5, 6], index=['f', 'g'])
#print(pd.concat([s1, s2, s3],axis=1,sort=False)) # 默认沿着行的方向连接"
a = Series([np.nan, 2.5, np.nan, 3.5, 4.5, np.nan],
index=['f', 'e', 'd', 'c', 'b', 'a'])
b = Series(np.arange(len(a), dtype=np.float64),
index=['f', 'e', 'd', 'c', 'b', 'a'])
b[-1] = np.nan
#print(a)
#print(b)
#print(np.where(pd.isnull(a), b, a)) # 根据where筛选,如果a对应位置的元素为None就选b"
df1 = DataFrame({'a':[1,NA,5,np.NAN],
'b':[NA,2,np.nan,6],
'c':range(2,18,4)})
df2 = DataFrame({'a':[5,4,np.nan,3,7],
'b':[NA,3,4,6,8]})
#print(df1)
#print(df2)
#print(df1.combine_first(df2))
#其他需要的知识点\n",
#1. pivot和melt\n",
#2. 值替换\n",
#3. 数据切割\n",
#4. 排列组合和随机采样"
# Pandas绘图
import pandas as pd
#test1
data=pd.read_csv('NVDA.csv', index_col='Date', parse_dates=['Date'])
data['year'] = data.index.year
print(data.info())
#test2
data1=pd.read_csv('NVDA.csv')
data1.set_index(['Date'],inplace=True)
data1.index = pd.to_datetime(data1.index)
#data1['Date'] = pd.to_datetime(data1['Date'])
data1['year'] = data1.index.year
print(data1.info())
#注意一但某一列被设置成索引后,不能通过data1['Date'] = pd.to_datetime(data1['Date'])这种方式来改类型
需要通过data1.index = pd.to_datetime(data1.index)来改类型
所以最好就是test1中在开始读取的时候就设置好索引,尤其是时间列索引的解析
|
__author__ = 'aligajani'
# MIT License: www.aligajani.com
# PyQuote | pyquote.py
# Beautify your quotes
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
class PyQuote():
# Break quote into seperate lines
def chunk(self, quote, step):
line = quote.split()
chunk = [ line [i:i+step] for i in range(0, len(line), step)]
return chunk
# Overlay quote on image with automatic adjustments
def draw(self, chunk, author, template, font, size):
# Load template image
im = Image.open(template)
draw = ImageDraw.Draw(im)
# Set font sizes and types
font_quote = ImageFont.truetype(font[0], size[0])
font_author = ImageFont.truetype(font[1], size[1])
# Overlay each line chunk from the raw quote
for i in range(len(chunk)):
draw.text((45, 75 * (i+1)), ' '.join(chunk[i]), (255, 255, 255), font=font_quote)
# Get width of author text
w = font_author.getsize(author)[0]
exponential_padding = 750 - w
draw.text((exponential_padding, 425), author, (255, 255, 255), font=font_author)
# Draw a rectangle design which increases on quote size
line_height = 85 * (len(chunk))
draw.rectangle([0, 80, 12, line_height], fill=(231, 76, 60))
# Save the image
im.save('output.jpg', quality=100)
py = PyQuote()
quote = "Better beware of notions like genius and inspiration; they are a sort of magic wand and should be used sparingly by anybody who wants to see things clearly.."
author = "P .J. O'Rourke"
chunk = py.chunk(quote, 6)
py.draw(chunk, author, "vinkk-template.jpg", ["h-ul.ttf", "h-th.ttf"], [45, 50]) |
def betterBnW(pic):
pixels = getPixels(pic)
for p in pixels:
average = int((getRed(p)*0.299) + (getGreen(p)*0.587) + (getBlue(p)*0.114))
setColor(p,makeColor(average,average,average))
return pic
def lineDrawing(pic):
pic = betterBnW(pic)
drawing = makeEmptyPicture(getWidth(pic)-1,getHeight(pic)-1)
for x in range(0,getWidth(pic)-1):
for y in range(0,getHeight(pic)-1):
pix = getPixel(pic, x,y)
bottom = getPixel(pic, x, y+1)
right = getPixel(pic,x+1,y)
if abs(getRed(pix)-getRed(bottom))<8 and abs(getRed(pix)-getRed(right))<8:
setColor(getPixel(drawing,x,y),makeColor(255,255,255))
else:
setColor(getPixel(drawing,x,y),makeColor(0,0,0))
return drawing |
"""
Unique elements Order Change of var Adding new var
LIST NO YES YES YES
TUPLE NO YES NO NO
DICTIONARIES YES NO YES YES
SET YES NO NO YES
"""
"""
- List - "[]" - Ordered sequence of Objects:
Can contain integers, strings, and even other lists.
Can contain variables which are equal.
Can add new elements and modify existing.
"""
#example - assigning list and simple operations
test = [Mark, Clark, James]
#input
lista = [1, 5, 7, 8, -2, "mark", "tim"]
lista.append(3)
print(lista)
#output
[1, 5, 7, 8, -2, 'mark', 'tim', 3]
#input
lista = [1, 5, 7, 8, -2, "mark", "tim"]
lista.insert(3,12)
print(lista)
#output
[1, 5, 7, 12, 8, -2, 'mark', 'tim']
#input
lista = [1, 5, 7, 8, -2, "mark", "tim"]
lista.pop(3)
print(lista)
#output
[1, 5, 7, -2, 'mark', 'tim']
"""
- Tuple - "()" - Orderer group of immutable objects:
test = ( 12 , Amy , student )
tuples can not be changed after defined.
Used when you are sure that variables won't change.
It's used in big application in order to save some memory.
"""
test = ( 12 , Amy , student )
"""
- Dictionary - "{}" - unordered key:value pairs:
build in system for storing data as key:value pairs. Assigning data to
the key and using it later. A value can be any Python object.
order doesn't matter.
"""
#example - updating dictonary
#input
dictonary = {1:"Mark", 2:"Dean",3:"Carl"}
print(dictonary)
dictonary.update ({1:"Mathew"})
print(dictonary)
#output
{1: 'Mark', 2: 'Dean', 3: 'Carl'}
{1: 'Mathew', 2: 'Dean', 3: 'Carl'}
"""
- Set - "{}" - unordered group of unique objects:
Sets are created by putting variables between curly brackets
Can't change variables in set.
Can add new elements
Most commonly used to reduce duplicates
"""
seta = {1, 3, 2, 4, 6,}
#Example - converting list into set and printing same elements from each group of
#variables
lista = [1, 5, 7, 8, -2]
listb = [3, 5, 12, 8, 23, -2, 12]
print(set(lista)&(set(listb)))
#Example - printing all of the lista elements that listb do not contain
lista = [1, 5, 7, 8, -2]
listb = [3, 5, 12, 8, 23, -2, 12]
print(set(lista)-(set(listb)))
#Example1 - Dictonary into list
"""Converting dictionaries into list and adding new dictonary to existing
list of dictonaries"""
#input
conf1 = { "interface": "FastEthernet 0/0",
"ipadress": "192.168.1.1",
"vlanid" : 2 }
conf2 = { "interface": "FastEthernet 0/1",
"ipadress": "192.168.1.2",
"vlanid" : 2 }
conf3 = { "interface": "FastEthernet 0/2",
"ipadress": "192.168.1.3",
"vlanid" : 2 }
config = [conf1,conf2,conf3]
config.append({"interface" : "FastEthernet 1/0","ip address":"192.168.1.4","vlanid" : 3 })
print(config)
#output
[{'interface': 'FastEthernet 0/0', 'ipadress': '192.168.1.1', 'vlanid': 2},
{'interface': 'FastEthernet 0/1', 'ipadress': '192.168.1.2', 'vlanid': 2},
{'interface': 'FastEthernet 0/2', 'ipadress': '192.168.1.3', 'vlanid': 2},
{'interface': 'FastEthernet 1/0', 'ip address': '192.168.1.4', 'vlanid': 3}]
#Example 2 - printing all elements using loop for
#input
guestlist = [
('Mark', 28, 'male'),
('Mathew', 22, 'male'),
('Martha', 32, 'female')
]
for name, age, sex in guestlist:
print("name: ", name )
print("age: ", age)
print("sex: ", sex )
print()
#output
name: Mark
age: 28
sex: male
name: Mathew
age: 22
sex: male
name: Martha
age: 32
sex: female
|
# Provided is a list of tuples. Create another list called t_check that contains the third element of every tuple.
lst_tups = [('Articuno', 'Moltres', 'Zaptos'), ('Beedrill', 'Metapod', 'Charizard', 'Venasaur', 'Squirtle'), ('Oddish', 'Poliwag', 'Diglett', 'Bellsprout'), ('Ponyta', "Farfetch'd", "Tauros", 'Dragonite'), ('Hoothoot', 'Chikorita', 'Lanturn', 'Flaaffy', 'Unown', 'Teddiursa', 'Phanpy'), ('Loudred', 'Volbeat', 'Wailord', 'Seviper', 'Sealeo')]
t_check = [ elmnt[2] for elmnt in lst_tups ]
# Below, we have provided a list of tuples. Write a for loop that saves the second element of each tuple into a list called seconds.
tups = [('a', 'b', 'c'), (8, 7, 6, 5), ('blue', 'green', 'yellow', 'orange', 'red'), (5.6, 9.99, 2.5, 8.2), ('squirrel', 'chipmunk')]
seconds = [ elmnt[1] for elmnt in tups]
|
from bicycles import *
david = Customers("David", 200)
lara = Customers("Lara", 500)
vicky = Customers("Vicky", 1000)
wheel1 = Wheels("wheel_model_1", 5, 30)
wheel2 = Wheels("wheel_model_2", 4, 70)
wheel3 = Wheels("wheel_model_3", 6, 200)
frame1 = Frames("aluminum", 10, 150)
frame2 = Frames("carbon", 8, 30)
frame3 = Frames("steel", 15, 100)
Manuf1 = Manufacturer("Manuf1")
Manuf2 = Manufacturer("Manuf2")
trek1 = Bicycle("trek1", "trek_2000", wheel3, frame1, "Manuf1")
trek2 = Bicycle("trek2", "trek_2005", wheel1, frame2, "Manuf1")
gary1 = Bicycle("gary1", "gary_90", wheel2, frame3, "Manuf2")
gary2 = Bicycle("gary2", "gary_88", wheel1, frame3, "Manuf2")
bike1 = Bicycle("bike1", "bike_100", wheel2, frame1, "Manuf2")
bike2 = Bicycle("bike2", "bike_200", wheel3, frame2, "Manuf2")
Manuf1.produce(trek1)
Manuf1.produce(trek1)
Manuf1.produce(trek2)
Manuf2.produce(gary1)
Manuf2.produce(bike2)
Manuf2.produce(bike1)
Manuf2.produce(gary2)
shop = Bike_shop("shop")
shop.buy(trek1, Manuf1)
shop.buy(trek2, Manuf1)
shop.buy(trek1, Manuf1)
shop.buy(gary1, Manuf2)
shop.buy(bike1, Manuf2)
shop.buy(bike2, Manuf2)
Manuf2.sell(gary2, shop)
# Print the name of each customer, and a list of the bikes offered by the bike shop that they can afford given their budget.
shop.offer(david)
shop.offer(lara)
shop.offer(vicky)
# Print the initial inventory of the bike shop for each bike it carries.
print(shop.inventory)
# Have each of the three customers purchase a bike then print the name of the bike the customer purchased, the cost,
# and how much money they have left over in their bicycle fund.
david.buy(trek1, shop)
david.buy(trek2, shop)
david.buy(trek1, shop)
# After each customer has purchased their bike, the script should print out the bicycle shop's remaining inventory for each bike,
# and how much profit they have made selling the three bikes.
for i in shop.inventory:
print("we have " + str(shop.inventory[i]) + " bicycles of the model " + str(i))
print("Profit: ", str(shop.profit))
|
#definir_datos de entrada
nota_1 = 0
nota_2 = 0
nota_3 = 0
nota_4 = 0
nota1 = int(input("Ingresar valor de la 1 unidad: "))
nota2 = int(input("Ingresar valor de la 2 unidad: "))
nota3 = int(input("Ingresar valor de la 3 unidad: "))
nota4 = int(input("Ingresar valor de la 4 unidad: "))
#proceso_datos de proceso
nota_1 = nota1 * 0.10;
nota_2 = nota2 * 0.15;
nota_3 = nota3 * 0.25;
nota_4 = nota4 * 0.50;
nota_final = nota_1 + nota_2 +nota_3 + nota_4;
#proceso_datos de salida
print(f"La nota 1 es de: {nota_1}")
print(f"La nota 2 es de: {nota_2}")
print(f"La nota 3 es de: {nota_3}")
print(f"La nota 4 es de: {nota_4}")
print(f"La suma de las 4 notas es de: {nota_final}")
|
def create_spectrogram(filename):
"""
From the path of the wav file, produces a png file in the same location
"""
sampling_rate, samples = wavfile.read(filename)
f, t, spectrogram = signal.spectrogram(samples, sampling_rate, nfft=2048)
img = Image.fromarray(np.uint8(spectrogram), mode='L')
img.save(filename.replace('wav', 'png'))
for root, dirs, files in os.walk('.'):
create_spectrogram(os.path.join(root, x)) for x in files if x.endswith('.wav')
|
ciphertext = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
wordparts = ['ing','er','or','ess','ist','ast','ian','ant',
'oi','io','ll','to','on','ir','ri','uo','ou','ent','ee',
'ic','oo','ic','man','woman','person','eur','tion','nce',
'ty','ry','ism','ics','ure','ss','an','en','ac','es']
ciphertext_decoded = ciphertext.decode("hex")
#print 'ciphertext:', ciphertext
#print 'ciphertext_decoded: ', ciphertext_decoded
for j in range(0,len(alphabet)):
plaintext = ''
score = 0
for x in ciphertext_decoded:
plaintext = plaintext + chr(ord(x) ^ ord(alphabet[j]))
for x in wordparts:
if plaintext.endswith(x):
score = score + 1
if score > 3:
print 'HIGH SCORE:',score,' ',plaintext
#print plaintext |
"""
计算(大)文件的哈希值 +md5 +sha1
"""
import hashlib
import time
def sha1Value(file, buffer_size=1024):
sha1 = hashlib.sha1()
with open(r'%s' % file, 'rb') as f:
data_buffer = f.read(buffer_size)
while data_buffer:
sha1.update(data_buffer)
data_buffer = f.read(buffer_size)
return sha1.hexdigest()
def md5Value(file, buffer_size=1024):
md5 = hashlib.md5()
time = 0
with open(r'%s' % file, 'rb') as f:
data_buffer = f.read(buffer_size)
while data_buffer:
md5.update(data_buffer)
time += 1
data_buffer = f.read(buffer_size)
print('md5 time: %s' % time)
return md5.hexdigest()
if __name__ == '__main__':
file_path = input('please input your file path')
begin = time.clock()
sha1_str = sha1Value(file_path)
print(sha1_str)
time1 = time.clock()
sha1_time = time1 - begin
print(sha1_time)
md5_str = md5Value(file_path)
print(md5_str)
md5_time = time.clock() - time1
print(md5_time)
|
print("Here is a list of all the prime numbers from 2-100,000!!! It'll take a while to rpint out ALL of them so bear")
# I will now start the main thing!
# Takes myNum, an integer
# Returns True if n is prime
# Returns False if n is composite
def isPrime(y, list):
x = range(1,int(y))
num = y - 2
o = 0
for number in x:
rder = int(y) % int(number)
# I have created a for loop to check all the numbers if they are prime
if rder != 0:
o = o + 1
# If the remainder is not 0 then it will continue
if o == num:
print(y)
list.append(y)
#Creating a empty list
primeList = []
# Opening the prime list text document
myPrimes = open("primes.txt", "w")
# Starting a range from 2 top 10001
rangeList = range(2, 10001)
# going through the list to find the primes
for n in rangeList:
g = isPrime(n, primeList)
for x in primeList:
myPrimes.write(str(x) + "\n")
#closing the list now we done
myPrimes.close()
|
print("Hello, how old are you?")
year_ = raw_input()
myVar = str( year_ + 10 )
print( " In ten years, you will be" + myVar + " years old!")
|
import sys
donuts = 40
donuts_str = str(donuts)
people = 11
people_str = str(people)
donuts_ = str( donuts // people )
print("our party has " + people_str + " people and " + donuts_str + " donuts.")
print( "Each person at the party gets " + donuts_ + " donuts.")
|
#coding=utf-8
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
def teleman(number,b,c,d):
a = str(number)
if a not in str(b) and a not in str(c) and a not in str(d):
return number
txt_numbers = []
txt_bnumbers = []
call_numbers = []
call_bnumbers = []
telemarketers = []
for call in calls:
call_numbers.append(call[0])
call_bnumbers.append(call[1])
for text in texts:
txt_numbers.append(text[0])
txt_bnumbers.append(text[1])
for call_number in call_numbers:
a = teleman(call_number, call_bnumbers,txt_bnumbers,txt_numbers)
if a != None:
telemarketers.append(a)
new_set = set(telemarketers)
# print new_set
print ("These numbers could be telemarketers: \n{}".format("\n".join(sorted(new_set))))
"""
任务4:
电话公司希望辨认出可能正在用于进行电话推销的电话号码。
找出所有可能的电话推销员:
这样的电话总是向其他人拨出电话,
但从来不发短信、接收短信或是收到来电
请输出如下内容
"These numbers could be telemarketers: "
<list of numbers>
电话号码不能重复,每行打印一条,按字典顺序排序后输出。
"""
|
import pyshorteners
your_url = input('Please enter your url:...\n')
shortener = pyshorteners.Shortener()
shortened_url = shortener.tinyurl.short(your_url)
print("Your new short url is..: ", shortened_url) |
# -*- coding: utf-8 -*-
import sqlite3
import os
class Sql(object):
def __init__(self):
pass
def createTable(self):
# 创建用户表
if not os.path.exists("game.db"):
conn = sqlite3.connect('game.db')
c = conn.cursor()
c.execute('''CREATE TABLE USER
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
USERNAME VARCHAR(20) NOT NULL UNIQUE ,
PASSWORD VARCHAR(20));''')
print "User Table created successfully"
# 创建数据表
c.execute('''CREATE TABLE DATA
(ID INTEGER PRIMARY KEY UNIQUE ,
HP INT,
AMMO INT,
LV INT,
EXP INT
);''')
print "Data Table created successfully"
conn.commit()
conn.close()
# 插入用户数据,当新用户注册时调用
def insert(self, username, password):
if not os.path.exists("game.db"):
self.createTable()
if not self.checkUsername(username):
return False
conn = sqlite3.connect('game.db')
c = conn.cursor()
c.execute("INSERT INTO USER (USERNAME,PASSWORD) \
VALUES ('" + username + "','" + password + "')");
conn.commit()
print "Records insert to user successfully";
userid = self.getID(username)
if userid == 0:
c.execute("DELETE from USER where username = '" + username + "';")
conn.commit()
conn.close()
return False
c.execute("INSERT INTO DATA (ID,HP,AMMO,LV,EXP) \
VALUES (" + str(userid) + ",100,100,1,0 )");
conn.commit()
print "Records insert to data successfully";
conn.close()
return True
# 更新用户数据,当用户结束一局游戏时调用
def update(self, username, HP, ammo, LV, EXP):
if not os.path.exists("game.db"):
self.createTable()
userid = self.getID(username)
if userid == 0:
return False
conn = sqlite3.connect('game.db')
c = conn.cursor()
c.execute("UPDATE DATA set \
HP = '" + str(HP) + "',AMMO = '" + str(ammo) + "',LV = '" + str(LV) + "',EXP = '" + str(EXP) + "' \
where ID = " + str(userid))
conn.commit()
print "Update Successfully"
conn.close()
return True
# 删除数据库
def __deleteSQL(self):
if not os.path.exists("game.db"):
os.remove("user.db")
if not os.path.exists("game.db"):
return True
else:
return False
# 通过用户名获取用户ID
def getID(self, username):
if not os.path.exists("game.db"):
self.createTable()
conn = sqlite3.connect('game.db')
c = conn.cursor()
cursor = c.execute("SELECT ID FROM USER WHERE USERNAME = '" + username + "'");
userid = 0
for row in cursor:
userid = row[0]
conn.close()
return userid
# 通过用户名获得DATA表中的数据
def getUserMsg(self, username):
userId = self.getID(username)
HP = 0
ammo = 0
LV = 0
EXP = 0
conn = sqlite3.connect('game.db')
c = conn.cursor()
cursor = c.execute("SELECT HP,AMMO,LV,EXP FROM DATA WHERE ID = " + str(userId));
for row in cursor:
HP = row[0]
ammo = row[1]
LV = row[2]
EXP = row[3]
conn.close()
return userId, HP, ammo, LV, EXP
# 检查用户名与密码是否匹配
def checkPassword(self, username, password):
if not os.path.exists("game.db"):
self.createTable()
conn = sqlite3.connect('game.db')
c = conn.cursor()
userPassword = ""
cursor = c.execute("SELECT PASSWORD FROM USER WHERE USERNAME = '" + username + "'");
for row in cursor:
userPassword = row[0]
conn.close()
if userPassword == '':
return False
elif userPassword == password:
return True
else:
return False
# 检查用户名是否可用
def checkUsername(self, username):
if not os.path.exists("game.db"):
self.createTable()
conn = sqlite3.connect('game.db')
if username.strip() == '':
return False
c = conn.cursor()
cursor = c.execute("SELECT USERNAME FROM USER WHERE USERNAME = '" + username + "'");
name = ''
for row in cursor:
name = row[0]
conn.close()
if name == '':
return True
else:
return False
if __name__ == '__main__':
sql = Sql()
print sql.update('wy123',100,100,1,0)
|
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
try:
city = input('Enter a city: ').lower()
if city in ('chicago', 'new york city', 'washington'):
break
else:
print('\nNo city with this name: try again!')
except ValueError:
print('That\'s not a valid name!')
# get user input for month (all, january, february, ... , june)
while True:
try:
month = input('Choose one month to analyze or type \'all\' to get all of them: ').lower()
if month in ('all', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'):
break
else:
print('That\'s not a valid month! Try again!')
except ValueError:
print('That\'s not a valid month!')
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
try:
day = input('Choose one day of the week or type \'all\' to get all of them: ').lower()
if day in ('all', 'monday', 'tuesday', 'wednesday', 'thursay', 'friday', 'saturday', 'sunday'):
break
else:
print('That\'s not a valid day')
except ValueError:
print('That\'s not a valid day!')
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month
df = df[df['month'] == month]
# filter by day of week
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
#add hour column:
df['hour'] = df['Start Time'].dt.hour
return df
def raw_data(df):
"""Display raw data if the user wants. """
x = 5
while True:
raw_dt_display = input('\nDo you want to see raw data?\n').lower()
if raw_dt_display == 'yes' and x < len(df.index):
print(df.head(x))
x += 5
elif x > len(df.index): #and x % 5 < 5:
print(df.head((x + (x % 5))))
print('\nYou have reached the last line of the dataset!\n')
break
else:
break
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
print('The most common month is: ', df['month'].mode()[0])
# display the most common day of week
print('The most common day is: ', df['day_of_week'].mode()[0])
# display the most common start hour
print('The most common start hour is: ', df['hour'].mode()[0])
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
m_startstation = df['Start Station'].mode()[0]
print('The most commonly used start station is {}'.format(m_startstation))
# display most commonly used end station
m_endstation = df['End Station'].mode()[0]
print('The most commonly used end station is {}'.format(m_endstation))
# display most frequent combination of start station and end station trip
most_freq = df.groupby(['Start Station', 'End Station']).size().nlargest(1).reset_index(name='count')
print('The most frequent combination of start station and end station trip is {} and {}'.format(most_freq['Start Station'], most_freq['End Station']))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
print('Total travel time is {} seconds'.format(df['Trip Duration'].sum()))
# display mean travel time
print('Mean travel time is {} seconds'.format(df['Trip Duration'].mean()))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df, city):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_types = df['User Type'].value_counts()
print('Users by type: \n{}'.format(user_types))
# Display counts of gender
if city != 'washington':
user_gender = df['Gender'].value_counts()
print('Users by gender: {}'.format(user_gender))
else:
print('There is no gender data in Washington dataset!')
# Display earliest, most recent, and most common year of birth
if city != 'washington':
earliest = df['Birth Year'].min()
most_recent = df['Birth Year'].max()
most_common = df['Birth Year'].mode()
print('The earliest, most recent, and most common year of birth are {}, {}, {}, respectively'.format(earliest, most_recent, most_common))
else:
print('There is no birth year data in Washington dataset!')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def plot_data(df):
"""Displays plots if user choose yes."""
plot_true = input('\nWould you like to see some calculed statistics with plots? Enter yes or no\n').lower()
#display number of users per type with a bar plot
if plot_true == 'yes':
df['User Type'].value_counts().plot(kind='barh')
plt.ylabel('User Type')
plt.xlabel('Number of users')
plt.title('Number of users per type')
plt.show()
#display number of users per gender
df['Gender'].value_counts().plot(kind='barh')
plt.ylabel('Gender')
plt.xlabel('Number of users')
plt.title('Number of users per gender')
plt.show()
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
raw_data(df)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
plot_data(df)
#ask if user wants to restar the script
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
from math import sqrt
def dist(col1, col2):
return sqrt(sum([(col1[i]-col2[i])**2 for i in range(3)]))
def sort_dictionnary(dic):
return {e:dic[e] for e in sorted(dic)}
def give_bottom_left_corner(points):
""""
Give the bottom left point of the rectangle containing the given points.
It could be one of the given points.
"""
bottom_left_corner = list(points[0])
for point in points:
if point[0]<bottom_left_corner[0]: # update the min x
bottom_left_corner[0] = point[0]
if point[1]<bottom_left_corner[1]: # update the min y
bottom_left_corner[1] = point[1]
return tuple(bottom_left_corner)
def give_top_right_corner(points):
""""
Give the top right point of the rectangle containing the given points.
It could be one of the given points.
"""
top_right_corner = list(points[0])
for point in points:
if point[0]>top_right_corner[0]: # update the max x
top_right_corner[0] = point[0]
if point[1]>top_right_corner[1]: # update the max y
top_right_corner[1] = point[1]
return tuple(top_right_corner)
def is_inside(rectangle, button):
"""
Return true if the button is inside the rectangle.
rectangle and button are both lists of 2 elements containing bottom left point and top right point
"""
if button[0][0] > rectangle[0][0] and button[0][1] > rectangle[0][1] and button[1][0] < rectangle[1][0] and button[1][1] < rectangle[1][1]:
return True
else:
return False
def bb_intersection_over_minimum(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
left = max(boxA.left, boxB.left)
top = max(boxA.top, boxB.top)
right = min(boxA.right, boxB.right)
bottom = min(boxA.bottom, boxB.bottom)
# compute the area of intersection rectangle
interArea = max(0, right - left + 1) * max(0, bottom - top + 1)
# compute the area of both bounding boxes
boxAArea = (boxA.right - boxA.left + 1) * (boxA.bottom - boxA.top + 1)
boxBArea = (boxB.right - boxB.left + 1) * (boxB.bottom - boxB.top + 1)
# compute the intersection over minimum by taking the intersection
# area and dividing it by the minimum of the two bounding box areas
iom = interArea / float(min(boxAArea, boxBArea))
return iom
|
# Naming the file : avoid spaces, avoid upper cases, '_' can be used to separate words
# new_variables.py (python), newVariables.java (java)
# Variables are temporarily conatiners.
# Variables:
#naming: should not start numbers
# nameofthevariables = value , declaring and setting a value for the variable
vname = "Gulmira" #String data type
num = 45 #Integar data type
status = True #BOoLEAN data type
price = 45.954# Double/float data type
message = "Hello Class, we are starting to learn python!!!" # string data type
print('Hello again')
print (vname)
print(num)
vname= 'mukhammadjon' # I am resetting the value of vname variable
print(vname, num, status, price, message)
#NameError : name 'num' is not defined ---this means 'num' is created before the the line
#Data types : Strings, Integers (int) , Floats(floats), Boolean (bool)
#Exercises: 2-1
message = 'This is a message for exercises 2-1'
print(message)
message= 'new message is for exercise 2-2'
print(message)
# CTRL + D - duplicates the line that your cursor is on
# CTRL + C - COPIES the line that your cursor is on, you dont have to to highlight
# CTRL + V - Pastes the copied content to the next line
# Shift + alt +up/down --takes the line that your coursor is on to up/down
#selenium is a library ,package of codes bindings
#selenium is a file that's written in certain language (python, java,...)
#it needs to automate testing
#selenium driver is not application, it is a package of code .
# to be able to write a code , have some feedback we installed Pycharm
gulmira="I am learning well python"
print (gulmira)
|
#a comment, this is so you can read the program later
#anything after the # is ignored by python
print "I could have code like this" # and comment ignored here
#you can also use a comment to disable or comment out a piece of code:
#print "shit this wont run"
print "hey, but this will run" |
## For Users ##
#user_id = input("Enter your Membership Name: ")
#print("Hello! " + user_id)
def test():
name = input('enter name of the actor:')
if(name== 'Will Smith') or (name== "will smith"):
print ("Spies in Disguise")
print("I am Legend")
print("Gemini Man")
print("Suicide Squad")
else:
print("movie unavailable")
test()
def test():
name = input('Enter Movie from List:')
if(name == 'I am Legend') or (name== 'I am legend'):
print("post-apocalyptic thriller film")
print("This Movie has a 3.5 out of 5 stars")
elif(name == 'Gemini Man') or (name== 'gemini man'):
print("American action thriller film")
print ("This Movie has 3 out of 5 stars")
elif(name == 'Suicide Squad') or (name== 'suicide squad'):
print("American Superhero Film")
print("This Movie has a 2.5 out of 5 stars")
elif(name == 'Spies in Disguise') or (name== 'Spies in Disguise'):
print("Computer-Animated Spy Comedy Film")
print("This Movie has a 4.0 out of 5 stars")
else:
("This Movie is not available")
test()
|
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
# Implementacion de Red Neuronal (Secuencial) con Keras
#read data file
df = pd.read_csv('data/SolucionSuma.csv', header=None)
df.rename(columns={0: 'idSolucion', 1: 'idProblema', 2: 'parametrosEntrada', 3: 'salida'}, inplace=True)
#df.to_csv('data/SolucionSuma.csv', index=False) # save to new csv file
#check data has been read in properly
df.head()
#create a dataframe with all training data except the target column
train_X = df.drop(columns=['idSolucion', 'idProblema', 'salida'])
# new data frame with split value columns
new = train_X["parametrosEntrada"].str.split(",", n=1, expand=True)
# making separate first name column from new data frame
train_X["entradaUno"] = new[0].astype(int)
# making separate last name column from new data frame
train_X["entradaDos"] = new[1].astype(int)
# Dropping old Name columns
train_X.drop(columns=["parametrosEntrada"], inplace=True)
test_X = train_X.iloc[ 0:5 ,]
print(test_X.head())
#check that the target variable has been removed
#print(train_X.dtypes)
#create a dataframe with only the target column
train_y = df[['salida']].astype(int)
#view dataframe
#print(train_y.dtypes)
#create model
model = Sequential()
#get number of columns in training data
n_cols = train_X.shape[1]
print(n_cols)
#add model layers
model.add(Dense(200, activation='relu', input_shape=(n_cols,)))
model.add(Dense(200, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(1))
#compile model using mse as a measure of model performance
model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()
#set early stopping monitor so the model stops training when it won't improve anymore
early_stopping_monitor = EarlyStopping(patience=10)
#train model
model.fit(train_X, train_y, validation_split=0.2, epochs=4000,callbacks=[early_stopping_monitor])
#example on how to use our newly trained model on how to make predictions on unseen data (we will pretend our new data is saved in a dataframe called 'test_X').
test_y_predictions = model.predict(test_X)
print(test_y_predictions.astype(int)) |
from cipher import Cipher
from text import Text
from english import ENGLISH_LETTERS
class Affine(Cipher):
def __init__(self, text):
super(Affine, self).__init__(text)
def decipher(self):
best_result = Text(self.text)
# go through all possible affine alphabets
for a in ( 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25 ):
for b in range(26):
cur_cipher = Text( self.encipher(a, b) )
# if cur_cipher looks more like english than best_result, it becomes the best_result
if cur_cipher.english_words > best_result.english_words:
best_result = cur_cipher
return str(best_result)
# Returns a string of ciphertext
def encipher(self, a, b):
# create new alphabet based on parameter a, b
alphabet = Affine.create_alphabet(a, b)
# convert each character in text to cipher character
# ord('a') = 97
cipher = [ alphabet[ch] for ch in self.text ]
return "".join(cipher)
@staticmethod
def create_alphabet(a, b):
# chr(97) = 'a'
return { ch: chr( 97 + (a * x + b) % 26) for x, ch in enumerate(ENGLISH_LETTERS) }
|
'''
How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.
I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it? According to Wikipedia, ROT13 (http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes on USENET.
Hint: For this task you're only supposed to substitue characters. Not spaces, punctuation, numbers etc. Test examples:
rot13("EBG13 rknzcyr.") == "ROT13 example.";
rot13("This is my first ROT13 excercise!" == "Guvf vf zl svefg EBG13 rkprepvfr!"
# list comprehension
# new_list = [expression(i) for i in old_list if filter(i)]
x = [i for i in range(10)]
print(x)
# This will give the output:
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
def rot13char(letter):
if letter.isupper():
num_return_char = (ord(letter) - ord("A") + 13) % 26
return_char = chr(num_return_char + ord("A"))
elif letter.islower():
num_return_char = (ord(letter) - ord("a") + 13) % 26
return_char = chr(num_return_char + ord("a"))
else: return letter
# char = chr(ord("E")+13) #A = 65 Z = 90 a = 97 z = 122
return return_char
def rot13(phrase):
return_phrase = [rot13char(letter) for letter in phrase]
return "".join(return_phrase)
print(rot13("EBG13 rknzcyr.")) #ROT13 example.
print(rot13("This is my first ROT13 excercise!")) # == "Guvf vf zl svefg EBG13 rkprepvfr!"
print(rot13("Guvf vf zl svefg EBG13 rkprepvfr!")) # == "Guvf vf zl svefg EBG13 rkprepvfr!"
'''
best practices
def rot13(message):
return message.encode('rot13')
def rot13(message):
def decode(c):
if 'a' <= c <= 'z':
base = 'a'
elif 'A' <= c <= 'Z':
base = 'A'
else:
return c
return chr((ord(c) - ord(base) + 13) % 26 + ord(base))
return "".join(decode(c) for c in message)
import string
def rot13(message):
first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
return message.translate(string.maketrans(first, trance))
''' |
'''
Simple Pig Latin
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !
'''
def is_punctuation(word):
return word[0] not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYX'
def pig_word(word):
if is_punctuation(word): return word
else: return word[1:] + word[0] + "ay"
def pig_it(sentence):
words_list = sentence.split()
new_words_list = []
for word in words_list:
new_words_list.append(pig_word(word))
separator = ' '
return separator.join(new_words_list)
print(pig_it('Pig latin is cool')) # igPay atinlay siay oolcay
print(pig_it('Hello world !')) # elloHay orldway !
'''
best practice 1
def pig_it(text):
lst = text.split()
return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])
best practice 2
def pig_it(text):
res = []
for i in text.split():
if i.isalpha():
res.append(i[1:]+i[0]+'ay')
else:
res.append(i)
return ' '.join(res)
''' |
from csp import Constraint, CSP
class QueensConstraint(Constraint):
def __init__(self, columns):
super().__init__(columns)
self.columns = columns
def satisfied(self, assignment):
# q_0_c = queen 0 column, q_0_r = queen 0 row
for q_0_c, q_0_r in assignment.items():
# q_1_c = queen 1 column
for q_1_c in range(q_0_c + 1, len(self.columns) + 1):
if q_1_c in assignment:
q_1_r = assignment[q_1_c] # q_1_r = queen 1 row
if q_0_r == q_1_r: # Same row?
return False
if abs(q_0_r - q_1_r) == abs(q_0_c - q_1_c): # Same diagonal?
return False
return True
if __name__ == '__main__':
columns = list(range(1, 9))
rows = {}
for column in columns:
rows[column] = list(range(1, 9))
csp = CSP(columns, rows)
csp.add_constraint(QueensConstraint(columns))
solution = csp.backtracking_search()
if solution is None:
print('No solution found!')
else:
print(solution)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.