text stringlengths 37 1.41M |
|---|
class student:
def set id(self,id):
self.id=id
def getid(self):
return self.id
def set Name(self,Name):
self.Name=Name
def get Name(self):
return self.Name
s=student()
s.setid(123)
s.setName("Ashish")
print(s.getid())
print(s.getName()) |
class countdown:
def __init__(self):
self.a = 1
def final(self):
print(type(self.a))
c = countdown()
c.final()
c.final()
#what's the output
def swap(a,b):
b,a = a,b
a,b = 2,203
swap(a,b)
print(a-b) |
#Write a Python program to count the number of occurrence of a specific character in a string.
s = "this is a cir"
print(s.count("i"))
#Write a Python program to check whether a file path is a file or a directory.
import os
path = "abc.txt"
if os.path.isdir(path):
print("\nIT is a directory")
elif os.path.isfile(path):
print("\n It is a normal file")
else:
print("it is a special file(socket,FIFo,device file)")
print()
#Write a Python program to get the ASCII value of a character.
print()
print(ord('A'))
print(ord('@'))
print(ord('h'))
print(ord('S'))
#Write a Python program to get the size of a file.
import os
file_size = os.path.getsize("abc.txt")
print("\nThe size of abc.txt is :",file_size,"Bytes")
print()
#what is output of this code
a = 148
b = a * a + a
print(b % a < b / a)
#Given variables x=30 and y=20, write a Python program to print t "30+20=50"
x = 30
y = 20
print("\n%d+%d=%d" % (x, y, x+y)) #remark
print()
#Write a Python program to perform an action if a condition is true.
n=1
if n==1:
print("\n First day of month")
print()
|
# -*- coding: utf-8 -*-
# Criando minha própria exceção através da classe Exception.
class ValorRepetidoErro(Exception):
def __init__(self, valor):
self.valor = valor
def __str__(self):
return "O valor %i já foi digitado antes." %(self.valor)
lista = []
for i in range(3):
try:
valor = int(input("Digite um valor: "))
if valor not in lista:
lista.append(valor)
else:
raise ValorRepetidoErro(valor) # Chamando a exceção criada passando um valor.
except ValueError: # Exceção do sistema, que verifica se só números foram digitados.
print("Só digite números.")
break
print("A lista digitada foi: ", lista) |
import tkinter as tk
from tkinter import Menu
janela = tk.Tk()
# Método para sair da aplicação.
def _sair():
janela.quit()
janela.destroy()
exit()
# Criando barra de menu e adicionando-a à janela.
barra_menu = Menu(janela) # Barra de menu.
janela.config(menu=barra_menu)
# Criando menus.
# O tearoff serve para remover a linha tracejada que
# aparece por padrão.
menu_arquivo = Menu(barra_menu, tearoff=0)
menu_ajuda = Menu(barra_menu, tearoff=0)
# Adicionando itens aos menus.
menu_arquivo.add_command(label="Novo") # Item.
menu_arquivo.add_separator() # Separador de itens.
menu_arquivo.add_command(label="Sair", command=_sair) # Item.
menu_ajuda.add_command(label="Sobre") # Item
# Adicionando o menus na barra de menus.
barra_menu.add_cascade(label="Arquivo", menu=menu_arquivo) # Menu.
barra_menu.add_cascade(label="Ajuda", menu=menu_ajuda) # Menu.
janela.mainloop() |
# Lendo um arquivo e salvando suas linhas em uma lista.
arquivo = open('arquivo.txt', 'r')
# Lista, onde cada elemento representa uma linha do arquivo.
linhas = arquivo.readlines()
for l in linhas:
print(l)
arquivo.close() |
# coding: utf-8
import os
os.system("clear")
#fila - FIFO
F = ["primeiro","segundo","terceiro","quarto","quinto"]
print("------------------")
print("Fila: ")
print(F)
while len(F) > 0:
print("Removendo o %s da fila. " %(F[0]))
F.pop(0)
print(F)
#pilha - LIFO
#pilha - LIFO
P = ["primeiro","segundo","terceiro","quarto","quinto"]
print("------------------")
print("Pilha")
print(P)
while len(P) > 0:
print("Removendo o %s da pilha. " %P[len(P)-1])
P.pop()
print(P)
|
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def info(self):
print(f'Plane brand {self.brand}, {self.model}', end=' ')
class Destroyer(Plane):
def __init__(self, brand, model):
super().__init__(brand, model)
self.can_fire = True
print(f'Airplane {self.brand} {self.model}, can fire = {self.can_fire}')
def fire(self):
return(f'This airplane can fire {self.can_fire}')
class Stelth(Plane):
def __init__(self, brand, model):
super().__init__(brand, model)
self.is_visible = False
def hide(self):
return(f'This airplane {self.brand} {self.model}, can hide anywhere = {self.is_visible}')
class Kukuruznik(Plane):
def __init__(self, brand, model):
super().__init__(brand, model)
self.can_fertilize = True
print(f'This airplane can fertilize {self.can_fertilize}')
def fertilize(self):
return(f'This airplane is good for farms because he can {self.can_fertilize}')
d = Destroyer('FirePlane', 'F-2')
print(d.fire())
s = Stelth('IlonPLane', 'Stelth-1')
print(s.hide())
k = Kukuruznik('PopcornPLane', 'Eagle')
print(k.fertilize()) |
from threading import Thread, Lock
import time
import random
from threading import Condition
buffer = []
lock = Lock()
MAX_NUM = 5
condition = Condition()
class ConsumidorThread(Thread):
def run(self):
global buffer
while True:
condition.acquire() #entrar na região crítica
if not buffer: #se não tiver nada no buffer
print ("Nada no Buffer, consumidor em espera")
condition.wait() #espera até que notify() seja chamado
print ("Produtor adicionou algo ao buffer, e liberou o consumidor")
num = buffer.pop(0) #tira o valor da posição 0
print ("Consumido", num)
condition.notify()
condition.release() #sair da região crítica
time.sleep(5)
class ProdutorThread(Thread):
def run(self):
nums = range(MAX_NUM)
global buffer
while True:
condition.acquire()
if len(buffer) == MAX_NUM:
print ("Buffer cheio, produtor esperando")
condition.wait()
print ("Espaço liberdo, produtor iniciado")
num = random.choice(nums) #pega um valor aleatorio
buffer.append(num) #adiciona ao buffer
print ("Produzido", num)
print (len(buffer))
condition.notify()
condition.release()
time.sleep(2)
ProdutorThread().start()
ConsumidorThread().start()
|
# -*- coding: utf-8 -*-
__author__ = 'vincent'
# property, 负责把一个方法变成属性调用
class Student(object):
# score is a property object, property 是一个内置的装饰器
# 加@property, 把一个get_score方法变成属性
# 只定义getter方法,不定义setter方法就是一个只读属性:
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._height * self._width
# test:
s = Screen()
s.width = 1024
s.height = 768
print(s.resolution)
assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-08-08
# @Last Modified by:
# @Last Modified time:
# @Title : Generate sequence in list and tuple
# '''
values = input("Input sequence of number seprated by comma: ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple) |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to remove an item from a tuple.
# '''
mytuple = (2, 4, 5, 67, 7, 4)
print("Tuple:-",mytuple)
tempTuple = list(mytuple)
tempTuple.pop(3)
print("Tuple after removing single element:-",tuple(tempTuple))
|
# ''""
# @Author: Sanket Bagde
# @Date: 2021-05-08
# @Last Modified by:
# @Last Modified time:Sanket
# @Title : Power of 2 till N
# '''
N = int(input("Enter N value:- "))
if N < 0 or N > 31:
print("Please enter positive value less then 31")
else:
for x in range(N):
print(2**x) |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to create a tuple.
# '''
"""
Description:
created function for as unpack_tuple with argument as x passes through tuple.
Parameter:
used n1, n2, n3, n4 to store the element after its get unpacked from tuple
Return:
Returning addition of all individual elements after unpacked from tuple
"""
def unpack_tuple(x):
n1, n2, n3, n4 = x
return n1 + n2 + n3 + n4
if __name__ == '__main__':
tuplex = 4, 8, 3, 2
print("Basic tuple:-",tuplex)
print("unpack tuple with addition:-",unpack_tuple(tuplex)) |
# ''""
# @Author: Sanket Bagde
# @Date: 2021-09-08
# @Last Modified by:
# @Last Modified time:
# @Title :Write a Python program to sum all the items in a list..
# '''
"""
Description:
created function for as sum_of_list.
Parameter:
declare total as 0 initially and assign values to the num in form of list.
Return:
Returning the value of total through print statement.
"""
def sum_of_list():
total = 0
nums = [2,4,6,8,10]
print("Lists:-",nums)
for x in range(0, len(nums)):
total = total + nums[x]
print("Sum of the elements in the list is:- ", total)
if __name__ == '__main__':
sum_of_list()
|
word=str(input())
a=list(word)
count=0
for i in a:
if i.isnumeric()==True:
count=count+1
print(count) |
#!/usr/bin/python3
# inputs are tensors which are defined as Python lists with dimensions like so:
# [batch, channel, 2-D numpy array]
#
# in some cases, they are expressed as [layer, batch, channel, 2-D numpy array]
import numpy as np
class ANN:
def __init__(self, layers, numChannels, actFunc, beta = 0.9):
np.random.seed (0)
self.N = len (layers)
self.numChannels = numChannels
actFuncs = {"sigmoid": self.sigmoid (beta),
"unit": self.unit () }
self.g = actFuncs[actFunc]
# the following are expressed as [layer][channel][numpy array]
self.weights = []
self.bias = []
for layer in range (len (layers)):
self.weights.append ([None] * numChannels[layer])
self.bias.append ([None] * numChannels[layer])
for layer in range (self.N - 1):
for channel in range (len (self.weights[layer])):
# weights
self.weights[layer][channel] = np.random.rand (layers[layer + 1], layers[layer])
# bias weights
self.bias[layer][channel] = np.random.rand (layers[layer + 1])
# "Input" is in the form of [batch][channel][numpy array]
def forward (self, Input):
# the following are expressed as [layer][batch][channel][numpy array]
self.psi = []
self.y = []
self.delta = []
for layer in range (self.N):
self.psi.append ([])
self.y.append ([])
self.delta.append ([])
for batch in range (len (Input)):
self.psi[layer].append ([])
self.y[layer].append ([])
self.delta[layer].append ([])
for channel in range (self.numChannels[layer]):
self.psi[layer][channel].append ([])
self.y[layer][channel].append ([])
self.delta[layer][channel].append ([])
self.y[0] = Input
for layer in range (self.N - 1):
for batch in range (len (self.y[layer])):
for channel in range (len (self.y[layer][batch])):
lweights = self.weights[layer][channel]
y = self.y[layer][batch][channel]
bias = self.bias[layer][channel]
self.psi[layer][batch][channel] = np.matmul (lweights, y) + bias
psi = self.psi[layer][batch][channel]
self.y[layer + 1][batch][channel] = self.g.activate (psi)
return self.y[self.N - 1]
# "Input" is in the form of [batch, channel, 2-D numpy array]
# "Output" is in the form of [batch, channel, 2-D numpy array]
# "stepsize" is a positive real number specifying the step size used in gradient descent
def back (self, Input, Output, stepsize):
z = self.forward (Input)
# the following are expressed as [batch][channel][numpy array]
diff = []
gamma = []
for batch in range (len (z)):
diff.append ([None])
gamma.append ([None])
for batch in range (len (self.y[self.N - 2])):
for channel in range (len (self.y[self.N - 2][batch])):
diff[batch][channel] = z[batch][channel] - Output[batch][channel]
gamma[batch][channel] = diff[batch][channel] * self.g.dactivate (self.psi[self.N - 2][batch][channel])
for layer in np.arange (self.N - 2, -1, -1):
for batch in range (len (self.y[layer])):
for channel in range (len (self.y[layer][batch])):
lweights = self.weights[layer][channel]
ldelta = self.delta[batch][channel]
# last layer
if (layer == self.N - 2):
dEdw = np.outer (gamma[batch][channel], self.y[layer][batch][channel])
lweights -= stepsize * dEdw
dEdu = gamma[batch][channel]
self.bias[layer][channel] -= stepsize * dEdu
# update delta for the next layer
self.delta[batch][channel] = np.matmul (gamma[batch][channel], lweights)
# all other interior layers
else:
# use the previously calculated delta to update the weights
LHS = np.tile (ldelta, (len (self.y[layer]), 1)).transpose ()
gp = self.g.dactivate (self.psi[layer][batch][channel])
RHS = np.outer (gp, self.y[layer])
dEdw = LHS * RHS
lweights -= stepsize * dEdw
dEdu = ldelta * gp
self.bias[layer] -= stepsize * dEdu
if layer > 0:
# update delta for the next layer
Gp = np.diag (gp)
Gpw = np.matmul (Gp, lweights)
self.delta[batch][channel] = np.matmul (ldelta, Gpw)
Error = 0.0
z = self.forward (Input)
for batch in range (len (self.y[self.N - 2])):
for channel in range (len (self.y[self.N - 2][batch])):
diff[batch][channel] = z[batch][channel] - Output[batch][channel]
Error += 0.5 * np.sum (diff[batch][channel] * diff[batch][channel])
return Error
class unit:
def activate (self, x): return x
def dactivate (self, x): return np.ones (len (x))
class sigmoid:
def __init__ (self, beta):
self.beta = beta
def activate (self, x):
return 1.0 / (1.0 + np.exp (-self.beta * x))
def dactivate (self, x):
sig = self.activate (x)
return self.beta * (1 - sig) * sig
|
import time
from random import randrange
def minimumValue(values):
overallMin = values[0]
for i in values:
smallest = True
for j in values:
if i > j:
smallest = False
if smallest:
overallMin = i
return overallMin
for listSize in range (100, 1001, 100):
values = [randrange(1000) for x in range(listSize)]
start = time.time()
print(minimumValue(values))
end = time.time()
print("size: %d time: %f" % (listSize, end-start)) |
'''
autor : Geovanna Alves Magalhães
data : 17/05/18
'''
nota1 = float(input('Digite sua primeira nota'))
nota2 = float(input('Digite sua segunda nota'))
nota_total = nota1+nota2
print('Sua nota total é ' , nota_total)
media = nota_total / 2
print ('Sua média é ' , media)
if media >= 9.0 and media <= 10.0 :
print('Você tirou A . VOCÊ FOI APROVADO ! ')
elif media >= 7.5 and media <=9.0 :
print('Você tirou B . VOCÊ FOI APROVADO !' )
elif media >=6.0 and media <= 7.5 :
print ('Você tirou C . VOCÊ FOI APROVADO ! ')
elif media >=4.0 and media <=6.0 :
print ('Você tirou D . VOCÊ FOI REPROVADO :(')
elif media <= 4.0 :
print ('Você tirou E . VOCÊ FOI REPROVADO :( ' )
|
"""
File: boggle.py
Name: Wilson Wang
----------------------------------------
This program recursively finds all the vocabs for the word input by user in boggle.
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
# global various
result = [] # a list to storage boggle answers
def main():
"""
This program let user enter 4 strings of words and use those string to start boggle game.
"""
lst = []
for i in range(4):
row = input(str(i+1)+' row of letters: ').lower()
if not check_form(row):
print("Illegal input")
return
new_row = simplify(row)
lst.append(new_row)
dictionary = read_dictionary()
# These double for-loop should target the coordinate of character and start recursion
for i in range(4):
for j in range(4):
find_ans(lst, [(i, j)], dictionary, '', (i, j))
print('There are '+str(len(result))+' words in total.')
def find_ans(lst, index, d, chosen, coordinate):
"""
This function should start back tracking answer in boggle. During back tracking, the function must follow
"neighbor" rule which means the back tracking could only go left, right, top, down, up-right, up-left,down-right and
down-left.
:param lst: list, storage all the strings which users enter in
:param index: list, storage the coordinate in boggle
:param d: list, storage all the vocab in dictionary
:param chosen: string, a string translate from index as the answer of boggle
:param coordinate: tuple, the coordinate of character at boggle
:return: none
"""
global result
chosen = ''
# get characters from list
for tuple in index:
chosen += lst[tuple[0]][tuple[1]]
# base_case
if len(chosen) >= 4 and chosen in d and chosen not in result:
print(f"Found \"{chosen}\" ")
result.append(chosen)
# recursive_case
# These double for-loops should limit back tracking in 'neighbor' rule
for i in range(-1, 2, 1):
for j in range(-1, 2, 1):
# check the coordinate of tuple is in area
if 0 <= coordinate[0]+i < 4 and 0 <= coordinate[1]+j < 4:
# check the coordinate is in list and found in dictionary
if (coordinate[0]+i, coordinate[1]+j) not in index and has_prefix(index, d, lst):
# if has_prefix(index, d, lst):
# choose
index.append((coordinate[0]+i, coordinate[1]+j))
# explore
find_ans(lst, index, d, chosen, (coordinate[0]+i, coordinate[1]+j))
# un-choose
index.pop()
def has_prefix(sub_s, dictionary, lst):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
check_word = ''
# translate index into string
for tuple in sub_s:
check_word += lst[tuple[0]][tuple[1]]
# get every vocab from dictionary
for vocab in dictionary:
# check the sub_s in vocab
if vocab.startswith(check_word):
return True
return False
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
with open(FILE, 'r') as f:
dictionary = []
# separate file into lines
for line in f:
# separate line into list
word_list = line.split()
# separate vocab in list
for word in word_list:
dictionary.append(word)
return dictionary
def check_form(row):
"""
This function check the string that user entered is regulated.
:param row: string, a string of words
:return: boolean
"""
# check the length of row is regulated
if len(row) < 6 or len(row) > 7:
return False
else:
for i in range(len(row)):
ch = row[i]
# check the user enter space between every character
if i % 2 == 1:
if ch != ' ':
return False
else:
if not ch.isalpha():
return False
return True
def simplify(row):
"""
This function simplify a string which has few space between characters.
:param row: string, a string of words
:return: ans, a string without space between characters
"""
ans = ''
for ch in row:
if ch.isalpha():
ans += ch
return ans
if __name__ == '__main__':
main()
|
"""
File: caesar.py
name: Wilson
------------------------------
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
# This constant shows the original order of alphabetic sequence
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
"""
This program demonstrates the idea of caesar cipher.
Users will be asked to input a number to produce shifted
ALPHABET as the cipher table. After that, any strings typed
in will be encrypted.
"""
secret = int(input('Secret number: '))
string = input("What's the ciphered string? " )
# This step insure string is made by capital letters
up_string = string.upper()
new_alphabet = build_new(secret)
deciphered = find_old(up_string,new_alphabet)
print('The deciphered string is: ' + str(deciphered))
def build_new(secret):
"""
This function will make a new line of alphabet, the first character should be choose by ' secret'
:param secret: int, secret >= 0
:return: ans: str
"""
new = ''
# when secret = 0, this step should skip
if secret >= 1:
# This step from a new line of alphabet , and the first character determined by 'secret'
for i in range(secret):
ch = ALPHABET[i+len(ALPHABET)-secret]
new+=ch
# This step should finish the rest of line of alphabet
for i in range(len(ALPHABET)-secret):
ch = ALPHABET[i]
new+=ch
return new
def find_old(up_string,new_alphabet):
"""
This function should use each character of 'up_string' to finds the location at 'new_alphabet' and encrypts the
answer from 'Alphabet'
:param up_string: str, The string that user type for decipher
:param new_alphabet: str, the rearrange alphabet string, which decided by SECRET
:return: ans: str, The string after deciphered
"""
ans=''
# This step should use both new_alphabet and Alphabet to find the answer
for i in range(len(up_string)):
ch = up_string[i]
if ch.isalpha():
# use each character to find the number at new_alphabet and use the number to find the character in Alphabet
ans += ALPHABET[new_alphabet.find(ch)]
else:
ans += ch
return ans
##### DO NOT EDIT THE CODE BELOW THIS LINE #####
if __name__ == '__main__':
main()
|
"""
File: quadratic_solver.py
Name: Wilson Wang
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math
def main():
"""
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match with 3 conditions, which have different number of root .
"""
print('stanCode Quadratic Solver')
a = int(input('Enter a:'))
b = int(input('Enter b:'))
c = int(input('Enter c:'))
if b*b - 4*a*c > 0:
# This equation should compute the roots of ax^2 + bx + c = 0
d = math.sqrt(b ** 2 - 4 * a * c)
# answer1 and answer3 are for the condition of 2 roots (d>0)
answer1 = (-b + d) / (2 * a)
answer3 = (-b - d) / (2 * a)
# this code should show two roots when d > 0
print('two roots: '+str(answer1)+' , '+str(answer3))
elif b*b - 4*a*c == 0:
# answer2 is for the condition of 1 root(d=0)
answer2 = -b / (2 * a)
# this code should show one roots when d = 0
print('one roots: '+str(answer2))
else:
# this condition shoe when d < 0
print('no real roots')
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == "__main__":
main()
|
# Convert Input values to SI's (Standard units)
#
import math
# Other Functions for this Module
def KTS_to_MS(x): return x * .514447
def MPH_to_MS(x): return x * .44704
def KPH_to_MS(x): return x * .2777778
def FT_to_M(x): return x * .3048
def FAT_to_M(x): return x * 1.829
def MTR_to_M(x): return x * 1
def NMI_to_M(x): return x * 1852
def MI_to_M(x): return x * 1609.344
def KM_to_M(x): return x * 1000
def DEG_to_RAD(x): return math.radians(x)
def DegF_to_Kelvin(x): return ((x - 32) * 5 / 9) + 273.15
def DegC_to_Kelvin(x): return (x + 273.15)
def HrMin_to_Sec(time_str):
h, m = time_str.split(':')
return int(h) * 3600 + int(m) * 60
def MinSec_to_Sec(time_str):
m, s = time_str.split(':')
return int(m) * 60 + int(s)
#
newValue = ""
# now to the main code
class sigUnits:
def __init__(self, dataValue, dataUnits):
sigUnits.newValue = dataValue
# Convert Knots _to_ m/s
if dataUnits == "KTS":
sigUnits.newValue = KTS_to_MS(dataValue)
# Convert MPH _to_ m/s
elif dataUnits == "MPH":
sigUnits.newValue = MPH_to_MS(dataValue)
# Convert KPH _to_ m/s
elif dataUnits == "KPH":
sigUnits.newValue = KPH_to_MS(dataValue)
# Convert Feet _to_ Meters
elif dataUnits == "FT":
sigUnits.newValue = FT_to_M(dataValue)
# Convert Fathom _to_ Meters
elif dataUnits == "FAT":
sigUnits.newValue = FAT_to_M(dataValue)
# Convert Nautical miles to Meters
elif dataUnits == "NMI":
sigUnits.newValue = NMI_to_M(dataValue)
# Convert Staute Miles _to_ Meters
elif dataUnits == "MI":
sigUnits.newValue = MI_to_M(dataValue)
# Convert Kilometers _to_ Meters
elif dataUnits == "KM":
sigUnits.newValue = KM_to_M(dataValue)
# Convert Degrees _to_ Radians
elif dataUnits == "DEG":
sigUnits.newValue = DEG_to_RAD(dataValue)
# Convert Deg F _to_ Kelvin
elif dataUnits == "`F":
sigUnits.newValue = DegF_to_Kelvin(dataValue)
# Convert Deg C _to_ Kelvin
elif dataUnits == "`C":
sigUnits.newValue = DegC_to_Kelvin(dataValue)
# Convert Meter to Meter
elif dataUnits == "MTR":
sigUnits.newValue = MTR_to_M(dataValue)
# Convert Hours:Minutes to Seconds
elif dataUnits == "H:M":
sigUnits.newValue = HrMin_to_Sec(dataValue)
# Convert Minute:Seconds to Seconds
elif dataUnits == "M:S":
sigUnits.newValue = MinSec_to_Sec(dataValue)
else:
sigUnits.newValue = dataValue
# print("Conversion Not Found for:", dataUnits)
# and return the adjusted values |
class Texts(object):
def intro():
print(
"¡Welcome to Pyshion! \n\nIn this application you can find the complementary, splitcomplementary and triad colors \n"
"By using the following syntax: \n"
"\tcolor\n"
"\tcomplementary color\n"
"\tsplitcomplements color\n"
"\ttriad color\n"
"These commands will return the possible combinations. For more information type help.")
def help():
print("Pyshion supports colors from the primary, secondary and tertiary colors\n"
"this include the following colors:"
"\n\tred"
"\tred-orange\n"
"\torange"
"\tyellow-orange\n"
"\tyellow"
"\tyellow-green\n"
"\tgreen"
"\tblue-green\n"
"\tblue"
"\tblue-violet\n"
"\tviolet"
"\tred-violet\n"
"\nYou can find the complementary, splitcomplementary and triad of any of these colors."
"\nTo find these, you just have to type in the desire action followed by the color"
"\n\t Examples:"
"\n\t >>>complementary red"
"\n\t Output: green"
"\n\t >>>splitcomplements orange"
"\n\t Output: blue-green and blue-violet"
"\n\t >>>triad blue"
"\n\t Output: red and yellow"
"\n\t >>>red"
"\n\t Output: the complementary is green"
"\n\t the splitcomplements are yellow-green and blue-green"
"\n\t the triads are blue and yellow"
"\n\n ¡Enjoy making combinations with Pyshion!"
) |
#This code is an edited version of an example referenced from
#(https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/planetary_motion_three_body_problem.ipynb), which discussed different constant step size ordinary differential equation (ODE) solvers (such as Forward Euler, Explicit Trapezoid, Midpoint Rule and fourth order Runge-Kutta) applied on a two dimensional one body problem. In this example we will use an adaptive step size ODE solver (Embedded Runge-Kutta pair) to solve two and three body problems. A brief motivation for the adaptive step size is explained in [Adaptive Runge-Kutta Methods](https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/adaptive_runge_kutta_methods.ipynb).
# Import libraries
import numpy as np
import time
# ### Equations of motion
#
# The gravitational pull between two objects is under classical conditions given by Newton's law of gravitation,
#
# $$
# \vec{F}_{21}(t)=\vec{F}_{12}(t) = -\frac{Gm_1m_2}{{\vec{r_{12}}(t)}^3}\vec r_{12},
# $$
#
# where $m_1$ and $m_2$ are the masses of the two objects, $r$ is the distance between them and $G\approx 6.67\times 10^{-11} \,\text{m}^3/ \text{kg}\,\text{s}^2$ is the gravitational constant. Newton's law holds if it is assumed that the masses of the objects are isotropically distributed.
#
# Consider a three body problem with three objects given by masses $m_1$, $m_2$ and $m_3$. By the principle of superposition, the gravitational pull on an object will be the sum of the gravitational pull of all the other objects $F_1 = F_{12} + F_{13}$. Thus, the equations of motion (EoM) of say $m_1$ is given by
#
# $$
# \ddot{\vec{r}}_1(t) = -\frac{Gm_2}{\left[\vec{r}_{2}(t)-\vec{r}_{1}(t)\right]^3}\left[\vec{r}_{2}(t)-\vec{r}_{1}(t)\right]-\frac{Gm_3}{\left[\vec{r}_{3}(t)-\vec{r}_{1}(t)\right]^3}\left[\vec{r}_{3}(t)-\vec{r}_{1}(t)\right],
# $$
#
# $$
# \dot{\vec{r}}_1(t)=\vec{v}_1.
# $$
#
# The EoM in this problem is a set of ODEs. By giving two initial conditions, e.g. the starting velocity and position, we can reduce the problem to two ODEs, where the next step of the first ODE depends on the previous step of the second ODE. The right hand side (RHS) of the EoM can be described by the following function:
# In[2]:
def RHS(t, y):
"""Calculate the RHS of the EoM, as described above.
Parameters:
y: array. Vector of length 12 holding the current position and velocity of the three objects
in the following manner: y = [x1, y2, x2, y2, x3, y3, vx1, vy1, vx2, vy2, vx3, vy3].
Returns:
z: array. Vector of length 12 holding the derivative of the current position and velocity
(the velocity and acceleration) of the three object in the following manner:
z = [vx1, vy1, vx2, vy2, vx3, vy3, ax1, ay1, ax2, ay2, ax3, ay3].
"""
# Allocate a vector to hold the output values
z = np.zeros(12)
# Define initial velocities and distances between objects
z[:6] = [y[6], y[7], y[8], y[9], y[10], y[11]]
r21 = ((y[2] - y[0])**2.0 + (y[3] - y[1])**2.0)**0.5
r31 = ((y[4] - y[0])**2.0 + (y[5] - y[1])**2.0)**0.5
r32 = ((y[4] - y[2])**2.0 + (y[5] - y[3])**2.0)**0.5
# Pairwise forces
Fx21 = G*m2*m1*(y[2] - y[0])/r21**3.0
Fy21 = G*m2*m1*(y[3] - y[1])/r21**3.0
Fx31 = G*m3*m1*(y[4] - y[0])/r31**3.0
Fy31 = G*m3*m1*(y[5] - y[1])/r31**3.0
Fx32 = G*m3*m2*(y[4] - y[2])/r32**3.0
Fy32 = G*m3*m2*(y[5] - y[3])/r32**3.0
# Accelerations
z[6] = (Fx21 + Fx31)/m1
z[7] = (Fy21 + Fy31)/m1
z[8] = (-Fx21 + Fx32)/m2
z[9] = (-Fy21 + Fy32)/m2
z[10] = (-Fx31 - Fx32)/m3
z[11] = (-Fy31 - Fy32)/m3
return z
# Furthermore, in this setup the absolute angular momentum $\vec L = \vec R\times m\vec v$ stays constant, and can be calculated by:
def angularMomentum(y):
"""Calculate absolute angular momentum of the three body system.
Parameters:
y: array. Vector of length 12 holding the current position and velocity of the three objects
in the following manner: y = [x1, y2, x2, y2, x3, y3, vx1, vy1, vx2, vy2, vx3, vy3].
Returns:
L1, L2, L3: array. Total absolute angular momentum of the system.
"""
L1 = m1*(y[0]*y[7] - y[1]*y[6])
L2 = m2*(y[2]*y[9] - y[3]*y[8])
L3 = m3*(y[4]*y[11] - y[5]*y[10])
return [L1, L2, L3]
# ### Embedded Runge-Kutta pair
#
# We now implement the embedded Runge-Kutta pair (often called an adaptive Runge-Kutta method) to solve the EoM. In short, it is a scheme that uses two different Runge-Kutta methods of different order to get an estimate of the local truncation error. Thus, it is possible to more or less decide what accuracy we want the solution to have by adjusting the step size for each iteration. Another advantage of the adaptive step size method is that we achieve better accuracy where it is needed and lower accuracy where it is not (an example will follow). However, these methods may become more computationally demanding, and hence won't improve our implementation in every case.
#
# The implementation can also be done with a constant step size method, which is done in the animation section below.
#
# We are going to use the Runge-Kutta-Fehlberg order 4 / order 5 embedded pair (RKF45) as described in [Adaptive Runge-Kutta Methods](https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/adaptive_runge_kutta_methods.ipynb):
# In[5]:
def ode45(f,t,y,h):
"""Calculate next step of an initial value problem (IVP) of an ODE with a RHS described
by the RHS function with an order 4 approx. and an order 5 approx.
Parameters:
t: float. Current time.
y: float. Current step (position).
h: float. Step-length.
Returns:
q: float. Order 2 approx.
w: float. Order 3 approx.
"""
s1 = f(t, y)
s2 = f(t + h/4.0, y + h*s1/4.0)
s3 = f(t + 3.0*h/8.0, y + 3.0*h*s1/32.0 + 9.0*h*s2/32.0)
s4 = f(t + 12.0*h/13.0, y + 1932.0*h*s1/2197.0 - 7200.0*h*s2/2197.0 + 7296.0*h*s3/2197.0)
s5 = f(t + h, y + 439.0*h*s1/216.0 - 8.0*h*s2 + 3680.0*h*s3/513.0 - 845.0*h*s4/4104.0)
s6 = f(t + h/2.0, y - 8.0*h*s1/27.0 + 2*h*s2 - 3544.0*h*s3/2565 + 1859.0*h*s4/4104.0 - 11.0*h*s5/40.0)
w = y + h*(25.0*s1/216.0 + 1408.0*s3/2565.0 + 2197.0*s4/4104.0 - s5/5.0)
q = y + h*(16.0*s1/135.0 + 6656.0*s3/12825.0 + 28561.0*s4/56430.0 - 9.0*s5/50.0 + 2.0*s6/55.0)
return w, q
# To get some basis for comparison we will also use the Ordinary (fourth order) Runge-Kutta method, as described in [Runge Kutta Method](https://nbviewer.jupyter.org/urls/www.numfys.net/media/notebooks/runge_kutta_method.ipynb) (this method will be used to make animations):
# In[6]:
def rk4step(f, t, y, h):
"""Calculate next step of an IVP of an ODE with a RHS described by the RHS function with RK4.
Parameters:
f: function. Right hand side of the ODE.
t: float. Current time.
y: float. Current step (position).
h: float. Step-length.
Returns:
q: float. Order 2 approx.
w: float. Order 3 approx.
"""
s1 = f(t, y)
s2 = f(t + h/2.0, y + h*s1/2.0)
s3 = f(t + h/2.0, y + h*s2/2.0)
s4 = f(t + h, y + h*s3)
return y + h/6.0*(s1 + 2.0*s2 + 2.0*s3 + s4)
def threeBody(M1,M2,M3,x1,y1,x2,y2,x3,y3,vx1,vy1,vx2,vy2,vx3,vy3):
# ### Computations
#
# Time to put it all together and plot the results. Initially, this solution describes a three body problem, but by choosing one of the masses equal to zero, the system will behave as if it is a two body system.
#
# To start with, we will choose initial conditions and set global constants:
# Set gravitaional constant and masses.
# The gravitaional constant is set to 1 for simplicity.
global G; G = 1.
global m1; m1 = M1
global m2; m2 = M2
global m3; m3 = M3
# Period of calculations
T = 5
# Tolerance
TOL = 0.00001
# Maximum number of steps
maxi = 1000
# "Protector-constant" for small w
theta = 0.001
# Number of steps (RK4)
n = 1000
# Different initial conditions to try out, on the form
# y = [x1, y2, x2, y2, x3, y3, vx1, vy1, vx2, vy2, vx3, vy3]
z0 = [x1, y1, x2, y2, x3, y3, vx1, vy1, vx2, vy2, vx3, vy3]
# z0 = [2., 2., 0., 0., -2., -2., 0.2, -0.2, 0., 0., -0.2, 0.2]
# z0 = [-0.970, 0.243, 0.970, -0.243, 0., 0., -0.466, -0.433, -0.466, -0.433, 2*0.466, 2*0.433]
# z0 = [2., 0., -2., 0., 0., 0., 0., -0.6, -0.6, 0., 0., 0.]
#z0 = [1., 0.000001, -1., 0., 0., 0., 0., -0.4, 0., 0.4, 0., 0.]
# In[10]:
# Set constant step size
h = T/n
# Set initial time
t = 0.
# Allocate matrices and fill with initial conditions
Z2 = np.zeros((12, n+1))
Z2[:, 0] = z0
tic = time.time()
for i in range(0, n):
Z2[:, i+1] = rk4step(RHS, t, Z2[:, i], h)
t += h
print("%.5f s, run time of RK4 method, with %i steps."% (time.time() - tic, n))
# Position
res = Z2[:,-1]
return res
|
# Method 1
def feb(n):
if n == 1 or n == 2:
result = 1
else:
result = feb(n-1) + feb(n-2)
return result
# Method 2
def feb2(n):
memo = [None] * (n+1)
return feb_memo(n,memo)
def feb_memo(n,memo):
if memo[n] is not None:
return memo[n]
if n == 1 or n == 2:
result = 1
else:
result = feb_memo(n-1,memo) + feb_memo(n-2,memo)
memo[n] = result
return result
# Method 3
def bottom_up(n):
if n == 1 or n == 2:
return 1
memo = [None] * (n+1)
memo[1] = 1
memo[2] = 1
for i in range(3,n+1):
memo[i] = memo[i-1] + memo[i-2]
return memo[n] |
"""
set method
add()
clear()
copy() - return a copy of set
implement - to work it out, to figure it out, to write the detail
"""
# copy()
A = {1,2,3,4,5}
# copy A to B
B = A.copy()
print(B)
# our solution of copy
C = set()
for i in A:
print(i)
C.add(i)
print(C)
print(C is A)
# upgrade our code
def mycopy(A):
C = set()
for i in A:
print(i)
C.add(i)
return C
D = mycopy(A)
print("D",D)
|
"""
start the game, the entrance of the game
init() - initializing
loadImage() - load background image
loadSound() - load background music
loadAcctInfo() - load user's account information
start()
user selects a level
sys loads level data and all resources (import load)
user plays game
user select exit or continue
if continue, then repeat
else exit
"""
import py201221a_python2_chen.day01_201221.game_v1_2.level.load as gmlvLoad
import py201221a_python2_chen.day01_201221.game_v1_2.level.over as gmlvOver
import py201221a_python2_chen.day01_201221.game_v1_2.image.open as imgOpen
import py201221a_python2_chen.day01_201221.game_v1_2.image.change as imgDisplay
import py201221a_python2_chen.day01_201221.game_v1_2.sound.load as sndLoad
import py201221a_python2_chen.day01_201221.game_v1_2.sound.play as sndPlay
import time
def init():
print("Starting...")
def loadImage(image_name):
print(f"load bg image {image_name}")
imgOpen.open_img(image_name)
imgDisplay.display_img(image_name)
def loadSound(sound_name):
print(f"load bg music {sound_name}")
sndLoad.load_snd(sound_name)
sndPlay.play_snd(sound_name)
def loadAcctInfo(account_info):
print(f"load account info {account_info}")
def start():
"""
:return:
"""
while True:
# levelid = '1-1'
print("\nPlease choose a level:", end="")
levelid = input()
# load level data and resources
gmlvLoad.loadLevel(levelid, )
# user starts to play game
print(f"user starts to play")
for i in range(3):
print(i+1)
time.sleep(1)
print(f"user stops playing\n")
# 1. closeLevel
gmlvOver.closeLevel(levelid,account_info)
# exit ?
print("\nDo you want to continue? [y|n]")
# if user press 'y', then continue
# else exit
tocontinue = input()
# if toexit == 'y':
# continue
# else:
# break
if tocontinue != 'y':
break
# main program
print("=====================")
print("=== My Funny Game ===")
print("=== Ver 1.0 ===")
print("=====================")
print("\n\n")
init()
bgImg = "bg-img.jpg"
loadImage(bgImg)
bgMusic = "bg-music.mp3"
loadSound(bgMusic)
account_info = "acct-info"
loadAcctInfo(account_info)
print("\nGame started.")
start()
gmlvOver.gameover(bgImg,bgMusic,account_info)
# gmlvOver.gameover()
# 3. test |
"""
part 2
question 2
"""
"""
function: ok 5/5
structure: ok 1.25/1.25
convention: ok 1.25/1.25
comment: ok 1.25/1.25
user-friendly: failed to use exception 0.75/1.25
subtotal: 9.5
"""
import os
def directory(dir, level=1):
for i in os.listdir(dir):
print(" "*level, i)
if os.path.isdir(dir+os.sep+i):
level += 1
directory(dir+os.sep+i, level)
level -= 1
return directory
dir_to_list_path = input('please enter the absolute path of the directory:')
directory(dir_to_list_path) |
"""
Quiz 5
"""
# question 6.2
# list1 = [1,2,3,4,5,6]
# print(list1[0], list1[5])
# question 6.3
# list1[3] = 999
# print(list1)
# question 6.4
# tuple1 = (21,31,41,51,61,17)
# print(tuple1[0], tuple1[5])
# question 6.5
# a tuple is unchangeable
# question 6.6
# set1 = {1,1,2,2,3,3}
# print(set1)
# question 6.7
# dict1 = {
# "JAN": "January",
# "FEB": "February"
# }
# print(dict1)
|
"""
positional argument
"""
print("Hello {0}, your balance is {1}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:9f}".format("Adam",230.2346))
print("Hello {0}, your balance is {1:9.3f}".format("Adam",230.2346))
|
# Issa - me
# copy()
A = {1, 2, 3, 4, 5}
# copy A to B
B = A.copy()
print(B)
# Another way
a = {2, 3, 1, 6, 2, 9, 4}
b = a
print(b, a)
|
"""
Password v3
Guang Zhu Cui
2020-06-21
v3. Encrypting Password
For security reasons, the password should not directly be persisted into databases in original form.
It is recommended that every character should get right shifted for 3 steps.
For example,
a -> d, b -> e, c -> f, …, 0 -> 3
print out the encrypted password
then decrypt the password and print it out to compare it with the original one
"""
def encrypted(password):
"""
todo
:param password:
:return: the encrypted password as a string
"""
encrpyted = ''
for i in password:
# print(chr(ord(i) + 3))
encrpyted += chr(ord(i) + 3)
return encrpyted
def decrypted(encrpyted_password):
decrypted = ''
for i in encrpyted_password:
# print(chr(ord(i) - 3))
decrypted += chr(ord(i) - 3)
return decrypted
# set a password for test
password = 'RETRE_BOSS1'
print('the password is:', password)
print('========= encrypted password ========')
decrypt_password = encrypted(password)
print('========= decrypted password ========')
# decrypt_password = 'UHWUHbERVV4'
original_password = decrypted(decrypt_password)
print(original_password)
|
"""
encrypting a password
decrypting a password
"""
char = '%'
print("original char :",char)
# encrypting
# get ascii number
asc_no = ord(char)
print(asc_no)
print()
asc_no += 3
en_char = chr(asc_no)
print("en_char :",en_char)
# decrypting
pwd_asc_no = ord(en_char)
print(pwd_asc_no)
print()
pwd_asc_no -= 3
de_char = chr(pwd_asc_no)
print("de_char :",de_char)
|
"""
loop
condition at the top
"""
a = 10
b = 5
while a > 0 and b < 15:
print()
|
"""
membership operator
in, not in
"""
# case 1. list
list1 = [1,2,3,4,5,6,7]
print(8 in list1)
print(8 not in list1)
print()
print(3 in list1)
print(3 not in list1)
print()
# case 2. tuple
tuple1 = ('a','b','c','d')
print('b' in tuple1)
print('b' not in tuple1)
print()
print('z' in tuple1)
print('z' not in tuple1)
print()
# case 3. set
set1 = {'pencil','eraser','crayon','sharpie'}
print('eraser' in set1)
print('eraser' not in set1)
print()
print('ruler' in set1)
print('ruler' not in set1)
print()
# case 4. dict
dict1 = {"w":"word", "s":'sentence', "a":"alphabet", "e":"encyclopedia"}
print('slang' in dict1)
print('slang' not in dict1)
print()
print('w' in dict1)
print('w' not in dict1)
print()
print('word' in dict1)
print('word' not in dict1)
|
"""
[Homework]
1. Search and Download an html file
Read it and print out
html - Hypertext Markup Language
render
2. Search and Download a CSV file
Read it and print out
"""
print("Starting load html document...")
try:
file = open("home1.html")
content = file.read()
print(content)
file.close()
except FileNotFoundError as fe:
print(fe)
except IOError as ie:
print(ie)
except Exception as e:
print(e)
else:
print("Done.")
|
"""
set
remove items from a set
discard() - remove a specified item
remove() - remove a specified item
pop() - remove an item randomly
clear() - remove all items
"""
# remove items by discard()
myset1 = {2, 3, 4, 5, 67, 7, 9, 45, 77, 51, 88, 91, 31}
myset1.discard(88)
print(myset1)
# myset1.discard()
# print(myset1)
myset1.discard(8888)
print(myset1)
print()
# remove items by remove()
myset1 = {2, 3, 4, 5, 67, 7, 9, 45, 77, 51, 88, 91, 31}
myset1.remove(88)
print(myset1)
# myset1.remove(88) # KeyError: 88
# print(myset1)
if 88 in myset1:
myset1.remove(88)
print(myset1)
# pop() - remove one item arbitrarily
myset1 = {'2', '3', '4', '5'}
myset1.pop()
print(myset1)
myset1.pop()
print(myset1)
# clear() - remove all items
myset1 = {'2', '3', '4', '5'}
myset1.clear()
print(myset1)
|
"""
Homework 10
click button [Click me]
create a Label object
set text
display the Label
"""
from tkinter import *
def response():
"""
create a Label object
set text
display the Label
:return:
"""
print("I was clicked!")
root = Tk()
root.title('Python GUI - Button')
root.geometry('640x480+300+300')
root.config(bg='#ddddff')
btn1 = Button(root, text='Click me', command=response)
btn1.pack()
btn2 = Button(root, text='Exit', command=root.destroy)
btn2.pack()
root.mainloop()
|
"""
solving problem
1,2,3,4,5,6,7,8,9,....,1000
how to calculate the sum of this sequence of number
"""
sum = 0
for i in range(1,1001):
print(i)
sum = sum + i
print(sum) |
"""
string - join()
"""
words = ['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
result = ' '.join(words)
print(result, type(result))
print()
result = ''.join(words)
print(result, type(result))
print()
nums = [str(1),str(2),str(3),str(4),str(5),str(6),str(7)]
result = ','.join(nums)
print(result, type(result))
print()
|
"""
dictionary - iterating
"""
dict1 = {1:1, 2:4, 3:9, 4:16}
print(type(dict1))
for key in dict1:
print(key)
print()
for i in dict1.items():
print(i, type(i))
print(f"{i[0]}:{i[1]}")
# print("{}:{}".format(i[0], i[1]))
print()
print(type(dict1.keys()))
for i in dict1.keys():
print(i)
print()
for i in dict1.values():
print(i)
print() |
"""
[Homework]
1. Write a Python program to get a list, sorted in increasing order
by the last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
2. Write a Python program to remove duplicates from a list.
3. Write a Python program to check a list is empty or not.
4. Write a Python program to clone or copy a list.
5. Write a Python program to find the list of words
that are longer than 3 from a given list of words.
The given words: "The quick brown fox jumps over the lazy dog"
"""
# 1. Question
# list1 = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
# for i in range(0, len(list1)):
# print(list1[i][1])
#
# if i-1 < i:
# list1[i][1] = i
# print(list1)
# Question 2.
print("Question 2.")
list1 = [1, 2, 2, 3, 4, 55, 55]
for i in list1:
n = list1.count(i)
if n >= 2:
list1.remove(i)
print(list1)
# Question 3.
print("Question 3.")
list1 = [1, 2, 2, 3, 4, 55, 55]
list2 = []
list3 = [] # Example, answer is True
if list3 == list2:
print(f"The condition is {True}")
else:
print(f"The condition is {False}")
if list1 == list2:
print(f"The condition is {True}")
else:
print(f"The condition is {False}")
# Question 4.
print("Question 4.")
list1 = [1, 2, 2, 3, 4, 55, 55]
list_copy = list1.copy()
print("This is copy of list1", list_copy)
# Question 5.
print("Question 5.")
sentence = ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
for i in sentence:
if len(i) > 3:
print(i, end=" ")
|
"""
local scope
local variable
"""
def foo():
y = "local"
print("inside foo() y is ",y)
foo()
# NameError: name 'y' is not defined
print(y)
|
"""
tell if a given number n is a prime number
if n is a prime number
print out : Yes, the number of {} is a prime number
else
print out : No, it is not a prime number
"""
# n = 11
#
# 1,2,3,4,5,6,...,11 (n times)
# i = 2 .. (n-1)
#
# 11 % i == 0
# not a prime number
# input a number
number = int(input("Enter a positive integer:"))
if number > 1:
# test if number is a prime number
# [2,3,4,5,6,7,8,...,number-1]
for i in range(2, number):
if number % i == 0:
print("No, the number is not a prime number".format(number))
print("{} can be divided by {} and {}".format(number,i, number//i))
break
else:
print("Yes, the number of {} is a prime number".format(number))
else:
print("Not a valid number")
# n = 59
# n = 113
#
# number = int(input("Enter an integer:"))
#
# a = 1
# print(type(a))
# print(isinstance(a, int) )
#
# # even number
# # a % 2 == 0
#
#
# for i in [1,2,3,4,5,6,7,8]:
# if i == 7:
# break;
|
"""
membership
in, not in
"""
# list membership
list1 = [1,2,3,4,5,6]
item = 4
result = item in list1
print(result)
result2 = item not in list1
print(result2)
# iterating through a list
for i in list1:
print(i)
|
"""
my text
goal: to replace all 'my' with 'your'
1. convert the sentence into a list of words
string.split()
2. iterate over the list
for-loop
if the current word == 'my'
then replace with 'your'
3. combine all words in the list into a string
' '.join(iterable)
4. output
print()
"""
s1 = "this is my demo text this is my demo text this is my demo text " \
"this is my demo text this is my demo text"
# step 1.
wordlist = s1.split()
print(wordlist, type(wordlist))
# step 2.
for word in wordlist:
if word == 'my':
index = wordlist.index(word)
wordlist[index] = 'your'
print(wordlist)
# step 3.
result = ' '.join(wordlist)
# step 4.
print(result)
|
"""
func9. variable arguments
default argument
rule:
positional arguments stay before all the default(keyword) arguments
"""
# def greeting(words="Good morning,", friendname):
# print(words, friendname, "!")
def greeting(friendname, words="Good morning,"):
print(words, friendname, "!")
# friendname1 = "Peter"
# greeting(friendname1)
#
# friendname2 = "Mary"
# greeting(friendname2)
#
# friendname3 = "Jackie"
# greeting(friendname3, "Good evening,")
def greeting(friendname="Marie", words="Good morning,"):
print(words, friendname, "!")
greeting()
friendname2 = "Lily"
greeting(friendname2)
words2 = "Good afternoon,"
greeting(words=words2)
friendname3 = "Jackie"
greeting(friendname3, "Good evening,")
|
"""
fromkeys()
"""
str1 = "python is a good language"
keys = set(str1)
print(keys)
charcount = {}
# charcount = charcount.fromkeys(keys)
charcount = charcount.fromkeys(keys, 0)
print(charcount)
for char in str1:
charcount[char] += 1
print(charcount)
|
"""
lambda, high order function
"""
# input a number
# output a mulplication table (a x 1 to a x 10)
"""
input : 3
3 x 1 = 3
3 x 2 = 6
...
3 x 10 = 30
"""
# return a lambda function
def table(n):
return lambda a : a * n
# input a number
n = int(input("Enter an integer (n>0):"))
# get the function with n
b = table(n)
for i in range(1, 11):
print(f"{n} x {i} = {b(i)}")
|
"""
Quiz 8
"""
# 8.
sentence = input("Enter a sentence:")
if "A" in sentence or "a" in sentence:
print("There is an A")
else:
print("There is no A")
# 9.
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 3, 4, 5]
print(list1 == list2)
print(list1 is list2)
# 10.
# If it is May 22
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
day2 = days.index('Fri')
future = (day2 + 100) % 7
if int(future) == 0:
print(days[0])
elif int(future) == 1:
print(days[1])
elif future == 2:
print(days[2])
elif future == 3:
print(days[3])
elif future == 4:
print(days[4])
elif future == 5:
print(days[5])
else:
print(days[6])
|
"""
sorting in ascending order
numeric : from the smallest to the biggest
string: A->Z a->z
sorting in descending order
"""
"""
a < b < c
ab < ac
acb > abc
ab < abb
"""
# sorting a dictionary
d = {'ca': 2, 'ab': 4, 'bb': 3, 'b': 1, 'aa': 0}
print("before:",d)
# sorted() - built-in
result = sorted(d.items())
# print(result, type(result))
# convert to dictionary
sorted_d = dict(result)
print("after:",sorted_d)
|
"""
a+b*c
user inputs a
user inputs b
user inputs c
to evaluate the expression of a+b*c
print out the result
Please keep in mind:
1. write down your idea
2. translate into your code
3. write a little and test a little
4. input + process + output
"""
"""
print("=== Calculator ===")
print("to evaluate a + b*c ")
# step 1. input
a = input('enter the a: ')
b = input('enter the b: ')
c = input('enter the c: ')
# test input
# print('a =',a)
# print('b =',b)
# print('c =',c)
# step 2. process
a = float(a)
b = float(b)
c = float(c)
result = a + b * c
# test result
# print("result =", result)
# step 3. output
print("The result of the a+b*c is", result)
"""
# lucas
print("a+b*c")
n1 = float(input("Write the first number: "))
n2 = float(input("Write the second number: "))
n3 = float(input("Write the third number: "))
print("Your result is: ",n1 + n2*n3)
# xuanxuan
# a = input('enter the first number: ')
# b = input('enter the second number: ')
# c = input('enter the third number: ')
# print(float(a)+float(b)*float(c))
|
"""
output print
"""
# syntax
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print(1,2,3,4,5)
print(1,2,3,4,5, sep=',')
print(1,2,3,4,5, end='&&')
print(1,2,3,4,5)
# How can we output a 3X4 matrix and make the layout like 3 rows and 4 columns? (1’)
# x x x x
# y y y y
# z z z z
print("The name is {}".format("Peter"))
print("The dimension of the box is width: 30cm, height: 20cm, depth: 10cm") |
"""
module: random
"""
# import math
import random
# get a random number from a specified range
# start, stop
# randrange(start, stop), and the stop number is excluded
for i in range(100):
print(random.randrange(1,6), end=",")
print()
# randint(start, stop)
for i in range(100):
print(random.randint(1,6), end=",")
|
"""
sort()
sort items in a list in ascending order
sort(reverse=True)
descending order
max, min
bubble sorting
quick sort
merge sort
select sort
insertion sort
heap sort
...
"""
odd = [1,2,10,31,5,10,7,9,10,12,14,10]
odd.sort()
print(odd)
odd.sort(reverse=True)
print(odd)
strlist = ['bac','abc','a','aa','bc']
strlist.sort()
print(strlist)
strlist.sort(reverse=True)
print(strlist)
|
"""
open a file in read mode
"""
f = open("file5_mode_r.txt",'r')
# read the whole data in the file
print(f.read())
f.close() |
# data type of set
list1 = [1,2,3,4,5]
print(list1, type(list1))
tuple1 = (1,2,3,4,5)
print(tuple1, type(tuple1))
set1 = {1,2,3,4,5}
print(set1, type(set1))
set2 = {1,1,2,2,3,3}
print(set2)
set3 = {3,2,1}
print(set3)
set4 = {'a',2,5.7}
print(set4)
set5 = {1,2,(1,23)}
print(set5)
# convert list to set
print(set([1,3,2,1,2]))
|
"""
import a module
how to use members of a module
"""
import math
# case1. use constant
a = math.pi
print(a)
# case2. use function
x = 9
b = math.sqrt(x)
print(b)
|
"""
homework: how to prove there is evenly distributed probability of 1-6 with a huge number of trials
f = 1/T
expectation: evenly distributed
"""
import random
for n in range(10000):
res1 = random.randrange(1,7)
# print(res1)
#
# ====================
# dict
frequencies = {}
res1 = str(res1)
for digits in res1:
if digits in frequencies == "1":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
for digits in res1:
if digits in frequencies == "2":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
for digits in res1:
if digits in frequencies == "3":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
for digits in res1:
if digits in frequencies == "4":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
for digits in res1:
if digits in frequencies == "5":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
for digits in res1:
if digits in frequencies == "6":
frequencies[digits] += 1
else:
frequencies[digits] = 1
print("The frequency of '{}' is :{}".format(res1,frequencies))
|
"""
truncate against strings
.3
"""
print("{:.3}".format("caterpillar"))
print("{:.4}".format("caterpillar"))
print("{:.5}".format("caterpillar"))
# and padding
print("|{:5.3}|".format("caterpillar"))
print("|{:>5.3}|".format("caterpillar"))
print("|{:^5.3}|".format("caterpillar"))
|
"""
module: random
"""
import random
# randrange(N)
# res1 = random.randrange(6)
# print(res1)
#
# res1 = random.randrange(6)
# print(res1)
for n in range(10):
res1 = random.randrange(6)
print(res1)
print('======')
# randrange(a, b)
for n in range(20):
res1 = random.randrange(1,7)
print(res1)
print('======')
"""
Date: 2021-01-30
How to prove there is evenly distributed probability of 1-6 with a huge number of trials
Due Date: by the end of next Friday
"""
# randint
# res2 = random.randint(1,6)
# print(res2)
for n in range(20):
res1 = random.randint(1,7)
print(res1)
print('>>>>>>>')
for n in range(20):
res1 = random.randint(9)
print(res1)
print('======')
|
my_dict = {1: 4, 5: 3, 7: 9}
def sort_by_value(my_dict_1):
items = my_dict_1.items()
back_items = [[v[1], v[0]] for v in items]
back_items = sorted(back_items)
print([back_items[i][1] for i in range(0, len(back_items))])
print([v for v in sorted(my_dict_1.values())])
sort_by_value(my_dict)
|
"""
stem1402_python_final_p2_ken
Ken
Commented out is an interactive result inputter.
"""
# results = []
# continues = True
#
# while continues:
# results.append(input("Please write the team's number: "))
# results.append(input("Please write the team's name: "))
# results.append(input("Please write the team's 1st score: "))
# results.append(input("Please write the team's 2nd score: "))
# while continues:
# choice = input("Add another team?:\n"
# "Enter 'yes' if so\n"
# "Enter 'no' if done\n")
# if choice == "yes":
# break
# elif choice == "no":
# continues = False
# else:
# print("Invalid input, try again")
# continue
# Test the inputter above if desired. However, the data is already here.
results = ['1', 'Robert Master', '220', '340',
'2', 'Montreal Sprite', '320', '270',
'3', 'Smart Maker', '115', '405',
'4', 'Nova Robert', '450', '380',
'5', '10 Stars', '100', '330']
def lego_competition_sorter(result):
number_of_teams = len(result)/4
count = 0
deleted = 0
# Remove the lowest score for each team.
for value in range(len(results)):
index = count - deleted
if (count)%4 == 2:
if results[index] <= results[index+1]:
del results[index]
deleted += 1
else:
del results[index+1]
deleted += 1
count += 1
# Create nested lists of teams
list_of_list_teams = []
list_of_teams = []
for count in range(len(results)):
list_of_teams.append(results[count])
if count%3 == 2:
list_of_list_teams.append(list_of_teams)
list_of_teams = []
# Sort nested lists of teams
sorted_list_of_list_of_teams = sorted(list_of_list_teams, key=lambda x: x[2], reverse=True)
return sorted_list_of_list_of_teams
print("Leaderboards of the International FIRST LEGO Robotic Competition")
placement = 1
for detail in lego_competition_sorter(results):
print(f"Place number {placement} is team no. {detail[0]}, {detail[1]}, with a score of {detail[2]}.")
placement += 1 |
"""
datatype
Knowing Datatype, then knowing the operations on the data
Every value in python has a datatype
Numbers (int, float, complex)
"""
# type() - built-in function in python
a = 10
print(a, type(a))
# integer , int
# isinstance() - return True or False
value = 99
print(isinstance(value, int))
print(isinstance(value, float))
# test boolean literal
value = True
print(value, type(value))
print(isinstance(value, bool))
print(isinstance(value, int))
print(value + 1)
print()
# type() get the datatype of a literal or variable (constant)
# isinstance(v, type)
# data types
"""
int
float
bool
str
"""
# GROUP1. Numbers
# case 1. int
h1 = 0x10
print(h1, type(h1))
# case 2. float
f1 = 1.23
print(f1, type(f1))
# case 3. complex
c1 = 1 + 3j
print(c1, type(c1))
# GROUP2. Strings
s1 = 'abc'
print(s1, type(s1))
# GROUP3. Boolean
b1 = True
print(b1, type(b1))
b2 = False
print(b2, type(b2))
# GROUP4. Collection
|
"""
Welcome back to python class!
"""
print()
"""
this is a multiple line comment
this is a multiple line comment
"""
'''
this is a multiple line comment
this is a multiple line comment
'''
# comments - single line comment
# what is comment?
# what is comment for?
# how many types?
# a = 1
# what is variable?
a = 1
# named location
char = 'A' # initialize
print(char)
# update the value
char = 'B'
print(char)
# can we update the value with the number of 123
char = 123
print(char)
|
"""
set symmetric difference
Symmetric Difference of A and B is a set of elements
in both A and B except those that are common in both.
"""
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
result = A ^ B
print(result)
result = A.symmetric_difference(B)
print(result)
result = B.symmetric_difference(A)
print(result)
# A - B | B - A
s1 = A - B
s2 = B - A
result = s1 | s2
print(result)
# A | B - (A & B)
s = A | B
c = A & B
result = s - c
print(result)
|
"""
infinite loop
"""
flag = True
while flag:
print("infinite loop")
# without any condition
flag = False
|
"""
"""
with open('colors.txt') as file:
colors = file.readlines()
print(type(colors))
for color in colors:
color = color.strip()
print(color,end='') |
list2 = [1, 2, 3, 4, 5]
x = 1
for i in list2:
x = x * i
print(x)
|
mydict = {1: 2, 3: 4, 5: 3, 4: 3, 2: 1, 0: 0}
result = mydict.items()
key = lambda item:item[1]
# sorted(iterable, key, reverse)
sorted_result = sorted(result, key=lambda item:item[1], reverse=True)
sorted_dict = dict(sorted_result)
print(sorted_dict) |
"""
2. Python Program to Display the 9X9 multiplication Table
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
*
* *
* * *
* * * *
* * * * *
"""
"""
basic idea: breaking down
pattern a * b = c
1. determine and print out (a,b)
2. layout
"""
for b in range(1,10):
# print(b)
for a in range(1,b+1):
print(a, b, a*b, end="\t\t")
print()
print("======")
# lucas
strtemp = '{}X{}={}\t'
for x in range(1, 10):
for b in range(1, x+1):
print(strtemp.format(b, x, x*b), end='')
print()
|
"""
number formatting with alignment
<
^ centered
>
= forces the sign(+/-) to the leftmost position
"""
# align to right by default
print("|{:5d}|".format(12))
print("|{:6d}|".format(12))
# centered
print("|{:^6d}|".format(12))
# left
print("|{:<6d}|".format(12))
# right
print("|{:>6d}|".format(12))
# leftmost for sign
print("|{:=6d}|".format(-12))
print("|{:=+6d}|".format(+12)) |
"""
Clock: v1
NOTE: root = window
1. Write a GUI program of clock
Requirements:
(Function)
Show current time in the pattern of HH:mm:ss.aaa
i.e.
10:12:45.369
(UI)
Display a title, main area for clock, and footer for the date
Due date: by the end of next Friday
Hint:
import datetime
strftime
review datetime
1. to get current date and time
Sample code:
now = datetime.datetime.now()
print(now)
2. to get string form of the datetime object
show datetime and milli-second
from datetime import datetime
# print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
"""
from time import *
from tkinter import *
from datetime import *
def time_label():
# current_time = strftime('%H: %M: %S %p')
# current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
current_time = datetime.now().strftime('%a %H:%M:%S.%f')[:-3]
clock_label.config(text=current_time)
clock_label.after(10, time_label)
# main program
root = Tk()
root.title("Python GUI - Clock label")
root.geometry("{}x{}+200+240".format(640, 200))
root.configure(bg="crimson")
root.resizable(0, 0)
# label object
clock_label = Label(root,
bg = "goldenrod",
fg = 'white',
height = 3,
width = 20,
font = "Helvetic 20 bold")
clock_label.pack(anchor="center", ipadx=20, ipady=20)
time_label()
root.mainloop()
|
"""
open a file
operate
close
file path(location)
file name
file path + file name
When to omit file path?
under the same directory or path
file path:
1. absolute path
D:\workspace\pycharm201803\stem1401python_student\py200912b_python2m6\day11_201121\file_1.txt
2. relative path
py200912b_python2m6/day11_201121/file_1.txt
"""
# import os
# import os.path
print("Start opening file...")
filepath = "testdir/file_1a.txt"
print("\t"+filepath)
file = open(filepath)
print("Closing...")
file.close()
print("Done.")
|
"""
sorted()
Return a new sorted list from elements in the set(does not sort the set itself).
"""
A = {3,2,4}
result = sorted(A)
print(result, type(result))
#
A = {'b','c','a'}
result = sorted(A)
print(result, type(result))
#
# A = {'b','c','a',2,3,1}
#
# result = sorted(A)
# print(result, type(result)) |
"""
datatype conversion of collection
list(), tuple(), dict(), set()
"""
# case 1. list to tuple
list1 = [1,2,3]
print(list1)
print(tuple(list1))
# case 2. tuple to list
tuple1 = (1,2,3)
print(tuple1)
print(list(tuple1))
# case 3. str (tuple) to list
str1 = 'hello'
print(list(str1))
print(list('hello'))
# case 4. list to dictionary
list2 = [["MON","Monday"],["TUE","Tuesday"]]
print(dict(list2))
# case 5. tuple to dictionary
tuple2 = (("MON","Monday"),("TUE","Tuesday"))
print(dict(tuple2))
print()
# case 6. dictionary to list
dict1 = {'MON': 'Monday', 'TUE': 'Tuesday'}
print(list(dict1))
# case 7. dictionary to tuple
dict1 = {'MON': 'Monday', 'TUE': 'Tuesday'}
print(tuple(dict1))
print()
# case 8. list to set
list1 = [1,2,3]
print(set(list1))
list1 = [1,1,2,2,3,3]
print(set(list1))
print()
# case 9. tuple to set
# case 10. set to list
set1= {1,2,3}
print(list(set1))
# case 11. set to tuple |
"""
"""
"""
matrix = [[11,12,13,14],[21,22,23,24],[31,32,33,34]]
# print(matrix)
for row in matrix:
# print(row)
for col in row:
print(col, end="\t")
print()
print()
matrix = [[11,12,13],[21,22,23],[31,32,33]]
# print(matrix)
for row in matrix:
# print(row)
for col in row:
print(col, end="\t")
print()
"""
def showmatrix(matrix):
for row in matrix:
for col in row:
print(col, end="\t")
print()
# input data
mtr1 = [[11,12,13,14],[21,22,23,24],[31,32,33,34]]
mtr2 = [[11,12,13],[21,22,23],[31,32,33]]
mtr3 = [[11,12],[21,22,23,24],[31,32,33]]
showmatrix(mtr1)
print()
showmatrix(mtr2)
print()
showmatrix(mtr3)
|
"""
set - method
"""
# copy()
# copy a set and return
# is it a built-in function?
A = {1,2,3}
B = A.copy()
print(B)
print(B is A)
# isdisjoint()
print()
A = {1,2,3}
B = {4,5,6}
print("A is disjoint to B?",A.isdisjoint(B))
# subset and superset
A = {1,2,3}
B = {1,2,3}
B = {1,2}
B = {1,2,5}
print("A = ",A)
print("B = ",B)
print("B.issubset(A) ? ",B.issubset(A))
print("A.issuperset(B) ? ",A.issuperset(B))
print("B.issuperset(A) ? ",B.issuperset(A))
|
"""
to check if a path is existing
"""
import os
# case 1. directory or folder
path = '../day12_201219'
result = os.path.exists(path)
print(f"The path of {path} exists? {result}")
# case 2. files or documents
path = '../filedir_1_rmfile.py'
path = r'D:\workspace\pycharm201803\stem1401python_student\py200912f_python2m7\day12_201219\filedir_1_rmfile.py'
result = os.path.exists(path)
print(f"The path of {path} exists? {result}")
|
"""
isdisjoint()
"""
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
C = {9,10}
#
result = A.isdisjoint(B)
print(result)
#
result = A.isdisjoint(C)
print(result)
# application
if A.isdisjoint(B):
print("A and B have common items")
else:
print("A and B do not have common items")
|
"""
set operation - set symmetric difference
"""
A = {1,2,3,4}
B = {4,5,6,7}
print(f"Set A: {A}")
print(f"Set B: {B}")
result = A ^ B
print(f"Result Set A^B : {result}")
result = (A-B) | (B-A)
print(f"Result Set A^B : {result}")
result = (A | B) - (A & B)
print(f"Result Set A^B : {result}")
result = A.symmetric_difference(B)
print(f"Result Set A^B : {result}")
result = B.symmetric_difference(A)
print(f"Result Set A^B : {result}")
|
"""
rename a file or dir
rename(old, new)
"""
import os
# rename a directory
# rename mydir3 -> mydir3a
# old = 'mydir3'
# new = 'mydir3a'
#
# os.rename(old, new)
# rename a file
os.rename("rename_file.py", "rename_file_new.py")
|
"""
symmetric difference
"""
#
A = {1,2,3,4,5}
B = {1,2,3,4,6}
C = {3,4,7}
result = A ^ B
print(result)
result = A ^ B ^ C
print(result)
result = C ^ B ^ A
print(result)
result = C ^ A ^ B
print(result)
|
"""
password
v3
encrypt
decrypt
"""
def encrypt(char):
pass
def decrypt(ascii):
pass
pwd = 'asdfsdfasdfas'
encrypt_pwd = []
decrypt_pwd = ""
for c in pwd:
encrypt_pwd.append(encrypt(c))
print("encrypted pwd is:", encrypt_pwd)
for pc in encrypt_pwd:
decrypt_pwd += decrypt(pc)
print("encrypted pwd is:", decrypt_pwd)
|
"""
file operation
read()
read(size)
readline()
readlines()
"""
try:
# step 1. open a file
file1 = open('file_1.txt')
# step 2. operate on the opened file
# round 1
content = file1.read()
print(content)
print("==================")
# file1.close()
# round 2
file1.seek(0)
content2 = file1.read()
print(content2)
# step 3. close the file
file1.close()
except FileNotFoundError as fe:
print(fe)
except Exception as e:
print(e)
|
"""
matrix_homework
"""
a = [[1, 2, 3, 4],
[11, 21, 31, 41],
[42, 53, 64, 75]]
print(a[1][0]) # getting the number 11
print(a) |
# ex 1.
# create a list with 6 items
# i.e
fruits = ['apple','pineapple','orange',
'watermelon','peach','grape']
print(fruits)
sports = ['basketball', 'football', 'hockey',
'baseball', 'soccer', 'gymnastic']
print(sports)
animals = ['dog','cat','horse',
'mouse','cow','bird']
print(animals)
drinks = ['coca cola', '7up', 'Sprite', 'soda water', 'Red Bull', 'Monster Energy']
print(drinks)
# ex 2.
# add a sequence no to your first item
# i.e. 'apple' => '1.apple'
# ['1.apple', 'pineapple', 'orange', 'watermelon', 'peach', '6.grape']
animals = ['dog','cat','horse','mouse','cow','bird']
animals[0] = '1.dog'
animals[5] = '6.bird'
print(animals)
print("=====")
mylist = ['basketball', 'football', 'hockey', 'baseball', 'soccer', 'gymnastic']
print(mylist)
mylist[0] = '1.basketball'
print(mylist)
mylist[5] = '6.gymnastic'
print(mylist)
#
mylist = ['coca cola', '7up', 'Sprite', 'soda water', 'Red Bull', 'Monster Energy']
mylist[0] = '1.coca cola'
print(mylist)
mylist[5] = '6.Monster Energy'
print(mylist)
# add a sequence no to your last item
# i.e. 'grape' => '6.grape'
# mylist = ["a",'b','c']
# mylist[0] = '1.a'
# print(mylist)
# calculate how many items you have in the list?
# your codes go here
num = len(mylist)
print("There are", num, "items in the list.")
# Expected Result on console: 'There are 6 items in the list.'
num = len(sports)
print("There are", num, "items in the list")
|
"""
Exception Handling
1. what is an exception?
error
at runtime
at compile time
validate or syntax checking
python
detect, catch, handle possible exceptions
types of exception:
a. built-in exception
b. user-defined exception
2. why?
to avoid to crash frequently
to improve the tolerance ability of your programs, robust
3. how to use?
"""
"""
Logical Errors Example/Case
"""
# case 1. Syntax Errors
a = 6
# if a>3
# SyntaxError: invalid syntaxs
if a > 3:
pass
# case 2. Logical Errors
# when your program is going to read a file, open the file first, there is no such file.
# FileNotFoundError
a = 1
b = 1
# ....
result = a/b
# ZeroDivisionError
# import a not existing module
# ImportError
# list all the built-in exceptions
# print(dir(locals()['__builtins__']))
"""
locals()['__builtins__']
functions
attributes
exceptions
dir() - list them out
"""
for entry in dir(locals()['__builtins__']):
print(entry)
|
"""
docstring in functions
"""
# docstring in function without argument
def foo():
"""
the description of this function
:return:
"""
print("Yes, we entered the function of foo()")
# call a function
foo()
print("Good bye!")
# docstring in function with arguments
def add(num1, num2):
"""
the description of this function add()
:param num1:
:param num2:
:return:
"""
res = num1 + num2
return res
result = add(3, 5)
print(foo.__doc__)
print(add.__doc__) |
"""
menu
basic menu and menu option
"""
from tkinter import *
from tkinter import messagebox
def test_menu1():
messagebox.showinfo("Test", "Menu 1 is clicked")
def test_menu2():
messagebox.showinfo("Test", "Menu 2 is clicked")
main = Tk()
main.title("Athensoft Python Course | Menu")
main.geometry("640x480+300+300")
# define menu and menu items
menubar = Menu(main)
menubar.add_command(label="MENU_1", command=test_menu1)
menubar.add_command(label="MENU_2", command=test_menu2)
menubar.add_command(label="Exit", command=main.destroy)
menubar2 = Menu(main)
menubar2.add_command(label="2MENU_1", command=test_menu1)
menubar2.add_command(label="2MENU_2", command=test_menu2)
menubar2.add_command(label="2Exit", command=main.destroy)
# set menu
main.config(menu=menubar2)
main.mainloop() |
"""
Button
create a Button
and write response code
"""
from tkinter import *
def response():
print("I was clicked.")
win = Tk()
win.title("Tkinter Button")
win.geometry("480x320+300+300")
win.config(bg="#ddddff")
# Button
# command option accepts function only (function name or anonymous function/lambda)
btn1 = Button(win, text="Click me!", font=(None, 20), command=response)
btn1.pack()
# Button
btn2 = Button(win, text="Close", font=(None, 20), command=win.destroy)
btn2.pack()
win.mainloop() |
"""
[Challenge] Project. Volume Controller
c04_button/button_03_b.py
Description
Max value and Min value
1. User can press '+' button to increase the number by one per click
2. User can press '-' button to decrease the number by one per click
3. The number shows in a Label
constraints:
the MAX value = 10,
the MIN value = -10,
default number = 0
default step number = 1, step number is adjustable
"""
from tkinter import *
digit = 0
step_number = 2
MAX = 10
MIN = -10
def add():
global digit
if digit == -10:
minus_button.config(state="normal")
digit += step_number
num.config(text=digit)
if digit == 10:
plus_button.config(state="disabled")
def sub():
global digit
if digit == 10:
plus_button.config(state="normal")
digit -= step_number
num.config(text=digit)
if digit == -10:
minus_button.config(state="disabled")
root = Tk()
root.title("number")
root.geometry("440x380")
root.config(bg="#ddddff")
root.resizable(0, 0)
num = Label(root, bg="gray", text=digit, width=60, height=10, font=("Arial",20))
num.pack()
minus_button = Button(root, text="-", width=20, height=4, relief="raised", command=sub)
minus_button.pack(side=LEFT)
plus_button = Button(root, text="+", width=20, height=4, relief="raised",command=add)
plus_button.pack(side=LEFT)
exit_button = Button(root, text="Exit", width=20, height=4,relief="raised", command=root.destroy)
exit_button.pack(side=RIGHT)
root.mainloop() |
"""
Write a Python program to sum all the items in a list.
[Homework] 2021-01-18
Write a Python program to multiply all the items in a list.
"""
# step 1. to create a list
list1 = [1,2,3,4,5,6]
# step 2. to sum all the items
a = [1, 2, 3, 4, 5]
b = sum(a)
print(b)
# step 2. to sum all the items using for loop
# how to print out each item by using for loop
a = [4,7,3,2,5,9]
# for i in a:
sum = 0
list1 = [4,7,3,2,5,9]
for i in list1:
# print(list1)
print(i)
sum = sum + i
# step 3.
print("The sum of the list items is {}".format(sum))
"""
1ST 4 SUM=(SUM)+4=4
2ND 7 SUM=(SUM)+7=11
3RD 3 SUM=(SUM)+3=14
4TH 2 SUM=(SUM)+2=16
5TH 5 SUM=(SUM)+5=21
6TH 9 SUM=(SUM)+9=30
"""
"""
4
7
3
2
5
9
"""
# how to write the print statement
# print('hello goodbye hello')
# print(1)
# print(a)
"""
mylist = ['10', '12', '14']
for elem in mylist:
print elem
10
12
14
""" |
"""
if-statement
if-elif-else statement
elif -> else if
if-elif,elif,...,else
"""
# sample
score = 89
if score >= 90:
print("You got an A")
elif score >= 80:
print("You got a B")
elif score >= 70:
print("You got a C")
elif score >= 60:
print("You got a D")
else:
print("You got a F")
# ex.
# if a given number >0, output 'positive number'
# elif a given number ==0 , output 'zero'
# otherwise ,output 'negative number'
number = float(input("Enter a number: "))
if number > 0:
print("{} is a positive number!".format(number))
elif number == 0:
print("{} is zero!".format(number))
else:
print("{} is a negative number!".format(number))
|
"""
Python dictionary
Sorting by key
functions:
sorted()
list()
map()
list comprehension
references:
https://blog.csdn.net/buster2014/article/details/50939892
"""
# option 1
def sortedDictValues1(mydict):
items = mydict.items()
# items.sort()
sorted(items)
return [value for key, value in items]
# option 2
def sortedDictValues2(mydict):
keys = mydict.keys()
# keys.sort()
sorted(keys)
return [mydict[key] for key in keys]
# option 3
def sortedDictValues3(mydict):
keys = mydict.keys()
# keys.sort()
sorted(keys)
return map(mydict.get, keys)
# option 4
def sortedDictValues4(mydict):
return [(k,mydict[k]) for k in sorted(mydict.keys())]
# main program
demo_dict = {
1: "c",
2: "a",
3: "b"
}
print("Original dictionary is: {}".format(demo_dict))
print()
# test 1
print("[info] testing sortedDictValues1()")
print(sortedDictValues1(demo_dict))
print()
# test 2
print("[info] testing sortedDictValues2()")
print(sortedDictValues2(demo_dict))
print()
# test 3
# list(map) - show data in a map by converting to a list
print("[info] testing sortedDictValues3()")
print(list(sortedDictValues3(demo_dict)))
print()
# test 4
print("[info] testing sortedDictValues4()")
print(list(sortedDictValues4(demo_dict)))
print()
|
"""
Leonj
"""
print("=== Login Form ===")
username = input('Please enter your username:')
# input ('please enter your password')
password = input('Please enter your password:')
number = input('Please enter your number:')
print("Welcome back, ", username, "!")
print("=== Done, ===")
|
"""
quiz 1
My quiz anwsers:
1.a and c
2.a and d
3.b
4.a
5.a
6.a and b
7.a
"""
"""
Homework: forming a triangle with *
"""
# I tried using while loop but i failed
num = 5
row = 0
while row < num:
star = row + 1
while star > 0:
print("*",end=" ")
star = star - 1
row = row + 1
print()
print()
print("*")
print("{:3s}{}".format('*','*'))
print("{:3s}{:3s}{}".format('*','*','*'))
print("{:3s}{:3s}{:3s}{}".format('*','*','*','*'))
print("{:3s}{:3s}{:3s}{:3s}{}".format('*','*','*','*','*')) |
"""
to permanently persist into external storage
to append content to an existing file
write a program to save any text-based content
"""
# step 1. prepare data to output
print("Program started.\n")
data = "This is the 4th part of content I would like to save as a new line.\n"
# step 2. writing
print("Writing...")
print(f"Data: {data}\n")
file = open("mydata.txt",'a')
file.write(data)
file.close()
print("Done.")
|
"""
[Homework]
Date: 2021-02-20
1. Write a GUI program of Label counter for implementing version 3.
Requirements:
(Function)
When the number reaches 10, then it comes to stop and displays the text of 'END'.
If a user clicks to close the main window, the program terminates.
(UI)
Using the layout manager of pack() for the UI.
A recommended UI design is given below.
"""
"""
score:
no enough white spaces (-1)
improper font size at footer (-1)
invalid char in file name (-1)
"""
from tkinter import *
from tkinter.ttk import Separator
# main program
root = Tk()
root.title('Counter to 10')
root.geometry("{}x{}+200+240".format(640, 480))
root.configure(bg='#ddddff')
def start_counting(mylabel):
print('entered start counting')
counter = 0
def counting():
nonlocal counter
counter = counter + 1
digit_label.config(text=counter)
digit_label.after(1000,counting)
if counter > 10:
counter += 0
digit_label.config(text='END')
root.update()
counting()
# label object
title_label = Label(root,text='Counter to 10', bg='navy', fg='snow', height=2, width=50, font='Roman 24 bold')
title_label.pack(side=TOP)
sep = Separator(root, orient=HORIZONTAL)
sep.pack(fill=X)
digit_label = Label(root,
bg = "seagreen",
fg = 'white',
height = 5,
width = 50,
font = "Helvetic 48 bold",relief='groove')
digit_label.pack()
sep = Separator(root, orient=HORIZONTAL)
sep.pack(fill=X)
footer_label = Label(root, text='Version 1, Guang Zhu, 25/02/2021', bg='snow', fg='PeachPuff3', width=50, height=2, font='Roman 24 bold')
footer_label.pack(side=BOTTOM)
start_counting(digit_label)
root.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.