text
stringlengths 37
1.41M
|
---|
# LEVEL 4
# http://www.pythonchallenge.com/pc/def/linkedlist.php
# 12345
# 44827
# 45439
# 94485
# 72198
# http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345
# and the next nothing is 44827
import re
import urllib.request
nothing = '12345'
finish = False
while not finish:
response = urllib.request.urlopen(
'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' + nothing).read().decode("utf-8")
all = re.findall('nothing is (\d*)', response)
if all:
nothing = all[0]
print(nothing)
else:
finish = True
print(response)
nothing = str(int(int(nothing) / 2))
finish = False
while not finish:
response = urllib.request.urlopen(
'http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=' + nothing).read().decode("utf-8")
all = re.findall('nothing is (\d*)', response)
if all:
nothing = all[0]
print(nothing)
else:
finish = True
print(response)
|
# LEVEL 28
# http://www.pythonchallenge.com/pc/ring/bell.html
from PIL import Image
img = Image.open('data/bell.png')
R, G, B = 0, 1, 2
w, h = img.size
# w, h = 20, 20
print(img.mode)
print(img.size)
print(img.info)
# the picture shows vertical stripes, let's try the horizontal differences by pairs
for y in range(h):
for x in range(0, w, 2):
dif = abs(img.getpixel((x, y))[G] - img.getpixel((x + 1, y))[G])
if dif != 42:
print(chr(dif), end='')
print()
# he hidden message is whodunnit().split()[0] ?
def whodunnit():
return 'Guido van Rossum'
print(whodunnit().split()[0])
|
"""RL Policy classes.
"""
import numpy as np
import attr
import random
class Policy:
"""Base class representing an MDP policy.
Policies are used by the agent to choose actions.
Policies are designed to be stacked to get interesting behaviors
of choices. For instances in a discrete action space the lowest
level policy may take in Q-Values and select the action index
corresponding to the largest value. If this policy is wrapped in
an epsilon greedy policy then with some probability epsilon, a
random action will be chosen.
"""
def select_action(self, **kwargs):
"""Used by agents to select actions.
- Output
- Any:
An object representing the chosen action. Type depends on
the hierarchy of policy instances.
"""
raise NotImplementedError('This method should be overriden.')
class UniformRandomPolicy(Policy):
"""Uniformly randomly Chooses a discrete action.
- Parameters
- num_actions: int
Number of actions to choose from. Must be > 0.
- Raises
- ValueError:
If num_actions <= 0
"""
def __init__(self, num_actions):
assert num_actions >= 1
self.num_actions = num_actions
def select_action(self, **kwargs):
"""Return a random action index.
- Output
- int
Action index in range [0, num_actions)
"""
return np.random.randint(0, self.num_actions)
def get_config(self):
return {'num_actions': self.num_actions}
class GreedyPolicy(Policy):
"""Always returns the best action according to Q-values.
This is a pure exploitation policy.
"""
def select_action(self, q_values, **kwargs):
"""Return a random action index.
- Input
- q_values: np.array
Q-values for all actions
- Output
- int
Action index in range [0, num_actions)
"""
return np.argmax(q_values)
class GreedyEpsilonPolicy(Policy):
"""Selects greedy action or with some probability a random action.
Standard greedy-epsilon implementation. With probability epsilon
choose a random action. Otherwise choose the greedy action.
- Parameters
- num_actions: int
Number of actions to choose from. Must be > 0.
- epsilon: float
- Initial probability of choosing a random action.
"""
def __init__(self, epsilon, num_actions):
self.epsilon = epsilon
assert num_actions >= 1
self.num_actions = num_actions
def select_action(self, q_values, **kwargs):
"""Run Greedy-Epsilon for the given Q-values.
- Input
- q_values: np.array
Q-values for all actions
- Output
- int
The action index chosen.
"""
x = random.uniform(0, 1)
if x > self.epsilon:
return np.argmax(q_values)
return np.random.randint(0, self.num_actions)
class LinearDecayGreedyEpsilonPolicy(Policy):
"""Policy with a parameter that decays linearly.
Like GreedyEpsilonPolicy but the epsilon decays from a start value
to an end value over k steps.
- Parameters
- start_value: float
The initial value of the parameter
- end_value: float
The value of the policy at the end of the decay.
- decay: int
The number of steps over which to decay the value.
- eps: float
Current epsilon
- num_actions: int
The number of actions
"""
def __init__(self, start_value, end_value, decay, num_actions):
self.start_value = start_value
self.end_value = end_value
self.decay = float(start_value - end_value) / decay
self.eps = start_value
self.num_actions = num_actions
def select_action(self, q_values, **kwargs):
"""Decay parameter and select action.
- Input
- q_values: np.array
The Q-values for each action.
- is_training: bool, optional
If true then parameter will be decayed. Defaults to true.
- Output
- int
Selected action index.
"""
is_training = kwargs.pop('is_training', True)
x = random.uniform(0, 1)
if x > self.eps:
action = np.argmax(q_values)
else:
action = np.random.randint(0, self.num_actions)
if is_training:
self.eps = max(self.eps - self.decay, self.end_value)
return action
def reset(self):
"""Start the decay over at the start value."""
self.eps = start_value
self.num_steps = 0
|
fname=input("enter file name")
fopen=open(fname)
dic=dict()
for line in fopen:
words=line.split()
for word in words:
dic[word]=dic.get(word,0)+1
highestcount=0
highestword=None
for k,v in dic.items():
if v>highestcount:
highestcount=v
highestword=k
|
def get_name():
name = input("What's your name? ==> ")
return name
def greet_name(your_name):
print("Hello, %s!" % your_name)
|
def part_one(data):
expenses = strings_to_integers(data)
first, second = find_two_sum(expenses, 2020)
return first * second
def strings_to_integers(data):
return list(map(int, data.split()))
def find_two_sum(integers, target_sum):
integers = sorted(integers)
low_index = 0
high_index = -1
total = 0
while total != target_sum:
total = integers[low_index] + integers[high_index]
if total == target_sum:
return (integers[low_index], integers[high_index])
elif low_index == len(integers)-1 or high_index == 0-len(integers):
break
elif total > target_sum:
high_index -= 1
elif total < target_sum:
high_index = -1
low_index += 1
def part_two(data):
expenses = strings_to_integers(data)
first, second, third = find_three_sum(expenses, 2020)
return first * second * third
def find_three_sum(integers, target_sum):
for i in integers:
new_integers = integers
new_integers.remove(i)
new_target_sum = target_sum - i
result = find_two_sum(new_integers, new_target_sum)
if result is None:
continue
else:
return {i, result[0], result[1]}
|
#Uma escola te contratou para desenvolver um programa em Python para que o
#professor gerencie as notas de seus alunos. Seu programa deve apresentar o seguinte
#menu:
#0. Sair
#1. Exibir lista de alunos com suas notas (cada aluno tem uma nota)
#2. Inserir aluno e nota
#3. Alterar a nota de um aluno
#4. Consultar nota de um aluno específico
#5. Apagar um aluno da lista
#6. Exibir a média da turma
#As notas e os nomes dos alunos serão fornecidos pelo professor. Implemente a sua
#solução utilizando dicionário.
import time
opcao = ''
alunos ={}
while opcao != 0:
print('Menu')
print('0. Sair')
print('1. Exibir lista de alunos com suas notas (cada aluno tem uma nota)')
print('2. Inserir aluno e nota')
print('3. Alterar a nota de um aluno')
print('4. Consultar nota de um aluno específico')
print('5. Apagar um aluno da lista')
print('6. Exibir a média da turma')
opcao = int(input('\nEscolha uma das opções: \n'))
if opcao == 1:
print(alunos)
elif opcao == 2:
nome = input('Nome do aluno: ')
nota = float(input('Notas do aluno: '))
alunos[nome] = nota
elif opcao == 3:
nome = input('Nome do aluno: ')
nota = float(input('Notas do aluno: '))
alunos.update({nome: nota})
elif opcao == 4:
nome = input('Nome do aluno: ')
print(alunos.get(nome))
elif opcao == 5:
nome = input('Nome do aluno que deseja apagar: ')
print('Nota:',alunos.get(nome), 'apagado com sucesso')
del alunos[nome]
elif opcao == 6:
media = sum(alunos.values())/len(alunos)
print('Média da turma {0:.1f}'.format(media))
|
#Faça um programa que leia dez conjuntos de dois valores,
# o primeiro representando o número do aluno e o segundo representando a sua altura em centímetros.
# Encontre o aluno mais alto e o mais baixo. Mostre o número do aluno mais alto e o número do aluno mais baixo, junto com suas alturas.
num_aluno = []
altura_aluno = []
n_aluno = 1
numero = True
while num_aluno != 10:
print("\nAluno n° ", n_aluno)
numero = int(input("Digite o numero do aluno: "))
if numero == 0:
break
else:
altura = float(input("Digite a altura: "))
num_aluno.append(numero)
altura_aluno.append(altura)
n_aluno += 1
num_alto = altura_aluno.index(max(altura_aluno))
num_baixo = altura_aluno.index(min(altura_aluno))
print()
print("Número do mais alto: ", num_aluno[num_alto],"medindo:",max("{0:.2f}".format(altura_aluno)))
print("Número do mais baixo: ", num_aluno[num_baixo],"medindo:",min("{0:.2f}".format(altura_aluno)))
|
class conta():
def __init__(self,titular, saldo):
self.titular = titular
self.saldo = saldo
def depositar(self,valor_deposito):
self.saldo = self.saldo + valor_deposito
def sacar(self, valor_saque):
if valor_saque > self.saldo:
print('saldo insuficiente')
else:
self.saldo = self.saldo - valor_saque
titular = input('Digite o nome do titular da conta: ')
saldo = float(input('Digite o valor do saldo inicial da conta: '))
conta1 = conta(titular, saldo)
print('Nome do titular: {}, seu saldo é: R${:0.2f}'.format(conta1.titular, conta1.saldo))
deposito = float(input('Quanto deseja depositar: '))
conta1.depositar(deposito)
print('Depósito efetuado no valor de: R${:0.2f}, seu saldo atualizado é: R${:0.2f}'.format(deposito, conta1.saldo))
saque = float(input('Quanto deseja sacar: '))
conta1.sacar(saque)
print('Saque no valor de: R${:0.2f} efetuado com sucesso, seu saldo atualizado é: R${:0.2f}'.format(saque, conta1.saldo))
|
#Crie um programa onde você cadastre a data de nascimento (dd/mm/aa) de algumas
#celebridades em um dicionário. Ao escolher uma celebridade, seu programa deve
#retornar a data completa. Não esqueça de validar se a celebridade escolhida está
#presente em seu dicionário.
celebridades = {'Albert Eisntein': '14/03/1979', 'Benjamin Franklin': '17/01/1706', 'Chuck Norris': '10/03/1940', 'Donald Trump': '14/06/1946', 'Bruce Lee': '27/11/1940', 'Rowan Atkinson': '06/01/1955' }
def buscar_celebridades(key):
print(celebridades.get(key))
print('Bem vindo ao nosso calendário. Sabemos a data de nascimento das seguintes celebridades: \nAlbert Eisntein \nBenjamin Franklin \nBruce Lee \nChuck Norris \nDonald Trump \nRowan Atkinson')
nome = input("Digite o nome da celebridade que deseja saber a data de nascimento: ")
while nome not in celebridades:
print('Essa celebridade não consta em nossa lista!!!')
print('Sabemos a data de nascimento das seguintes celebridades: \nAlbert Eisntein \nBenjamin Franklin \nBruce Lee \nChuck Norris \nDonald Trump \nRowan Atkinson')
nome = input("Digite o nome da celebridade que deseja saber a data de nascimento: ")
buscar_celebridades(nome)
|
#08 - Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário.
# Se por acaso a CTPS for diferente de 0, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente ,
# além da idade, com quantos anos a pessoa vai se aposentar. Considere que o trabalhador deve contribuir por 35 anos para se aposentar.
import datetime
dados_funcionario = {}
nome = input("\nDigite o nome do funcionário: ")
data_nasc = input("Digite o ano de nascimento (dd/MM/yyyy): ")
dtn= datetime.datetime.strptime(data_nasc, "%d/%m/%Y")
ctps = input("Digite o número da carteira de trabalho: ")
idade= datetime.datetime.now().year - dtn.year
dados_funcionario[ctps]= nome
dados_funcionario['data de nascimento'] = data_nasc
dados_funcionario['idade'] = idade
if ctps != 0:
data_contrat = input("Digite o ano de contratação (dd/MM/yyyy):")
dtc= datetime.datetime.strptime(data_contrat, "%d/%m/%Y")
aposentadoria = (dtc.year - dtc.year) + 35 + idade
salario = input("Digite o salário:")
dados_funcionario['ano da contratação']= data_contrat
dados_funcionario['salário']= salario
dados_funcionario['previsão da aposentadoria']= aposentadoria
print(dados_funcionario)
|
#Escreva um programa que determine todos os números de 4 algarismos que possam ser separados em dois números de dois algarismos que somados e
# elevando-se a soma ao quadrado obtenha-se o próprio número.
for x in range(1000,10000):
n1 = x // 100
n2 = x % 100
if(n1+n2)**2 == x:
print(x)
|
def most_prolific(dict):
year = []
occurences = {}
maxnumber = 0
for items in dict.values():
year.append(items)
# print(year)
for y in year:
if y in occurences:
occurences[y] = occurences[y] + 1
else:
occurences[y] = 1
for o in occurences:
if occurences[o] > maxnumber:
maxyears = []
maxyears.append(o)
maxnumber = occurences[o]
# print(maxnumber)
# print(maxyears)
elif occurences[o] == maxnumber and not (o in maxyears):
maxyears.append(o)
if (len(maxyears) == 1):
return maxyears[0]
else:
return maxyears
Beatles_Discography = {"Please Please Me": 1963, "With the Beatles": 1963,
"A Hard Day's Night": 1964, "Beatles for Sale": 1964, "Twist and Shout": 1964,"Help": 1965, "Rubber Soul": 1965, "Revolver": 1966,
"Sgt. Pepper's Lonely Hearts Club Band": 1967,
"Magical Mystery Tour": 1967, "The Beatles": 1968,
"Yellow Submarine": 1969, 'Abbey Road': 1969,
"Let It Be": 1970}
print(most_prolific(Beatles_Discography))
|
#find maximum profit of the stock prices
stock_prices=[23,44,53,11,2,3,178,98]
#21+9+1+175
profit=0
for i in range(1,len(stock_prices)):
if stock_prices[i]>stock_prices[i-1]:
profit+=stock_prices[i]-stock_prices[i-1]
print(profit)
|
numbers1 = [1,2,5,7];
numbers2 = [2,3,7,9];
for num in numbers1:
if num in numbers2:
print(str(num) + "在numbers中");
else:
print(str(num) + "不在在numbers中");
|
# 不可变的列表称为元组
areas = (10,20);
print(areas[0]);
print(areas[1]);
# area[0] = 1;
print(areas[0])
for val in areas:
print(val);
# 区别Java的final 修饰变量
ages = (22,23);
print(ages);
ages = (30,32);
print(ages);
|
# Python
# By Kulter Ryan
# https://github.com/kulterryan/
# Calculating Download Speed of A File
# Last Edit: 09/04/2021
# import Libraries
import time
# Welcome Screen
print("Hi There")
print("Download Time Calculator")
print("** Only 'mbps' to 'MBps' is currently available. ** ")
# Input Screen
downloadspeed = int(input("Enter Download Speed (in mbps): "))
filesizeF = int(input("Choose the File Size format:\n1. GB\n2. MB\nEnter your Choice: "))
# Predefined
def time_convert(downloadtime):
return time.strftime("%H:%M:%S", time.gmtime(downloadtime))
# For File Size Consversion
def dt_conversion_mb(downloadspeed):
filesize_Mb = float(input("Enter File Size (in): ")) # File Size Mb = MegaBytes
if (filesizeF==1): # For GB Conversion to Bits
filesize_bit = filesize_Mb * 1000 * 1000 * 1000 * 8
elif (filesizeF==2): # For MB Conversion to Bits
filesize_bit = filesize_Mb * 1000 * 1000 * 8
else:
print("Incorrect Input! See YA!")
filesize_mb = filesize_bit / (1000*1000)
# print(filesize_mb)
downloadtime = filesize_mb / downloadspeed
# print(downloadtime)
downloadrate = round(((filesize_mb/8) / downloadtime), 3)
# print(downloadrate)
totaltime = time_convert(downloadtime)
print("Total Download Time (HH:MM:SS):", totaltime)
print("Rate of File Downloading", downloadrate, "MBs Per Second")
# print("Speed Entered: ", downloadspeed, "mbps")
dt_conversion_mb(downloadspeed)
|
import copy
import gc
class AppendException(Exception):
pass
class ForEachException(Exception):
pass
class RecordKeyError(Exception):
pass
class Store:
"""
This is the class for stores in the database
Attributes:
store (dict({string: string | dict | list)): The records stored in the database
"""
def __init__(self):
self.__store = {}
def set_record(self, record_name, value):
"""
The function to set the record with the given name to the given value.
Parameters:
record_name (string): The name of the record
expr (string | dict | list): The value or reference associated with the record
"""
self.__store[record_name] = copy.deepcopy(value)
def append_record(self, record_name, value):
"""
The function to append the record with the given name with the given value.
Parameters:
record_name (string): The name of the record
expr (string | dict | list): The value or reference to be appended to the record
is_ref (bool): Whether the element is a literal value or a reference
Errors:
AppendException(): If the value associated with the record name is not a list
"""
record = self.__store[record_name]
if not isinstance(record, list):
raise AppendException("unable to append record to non-list object")
else:
if isinstance(value, list):
gc.disable()
record.extend(value)
gc.enable()
else:
gc.disable()
record.append(value)
gc.enable()
self.__store[record_name] = record
def read_record(self, record_name):
"""
The function to read a record from the store. Recursively reads the record
from the database reading each of the dots in the reference
Parameters:
record_name (string): The name of the record
Returns:
value (string | dict | list | None): A deepcopy of the original record
"""
record = self.__store
for elem in record_name.split('.'):
if elem not in record:
return None
record = record[elem]
return record
def delete_record(self, record_name):
"""
The function to delete the record from the store. Recursively reads the record
from the database reading each of the dots of the reference
Parameters:
record_name (string): The name of the record
Errors:
RecordKeyError(): If the record does not exist in the store
"""
record = self.__store
split_record_name = record_name.split('.')
for i in range(len(split_record_name) - 1):
if split_record_name[i] not in record:
return RecordKeyError("record not in database")
record = record[split_record_name[i]]
del record[split_record_name[-1]]
|
def twoCitySchedCost(costs: [[int]]) -> int:
sum=0
sorted_cost=sorted(costs,key=lambda x: x[0]-x[1])
for i in range(len(costs)):
if(i<len(costs)//2):
sum+=sorted_cost[i][0]
else:
sum+=sorted_cost[i][1]
return sum
print(twoCitySchedCost([[10,20],[30,200],[400,50],[30,20]]))
|
class Trie_Node:
def __init__(self):
self.endofword=False
self.children={}
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root=Trie_Node()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
nroot=self.root
for i in word:
# index=ord(i)-ord('a')
if i not in nroot.children:
nroot.children[i]=self.root
nroot=nroot.children[i]
nroot.endofword=True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
nroot=self.root
for j in word:
# index=ord(j)-ord('a')
if j not in nroot.children:
return False
nroot=nroot.children[j]
return nroot.endofword
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
nroot=self.root
for i in prefix:
# index=ord(i)-ord('a')
if not nroot.children:
return False
nroot=nroot.children[i]
return True
obj=Trie()
obj.insert("apqle")
print(obj.search("ap"))
|
def arrangeWords(text) -> str:
words = text.split()
str=" "
words.sort(key=len,reverse=False)
return (str.join(words).capitalize())
# for w in words:
# print(w)
print(arrangeWords("Leetcode is cool"))
|
from tkinter import *
from tkinter import messagebox as ms
import sqlite3
win = Tk()
win.geometry('800x800')
win.title("Login Form")
#field for gui
UserName=StringVar()
Password=StringVar()
def database():
un=UserName.get()
print(un)
ps=Password.get()
print(ps)
#connection with db
conn = sqlite3.connect('Register.db')
with conn:
cursor=conn.cursor()
cursor.execute("select * from Student where Name=='"+un+"'and Pass=='"+ps+"'")
result=cursor.fetchone()
if result==None:
ms.showwarning("invalid Entry")
else:
ms.showwarning("Login Detail "," User_Name " + UserName.get()+" Password: "+Password.get())
#label1=tk.Label(ms,text="Your name: "+un.get())
#label2=tk.Label(ms,text="Your password: "+ps.get())
#label1.place(x=10,y=125)
#label2.place(x=10,y=150)
Uname= Label(win, text="UserName",width=20)
Uname.place(x=80,y=130)
Uname1 = Entry(win,textvar=UserName)
Uname1.place(x=240,y=130)
Pwd= Label(win, text="Password",width=20)
Pwd.place(x=68,y=180)
Pwd1 = Entry(win,textvar=Password)
Pwd1.place(x=240,y=180)
Button(win, text='Login',width=20,bg='brown',fg='white',command=database).place(x=180,y=420)
win.mainloop()
|
#!/usr/bin/env python
# coding: utf-8
# # Scales in Python
# In[2]:
import pandas as pd
# In[ ]:
s = pd.Series(['Low', 'Low', 'High', 'Medium', 'Low', 'High', 'Low'])
s.astype('category', categories=['Low', 'Medium', 'High'], ordered=True)
# # Cut Data into bins to build interval data
# In[3]:
s = pd.Series([168, 180, 174, 190, 170, 185, 179, 181, 175, 169, 182, 177, 180, 171])
pd.cut(s, 3)
# You can also add labels for the sizes [Small < Medium < Large].
pd.cut(s, 3, labels=['Small', 'Medium', 'Large'])
# # Pivot Tables - Means of summarising data
# In[ ]:
df.pivot_table ( vlues = '(kW)', index = 'YEAR',COLUMNS = 'Make', aggfunc = np.mean)
#Another Way
print(pd.pivot_table(Bikes, index=['Manufacturer','Bike Type']))
# Another Way to see that allows us to see the All Totals
df.pivot_table ( vlues = '(kW)', index = 'YEAR',COLUMNS = 'Make', aggfunc = [np.mean,np.min], Margins = True)
|
nu1 = float(input("Enter First Number: "))
nu2 = float(input("Enter Second Number: "))
nu3 = float(input("Enter Third Number: "))
if (nu1 >= nu2) and (nu1 >= nu3):
largest = nu1
elif (nu2 >= nu1) and (nu2 >= nu3):
largest = nu2
else:
largest = nu3
print("The Largest Number Between", nu1, ",", nu2, "&", nu3,"is",largest)
|
from Matrix import Matrix
from Vector import Vector
from Algebra import *
class EigenVector:
'''
Helper Functions to Compute Eigenvectors
'''
@classmethod
def orig_mat(cls, diagonal_matrix, eigenvectors):
'''
Given the Diagonal Matrix D and Eigenvectors, compute the original matrix A
Formulation: P^-1 A P = D
A P = P D
A = P D P^-1
Eigenvectors: Square Matrix of eigenvectors
'''
assert diagonal_matrix.is_square() and eigenvectors.is_square()
P_inverse = Matrix.compute_square_inverse(copy.deepcopy(eigenvectors))
return Matrix.matmul(Matrix.matmul(eigenvectors, diagonal_matrix), P_inverse)
@classmethod
def find_orig_mat(cls, eigenvectors, eigenvalues):
'''
Given eignevectors and eigenvalues, we can compute the orig matrix A.
Formulation: P^-1 A P = D
D = eigenvalues
P = eigenvectors
Solve for A
eigenvectors: Square Matrix of vectors
eigenvalues: list of eigen
'''
W, H = eigenvectors.get_size()
assert W == H and W == len(eigenvalues)
# Form Diagonal Matrix
diag_matrix = Matrix(W, W)
for i in range(W):
diag_matrix.set_value(i, i, eigenvalues[i])
# Solve for A using helper
return EigenVector.orig_mat(diag_matrix, eigenvectors)
@classmethod
def trace(cls, matrix):
'''
Computes the trill of a square
'''
width, height = matrix.get_size()
trace = 0
for i in range(width):
trace += matrix.get_value(i, i)
return trace
@classmethod
def compute_eigen(cls, matrix):
'''
Computes the eigenvalues and eigenvectors of matrixA, return eigen pairs of form (eigenvalue, eigenvector)
'''
matrix = copy.deepcopy(matrix)
eigenvalues = EigenVector.compute_eigenvalues(matrix)
eigenvectors = EigenVector.compute_eigenvectors(matrix, eigenvalues, filter_zeros=False)
eigenpairs = []
for idx in range(len(eigenvectors)):
eigenvec = eigenvectors[idx]
eigenval = eigenvalues[idx]
if Vector.sum_all(eigenvec) == 0:
eigenpairs += [(eigenval, "Invalid Eigenvector(All 0s)")]
else:
eigenpairs += [(eigenval, eigenvec)]
return eigenpairs
@classmethod
def valid_eigenvalue(cls, eigenvalue, matrix):
'''
Checks if an eigenvalue is valid or not
'''
assert Matrix.is_square()
W, H = matrix.get_size()
eigenvectors = EigenVector.compute_eigenvectors(matrix, [eigenvalue], filter_zeros = True)
return len(eigenvectors) > 0
@classmethod
def find_eigenvalues(cls, matrix, eigenvector):
'''
Finds the eigenvalue associated with the matrix, if it exists.
matrix: Matrix
eigenvector: Vector
'''
assert matrix.is_square()
W, H = matrix.get_size()
eigenmat = Matrix(1, W)
eigenmat.list_fill([[val] for val in eigenvector.values])
# Ax
Ax = Matrix.matmul(matrix, eigenmat)
# Find if x is a scalar muliple of Ax
ax_1 = Ax.get_value(0, 0)
x_1 = eigenmat.get_value(0, 0)
eigenvalue = ax_1 / x_1
# Sanity Check
if len(eigenvector) > 1:
# Check second position to see if valid
ax_2 = Ax.get_value(1, 0)
x_2 = eigenmat.get_value(1, 0)
if x_2 * eigenvalue != ax_2:
return False
return eigenvalue
@classmethod
def valid_eigenvector(cls, eigenvector, matrix):
'''
Checks if an eigenvector is valid
eigenvector: Vector
matrix: MatrixA
'''
return EigenVector.find_eigenvalues(matrix, eigenvector) != False
@classmethod
def compute_eigenvalues(cls, matrix):
'''
Computes eigenvalues of a matrix(Unique eigen values, will not return the algebraic multiplicity of each one - Need to factor for this.)
'''
matrix = copy.deepcopy(matrix)
assert matrix.is_square(), "Matrix must be square."
# Equation: det(A - LambdaI) = 0
# Construct Algebraic Expression Matrix
W, H = matrix.get_size()
for i in range(W):
x = AlgebraicExpression()
x.add_exp(Variable(matrix.get_value(i, i), 0))
x.add_exp(Variable(-1, 1))
matrix.set_value(i, i, x)
# Compute Determinant
det = Matrix.recursive_determinant(matrix)
# Solve for roots using brute-force(I cant factor with Python)
roots = AlgebraicExpression.brute_force_root_search(det)
return roots
@classmethod
def compute_eigenvectors(cls, matrix, eigenvalues, filter_zeros = True):
'''
Computes EigenVectors of a matrix, using the eigen values
'''
matrix = copy.deepcopy(matrix)
# Formula (A - LambdaI) x = 0
assert matrix.is_square()
W, H = matrix.get_size()
result = []
for eigen in eigenvalues:
identity = Matrix(W, H)
identity.fill_identity()
identity = Matrix.scal_mult(identity, eigen)
eigen_vec = Matrix.sub(copy.deepcopy(matrix), identity)
reduced = Matrix.RREF(eigen_vec)
# Extract Valid Rows
valid_rows = Matrix.remove_empty_rows(reduced)
# Substitute Variables to get eigen vector.
eigenvector = Vector([0 for i in range(len(valid_rows[0]))])
for vec_idx in range(len(valid_rows)):
# Note that x^2 = x_2 in the algebraic expression
vec = valid_rows[vec_idx]
right = Vector.extract_right(vec, vec_idx)
# Check if empty: then 0
if Vector.sum_all(right) == 0:
eigenvector.values[vec_idx] = 0
else:
alg_exp = AlgebraicExpression()
for i in range(len(right)):
alg_exp.add_exp(Variable(-right.values[i], i + vec_idx + 1))
eigenvector.values[vec_idx] = alg_exp
if filter_zeros:
# Check for fully 0 eigen vector
if Vector.sum_all(eigenvector) == 0:
pass
else:
result += [eigenvector]
else:
result += [eigenvector]
return result
def main():
matrix = Matrix(3, 3)
matrix.list_fill([[3, 6, 7], [3, 3, 7], [5, 6, 5]])
vec = Vector([1, -2, 1])
print(EigenVector.valid_eigenvector(vec, matrix))
if __name__ == '__main__':
main()
|
feet = float(input("Please enter a number of feet to convert to meters: "))
meters = feet * .305
print (meters)
|
Rows = int(4)
A = int(1)
print("a a^2 a^3")
for row in range(Rows):
a2 = int(A**2)
a3 = int(A**3)
print(A, ' ',a2,' ',a3)
A+=1
|
name=input("enter name:")
age=input("enter age:")
print("name:" +name)
print("age:" +age)
x=100-age
if()
|
import re
from typing import Optional, List, Set
class Bag(object):
color: Optional[str] = None
outer_bag = None
bags: {} = {}
def __init__(self, color: str = None, bags=None, outer_bag=None) -> None:
super().__init__()
if bags is None:
bags = {}
self.color = str(color)
self.bags = bags
self.outer_bag = outer_bag
def __str__(self) -> str:
return "{} ({}) {}".format(self.color, self.count(), [str(bag) for bag in self.bags])
def contains(self, color: str) -> bool:
for bag in self.bags:
if bag.color == color:
return True
else:
if bag.contains(color):
return True
return False
def count(self) -> int:
_count: int = 0
for k in self.bags:
_count = _count + self.bags[k] + self.bags[k] * k.count()
return _count
def level(self) -> int:
if self.outer_bag is None:
return 0
else:
return self.outer_bag.level() + 1
bag_map: {str, Bag} = {}
bags: List[Bag] = []
def get_bag(color: str) -> Bag:
bag = bag_map.get(str(color))
if bag is None:
bag = Bag(color)
bag_map[str(color)] = bag
return bag
with open('input.txt', 'r') as input:
file = input.read()
for line in file.splitlines():
split = re.split("([\w\s]+)\s+bags\s+contain\s+(.*)", line)
outer_bag = get_bag(split[1])
if split[2].startswith('no other bags'):
pass
else:
parts = split[2].split(',')
for part in parts:
sub_split = re.split("(\d+)\s+([\w\s]+)\s+bags?", part)
bag = get_bag(sub_split[2])
bag.outer_bag = outer_bag
outer_bag.bags[bag] = int(sub_split[1])
bags.append(outer_bag)
count: int = 0
for bag in bags:
if bag.contains('shiny gold'):
count = count + 1
print(count)
print(bag_map['shiny gold'].count())
|
#!/bin/python
from typing import List, Set
def max_dist(x: int) -> int:
distance: int = 0
while x > 0:
distance += x
if x > 0:
x -= 1
elif x < 0:
x += 1
return distance
def calc_height(y: int, target_y: List[int]) -> int:
height: int = 0
while height > min(target_y):
height += y
def max_height(target_y: List[int]) -> int:
step: int = abs(min(target_y)) - 1
y: int = 0
max_height: int = 0
while not (min(target_y) < y < max(target_y)) and y > min(target_y):
y = y + step
step -= 1
if y > max_height:
max_height = y
return max_height
def y_steps(start_y: int, target_y: List[int]) -> List[int]:
y: int = 0
velocity: int = start_y
steps: int = 0
valid: List[int] = []
while y >= min(target_y):
if min(target_y) <= y <= max(target_y):
valid.append(steps)
y += velocity
velocity -= 1
steps += 1
return valid
def x_steps(steps: int, target_x: List[int]) -> Set[int]:
valid: Set[int] = set()
for start_x in range(max(target_x) + 1):
x: int = 0
velocity: int = start_x
for _ in range(steps):
x += velocity
velocity -= min(velocity, 1)
if min(target_x) <= x <= max(target_x):
valid.add(start_x)
return valid
def find_min_x(target_x: List[int]) -> int:
start_x: int = 0
x: int = start_x
while not (min(target_x) < x < max(target_x)):
start_x += 1
x = max_dist(start_x)
print(f"{start_x} -> {x}")
return start_x
with open('2021/17/input.txt', 'r') as file:
for line in file.readlines():
parts = line.split(':')
x_part = parts[1].split(',')[0].strip().split('=')[1].split('..')
y_part = parts[1].split(',')[1].strip().split('=')[1].split('..')
target_x: List[int] = [int(x) for x in x_part]
target_y: List[int] = [int(y) for y in y_part]
height: int = max_height(target_y)
print(f"{height}")
count: int = 0
for start_y in range(min(target_y), abs(min(target_y)) + 1):
valid: Set[int] = set()
for steps in y_steps(start_y, target_y):
start_xs: Set[int] = x_steps(steps, target_x)
valid.update(start_xs)
count += len(valid)
print(count)
|
#!/use/bin/env python
from sys import argv
from typing import List, Tuple
def read_file(file: str) -> List[List[int]]:
with open(file, 'r') as f:
trees: List[List[int]] = []
for line in f.readlines():
line = line.strip()
row: List[int] = []
for l in line:
row.append(int(l))
trees.append(row)
return trees
def print_trees(trees: List[List[int]]) -> None:
for column in trees:
for row in column:
print(row, end="")
print()
def part_one(file: str) -> int:
trees: List[List[int]] = read_file(file)
visible_trees: List[Tuple[int, int]] = []
for i in range(1, len(trees) - 1):
for j in range(1, len(trees[i]) - 1):
visible: bool = True
for x in range(i):
if trees[i][j] <= trees[x][j]:
visible = False
break
if visible:
visible_trees.append(tuple((i, j)))
continue
visible = True
for x in range(i + 1, len(trees)):
if trees[i][j] <= trees[x][j]:
visible = False
break
if visible:
visible_trees.append(tuple((i, j)))
continue
visible = True
for y in range(j):
if trees[i][j] <= trees[i][y]:
visible = False
break
if visible:
visible_trees.append(tuple((i, j)))
continue
visible = True
for y in range(j + 1, len((trees[i]))):
if trees[i][j] <= trees[i][y]:
visible = False
break
if visible:
visible_trees.append(tuple((i, j)))
continue
return (len(visible_trees) + (len(trees) + len(trees[0]) - 2) * 2)
def part_two(file: str) -> int:
trees: List[List[int]] = read_file(file)
visible_trees: List[Tuple[int, int]] = []
scores: List[int] = []
for i in range(1, len(trees) - 1):
for j in range(1, len(trees[i]) - 1):
up: int = 0
for u in range(i - 1, 0, -1):
if trees[i][j] <= trees[u][j]:
up = u
break
if up != 0:
up = i - up
else:
up = i
down: int = 0
for d in range(i + 1, len(trees)):
if trees[i][j] <= trees[d][j]:
down = d
break
if down != 0:
down = down - i
else:
down = len(trees) - i - 1
left: int = 0
for l in range(j - 1, 0, -1):
if trees[i][j] <= trees[i][l]:
left = l
break
if left != 0:
left = j - left
else:
left = j
right: int = 0
for r in range(j + 1, len((trees[i]))):
if trees[i][j] <= trees[i][r]:
right = r
break
if right != 0:
right = right - j
else:
right = len(trees[i]) - j - 1
score: int = left * right * up * down
scores.append(score)
return max(scores)
def main():
print("Part One: {}".format(part_one(argv[1])))
print("Part Two: {}".format(part_two(argv[1])))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: ran
@file: counting_bits_338.py
@time: 2021/6/13 19:52
@desc:
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,
计算其二进制数中的 1 的数目并将它们作为数组返回。
"""
class Solution(object):
def countBits(self, n):
"""
:type n: int
:rtype: List[int]
"""
res = [0] * (n + 1)
for i in range(1, n + 1):
res[i] = res[i & (i - 1)] + 1
return res
|
def ALG(list1, list2, k):
#BASE CASES
#If one list is empty, the kth smallest element (where
#k starts at 0) must be at index k in the other list.
if len(list1) == 0:
return list2[k]
elif len(list2) == 0:
return list1[k]
#RECURSIVE CASES
#The list1 is of size m and the list2 is of size n. Divide
#their lengths by two to get the middle index of each list.
m_div_2 = int(len(list1)/2)
n_div_2 = int(len(list2)/2)
#Case 1 - Indexes do not sum up to k
if m_div_2 + n_div_2 < k:
#If the larger middle value is in list1, cut list2 in
#half, keep the second half, and decrement k to
#accomodate the change in list2 size.
if list1[m_div_2] > list2[n_div_2]:
return ALG(list1, list2[n_div_2+1:], k-(n_div_2)-1)
#Else, the larger middle value is in list2 or the middle
#values are equal. Cut list1 in half, keep the second half,
#and decrement k to accomodate the change in list1 size.
else:
return ALG(list1[m_div_2+1:], list2, k-(m_div_2)-1)
#Case 2 - Indexes sum up to or greater than k
else:
#If the larger middle value is in list1, cut list2 in
#half, keep the first half, and do not change k.
if list1[m_div_2] > list2[n_div_2]:
return ALG(list1[:m_div_2], list2, k)
#Else, the larger middle value is in list2 or the middle
#values are equal. Cut list2 in half, keep the first half,
#and do not change k.
else:
return ALG(list1, list2[:n_div_2], k)
|
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
def createList() -> ListNode:
n = int(input())
head = None
tail = None
for i in range(0,n):
ele = int(input())
tempnode = ListNode(ele)
if tail == None:
head = tail = tempnode
else:
tail.next = tempnode
tail = tail.next
return head
def printlist(t1:ListNode):
temp = t1
while temp!= None:
print(temp.val)
temp = temp.next
def addToList(head:ListNode, tail: ListNode,tempnode: ListNode):
if tail == None:
head = tail = tempnode
else:
tail.next = tempnode
tail = tail.next
return [head,tail]
def addTwoNumbers(l1: ListNode, l2 : ListNode) -> ListNode:
head1 = l1
head2 = l2
anshead = None
anstail = None
carry = 0
while head1!=None and head2!= None :
val = head1.val + head2.val + carry
carry = int((val / 10))
val = val % 10
tempnode = ListNode(val)
temp = addToList(anshead,anstail,tempnode)
anshead = temp[0]
anstail = temp[1]
head1 = head1.next
head2 = head2.next
while head1 != None:
val = head1.val + carry
carry = int((val/10))
val = val % 10
tempnode = ListNode(val)
temp = addToList(anshead,anstail,tempnode)
anshead = temp[0]
anstail = temp[1]
head1 = head1.next
while head2 != None:
val = head1.val + carry
carry = int((val/10))
val = val % 10
tempnode = ListNode(val)
temp = addToList(anshead,anstail,tempnode)
anshead = temp[0]
anstail = temp[1]
head2 = head2.next
if carry == 1:
tempnode = ListNode(carry)
temp = addToList(anshead,anstail,tempnode)
anshead = temp[0]
anstail = temp[1]
return anshead
l1 = createList()
l2 = createList()
val = addTwoNumbers(l1,l2)
printlist(val)
|
#!/usr/bin/env python3
# Designing Algorithms /// top-down design
## What is smallest value? This code tells us just that - it is the data for past 10 years
counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
print (min(counts))
## If we want to know in which year the population bottomed out, we can use list.index to find the index of the smallest value:
counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
low = min(counts)
print (counts.index(low))
counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
print (counts.index(min(counts)))
# Lists have no method to find indices of the two smallest values?
# So we have to make an algorithm
from typing import List, Tuple
def find_two_smallest1(L: List[float]) -> Tuple[int, int]:
"""Return a tuple of the indices of the two smallest values in list L.
>>> items = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
>>> find_two_smallest(items)
(6, 7)
>>> items == [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
True
"""
# Find the index of the minimum and remove that item
smallest = min(L)
min1 = L.index(smallest)
L.remove(smallest)
# Find the index of the new minimum
next_smallest = min(L)
min2 = L.index(next_smallest)
# Put smallest back into L
L.insert(min1, smallest)
# Fix min2 in case it was affected by the removal and reinsertion:
if min1 <= min2:
min2 += 1
return (min1, min2)
### Second way
from typing import List, Tuple
def find_two_smallest2(L: List[float]) -> Tuple[int, int]:
"""Return a tuple of the indices of the two smallest values in list L.
>>> items = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
>>> find_two_smallest(items)
(6, 7)
>>> items == [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
True
"""
# Get a sorted copy of the list so that the two smallest items are at the # front
temp_list = sorted(L)
smallest = temp_list[0]
next_smallest = temp_list[1]
# Find the indices in the original list L
min1 = L.index(smallest)
min2 = L.index(next_smallest)
return (min1, min2)
### Third way
import time
import doctest
def find_two_smallest(L):
""" (list of float) -> tuple of (int, int)
Return a tuple of the indices of the two smallest values in list L
>>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324, 476])
(6, 7)
"""
# set min1 and min2 to the indices of the smallest and next smallest values at the beginning of L
if L[0] < L[1]:
min1, min2 = 0,1
else:
min1, min2 = 1,0
# Examine each value in the list in order
for i in range(2,len(L)):
# Update these values when a new smaller value is found
if L[i] < L[min1]:
min2 = min1
min1 = i
elif L[i] <L[min2]:
min2 = i
return (min1,min2)
print (doctest.testmod())
# Exercises
# 1
# A DNA sequence is a string made up of the letters A, T, G, and C. To find the complement of a DNA sequence,
# As are replaced by Ts, Ts by As, Gs by Cs, and Cs by Gs. For example,
# the complement of AATTGCCGT is TTAACGGCA.
import doctest
def complement(sequence):
""" (str) -> str
Return the complement of sequence.
>>> complement('AATTGCCGT')
'TTAACGGCA'
"""
complement_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
sequence_complement = ''
for char in sequence:
sequence_complement = sequence_complement + complement_dict[char]
return sequence_complement
print (doctest.testmod())
# 2
# In this exercise, you’ll develop a function that finds the minimum or
# maximum value in a list, depending on the caller’s request.
import time
def min_or_max_index(L, flag):
""" (list, bool) -> tuple of (object, int)
Return the minimum or maximum item and its index from L, depending on
whether flag is True or False.
>>> min_or_max_index([4, 3, 2, 4, 3, 6, 1, 5], True)
(1, 6)
>>> min_or_max_index([4, 3, 2, 4, 3, 6, 1, 5], False)
(6, 5)
"""
index = 0
current_value = L[0]
if flag:
for i in range(1, len(L)):
if L[i] < current_value:
index = i
current_value = L[i]
else:
for i in range(1, len(L)):
if L[i] > current_value:
index = i
current_value = L[i]
return (current_value, index)
print (doctest.testmod())
# 3
import doctest
def hopedale_average(filename):
""" (str) -> float
Return the average number of pelts produced per year for the data in
Hopedalefile named filename.
"""
with open(filename, 'r') as hopedale_file:
# Read the description line.
hopedale_file.readline()
# Keep reading comment lines until we read the first piece of
data = hopedale_file.readline().strip()
while data.startswith('#'):
data = hopedale_file.readline().strip()
# Now we have the first piece of data append it to an empty list.
pelts_list = []
pelts_list.append(int(data))
# Read the rest of the data.
for data in hopedale_file:
pelts_list.append(int(data.strip()))
return sum(pelts_list) / len(pelts_list)
print (doctest.testmod())
# 4
# Write a set of doctests for the find-two-smallest functions.
# Think about what kinds of data are interesting, long lists or short lists,
# and what order the items are in. Here is one list to test with: [1, 2].
# What other interesting ones are there?
print (find_two_smallest([1, 2]))
print (find_two_smallest([3, 2]))
print (find_two_smallest([3, 3]))
print (find_two_smallest([3, 1, 3]))
print (find_two_smallest([1, 4, 2, 3, 4]))
print (find_two_smallest([4, 3, 1, 5, 6, 2]))
print (find_two_smallest([-2, 4, 3, 2, 5, 6, -1]))
# 6
import time
def dutch_flag(flag):
red_counter = 0
index = 0
while index != len(flag):
if flag[index] == 'red':
del flag[index]
flag.insert(0, 'red')
red_counter += 1
elif flag[index] == 'green':
del flag[index]
flag.insert(red_counter, 'green')
elif flag[index] == 'blue':
del flag[index]
flag.append('blue')
if flag[index] == 'red':
if index == 0 or flag[index-1] == 'red':
index += 1
elif flag[index] == 'green' and flag[index-1] != 'blue':
index += 1
elif flag[index] == 'blue':
if index == len(flag) - 1 or flag[index] == 'blue':
index += 1
def dutch_flag2(color_list):
""" (list of str) -> list of str
Return color_list rearranged so that 'red' strings come first, 'green'
second,
and 'blue' third.
>>> color_list = ['red', 'green', 'blue', 'red', 'red', 'blue', 'red',
'green']
>>> dutch_flag(['red', 'green', 'blue', 'red', 'red', 'blue', 'red',
'green'])
>>> color_list
['red', 'red', 'red', 'red', 'green', 'green', 'blue', 'blue']
"""
# The start of the green section.
start_green = 0
# The index of the first unexamined color.
start_unknown = 0
# The index of the last unexamined color.
end_unknown = len(color_list) - 1
while start_unknown <= end_unknown:
# If it is red, swap it with the item to the right of the red section.
if color_list[start_unknown] == 'red':
color_list[start_green], color_list[start_unknown] \
= color_list[start_unknown], color_list[start_green]
start_green += 1
start_unknown += 1
# If it is green, leave it where it is.
elif color_list[start_unknown] == 'green':
start_unknown += 1
# If it is blue, swap it with the item to the left of the blue section.
else:
color_list[start_unknown], color_list[end_unknown] \
= color_list[end_unknown], color_list[start_unknown]
end_unknown -= 1
def dutch_flag_runtime(function, list):
"""
(function, list) -> float
Returns the amount of milliseconds elapsed for the function to search through list.
"""
time1 = time.perf_counter()
function(list)
time2 = time.perf_counter()
return (abs(time2 -time1)*1000)
color_list = ['red', 'blue', 'green', 'green', 'red', 'blue', 'red', 'green']
color_list2 = ['red', 'blue', 'green', 'green', 'red', 'blue', 'red', 'green']
dutch_flag(color_list)
print(color_list)
dutch_flag2(color_list2)
print(color_list2)
print(dutch_flag_runtime(dutch_flag, color_list))
print(dutch_flag_runtime(dutch_flag2, color_list2))
print(dutch_flag_runtime(dutch_flag, color_list)/dutch_flag_runtime(dutch_flag2, color_list2))
|
#!/usr/bin/env python3
# Reading and Writing Files
# To check the current directory
import os
print(os.getcwd())
# To look for file in different directory
file = open('file_examples/file_example.txt', 'r')
contents = file.read()
file.close()
print(contents)
# Another way look for file in different directory
with open('file_examples/file_example.txt', 'r') as file:
contents = file.read()
print(contents)
# Reads ten characters and then the rest of the file:
# Method call example_file.read(10) moves the file cursor,
# so the next call, exam- ple_file.read(), reads everything from character 11 to the end of the file.
with open('file_examples/file_example.txt', 'r') as example_file:
first_ten_chars = example_file.read(10)
the_rest = example_file.read()
print("The first 10 characters:", first_ten_chars)
print("The rest of the file:", the_rest)
# This example reads the contents of a file into a list of strings and then prints that list:
with open('file_examples/file_example.txt', 'r') as example_file:
lines = example_file.readlines()
print(lines)
with open('file_examples/planets.txt', 'r') as planets_file:
planets = planets_file.readlines()
print(planets)
for planet in reversed(planets):
print(planet.strip())
# The “For Line in File” Technique
with open('file_examples/planets.txt', 'r') as data_file:
for line in data_file:
print(len(line))
# whitespace characters (spaces, tabs, and newlines) stripped away:
with open('file_examples/planets.txt', 'r') as data_file:
for line in data_file:
print(len(line.strip()))
# The Readline Technique
with open('file_examples/hopedale.txt', 'r') as hopedale_file:
# Read and skip the description line.
hopedale_file.readline()
# Keep reading and skipping comment lines until we read the first piece # of data.
data = hopedale_file.readline().strip()
while data.startswith('#'):
data = hopedale_file.readline().strip()
# Now we have the first piece of data. Accumulate the total number of # pelts.
total_pelts = int(data)
# Read the rest of the data.
for data in hopedale_file:
total_pelts = total_pelts + int(data.strip())
print("Total number of pelts:", total_pelts)
# Each call on the function readline moves the file cursor to the beginning of the next line.
# Here is a program that prints the data from that file, preserving the whitespace:
with open('file_examples/hopedale.txt', 'r') as hopedale_file:
# Read and skip the description line.
hopedale_file.readline()
# Keep reading and skipping comment lines until we read the first piece # of data.
data = hopedale_file.readline().rstrip()
while data.startswith('#'):
data = hopedale_file.readline().rstrip()
# Now we have the first piece of data.
print(data)
# Read the rest of the data.
for data in hopedale_file:
print(data.rstrip())
# Files over the Internet
import urllib.request
url = 'https://robjhyndman.com/tsdldata/ecology1/hopedale.dat'
with urllib.request.urlopen(url) as webpage:
for line in webpage:
line = line.strip()
line = line.decode('utf-8')
print(line)
# Writing Files
with open('file_examples/topics.txt', 'w') as output_file:
output_file.write('Computer Science')
with open('file_examples/topics.txt', 'a') as output_file:
output_file.write('\nSoftware Engineering')
# The next example, in a file called total.py, is more complex, and it involves both reading from and writing to a file.
# Notice that it uses typing.
# TextIO as the type annotation for an open file. “IO” is short for “Input/Output.”
# Our input file contains two numbers per line separated by a space. The output file will contain three numbers per line:
# the two from the input file followed by their sum (all separated by spaces).
from typing import TextIO
from io import StringIO
def sum_number_pairs(input_file: TextIO, output_file: TextIO) -> None:
"""Read the data from input_file, which contains two floats per line
separated by a space. output_file for writing and, for each line in
input_file, write a line to output_file that contains the two floats from
the corresponding line of input_file plus a space and the sum of the two
floats.
"""
for number_pair in input_file:
number_pair = number_pair.strip()
operands = number_pair.split()
total = float(operands[0]) + float(operands[1])
new_line = '{0} {1}\n'.format(number_pair, total)
output_file.write(new_line)
if __name__ == '__main__':
with open('file_examples/number_pairs.txt', 'r') as input_file, \
open('file_examples/number_pair_sums.txt', 'w') as output_file:
sum_number_pairs(input_file, output_file)
# Writing Example Calls Using StringIO
# Here, we create a StringIO object containing the same information as file num- ber_pairs.txt, and read the first line:
from io import StringIO
input_string = '1.3 3.4\n2 4.2\n-1 1\n'
infile = StringIO(input_string)
print(infile.readline())
# We can also write to StringIO objects as if they were files, and retrieve their contents as a string using method getvalue:
from io import StringIO
outfile = StringIO()
print(outfile.write('1.3 3.4 4.7\n'))
print(outfile.write('2 4.2 6.2\n'))
print(outfile.write('-1 1 0.0\n'))
print(outfile.getvalue())
from typing import TextIO
from io import StringIO
def sum_number_pairs(input_file: TextIO, output_file: TextIO) -> None:
"""Read the data from input_file, which contains two floats per line
separated by a space. output_file for writing and, for each line in
input_file, write a line to output_file that contains the two floats from
the corresponding line of input_file plus a space and the sum of the two
floats.
>>> infile = StringIO('1.3 3.4\\n2 4.2\\n-1 1\\n')
>>> outfile = StringIO()
>>> sum_number_pairs(infile, outfile)
>>> outfile.getvalue()
'1.3 3.4 4.7\\n2 4.2 6.2\\n-1 1 0.0\\n'
"""
for number_pair in input_file:
number_pair = number_pair.strip()
operands = number_pair.split()
total = float(operands[0]) + float(operands[1])
new_line = '{0} {1}\n'.format(number_pair, total)
output_file.write(new_line)
if __name__ == '__main__':
with open('file_examples/number_pairs.txt', 'r') as input_file, \
open('file_examples/number_pair_sums.txt', 'w') as output_file:
sum_number_pairs(input_file, output_file)
# Writing Algorithms That Use the File-Reading Techniques
from typing import TextIO
from io import StringIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
# Read the description line
line = reader.readline()
# Find the first non-comment line
line = reader.readline()
while line.startswith('#'):
line = reader.readline()
# Now line contains the first real piece of data
return line
def process_file(reader: TextIO) -> None:
"""Read and print the data from reader, which must start with a single
description line, then a sequence of lines beginning with '#', then a
sequence of data.
>>> infile = StringIO('Example\\n# Comment\\nLine 1\\nLine 2\\n')
>>> process_file(infile)
Line 1
Line 2
"""
# Find and print the first piece of data
line = skip_header(reader).strip()
print(line)
# Read the rest of the data
for line in reader:
line = line.strip()
print(line)
if __name__ == '__main__':
with open('file_examples/hopedale.txt', 'r') as input_file:
process_file(input_file)
# This program processes the Hopedale data set to find the smallest number of fox pelts produced in any year.
# As we progress through the file, we keep the smallest value seen so far in a variable called smallest.
# That variable is initially set to the value on the first line, since it’s the smallest (and only) value seen so far:
from typing import TextIO
import time_series
def smallest_value(reader: TextIO) -> int:
"""Read and process reader and return the smallest value after the
time_series header.
>>> infile = StringIO('Example\\n1\\n2\\n3\\n')
>>> smallest_value(infile)
1
>>> infile = StringIO('Example\\n3\\n1\\n2\\n')
>>> smallest_value(infile)
1
"""
line = time_series.skip_header(reader).strip()
# Now line contains the first data value; this is also the smallest value
# found so far, because it is the only one we have seen.
smallest = int(line)
for line in reader:
value = int(line.strip())
# If we find a smaller value, remember it.
if value < smallest:
smallest = value
return smallest
if __name__ == '__main__':
with open('file_examples/hopedale.txt', 'r') as input_file:
print(smallest_value(input_file))
# To fix our code, we must add a check inside the loop that processes a line only if it contains a real value.
# We will assume that the first value is never a hyphen because in the TSDL data sets, missing entries are always marked with hyphens.
# So we just need to check for that before trying to convert the string we have read to an integer:
from typing import TextIO
from io import StringIO
import time_series
def smallest_value_skip(reader: TextIO) -> int:
"""Read and process reader, which must start with a time_series header.
Return the smallest value after the header. Skip missing values, which
are indicated with a hyphen.
>>> infile = StringIO('Example\\n1\\n-\\n3\\n')
>>> smallest_value_skip(infile)
1
"""
line = time_series.skip_header(reader).strip()
# Now line contains the first data value; this is also the smallest value # found so far, because it is the only one we have seen.
smallest = int(line)
for line in reader:
line = line.strip()
if line != '-':
value = int(line)
smallest = min(smallest, value)
return smallest
if __name__ == '__main__':
with open('file_examples/hebron.txt', 'r') as input_file:
print("This is smallest value: ", smallest_value_skip(input_file))
# Processing Whitespace-Delimited Data
# The helper function required is one that finds the largest value in a line, and it must split up the line.
# String method split will split around the whitespace,
# but we still have to remove the periods at the ends of the values.
from typing import TextIO
from io import StringIO
def process_file(reader: TextIO) -> int:
"""Read and process reader, which must start with a time_series header.
Return the largest value after the header. There may be multiple pieces
of data on each line.
>>> infile = StringIO('Example\\n 20. 3.\\n')
>>> process_file(infile)
20
>>> infile = StringIO('Example\\n 20. 3.\\n 100. 17. 15.\\n')
>>> process_file(infile)
100
"""
# Read the description line
line = reader.readline()
# Find the first non-comment line
line = reader.readline()
while line.startswith('#'):
line = reader.readline()
# Now line contains the first real piece of data
# The largest value seen so far in the current line
largest = -1
for value in line.split():
# Remove the trailing period
v = int(value[:-1])
# If we find a larger value, remember it
if v > largest:
largest = v
# Check the rest of the lines for larger values
for line in reader:
# The largest value seen so far in the current line
largest_in_line = -1
for value in line.split():
# Remove the trailing period
v = int(value[:-1])
# If we find a larger value, remember it
if v > largest_in_line: largest_in_line = v
if largest_in_line > largest:
largest = largest_in_line
return largest
if __name__ == '__main__':
with open('file_examples/lynx.txt', 'r') as input_file:
print(process_file(input_file))
#
# Multiline Records
#
from typing import TextIO
from io import StringIO
def read_molecule(reader: TextIO) -> list:
"""Read a single molecule from reader and return it, or return None to
signal end of file. The first item in the result is the name of the
compound; each list contains an atom type and the X, Y, and Z coordinates
of that atom.
>>> instring = 'COMPND TEST\\nATOM 1 N 0.1 0.2 0.3\\nATOM 2 N 0.2 0.1 0.0\\nEND\\n'
>>> infile = StringIO(instring)
>>> read_molecule(infile)
['TEST', ['N', '0.1', '0.2', '0.3'], ['N', '0.2', '0.1', '0.0']]
"""
# If there isn't another line, we're at the end of the file.
line = reader.readline()
if not line:
return None
# Name of the molecule: "COMPND name"
parts = line.split()
name = parts[1]
# Other lines are either "END" or "ATOM num atom_type x y z"
molecule = [name]
reading = True
while reading:
line = reader.readline()
if line.startswith('END'):
reading = False
else:
parts = line.split()
molecule.append(parts[2:])
return molecule
def read_all_molecules(reader: TextIO) -> list:
"""Read zero or more molecules from reader, returning a list of the molecule information.
>>> cmpnd1 = 'COMPND T1\\nATOM 1 N 0.1 0.2 0.3\\nATOM 2 N 0.2 0.1 0.0\\nEND\\n'
>>> cmpnd2 = 'COMPND T2\\nATOM 1 A 0.1 0.2 0.3\\nATOM 2 A 0.2 0.1 0.0\\nEND\\n'
>>> infile = StringIO(cmpnd1 + cmpnd2)
>>> result = read_all_molecules(infile)
>>> result[0]
['T1', ['N', '0.1', '0.2', '0.3'], ['N', '0.2', '0.1', '0.0']]
>>> result[1]
['T2', ['A', '0.1', '0.2', '0.3'], ['A', '0.2', '0.1', '0.0']]
"""
# The list of molecule information.
result = []
reading = True
while reading:
molecule = read_molecule(reader)
if molecule: # None is treated as False in an if statement
result.append(molecule)
else:
reading = False
return result
if __name__ == '__main__':
molecule_file = open('file_examples/multimol.pdb', 'r')
molecules = read_all_molecules(molecule_file)
molecule_file.close()
print(molecules)
########################
# Exercises chapter 10 #
########################
##############
# Exercise 1 #
##############
# Write a program that makes a backup of a file. Your program should prompt the user for the name of the
# file to copy and then write a new file with the same contents but with .bak as the file extension.
filename = input('Which file would you like to back-up? ')
new_filename = filename + '.bak'
backup = open(new_filename, 'w')
for line in open(filename):
backup.write(line)
backup.close()
# When ask for file simply give it some as follow the .bak will be in same directory:
# Which file would you like to back-up? file_examples/lynx.txt
##############
# Exercise 2 #
##############
#Suppose the file alkaline_metals.txt contains the name, atomic number,
# and atomic weight of the alkaline earth metals:
# beryllium 4 9.012
# magnesium 12 24.305
# calcium 20 20.078
# strontium 38 87.62
# barium 56 137.327
# radium 88 226
# Write a for loop to read the contents of alkaline_metals.txt and store it in a list of lists,
# with each inner list containing the name, atomic
# number, and atomic weight for an element. (Hint: Use string.split.)
alkaline_metals = []
for line in open('file_examples/alkaline_metals.txt'):
alkaline_metals.append(line.strip().split(' '))
print(alkaline_metals)
##############
# Exercise 3 #
##############
# All of the file-reading functions we have seen in this chapter read forward
# through the file from the first character or line to the last. How could you
# write a function that would read backward through a file?
# We could read the file contents into a data structure, such as a list, and then iterate over the
# list from end (last line) to beginning (first line).
##############
# Exercise 4 #
##############
#In Processing Whitespace-Delimited Data, on page 192, we used the “For
# Line in File” technique to process data line by line, breaking it into pieces
# using string method split. Rewrite function process_file to skip the header as
# normal but then use the Read technique to read all the data at once.
def process_file(reader):
""" (file open for reading) -> NoneType
Read and print the data from reader, which must start with a single
description line, then a
sequence of lines beginning with '#', then a
sequence of data.
"""
# Find and print the first piece of data.
line = skip_header(reader).strip()
print(line)
# Read the rest of the data.
print(reader.read())
if __name__ == '__main__':
with open('file_examples/hopedale.txt', 'r') as input_file:
process_file(input_file)
##############
# Exercise 5 #
##############
# Modify the file reader in read_smallest_skip.py of Skipping the Header, on page 188
# so that it can handle files with no data after the header.
# Defined on line 280
import time_series
def smallest_value_skip(reader):
""" (file open for reading) -> number or NoneType
Read and process reader, which must start with a time_series header.
Return the smallest value after the header. Skip missing values, which
are indicated with a hyphen.
"""
line = time_series.skip_header(reader).strip()
# Only execute this code, if there is data following the header.
if line != '':
smallest = int(line)
for line in reader:
line = line.strip()
if line != '-':
value = int(line)
smallest = min(smallest, value)
return smallest
if __name__ == '__main__':
with open('file_examples/hebron.txt', 'r') as input_file:
print(smallest_value_skip(input_file))
##############
# Exercise 6 #
##############
# Refer to "read_smallest_skip.py"
##############
# Exercise 7 #
##############
# Modify the PDB file reader of Multiline Records, on page 195, so that it ignores
# blank lines and comment lines in PDB files. A blank line is one that contains
# only space and tab characters (that is, one that looks empty when viewed).
# A comment is any line beginning with the keyword CMNT.
def read_molecule(reader):
""" (file open for reading) -> list or NoneType
Read a single molecule from reader and return it, or return None to
signal
end of file. The first item in the result is the name of the compound;
each list contains an atom type and the X, Y, and Z coordinates of that
atom.
"""
# If there isn't another line, we're at the end of the file.
line = reader.readline()
if not line:
return None
if not (line.startswith('CMNT') or line.isspace()):
# Name of the molecule: "COMPND name"
key, name = line.split()
# Other lines are either "END" or "ATOM num atom_type x y z"
molecule = [name]
else:
molecule = None
reading = True
while reading:
line = reader.readline()
if line.startswith('END'):
reading = False
elif not (line.startswith('CMNT') or line.isspace()):
key, num, atom_type, x, y, z = line.split()
if molecule == None:
molecule = []
molecule.append([atom_type, x, y, z])
return molecule
if __name__ == '__main__':
molecule_file = open('file_examples/multimol.pdb', 'r')
molecules = read_all_molecules(molecule_file)
molecule_file.close()
print(molecules)
##############
# Exercise 8 #
##############
# Modify the PDB file reader to check that the serial numbers on atoms
# start at 1 and increase by 1. What should the modified function do if it
# finds a file that doesn’t obey this rule?
def read_molecule(reader):
""" (file open for reading) -> list or None Type
Read a single molecule from reader and return it, or return None to
signal
end of file. The first item in the result is the name of the compound;
each list contains an atom type and the X, Y, and Z coordinates of that
atom.
"""
# If there isn't another line, we're at the end of the file.
line = reader.readline()
if not line:
return None
# Name of the molecule: "COMPND name"
key, name = line.split()
# Other lines are either "END" or "ATOM num atom_type x y z"
molecule = [name]
reading = True
serial_number = 1
while reading:
line = reader.readline()
if line.startswith('END'):
reading = False
else:
key, num, atom_type, x, y, z = line.split()
if int(num) != serial_number:
print('Expected serial number {0}, but got {1}'.format(
serial_number, num))
molecule.append([atom_type, x, y, z])
serial_number += 1
return molecule
if __name__ == '__main__':
molecule_file = open('file_examples/multimol_no_end.pdb', 'r')
molecules = read_all_molecules(molecule_file)
molecule_file.close()
print(molecules)
# if this function find a file that not obey this rule will be an error
|
#!/usr/bin/env python3
import math
type(math)
print(math.sqrt(9))
print(math.pi)
radius = 5
print('area is', math.pi * radius ** 2)
import temperature
celsius = temperature.convert_to_celsius(90.1)
print(celsius)
print(temperature.above_freezing(celsius))
import panda_print
print('__name__ is ',__name__)
import main_example
import temperature_program
import baking
import hello
import calendar
tc= calendar.TextCalendar(firstweekday=0)
print(tc.prmonth(2016, 7))
|
class Fruit: #class
__secret_var ="40" #hidden variable
def __init__(self, calorie=0, color=""):
self.calorie = calorie #field/attribute
self.color = color
__confidential = "abc" # private variable meant to be hidden from outsiders, concept of encapsulation
#print(self.__confidential)
def __helperMethod(self): #hidden method, similar to hidden variable.
print("I am hidden.")
def isHighCalorie(self):
self.__secret_var
self.__helperMethod()
if self.calorie >= 100:
return True
return False
def __mul__(self, other):
# eg. A * B, you call on __mul__ on A, other will be B
return "{} multiplied by {} results in {}".format(self.calorie, other.calorie, self.calorie * other.calorie)
def __str__(self): #method
return "Fruit class with calorie {} and color {}." \
"".format(self.calorie, self.color)
class AsiaFruit(Fruit):
def isHighCalorie(self):
if self.calorie > 80:
return True
return False
class StrawBerry(Fruit): #Strawberry inherits from Fruit class and possess all attributes and methods from superclass
# StrawBerry - child class/ sub-class
# Fruit - superclass / parent class
# Test for inheritance: Strawberry is a Fruit
def isHighCalorie(self):
if self.calorie > 50:
return True
return False
class Durian(AsiaFruit):
def isHighCalorie(self): #overloading, over-write the method from parent class
if self.calorie > 200:
return True
return False
def printOtherProperties(self, *args): #variable length of arguments passed in as list
print("In other properties")
for each in args:# args[0]= spiky, args[1]= smelly
print("printing contents: {}".format(each))
def printKeyValueFeatures(self, **kwargs): #key word arguments
print("in printKeyValueFeatures()")
for key, value in kwargs.items():
print("{} -> {}".format(key, value))
durian1 = Durian(200, "Green")
#print(durian1)
papaya = Fruit(200, "Green")
papaya.isHighCalorie()
#print(durian1 * papaya)
#print(durian1 == papaya)
#print(papaya.isHighCalorie())
# durian1.printOtherProperties("spiky", "smelly")
#
# durian1.printKeyValueFeatures(origin="Thailand", years=5) # variable name origin (key), value =Thailand (value)
#
# dict_var = {"key1": 100, "key2": 200}
# durian1.printKeyValueFeatures(**dict_var) # Add ** if using existing dictionary
# fruitA = Fruit(100, "yellow") #object
# print(fruitA)
# print(fruitA.isHighCalorie())
# #print(fruitA.calorie)
# #print(Fruit.__confidential)
# strawberry1 = StrawBerry(60, "red")
# print(strawberry1.isHighCalorie()) # specificity rule, the nearest method will be used, else traverse to higher
# #hierachy until the method is found
#
# durian1 = Durian(150, "Green")
# print(durian1.isHighCalorie())
#
# print(AsiaFruit(1000, "Green"))
"""
Fruit
^
|
AsiaFruit
^
|
Durian
"""
|
def get_number(lower, upper):
while (True):
try:
user_input = int(input("Enter a number ({}-{}):".format(lower, upper)))
if user_input < lower:
print("Number too low.")
elif user_input > upper:
print("Number too large.")
else:
return user_input
except ValueError:
print("Error in number")
return_value = get_number(10, 50)
print("The returned value is {}".format(return_value))
|
# list of positive integer numbers
from statistics import mean
# list the numbers in the order
data1 = [1, 2, 3, 4, 5, 6]
# assume x that is the mean value of the list
x = mean(data1)
# Printing the mean
print("Mean is :", x)
|
"""
Write a function that takes an integer and prints the numbers from that down to 0.
Hint: while or for or recursion
eg. print_num(5)
output:
5
4
3
2
1
0
"""
def print_num_recursion(x):
print(x)
if x == 0:
return
else:
print_num_recursion(x-1)
def print_num_while(x):
while x >= 0:
print(x)
x -= 1
def print_num_for(x):
for i in range(x, -1, -1):
print(i)
#print_num_recursion(7)
def recurse(n): #1) n=4 4) n=3
if n <= 0:
print("Thing!") # Thing
else:
print(n) #2) 4 5) 3, 2, 1
recurse(n - 1) #3) recurse(3) 6)recurse(2)
print(n)
recurse(4)
|
user_input = input("Enter your name:")
while user_input == "":
user_input = input("Enter your name:")
print(user_input[::2])
|
"""This file should have our order classes in it."""
from random import randint
import time
import datetime
class AbstractMelonOrder(object):
"""Tracks melon orders and calculates totals."""
def __init__(self, species, quantity, country_code):
"""Initialize melon order attributes."""
self.species = species
self.quantity = quantity
self.shipped = False
self.order_type = None
self.tax = 0.00
self.country_code = country_code
# self.base_price = self.get_base_price()
def get_base_price(self):
"""Generating a random base price, between 5 - 9."""
price = randint(5, 9)
# this is a weekday, because it's not Saturday or Sunday
if datetime.date.today().strftime("%a") not in ["Sat", "Sun"]:
# rush hour is from 8 AM - 11 AM
now_time = int(datetime.datetime.now().strftime("%H" + "%M"))
if now_time >= 800 and now_time <= 1400:
price += 4
print price
return price
def get_total(self):
"""Calculate price."""
price = self.get_base_price()
if self.species.lower() == "christmas":
price = price * 1.5
total = (1 + self.tax) * self.quantity * price
if self.order_type == "international" and self.quantity < 10:
total += 3
return total
def mark_shipped(self):
"""Set shipped to true."""
self.shipped = True
def get_country_code(self):
"""Return the country code."""
return self.country_code
class DomesticMelonOrder(AbstractMelonOrder):
"""A domestic (in the US) melon order."""
def __init__(self, species, quantity):
"""Initialize melon order attributes."""
super(DomesticMelonOrder, self).__init__(species, quantity, 'USA')
self.order_type = "domestic"
self.tax = 0.08
class InternationalMelonOrder(AbstractMelonOrder):
"""An international (non-US) melon order."""
def __init__(self, species, quantity, country_code):
"""Initialize melon order attributes"""
super(InternationalMelonOrder, self).__init__(species,
quantity,
country_code)
self.order_type = "international"
self.tax = 0.17
class GovernmentMelonOrder(AbstractMelonOrder):
"""Melons for The Government"""
passed_inspection = None
def mark_inspection(self, passed):
"""Changes inspection status to your inspection results (True or False).
"""
self.passed_inspection = passed
|
# Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages.
# The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail.
# The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file.
# After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
sendersDict = dict()
fname = input("enter file name:")
fhand = open(fname)
for line in fhand:
if not line.startswith("From "):
continue
email = line.rstrip().split()[1]
sendersDict[email] = sendersDict.get(email, 0)+1
fhand.close()
maxValue = None
maxKey = None
for key, value in sendersDict.items():
if maxValue is None or value > maxValue:
maxValue = value
maxKey = key
print(maxKey, maxValue)
|
# TODO:pagenumber:123
s = {} # this creates a empty dictionary
print(type(s))
# to create set
s1 = set("vinaychowdary")
s2 = set("VinayChowdary")
print(s1, s2)
print(s1 | s2) # union
print(s1-s2) # difference
print(s1 & s2) # intersection
print(s1 ^ s2) # x-y U y-x
print(s1 > s2) # superset
print(s1 < s2) # subset
print(s1.intersection(s2))
print(s1.union(s2))
print("\n", "-"*50, "functions", "-"*50, "\n")
s3 = "17282"
s1.add("ch")
print(s1)
s1.update(s3)
print(s1)
s1.remove("c")
print(s1)
s1.discard("i")
print(s1)
print(s1.issubset(s2))
print(s1.issuperset(s2))
# copy(),clear(),del,symmetric_difference()
|
import random
# lists are nothing but arrays but these can hold different types of data
# lists are mutable
friends = ["a", "b", "c", "d", 0]
list2 = [1, 80, 2, 3, 10, 24, 5, 6]
sample = [0]*5
print(sample)
# range() function gives list of values from 0 upto value specified in python2
# but in python 3 range() gives iterator.
# in python 3 we should use list() to get list from range()
print(list(range(len(friends))))
# concatenate lists
concate = friends+list2
print(concate)
# slicing lists similar to slicing strings by using : operator
print(concate[2:4])
# dir() --> lists all methods in that class(which is passed as parameter)
print(dir(list()))
# using some builtin functions on lists
concate.append([7, 8])
print(concate)
print(8 not in concate)
print(0 in concate)
# sorting list "sort() does not working if there are both int , str in list"
print("---------------- functions ----------------")
list2.sort()
print(list2)
list2.pop(5)
print(list2)
list2.reverse()
print(list2)
print(sum(list2))
list2.insert(0, 90)
print(list2)
list2.remove(1)
print(list2)
print(list2.count(3))
print(min(list2))
print(max(list2))
print(random.choice(list2))
# print(list2.choice()) --> wrong
print(random.shuffle(list2))
# TODO:copy(),deepcopy(),sort(key=func)
lstsInLst = [[1, 2, 3], [4, 5, 6]]
for a, b, c in lstsInLst:
print(a, b, c)
def inplaceUpdate(l):
l += [10, 20, 30]
print("inside ", l)
def noInPlaceUpdate(l):
l = l+[40, 50]
print("inside ", l)
lst = [1, 2, 3]
inplaceUpdate(lst)
print("outside ", lst)
noInPlaceUpdate(lst)
print("outside ", lst)
print(lst[::-1])
print(lst[5:2:-1])
|
import arcade
y = 0
x = 0
def draw_section_outlines():
color = arcade.color.BLACK
# Bottom squares
arcade.draw_rectangle_outline(150, 150, 300, 300, color)
arcade.draw_rectangle_outline(450, 150, 300, 300, color)
arcade.draw_rectangle_outline(750, 150, 300, 300, color)
arcade.draw_rectangle_outline(1050, 150, 300, 300, color)
# Top squares
arcade.draw_rectangle_outline(150, 450, 300, 300, color)
arcade.draw_rectangle_outline(450, 450, 300, 300, color)
arcade.draw_rectangle_outline(750, 450, 300, 300, color)
arcade.draw_rectangle_outline(1050, 450, 300, 300, color)
# Entire box of dots
def draw_section_1():
for row in range(30):
for column in range(30):
# Instead of zero, calculate proper x location using column
x = 10 * column
# Instead of zero, calcute proper y location using row
y = 10 * row
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
print ()
# Box of dots that are black and white
def draw_section_2():
for row in range(30):
for column in range(30):
x = 10 * column + 304
y = 10 * row
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.BLACK)
if column % 1 == 0 and column % 2 == 0:
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
# Replace "pass" with loop code
# Use modulus operator and an if statement to select color
# Don't loop from 30 to 60 to shift everything over, just add 300 to x
def draw_section_3():
for row in range(30):
for column in range(30):
x = 10 * column + 603
y = 10 * row
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.BLACK)
if row % 1 == 0 and row % 2 == 0:
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
def draw_section_4():
for row in range(30):
for column in range(30):
x = 10 * column + 903
y = 10 * row
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.BLACK)
if row % 2 == 0 and column % 2 == 0:
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
# Use modulus operator and an if statement to select color
#if ... and ...
def draw_section_5():
for row in range(30):
for column in range(row+1):
x = 10 * row
y = 10 * column + 304
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
# Do NOT use if statements tp complete 5-8. Manipulate loops Instead
def draw_section_6():
for column in range(30):
for row in range(30-column):
x = 10 * column + 303
y = 10 * row + 303
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
def draw_section_7():
for row in range(30):
for column in range(row+1):
x = 10 * column + 603
y = 10 * row + 303
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
def draw_section_8():
for row in range(30):
for column in range(row):
for column in range(30-row):
x = 10 * column + 903
y = 10 * row + 303
arcade.draw_rectangle_filled(x, y, 5, 5, arcade.color.WHITE)
def main():
# Window
arcade.open_window(1200, 600, "Lab 05 - Loopy Lab")
arcade.set_background_color(arcade.color.AIR_FORCE_BLUE)
arcade.start_render()
# Draw outlines
draw_section_outlines()
# Draw sections
draw_section_1()
draw_section_2()
draw_section_3()
draw_section_4()
draw_section_5()
draw_section_6()
draw_section_7()
draw_section_8()
arcade.finish_render()
arcade.run()
if __name__=='__main__':
main()
|
from CalculatorMethods import *
from Packages import *
# is used when using eval to run equations
from math import *
def router(choice, total):
print("\n" * 50)
if 1 <= choice <= 4:
statement, total = basicmath_driver(choice, total)
print(statement)
elif choice == 5:
statement, total = trig_driver(total)
print(statement)
elif choice == 6:
stat_driver()
elif choice == 7:
db_driver()
elif choice == 8:
man_graph_driver()
elif choice == 9:
tup_graph_driver()
elif choice == 10:
eq_graph_driver()
elif not choice:
print("The total was reset")
total = 0
if total:
return total
def basicmath_driver(choice, total):
if not total:
print("Enter the first number:")
num1 = float_input()
else:
num1 = total
print("The previous total is", num1)
print("Enter the next number:")
num2 = float_input()
if choice == 1:
total = eval(str(num1) + "+" + str(num2))
elif choice == 2:
total = eval(str(num1) + "-" + str(num2))
elif choice == 3:
total = eval(str(num1) + "*" + str(num2))
elif choice == 4:
total = eval(str(num1) + "/" + str(num2))
return "The total is: " + str(total), total
def trig_driver(total):
if not total:
print("Enter the number in radians as a decimal (without the pi):")
num = float_input()
else:
print("Is the number in radians yet?")
rad_tru = input().lower()
if rad_tru[0] == 'y':
num = total
elif rad_tru[0] == 'n':
num = (total / 180) * pi
print("which operation do you want to preform on:", str(num) + "?\n",
"1. sin\n 2. cos\n 3. tan\n 4. sec\n 5. csc\n 6. cot")
op = int_input()
while op not in range(1, 7):
print("Please enter a value between 1 - 6")
op = int_input()
total = trig(num * pi, op)
return "The total is: " + str(total), total
def db_driver():
print("How many columns?")
cols = int_input()
print("How many rows?")
rows = int_input()
full_arr = []
for col_num in range(1, 1 + cols):
part_arr = []
for row_num in range(1, 1 + rows):
print("Enter the number for", str(col_num) + "," + str(row_num) + ":")
part_arr.append(float_input())
full_arr.append(part_arr)
print(database(full_arr))
def man_graph_driver():
print("How many columns?")
cols = int_input()
print("How many rows?")
rows = int_input()
full_arr = []
for col_num in range(1, 1 + cols):
part_arr = []
for row_num in range(1, 1 + rows):
print("Enter the number for", str(col_num) + "," + str(row_num) + ":")
part_arr.append(float_input())
full_arr.append(part_arr)
print(database(full_arr))
grapher(database(full_arr))
def tup_graph_driver():
print("How many coord points?")
count = int_input()
full_arr = []
for i in range(count):
print("Enter a point (x , y):")
str_coord_point = input()
a = tuple(map(float, str_coord_point.strip().split(",")))
full_arr.append(a)
tuple_grapher(full_arr)
def stat_driver():
print("How many entries of data?")
rows = int_input()
full_arr = []
for row_num in range(rows):
print("Enter a number:")
full_arr.append(float_input())
avg, numsum, numsum2, sam_std, pop_std, count, minimum, med, maximum = stats_onevar(full_arr)
print("The average:", avg, "\n",
"The sum:", numsum, "\n",
"The sum of num**2:", numsum2, "\n",
"The sample standard deviation:", sam_std, "\n",
"The population standard deviation:", pop_std, "\n",
"The n:", count, "\n",
"The minimum:", minimum, "\n",
"The median:", med, "\n",
"The maximum:", maximum)
def eq_graph_driver():
print("Acceptable functions:\n\n"
"sin(x)\tt**z\n"
"cos(t)\tsqrt(x)\n"
"tan(x)\tlog(t)\n"
"***The calculator requires notation such as:\n"
"...##*x...##*(t)...\n")
print("Enter the equation")
eq = str(input())
print("Enter the minimum x-value")
x_min = input()
print("Enter the maximum x-value")
x_max = input()
print("Enter the x-step")
x_step = input().lower()
print(equation_processor(eq, x_min, x_max, x_step))
if __name__ == '__main__':
total = 0
looper = True
while looper:
print("\n" * 50)
total = router(menu(total), total)
print("Enter (0) to quit, or any other key to continue")
looper = bool(int_input())
|
#!/usr/bin/env python
# coding: utf-8
# **Collecting and Importing the data**
# In[10]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import math
# In[3]:
titanic_url = "D:\My Work\Otherthan Syllabus\Data Science\Projects\Titanic Dataset\TitanicData.csv"
# In[111]:
df = pd.read_csv(titanic_url)
# In[112]:
df
# In[48]:
print("The no of passengers: ",len(df))
# **Analyzing the data**
# In[14]:
#Compoaring the passengers who survived and who did not
sns.countplot(x="Survived",data=df)
#So, 0 represents the non-survivors and 1 represents the survivors
# In[15]:
# Of the survivors how many were men and how many were women
sns.countplot("Survived",hue="Sex",data=df)
# In[17]:
# Of the survivors which class passengers survived the most
sns.countplot("Survived",hue="Pclass",data=df)
# So 3rd class passengers are the most non-survivors
# In[18]:
# different ages of passengers
df['Age'].plot.hist()
# **Data Wrangling**
# In[113]:
df.isnull().sum()
# In[114]:
#dropping the Cabin cloumn
df.drop("Cabin",axis=1,inplace=True)
# In[115]:
df
# In[116]:
df.isnull().sum()
# In[117]:
df.dropna(subset=["Embarked"],axis=0,inplace=True)
# In[118]:
df.isnull().sum()
# In[119]:
# replacing the null values of age with mean age of the cloumn
mean_age = df['Age'].mean()
mean_age
# In[120]:
df['Age'] = df['Age'].replace(np.nan,mean_age)
df['Age']
# In[121]:
df.isnull().sum()
# In[122]:
#rounding off the age
df['Age'].round()
# In[123]:
df['Age'] = df['Age'].astype('int')
# In[124]:
df.info()
# In[125]:
df.dtypes
# In[126]:
df.isnull().sum()
# In[127]:
df
# In[128]:
#converting sex, pclass and embarked to dummy variables
sex = pd.get_dummies(df['Sex'],drop_first=True)
sex.columns = ['Male']
sex
# In[81]:
#if Male is 1 then male else if it is 0 then female
# In[129]:
ebmarked = pd.get_dummies(df['Embarked'],drop_first = True)
ebmarked
# In[85]:
#if Q is 1 then its Q else if S is 1 then S else if both Q and S is 0 then it is C
# In[130]:
pclass = pd.get_dummies(df['Pclass'],drop_first = True)
pclass.columns = ['2nd class','3rd class']
pclass
# In[88]:
#if 2nd class is 1 then its 2nd class else if 3rd class is 1 then 3rd class else if both 2nd class and 3rd class is 0 then it is 1st class
# In[131]:
df = pd.concat([df,sex,ebmarked,pclass],axis=1)
df
# In[132]:
df = df.drop(['PassengerId','Pclass','Name','Sex','Ticket','Embarked'],axis=1)
# In[133]:
df
# **Training the data**
# In[135]:
x = df.drop(['Survived'],axis=1)
y = df['Survived']
# In[138]:
from sklearn.model_selection import train_test_split
# In[139]:
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.3,random_state=1)
# In[140]:
from sklearn.linear_model import LogisticRegression
# In[141]:
log_model = LogisticRegression()
# In[142]:
log_model.fit(x_train,y_train)
# In[143]:
prediction = log_model.predict(x_test)
# In[144]:
from sklearn.metrics import classification_report
# In[145]:
classification_report(y_test,prediction)
# In[146]:
from sklearn.metrics import confusion_matrix
# In[147]:
confusion_matrix(y_test,prediction)
# In[148]:
from sklearn.metrics import accuracy_score
# In[150]:
accuracy = accuracy_score(y_test,prediction)*100
# In[151]:
print(accuracy.round())
# In[ ]:
#So the model is 84% accurate
|
# -*- coding: utf-8 -*-
from fractions import gcd
def lcm(numbers):
def lcm(a, b):
return (a * b) // gcd(a, b)
return reduce(lcm, numbers)
print lcm(range(1,21))
|
# -*- coding: utf-8 -*-
print(sum([x for x in range(1,1000) if x%3==0 or x%5==0]))
|
# this is all of ETL to split the customers csv into first name, last name and age and add to the person table on SQL!
import pymysql
from os import environ
from datetime import date
from ETL.Extract.extract import csv_load
title_list = ["miss","ms","mrs","mr","dr"]
def process_customers(data):
temp_list=[]
for row in data:
if len(row) == 0 or row[0] == "Name": # check for empty rows or rows indicating table headers
continue # if the above is the case skips that row
try:
age = age_gen(row[1]) # try to generate an age from the DOB
except ValueError: # if that fails gives a value error
continue # then skips that row
first_name, last_name = name_breaker(row[0]) # assigning the values in the tuple
customer_tuple = (first_name, last_name, age) # making a new tuple with the age and masked ccn
temp_list.append(customer_tuple) # appending aforementioned tuple to the customer_list
return temp_list # returns list
def name_breaker(name): # Function to reformat names into the order "title","first name", "last name"
breaking_name = name.strip().lower().replace(".", "") # Strip away unwanted things e.g leading and trailing spaces, \n etc, formats all to lowercase and replaces any "." with ""
broken_name = breaking_name.split(" ") # Takes breaking_name and splits where there are " " into seperate values
last_name = broken_name[-1].title() # looks up the final index (-1) and formats it using "title" which recognises irish and double barrelled names.
if broken_name[0] in title_list: # if the first value in broken_name is a title from the list above in title_list then continue
title = broken_name[0].capitalize() # defining the first value as "title" and capitalising it
first_name = broken_name[1].capitalize() # the remainin value is then defined as the "first_name"
else:
title = None # if there is no title then None
first_name = broken_name[0].capitalize() # the remainin value is then defined as the "first_name"
return (first_name, last_name) # Either way, return the define values: title, first_name, last_name
def age_gen(dob): # generate an age from a dob
days_in_year = 365.2425 # defines how many days are a year including leap years
y, m, d = int(dob[:4]), int(dob[5:7]), int(dob[-2:]) # essentially splitting the dob according to the index and defining the y, m, d varibles.
birth_date = date(y, m, d) # defining the variable "birth_date" in the "date" format using the y, m, d varables from above.
age = int((date.today() - birth_date).days / days_in_year) # Defining variable age as: todays date subtract the birth_date, format this in number of days and divide by the days in the year.
return age # returns age in years
def get_connection(): # function to get the connection string using: pymysql.connect(host, username, password, database)
try:
db_connection = pymysql.connect(
environ.get("DB_HOST"), # host
environ.get("DB_USER"), # username
environ.get("DB_PW"), # password
environ.get("DB_NAME") # database
)
return db_connection
print("worked")
except Exception as error:
print(f"didn't work lol {error}")
def save_from_csv_to_db(list):
connection = get_connection()
cursor = connection.cursor()
for tuple in list:
first_name, last_name, age = tuple
args = (first_name, last_name, age)
try:
cursor.execute("INSERT INTO person (first_name, last_name, age) VALUES (%s, %s, %s)", args) # %s prevents SQL injection!
except Exception as err: # catches any duplicate errors, preventing it crashing out upon a duplicate.
print("Error: {}".format(err))
connection.commit() # updates the db, stack up the queries then commit at the end to be the most efficent.
cursor.close()
connection.close()
load_list = csv_load("customer.csv")
transformed_list = process_customers(load_list)
print(transformed_list)
save_from_csv_to_db(transformed_list)
|
import math
x = 3400
empirico = x + (0.3*x) * ( (0.7*x) + (0.7*x * math.log2(x)) + (0.7*x) + (0.7*x))
print("Custo empirico: ", empirico)
assintotico = x**2 * math.log2(x)
print("Custo assintotico: ", assintotico)
proporcao = empirico/assintotico
print("Proporcao: ", proporcao)
|
#If change in parameter can't enhance the model greatly, cross validation will be forewent.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn import preprocessing
diabetes=load_diabetes()
X_raw=diabetes.data
y=diabetes.target
X_normalized=preprocessing.scale(X_raw)
X_train, X_test, y_train, y_test=train_test_split(X_normalized,y,test_size=0.3)
lr=LinearRegression(fit_intercept=False)
lr.fit(X_train,y_train)
score=lr.score(X_test,y_test)
print(score)
#score=-3.285289767
#Conclusion: In this example, it is unwise to not fit the intercept.
#Conclusion: Another model has to be chosen. Accoding the sklearn cheat sheet, Lasso and Elastic Net will be chosen.
#Reason: Aftering plotting graph of features, many of features seem irrealvant to the target by visulization from the below a
#piece of code
#for i in range(10):
# plt.scatter(X_raw[:,i], y)
# plt.show()
|
#coding: utf-8
age = 20
name = 'Swaroop'
#format格式化参数,变量的设置
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('why is {0} playing with that python?'.format(name))
#对于浮点数,保留小数点后三位
print('{0:.3f}'.format(1.0/3))
#下划线填充文本,使字符串位于中间
#使用(^)定义字符串长度
print('{0:_^7}'.format('hello'))
#print会自带一个'\n'换行,如果不想换行可以通过end指定以空白结尾
print('a', end=' ')
print('b')
|
"""
687. 最长同值路径
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例 1:
输入:
5
/ \
4 5
/ \ \
1 1 5
输出:
2
示例 2:
输入:
1
/ \
4 5
/ \ \
4 4 5
输出:
2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
result = 0
def traverse(root):
nonlocal result
if root == None:
return 0
# elif root.right == None and root.left == None:
# return 1
traveseLeft = traverse(root.left)
traveseRight = traverse(root.right)
traveseLeft = 0 if (not root.left or root.val != root.left.val) else traveseLeft
traveseRight = 0 if (not root.right or root.val != root.right.val) else traveseRight
if 1 + traveseLeft + traveseRight > result:
result = 1 + traveseLeft + traveseRight
return 1 + max(traveseRight, traveseLeft)
traverse(root)
return 0 if result == 0 else result - 1
t = TreeNode(1, TreeNode(4, TreeNode(4, None), TreeNode(4, None)), TreeNode(5, None))
s = Solution()
r = s.longestUnivaluePath(t)
print(r)
|
#2 Write a program to find the biggest of 3 numbers (Use If Condition)
num1=int(input('Enter first number:'))
num2=int(input('Enter second number:'))
num3=int(input('Enter third number:'))
if (num1>num2 & num1>num3):
print('{0} is greatest)'.format(num1))
elif (num2>num1 & num2>num3):
print('{0} is greatest)'.format(num2))
else :
print('{0} is greatest'.format(num3))
|
#9.Write program to Add, Subtract, Multiply, Divide 2 Complex numbers.
a=input('Enter the part a of number:')
b=input('Enter the part b of number:')
c=("Complex number:",str(a)+' + '+str(b)+' '+'j')
print(c)
|
#7.Create a list with at least 10 elements having integer values in it;
#Print all elements
#Perform slicing operations
#Perform repetition with * operator
#Perform concatenation with other list.
List = [1,2,3,4,5,6,7,8,9,10]
print(List)#Print all elements
print(List[1:4]) #Perform slicing elements
print(10 * List[0:10]) #Perform repetition with * operator
List2=[3,4,5]
List3=List+List2
print(List3[0:10])
|
def number_tally(numbers):
tally = {}
for number in numbers:
if number not in tally:
tally[number]=0
tally[number]+= 1
print (tally)
return tally
numbers = "123475661264"
number_tally(numbers)
|
arr = [4, 3, 2, 1]
for elements in range(len(arr),0,-1):
print(arr[elements])
|
string = input("enter the string")
list = string.split(",")
print(list)
result = {}
count = 1
for elements in range(0, len(list)):
result[list[elements]] = count
if list[elements] in result.keys():
result[list[elements]] = +1
print(result)
|
from collections import Counter
s = 'aabbccdde'
dict = {}
for element in s:
if element not in dict:
dict[element] = 1
else:
dict[element] += 1
print(dict)
values = dict.values()
list = []
for val in values:
list.append(val)
print(list)
print(Counter(list))
|
# from math import floor
#
#
# def activityNotifications(expenditure, d):
# print(expenditure)
# median_list = []
# sorted_list = []
# mid_value = floor(d / 2)
# notice_count = 0
# print("mid_value:", mid_value)
#
# for index in range(0, len(expenditure)):
# slice_range = index + d
# slice_object = slice(index, slice_range)
# value = expenditure[slice_object]
# if len(value) == d:
# median_list.append(expenditure[slice_object])
# for element in range(0, len(median_list)):
# sorted_value = sorted(median_list[element])
# sorted_list.append(sorted_value)
# median = sorted_list[element][mid_value]
# print("median:", median)
# print("sorted list:", sorted_list)
# print(median_list)
#
#
# #
# # if __name__ == '__main__':
# # nd = input().split()
# #
# # n = int(nd[0])
# #
# # d = int(nd[1])
# #
# # expenditure = list(map(int, input().rstrip().split()))
# #
# # result = activityNotifications(expenditure, d)
#
# activityNotifications([1, 2, 3, 4, 4], 4)
|
print(" Welcome to Hangman!")
print("Guess your letter")
Guess_word = str("CAT")
list = []
guess_list = []
for letter in Guess_word:
value = ord(letter)
list.append(value)
for blank in range(0, len(Guess_word)):
print('- ', end='')
game = str(input())
guess_value = ord(game)
guess_list.append(guess_value)
for element in range(0, len(list)):
if guess_list[0] == list[element]:
print("GUESS IS CORRECT")
|
print(" Welcome to Hangman!")
print("Guess your letter")
guess_Word = str("CAT")
print("- " * len(guess_Word))
guess_Dict = {}
for letter in range(0, len(guess_Word)):
key = guess_Word[letter]
value = ord(guess_Word[letter])
guess_Dict[key] = value
print(guess_Dict)
user_input = input("Enter any alphabet to play:")
user_input = user_input.upper()
guess_value = ord(user_input)
for element in guess_Dict.values():
if guess_value != element:
continue
elif guess_value == element:
print(chr(element))
break
|
#komentarz
print("Hello world!")
print('Hello "world"!')
number = 3
number_str = "3"
print(number_str)
print(number)
print(type(number_str))
print(type(number))
print(type(3.14))
print(0.1+0.1+0.1)
print(type(True))
print(type(None))
number = number + 1
print(number)
hello = "Hello"
world = "world"
ex = "!"
#konkatenacja stringów
sign = hello +" "+ world + ex
print(sign)
#name = input("Jak masz na imię?").capitalize()
#name = name.upper()
#greeting =hello.upper() + " " + name.lower() + ex.upper()
#print(greeting)
#print(greeting[:])
#print(len(greeting)) #11
#print(greeting[:len(greeting)-2]) # wyswietli 11-2
#print(greeting[12])
#number = "3"
#print(number.isnumeric())
sentence = "ala ma kota"
#print("ala" in sentence)
print(type(sentence) is float)
birthyear ="1990"
birthyear = int(birthyear)
print(birthyear)
print(type(str(6)))
print(type(bool(0)))
print()
|
#!/usr/bin/python
#
# Juan Carlos Perez
# [email protected]
# @perezpardojc
#
# Program:
#
# Program to convert in any bases
# How to use: execute # python alltogether.py
#
#
#imports
import os
import sys
import re
import datetime
import time
import argparse
import itertools
def Palindrome_Number(n):
#n = input('Enter Number to check for palindromee: ')
#print "Hi , The number is :",n
#print ""
m=n
a = 0
while(m!=0):
a = m % 10 + a * 10
m = m / 10
if( n == a):
print('%d is a palindrome number' %n)
else:
print('%d is not a palindrome number' %n)
return ""
#return
#pass
def My_Bases(argument):
switcher = {
2: "Binary - Base 2",
3: "Base 3",
4: "Base 4",
5: "Base 5",
6: "Base 6",
7: "Base 7",
8: "Octal - Base 8",
9: "Base 9",
10: "Decimal - Base 10",
11: "Base 11",
12: "Base 12",
13: "Base 13",
14: "Base 14",
15: "Base 15",
16: "Hexadecimal - Base 16",
}
return switcher.get(argument, "nothing")
def base10toN(num, base):
"""Change ``num'' to given base
Upto base 36 is supported."""
converted_string, modstring = "", ""
currentnum = num
if not 1 < base < 37:
raise ValueError("base must be between 2 and 36")
if not num:
return '0'
while currentnum:
mod = currentnum % base
currentnum = currentnum // base
converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
return converted_string
#
# main area
#
print("Comienzo of my super palindrome")
for base in itertools.count(start=2, step=1): #base
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
for num in itertools.count(start=0, step=1): #numbers
print("Numero en decimal: ",num)
print("BASE en : ",My_Bases(base),base10toN(num,base)) #base en
print(Palindrome_Number(int(base10toN(num,base))))
#print("Numero en base binaria: ",base10toN(num,base))
time.sleep (50.0 / 1000.0);
if (num==10):
break
if (base==16):
break
print("")
print("Final")
|
#!/usr/bin/python
#
# Juan Carlos Perez
# [email protected]
# @perezpardojc
#
# Program:
#
# Get help python palindromic.py -h
#
#
#imports
import os
import sys
import re
import datetime
import time
import argparse
# functions
#def palindrome(num):
# return num == num[::-1]
# print "es palindromo"
def palindrome(num):
if (num[::-1] == num):
print "es palindromo"
return True
else:
return False
# main
# this is the help in case executed -h
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
#print "Hola , el numero es :", args.integers[0]
num = int(args.integers[0])
print "Hola , el numero es :",num
print id(num)
#palindrome(num)
def ReverseNumber(n, partial=0):
if n == 0:
return partial
return ReverseNumber(n / 10, partial * 10 + n % 10)
trial = 123454321
if ReverseNumber(trial) == trial:
print "It's a Palindrome!"
|
import csv
import json
#Read the input.csv and convert it to output.json
csvfile = open('input.csv', 'r')
jsonfile = open('output.json', 'w')
#Sort each row with cooresponding attribute to json format
fieldnames = ("")
csvReader = csv.DictReader(csvfile, fieldnames)
for csvRow in csvReader:
json.dump(csvRow, jsonfile)
jsonfile.write('\n')
|
import random
import math
import time
import sys
def simulation(n, k, alpha_low, alpha_high, alpha_step):
"""Run the simulation on the complete graph of size n.
For each value of alpha perform k simulations
Note that here beta = alpha / n and the critical point should occur at alpha = 1
"""
#vary alpha from small to above critical value
f = open('new_results/curie_weiss:' + str(n) + ':' + str(k) + ':time: ' + str(time.time()), 'w')
alpha = alpha_low
while alpha <= alpha_high:
print("Testing alpha = " + str(alpha))
for i in range(1, k):
print(i)
iterations, duration = mix_chains(n, alpha)
f.write(str(alpha) + ", " + str(iterations) + ", " + str(duration) + "\n")
alpha += alpha_step
f.close()
def mix_chains(n, alpha):
"""Run the chains X and Y until they have the same state
Return the number of moves taken as well as the system time
"""
#we are on the graph K_n so we represent X and Y by two lists and counts for bookkeeping
X = [1 for i in range(n)]
X_pos_total = n
Y = [-1 for i in range(n)]
Y_pos_total = 0
#timing information
iterations = 0
start = time.clock()
#+-1 for spins
while X_pos_total != Y_pos_total:
iterations += 1
#choose a random vertex
v = random.randint(0, n - 1)
#calculate the probability of the vertex being positive with Glauber for both chains
Y_pos_prob = 0
Y_pos_count = 0
if(Y[v] == 1):
Y_pos_count = Y_pos_total - 1
spin_sum = Y_pos_count - (n - Y_pos_count - 1)
Y_pos_prob = math.exp(alpha / n * spin_sum) / (math.exp(alpha / n * spin_sum) + math.exp(-1 * alpha / n * spin_sum))
X_pos_prob = 0
X_pos_count = 0
if(X[v] == 1):
X_pos_count = X_pos_total - 1
spin_sum = X_pos_count - (n - X_pos_count - 1)
X_pos_prob = math.exp(alpha / n * spin_sum) / (math.exp(alpha / n * spin_sum) + math.exp(-1 * alpha / n * spin_sum))
r = random.random()
if r <= Y_pos_prob:
if Y[v] == -1:
Y_pos_total += 1
Y[v] = 1
else:
if Y[v] == 1:
Y_pos_total -= 1
Y[v] = -1
if r <= X_pos_prob:
if X[v] == -1:
X_pos_total += 1
X[v] = 1
else:
if X[v] == 1:
X_pos_total -= 1
X[v] = -1
return (iterations, time.clock() - start)
def main():
"""
Main method, read in command line arguments and call simulation
Command Line Args are:
size, iterations per alpha, lower alpha, uper alpha, step alpha
"""
if len(sys.argv) < 6 :
print("Must supply n, k, a_low, a_high, a_step space delimited")
else:
simulation(int(sys.argv[1]), int(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5]))
main()
|
friends = ["Asad", "Fawad", "Sadaf", "Hammad"]
for text in friends:
print(text)
print()
for friend in range(len(friends)):
print(friends[friend])
print()
for index in range(1, 200):
print(index)
for index in range(5):
if index == 0:
print("First")
else:
print("Not First")
|
"""
Write an efficient function that checks whether
any permutation of an input string is a palindrome.
I'm assuming here that 'efficient' refers to an algorithm
that runs in O(n) time.
"""
import unittest
def is_permutation_palindromic(instr):
# if string has even number of chars,
# all should appear in pairs
# if string has odd number, we should
# get all pairs and a singleton.
# otherwise this is not a palindromic string.
if len(instr) % 2 == 0:
#pair up numbers
else:
#pair up numbers
# check we have a singleton
pass
class Tests(unittest.TestCase):
def test_all_chars_same(self):
self.assertTrue(is_permutation_palindromic("aaa"))
self.assertTrue(is_permutation_palindromic("bbbb"))
def test_odd_char(self):
self.assertTrue(is_permutation_palindromic("civic"))
self.assertTrue(is_permutation_palindromic("ivicc"))
self.assertFalse(is_permutation_palindromic("civil"))
self.assertFalse(is_permutation_palindromic("livci"))
def test_even_chars(self):
self.assertTrue(is_permutation_palindromic("ciic"))
self.assertTrue(is_permutation_palindromic("icic"))
self.assertTrue(is_permutation_palindromic("aa"))
self.assertFalse(is_permutation_palindromic("oxoo"))
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
### dict ###
#dict就是key-value存储
dict_test = {'a': 1, 'b': 2, 'c': 3}
print(dict_test['a'])
print(dict_test.get('a'))
print(dict_test.get('aa'))
print('aa' in dict_test)
###增
dict_test['d'] = 4
print(dict_test)
###改
dict_test['d'] = 666
print(dict_test)
###改增
dict_test_temp = {'dd': 888}
dict_test.update(dict_test_temp)
print(dict_test)
###删
dict_test.pop('dd')
print(dict_test)
### set ###
#set就是没有value的dict,由于key的唯一性,所以多用于去重
s=set([1,2,3,4,5,6])
print(s)
#增
s.add(1)
print(s)
s.add(7)
print(s)
s.remove(2)
print(s)
#交集并集
s1=set([1,2,3])
s2=set([2,3,4])
print(s1&s2)
print(s1|s2)
|
#PROGRAMACION ORIENTADA A OBJETOS EN PYTHON
class Character:
#__init__ es el constructor, importante el objeto "self" es objeto y no variable
#las variables del constructor son name e initial_health
#self es lo mismo que "this" en C# o "me" en VB.NET
def __init__(self, name, initial_health):
self.name = name
self.health = initial_health
self.inventory = []
# __str__ es otra funcion especial, viene siento el toString() en VB.NET
#y puedo acceder a las propiedades name, health, y tambien inventory
def __str__(self):
s = "Name: " + self.name
s += ", Health: " + str(self.health)
s += ", Inventory: " + str(self.inventory)
return s
#funciones normales
def grab(self, item):
self.inventory.append(item)
def get_health(self):
return self.health
#ojo, no se pasa el parametro self, y se ejecuta el constructor
yo = Character("Luis", 21)
#cuando imprimo el objeto se llama el metodo __str__
print (yo)
#puedo llamar a mas funciones
yo.grab("pc")
yo.grab("telefono")
print (yo)
print (yo.get_health())
|
nums=[-7,-3,2,3,11]
def square_num(nums):
return sorted([x**2 for x in nums ])
print(square_num(nums))
|
def cons_num(nums):
cnt, res = 0, 0
for i in nums:
if i == 1:
cnt += 1
else:
res = max(res, cnt)
cnt = 0
return res
print(cons_num([1,1,1,1,0,1]))
|
'''
Prints the total value of all sites
'''
def task_four(websites):
total = 0
for website in websites:
try:
total += website['value']
except:
print('Website does not have "value" key or invalid value type.')
continue
print(total)
return total
|
import keyboard
def pfun():
print("you pressed p")
def rfun():
print("you pressed r")
while True:
if keyboard.read_key()=="p":
#pfun()
print(" you pressed p")
if keyboard.read_key()=="r":
print(" you pressed r")
#rfun()
if keyboard.read_key()=="q":
print("You pressed q")
break
|
# Authur: Nasir Lawal
# Date: 23-Nov-2019
"""
Description: Tutorial on the difference between "Syntax and Exception"
"""
while True:
try:
number = int(input("What is your fav number?\n"))
print(18/number)
break
except ValueError:
print("Make sure you enter a number")
except ZeroDivisionError:
print("Don't pick zero")
except:
break
finally:
print("loop complete")
|
from heapq import heappush, heappop
def execution_time(tasks, cool_down):
"""
Calculate the total execution time of a given task with cool down
:param tasks: a string denoting tasks
:param cool_down: cool down time for the same task
:return: total execution time
"""
task_index_dict = {} # {task: index in execution list + 1 = exe_time}
exe_time = 0
for t in tasks:
if t in task_index_dict and exe_time - (task_index_dict[t] - 1) <= cool_down:
exe_time += (cool_down - (exe_time - task_index_dict[t]))
exe_time += 1
task_index_dict[t] = exe_time
return exe_time
print(execution_time("AABA", 3))
# Follow up: rearrange the order of tasks to minimize the total execution time
def min_task_sequence(tasks, cool_down):
task_freq_dict, freq_heap = {}, []
# Step 1: go through tasks and calculate their frequency
for t in tasks:
task_freq_dict[t] = task_freq_dict.get(t, 0) + 1
# Step 2: Maintain a max heap to get task by frequency
for t, f in task_freq_dict.items():
heappush(freq_heap, [-f, t]) # min heap by default
# Step 3: Rearrange sequences. e.g. AAAAABBBBCCCDDEF -> ABAB... if cool_down = 1
# ABCABC... if cool_down = 2; ABCDABCD... if cool_down = 3
# In general, put the most frequent task first, and then the less frequent task, and so on. window len = cool_down
min_sequence = ""
while freq_heap:
group = []
# Put the most frequent task first, and then the less frequent task, inside a widow with len = cool_down
for i in range(cool_down + 1):
if freq_heap: # length of freq_heap may be < cool_down
task = heappop(freq_heap)
min_sequence += task[1] # Get the task occurring most frequently
group.append(task)
else:
break
# Make as many groups as possible
group_len = len(group)
while group:
task = group.pop()
task[0] += 1 # Subtract the frequency by 1, Notice '-' in [-f, t]
if -task[0] > 0:
heappush(min_sequence, task) # Get task out and subtract by 1 and then push it back
# Fill sequence with '-' when the group_len is less than cool_down. i.e. groups * N + remainder
if freq_heap:
min_sequence += '_' * (cool_down + 1 - group_len)
return min_sequence
|
def min_subarray_sum(n, s):
"""
Find the minimum size of sub array which has sum greater than or equal to s
:param n: array with positive integers
:param s: target sum
:return: minimum size of sub array
"""
n_len = len(n)
min_size = n_len + 1
if n_len == 0:
return 0
sum_ij = 0
j = 0
for i in range(n_len):
# Move left cursor
if i != 0:
sum_ij -= n[i - 1]
if sum_ij >= s:
min_size = min(min_size, j - i + 1)
continue
else:
j += 1
# Move right cursor
while j < n_len:
sum_ij += n[j]
if sum_ij >= s:
min_size = min(min_size, j - i + 1)
break
j += 1
return min_size if min_size != n_len + 1 else 0
def min_size_subarray_sum_concise(n, s):
sub_sum = i = 0
min_len = len(n) + 1
for j in range(len(n)):
sub_sum += n[j]
while sub_sum >= s:
min_len = min(min_len, j - i + 1)
sub_sum -= n[i]
i += 1
return min_len if min_len < len(n) + 1 else 0
def subarray_sum_2d_brute_force(nums, target):
row = len(nums)
if row == 0:
return False
col = len(nums[0])
if col == 0:
return False
# Calculate accumulative sum and overwrite nums
for i in range(1, row): # first column
nums[i][0] += nums[i - 1][0]
for j in range(1, col): # first row
nums[0][j] += nums[0][j - 1]
for i in range(1, row):
for j in range(1, col):
nums[i][j] = nums[i - 1][j] + nums[i][j - 1] - nums[i - 1][j - 1] + nums[i][j]
for n in nums:
n.insert(0, 0)
nums.insert(0, [0] * (col + 1))
# Search rectangle inside which the elements sum up to target
for i in range(1, row + 1):
for j in range(1, col + 1):
sub_sum = nums[i][j]
if sub_sum >= target:
for m in range(i + 1):
for n in range(j + 1):
if sub_sum == target:
return True
sub_sum = nums[i][j] - nums[m][j] - nums[i][n] + nums[m][n]
return False
def subarray_sum_2d_concise(nums, target):
# Corner cases: nums = None, nums = []
if not nums:
return False
row = len(nums)
col = len(nums[0])
# Corner case: nums = [[]]
if col == 0:
return False
for left in range(col):
row_sum = [0] * col
for right in range(left, col):
# Get sum of elements at the same row
for r in range(row):
row_sum[r] += nums[r][right]
# Leveraging 1D case
if check_rectangle_sum(row_sum, target):
return True
return False
def check_rectangle_sum(array, target):
s = i = 0
for j in range(len(array)):
s += array[j]
while s >= target:
if s == target:
return True
s -= array[i]
i += 1
return False
print(min_subarray_sum([3, 1], 10))
print(subarray_sum_2d_brute_force([[2, 3, 6], [4, 1, 5], [7, 8, 9]], 20))
print(subarray_sum_2d_concise([[2, 3, 6], [4, 1, 5], [7, 8, 9]], 20))
|
class Solution(object):
def find_sub_string(self, s, words):
indices, num_words = [], len(words)
if num_words == 0:
return indices
str_len, word_len = len(s), len(words[0])
word_count_dict = dict()
# Get frequency of each word. Words may contain duplicates
for w in words:
word_count_dict[w] = word_count_dict.get(w, 0) + 1
# Traverse from
for i in range(str_len - num_words * word_len + 1):
j, str_count_dict = 0, dict()
while j < num_words:
sub_str = s[i + word_len * j: i + word_len * (j + 1)]
if word_count_dict.get(sub_str, None):
str_count_dict[sub_str] = str_count_dict.get(sub_str, 0) + 1
if str_count_dict[sub_str] > word_count_dict[sub_str]:
break
else:
break
j += 1
if j == num_words:
indices.append(i)
return indices
s = Solution()
print(s.find_sub_string("barfoofoo", ["foo", "bar"]))
|
from collections import deque
def longest_path_in_BST(root):
max_path = 0
def longest_path_in_BST_helper(root):
"""Return the maximum depth of a BST"""
nonlocal max_path
if not root:
return 0
left_depth = longest_path_in_BST_helper(root.left)
right_depth = longest_path_in_BST_helper(root.right)
max_path = max(max_path, left_depth + right_depth + 1)
return max(left_depth, right_depth) + 1
longest_path_in_BST_helper(root)
return max_path
def print_longest_path_in_BST(root):
path = deque()
longest_path = []
print_longest_path_in_BST_helper(root, path, longest_path)
return longest_path
def print_longest_path_in_BST_helper(root, path, longest_path):
if not root:
return []
if not root.left and not root.right:
return path.appendleft(root.val)
path.appendleft(root.val)
left_path = print_longest_path_in_BST_helper(root.left, path, longest_path)
right_path = print_longest_path_in_BST_helper(root.right, path, longest_path)
for l in left_path:
for r in right_path:
if len(l) + len(r) + 1 > len(longest_path):
longest_path = [l + [root.val] + r]
elif len(l) + len(r) + 1 == len(longest_path):
longest_path.append(l + [root.val] + r)
if left_path > right_path:
return left_path
elif left_path < right_path:
return right_path
else:
return left_path + right_path
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(longest_path_in_BST(root))
print(print_longest_path_in_BST(root))
|
from heapq import heappush, heappop, heapify
def find_median(nums_list):
"""
Find median of a list of sorted arrays
:param nums_list:
:return:
"""
index = [0] * len(nums_list)
total_nums = sum(list(map(lambda x: len(x), nums_list)))
heap = []
for i, nums in enumerate(nums_list):
heappush(heap, (nums[0], i))
n = total_nums // 2 + 1
median1 = median2 = 0
while n > 0:
median2 = median1
median1, j = heappop(heap)
index[j] += 1
if index[j] < len(nums_list[j]):
heappush(heap, (nums_list[j][index[j]], j))
n -= 1
return median1 if total_nums % 2 else (median1 + median2) / 2
print(find_median([[1, 2, 3], [5]]))
|
class ticket(object):
def __init__(self,price,start = '',destination = '',date = '',Class = 'economy'):
"""initialize the ticket field"""
self.start = start
self.destination = destination
self.date = date
self.Class = Class
self.price = price
def __str__(self):
"""display all the field"""
return "start from %s to %s the date is:%s Class:%s and price:%d" % \
(self.start,self.destination,self.date,self.Class,self.price)
print "I am come from another computer"
|
from Mars import MarsLandingArea
from Rover import Rover
import sys
def navigate(commands,rover,landingArea):
# This is the knowledge the Rover uses to read its commands.
# If the rover does not read an 'L', 'R', or 'M' then it sends an Error message, returns to its initial position and requests a new set of commands.
# Otherwise, it uses its own methods to turn 90 degrees, left or right, and move accordingly.
# After a 'Move Forward' request is made, the rover checks to see if the that space is occupied.
# If space is occupied, then an Error message, rover is returned to initial position, along with a request for a new set of commands.
# If space is NOT occupied, then the rover Object is updated and moves on in the land_rover() process.
try:
for command in commands:
if command == "L":
rover.turnLeft() # => see Rover.py for more details
elif command == "R":
rover.turnRight() # => see Rover.py for more details
elif command == "M":
rover.moveForward(landingArea) # => see Rover.py for more details
else:
raise ValueError('Incorrect directional value')
except Exception as err:
raise err
def get_intial_rover_position(landingArea):
# Here is where we create a Rover Object attached to the Landing Area Object
# We also check too see if the input is 'report' or 'exit', if so, => See user_input_check()
# Again, a loop is run to ensure that acquiring user input does not terminate the program until all rovers are created and landed.
while True:
rover = None
rover_input = user_input_check(input("\n--------------\n** Enter a Rover's starting position and direction.\n* Or enter 'report' to get Rover Report.\n* Or enter: 'end' to terminate:\n--------------\n=> "), landingArea).split()
try:
if 'report' not in rover_input:
rover = Rover(int(rover_input[0]), int(rover_input[1]), rover_input[2].upper(),landingArea)
except Exception as err:
print(err)
continue
# If input values are valid, a new Rover is create and sent for landing => land_rover()
if rover is not None:
return rover
def user_input_check(userInput, landingArea):
# Here is where we check to see if the user has requested to a Rover Report status or wants to exit the program.
# Regardless , the user input is return to whatever function it was acquired.
if 'end'.upper() in userInput.upper():
print('\n========================\n### End Program ###\n========================\n')
sys.exit()
elif 'report' in userInput.lower():
show_landed_rovers(landingArea)
return userInput
def land_rover(rover,landingArea):
# Using only a sequence of L, M ,R. The user gives commands for the Rover to take in and see if it can land or not.
# If there is a Rover already occupying the attempted landing position, the rover will alert an Error Message and return to its initail position.
# If the Rover is ordered to try and land outside of the Landing Area, it will alert an Error Message and return to its initial position.
moved = False
try:
commands = user_input_check(input("\n--------------\nPlease enter a sequence of commands:\nOnly use 'L','R','M' or 'end' to terminate\n--------------\n=> "),landingArea).upper()
if 'REPORT' not in commands:
# Here is where the commands are sent with the Rover to be calculated and to determine if the spot is taken by another Rover.
navigate(commands, rover, landingArea) # => Here is all the knowledge for the Rover to compute the sequence of commands
# If commands are determined valid and the rover object is updated, another check comes to determine
if (rover.yPositionCheck(landingArea) and rover.xPositionCheck(landingArea) and rover.directionPositionCheck(landingArea)):# Here is where the rover checks if the landing coordinates are acceptable
landingArea.taken.append([rover.x, rover.y, rover.direction])
moved = True
except Exception as err:
print(err)
if moved:
print('\n------------------------------------\n~~~~~~ Rover Landing Success! ~~~~~~\n------------------------------------')
show_landed_rovers(landingArea)
return
def show_landed_rovers(landingArea):
# Here is where we present the Rover Report
# The Rover Report prints the taken Landing Area list, it also is shown after each succesful landing
print('\n-----------------------\n ** Rover Report ** \n-----------------------\nMars landing area:\n'+ str(landingArea.x) + ' x ' + str(landingArea.y)+'\n')
for rover in landingArea.taken:
print ("{} {} {}".format(rover[0],rover[1],rover[2]))
print('-----------------------')
def main():
# This where the program is initiated.
# A loop is used to allow the input to not terminate until a Landing Object is created
print('\n==================================\n ~~ MARS ROVER TECH CHALLENGE ~~ \n==================================')
end_loop = False
while (not end_loop):
landing_area_input = input('\n--------------\n** Please enter two numbers, separated by a space, to determine the dimensions for the Mars landing Area:\n--------------\n => ').split(' ')
if len(landing_area_input) == 2 and landing_area_input[0].isdigit() and landing_area_input[1].isdigit():
landingArea = MarsLandingArea(int(landing_area_input[0]), int(landing_area_input[1]))
end_loop = True
else:
print('Please enter valid dimensions for landing plateau')
# Once Landing Area dimensions are determined, the Landing Area is passed to the where the Rover's intial position is, and assigned the created rover.
while True:
rover = get_intial_rover_position(landingArea) # Create Rover and initial position
# After initial Rover position is set, acquire sequence of commands to attempt to land Rover.
# Also, keep track of the landing area to see if there is already a rover that has landed.
land_rover(rover, landingArea) # land Rover based on given instructions
if __name__ == "__main__":
main()
|
import re
# On 'None' method, you cannot invoke group method
str = "Take up one idea. one idea at a time."
str1 = "Take 1 up one 23 idea. one idea 45 at a time."
result1 = re.search(r'o\w\w', str)
print(result1.group())
result2 = re.findall(r'o\w\w', str)
print(result2)
# 'match' only looks at the beginning
result3 = re.match(r'o\w\w', str)
print(result3)
result3 = re.match(r'T\w\w', str)
print(result3.group())
result4 = re.split(r'\d', str1)
print(result4)
result5 = re.sub(r'one', 'two', str)
print(result5)
result6 = re.findall(r'o\w{1, 2}', str)
print(result2)
str2 = "Today's date is 29-12-2019 and tomorrow's date is 30-12-2019."
result7 = re.findall(r'\d{1,2}-\d{1,2}-\d{4}', str2)
print(result7)
result8 = re.search(r'^T\w*', str)
print(result8.group())
|
x = 10
y = 20
print(x + y)
s1 = "Hello!"
s2 = " How are you?"
print(s1 + s2)
lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
print(lst1 + lst2)
|
#创建一个表示汽车的类,存储有关汽车的信息,还有一个总汇这些信息的方法-get_descriptive_name
class Car():
#一次模拟汽车的简单尝试
def __init__(self,make,model,year):
#初始化描述汽车的属性
self.make = make
self.model = model
self.year = year
def get_discriptive_name(self):
#返回整洁的描述信息
long_name = str(self.year) + ' '+self.make + ' '+self.model
return long_name.title()
#创建实例
my_new_car = Car('audi','a4',2016)
print(my_new_car.get_discriptive_name())
|
prompt = "\nTell me somthing, and I will repeat it it to you:"
prompt += "\nEnter 'quit' to end the program."
message = 1
while message != 'quit':
print(prompt)
message = input()
|
cars = ['bmw','audi','toyota','subaru']
cars.sort() #顺序归纳
print(cars)
cars.sort(reverse = True)
print(cars)
|
#Práctico 5: Usando como base el programa anterior, crear un programa que permita seleccionar un rectángulo de una imagen.
# Con la letra “g” lo guardamos a disco en una nueva imagen y salimos.
# Con la letra “r” restauramos la imagen original y volvemos a realizar la selección.
# Con la “q” salimos.
import cv2
img = cv2.imread('La libertad guiando al pueblo.jpg', cv2.IMREAD_COLOR)
x1, y1, x2, y2 = -1, -1, 1, -1
def draw(event, x, y, flags, param):
global x1, y1, x2, y2
if event == cv2.EVENT_LBUTTONDOWN:
x1, y1 = x, y
elif event == cv2.EVENT_LBUTTONUP:
x2, y2 = x, y
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), 3)
return (x1, x2, y1, y2)
cv2.namedWindow('Imagen')
cv2.setMouseCallback('Imagen', draw)
while(True):
cv2.imshow('Imagen', img)
tecla = cv2.waitKey(20)
if tecla == ord('g'):
print('x1:', x1, 'x2:', x2, 'y1:', y1, 'y2:', y2)
img = cv2.imread('La libertad guiando al pueblo.jpg', cv2.IMREAD_COLOR)
if (y2 >= y1) & (x2 >= x1):
crop_img = img[y1:y2, x1:x2]
elif (y2 >= y1) & (x2 < x1):
crop_img = img[y1:y2, x2:x1]
elif (y2 < y1) & (x2 >= x1):
crop_img = img[y2:y1, x1:x2]
else:
crop_img = img[y2:y1, x2:x1]
cv2.imshow('Imagen recortada', crop_img)
cv2.waitKey(0)
cv2.imwrite('La libertad guiando al pueblo-editado-.jpg', crop_img)
break
elif tecla == ord('r'):
img = cv2.imread('La libertad guiando al pueblo.jpg', cv2.IMREAD_COLOR)
elif tecla == ord('q'):
break
cv2.destroyAllWindows()
|
#공포도 별 모험가 그룹 나누기
#내 코드
n=int(input("모헙가의 수 입력하세요"))
data=list(map(int,input().split()))
data.sort()
#5명 공포도 3이하의 공포도를 가진 사람들(3명)으로 구성
count=0
max_scared=max(data)
while(True):
if ( len(data) >= max_scared ):
for _ in range(max_scared):
del data[n-1]
n-=1
count+=1
if len(data)==0:
break
max_scared=max(data)
elif len(data) < max_scared:
data.remove(max_scared)
n-=1
max_scared = max(data)
if len(data)==0:
break
#3 3 3 3 1 -> 1 3
print(count)
# 새로운 코드
n=int(input("모헙가의 수 입력하세요"))
data=list(map(int,input().split()))
data.sort()
#총 그룹 수
result=0
#그룹 포함된 모험가 수
count=0
for i in data:
count+=1
if count >= i:
result+=1
count=0
#여긴 내가 추가한 부분
print(result)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 21:55:13 2018
@author: liran
"""
class A(type):
def __call__(c,arg):
c.xyz=900
print("A",arg)
return super(A,c).__call__(arg)
class B(object):
def __call__(c,arg):
print("B")
def fn(self):
print("B fn")
class C(B,metaclass=A):
def __call__(c,arg):
print("C")
def __init__(self,x):
print("C init",x)
def pr(self):
print
c1= C(10)
def cldec(ccls):
class Inner(ccls):
attr = 1008
return Inner
@cldec
class X:
def f1(self,v1):
print("f1")
self.v=v1
def f2(self):
print(self.v)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 22:24:10 2017
@author: parallels
"""
class Account:
numCreated = 0
def __init__(self, initial):
self.__balance = initial
self.list = [1,2,3]
Account.numCreated += 1
self.__name="Avi"
def deposit(self, amt):
self.__balance = self.__balance + amt
self.list+=[self.__balance]
def withdraw(self,amt):
self.__balance = self.__balance - amt
def getbalance(s):
return s.__balance
def getlist(self):
return self.list
def __str__(self):
return "bal:" + str(self.__balance)
@property
def owner(self):
return self.__name
@owner.setter
def owner(self,value):
self.__name = value
# @owner.deleter
# def owner(self):
# print "del"
# self.__name = None
# @classmethod
# def shownum(cls):
# cls.aaa=20
# print cls.numCreated
# @classmethod
# def shownum3(cls):
# return cls.aaa
# @staticmethod
# def shownum2():
# print Account.numCreated
a = Account(9)
Account.numCreated +=1
print Account.numCreated
print a
#del a.owner
print a.owner
a.deposit(10000)
#Account.shownum()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
# An enumeration type:
class Outcome:
def __init__(self, value, name):
self.value = value
self.name = name
def __str__(self):
return self.name
def __eq__(self, other):
return self.value == other.value
Outcome.WIN = Outcome(0, "win")
Outcome.LOSE = Outcome(1, "lose")
Outcome.DRAW = Outcome(2, "draw")
class Item(object):
def __str__(self):
return self.__class__.__name__
class Paper(Item):
def compete(self, item):
return item.evalPaper(self)
def evalPaper(self, item):
return Outcome.DRAW
def evalScissors(self, item):
return Outcome.WIN
def evalRock(self, item):
return Outcome.LOSE
class Scissors(Item):
def compete(self, item):
return item.evalScissors(self)
def evalPaper(self, item):
return Outcome.LOSE
def evalScissors(self, item):
return Outcome.DRAW
def evalRock(self, item):
return Outcome.WIN
class Rock(Item):
def compete(self, item):
return item.evalRock(self)
def evalPaper(self, item):
return Outcome.WIN
def evalScissors(self, item):
return Outcome.LOSE
def evalRock(self, item):
return Outcome.DRAW
def match(item1, item2):
print("%s <--> %s : %s" % (item1, item2, item1.compete(item2)))
def itemPairGen(n):
# Create a list of instances of all Items:
Items = Item.__subclasses__()
for i in range(n):
yield (random.choice(Items)(), random.choice(Items)())
for item1, item2 in itemPairGen(20):
match(item1, item2)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
class Account(object):
def __init__(self, initial):
self._balance = initial
def deposit(self, amt):
self._balance = self._balance + amt
def withdraw(self,amt):
self._balance = self._balance - amt
def getbalance(s):
return s._balance
def __str__(self):
return "Balance:" + str(self._balance)
class Checking(Account):
def __init__(self):
super(Checking,self).__init__(0)
# def __str__(self):
# return "Balance:" + str(self._balance)
class Bank(object):
def __init__(self):
self._accounts = []
def __len__(self):
return len(self._accounts)
def __getitem__(self,key):
return self._accounts[key]
def __setitem__(self,key,value):
self._accounts[key] = value
def __delitem__(self,key):
del self._accounts[key]
def __contains__(self,item):
return item in self._accounts
def __iter__(self):
for a in self._accounts:
yield a.getbalance()
def Add(self,account):
self._accounts.append(account)
##############################################################3
class Person(object):
def __init__(self,first,last):
self._name = "{} {}".format(first,last)
class Employee(Person):
def introduce(self):
print("Hi! My name is {}".format(self._name))
e = Employee("eli","cohen")
e.introduce()
##################################################################3
d = Checking()
print (d)
b = Bank()
b.Add(Account(1000))
b.Add(d)
b.Add(Account(3000))
print (len(b))
print ( b[0].getbalance())
b[0].deposit(1000)
print (b[0].getbalance())
del b[0]
print (len(b))
print (b[1].getbalance())
for a in b:
print( a)
print (d in b)
|
import copy
class Country(object):
index = {'name':0,'population':1,'capital':2,'citypop':3,'continent':4,
'ind_date':5,'currency':6,'religion':7,'language':8}
# Insert your code here
# 1a) Implement a constructor
def __init__(self, row):
self.__attr = row.split(',')
# 1e) Added to support + and -
self.__attr[Country.index['population']] = \
int(self.__attr[Country.index['population']])
# 1b) Implement a print method
def printit(self):
#print self.__attr[Country.index['name']]
return self.name
# 1c) Overloaded stringification
def __str__(self):
return self.__attr[Country.index['name']]
# Getter methods
# 1d) Implement a getter method for country name
@property
def name(self):
return self.__attr[Country.index['name']]
@property
def population(self):
return int(self.__attr[Country.index['population']])
# 1e) Overloaded + and -
def __add__(self,amount):
retn = copy.deepcopy(self)
retn.__attr[Country.index['population']] += amount
return retn
def __sub__(self,amount):
retn = copy.deepcopy(self)
retn.__attr[Country.index['population']] -= amount
return retn
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu May 11 13:40:33 2017
@author: parallels
"""
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
# Multiplier of 3
times3 = make_multiplier_of(3)
# Multiplier of 5
times5 = make_multiplier_of(5)
# Output: 27
print(times3(9))
# Output: 15
print(times5(3))
# Output: 30
print(times5(times3(2)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.