text
stringlengths 37
1.41M
|
---|
import re
list_tens_2 = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
list_tens = ['', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
list_ones = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
# returns the string expression of numbers from 0-9
def ConvertOnes(input_ones):
ones = int(input_ones)
return list_ones[ones]
# returns the string expression of numbers from 10-99
def ConvertTens(input_tens):
tenth_digit = ''
ones_digit = ''
tens = int(input_tens)
# [10, 20, 30, 40, 50, 60, 70, 80, 90]
if tens == 90: return list_tens_2[9]
elif tens == 80: return list_tens_2[8]
elif tens == 70: return list_tens_2[7]
elif tens == 60: return list_tens_2[6]
elif tens == 50: return list_tens_2[5]
elif tens == 40: return list_tens_2[4]
elif tens == 30: return list_tens_2[3]
elif tens == 20: return list_tens_2[2]
elif tens == 10: return list_tens_2[1]
else:
# [21-99]
if tens/90>0:
tenth_digit = list_tens_2[9]
elif tens/80>0:
tenth_digit = list_tens_2[8]
elif tens/70>0:
tenth_digit = list_tens_2[7]
elif tens/60>0:
tenth_digit = list_tens_2[6]
elif tens/50>0:
tenth_digit = list_tens_2[5]
elif tens/40>0:
tenth_digit = list_tens_2[4]
elif tens/30>0:
tenth_digit = list_tens_2[3]
elif tens/20>0:
tenth_digit = list_tens_2[2]
else:
# [11-19]
return list_tens[tens%10]
onesdigit = list_ones[tens%10]
return tenth_digit + ' ' + onesdigit
# returns the string expression of numbers from 100-999
def ConvertHundreds(input_huns):
hundred_digit = ''
single_hundred_digit = str(input_huns)[0]
if int(input_huns[0]) != 0:
hundred_digit += list_ones[int(single_hundred_digit)]
hundred_digit += ' hundred '
single_tens_digit = str(input_huns)[1] + str(input_huns)[2]
int_single_tens_digit = int(single_tens_digit)
# if NOT 100
if int_single_tens_digit != 0:
# e.g. 101
if len(str(int_single_tens_digit))==1:
hundred_digit += 'and '
hundred_digit += ConvertOnes(single_tens_digit)
elif len(str(int_single_tens_digit))==2:
tens_digit = ConvertTens(single_tens_digit)
# hundred_digit += ' '
hundred_digit += tens_digit
return hundred_digit
# returns the string expression of numbers from 1,000-9,999
def ConvertThousands(input_thou):
thousand_digit = ''
single_thou_digit = str(input_thou)[0]
thousand_digit += list_ones[int(single_thou_digit)]
thousand_digit += ' thousand'
single_hun_digit = str(input_thou)[1] + str(input_thou)[2] + str(input_thou)[3]
int_single_hun_digit = int(single_hun_digit)
# e.g if NOT 1,000
if int_single_hun_digit != 0:
# e.g. 1,001
if str(input_thou)[1] == '0' and str(input_thou)[2] == '0':
thousand_digit += ' '
thousand_digit += ConvertOnes(single_hun_digit)
# e.g 1,010
elif str(input_thou)[1] == '0':
thousand_digit += ' '
thousand_digit += ConvertTens(single_hun_digit)
# e.g. 1,100
else:
hundreds_digit = ConvertHundreds(single_hun_digit)
thousand_digit += ' '
thousand_digit += hundreds_digit
return thousand_digit
# returns the string expression of numbers from 10,000-99,999
def ConvertTenThousands(input_ten_thou):
tenthousand_digit = ''
single_tenthou_digit = str(input_ten_thou)[0] + str(input_ten_thou)[1]
tenthousand_digit += ConvertTens(single_tenthou_digit)
tenthousand_digit += ' thousand'
single_thou_digit = str(input_ten_thou)[2] + str(input_ten_thou)[3] + str(input_ten_thou)[4]
int_single_thou_digit = int(single_thou_digit)
if int_single_thou_digit != 0:
# e.g. 10,001
if len(str(int_single_thou_digit)) == 1:
tenthousand_digit += ' and '
tenthousand_digit += ConvertOnes(single_thou_digit)
# e.g. 10,010
elif len(str(int_single_thou_digit)) == 2:
tenthousand_digit += ' '
tenthousand_digit += ConvertTens(single_thou_digit)
# e.g. 10,100
else:
thousands_digit = ConvertHundreds(single_thou_digit)
if single_thou_digit !=0:
tenthousand_digit += ' '
tenthousand_digit += thousands_digit
return tenthousand_digit
# returns the string expression of numbers from 100,000-999,999
def ConvertHundredThousands(input_hun_thou):
hunthousand_digit = ''
single_hunthou_digit = str(input_hun_thou)[0] + str(input_hun_thou)[1] + str(input_hun_thou)[2]
hunthousand_digit += ConvertHundreds(single_hunthou_digit)
hunthousand_digit += ' thousand'
single_thou_digit = str(input_hun_thou)[3] + str(input_hun_thou)[4] + str(input_hun_thou)[5]
int_single_thou_digit = int(single_thou_digit)
if int_single_thou_digit != 0:
# e.g. 100,001
if len(str(int_single_thou_digit)) == 1:
hunthousand_digit += ' and '
hunthousand_digit += ConvertOnes(single_thou_digit)
# e.g. 100,010
elif len(str(int_single_thou_digit)) == 2:
hunthousand_digit += ' '
hunthousand_digit += ConvertTens(single_thou_digit)
# e.g 100,100
else:
thousands_digit = ConvertHundreds(single_thou_digit)
if single_thou_digit !=0:
hunthousand_digit += ' '
hunthousand_digit += thousands_digit
return hunthousand_digit
# [1,000,000-9,999,999]
def ConvertMillion(input_million):
million_digit = ''
hunthousand_digit = ''
single_million_digit = str(input_million)[0]
million_digit += list_ones[int(single_million_digit)]
million_digit += ' million'
single_hunthou_digit = str(input_million)[1] + str(input_million)[2] + str(input_million)[3] + str(input_million)[4] + str(input_million)[5] + str(input_million)[6]
int_single_hunthou_digit = int(single_hunthou_digit)
# e.g if NOT 1,000,000
if int_single_hunthou_digit != 0:
million_digit += ' '
million_digit += ConvertHundredThousands(single_hunthou_digit)
return million_digit
# [10,000,000-99,999,999]
def ConvertTenMillion(input_tenmillion):
tenmillion_digit = ''
single_tenmillion_digit = str(input_tenmillion)[0] + str(input_tenmillion)[1]
tenmillion_digit += ConvertTens(single_tenmillion_digit)
tenmillion_digit += ' million'
single_hunthou_digit = str(input_tenmillion)[2] + str(input_tenmillion)[3] + str(input_tenmillion)[4] + str(input_tenmillion)[5] + str(input_tenmillion)[6] + str(input_tenmillion)[7]
int_single_hunthou_digit = int(single_hunthou_digit)
# e.g if NOT 10,000,000
if int_single_hunthou_digit != 0:
tenmillion_digit += ' '
tenmillion_digit += ConvertHundredThousands(single_hunthou_digit)
return tenmillion_digit
# # [100,000,000-999,999,999]
def ConvertHunMillion(input_hunmillion):
hunmillion_digit = ''
single_hunmillion_digit = str(input_hunmillion)[0] + str(input_hunmillion)[1] + str(input_hunmillion)[2]
hunmillion_digit += ConvertHundreds(single_hunmillion_digit)
hunmillion_digit += ' million'
single_hunthou_digit = str(input_hunmillion)[3] + str(input_hunmillion)[4] + str(input_hunmillion)[5] + str(input_hunmillion)[6] + str(input_hunmillion)[7] + str(input_hunmillion)[8]
int_single_hunthou_digit = int(single_hunthou_digit)
# e.g if NOT 10,000,000
if int_single_hunthou_digit != 0:
hunmillion_digit += ' '
hunmillion_digit += ConvertHundredThousands(single_hunthou_digit)
return hunmillion_digit
def ConvertFullNumber(input_int):
eng_full = ''
# [0-9]
if len(str(input_int))==1:
eng_full = ConvertOnes(input_int)
# [10-99]
elif len(str(input_int))==2:
eng_full = ConvertTens(input_int)
# [100-999]
elif len(str(input_int))==3:
eng_full = ConvertHundreds(input_int)
# [1,000-9,999]
elif len(str(input_int))==4:
eng_full = ConvertThousands(input_int)
# [10,000-99,999]
elif len(str(input_int))==5:
eng_full = ConvertTenThousands(input_int)
# [100,000-999,999]
elif len(str(input_int))==6:
eng_full = ConvertHundredThousands(input_int)
# [1,000,000-9,999,999]
elif len(str(input_int))==7:
eng_full = ConvertMillion(input_int)
# [10,000,000-99,999,999]
elif len(str(input_int))==8:
eng_full = ConvertTenMillion(input_int)
# # [100,000,000-999,999,999]
elif len(str(input_int))==9:
eng_full = ConvertHunMillion(input_int)
return eng_full
def ConvertDecimal(input_dec):
eng_decimal = ''
integer = ''
decimal = ''
# split number into integer and decimal parts
split_dec = str(input_dec).split('.')
integer = split_dec[0]
decimal = split_dec[1]
eng_decimal += ConvertFullNumber(integer)
eng_decimal += ' point'
for i in range(0, len(decimal)):
eng_decimal += ' '
eng_decimal += ConvertOnes(decimal[i])
return eng_decimal
def EvaluateOthersFull(substring):
reg_int = re.findall(r'(\d+(?:(?:\,\d{3})+)?)', substring)
if reg_int:
for r6 in range(0, len(reg_int)):
new_substring = ''
ori_int = reg_int[r6]
integer = reg_int[r6].replace(',', '')
new_substring += ConvertFullNumber(integer)
# print ori_int + " : " + new_substring
substring = substring.replace(ori_int, new_substring)
return substring
def EvaluateOthersDecimal(substring):
# .4 and 1,000.2332 and 1000 and 2.34
reg_dec = re.findall(r'(\d+(?:(?:\,\d{3})+)?(?:\.\d+))', substring)
if reg_dec:
for r5 in range(0, len(reg_dec)):
new_substring = ''
ori_dec = reg_dec[r5]
decimal = reg_dec[r5].replace(',', '')
new_substring += ConvertDecimal(decimal)
# print ori_dec + " : " + new_substring
substring = substring.replace(ori_dec, new_substring)
return substring
|
import math
import os
masses = open('./input.txt','r').readlines()
masses = [ int(m) for m in masses]
def compute_fuel(mass):
assert type(mass)==int
return math.floor(mass/3)-2
def compute_extra_fuel(mass):
assert type(mass)==int
extra_fuel = compute_fuel(mass)
actual_fuel = 0
while extra_fuel>0:
actual_fuel+=extra_fuel
extra_fuel = compute_fuel(extra_fuel)
return actual_fuel
total_fuel = sum([compute_extra_fuel(m) for m in masses])
print(total_fuel)
|
print ("Ternary Operator")
print ("""
Ternary Operator atau operator rangkap tiga ini adalah kondisional
yang ditulis dengan lebih hemat. Tetapi struktur yang dapat dibuat
hanya if dan else saja. Operator ini ditulis didalam variabel.
rumus :
var1 = 'statement1' if 'kondisi' else 'statement2'
""")
total_belanja_A = 100000
diskon_A = "Selamat kamu dapat voucher belanja 20.000!" if total_belanja_A > 99000 else "Belanja lebih banyak untuk dapatkan voucher belanja"
total_belanja_B = 200000
diskon_B = "Selamat kamu dapat voucher belanja 20.000!" if total_belanja_B > 99000 else "Belanja lebih banyak untuk dapatkan voucher belanja"
total_belanja_C = 50000
diskon_C = "Selamat kamu dapat voucher belanja 20.000!" if total_belanja_C > 99000 else "Belanja lebih banyak untuk dapatkan voucher belanja"
print (diskon_A)
print (diskon_B)
print (diskon_C)
|
print ("If Statement")
print ("""
Dalam algoritma kita mengenal pilihan. Untuk mewujudkan pilihan atau
bisa juga kondisional kita akan menggunakan if. Cara kerjanya,
kita harus tetapkan dulu suatu kondisi A yang akan melaksanakan
perintah A, dan kalau tidak memenuhi kondisi A, maka akan melakukan
perintah yang lainnya.
Statement if memerlukan kondisi yang dibuat dengan operator logika
dan operator relasional. Kemudian kalau kondisi itu tidak sesuai,
maka else yang akan melanjutkannya.
rumus penggunaan:
if 'kondisi A':
'reaksi A'
else:
'reaksi B'
* Catatan: Baris reaksi harus diberikan tab.
Variabel lab ini:
nilai = 65
""")
nilai = 65
if nilai > 80:
print ("Selamat, kamu lulus ujian.")
else:
print ("Kamu belum lulus ujian.")
|
print("Elif Statement")
print("""
Elif statement memungkinkan kita membuat kondisional lebih dari 1,
sebelumnya kita tau if dan else. Dengan adanya elif, kita dapat
membuat banyak kondisi dengan banyak reaksinya.
rumus penggunaan :
if 'kondisi A':
'reaksi A'
elif 'kondisi B':
'reaksi B'
elif 'kondisi C':
'reaksi C'
else:
'reaksi Z'
*Catatan : dengan elif, kamu bisa mengakhiri sebuah kondisi
dengan atau tanpa else.
variabel lab ini:
nilai = 65
""")
nilai = 65
if nilai >= 96:
print ("Kamu Genius!")
elif nilai >= 80 and nilai < 96:
print ("Kamu Pintar!")
elif nilai >= 70 and nilai < 80:
print ("Belajar lagi, kamu pasti bisa")
elif nilai >=65 and nilai <=70:
print ("Jangan main melulu")
else:
print ("goblok lu!")
|
print("____Taş,kağıt,makas oyununa hoşgeldiniz____")
player_1=input("1.oyuncu Lütfen adınızı giriniz:" )
player_2=input("2.oyuncu Lütfen adınızı giriniz:" )
player_1skor=0
player_2skor=0
tur=1
while tur<11 :
player_1_answer = input("%s,Taş(T),Kağıt(K),Makas(M) hangisini seçmek istersiniz?" % player_1)
player_2_answer = input("%s,Taş(T),Kağıt(K),Makas(M) hangisini seçmek istersiniz?" % player_2)
if player_1_answer == player_2_answer:
print("Berabere!")
elif player_1_answer == 'T':
if player_2_answer == 'M':
print("{},kazandı!".format(player_1))
tur += 1
player_1skor += 1
else:
print("{},kazandı!".format(player_2))
tur += 1
player_2skor += 1
elif player_1_answer== 'M':
if player_2_answer == 'K':
print("{},kazandı!".format(player_1))
tur += 1
player_1skor += 1
else:
print("{},kazandı!".format(player_2))
tur += 1
player_2skor += 1
elif player_1_answer == 'K':
if player_2_answer == 'T':
print("{},kazandı!".format(player_1))
tur += 1
player_1skor += 1
else:
print("{},kazandı!".format(player_2))
tur += 1
player_2skor += 1
else:
print("Geçersiz giriş yaptınız!Lütfen geçerli 3 seçeneğimiz olan T(taş),K(kağıt) veya M(makas) giriniz.")
else:
print("Oyun bitti")
if player_1skor > player_2skor :
print("{} kazandi. Skor {} - {}".format(oyuncu_1, oyuncu_1_skor, oyuncu_2_skor))
elif oyuncu_2_skor > oyuncu_1_skor:
print("{} kazandi. Skor {} - {}".format(oyuncu_2, oyuncu_2_skor, oyuncu_1_skor))
else:
print("Oyun berabere.") |
'''
Created on Dec 15, 2010
@author: Michael Kwan
'''
import numpy as np
from matplotlib import pyplot
def closest_feature(map, x):
'''Finds the closest feature in a map based on distance.'''
ind = 0
mind = np.inf
for i in xrange(len(map)):
d = np.sqrt(np.power(map[i, 0] - x[0], 2) + np.power(map[i, 1] - x[1], 2))
if d < mind:
mind = d
ind = i
return (map[ind, :].T, ind)
def distToEdge(v, edge):
'''Computes the shortest distance to a line segment, returns distance and closest point.'''
S = edge[2:3] - edge[0:1]
S1 = v - edge[0:1]
m1 = np.asscalar(np.dot(S1, S.T))
if m1 <= 0:
d = np.linalg.norm(v - edge[0:1])
pt = edge[0:1]
else:
m2 = np.asscalar(np.dot(S, S.T))
if m2 <= m1:
d = np.linalg.norm(v - edge[2:3])
pt = edge[2:3]
else:
b = m1 / m2
pt = edge[0:1] + np.dot(b, S)
d = np.linalg.norm(v - pt)
return d, pt
def minDistToEdges(v, edges, fig=None):
'''Computes the shortest distance to a sequence of edges, which may form a
path, for example. Returns the min distance, the closest point, and the
list of distances and closest points for each edge.'''
n = len(edges)
d = np.zeros(n)
pt = np.zeros((n, 2))
for i in xrange(len(edges)):
d[i], pt[i, :] = distToEdge(v, edges[i - 1, :])
ind = np.argmin(d)
minD = d[ind]
minPt = pt[int(ind) - 1, :]
if not fig is None:
pyplot.figure(fig)
pyplot.hold(True)
l = np.array([v, minPt])
pyplot.plot(l[:, 0], l[:, 1], 'g')
return (minD, minPt, d, pt, ind)
def polygonal_world(posMinBound, posMaxBound, minLen, maxLen, numObsts,
startPos, endPos, obst_buffer, max_count):
'''Creates an environment of non-overlapping rectangles within a bound.
In addition, none of the rectangles can be on top of the start or end
position.
'''
a = np.zeros((numObsts, 4, 2))
b = np.zeros((numObsts, 4))
pos = np.zeros((numObsts, 4))
length = np.zeros((numObsts, 4))
fake_len = np.zeros((numObsts, 4))
theta = np.zeros(numObsts)
for j in xrange(numObsts):
a[j, 0, :] = np.array([0, -1])
a[j, 1, :] = np.array([1, 0])
a[j, 2, :] = np.array([0, 1])
a[j, 3, :] = np.array([-1, 0])
#create the number of obsts
count = 0
for i in xrange(numObsts):
#loop while there are collisions with obstacles
while True:
#generate random positions and lengths
pos[i, :] = posMinBound + [np.random.rand(1) * (posMaxBound[0] - posMinBound[0]), np.random.rand(1) * (posMaxBound[1] - posMinBound[1])];
length[i, :] = [np.random.rand(1) * (maxLen.a - minLen.a) + minLen.a, np.random.rand(1) * (maxLen.b - minLen.b) + minLen.b];
fake_len[i, :] = length[i, :] + obst_buffer
theta[i] = np.random.rand(1) * np.pi
rotationMatrix = [[np.cos(theta[i]), np.sin(theta[i])],
[-np.sin(theta[i]), np.cos(theta[i])]];
#find the points
pts = [[-length[i, 0] / 2, -length[i, 1] / 2],
[length[i, 0] / 2, -length[i, 1] / 2],
[length[i, 0] / 2, length[i, 1] / 2],
[-length[i, 0] / 2, length[i, 1] / 2]]
fake_pts = [[-fake_len[i, 0] / 2, -fake_len[i, 1] / 2],
[ fake_len[i, 0] / 2, -fake_len[i, 1] / 2],
[fake_len[i, 0] / 2, fake_len[i, 1] / 2],
[-fake_len[i, 0] / 2, fake_len[i, 1] / 2]]
for j in xrange(4):
pts[j, :] = (np.dot(rotationMatrix, pts[j, :].T)).T + np.array([pos[i, 0], pos[i, 1]])
fake_pts[j, :] = np.dot(rotationMatrix, fake_pts[j, :].T).T + np.array([pos[i, 0], pos[i, 1]])
##need to redo these checks
#check to see if it is outside the region
if (np.min(fake_pts[:, 0]) <= posMinBound[0]
or np.max(fake_pts[:, 0]) >= posMaxBound[0]
or np.min(fake_pts[:, 1]) <= posMinBound[1]
or np.max(fake_pts[:, 1]) >= posMaxBound[1]):
continue
if (np.min(pts[:, 0]) < startPos[0]
and np.max(pts[:, 0]) > startPos[0]
and np.min(pts[:, 1]) < startPos[1]
and np.max(pts[:, 1]) > startPos[1]):
continue
#check to see if it is on top of the end pos
if (np.min(pts[:, 0]) < endPos[0]
and np.max(pts[:, 0]) > endPos[0]
and np.min(pts[:, 1]) < endPos[1]
and np.max(pts[:, 1]) > endPos[1]):
continue
#check to see if it collided with any of the other obstacles
collided = 0;
for j in xrange(i):
#check for collision
if polygonsOverlap(fake_pts, ptsStore[:, j * 2:j * 2 + 1]):
collided = 1;
break;
if not collided:
break
count = count + 1
if count >= max_count:
a = np.array([])
b = np.array([])
ptsStore = np.array([])
return a, b, ptsStore
ptsStore[:, i * 2:i * 2 + 1] = pts
for j in xrange(4):
next = j + 1;
if j == 3:
next = 0
temp = np.array([[-(pts[j, 1] - pts[next, 1])], [(pts[j, 0] - pts[next, 0])]])
temp = (temp / np.linalg.norm(temp)).flatten()
a[i, j, 0] = temp[0]
a[i, j, 1] = temp[1]
#calculate the b matrix
for k in xrange(4):
for j in xrange(2):
b[i, k] = b[i, k] + pts[k, j] * a[i, k, j]
return a, b, ptsStore
def function val = polygonsOverlap(poly1, poly2)
'''Checks if two polygons intersect.
Assumes Polygon vertices are ordered counter clockwise (can be enforced with
our scripts)
Args:
poly1: N1x2 matrix of x,y coordinates of polygon vertices
poly2: N2x2 matrix of x,y coordinates of polygon vertices
'''
val = False
# Simple test to check if 1 is fully or partially enclosed in polygon 2
if sum(inpolygon(poly1(:, 1), poly1(:, 2), poly2(:, 1), poly2(:, 2)))
val = true;
return
end
# Simple test to check if 2 is fully or partially enclosed in polygon 1
if sum(inpolygon(poly2(:, 1), poly2(:, 2), poly1(:, 1), poly1(:, 2)))
val = true;
return
end
# Close the polygons
poly1 = [poly1;poly1(1, :)];
obstEdges = [poly2, [poly2(2:end, :);poly2(1, :)]];
# Loop over all possible intersections
for vertex = 1:(length(poly1) - 1)
if (CheckCollision(poly1(vertex, :), poly1(vertex + 1, :), obstEdges))
val = true;
return
end
end
return val
|
""" This library act as interactive bridge between user and code.
It contains higher level functions which are used to train models
* learn - returns trained model to generate new images
"""
import pickle
from gimmick import mapping
from gimmick.image_op import functions as image_functions
from sklearn.model_selection import train_test_split
algo = list(mapping.algo_mapping.keys())
def learn(images, algo, code_length=8, num_encoder_layers='auto', num_decoder_layers='auto', epochs=10,
batch_size=16, optimizer='adam', learning_rate=0.001, loss_function='mse', metrics=['mse'],
samples_for_code_statistics=64):
""" This function train model based on passed data and argumenents to generate realastic looking images
**Parameters**
images : list
Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size
algo : str
Algorithm to be used to learn image representation, Eg Autoencode_dense,
code_length: int
Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed.
num_encoder_layer: int
Default 'auto', number of layers to be used in encoder, applicable for autoenocder
num_decoder_layers: int
Default 'auto', number of layers to be used in decoder, applicable for autoenocder
epochs: int
Default 10, number of epoch to be used while training model
batch_size: int
Default 16, batch size of each training/eval/generation step
optimizer: string
Default 'adam', optimizer used to train the model
learning_rate: int
Default 0.001, learning rate for training model
loss_function: string
Default 'mse', loss function for training model
metrics: list of string
Default ['mse'], list of metrics to be printed while training
samples_for_code_statistics: int
Default 64, samples to be used to generate code statistics
**Returns**
object
model object trained on given dataset
"""
print("Number sample:", images.shape[0], "Image shape:", images[0].shape)
model = mapping.algo_mapping.get(algo, None)
if not model:
raise Exception("Algo not implement/present possible values for also are %s" % (mapping.algo_mapping.keys()))
optimizer_keys = optimizer
optimizer = mapping.optimizer_mapping.get(optimizer, None)
if not optimizer:
raise Exception("Optimizer not implement/present possible values for also are %s" % (mapping.optimizer_mapping.keys()))
loss_function_keys = loss_function
loss_function = mapping.loss_function_mapping.get(loss_function, None)
if not optimizer:
raise Exception("loss_function not implement/present possible values for also are %s" % (mapping.loss_function_mapping.keys()))
metrics_keys = metrics
metrics = [mapping.metrics_mapping.get(x, None) for x in metrics]
if list(filter(lambda x: x == None, metrics)):
raise Exception("One or more of the metrics passed is not a valid metrics, possible values are %s" % (mapping.metrics_mapping.keys()))
if code_length % 4 != 0:
raise Exception("code_length must be a multiple of 4")
print("===================================================================")
print("Algo:\t\t", model)
print("optimizer:\t", optimizer)
print("loss_function:\t", loss_function)
print("metrics:\t", metrics)
print("Epochs:\t\t", epochs)
print("batch_size:\t", batch_size)
print("learning_rate:\t", learning_rate)
print("===================================================================")
## Write code to normalize image to nearest 2 power, min 8x8x1
images = image_functions.convert_2dto3d(images)
if algo.startswith('gan'):
model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys,
loss_function=loss_function, loss_function_keys=loss_function_keys,
metrics=metrics, metrics_keys=metrics_keys,code_length=code_length,
num_generator_layers=num_encoder_layers, num_discriminator_layers=num_decoder_layers)
else:
model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys,
loss_function=loss_function, loss_function_keys=loss_function_keys,
metrics=metrics, metrics_keys=metrics_keys,code_length=code_length,
num_encoder_layers=num_encoder_layers, num_decoder_layers=num_decoder_layers)
model.build_model_graph(images[0].shape)
images_train, images_test = train_test_split(images, test_size=0.3, shuffle=True)
print("Train:", len(images_train.shape))
print("Test:", len(images_test.shape))
model.train(images_train, images_test, epochs=epochs, batch_size=batch_size, validation_split=0.2)
if not algo.startswith('gan'):
model.prepare_code_statistics(images_train, batch_size=batch_size, sample_size=samples_for_code_statistics)
return model
|
calories = [int(x) for x in input().split()]
string = [str(x) for x in input()]
result = 0
for i in range(len(calories)):
result += calories[i]*string.count(str(i+1))
print(result) |
pn = 0
ss = ""
pw = 1
anton = 0
danik = 0
print("Enter no. of playing")
pn = int(input())
while pw <= pn :
print(f"Enter {pw} of playing")
ss = input()
if ss == "A":
anton+=1
elif ss == "D":
danik+=1
pw+=1
if anton > danik:
print("Anton Won")
elif anton < danik:
print("Danik Won")
else:
print("friendship") |
# When the attacker's die value is larger: Attacker wins (1 defender unit dies)
# When the 2 dice value is tie: Defender wins (1 attacker unit dies)
# When the defender's die value is larger: Defender wins (1 attacker unit dies)
# Attacker: Lost x units
# Defender: Lost x units
import random
# print(random.randrange(1,6))
a1 = 0 # kosc atakujacego1
a2 = 0
a3 = 0
d1 = 0 # kosc bronionacego1
d2 = 0
def readNumber3(text):
isCorrect = False
num = 0
while isCorrect == False:
userInput = input(text)
userInputint = int(userInput)
if userInputint <=3 and userInputint >0:
num = int(userInput)
isCorrect = True
else:
print("Type 1 , 2 or 3")
return num
def readNumber2(text):
isCorrect = False
num = 0
while isCorrect == False:
userInput = input(text)
userInputint = int(userInput)
if (userInput.isdigit()) and userInputint <=2 and userInputint >0:
num = int(userInput)
isCorrect = True
else:
print("Type 1 , 2 or 3")
return num
def dice_throw():
diceoutcome = (random.randrange(1,6))
return diceoutcome
def throw_and_set_attacker_dice(number_of_attackers):
if number_of_attackers > 0:
a1 = dice_throw()
attacker_list = [a1]
if number_of_attackers > 1:
a2 = dice_throw()
attacker_list = [a1, a2]
if number_of_attackers > 2:
a3 = dice_throw()
attacker_list = [a1, a2, a3]
attacker_list.sort(reverse = True)
if number_of_attackers > 2:
print(" Attacker: ", attacker_list[0] , "-" , attacker_list[1] , "-" , attacker_list[2])
elif number_of_attackers > 1:
print(" Attacker: ", attacker_list[0] , "-" , attacker_list[1])
elif number_of_attackers >0:
print(" Attacker: ", attacker_list[0])
return attacker_list
def throw_and_set_defender_dice(number_of_defenders):
if number_of_defenders > 0:
d1 = dice_throw()
defender_list = [d1]
if number_of_defenders > 1:
d2 = dice_throw()
defender_list = [d1, d2]
defender_list.sort(reverse = True)
if number_of_defenders > 1:
print(" Defender: ", defender_list[0] , "-" , defender_list[1])
elif number_of_defenders > 0:
print(" Defender: ", defender_list[0])
return defender_list
# fix it!
def outcome(attackersortedlist, defendersortedlist):
awin = 0
dwin = 0
if len(attackersortedlist) > len(defendersortedlist):
longerlist = len(attackersortedlist)
else:
longerlist = len(defendersortedlist)
if len(attackersortedlist) == len(defendersortedlist):
for x in range(1 , longerlist):
if attackersortedlist[x] > defendersortedlist[x]:
awin += 1
else:
dwin += 1
print(" Attacker: Lost", dwin , "units")
print(" Defender: Lost", awin , "units")
def main():
attackernum = readNumber3("How many attackers are there? ")
defendernum = readNumber2("How many defenders are there? ")
print("Dice:")
attackersortedlist = throw_and_set_attacker_dice(attackernum)
defendersortedlist = throw_and_set_defender_dice(defendernum)
print("Outcome:")
outcome(attackersortedlist , defendersortedlist)
main()
|
from turtle import Turtle
class Scoreboard(Turtle):
player = 0
computer = 0
def __init__(self):
super().__init__()
self.shape("circle")
self.hideturtle()
self.pencolor("cyan")
self.penup()
self.goto(0, 360)
self.write(f"Score : {self.computer} | Score : {self.player}", align="center", font=("Arial", 20, "normal"))
def update(self):
self.clear()
self.write(f"Score : {self.computer} | Score : {self.player}", align="center", font=("Arial", 20, "normal"))
def score(self, who):
if who == "player":
self.player += 1
else:
self.computer += 1
self.update()
|
from turtle import Turtle
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.pensize(3)
self.pencolor("white")
self.fillcolor("white")
self.penup()
def move(self, dirc):
if dirc == "w":
self.forward(2.5)
else:
self.back(2.5)
|
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
if x == "cherry":
break
print(x)
else:
print("We have reached the end.")
for x in range(6):
print(x)
else:
print("Finally finished!")
|
from turtle import Turtle
class Plate(Turtle):
def __init__(self, side):
super().__init__()
self.shape("square")
self.pensize(5)
self.shapesize(1,5,1)
self.left(90)
self.pencolor("white")
self.fillcolor("white")
self.penup()
self.goto(side * 360, 0)
def move_up(self):
self.forward(5)
def move_down(self):
self.back(5)
|
import random
import math
# Limits
lower = int(input("Enter Lower bound:- "))
upper = int(input("Enter Upper bound:- "))
# Prep
generated = random.randint(lower, upper)
expected = math.ceil(math.log(upper - lower + 1, 2))
guesses = 0
guess = lower - 1
# Game
while generated != guess:
guess = int(input("Guess a number:- "))
guesses += 1
print()
if generated > guess:
print(f"Go higher than {guess}.")
elif generated < guess:
print(f"Go lower than {guess}.")
# Result
print(f"Expected guess count was {expected}.")
print(f"You found the number {guess} in {guesses} guesses.")
|
#This exercise is to become more familiar with variables
# and printing in python
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
#Insert a string variable into a string
print "Let's talk about %s." % my_name
#Insert an integer variable into a string
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually, that's not too heavy."
print "He's got %s eyes and %s hair" % (my_eyes, my_hair)
print "His teeth are ususally %s depending on the coffee." % my_teeth
#This line is tricky, try to get it exactly right
print "If I add %d, %d, and %d, I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight)
# See rest of python formatters by googling "python format characters"
# "%r" is a very useful formatter because it will print anything
print "\nExample of the formatter 'r':"
print "He has %r teeth and weighs %r pounds!" %(my_teeth,my_weight)
print "However, '%r' does put strings in quotes, as demonstrated above!" |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int] 前序遍历
:type inorder: List[int] 中序遍历
:rtype: TreeNode
"""
self.pos = {}
n = len(preorder)
for i in range(n):
self.pos[inorder[i]] = i
return self.dfs(preorder, inorder, 0, n-1, 0, n-1)
def dfs(self, preorder, inorder, pl, pr, il, ir):
if pl > pr: return None
k = self.pos[preorder[pl]] - il
root = TreeNode(preorder[pl])
root.left = self.dfs(preorder, inorder, pl+1, pl+k, il, il+k-1)
root.right = self.dfs(preorder, inorder, pl+k+1, pr, il+k+1, ir)
return root
|
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# write code here
start = 0
end = start + size
max_list = []
if len(num) < size or size==0:
return []
while(end<=len(num)):
max_list.append(max(num[start:end]))
start = start + 1
end = end + 1
return max_list
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 14 12:54:15 2019
@author: Killer1
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
datos = pd.read_csv("student.csv")
"""
print(datos.dtypes)
print(datos.info())
print(datos.describe())
print(datos.head())
"""
df1=datos.loc[(datos['school']=='GP')] #obtener dataframe de GP
print(df1.info())
df2=datos.loc[(datos['school']=='MS')] #obtener dataframe de MS
print(df2.info())
"""
print('¿Cuantos estudiantes viajan mas de 1 hora?')
print(df1.where(df1.traveltime==4).traveltime.count())
print("Estadisticas basicas")
print(df1['traveltime'].mean())
plt.figure
df1['traveltime'].hist()
"""
"""
print('¿Cuantos estudiantes no tienen internet en casa?')
print(df1.where(df1.internet=='no').internet.count())
"""
"""
print('¿Cuantos estudiantes requieren apoyo de un tutor?')
print(df1.where(df1.famrel==1).famrel.count())
tabla = pd.pivot_table(df1, index='sex',values='famrel')
print(tabla)
print('Tabla Pivote Usuario')
agrupar=input("¿Cómo quieres agrupar los datos?")
datos1 =input("¿Cuál dato quieres analizar?")
tablau =pd.pivot_table(df1, index=[agrupar],values=datos1,aggfunc=[np.mean,min,max])
print(tablau)
"""
#Alerta
if df1.where(df1.famrel<=2).famrel.count() > 0:
print('Se requiere atencion especializada')
tutores = df1.where(df1.famrel<=2).famrel.count()/2
print('Se necesitan ', int(round(tutores)),"tutores")
|
from cs50 import get_int
# Our main funcion
def main():
# continue forever
while True:
height = get_int("Height: ")
# does the input match our range
if height <= 8 and height > 0:
# draw it if it does
mario(height)
# end the loop
break
def mario(height):
for i in range(height):
for j in range(height):
if i >= height - (j + 1):
print("#", end="")
else:
print(" ", end="")
print()
main() |
#!/usr/bin/env python
"""
Implementation of a PID controller.
Assignment 4, in3140
"""
import rospy
import math
class PID(object):
def __init__(self):
# Proportional constant
self.p = 0.0
# Integral constant
self.i = 0.0
# Integral accumulation variable
self.integral = 0.0
# Derivative constant
self.d = 0.0
# Non-linear constant
self.c = 0.0
# Position error
self.error = 0.0
def __call__(self, desired_theta, current_theta, velocity_theta, dt):
"""
Perform PID control step
:param desired_theta: Desired set-point in radians
:param current_theta: Current joint angle in radians
:param velocity_theta: Current joint angle velocity in radians/second
:param dt: Time since last call in seconds
:returns: Effort for joint
"""
# TODO: Change which line is commented according to which part
# you are testing in your code.
return self.P_ctrl(desired_theta, current_theta, dt)
# return self.PD_ctrl(desired_theta, current_theta, velocity_theta, dt)
# return self.PID_ctrl(desired_theta, current_theta, velocity_theta, dt)
# return self.PIDD_ctrl(desired_theta, current_theta, velocity_theta, dt)
def P_ctrl(self, desired_theta, current_theta, dt):
"""
Calculate proportional control
:param desired_theta: Desired set-point in radians
:param current_theta: Current joint angle in radians
:param dt: Time since last call in seconds
:returns: Effort of joint
"""
# TODO: Implement!
# TIP: Use 'rospy.loginfo' to print output in ROS
return 0.0
def PD_ctrl(self, desired_theta, current_theta, velocity_theta, dt):
"""
Calculate Proportional-Derivative control
:param desired_theta: Desired set-point in radians
:param current_theta: Current joint angle in radians
:param velocity_theta: Current joint angle velocity in radians/second
:param dt: Time since last call in seconds
:returns: Effort for joint
"""
# TODO: Implement!
# TIP: Use 'rospy.loginfo' to print output in ROS
return 0.0
def PID_ctrl(self, desired_theta, current_theta, velocity_theta, dt):
"""
Calculate PID control
:param desired_theta: Desired set-point in radians
:param current_theta: Current joint angle in radians
:param velocity_theta: Current joint angle velocity in radians/second
:param dt: Time since last call in seconds
:returns: Effort for joint
"""
# TODO: Implement!
# TIP: Use 'rospy.loginfo' to print output in ROS
return 0.0
def PIDD_ctrl(self, desired_theta, current_theta, velocity_theta, dt):
"""
Calculate non-linear PID control
:param desired_theta: Desired set-point in radians
:param current_theta: Current joint angle in radians
:param velocity_theta: Current joint angle velocity in radians/second
:param dt: Time since last call in seconds
:returns: Effort for joint
"""
# TODO: Implement!
# TIP: Use 'rospy.loginfo' to print output in ROS
return 0.0
|
#!/usr/bin/python3.6
# Exercise 30: Else and If
people = 30
cars = 40
trucks = 15
if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")
if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("Maybe we could take the trucks.")
else:
print("We still can't decide.")
if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine, let's stay home then.")
# Let's try something out-of-the-box
result = trucks != cars or cars == people
if result == False:
print("We have to think carefully now!")
else:
print("It's up to you")
check = 5 != 7 and not (7 == 7)
if check == True:
print(f"The expression is: {check}")
else:
print(f"The expression is: {check}")
print (" ")
print("We're trying something unique here!\nLet's get started!\n")
students = input("Enter the number of students: ")
teachers = input("Enter the number of teachers: ")
rooms = input("Enter the number of rooms: ")
if teachers == rooms and not (rooms != teachers):
print("We cannot consider this at the moment!")
elif students == rooms:
print("This should be the right decision!")
else:
print("This is redundant!")
|
#Functions holding the answers
def founder_name():
name = "Fred Swaniker"
return name.lower()
def year_founded():
return 2015
def campus():
campuses = "Rwanda and Mauritius"
return campuses.lower()
def number_of_campus():
return 2
def dean_name():
dean = "Gaidi Faraj"
return dean.lower()
def student_life_head():
name = "Sila Ogidi"
return name.lower()
def lab_name():
name_of_lab = "Nigeria"
return name_of_lab.lower()
def number_of_cs_students():
return 30
def number_of_degrees():
return 8
def headquarters():
name_of_headquarter = "Mauritius"
return name_of_headquarter.lower()
#our program logic function
def program_logic():
while True:
score = 0
failed = 0
print("\nWelcome to Hangman game by Africa Board Rwanda\n")
name = input("Enter your name here: ")
print("The game is about to start!\n Let's play Hangman!")
print("Hello " + name + "! Best of Luck to you!")
# QUESTIONS
print("Welcome to the hangman game, you will be asked 10 questions about ALU. Good Luck!")
question_one = int(input("when was ALU founded? "))
if question_one == year_founded():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
question_two = input("who founded ALU? ")
if question_two.lower() == founder_name():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
question_three = input("Where are the ALU campuses? ")
if question_three.lower() == campus():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
question_four = int(input("How many campuses does ALU have? "))
if question_four == number_of_campus():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
question_five = input("What is the name of ALU Rwanda dean? ")
if question_five.lower() == dean_name():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
question_six = input("Who is in charge of Student Life? ")
if question_six.lower() == student_life_head():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
if failed == 6:
print("You have hang the man 6 times, the man is dead")
question_seven = input("What is the name of our Lab? ")
if question_seven.lower() == lab_name():
score += 1
else:
failed += 1
# score = score
if failed == 6:
print("You have hang the man 6 times, the man is dead")
while True:
try:
question_eight = int(input("How many students do we have in year 2 Cs (put the number of students)? "))
break
except ValueError:
print("Enter a number, a valid response")
if question_eight == number_of_cs_students():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
if failed == 6:
print("You have hang the man 6 times, the man is dead")
question_nine = int(input("How many degrees does ALU offer? "))
if question_nine == number_of_degrees():
score += 1
else:
failed += 1
# score = score
print("You have hang the man!")
if failed == 6:
print("You have hang the man 6 times, the man is dead")
question_ten = input("Where are the headquarters of ALU? ")
if question_ten.lower() == headquarters():
score += 1
else:
failed += 1
score = score
print("You have hang the man!")
if failed == 6:
print("You have hang the man 6 times, the man is dead")
if score == 10:
print("Congratulations! You got all questions right!")
elif score < 10:
print(f"You scored {score} and failed {failed} questions \n")
return f"Total score = {score}"
program_logic()
|
#Write your code here
class Patient:
def __init__(self,name,age,weight,height):
self.name = name
self.age = age
self.weight = weight
self.height = height
def print_details(self):
print("Name:",self.name)
print("Age:",self.age)
print("Weight",self.weight)
print("Height",self.height)
self.height = self.height/100
self.bmi = self.weight/(self.height*self.height)
print("BMI:",self.bmi)
# TODO
# Do not change the following code:
p1 = Patient("A", 55, 63.0, 158.0)
p1.print_details()
print()
p2 = Patient("B", 53, 61.0, 149.0)
p2.print_details() |
#Check if all alphabets are present
def checkletters():
for alphabet in alphabets:
if alphabet not in strupper:
return 'The input string does not contains all alphabets'
return 'The input string contains all alphabets'
#Take input
str= input('Please enter a string of your choice')
#convert to upper case
strupper=str.upper()
alphabets ="ABCDEFGHIJKLMNOPQRSTUVWXYZ "
#call the function checkletters
print(checkletters())
|
from fastNLP import Vocabulary
from fastNLP import DataSet
# 问题:fastNLP虽然已经提供了split函数,可以将数据集划分成训练集和测试机,但一般网上用作训练的标准集都已经提前划分好了训练集和测试机,
# 而使用split将数据集进行随机划分还引来了一个问题:
# 因为每次都是随机划分,导致每次的字典都不一样,保存好模型下次再载入进行测试时,因为字典不同导致结果差异非常大。
#
# 解决方法:在Vocabulary增加一个字典保存函数和一个字典读取函数,而不是每次都生成一个新字典,同时减少下次运行的成本,第一次使用save_vocab()
# 生成字典后,下次可以直接使用load_vocab()载入的字典。
if __name__ == '__main__':
data_path = "data_for_tests/tutorial_sample_dataset.csv"
train_data = DataSet.read_csv(data_path, headers=('raw_sentence', 'label'), sep='\t')
print('len(train_data)', train_data)
# 将所有字母转为小写
train_data.apply(lambda x: x['raw_sentence'].lower(), new_field_name='raw_sentence')
# label转int
train_data.apply(lambda x: int(x['label']) - 1, new_field_name='label_seq', is_target=True)
# 使用空格分割句子
def split_sent(ins):
return ins['raw_sentence'].split()
train_data.apply(split_sent, new_field_name='words')
# 增加长度信息
train_data.apply(lambda x: len(x['words']), new_field_name='seq_len')
# 筛选数据
train_data.drop(lambda x: x['seq_len'] <= 3)
# set input,模型forward时使用
train_data.set_input("words")
# 构建词表, Vocabulary.add(word)
vocab = Vocabulary(min_freq=2, write_path='data_for_tests')
train_data.apply(lambda x: [vocab.add(word) for word in x['words']])
vocab.build_vocab()
vocab.save_vocab()
voc = vocab.load_vocab()
print('载入的字典为:')
print(voc)
|
class Instance(object):
"""An Instance is an example of data.
Example::
ins = Instance(field_1=[1, 1, 1], field_2=[2, 2, 2])
ins["field_1"]
>>[1, 1, 1]
ins.add_field("field_3", [3, 3, 3])
:param fields: a dict of (str: list).
"""
def __init__(self, **fields):
self.fields = fields
def add_field(self, field_name, field):
"""Add a new field to the instance.
:param field_name: str, the name of the field.
"""
self.fields[field_name] = field
def __getitem__(self, name):
if name in self.fields:
return self.fields[name]
else:
raise KeyError("{} not found".format(name))
def __setitem__(self, name, field):
return self.add_field(name, field)
def __repr__(self):
s = '\''
return "{" + ",\n".join(
"\'" + field_name + "\': " + str(self.fields[field_name]) +\
f" type={(str(type(self.fields[field_name]))).split(s)[1]}" for field_name in self.fields) + "}"
|
# the list "students" is already defined
# students = [["Will", "B"], ["Kate", "B"], ["Max", "A"], ["Elsa", "C"], ["Alex", "B"], ["Chris", "A"]]
top_students = [student[0] for student in students if student[1] == "A"]
#
# top_students = []
# for student in students:
# if student[1] == "A":
# top_students.append(student[0])
print(top_students)
|
# solution uploaded to
# https://repl.it/@MikaMusic/NoxiousAdmiredBlogs#mean_var_std.py
import numpy as np
# list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
def calculate(list):
'''this function will convert a list to a 3-by-3 matrix (fixed-size) and return
statistics mean, var and std vor each column, line and the flattened matrix. '''
# throw error when len(list) < 9
l = len(list)
if l < 9:
raise ValueError("List must contain nine numbers.")
M = create_matrix_from_list(list)
# peralloc statistics lists
mean_m = []
mean_n = []
mean = []
var_m = []
var_n = []
std_m = []
std_n = []
max_m = []
max_n = []
min_m = []
min_n = []
sum_m = []
sum_n = []
# calculate statistics
m = 3 # matrix size m-by-m
for mm in range(m):
mean_m.append(np.mean(M[:, mm]))
var_m.append(np.var(M[:, mm]))
std_m.append(np.std(M[:, mm]))
max_m.append(np.max(M[:, mm]))
min_m.append(np.min(M[:, mm]))
sum_m.append(np.sum(M[:, mm]))
mean_n.append(np.mean(M[mm]))
var_n.append(np.var(M[mm]))
std_n.append(np.std(M[mm]))
max_n.append(np.max(M[mm]))
min_n.append(np.min(M[mm]))
sum_n.append(np.sum(M[mm]))
mean_flat = np.mean(M)
var_flat = np.var(M)
std_flat = np.std(M)
max_flat = np.max(M)
min_flat = np.min(M)
sum_flat = np.sum(M)
means = [mean_m, mean_n, mean_flat]
varis = [var_m, var_n, var_flat]
stds = [std_m, std_n, std_flat]
maxs = [max_m, max_n, max_flat]
mins = [min_m, min_n, min_flat]
sums = [sum_m, sum_n, sum_flat]
# create dictionary
calculations = {
'mean': means,
'variance': varis,
'standard deviation': stds,
'max': maxs,
'min': mins,
'sum': sums
}
return calculations
def create_matrix_from_list(list):
M = np.zeros((3, 3))
ii = 0
for mm in range(3):
for nn in range(3):
M[mm][nn] = list[ii]
ii += 1
return M
# result = calculate(list)
#
# for i in result.items():
# print(i)
|
import timeit
import sympy
import numpy
from part1_output import Output
from equations_util import create_dataframe_part2
import timeit
import equations_util
from part1_output import Output
def _eliminate(system: sympy.Matrix, i, j):
"""
Performs forward eliminates on a row inside a system of linear equations.
:param system: linear equations system.
:param i: index of the base row.
:param j: index of the row to be eliminated.
:var system: a mutable matrix can be passed (reference passing)
:return: an augmented square matrix after eliminating the row.
"""
n = system.shape[1]
c = system[j, i] / system[i, i]
for k in range(0, n):
system[j, k] -= c * system[i, k]
return system
def _back_sub(tri_mat: sympy.Matrix, index_map=None):
"""
Performs back substitution on an augmented upper triangular matrix.
:param tri_mat: augmented triangular matrix.
:return: a [n, 1] matrix containing result.
"""
n = tri_mat.shape[0]
x = sympy.zeros(n, 1)
if index_map is None:
index_map = numpy.array(range(n), dtype=numpy.int)
for i in range(n - 1, -1, -1):
s = 0
for j in range(i + 1, n):
s += tri_mat[index_map[i], j] * x[j]
x[i] = (tri_mat[index_map[i], n] - s) / tri_mat[index_map[i], i]
return x
def _forward_sub(a: sympy.Matrix, b:sympy.Matrix, index_map=None):
"""
Performs forward substitution on a lower triangular matrix.
:param a: triangular matrix, the coefficients of the variables.
:param b: r.h.s of the equations.
:param index_map: an array specifying the actual position of each row.
:return: a [n, 1] matrix containing result.
"""
n = a.shape[0]
y = sympy.zeros(n, 1)
if index_map is None:
index_map = numpy.array(range(n), dtype=numpy.int)
y[index_map[0]] = b[index_map[0]]
for i in range(1, n):
sum = b[index_map[i]]
for j in range(0, i):
sum -= a[index_map[i], j] * y[index_map[j]]
y[index_map[i]] = sum
return y
def _get_max_elem(system, i):
n = system.shape[0]
max_mag, max_ind = abs(system[i, i]), i
for j in range(i + 1, n):
if abs(system[j, i]) > max_mag:
max_mag, max_ind = abs(system[j, i]), j
return max_ind
def gauss(system: sympy.Matrix, symbol_list: list):
"""
Performs gauss elimination with partial pivoting on a system of
linear equations.
:param system: system of linear equations.
:param symbol_list: list of symbols used in the equations.
:return: a [n, 1] matrix containing result.
"""
output = Output()
output.title = "Gaussian-Elimination"
system = system.as_mutable()
n = system.shape[0]
begin = timeit.default_timer()
# iterate over columns
for i in range(0, n):
# find maximum magnitude and index in this column
max_ind = _get_max_elem(system, i)
# swap current row with the row found to have the maximum element
system.row_swap(max_ind, i)
# forward elimination, iterate over remaining rows and eliminate
for j in range(i + 1, n):
_eliminate(system, i, j)
# perform back substitution.
end = timeit.default_timer()
output.execution_time = abs(end - begin)
output.dataframes.append(equations_util.create_equ_sys_df(symbol_list, _back_sub(system)))
return output
def gauss_jordan(system: sympy.Matrix, symbol_list):
"""
Performs gauss jordan elimination with partial pivoting on a system of
linear equations.
:param system: system of linear equations.
:param symbol_list: list of symbols used in the equations.
:return: a [n, 1] matrix (vector) containing result.
"""
system = system.as_mutable()
n = system.shape[0]
output = Output()
output.title = "Gauss Jordan"
begin = timeit.default_timer()
# iterate over rows
for i in range(0, n):
# find maximum magnitude and index in this column
max_ind = _get_max_elem(system, i)
# swap current row with the row found to have the maximum element
system.row_swap(max_ind, i)
# normalize current row
system.row_op(i, lambda u, v: u / system[i, i])
# forward elimination, iterate over remaining rows and eliminate
for j in range(i + 1, n):
_eliminate(system, i, j)
# forward elimination, iterate over previous rows and eliminate
for j in range(i - 1, -1, -1):
_eliminate(system, i, j)
# return last column
end = timeit.default_timer()
output.execution_time = abs(end - begin)
output.dataframes.append(equations_util.create_equ_sys_df(symbol_list, sympy.Matrix(system.col(system.shape[0]))))
return output
def _decompose(a, indexMap):
n = a.shape[0]
# iterating over columns
for i in range(0, n):
# find maximum magnitude and index in this column
max_ind = _get_max_elem(a, i)
indexMap[i], indexMap[max_ind] = indexMap[max_ind], indexMap[i]
for j in range(i + 1, n):
# store the factor in-place in matrix a
factor = a[indexMap[j], i] / a[indexMap[i], i]
a[indexMap[j], i] = factor
# eliminate the current row by the calculated factor
for k in range(i + 1, n):
a[indexMap[j], k] -= factor * a[indexMap[i], k]
return a, indexMap
def lu_decomp(system: sympy.Matrix, symbol_list):
system = system.as_mutable()
output = Output()
output.title = "LU Decomposition"
begin = timeit.default_timer()
n = system.shape[0]
a = system[:, :n]
b = system[:, n]
indexMap = numpy.array(range(n), dtype=numpy.int)
a, indexMap = _decompose(a, indexMap)
y = _forward_sub(a, b, indexMap)
output.dataframes.append(equations_util.create_equ_sys_df(symbol_list, _back_sub(a.row_join(y), indexMap)))
end = timeit.default_timer()
output.execution_time = abs(end - begin)
return output
def jacobi(A: sympy.Matrix, symbols: list, b=None, max_iter=100, max_err=1e-5, x=None):
"""Jacobi Iterative Method for Solving A System of Linear Equations:
takes a system of linear equations and returns an approximate solution
for the system using Jacobi's approximation.
Keyword arguments:
A: sympy.Matrix -- The augmented matrix representing the system if b = None
else the coefficients matrix. A is an [n, n] matrix.
symbols: list of sympy.Symbol representing the variables' names.
b: sympy.Matrix -- The r.h.s matrix of the system. b is an n-dimensional
vector.
max_iter: int -- The maximum number of iterations to perform.
max_err: float -- The maximum allowed error.
x: sympy.Matrix -- The initial value for the variables. x is an n-dimensional
vector.
return:
1) The n-dimensional vector x containing the final approximate solution.
2) The [n, number_of_iterations] matrix x_hist containing the values
of x during each iteration.
3) The numpy array err_hist containing the values of the error during each iteration.
"""
A = A.as_mutable()
n = len(symbols)
output = Output()
output.title = "Jacobi"
if b is None:
A, b = [A[:, :-1], A[:, -1]]
if x is None:
x = sympy.Matrix.zeros(n, 1)
D = A.multiply_elementwise(sympy.Matrix.eye(n))
x_prev = x[:, :]
err_hist = [float('NaN')]
x_hist = sympy.Matrix(x)
begin = timeit.default_timer()
for _ in range(0, max_iter):
x = D.inv() * (b - (A - D) * x)
x_hist = x_hist.row_join(x)
#print("XHIST:\n", x_hist)
diff = (x - x_prev).applyfunc(abs)
err = numpy.amax(numpy.array(diff).astype(numpy.float64))
err_hist.append(err)
x_prev = x[:, :]
if err < max_err:
break
end = timeit.default_timer()
output.execution_time = abs(end - begin)
output.roots = numpy.array(x[:]).astype(numpy.float64)
output.errors = numpy.append(output.errors, err)
output.dataframes.append(create_dataframe_part2(x_hist, err_hist, symbols))
return output
def gauss_seidel(A: sympy.Matrix, symbols: list, b=None, max_iter=100, max_err=1e-5, x=None):
"""Gauss-Seidel Iterative Method for Solving A System of Linear Equations:
takes a system of linear equations and returns an approximate solution
for the system using Gauss-Seidel approximation.
Keyword arguments:
A: sympy.Matrix -- The augmented matrix representing the system if b = None
else the coefficients matrix. A is an [n, n] matrix.
symbols: list of sympy.Symbol representing the variables' names.
b: sympy.Matrix -- The r.h.s matrix of the system. b is an n-dimensional
vector.
max_iter: int -- The maximum number of iterations to perform.
max_err: float -- The maximum allowed error.
x: sympy.Matrix -- The initial value for the variables. x is an n-dimensional
vector.
return:
1) The n-dimensional vector x containing the final approximate solution.
2) The [n, number_of_iterations] matrix x_hist containing the values
of x during each iteration.
3) The numpy array err_hist containing the values of the error during each iteration.
"""
A = A.as_mutable()
n = len(symbols)
output = Output()
output.title = "Gauss-Seidel"
if b is None:
A, b = [A[:, :-1], A[:, -1]]
if x is None:
x = sympy.Matrix.zeros(n, 1)
x_prev = x[:, :]
err_hist = [float('NaN')]
x_hist = sympy.Matrix(x)
begin = timeit.default_timer()
for _ in range(0, max_iter):
for i in range(0, n):
xi_new = b[i]
for j in range(0, n):
if i != j:
xi_new -= A[i, j] * x[j]
x[i] = xi_new / A[i, i]
x_hist = x_hist.row_join(x)
diff = (x - x_prev).applyfunc(abs)
err = numpy.amax(numpy.array(diff).astype(numpy.float64))
err_hist.append(err)
x_prev = x[:, :]
if err < max_err:
break
end = timeit.default_timer()
output.execution_time = abs(end - begin)
output.roots = numpy.array(x[:]).astype(numpy.float64)
output.errors = numpy.append(output.errors, err)
output.dataframes.append(create_dataframe_part2(x_hist, err_hist, symbols))
return output
|
# @Author: Akash Raj
# @Date: 2020-01-07 12:37:55
# @Last Modified by: Akash Raj
# @Last Modified time: 2020-01-07 12:38:33
#
# https://www.interviewbit.com/problems/power-of-two-integers/
#
# Given a positive integer which fits in a 32 bit signed integer, find if it can be expressed as A^P where P > 1 and A > 0. A and P both should be integers.
#
# since integer are 32bits it has to be less than 2^32 hence only checking power till 32
# anything beyond that is unnecessary
def isPower(self, A):
for p in range(2,33):
# print(p)
a=round(A**(1/p))
# print((str)(p)+" "+(str)(a));
if(a**p==A):
return 1
return 0 |
import test
# this stack implementation assumes that the end of the list
# will hold the top element of the stack. as the stack grows(push)
# new items will be added on the end of the list. pop operations
# will manipulate that same end
class Stack():
# 0(1) append and pop
# will perform in constant time no matter how many items
# are on the stacks
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def pop(self):
return self.items.pop()
def peak():
return self.items[len(self.items)-1]
def push(self, data):
self.items.append(data)
def size(self):
return len(self.items)
def revstring(mystr):
""" uses a stack to reverse characters in a string """
m = Stack()
for letter in mystr:
m.push(letter)
rever = ""
while not m.isEmpty():
rever = rever + m.pop()
return rever
def parChecker(symbolString):
""" implements the Stack class
returns a boolean result as to whether
the string of parentheses is balanced """
s = Stack()
balanced = True
index = 0
opens = '([{'
close = ')]}'
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in opens:
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
# todo
if not opens.index(opens) == close.index(close):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def divideBy2(num):
""" converting decimal numbers to binary numbers """
r = Stack()
while num > 0:
result = num % 2
r.push(result)
num = num // 2
binString = ""
while not r.isEmpty():
binString = binString + str(r.pop())
return binString
def baseConverter(num, base):
""" takes any decimal number and any base between 2 - 16
as parameters """
# help w bases above 9
# stores the digits in their corresponding positions
digits = "0123456789ABCDEF"
# hexadecimal uses ten decimal digits
# along with the first six alphabet characters for the 16 digits
r = Stack()
while num > 0:
result = num % base
r.push(result)
num = num // base
newString = ''
while not r.isEmpty():
# when a remainder is removed from the stack,
# it can be used to index
# into the digit string and the correct resulting
# digit can be appended to the answer.
newString = newString + digits[r.pop()]
return newString
print(baseConverter(25,8))
print(baseConverter(26,26))
print(parChecker('((()))'))
print(parChecker('(()'))
print(divideBy2(42))
# testEqual(revstring('apple'),'elppa')
# testEqual(revstring('x'),'x')
# testEqual(revstring('1234567890'),'0987654321')
|
def ana_of_pal(str):
""" is the word an anagram of a palindrome? """
seen = {}
# count each letter
for letter in word:
cound = seen.get(letter, 0)
seen[letter] = count + 1
# it's a palindrome if the number of odd counts is 0 or 1
seen_an_odd = False
for count in seen.values():
if count %2 != 0:
if seen_an_odd:
return False
seen_an_odd = True
return True
def dec2bin(num, base):
"""Convert a decimal number to binary representation."""
convertString = "0123456789ABCDEF"
if num < base:
return convertString[n]
else:
return dec2bin(n // base, base) + convertString[n%base]
def add_to_zero(lst):
"""Return True if any two ints in a list add to zero else return False
>>> add_to_zero([])
False
>>> add_to_zero([1])
False
>>> add_to_zero([1, 2, 3])
False
>>> add_to_zero([1, 2, 3, -2])
True
"""
if len(lst) == 0:
return False
for item in list_of_ints:
if -item in list_of_ints:
return True
return False
if __name__ == "__main__":
import doctest
# add_to_zero([1, 2, 3])
doctest.testmod(verbose=True) |
""" write a function fib() that takes an integer n
and returns the nth fib number"""
# o(n2)
# each call to fib makes 2 more calls
# draw it out - forms a binary tree
# exponential time cost
# recurrence tree gets twice as big each time u add 1 to n
def fib(n):
if n in [1, 0]:
return n
else:
return fib(n-1) + fib(n-2)
# solution
# 0(n)
class Fibber(object):
def __init__(self):
self.memo = {}
def fib(self, n):
# edge case: negative index
if n < 0:
raise Exception("Index was negative")
# base case: 0 or 1
elif n in [0, 1]:
return n
# see if we've already calculated this
if n in self.memo:
return self.memo[n]
result = self.fib(n - 1) + self.fib(n - 2)
# memoize
self.memo[n] = result
return result
# 0(n)
def fib_iterative(n):
# edge cases:
if n < 0:
raise Exception("Index was negative. No such thing as a negative index in a series.")
elif n in [0, 1]:
return n
prev = 0
prev_prev = 1
for _ in xrange(n):
current = prev + prev_prev
prev_prev = prev
prev = current
return current
|
# 0(n2)
# stop if the lst is sorted
def bubble_sort(lst):
exchanges = True
passnum = len(lst) - 1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if lst[i] > lst[i+1]:
exchanges = True
lst[i], lst[i+1] = lst[i+1], lst[i]
passnum = passnum - 1
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)
|
"""You're given a list that contains the prices of a stock during one trading day,
at 1 minute intervals. The list is chronologically ordered. You want to buy and
sell the stock the same day, and maximize your profit. Write a method that takes
the list and returns the time to buy and time to sell in order to maximize your
profit."""
def stock_prices(stock_prices_yesterday):
# init max profit to buying and selling the first opportunity
max_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0]
min_price = stock_prices_yesterday[0]
if len(stock_prices_yesterday) < 2:
raise IndexError('too few items in list')
for index, curr_price in enumerate(stock_prices_yesterday):
# u cannot buy & sell the first item
if index == 0:
continue
potential_price = curr_price - min_price
# update max profit
max_profit = max(potential_price, max_profit)
# update min price
min_price = min(min_price, curr_price)
return max_profit
stock_prices_yesterday = [10, 7, 5, 8, 11, 9]
print(stock_prices(stock_prices_yesterday))
"""Write a Python method that takes a string S,
and returns a string containing the characters in S
with duplicates removed. For example, if it gets 'ABA%%3',
it should return 'AB%3'."""
# iterative
def isDup(word):
new_str = ''
uniq_letter = set()
for letter in word:
if letter not in uniq_letter:
uniq_letter.add(letter)
new_str = new_str + letter
return new_str
# recursive
# deletes the first occurence of the letter
def isDup_rec(word):
if len(word) == 0:
return word
if word[0] not in word[1:]:
new_word = word[0] + isDup(word[1:])
else:
new_word = isDup(word[1:])
return new_word
word = 'ABA%%3'
print(isDup_rec(word))
print(isDup(word))
|
class Item():
"""The Base Class for all the loot and magical nonsense"""
def __init__(self, name, description, value):
self.name = name
self.description = description
self.value = value
def __str__(self):
return "{}\n=====\n{}\nValue: {}\n".format(self.name, self.description, self.value)
class Torch(Item):
"""To see in... 'Advanced Darkness'..."""
def __init__(self):
super().__init__(name="Torch",
description="TODO: HAVE GIRLFRIED WRITE",
)
class Gold(Item):
"""A very unfortunate schmelting accident..."""
def __init__(self, amt):
self.amt = amt
super().__init__(name="Gold",
description="A round gold coin with a faded figure, and some alien symbols "
"stamped on both sides.",
value=self.amt)
class Weapon(Item):
"""The Base Class for all the pointy Sticks"""
def __init__(self, name, description, value, damage, damageType):
self.damage = damage
self.damageType = damageType
super().__init__(name, description, value)
def __str__(self):
return "{}\n=====\n{}\nValue: {}\nDamage: {}\nDamage Type: {}".format(self.name, self.description, self.value,
self.damage, self.damageType)
class Armour(Item):
"""Something between you and the swords"""
def __init__(self, name, description, value, damageReduction, damageAffinity, damageVulnerability):
self.damageReduction = damageReduction
self.damageAffinity = damageAffinity
self.damageVulnerability = damageVulnerability
super().__init__(name, description, value)
def __str__(self):
return "{}\n=====\n{}\nValue: {}\nDamage Reduction: {}\nDamage Type: {}".format(self.name, self.description, self.value,
self.damageReduction, self.damageAffinity)
class Rock(Weapon):
"""and roll"""
def __init__(self):
super().__init__(name="Rock",
description="A fist sized rock, suitable for bludgeoning.",
value=0,
damage=5,
damageType='Bludgeoning')
class Knife(Weapon):
"""Whats a dungeon crawler without pointy objects?"""
def __init__(self):
super().__init__(name="Knife",
description="A small, cheap kitchen knife. Barely more effective than a rock.",
value=10,
damage=10,
damageType='Piercing')
class M1911(Weapon):
""".45 ACP > 9mm. fite me /k/."""
def __init__(self):
super().__init__(name="M1911",
description="An old reliable sidearm. Strange, the magazine seems stuck, but the gun seems to"
"function anyway. There are some strange symbols etched onto the slide. You can't"
"understand them, but the world 'bottomless' floats through your mind upon reading"
"them",
value=50,
damage=18,
damageType='Ballistic')
class Fists(Weapon):
"""Good 'ol rightie and leftie"""
def __init__(self):
super().__init__(name="Fists",
description="Your balled up hands attached to the ends of your arms",
value=0,
damage=2,
damageType='Bludgeoning')
class Coat(Armour):
"""If its a trench-coat, you're a neckbeard"""
def __init__(self):
super().__init__(name="Coat",
description="It's your old overcoat. It's familiarity provides some comfort.",
value=5,
damageReduction=1,
damageAffinity='Bludgeoning',
damageVulnerability='None')
class SpiderFang(Weapon):
"""shelob"""
def __init__(self):
super().__init__(name="Spider Fang",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damage=2,
damageType='Piercing')
class CultistDagger(Weapon):
"""Draw the lines... Cut the man... Drain the blood..."""
def __init__(self):
super().__init__(name="Cultist Dagger",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damage=8,
damageType='Piercing')
class ExoSkeleton(Armour):
"""fookin boogs"""
def __init__(self):
super().__init__(name="Exo Skeleton",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damageReduction=2,
damageAffinity='Magic',
damageVulnerability='Bludgeoning')
class CultistsRobes(Armour):
"""Spooky Magic Robes"""
def __init__(self):
super().__init__(name="CultistsRobes",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damageReduction=2,
damageAffinity='Magic',
damageVulnerability='Piercing')
class NoArmour(Armour):
"""Bare as the day you were born"""
def __init__(self):
super().__init__(name="None",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damageReduction=0,
damageAffinity='None',
damageVulnerability='None')
class ShoggothTentacle(Weapon):
"""Don't get got."""
def __init__(self):
super().__init__(name="Shoggoth Tentacle",
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damage=14,
damageType='Piercing')
class ChortWhip(Weapon):
"""kinky"""
def __init__(self):
super().__init__(name='Chort Whip',
description="You Shouldn't be seeing this in game. pls leme know on github.",
value=0,
damage=9,
damageType='Bludgeoning')
|
from decimal import *
import platform
import os
import struct
def get_integer_input(prompt):
while True:
try:
res = int(input(prompt + ': \n'))
break
except (ValueError, NameError):
print("Por favor, digite um número inteiro, de acordo com o menu exibido.")
return res
def get_float_input(prompt):
while True:
try:
res = float(input(prompt + ': \n'))
break
except (ValueError, NameError):
print("Digite um número!")
return res
def get_decimal_input(prompt):
while True:
try:
res = Decimal(input(prompt + ': \n'))
break
except (ValueError, NameError):
print("Digite um número!")
return res
def clrscr():
if platform.system() == 'Windows':
os.system('cls')
else:
os.system('clear')
def newline():
print('\n')
def waitForKeypress():
input("Pressione qualquer tecla para continuar")
|
from decimal import *
# Decimal precision.
getcontext().prec = 15
#-----------------------------------------------------------
# Tool to convert GPS coordinates.
# Degrees-minutes-seconds to decimal degree, vice-versa.
#-----------------------------------------------------------
def dms_to_deci_deg(dms_coord):
"""
Helper function to convert degrees/minutes/seconds to decimal degree coordinates.
https://docs.microsoft.com/en-us/office/troubleshoot/excel/convert-degrees-minutes-seconds-angles
"""
degrees = Decimal(dms_coord[0] * 1.0)
minutes = Decimal(dms_coord[1] * 1.0)
seconds = Decimal(dms_coord[2] * 1.0)
deci_coord = degrees + (minutes / 60) + (seconds / 3600)
return deci_coord
def deci_deg_to_dms(deci_deg_coord):
"""
Helper function to convert decimal degree coordinates to degrees/minutes/seconds.
https://docs.microsoft.com/en-us/office/troubleshoot/excel/convert-degrees-minutes-seconds-angles
"""
degrees = int(deci_deg_coord)
minutes = (deci_deg_coord - degrees) * 60.0
seconds = (minutes - int(minutes)) * 60.0
dms_coord = ((abs(degrees), 1), (abs(int(minutes)), 1), (abs(int(seconds*100)), 100))
return dms_coord |
class Solution:
def toLowerCase(self, s: str) -> str:
return s.lower()
# Solved using ascii code
'''
approach:
- check every character of string is Uppercase or not
- if character is upper case then convert it to lowercase
- else do nothing
'''
class Solution:
def toLowerCase(self, s: str) -> str:
lowerStr: str = ''
for i in range(len(s)):
char: str = s[i]
asciiCode: int = ord(char)
if asciiCode > 64 and asciiCode < 91:
lowerStr += chr(asciiCode + 32)
else:
lowerStr += char
return lowerStr
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return 'student object (name = %s)' % self.name
__repr__ = __str__
print (Student('Michael'))
class Fib(object):
def __init__(self):
self.a, self.b = 0,1
# 一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 1000:
raise StopIteration()
return self.a
# 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法:
# >>> list(range(100))[5:10]
# [5, 6, 7, 8, 9]
def __getitem__(self,n):
if isinstance(n,int):
a,b = 1,1
for x in range(n):
a, b = b, a+b
return a
if isinstance(x,slice):
start = n.start
stop = n.stop
if start is None:
start = 0
a,b = 1,1
L =[]
for x in range(stop):
if x >= start:
L.append(a)
a,b = b,a+b
return L
for n in Fib():
print(n)
# 如果需要更精确地控制枚举类型,可以从Enum派生出自定义类:
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
for name, member in Weekday.__members__.items():
print(name, '=>', member, member.value) |
# Functions for running an encryption or decryption algorithm
ENCRYPT = 'e'
DECRYPT = 'd'
# Write your functions after this comment. Do not change the statements above
# this comment. Do not use import, open, input or print statements in the
# code that you submit. Do not use break or continue statements.
def clean_message(msg):
""" (str) -> str
Return a copy of the message that includes only its alphabetical
characters, where each of those characters has been converted to uppercase.
>>> clean_message(I like eat food.)
'ILIKEEATFOOD'
>>> clean_message(?>??!!!23123123)
''
"""
clean_msg = ''
for character in msg:
if character.isalpha():
clean_msg += character.upper()
return clean_msg
def encrypt_letter(letter, keystream_value):
""" (str, int) -> str
Apply the keystream value to the letter to encrypt the letter, and return the result.
>>> encrypt_letter('A',0)
'A'
>>> encrypt_letter('X',23)
'U'
"""
return chr(65 + (ord(letter) - 65 + keystream_value) % 26)
def decrypt_letter(letter, keystream_value):
""" (str, int) -> str
Apply the keystream value to the letter to decrypt the letter, and return the result.
>>> decrypt_letter('B',23)
'E'
>>> decrypt_letter('L',8)
'D'
"""
letter_code = ord(letter) - 65 -keystream_value
if letter_code >= 0:
return chr(65 + letter_code % 26)
else:
return chr (65 + (letter_code + 26))
def swap_cards(deck, index):
""" (list of int, int) -> NoneType
Swap the card at the index with the card that follows it.
Treat the deck as circular: if the card at the index is on the bottom of the deck,
swap that card with the top card.
>>> deck = [0,1,2,3,5,6,7]
swap_cards(deck, 2)
deck = [0,1,3,2,5,6,7]
>>> deck = [0,1,2,3,5,6,7]
swap_cards(deck, 6)
deck = [7,1,2,3,5,6,0]
"""
temp = deck[index]
next_index = (index+1) % len(deck)# ensure the next index is in the range
deck[index] = deck[next_index]
deck[next_index] = temp
def get_small_joker_value(deck):
""" (list of int) -> int
Return the value of the small joker (value of the second highest card)
for the given deck of cards.
>>> deck = [1,2,3,4,5,6]
get_small_joker_value(deck)
'5'
>>> deck = [6,5,4,3,2,1]
get_small_joker_value(deck)
'5'
"""
return max(deck) - 1
def get_big_joker_value(deck):
""" (list of int) -> int
Return the value of the big joker (value of the highest card)
for the given deck of cards.
>>> deck = [1,2,3,4,5,6]
get_big_joker_value(deck)
'6'
>>> deck = [6,5,4,3,2,1]
get_big_joker_value(deck)
'6'
"""
return max(deck)
def move_small_joker(deck):
""" (list of int) -> NoneType
Swap the small joker with the card that follows it. Treat the deck as circular.
>>> deck = [1,2,3,4,5,6]
move_small_joker(deck)
deck = [1,2,3,4,6,5]
>>> deck = [6,5,4,3,2,1]
move_small_joker(deck)
deck = [6,4,5,3,2,1]
"""
index = deck.index(get_small_joker_value(deck))
swap_cards(deck,index)
def move_big_joker(deck):
""" (list of int) -> NoneType
Move the big joker two cards down the deck. Treat the deck as circular.
>>> deck = [1,2,3,4,5,6]
move_big_joker(deck)
deck = [2,6,3,4,5,1]
>>> deck = [6,5,4,3,2,1]
move_small_joker(deck)
deck = [5,4,6,3,2,1]
"""
#swap two times for the big joker
for i in range (2):
index = deck.index(get_big_joker_value(deck))
swap_cards(deck,index)
def triple_cut(deck):
""" (list of int) -> NoneType
Do a triple cut on the deck.
>>> deck = [1,2,3,9,5,6,8,4,7]
triple_cut(deck)
'4,7,9,5,6,8,1,2,3'
>>> deck = [1,4,7,10,13,16,19,22,25,3,6,28,9,12,15,18,21,24,2,27,5,8,11,14,17,20,23,26]
triple_cut(deck)
'5,8,11,14,17,20,23,26,28,9,12,15,18,21,24,2,27,1,4,7,10,13,16,19,22,25,3,6'
"""
#find first and second joker index by comparing the index of the two joker
big_joker_index = deck.index(get_big_joker_value(deck))
small_joker_index = deck.index(get_small_joker_value(deck))
first_joker_index = min(big_joker_index,small_joker_index)
second_joker_index = max(big_joker_index,small_joker_index)
upper_part = deck[:first_joker_index]
middle_part = deck[first_joker_index:second_joker_index+1]
lower_part = deck[second_joker_index+1:]
#swap the position of the cards
new_list = lower_part + middle_part +upper_part
#change the postion in the deck
for i in range(len(new_list)):
deck[i] = new_list[i]
def insert_top_to_bottom(deck):
""" (list of int) -> NoneType
Examine the value of the bottom card of the deck;
move that many cards from the top of the deck to the bottom,
inserting them just above the bottom card. Special case:
if the bottom card is the big joker,
use the value of the small joker as the number of cards.
>>> deck = [4,7,9,5,6,8,1,2,3]
insert_top_to_bottom(deck)
'5,6,8,1,2,4,7,9'
>>> deck = [5,8,11,14,17,20,23,26,28,9,12,15,18,21,24,2,27,1,4,7,10,13,16,19,22,25,3,6]
insert_top_to_bottom(deck)
'23,26,28,9,12,15,18,21,24,2,27,1,4,7,10,13,16,19,22,25,3,5,8,11,14,17,20,6'
"""
v = deck[-1]
l = deck[-1] #the last value of array
# v is equal to the big joker, then change it to small joker
if v == get_big_joker_value(deck):
v = get_small_joker_value(deck)
top = deck[:v]
rest_list = deck[v:-1]
#put the top list to the bottom
new_list = rest_list + top + [l] #use l in case we change the value of v
#change the position in the deck
for i in range(len(new_list)):
deck[i] = new_list[i]
def get_card_at_top_index(deck):
""" (list of int) -> int
Using the value of the top card as an index,
return the card in the deck at that index.
Special case: if the top card is the big joker,
use the value of the small joker as the index.
>>> deck = [4,7,9,5,6,8,1,2,3]
get_card_at_top_index(deck)
'6'
>>> deck = [23,26,28,9,12,15,18,21,24,2,27,1,4,7,10,13,16,19,22,25,3,5,8,11,14,17,20,6]
get_card_at_top_index(deck)
'11'
"""
index = deck[0]
#if the card is the big joker change it to small joker
if index == get_big_joker_value(deck):
index = get_small_joker_value(deck)
return deck[index]
def get_next_keystream_value(deck):
""" (list of int) -> int
This is the function that repeats all five steps of the algorithm
until a valid keystream value is produced.
>>> deck = [1,4,7,10,13,16,19,22,25,28,3,6,9,12,15,18,21,24,27,2,5,8,11,14,17,20,23,26]
get_next_keystream_value(deck)
'11'
>>> deck = [23,26,28,9,12,15,18,21,24,2,27,1,4,7,10,13,16,19,22,25,3,5,8,11,14,17,20,6]
get_next_keystream_value(deck)
'9'
"""
move_small_joker(deck)
move_big_joker(deck)
triple_cut(deck)
insert_top_to_bottom(deck)
keystream_value = get_card_at_top_index(deck)
#keep find keystream value until a valid key value is found
while keystream_value == get_small_joker_value(deck) or keystream_value == get_big_joker_value(deck):
move_small_joker(deck)
move_big_joker(deck)
triple_cut(deck)
insert_top_to_bottom(deck)
keystream_value = get_card_at_top_index(deck)
return keystream_value
def process_messages(deck, msg, command):
""" (list of int, list of str, str) -> list of str
Return a list of encrypted or decrypted messages,
in the same order as they appear in the given list of messages.
Note that the first parameter may also be mutated during a function call.
>>> deck = [1,4,7,10,13,16,19,22,25,28,3,6,9,12,15,18,21,24,27,2,5,8,11,14,17,20,23,26]
msg = ['OXXIKQCPSZXWW']
process_messages(deck,msg,'d')
'['DOABARRELROLL']'
deck = [1,4,7,10,13,16,19,22,25,28,3,6,9,12,15,18,21,24,27,2,5,8,11,14,17,20,23,26]
msg = ['THISISITTHEMASTERSWORD','NOTHISCANTBEITTOOBAD']
process_messages(deck,msg,'e')
'['EQFZSRTEAPNXLSRJAMNGAT','GLCEGMOTMTRWKHAMGNME']'
"""
modified_msg = []
if command == ENCRYPT:
func = encrypt_letter
else:
func = decrypt_letter
for sentence in msg:
new_sentence = ''
for c in sentence:
new_sentence+=func(c,get_next_keystream_value(deck))
modified_msg.append(new_sentence)
return modified_msg
def read_messages(msg_file):
""" (file open for reading) -> list of str
Read and return the contents of the file as a list of messages,
in the order in which they appear in the file. Strip the newline from each line.
"""
return [clean_message(line) for line in msg_file.readlines()]
def is_valid_deck(deck):
""" (list of int) -> bool
Return True if and only if the candidate deck is a valid deck of cards.
>>> deck = [1,2,3,4,5,6,7,8]
is_valid_deck(deck)
'True'
>>> deck == [2,15,64]
is_valid_deck(deck)
'False'
"""
for i in range(1, get_big_joker_value(deck)):
#encuse the cards are consecutive
if i not in deck:
return False
return True
def read_deck(deck_file):
""" (file open for reading) -> list of int
Return True if and only if the candidate deck is a valid deck of cards.
"""
return [int(i) for i in deck_file.read().split()] |
a=[1,2,3,[4,[5,6,[7]],8],[9]]
b=[]
def fun(a):
for i in a:
if type(i)==list:
fun(i)
else:
b.append(i)
print(a)
fun(a)
print(b) |
import random
from node import Node
#######################################################################################################
#######################################################################################################
class Stack:
def __init__(self, limit=1000): # only as an exercise, a limit will be imposed on the number of elements
self.top = None # when a stack is initialized, the reference to the first item points to None
self.size = 0 # Its size starts with zero
self.limit = limit
def __repr__ (self):
stack_string = 'Top ->'
temp = self.top
if self.is_empty() :
return "Empty Stack !!"
while(temp is not None):
if(temp.get_value() is not None): # check is the stack started with a value
stack_string += str(temp.get_value())+" ->"
temp = temp.get_next_node()
stack_string += "None"
return stack_string
def has_space(self): # helper function to check whether there is available space to add new items
return self.limit > self.size
def is_empty(self): # helper function to check if the stack is empty or not
return self.size == 0
def push(self, value): # method to add new elements at the top of the stack
if self.has_space() :
temp = Node(value)
temp.set_next_node(self.top)
self.top = temp
self.size += 1 # Increment stack size by 1
print("New element added at the top of the Stack")
else:
print("All out of space !!")
def pop(self): # method to remove elements from the stack
if self.size > 0:
item_to_remove = self.top
self.top = item_to_remove.get_next_node()
self.size -= 1
print("Element Removed from the top of the Stack")
return item_to_remove.get_value()
else:
print("This stack is empty !!")
def peek(self):
if self.size > 0:
return self.top.get_value()
else:
print("This stack is empty !!")
#######################################################################################################
#######################################################################################################
## TEST
my_stack = Stack(10)
def main():
for i in range(12):
temp = random.randint(1, 100)
my_stack.push(temp)
print(my_stack)
print(my_stack.peek())
for i in range(6):
my_stack.pop()
print(my_stack)
for i in range(7):
my_stack.pop()
print(my_stack)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 5 12:43:39 2019
@author: danielacamacho
"""
from graphics import *
initial_instructions= 'Click on the item where you would like to begin! Here’s a hint: Jed would probably be the best place to start because Jed knows all. \nBe sure to keep track of the letters you are asked to remember at each object, as you will need to scramble these letters at the end when you reach the door in order to leave the classroom!\nClick anywhere on the screen to start playing'
jed = 'JED : This type of scalar object represents real numbers (ex. 3.14, 7.29, etc.). You will want to keep the third letter from this term. Need more information? Go to the screen next!\nClick anywhere on the screen whenever you are done with your turn'
screen = 'SCREEN: This type of loop is used to work through a set of code repeatedly for an unknown number of times, given specified conditions are met. \nIt can also be thought of as repeating “if" statements. You will want to keep the fourth letter of this term. Take a look at the front whiteboard for more information!\nClick anywhere on the screen whenever you are done with your turn'
front_board = 'FRONT BOARD: This type of method takes advantage of the fact that numbers are ordered. These types of searches require an initial low and high end, which gets updated with each guess. \nFor example, if the guess is too low, then that guess becomes the new low end. Same concept goes for the high end. \nTake the new guess to be the average of the low and the high points to get you a point exactly in the middle. Take the 2nd to last letter of this term, then move on to the window to find your next clue!\nClick anywhere on the screen whenever you are done with your turn'
win_drawing = 'WINDOW: This term is used to describe an unordered set of objects, that can not be indexed with a number, but can be indexed with keys. \nYou will want to keep the 7th letter of this term. Head over to the back whiteboard to find your next clue!\nClick anywhere on the screen whenever you are done with your turn'
back_board = 'BACK BOARD: This type of variable is defined at the outermost scope of the program, making it accessible to all functions in the program. You will want to take the 4th letter from this term. \nGo take a look at the table for your next set of hints!\nClick anywhere on the screen whenever you are done with your turn'
table = 'TABLE: Anonymous functions can be written using ______ expressions. You will want to keep the 2nd letter of this term. Go to the door to get your final hint to leave the classroom!\nClick anywhere on the screen whenever you are done with your turn'
#door = 'This non-scalar object holds the following properties: comprised of ordered smaller elements, immutable, delimited by parentheses. You will want to keep the last letter of this term.'
door = "DOOR: Here's a freebie for you: N. You will only be able to leave if you have collected the other clues and have the correct password.\nEnter the password on the console."
text = ''
def get_clue(chosen_element):
'''
Gives chosen clue
Input: chosen_element (str)- element that was selected to reveal clue
Output: text (str) - actual clue ready to draw to window
'''
global initial_instructions
global jed
global screen
global front_board
global win_drawing
global back_board
global table
global door
global text
if chosen_element == 'initial':
text = Text(Point(500, 540), initial_instructions)
elif chosen_element == 'jed':
text = Text(Point(500, 540), jed)
elif chosen_element == 'screen':
text = Text(Point(500, 540), screen)
elif chosen_element == 'front_board':
text = Text(Point(500, 540), front_board)
elif chosen_element == 'win_drawing':
text = Text(Point(500, 540), win_drawing)
elif chosen_element == 'back_board':
text = Text(Point(500, 540), back_board)
elif chosen_element == 'table':
text = Text(Point(500, 540), table)
elif chosen_element == 'door':
text = Text(Point(500, 540), door)
else:
text = Text(Point(500, 540), 'It seems like this is not a clue. You just lost your turn')
return text
def delete_clue():
'''
Undraws text describing clues from window.
No input. No output
'''
global text
text.undraw()
|
#!/usr/bin/env python
#======================================================================#
# Logic-2 #
# Medium boolean logic puzzles -- if else or not. #
#======================================================================#
# make_bricks
# We want to make a row of bricks that is goal inches long. We have a
# number of small bricks (1 inch each) and big bricks (5 inches each).
# Return True if it is possible to make the goal by choosing from the
# given bricks. This is a little harder than it looks and can be done
# without any loops.
def make_bricks(small, big, goal):
# Solve problem negatively. Divide and conquer!
# Fail #1 -- not enough
if 5*big + small < goal:
return False
# Fail #2 -- not enough small
if small < goal % 5:
return False
return True
# lone_sum
# Given 3 int values, a b c, return their sum. However, if one of the
# values is the same as another of the values, it does not count towards
# the sum.
def lone_sum(a, b, c):
sum = 0
if a != b and a != c: sum += a
if b != a and b != c: sum += b
if c != a and c != b: sum += c
return sum
# lucky_sum
# Given 3 int values, a b c, return their sum. However, if one of the
# values is 13 then it does not count towards the sum and values to its
# right do not count. So for example, if b is 13, then both b and c do
# not count.
def lucky_sum(a, b, c):
if a == 13:
return 0
elif b == 13:
return a
elif c == 13:
return a + b
else:
return a + b + c
# no_teen_sum
# Given 3 int values, a b c, return their sum. However, if any of the
# values is a teen -- in the range 13..19 inclusive -- then that value
# counts as 0, except 15 and 16 do not count as a teens. Write a
# separate helper "def fix_teen(n):"that takes in an int value and
# returns that value fixed for the teen rule. In this way, you avoid
# repeating the teen code 3 times (i.e. "decomposition"). Define the
# helper below and at the same indent level as the main no_teen_sum().
fix_teen = lambda n: 0 if ((13 <= n < 15) or (16 < n <= 19)) else n
def no_teen_sum(a, b, c):
return fix_teen(a) + fix_teen(b) + fix_teen(c)
# round_sum
# For this problem, we'll round an int value up to the next multiple of
# 10 if its rightmost digit is 5 or more, so 15 rounds up to 20.
# Alternately, round down to the previous multiple of 10 if its
# rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints,
# a b c, return the sum of their rounded values. To avoid code
# repetition, write a separate helper "def round10(num):" and call it 3
# times. Write the helper entirely below and at the same indent level as
# round_sum().
round10 = lambda n: int(round(n, -1))
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
# close_far
# Given three ints, a b c, return True if one of b or c is "close"
# (differing from a by at most 1), while the other is "far", differing
# from both other values by 2 or more. Note: abs(num) computes the
# absolute value of a number.
def close_far(a, b, c):
if abs(a-b) <= 1:
return (abs(a-c) >= 2) and (abs(b-c) >= 2)
elif abs(a-c) <= 1:
return (abs(a-b) >= 2) and (abs(c-b) >=2)
else:
return False
# make_chocolate
# We want make a package of goal kilos of chocolate. We have small bars
# (1 kilo each) and big bars (5 kilos each). Return the number of small
# bars to use, assuming we always use big bars before small bars.
# Return -1 if it can't be done.
def make_chocolate(small, big, goal):
# First decide if we can use all the big bars
if goal >= 5*big:
left = goal - 5*big
else:
left = goal % 5
# Then return the number of small bars to use
if left == 0:
return left
else:
return left if small >= left else -1
|
#!/usr/bin/env python
#======================================================================#
# List-1 #
# Basic python list problems -- no loops. Use a[0], a[1], ... to #
# access elements in a list, len(a) is the length. #
#======================================================================#
# first_last6
# Given an array of ints, return True if 6 appears as either the first
# or last element in the array. The array will be length 1 or more.
def first_last6(nums):
return nums[0]==6 or nums[-1]==6
# same_first_last
# Given an array of ints, return True if the array is length 1 or more,
# and the first element and the last element are equal.
def same_first_last(nums):
return (len(nums) >= 1) and (nums[0] == nums[-1])
# make_pi
# Return an int array length 3 containing the first 3 digits of pi,
# {3, 1, 4}.
def make_pi():
return [3, 1, 4]
# common_end
# Given 2 arrays of ints, a and b, return True if they have the same
# first element or they have the same last element. Both arrays will be
# length 1 or more.
def common_end(a, b):
return (a[0] == b[0]) or (a[-1] == b[-1])
# sum3
# Given an array of ints length 3, return the sum of all the elements.
def sum3(nums):
return sum(nums)
# rotate_left3
# Given an array of ints length 3, return an array with the elements
# "rotated left" so {1, 2, 3} yields {2, 3, 1}.
def rotate_left3(nums):
return nums[1:] + [nums[0]]
# reverse3
# Given an array of ints length 3, return a new array with the elements
# in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
def reverse3(nums):
return nums[::-1]
# max_end3
# Given an array of ints length 3, figure out which is larger between
# the first and last elements in the array, and set all the other
# elements to be that value. Return the changed array.
def max_end3(nums):
larger = max(nums[0], nums[-1])
return [larger for n in nums]
# sum2
# Given an array of ints, return the sum of the first 2 elements in the
# array. If the array length is less than 2, just sum up the elements
# that exist, returning 0 if the array is length 0.
def sum2(nums):
return sum(nums[:2])
# middle_way
# Given 2 int arrays, a and b, each length 3, return a new array length
# 2 containing their middle elements.
def middle_way(a, b):
return [a[1], b[1]]
# make_ends
# Given an array of ints, return a new array length 2 containing the
# first and last elements from the original array. The original array
# will be length 1 or more.
def make_ends(nums):
return [nums[0], nums[-1]]
# has23
# Given an int array length 2, return True if it contains a 2 or a 3.
def has23(nums):
return (2 in nums) or (3 in nums)
|
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stopwords = list(stopwords.words('english'))
numbers = list(range(0, 100)) #numbers that is identifiers of pages
forumSpecificWords = ['>', '<', '?', '[', ']', '*'] + numbers #special signs
stopwords += forumSpecificWords
print('All tokens in English alphabet:', stopwords)
with open("shakespeare.txt", 'rb') as f:
content = f.read().decode('utf-8')
tokens = word_tokenize(content)
withoutStopWords = [w for w in tokens if w not in stopwords]
for w in tokens:
if w not in stopwords:
withoutStopWords.append(w.strip().lower()) #clean white spaces
# withoutStopWords.append(w.strip().lower())
print(withoutStopWords)
|
import turtle
t = turtle.Turtle()
t.color("cyan")
for side in range(19):
t.forward(side *10)
t.right(120)
|
def word_triangle(word):
length = len(word)
for n in range(length):
print(word[:length-n])
word_triangle("Pineapple")
|
# Example of if/else statement
import turtle
oz = turtle.Turtle()
oz.width(5)
for side in range(4):
if side == 1:
oz.color("white")
else:
oz.color("red")
jack.forward(100)
jack.right(90)
|
# Strings are ordered sequence of characters
# Strings: s = 'Hello world'
# String methods: Upper(), Lower(), Split()
# v1 print('The result was {}'.format(3.14))
# v2 {value:width.precision f} print('The result was {r:1.3f}'.format(r=3.14))
# Lists are ordered sequence of objects (mutable)
# Lists: l = ['STRING', 100, 23.2]
# List methods: Append(), Pop(), Sort(), Reverse()
# Tuples are ordered sequence of objects (immutable)
# Tuples: t = ('a', 'a', 'b')
# Tuple methods: Count() and Index()
# Dictionary is Key-Value pairing that is unordered
# Dictionaries: d = {'v1':1, 'v2':2, 'v3':3}
# Dictionaries methods: Keys(), Values(), Items()
# print(d['v1'])
# 1 - Numbers
print('What is the value of the expression', 4 * (6 + 5))
print('What is the value of the expression', 4 * 6 + 5)
print('What is the value of the expression', 4 + 6 * 5)
print(type(3 + 1.5 + 4))
# Square root
print(4 ** 0.5)
# Square
print(4 ** 2)
# 2 - Strings
s = 'hello'
print(s[1])
# Go from beginning all the way till the end with the step size negative 1
print(s[::-1])
print(s[4])
print(s[-1])
# 3 - Lists
l = ['0', '0', '0']
l2 = [0] * 3
list3 = [1, 2, [3, 4, 'hello']]
print(list3[2][2])
list4 = [5, 3, 4, 6, 1]
list4.sort()
print(list4)
print(sorted(list4))
# 4 - Dictionaries
d = {'simple_key': 'hello'}
print(d['simple_key'])
d = {'k1': {'k2': 'hello'}}
print(d['k1']['k2'])
d = {'k1': [{'nest_key': ['this is deep', ['hello']]}]}
print(d['k1'][0]['nest_key'][1][0])
d = {'k1': [1, 2, {'k2': ['this is tricky', {'tough': [1, 2, ['hello']]}]}]}
print(d['k1'][2]['k2'][1]['tough'][2][0])
# 5 - Tuples
t = ('a', 'a', 'b')
# 6 - Sets
list5 = [1, 2, 2, 33, 4, 4, 11, 22, 3, 3, 2]
print(set(list5))
|
# File name: creditCardValidator.py
# Description: Script for credit card validation
# Author: Juris Tihomirovs
# Date: 28-05-2021
def check_luhn(number):
num_list = []
# Create digit list - iterate through string and add items to list
for num in number:
num_list.append(int(num))
# From end first num till beginning with step size 2
odd_digits = num_list[-1::-2]
# From end second num till beginning with step size 2
even_digits = num_list[-2::-2]
# Starting from the rightmost digit, double the value of every second digit
even_digits = [x * 2 for x in even_digits]
# If doubling of a number results in a two digit number i.e greater than 9(e.g., 6 × 2 = 12), then add the digits
# of the product
even_digits = [x - 9 if x > 9 else x for x in even_digits]
# Now take the sum of all digits
total_sum = sum(even_digits) + sum(odd_digits)
if total_sum % 10 == 0:
print('[Validation OK]:', number)
else:
print('[Validation not OK]', number)
def main():
card_number = input('Enter the card number: ')
check_luhn(card_number)
if __name__ == '__main__':
main()
|
# Goal: Get title of every book with a 2 star rating
import bs4
import requests
base_url = 'http://books.toscrape.com/catalogue/page-{}.html'
res = requests.get(base_url.format(1))
soup = bs4.BeautifulSoup(res.text, 'lxml')
products = soup.select('.product_pod')
example = products[0]
# We can check if something is 2 stars (string call in, example.select(rating)
# 1 - Quick and dirty way
print('star-rating Three' in str(example))
# 2 - is this class present?
# example.select(".star-rating.Three")
# example.select('a')[1]['title'] to grab the book title
# example.select('a')[1]['title']
two_star_titles = []
for n in range(1, 51):
scrape_url = base_url.format(n)
res = requests.get(scrape_url)
soup = bs4.BeautifulSoup(res.text, 'lxml')
# select book html container with class .product_pod
books = soup.select('.product_pod')
for book in books:
# if 'star-rating Two' in str(book)
if len(book.select('.star-rating.Two')) != 0:
book_title = book.select('a')[1]['title']
two_star_titles.append(book_title)
print(two_star_titles)
|
import datetime
mytime = datetime.time(2, 20, 1, 20)
print(mytime)
print(mytime.hour)
print(mytime.minute)
print(mytime.second)
print(mytime.microsecond)
today = datetime.date.today()
print(today)
print(today.year)
print(today.month)
print(today.day)
print(today.ctime())
mydatetime = datetime.datetime(2021, 10, 3, 14, 20, 1)
print(mydatetime)
mydatetime = mydatetime.replace(year=1999)
print(mydatetime)
date1 = datetime.date(2021, 11, 3)
date2 = datetime.date(2020, 11, 3)
date_diff = date1 - date2
print(date_diff)
datetime1 = datetime.datetime(2021, 11, 3, 22, 0)
datetime2 = datetime.datetime(2020, 11, 3, 12, 0)
datetime_diff = datetime1 - datetime2
print(datetime_diff)
|
# File name: collatzConjecture.py
# Description: Start with a number n > 1. Find the number of steps it takes to reach
# 1 using the following process: If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1.
# Author: Juris Tihomirovs
# Date: 28-05-2021
def get_collatz():
user_input = 0
while True:
try:
user_input = int(input("Please enter number n > 1: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Number accepted")
break
steps = 0
# If n is even, divide it by 2
while user_input != 1:
if user_input % 2 == 0:
user_input = user_input / 2
steps += 1
# If n is odd, multiply it by 3 and add 1
else:
user_input = (user_input * 3) + 1
steps += 1
print('Steps taken', steps)
def main():
get_collatz()
if __name__ == '__main__':
main()
|
'''
Created on May 28, 2013
@author: Tsss-Pc1
'''
#Program to Find Factorial of a Number
#5 = 5*4*3*2*1
a = input()
a=int(a)
b=1
for i in range(a):
i=i+1
b=b*i;
#i=i+1
print(b) |
'''
Created on May 28, 2013
@author: Tsss-Pc1
'''
#Program to Check Vowel or Consonant
c=input()
if c=='a' or c=='e' or c=='i' or c=='o' or c=='u':
print(c," is vowel")
else:
print(c," is consonant") |
def operation(str1, str2, set1):
str1 = str1+str2[0]
str2 = str2[1:]
sign = ['+','-','']
for item in sign:
str3 = str1+item
str4 = str3+str2
if str4[-1] == item:
break
add = eval(str4)
if add == 100:
if str4[0] == '+':
set1.add(str4[1:])
else:
set1.add(str4)
operation(str3,str2,set1)
def main(string):
set1 = set()
item = ['+','-','']
str2 = string
str1 =''
for items in item:
operation(items+str1, str2, set1)
print(set1)
print(len(set1))
main('123456789')
|
"""
Challenge
Given a list of integers, can you count and output the number
of times each value appears?
"""
n = int(input().strip())
arr = list(map(int, input().strip().split()))
max_value = max(arr)
buckets = [0]*(max_value+1) #create an array that can include number from 0 to max_value.
for i in range(n):
buckets[arr[i]] += 1
for item in buckets:
print(item, end = ' ')
|
#Ste= p 1
#{}Debug the following program so that it properly takes a users order and outputs the price of the order.
#Step 2
#Edit the existing code and have it print out the items you are ordering as follows...
#Example
# "Coffee x 0"
# "Cake x 2"
# "Tea x 3"
#Step 3
#Have the items you are ordering also output their indavidual cost.
#Example
# "Coffee x 0 : 0.00"
# "Cake x 2 : 5.00"
# "Tea x 3 : 3.6"
listOfOrders = ["Cofee" "Cake" "Tea"]
Price = 0
for i in listOfOrders:
message = "Would you like to buy a str(listOfOrders[i]) Yes / No "
myOrder = str( input(message))
"if myOrder == Yes and i = 1:"
number = int(input("How many would you like"))
for a in range (number
price = price + 2.5
if myOrder == "Yes" and i = 2:
number = int(input("How many would you like?"))
For a in range(number):
price += 5.2
if myOrder == yes and i = 3:
number = int(input("How many would you like? "))
for a in range(number):
price += 1.2
print("Your total price is", price, ".") |
def find_it(seq):
result = [number for number in seq if seq.count(number) % 2 != 0]
return result[0]
print(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5])) |
def count_pairings(n, taken, are_friends):
first_free = None
for i in range(n):
if not taken[i]:
first_free = i
break
if first_free is None:
return 1
ret = 0
for pair_with in range(first_free+1, n):
if not taken[pair_with] and are_friends[first_free][pair_with]:
taken[first_free], taken[pair_with] = True, True
ret += count_pairings(n, taken, are_friends)
taken[first_free], taken[pair_with] = False, False
return ret
if __name__ == '__main__':
n_test = int(input())
while n_test:
n_people, n_friends = list(map(int, input().split()))
taken = [False] * n_people
are_friends = [[False]*n_people for _ in range(n_people)]
friends = list(map(int, input().split()))
for i in range(n_friends):
i, j = friends[2*i], friends[2*i+1]
are_friends[i][j], are_friends[j][i] = True, True
print(count_pairings(n_people, taken, are_friends))
n_test -= 1
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 18:53:05 2019
@author: satbi
"""
def Sum_rec(n):
if n<0:
return n+1
else:
return n+Sum_rec(n-1)
n=int(input("Enter a number to add till 0: "))
print(Sum_rec(n)) |
def check_if_self_dividing(number):
try:
digits = list(map(int, list(str(number))))
for digit in digits:
if number % digit != 0:
return False
return True
except: # some zeros probably or invalid input
return False
def get_self_dividing_numbers(left, right):
list_of_div_num = []
for number in range(left, right + 1):
if check_if_self_dividing(number):
list_of_div_num.append(number)
return list_of_div_num
if __name__ == "__main__":
print(*get_self_dividing_numbers(1, 22))
print(*get_self_dividing_numbers(47, 85))
|
def sign_func(nums):
ans = 1
for num in nums:
ans *= num
if ans == 0:
return 0
elif ans > 0:
return 1
else:
return -1
|
def computepay(h, r):
pay = h * r
if(h > 40):
pay += (h - 40) * (r * .5)
return pay
try:
hours = float(input("Enter in hours: "))
except:
print("Error, you get no hours!")
hours = 0
try:
rate = float(input("Enter in rate: "))
except:
print("Error, you now work for free")
rate = 0
print(computepay(hours, rate))
|
# -*- coding: cp1252 -*-
## =================
## MorseCode.py
## =================
## 2012.09.07
## Justin Whitehouse
##
# -*- coding: cp1252 -*-
## *****************
## Morse Code = INTERNATIONAL Morse Code
## *****************
## -----------------
##
## Program to convert text into morse code.
## e.g. if the user types in:
##
## 'Morse Code'
##
## the program should print
##
## -- --- - -- --- -
##
## -----------------
## =================
##
## How to implement this?
## ----------------------
##
## 1. need a 'master' function (convert?), so that we can do:
##
## >>> MorseCode.convert("Morse Code")
## '-- --- - -- --- - '
##
## 2. function like 'convertCharacter' which takes a single character
## and looks up the morse code string for the character, adds to it
## the 'LETTER_END' character, and gives it back to the first
## function.
##
## 3. so, do something like:
##
## def convert(string):
## morse_out = ''
## for s in string:
## morse_out += convertCharacter(s)
## return morse_out
##
## =================
## -----------------
##
## Timings in Morse Code:
##
# 1 2 3 4 5 6 7 8
# 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
#
# M------ O---------- R------ S---- E C---------- O---------- D------ E
# ===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...=
# ^ ^ ^ ^ ^
# | dah dit | |
# symbol space letter space word space
#
## ------------------
## ------------------
##
## Morse Code Map:
##
## A - | J --- | S | 1 ---- | Period [.] --- | Colon [:] ---
## B - | K -- | T - | 2 --- | Comma [,] ---- | Semicolon [;] ---
## C -- | L - | U - | 3 -- | Question mark [?] -- | Double dash [=] --
## D - | M -- | V - | 4 - | Apostrophe ['] ---- | Plus [+] --
## E | N - | W -- | 5 | Exclamation mark [!] ---- | Hyphen, Minus [-] --
## F - | O --- | X -- | 6 - | Slash [/], Fraction bar -- | Underscore [_] ---
## G -- | P -- | Y --- | 7 -- | Parenthesis open [(] --- | Quotation mark ["] --
## H | Q --- | Z -- | 8 --- | Parenthesis closed [)] ---- | Dollar sign [$] --
## I | R - | 0 ----- | 9 ---- | Ampersand [&], Wait - | At sign [@] ---
MORSE_A="-"
MORSE_B="-"
MORSE_C="--"
MORSE_D="-"
MORSE_E=""
MORSE_F="-"
MORSE_G="--"
MORSE_H=""
MORSE_I=""
MORSE_J="---"
MORSE_K="--"
MORSE_L="-"
MORSE_M="--"
MORSE_N="-"
MORSE_O="---"
MORSE_P="--"
MORSE_Q="---"
MORSE_R="-"
MORSE_S=""
MORSE_T="-"
MORSE_U="-"
MORSE_V="-"
MORSE_W="--"
MORSE_X="--"
MORSE_Y="---"
MORSE_Z="--"
MORSE_0="-----"
MORSE_1="----"
MORSE_2="---"
MORSE_3="--"
MORSE_4="-"
MORSE_5=""
MORSE_6="-"
MORSE_7="--"
MORSE_8="---"
MORSE_9="----"
MORSE_PERIOD="---"
MORSE_COMMA="----"
MORSE_QUSETION="--"
MORSE_APOSTROPHE="----"
MORSE_EXCLAMATION="----"
MORSE_SLASH="--"
MORSE_PAREN_OPEN="---"
MORSE_PAREN_CLOSE="----"
MORSE_AMPERSAND="-"
MORSE_COLON="---"
MORSE_SEMICOLON="---"
MORSE_EQUAL="--"
MORSE_PLUS="--"
MORSE_MINUS="--"
MORSE_UNDERSCORE="---"
MORSE_QUOTATION="--"
MORSE_DOLLAR="--"
MORSE_AT="---"
MORSE_LETTER_END=" " #1 space after each letter
MORSE_SPACE=" " #6 spaces
# letter end + space = 7 spaces between words
## ------------------
TEXT_TO_MC = { "a":MORSE_A, "A":MORSE_A, "b":MORSE_B, "B":MORSE_B, "c":MORSE_C, "C":MORSE_C,
"d":MORSE_D, "D":MORSE_D, "e":MORSE_E, "E":MORSE_E, "f":MORSE_F, "F":MORSE_F,
"g":MORSE_G, "G":MORSE_G, "h":MORSE_H, "H":MORSE_H, "i":MORSE_I, "I":MORSE_I,
"j":MORSE_J, "J":MORSE_J, "k":MORSE_K, "K":MORSE_K, "l":MORSE_L, "L":MORSE_L,
"m":MORSE_M, "M":MORSE_M, "n":MORSE_N, "N":MORSE_N, "o":MORSE_O, "O":MORSE_O,
"p":MORSE_P, "P":MORSE_P, "q":MORSE_Q, "Q":MORSE_Q, "r":MORSE_R, "R":MORSE_R,
"s":MORSE_S, "S":MORSE_S, "t":MORSE_T, "T":MORSE_T, "u":MORSE_U, "U":MORSE_U,
"v":MORSE_V, "v":MORSE_V, "w":MORSE_W, "W":MORSE_W, "x":MORSE_X, "X":MORSE_X,
"y":MORSE_Y, "Y":MORSE_Y, "z":MORSE_Z, "Z":MORSE_Z,
"0":MORSE_0, "1":MORSE_1, "2":MORSE_2, "3":MORSE_3, "4":MORSE_4,
"5":MORSE_5, "6":MORSE_6, "7":MORSE_7, "8":MORSE_8, "9":MORSE_9,
".":MORSE_PERIOD, ",":MORSE_COMMA, "'":MORSE_APOSTROPHE,
"?":MORSE_QUSETION, "!":MORSE_EXCLAMATION, "/":MORSE_SLASH,
"(":MORSE_PAREN_OPEN, ")":MORSE_PAREN_CLOSE, "&":MORSE_AMPERSAND,
":":MORSE_COLON, ";":MORSE_SEMICOLON,
"=":MORSE_EQUAL, "+":MORSE_PLUS, "-":MORSE_MINUS,
"_":MORSE_UNDERSCORE, "\"":MORSE_QUOTATION, "$":MORSE_DOLLAR, "@":MORSE_AT,
0:MORSE_LETTER_END, # every letter should end with this
" ":MORSE_SPACE,
-1:None # if the character in the text cannot be found here, it is mapped to 'None'
# - actually this may be redundant
}
def convertCharacter(char_str):
morse_equiv = ''
try:
morse_equiv += TEXT_TO_MC[char_str]
except KeyError:
morse_equiv += char_str
morse_equiv += TEXT_TO_MC[0]
return morse_equiv
def convert(text_str):
morse_out = ''
for character in text_str:
morse_out += convertCharacter(character)
return morse_out
|
class marksheet:
def __init__(self):
self.Snumber=0
self.Sname=""
self.english=23
self.cs=34
self.maths=33
self.physics=16
self.chemistry=45
def calc(self):
self.t=self.chemistry+self.physics+self.cs+self.maths+self.english
self.p=float((self.t*100)/500)
def Input(self):
self.Snumber=input("Enter the Snumber of students :")
self.Sname=raw_input("Enter the Sname of students :")
self.english=input("Enter the marks of english :")
self.cs=input("Enter the marks of c-s :")
self.maths=input("Enter the marks of maths :")
self.physics=input("Enter the marks of physics :")
self.chemistry=input("Enter the marks of chemistry :")
self.calculate=obj.calc()
def show(self):
print' Report Card'
print'--------------------------------------------------------------------------------'
print' Name :',self.Sname,' RollNumber:',self.Snumber
print' Class:XII',' School:BVM'
print'-------------------------------------------------------------------------------'
print'|SUBJECTS',' MARKS '
print'------------------------------------------------------------------------------'
print "|ENGLISH " ,self.english,' '
print'------------------------------------------------------------------------------'
print "|CS " ,self.cs,' '
print'------------------------------------------------------------------------------'
print "|MATHS ",self.maths,' '
print'------------------------------------------------------------------------------'
print "|PHYSICS ",self.physics,' '
print'------------------------------------------------------------------------------'
print "|CHEMISTRY ",self.chemistry,' '
print'------------------------------------------------------------------------------'
print "|TOTALMARKS ",self.t,' '
print'-------------------------------------------------------------------------------'
print "|PERCENTAGE ",self.p,' '
print'------------------------------------------------------------------------------'
ch=input("Enter the number of students to represent the result:")
n=[]
for i in range(ch):
obj=marksheet()
n.append(obj.Input())
s=input('Enter Snumber To display :')
if s==obj.Snumber:
obj.show()
##while n<=ch:
## obj=marksheet()
## obj.Input()
##
## n+=1
## s=input('Enter snumber to display')
## obj.show()
|
class marksheet:
def __init__(self):
self.Snumber=0
self.Sname=""
self.english=23
self.cs=34
self.maths=33
self.physics=16
self.chemistry=45
def calc(self):
self.t=self.chemistry+self.physics+self.cs+self.maths+self.english
self.p=float((self.t*100)/500)
def Input(self):
self.Snumber=input("Enter the Snumber of students :")
self.Sname=raw_input("Enter the Sname of students :")
self.english=input("Enter the marks of english :")
self.cs=input("Enter the marks of c-s :")
self.maths=input("Enter the marks of maths :")
self.physics=input("Enter the marks of physics :")
self.chemistry=input("Enter the marks of chemistry :")
self.calculate=obj.calc()
def show(self):
print'Name',' Percentage'
print self.Sname, self.p
n=[]
ch=input('Enter the Number Of Students :')
for i in range(ch):
obj=marksheet()
obj.Input()
n.append(marksheet(obj.show())
def insertion(l1):
for i in range(1,len(l1)):
temp=l1[i]
ptr=i-1
while ptr>=0 and l1[ptr]>temp:
l1[ptr+1]=l1[ptr]
ptr-=1
l1[ptr+1]=temp
for i in l1:
print i
insertion(n)
##while n<=ch:
## obj=marksheet()
## obj.Input()
##
## n+=1
## s=input('Enter snumber to display')
## obj.show()
|
def encrypt(x):
y=len(x)
a=0
b=1
q=j=r=" "
while a<y:
q=q+x[a]
a=a+2,
while b<=y:
r=r+x[b]
b=b+2
j=q+r
print q+r
return j
def decrypt(x):
y=len(x)
if y%2==0:
a=y/2
b=y/2
else:
a=((y-1)/2)+1
b=((y-1)/2)
e=x[:a]
o=x[(-b):]
c=1
d=" "
count=0
while c<a:
d=d+e[count]+o[count]
count+=1
c+=1
if (y/2)==0:
print d
else:
d=d+e[-1]+o[-1]
print d,
j=raw_input('e')
a=decrypt(j)
b=encrypt(j)
|
# SET 2:
# This program explores how Linear Regression for classification works,
# using an input set of X = [-1, 1] x [-1, 1].
import math
from random import random
import numpy as np
def getSign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def getOutput(x, y, m, b):
if y > m*x+b:
return 1
else:
return -1
def getF(x1, y1, x2, y2):
m = (y1 - y2) / (x1 - x2)
b = (x1*y2 - x2*y1) / (x1-x2)
return [m, b]
# Use linear regression on input set [-1, 1] x [-1. 1] and target function f.
def LinReg(N):
# Generate two random points in [-1, 1] x [-1. 1]
x1 = random()*2-1
y1 = random()*2-1
x2 = random()*2-1
y2 = random()*2-1
f1 = [x1, y1]
f2 = [x2, y2]
nums = getF(x1, y1, x2, y2)
m1 = nums[0]
b1 = nums[1]
# collection of N randomly generated points and their outputs
X_vector = []
y_vector = []
for i in range(N):
x = random()*2-1
y = random()*2-1
X_vector.append([1.0, x, y])
y_vector.append(getOutput(x, y, m1, b1))
X_matrix = np.matrix(X_vector)
y_matrix = np.matrix.transpose(np.matrix(y_vector))
pseudo_inv = np.matmul(np.linalg.inv(np.matmul(np.matrix.transpose(X_matrix), X_matrix)), np.matrix.transpose(X_matrix))
w = np.matmul(pseudo_inv, y_matrix)
i = 0
count = 0
for x in X_vector:
if (getSign(w[0]*x[0]+w[1]*x[1]+w[2]*x[2]) != y_vector[i]):
count += 1
i += 1
count2 = 0
for i in range(1000):
x = random()*2-1
y = random()*2-1
if (getSign(w[0]*1+w[1]*x+w[2]*y) != getOutput(x, y, m1, b1)):
count2 += 1
return (float(count) / 100.0), (float(count2) / 1000.0)
# Uses weights from Linear Regression as the vector of initial weights for
# the Perceptron Learning Algorithm.
def PLA(N):
# Generate two random points in [-1, 1] x [-1. 1]
x1 = random()*2-1
y1 = random()*2-1
x2 = random()*2-1
y2 = random()*2-1
f1 = [x1, y1]
f2 = [x2, y2]
nums = getF(x1, y1, x2, y2)
m1 = nums[0]
b1 = nums[1]
# collection of N randomly generated points and their outputs
X_vector = []
y_vector = []
for i in range(N):
x = random()*2-1
y = random()*2-1
X_vector.append([1.0, x, y])
y_vector.append(getOutput(x, y, m1, b1))
X_matrix = np.matrix(X_vector)
y_matrix = np.matrix.transpose(np.matrix(y_vector))
pseudo_inv = np.matmul(np.linalg.inv(np.matmul(np.matrix.transpose(X_matrix), X_matrix)), np.matrix.transpose(X_matrix))
w = np.matmul(pseudo_inv, y_matrix)
i = 0
misclassified = [] # set of misclassified points
mis_length = 0
classified = []
class_length = 0
for x in X_vector:
if (getSign(w[0]*x[0]+w[1]*x[1]+w[2]*x[2]) != y_vector[i]):
misclassified.append([x, y_vector[i]])
mis_length += 1
else:
classified.append([x, y_vector[i]])
class_length += 1
iterations = 0
while mis_length > 0:
i = int(random()*mis_length)
w = [w[0] + misclassified[i][1]*misclassified[i][0][0], \
w[1] + misclassified[i][1]*misclassified[i][0][1], \
w[2] + misclassified[i][1]*misclassified[i][0][2]]
classified.append(misclassified[i])
class_length += 1
misclassified.pop(i)
mis_length -= 1
index = 0
while index < class_length:
if getSign(w[0]*classified[index][0][0] + w[1]*classified[index][0][1] \
+ w[2]*classified[index][0][2]) != classified[index][1]:
misclassified.append(classified[index])
mis_length += 1
classified.pop(index)
class_length -= 1
else:
index += 1
iterations += 1
return iterations
def main():
# for Q5 and Q6:
print("N = 100:")
s1 = 0.0
s2 = 0.0
for i in range(1000):
values = LinReg(100)
s1 += values[0]
s2 += values[1]
# finds average E_in
print("E_in:", s1 / 1000.0)
# finds average E_out
print("E_out:", s2 / 1000.0)
# for Q7:
print("N = 10:")
s3 = 0
for i in range(1000):
s3 += PLA(10)
# finds average number of iterations that PLA takes to converge
print("iterations:", float(s3)/1000.0)
if __name__ == "__main__":
main()
|
# SET 1:
# This program explores how the Perceptron Learning Algorithm works.
import math
from random import random
def getSign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def getOutput(x, y, m, b):
if y > m*x+b:
return 1
else:
return -1
def getF(x1, y1, x2, y2):
m = (y1 - y2) / (x1 - x2)
b = (x1*y2 - x2*y1) / (x1-x2)
return [m, b]
# Implements the Perceptron Learning Algorithm for d = 2 on a linear data set.
def PLA(N):
# Generate two random points in [-1, 1] x [-1. 1]
x1 = random()*2-1
y1 = random()*2-1
x2 = random()*2-1
y2 = random()*2-1
f1 = [x1, y1]
f2 = [x2, y2]
nums = getF(x1, y1, x2, y2)
m1 = nums[0]
b1 = nums[1]
# collection of N randomly generated points and their outputs
mis_points = [] # list of misclassified points
for i in range(N):
x = random()*2-1
y = random()*2-1
mis_points.append([[1.0, x, y], getOutput(x, y, m1, b1)])
mis_length = N # length of this list
weight = [0.0, 0.0, 0.0]
class_points = [] # list of properly classified points
class_length = 0 # length of this list
iterations = 0
while mis_length > 0: # while there are still misclassified points
i = int(random()*mis_length)
weight = [weight[0] + mis_points[i][1]*mis_points[i][0][0], \
weight[1] + mis_points[i][1]*mis_points[i][0][1], \
weight[2] + mis_points[i][1]*mis_points[i][0][2]]
class_points.append(mis_points[i])
class_length += 1
mis_points.pop(i)
mis_length -= 1
index = 0
# update list of properly classified points
while index < class_length:
if (getSign(weight[0]*class_points[index][0][0] \
+ weight[1]*class_points[index][0][1] \
+ weight[2]*class_points[index][0][2]) \
!= getSign(class_points[index][1])):
mis_points.append(class_points[index])
mis_length += 1
class_points.pop(index)
class_length -=1
else:
index += 1
iterations += 1
# calculate P(f =/= g):
count = 0
times = 100
for i in range(times):
x = random()*2-1
y = random()*2-1
if (getSign(weight[0]*1 + weight[1]*x + weight[1]*y) \
!= getOutput(x, y, m1, b1)):
count += 1.0
return [iterations, count / float(times)]
def calcAverage(iterations, N, value):
total = 0.0
for i in range(iterations):
total += PLA(N)[value]
return 1.0 * total / iterations
def main():
# for N = 10:
print("N = 10:")
print("iterations: ", calcAverage(1000, 10, 0))
print("probability: ", calcAverage(1000, 10, 1))
# for N = 100:
print("N = 100:")
print("iterations: ", calcAverage(1000, 100, 0))
print("probability: ", calcAverage(1000, 100, 1))
if __name__ == "__main__":
main()
|
# Author: Victor Ding
# -*- coding: utf-8 -*-
# 用线程实现
import threading
import time
def sayhi(name, age, interval):
time.sleep(1)
print("My name is {},I am {} years old".format(name, age))
start_time = time.time()
print("Thread {} started at {}".format(threading.current_thread().getName(), time.ctime(time.time())))
time.sleep(interval)
print("Thread {} stopped at {}".format(threading.current_thread().getName(), time.ctime(time.time())))
print("Thread {} execution time: {}".format(threading.current_thread().getName(), time.time() - start_time))
thread_list = []
for i in range(10):
new_thread = threading.Thread(name="vding{}".format(i), target=sayhi, args=('Victor{}'.format(i), i, i+3))
# new_thread.setDaemon(True)
thread_list.append(new_thread)
print('main thread start......')
for t in thread_list:
t.start()
# t.join(1.0)
s_time = time.time()
# t1 = threading.Thread(name="vding", target=sayhi, args=('Victor', 44))
# t2 = threading.Thread(name="mzhu", target=sayhi, args=('Mary', 38))
#
# # t1.setDaemon(True)
# # t2.setDaemon(True)
# t1.start()
# t2.start()
# t1.join()
#
# print(threading.enumerate())
#
# time.sleep(2)
# print(t2.getName())
# print(t1.is_alive())
#
#
# while True:
# c_time = time.time()
# if c_time - s_time > 10:
# print(c_time - s_time)
# break
print('main thread end......')
# print(f'main thread execution time: {c_time - s_time}')
|
# Author: Victor Ding
list1 = [1,2,3,4,5,6,8,7,9,10,11,12,13,14,15]
print(list1[::-1]) # reverse the list
# 若 step < 0, 则表示从右向左进行切片。 此时,start必须大于end才有结果,否则为空。列如: s[5: 0: -1]的结果是'fedcb'
# 那么,s[::-1]表示从右往左,以步长为1进行切片; s[::2] 表示从左往右以步长为2进行切片
print(list1[::-2])
print(list(reversed(list1)))
print(sorted(list1))
print(list1) |
# Author: Victor Ding
# with open("file.txt","r") as fh:
# for line in fh:
# print(line.strip())
# fh.close()
# with open("file.txt","r") as fh:
# for line in fh.readlines():
# print(line.strip())
# fh.close()
# with open("file.txt","r+") as fh:
# fh.write("TITLE\n")
# l = fh.readlines().copy()
# l.reverse()
# for line in l:
# fh.write(line)
# fh.write("THE END")
with open("file.txt","a+") as fh:
fh.seek(0) # 挪动光标,好像只对read有效
l = fh.readlines().copy()
l.reverse()
for line in l:
fh.write(line)
fh.write("THE END")
fh.close()
with open("file.txt","r") as fh:
for line in fh:
print(line)
fh.close()
|
# Author: Victor Ding
names = ['vmware','sonicwall','red hat','cisco','juniper','palo alto','arista']
names.append('fortinet') # insert at the end
names[2] = 'citrix' # replace specific element
names.insert(2,'extreme')
# How to delete elments
names.remove('arista')
print(names)
names.__delitem__(names.index('juniper'))
del names[names.index('cisco')]
print(names)
names.pop()
names.pop(2)
names.append('sonicwall')
print(names)
print(names[-2:]) # slice
print(names.count('sonicwall'))
names.extend(i for i in range(5))
print(names)
del names
print(names) |
# Author: Victor Ding
#Python 多态
class Animal():
@staticmethod
def act(obj):
obj.action()
class Bird(Animal):
def __init__(self,type):
self.type = type
def action(self):
print("{} 在飞翔".format(self.type))
class Fish(Animal):
def __init__(self,type):
self.type = type
def action(self):
print("{} 在游来游去".format(self.type))
parrot = Bird("Parrot")
flounder = Fish("Flounder")
Animal.act(parrot)
Animal.act(flounder) |
# Author: Victor Ding
# -*- coding: utf-8 -*-
import threading,multiprocessing
import time
def ttt(t):
print("This is Thread {}".format(t))
time.sleep(5)
def sayhi():
tlist = [threading.Thread(target=ttt,args=("name%s"%(str(i)),),) for i in range(3)]
for i in tlist:
i.start()
for i in threading.enumerate():
print("Hello, I am thread:%s" % (i.name))
for i in tlist:
i.join()
# time.sleep(2)
# print("Hello World")
if __name__ == '__main__':
p = multiprocessing.Process(target=sayhi)
p.start() |
# Author: Victor Ding
# -*- coding: utf-8 -*-
class people():
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
print("{} is talking about his age,which is {}".format(self.name, self.age))
def eat(self):
print("{} is eating breakfast".format(self.name))
# 反射:反射就是通过字符串的形式,导入模块;通过字符串的形式,去模块寻找指定函数,并执行。
# 利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
victor = people("Victor", 44)
print(hasattr(victor, 'talk'))
getattr(victor, 'talk')()
setattr(victor, 'age', 22)
getattr(victor, 'talk')()
setattr(victor,'breakfast',eat)
victor.breakfast(victor)
|
# Author: Victor Ding
# -*- coding: utf-8 -*-
import threading
import time
import random
# At start-up, a Thread does some basic initialization and then calls its run() method,
# which calls the target function passed to the constructor. To create a subclass of Thread, override run() to do whatever is necessary.
class People(threading.Thread):
# def __init__(self, group=None, target=None, name=None, #参数的写法看不懂,需要再研究
# args=(), kwargs=None, *, daemon=None):
# # super(People,self).__init__()
# super().__init__(group=group, target=target, name=name,daemon=daemon)
# print(*args)
# self.p_name = args[0]
# self.p_age = args[1]
def __init__(self, p_name, p_age, t_name):
super().__init__()
self.p_name = p_name
self.p_age = p_age
self.setDaemon(True)
self.setName(t_name)
def run(self):
t = random.randint(1, 20)
print("{} is started for {} seconds".format(threading.current_thread().getName(), t))
print("My name is {},I am {} years old".format(self.p_name, self.p_age))
time.sleep(t)
print("{} is stopped".format(threading.current_thread().getName()))
# t1 = People(args=("Victor",44),name="vding",daemon=True)
# t2 = People(args=("mary",38),name="mzhu")
t1 = People("victor", 44, "vding")
t2 = People("victor", 38, "mzhu")
t1.start()
t2.start()
main_thread = threading.main_thread()
for th in threading.enumerate():
if th == main_thread:
continue
if th.isDaemon():
th.join(3)
|
n = int(input('Digite um número '))
a = n - 1
s = n + 1
print('Analisando seu valor {}, seu antecessor {}, e o sucessor é {}'.format(n, a, s))
|
# NewPogi.py
# Python2
# Andresito de Guzman
apptitle = "\n\nAkala mo may itsura ka?"
appcreate = "April 2016"
appseparate = "========================"
appbreak = "\n"
print apptitle
print appcreate
print appseparate
print appbreak
# Ask name
print "Computer: Oi ikaw, oo ikaw nga! Ano pangalan mo?"
pangalan = raw_input('You: Ako si ')
print "Computer: Ahhh.. " + pangalan + " pala pangalan mo."
# Ask age
print "Computer: Edi wow... So teka " + pangalan + " ilang taon ka na?"
age = input('You: ')
# Process age and generate response simple if else logic
if age >= 18:
print ("Computer: Ahhh medyo matanda ka na pa pala eh...")
else:
print ("Computer: Ahhh ang bata mo pa pala eh...")
# Convert int to str for reuse
edad = str(age)
# Ask Location
print "Computer: Sooo saan ka naman nakatira? Saang city? :)"
lugar = raw_input('You: Sa ')
print "Computer: Ahhhh.. taga " + lugar + " ka pala :)"
print "Computer: Ako taga Star City eh hahaha joke lang hahaha"
# Ask If ok
print "Computer: Anyways, " + pangalan + " masaya ko na nakilala kita"
print "Computer: Ayan may kaibigan na ko " + pangalan + " ang name nya tapos nakatira siya sa " + lugar
print "Computer: Cool! Marami pa kong itatanong sayo :) Ok lang ba? :) Lagay mo 1 kung oo at 0 kung hindi :) Alam mo naman computer ako di ba hahaha"
ok1 = input('You: ')
if ok1 > 0:
print ("Computer: Good! :) Kaibigan talaga kita " + pangalan)
else:
print ("Computer: Awww di pala ok eh :( K. bye </3")
print ("Computer: Pero salamat na rin sa oras " + pangalan)
quit()
# Ask My Age compare with simple if else if and else logic
print "Computer: So feeling mo ilang taon na ko?"
myage = input('You: Feeling ko... ')
if myage == 19:
print "Computer: Aba tama ka! Ang galing mo ha :)"
elif myage > 19:
print "Computer: Grabe tanda ko naman hahaha 19 lang ako"
else:
print "Computer: Grabe bata ko naman hahaha 19 na ako no"
# Age Comparison
realage = int(19)
myage = int(edad)
agediff = abs(myage - realage)
if agediff == 0:
print "Computer: Magkaedad pala tayo nu hahaha akalain mo yun"
else:
print "Computer: " + str(agediff) + " years pala yung agwat natin " + edad + " years old ka di ba :)"
print "Computer: Saan naman yung favorite na lugar mo sa " + lugar + "?"
favlugar = raw_input('You: ')
print "Computer: Ahhh.. anung meron dun sa " + favlugar + " at paborito mo yon?"
favelugarwhy = raw_input("You: ")
|
# utility functions
# Use this file for all functions you create and might want to reuse later.
# Import them in the `main.py` script
def mean_ano(x, lat_min, lat_max, lon_min, lon_max, year):
"""
Calculates the mean anomaly from the monthly anomaly values.
The single monthly anomalies were calculated and used in a mean function.
Parameters
----------
x : xarray Dataset
The original dataset
lat_min : number
The minimum latitude extent
lat_max : number
The maximum latitude extent
lon_min : number
The minimum longitude extent
lon_max : number
The maximum longitude extent
year : number
The requested year
Returns
-------
xarray Dataset
"""
#create a month vector
import numpy as np
month = np.arange(1,13)
#create 12 arrays for the 12 month and groupby month
arrayDict = {}
for i in month:
if i < 10:
temp = x.sel(latitude = slice(lat_min,lat_max), longitude = slice(lon_min, lon_max), time = str(year)+"-0"+str(i))
arrayDict["mon"+str(i)] = temp["tg"].groupby("time.month").mean("time")
else:
temp = x.sel(latitude = slice(lat_min,lat_max), longitude = slice(lon_min, lon_max), time = str(year)+"-"+str(i))
arrayDict["mon"+str(i)] = temp["tg"].groupby("time.month").mean("time")
#sum up the monthly anomalies
for i in month:
if i == 1:
annualSum = arrayDict["mon"+str(i)]
else:
annualSum = sum(annualSum, arrayDict["mon"+str(i)]) #use the sum() function because the "+" produce errors
#divide the result by the number of month
anomaly_total = annualSum / 12
return anomaly_total |
#se importa asi: from { file name } import {class name}
from Calculator import Calculator
firstNumber = int(input('enter the first number: '))
secondNumber = int(input('enter the second number: '))
operator = input('enter the operator: ')
c = Calculator()
result = 0
if operator== '*':
result = c.__multiply__(firstNumber,secondNumber)
elif operator == '+':
result = c.__sum__(firstNumber,secondNumber)
elif operator == '-':
result = c.__subtract__(firstNumber,secondNumber)
else:
result = c.__divide__(firstNumber,secondNumber)
print('the result is: ' + str(result)) |
'''
Author: Fernando Luiz Neme Chibli
Date: 2019/04/29
This code will find the least number that has 99% or more of bouncy numbers in its collection.
For performance purpouses, this verification will start at 21780.
'''
from BouncyTools import BouncyList, LeastBouncyFinder
from sys import argv
usage_exemple='\nUsage:\n\tpython %s [integer or float number]'%argv[0]
def byList(current_range,percentage):
#deprecated
bouncy_list_object=BouncyList()
while bouncy_list_object.bouncy_percentage<percentage:
bouncy_list_object.setNewCollection(range(1, current_range))
bouncy_list_object.run()
current_range+=1
print (bouncy_list_object)
def byFinder(percentage):
bouncy_finder=LeastBouncyFinder(percentage)
bouncy_finder.run()
print(bouncy_finder)
def main():
if '-h' in argv:
print(usage_exemple)
return False
try:
percentage=float(argv[1])/100
except IndexError:
percentage=0.99
except ValueError:
print('You must give a number or 99 will be used as percentage. %s'%(usage_exemple))
return False
byFinder(percentage)
input('\n\t(Press return to exit)')
return True
if __name__ == '__main__':
main() |
"""
Evaluate the value of a polynomial using the Horner's method.
"""
class Polynomial:
def __init__(self, coefficients: list):
self._coefficients = coefficients
def evaluate_at(self, x: float) -> float:
result = self._coefficients[0]
for coefficient in self._coefficients[1:]:
result = coefficient + result * x
return result
|
# to run this file, run 'python ls1.2.py demo2.txt' in the console
import random
import sys
# write
f = open("c1/demo2.txt", "w")
i = 0
while i < 50:
f.write("%3d \n" % random.randint(0, 100))
i += 1
f.close()
# read and calculate
if len(sys.argv) != 2: # sys.argv returns a list ["ls1.2.py", "demo2.txt"]
print("Please supply a filename")
raise SystemExit(1)# to run this file, run 'python ls1.2.py demo2.txt' in the console
f = open(sys.argv[1])
lines = f.readlines() # read all input lines into a list of strings
f.close()
fvalues = [float(l) for l in lines] # list comprehension
"""
The codes in the above line is the same as the follow:
fvalues = list()
for l in lines
fvalues.append(float(l))
fvalues = [float(l) for l in f]
also works, because lines in f can be read using for loop
"""
print("The minimum value is ", min(fvalues))
print("The maximum value is ", max(fvalues))
|
from sys import stdin, stdout
# The anormaly unexplained
#stdout.write("Enter your name :")
#name = stdin.readline()
#print("")
#print("You just typed: ", name)
# alternatively
name = input("Enter your name: ")
stdout.write("You just typed: %s" % name)
print("")
|
# Tuples are immutable
# The benefit of immutability is that we can use them as keys in dictionaries,
# and in other locations where an object requires an hash value.
# Behavior cannot be stored in a tuple
# create a tuple
stock = "FB", 75.00, 75.03, 74.90
# or
stock2 = ("FB", 75.00, 75.03, 74.90)
print(stock == stock2)
# parentheses are required for wrapping tuples in other objects
import datetime
def middle(stock, date):
symbol, current, high, low = stock # learn tuple unpacking
return ((high + low) / 2, date)
mid_value, date = middle(("FB", 75.00, 75.03, 74.90), datetime.date(2014, 10, 31))
# access tuple
high = stock2[2]
########### namedtuple
# namedtuple returns a class-like object, which can be instantiated as many times as possible
from collections import namedtuple
Stock = namedtuple("Stock", 'symbol current high low')
stock1 = Stock("FB", 75.00, 75.03, 74.90)
stock2 = Stock(symbol='FB', current=75.00, high=75.30, low=74.90)
stock3 = Stock('FB', current=75.00, high=75.30, low=74.90)
#positional argument can only go ahead of keyword argument
print(stock1.high)
symbol, current, high, low = stock2
# Named tuples are perfect for many data only representations, but it is immutable, so it's difficult to modify
try:
stock1.high = 77.00
except AttributeError as e:
print(e)
# Hashable object usually have a defined algorithm that converts the object in to a unique integer
# for rapid lookup.
######################### use defaultdict
# Using scenario
def letter_frequency(sentence):
frequencies = {}
for letter in sentence:
frequencies.setdefault(letter, 0)
frequencies[letter] += 1
return frequencies
# which has to test if it has a value each time.
# Instead we can use defaultdict
from collections import defaultdict
def letter_frequency2(sentence):
frequencies = defaultdict(int)
for letter in sentence:
frequencies[letter] += 1
return frequencies
# The defaultdict accepts a function in its constructor.
# Whenever a key is accessed that is not already in the dictionary,
# it calls that function, with no parameters, to create a default value
# Here it calls int, which is a constructor of int object.
class TupleCounter():
def __init__(self):
self.counter = 0
def tuple_count(self):
self.counter += 1
return (self.counter, [])
d = defaultdict(TupleCounter().tuple_count)
d['a'][1].append("hello")
d['b'][1].append('world')
d['a'][1].append('kitty')
print(d)
########################### counter
# count specific instances in an iterable
from collections import Counter
def letter_frequency3(sentence):
return Counter(sentence)
|
# ABCs define a set of methods and properties that
# a class must implement in order to be considered a duck-type
# instance of that class
########## Use an abstract base class
# most ABCs live in the collections module
from collections import Container
def main():
print(Container.__abstractmethods__) # get __contains__
help(Container.__contains__) # get signature
if __name__ == "__main__":
main()
class OddContainer:
def __contains__(self, item):
if not isinstance(item, int) or not item % 2:
return False
return True
oc = OddContainer()
def main2():
print(isinstance(oc, Container))
if __name__ == "__main__":
main2()
# Although OddContainer doesn't extend Container, the oc is a Container object
# That is why duck typing is more awesome than classical polymorphism
# The interesting about the Container ABC is that any class implements it
# gets to use the in keyword for free!!!!!!
# in is just the syntax sugar delegates to the __contains__ method
def main3():
print(1 in oc)
print(2 in oc)
print(3 in oc)
print(4 in oc)
print("st" in oc)
if __name__ == "__main__":
main3()
####################### Create an ABC
import abc
# Yi Bu Yi Wai, Jing Bu Jing Xi?
# Create an ABC to document what API the third-party plugins should provide
class MediaLoader(metaclass=abc.ABCMeta):
@abc.abstractmethod
def play(self):
pass
@abc.abstractproperty
def ext(self):
pass
@classmethod # the method can be called on a class instead of an object
def __subclasshook_(cls, C): # let interpreter answer, is C a subclass of this class?
if cls is MediaLoader:
attrs = set(dir(C))
if set(cls.__abstractmethods__) <= attrs: # check if all the abstract methods have been supplied
return True
return NotImplemented # if nay of the conditions have not been met
class Wav(MediaLoader):
pass
class Ogg(MediaLoader):
ext = '.ogg'
def play(self):
pass
def main():
try:
x = Wav()
except TypeError as e:
print(e)
o = Ogg()
if __name__ == "__main__":
main()
# More common object-oriented languages have a clear separation between
# the interface and the implementation of a class.
# For example, some languages provide an explicit interface keyword that
# allows us to define the methods that a class must have without any
# implementation.
# In such an environment, an abstract class is one that provides both an
# interface and a concrete implementation of some but not all methods.
# Any class can explicitly state that it implements a given interface
# Python's ABCs help to supply the functionality of interfaces without
# compromising on the benefits of duck typing.
# Because of the __subclasshook__, we can use duck typing, no need for
# extending the MediaLoader class anymore.
class Ogg2():
ext = ".ogg"
def play(self):
print("This will play an ogg file")
def main2():
print(issubclass(Ogg, MediaLoader))
print(isinstance(Ogg(), MediaLoader))
if __name__ == "__main__":
main2()
|
def divide(a, b):
q = a // b # // returns the quotient
r = a - q * b
return (q, r)
def te():
print("say teeee")
print(divide(5,3))
|
# sets are unordered
# in python, set can hold any hashable objects
# so lists and dictionaries are out
song_library =[('a', "James"), ('b', "Eric"), ('c', "John"), ('d', "Eric")]
artists = set()
for song, artist in song_library:
artists.add(artist)
artists
# There is no built-in syntax for empty set
# but we can use curly braces
# compare:
{'a', 'b'}
{'a':'b'}
for artist in artists:
print("{} plays good music".format(artist))
alphabetical = list(artists)
alphabetical.sort()
alphabetical
seta = {'a', 'b', 'c', 'd', 'e'}
setb = {'d', 'e', 'f', 'g', 'h'}
# symmetric operation
print("All: {}".format(seta.union(setb)))
print("Both: {}".format(seta.intersection(setb)))
print("Either but not both: {}".format(
seta.symmetric_difference(setb)
))
setc = {'a', 'b', 'c'}
# asymmetric operation
setc.issubset(seta)
seta.issuperset(setc)
seta.difference(setb)
setb.difference(seta)
print("*"*20)
'a' in setc
# Sets are much more efficient than lists when
# checking for membership using the in keyword
# for set, it simply hashes the value and checks
# for membership
# This means that a set will find the value in
# the same amount of time no matter how big the
# container is
|
# What is stack? (https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29)
# What is the first argument of each method?
# What is the difference between instance method and static method?
items = [37, 42] # set up an object
items.append(73) # edit the object
print(dir(items)) # dir lists all methods available on the object
# double underscore method
print(items.__repr__())
print(items.__str__())
print(items.__add__([99, 66]))
# build new class
class Stack(object): # Stack inherits from object, the root of all python types
def __init__(self): # initialize a stack
self.stack = []
def push(self, object):
self.stack.append(object)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
def __str__(self):
# make common functions like print, str work in the Stack
return str(self.stack)
s = Stack() # create a stack
s.push("Dave") # push into a stack
s.push(42)
s.push([3, 4, 5])
print(s)
x = s.pop()
print("x is", x)
print("s is", s)
del s
# inherit from list
class Stack(list): # Stack inherit from list
def push(self, object):
self.append(object)
# since Stack inherit from list, it can use any methods of list
# to build its own method
@staticmethod # declare as static method, this is known as a decorator
def privateStack():
# This static method returns a stack containing an element "Treasure"
s = Stack()
s.push("Treasure")
print(s)
return s
Stack.privateStack() # call a static method
|
import math
##
class MyFirstClass:
pass
a = MyFirstClass()
b = MyFirstClass()
##
class Point:
pass
p1 = Point()
p2 = Point()
p1.x = 5
p1.y = 4
p2.x = 3
p2.y = 6
##
class Point:
def reset(self):
self.x = 0
self.y = 0
p = Point()
p.reset()
# which is equivalent to:
Point.reset(p)
# which means that this method can also be a method on the class
# you must explicitly include the `self' in the code, which is p here.
# you must include self in your methods when declares a method in the class
class Point:
def reset():
pass
p = Point()
# 1
try:
p.reset()
except TypeError as e:
print(e)
# 2
try:
Point.reset(p)
except TypeError as e:
print(e)
# 3
try:
Point.reset()
except TypeError as e:
print(e)
## multiple arguments
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt(
(self.x - other_point.x) ** 2
+
(self.y - other_point.y) ** 2)
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
point1.move(3,4)
point1.calculate_distance(point2)
assert(point1.calculate_distance(point2) == point2.calculate_distance(point1))
## Initialization
# __sth__ will be treated by interpreter as a special case
# which has leading and trailing double underscores
class Point:
def __init__(self, x, y):
self.move(x, y)
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt(
(self.x - other_point.x) ** 2
+
(self.y - other_point.y) ** 2)
point = Point(3,5)
point.x
## default arguments
class Point:
def __init__(self, x=0, y=0):
self.move(x, y)
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt(
(self.x - other_point.x) ** 2
+
(self.y - other_point.y) ** 2)
point = Point()
point.x
# But you still can freely assign attribute to the object
point.z = 4
## Constructor
class Point:
def __new__(cls):
pass
# __new__ construct an object, takes (at least) one argument, the class
# Since it is called before the object is constructed,
# so there is no self argument
## docstring
class Point:
"""
Represents a point in two-dimensional geometric coordinates
"""
def __init__(self, x=0, y=0):
'''Initialize the position of a new point. The x and y
coordinates can be specified. If they are not, the
point defaults to the origin.'''
self.move(x, y)
def move(self, x, y):
"Move the point to a new location in 2D space."
self.x = x
self.y = y
def reset(self):
'Reset the point back to the geometric origin: 0, 0'
self.move(0, 0)
def calculate_distance(self, other_point):
"""Calculate the distance from this point to a second
point passed as a parameter.
This function uses the Pythagorean Theorem to calculate
the distance between the two points. The distance is
returned as a float."""
return math.sqrt(
(self.x - other_point.x) ** 2
+
(self.y - other_point.y) ** 2)
help(Point)
|
""" Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position.
print: Print the list.
remove e: Delete the first occurrence of integer.
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of
followed by lines of commands where each command will be of the
types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer,
, denoting the number of commands.
Each line of the
subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
def execute(lst, cmd, *args):
if cmd == 'insert':
lst.insert(int(args[0]), int(args[1]))
elif cmd == 'print':
print(lst)
elif cmd == 'remove':
lst.remove(int(args[0]))
elif cmd == 'append':
lst.append(int(args[0]))
elif cmd == 'sort':
lst.sort()
elif cmd == 'reverse':
lst.reverse()
elif cmd == 'pop':
lst.pop()
else:
print("Command not recognized!")
lst = []
for _ in range(int(input())):
execute(lst, *input().split())
|
a = int(input("Enter a \n"))
b = int(input("Enter b \n"))
#if a>b: print("A is greater than B")
print("B is greater than A") if b>a else print("A is greater than B") |
# # 1. print string within str
# for val in "String":
# if val == "i":
# break
# print(val)
# print("The end")
# # 2. print 1 to 4
# i = 0
# while i < 6:
# x = i + 1
# print(x)
# i = x
# if i == 4:
# break
# print("the end")
# # 3. print string without i
# for val in "string":
# if val == "i":
# continue
# print(val)
# print("the end")
# # 4. print 1 to 6 without 3
# i = 0
# while i < 6:
# i = i + 1
# if i == 3:
# continue
# print(i)
# print("the end")
# # 5. break in while loop
# num_sum = 0
# count = 0
# while count < 10:
# num_sum = num_sum + count
# count = count + 1
# if count == 5:
# break
# print("Sum of first ", count, "integers is: ", num_sum)
# # 6. break in for loop
# numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
# num_sum = 0
# count = 0
# for x in numbers:
# num_sum = num_sum + x
# count = count + 1
# if count == 5:
# break
# print("Sum of first ", count, "integers is: ", num_sum)
# # 7.
# for i in range(9):
# if i > 3:
# break
# print(i)
# print("the end")
# # 8.
# i = 1
# while i < 9:
# print(i)
# if i == 3:
# break
# i += 1
# print("the end")
# #9
# for x in range(4):
# if (x==2):
# continue
# print(x)
# i = 0
# while (True):
# if i < 10:
# i = i + 1
# continue
# print(i+1, end=" ")
# if i == 44:
# break #stop the loop
# i = i+1
#break kore eikhane chole asbe
while True:
take_input = int(input("Give the number: \n"))
if take_input <100:
print("Try Again \n")
continue
if take_input >=100:
print("Congratulations you give the number which is greater than 100")
break |
print("-" * 20)
print(" IGEL DISTRIBUIDORA")
print("-" * 20)
#5 reais serão do custo fixo do ML
#45% é a margem de lucro ideal
#11% é a tributação por venda
#18% é a tarifa do ML
#15% é o custo fixo da IGEL, cálculo feito com base no ticket médio e total de vendas por mês
#Cálculo Markup:
#Markup = 100/100 - (Despesas fixas + Despesas variáveis + Margem de lucro)
while True:
custo_peca=float(input("Qual o custo da peça?\n"))
#Markup para produtos pagos a vista:
markup_avis = 100/(100-(15+0+10))
preco_venda_avis = markup_avis * custo_peca
#Markup para produtos pagos no débito:
markup_debito = 100/(100-(15+2+10))
preco_venda_deb = markup_debito * custo_peca
#Markup para produtos pagos no crédito a vista na máquininha do MP:
markup_avis_cred = 100/(100-(15+5+10))
preco_venda_avis_cred = markup_avis_cred * custo_peca
#Markup para produtos pagos no crédito a vista na máquininha da rede:
markup_avis_cred_rede = 100/(100-(15+3.78+10))
preco_venda_avis_cred_rede = markup_avis_cred_rede * custo_peca
#Markup para produtos parcelados pela maquininha do MP:
markup_parc_MP = 100/(100-(15+11.29+10))
preco_venda_parc_MP = markup_parc_MP * custo_peca
#Markup para produtos parcelados pela rede:
markup_parc_rede = 100/(100-(15+6.59+10))
preco_venda_parc_rede = markup_parc_rede * custo_peca
#Preço de venda Shopee sem nota:
print("O preço mínimo de venda a vista será: " + str("%.2f" %preco_venda_avis ))
print("O preço mínimo de venda no débito será: " + str("%.2f" %preco_venda_deb ))
print("O preço mínimo de venda crédito a vista(MP) será: " + str("%.2f" %preco_venda_avis_cred))
print("O preço mínimo de venda crédito a vista(rede) será: " + str("%.2f" %preco_venda_avis_cred_rede ))
print("O preço mínimo de venda parcelado(MP) será: " + str("%.2f" %preco_venda_parc_MP ))
print("O preço mínimo de venda parcelado(rede) será: " + str("%.2f" %preco_venda_parc_rede ))
yn = input('Aperte "ENTER" para calcular mais um custo ou digite "n" para sair\n')
if yn == "y":
continue
elif yn == "n":
break |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.