text stringlengths 37 1.41M |
|---|
import pymysql
from pymysql.cursors import DictCursor # 导入DictCursor类
def select_id():
mysqlcon = pymysql.connect(host='172.16.102.150', user='aironm', password='aironm', database='school', cursorclass=DictCursor)
try:
# pymsysql.connect的__enter__方法返回的就是cursor;
# 问题:如果不想使用默认的Cursor类,则必须再connect中指定cursorclass类为cursorclass=DictCursor
with mysqlcon as cursor:
select_sql = "SELECT * FROM student WHERE id = %s"
cursor.execute(select_sql, (5,))
# fetchall返回集中所有的元素
return cursor.fetchall()
except Exception as e:
print(e)
# 问题:mysqlcon使用with返回的是cursor;mysqlcon的__exit__只会commit或rollback;而这里没有对cursor使用with;所以cursor也不会关闭释放资源;
finally:
# 释放cursor和mysqlcon的资源
cursor.close()
mysqlcon.close()
if __name__ == '__main__':
# 使用了DictCursor,所以返回的是一个字典
print(select_id()) |
# 问题:给函数参数增加元信息
# 解决:使用参数注解
# Python解释器不会对这些注解添加任何的语义;它们不会被类型检查,运行时跟没有加注解之前的效果也没有任何差距
def add(x:int, y:int) -> int:
return x + y
print(help(add))
# 函数注解存储在函数的__annotations__属性中
print(add.__annotations__)
|
from data_structures.linkedlists.node import Node
class Queue():
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def enqueue(self, value):
node = Node(value)
if self.is_empty():
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def peek(self):
if self.is_empty():
return
return self.head.value
def dequeue(self):
if self.is_empty():
return
deleted = self.head.value
if self.tail == self.head:
self.tail = self.head = None
else:
self.head = self.head.next
self.size -= 1
return deleted
def is_empty(self):
return not self.size
def display(self):
curr = self.head
while curr:
print(curr.value, "->", end=' ')
curr = curr.next
class QueueArray:
def __init__(self) -> None:
self.capacity = 10
self.stack = [None] * self.capacity
self.size = 0
self.rear = -1
self.first = 0
def enqueue(self, value):
if self.is_full():
self.resize()
self.rear += 1
self.stack[self.rear] = value
self.size += 1
def peek(self):
if self.is_empty():
return
return self.stack[self.first]
def dequeue(self):
if self.is_empty():
return
deleted = self.stack[self.first]
self.size -= 1
self.first += 1
return deleted
def is_empty(self):
return not self.size
def display(self):
for i in range(self.first, self.rear + 1):
print(self.stack[i])
def is_full(self):
return self.size == self.capacity
def resize(self):
self.capacity *= 2
temp = [None] * self.capacity
for i in range(self.size):
temp[i] = self.stack[i]
self.stack = temp
|
n = int(input())
a = n
cycle_length = 0
while a != n or cycle_length == 0:
units = a % 10
ten = a // 10
value = (units + ten) % 10
a = units * 10 + value
cycle_length += 1
print(cycle_length)
|
n = int(input())
low = 1
high = n
while 1:
mid = (low + high) // 2
if mid ** 2 == n:
print(mid)
break
elif mid ** 2 > n:
high = mid - 1
elif mid ** 2 < n:
low = mid + 1
'''
import math
print(f"{int(math.sqrt(int(input())))}")
'''
|
# Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
# Example
# to_camel_case("the-stealth-warrior") # returns "theStealthWarrior"
# to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior"
def to_camel_case(text):
if text == '' or text == ' ':
pass
else:
# for index in range(len(text)):
# if text[index] == '_':
# char = text[index+1]
# char.Upper()
# text.replace(index+1, char)
return text
print(to_camel_case('hola_mundo'))
|
import numpy as np
import matplotlib.pyplot as plt
def plotDecisionBoundary(X, y, predictor, nPoints=100):
'''
Takes in a set of 2-d observations X with labels y, and
an instance machine learning algorithm class that has a
predict() method. Creates a grid of points and uses
the given machine learning algorithm to predict
labels on that grid. Plots the grid predictions as a plot
background of decision "zones", then overlays the true
data X, with labels y. Labels are denoted by colors.
Inputs : X as as an (n, 2) numpy array with n=number of
observations and columns as (x, y) to plot
: y as (n,) numpy array with each row being the
label for the corresponding row of X
: predictor as an object of a class with a predict
method, which takes in a (2,) numpy array and
predicts a class label
: nPoints as an int specifying the number of points
along each axis used to plot decision zones
Output : none
'''
# evenly sampled points
xMin, xMax = X[:, 0].min(), X[:, 0].max()
yMin, yMax = X[:, 1].min(), X[:, 1].max()
xx, yy = np.meshgrid(np.linspace(xMin, xMax, nPoints),
np.linspace(yMin, yMax, nPoints))
plt.xlim(xMin, xMax)
plt.ylim(yMin, yMax)
# plot background colors
ax = plt.gca()
Z = predictor.predict(np.vstack([xx.ravel(), yy.ravel()]).T)
Z = Z[:, 0]
Z = Z.reshape(xx.shape)
cs = ax.contourf(xx, yy, Z, cmap='RdBu', alpha=0.25)
cs2 = ax.contour(xx, yy, Z, cmap='RdBu', alpha=0.25)
ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.get_cmap('RdBu'), alpha=0.75)
plt.show()
|
# write your code here
def fill_table_from_input(table_state):
table = []
k = 0
for i in range(3):
table.append([])
for j in range(3):
if table_state[k + j] == '_':
table[i].append(' ')
else:
table[i].append(table_state[k + j])
k += 3
return table
def print_board(table):
print('---------')
for r in table:
print('|', *r, '|')
print('---------')
def evaluate_board(table):
# evaluating rows and checks if there is a draw
board = 0
for i in range(3):
count_x = 0
count_o = 0
for j in range(3):
if table[i][j] == 'X':
count_x += 1
board += 1
if count_x == 3:
return 'X wins'
if table[i][j] == 'O':
count_o += 1
board += 1
if count_o == 3:
return 'O wins'
elif board == 9:
return 'Draw'
# evaluating columns
for i in range(3):
col_x = 0
col_o = 0
for j in range(3):
if table[j][i] == 'X':
col_x += 1
if col_x == 3:
return 'X wins'
if table[j][i] == 'O':
col_o += 1
if col_o == 3:
return 'O wins'
# evaluating diagonals
if table[0][0] == 'X' and table[1][1] == 'X' and table[2][2] == 'X':
return 'X wins'
if table[0][2] == 'X' and table[1][1] == 'X' and table[2][0] == 'X':
return 'X wins'
if table[0][0] == 'O' and table[1][1] == 'O' and table[2][2] == 'O':
return 'O wins'
if table[0][2] == 'O' and table[1][1] == 'O' and table[2][0] == 'O':
return 'O wins'
def determine_move(table):
num_of_x = 0
num_of_o = 0
for i in range(3):
for j in range(3):
if table[i][j] == 'X':
num_of_x += 1
if table[i][j] == 'O':
num_of_o += 1
if num_of_x <= num_of_o:
return 'X'
else:
return 'O'
def get_coordinates(input_coordinates):
try:
column, row = input_coordinates.split()
column, row = int(column), int(row)
if (column < 1) or (column > 3) or (row < 1) or (row > 3):
return 'Coordinates should be from 1 to 3!'
elif the_table[3 - row][column - 1] == "X" or the_table[3 - row][column - 1] == "O":
return 'This cell is occupied! Choose another one!'
else:
return int(column), int(row)
except ValueError:
return 'You should enter numbers!'
the_table = fill_table_from_input(input('Enter the cells: '))
print_board(the_table)
inp = input('Enter the coordinates: ')
the_coordinates = get_coordinates(inp)
while isinstance(the_coordinates, str):
print(the_coordinates)
inp = input('Enter the coordinates: ')
the_coordinates = get_coordinates(inp)
column, row = the_coordinates
the_table[3 - row][column - 1] = determine_move(the_table)
print_board(the_table)
if evaluate_board(the_table) == 'X wins' or evaluate_board(the_table) == 'O wins' or evaluate_board(the_table) == 'Draw':
print(evaluate_board(the_table))
else:
print('Game not finished')
|
"""
Curses-based User Interface for CursMon.
"""
import curses
WHITE = 1
RED = 2
BLUE = 3
YELLOW = 4
CYAN = 5
GREEN = 6
MAGENTA = 7
class UI(object):
"""
The Curses-based User Interface class.
"""
def __init__(self, scr):
self.lines = curses.LINES
self.cols = curses.COLS
self.graphs = []
curses.init_pair(WHITE, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(RED, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(BLUE, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(YELLOW, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(CYAN, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(GREEN, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(MAGENTA, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
self.scr = scr
self.scr.clear()
# plot_x_size = self.cols - 5 - (self.cols % 5)
self.scr.refresh()
def refresh(self, data):
self.lines = curses.LINES
self.cols = curses.COLS
self.display_graphs(data)
self.scr.refresh()
def add_graph(self, graph):
self.graphs.append(graph)
def display_graphs(self, data):
[graph.display(data) for graph in self.graphs]
def wait_for_input_char(self):
return self.scr.getch()
class Graph(object):
def __init__(self, scr, title, top_graph_y=0, top_graph_x=0,
plot_y_size=10, plot_x_size=10, y_step=1, mv_avg_y=7,
show_y=True, show_mv_avg_y=False, bar=False):
self.title = title
self.scr = scr
self.left_margin = 5
self.top_margin = 1
self.top_graph_y = top_graph_y
self.top_graph_x = top_graph_x
self.top_plot_y = top_graph_y + self.top_margin
self.top_plot_x = top_graph_x + self.left_margin
self.plot_y_size = plot_y_size
self.plot_x_size = plot_x_size
self.y_step = y_step
self.mv_avg_y = mv_avg_y
self.show_y = show_y
self.show_mv_avg_y = show_mv_avg_y
self.bar = bar
self.plot_win = curses.newwin(plot_y_size, plot_x_size + 1,
self.top_margin + self.top_graph_y,
self.left_margin + self.top_graph_x)
assert curses.has_colors()
def display(self, data):
self.draw_title()
self.draw_y_axis()
self.draw_x_axis()
self.plot_win.clear()
self.draw_grid()
self.plot_data(data)
self.plot_win.refresh()
self.scr.refresh()
def draw_title(self):
title = self.title
# if self.mv_avg_y is not 1 and self.show_mv_avg_y:
# title = title + " (avg: %d)" % self.mv_avg_y
x = int(((self.plot_x_size - len(title)) / 2) + self.left_margin +
self.top_graph_x)
self.scr.addstr(self.top_graph_y, x, title,
curses.color_pair(WHITE))
extra_space = x - self.left_margin - self.top_graph_x
if extra_space < 3:
return
left = "=" * (extra_space - 2) + "["
self.scr.addstr(self.top_graph_y, self.left_margin + self.top_graph_x,
left, curses.color_pair(MAGENTA))
if (len(self.title) + self.plot_x_size) % 2 == 0:
rounding = 0
else:
rounding = 1
right_x = self.plot_x_size - extra_space + self.left_margin + 1
right = "]" + "=" * (extra_space - 2 + rounding)
self.scr.addstr(self.top_graph_y,
right_x - rounding + self.top_graph_x,
right, curses.color_pair(MAGENTA))
def plot_data(self, data):
if len(data) > self.plot_x_size:
plot_data = data[-self.plot_x_size:]
else:
plot_data = data
for i in range(0, len(plot_data)):
y = int(plot_data[i][self.title])
if self.mv_avg_y == 1:
avg_y = y
else:
avg_y = self.calc_mv_avg_y(i, plot_data)
y = self.round_y(y)
avg_y = self.round_y(avg_y)
if self.show_y:
self.plot(y=y, x=i, char="*", color=GREEN)
if self.bar:
bar_y = y - 1
while bar_y > 0:
self.plot(y=bar_y, x=i, char="|", color=GREEN)
bar_y = bar_y - 1
if self.show_mv_avg_y:
self.plot(y=avg_y, x=i, char="¤", color=BLUE)
# self.scr.addstr(22, 0, "y: %d, data: %d\n" % (y, data[i]))
# self.scr.getch()
def draw_grid(self):
y = 5
while y <= self.plot_y_size:
x = 10
while x <= self.plot_x_size:
self.plot(y, x - 1, "+")
x = x + 10
y = y + 5
def draw_y_axis(self):
for row in range(1, self.plot_y_size + 1):
y = self.plot_y_size - row + self.top_margin + self.top_graph_y
x = self.left_margin - 5 + self.top_graph_x
if row == self.plot_y_size:
char = "^"
else:
if row % 5 == 0:
char = "+"
else:
char = "|"
self.scr.addstr(y, x, "%4d" % (row * self.y_step),
curses.color_pair(WHITE))
self.scr.addstr(y, x + 4, "%s" % char,
curses.color_pair(MAGENTA))
def draw_x_axis(self):
for col in range(0, self.plot_x_size + 1):
y = self.plot_y_size + self.top_margin + self.top_graph_y
x = col + self.left_margin - 1 + self.top_graph_x
if col == self.plot_x_size:
char = ">"
else:
if col % 5 == 0:
char = "+"
else:
char = "-"
self.scr.addch(y, x, char, curses.color_pair(MAGENTA))
# self.scr.addstr(25, 0, "col: %d\n" % col)
# self.scr.addstr(26, 0, " x: %d\n" % x)
# self.scr.getch()
def plot(self, y: int, x: int, char: str, color: int=0):
# self.scr.addstr("y: %d, x: %d\n" % (y, x))
y = self.plot_y_size - y
if y < 0:
y = 0
if x < 0:
x = 0
if y >= self.plot_y_size:
y = self.plot_y_size - 1
if x >= self.plot_x_size:
x = self.plot_x_size - 1
self.plot_win.addstr(y, x, char, curses.color_pair(color))
self.plot_win.refresh()
def calc_mv_avg_y(self, index, data):
if self.mv_avg_y == 1:
return int(data[index][self.title])
if index < (self.mv_avg_y - 1):
min_point = 0
else:
min_point = index - self.mv_avg_y + 1
max_point = index + 1
# data_subset = data[min_point:max_point]
data_subset = []
for row in data[min_point:max_point]:
data_subset.append(int(row[self.title]))
avg = sum(data_subset) / len(data_subset)
return avg
def round_y(self, y):
if y > 0:
y = int((y + self.y_step / 2) / self.y_step)
else:
y = 0
return y
|
import matplotlib.pyplot as plt
import random
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
averageMoney = []
explode = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(12):
averageMoney.append(random.randint(1, 101))
print(averageMoney)
largestValue = max(averageMoney)
for i in range(12):
if (averageMoney[i] == largestValue):
listIndex = i
explode[i] = 0.2
fig1, ax1 = plt.subplots()
ax1.pie(averageMoney, explode=explode, labels=months, autopct='%1.1f%%', shadow=False, startangle=90)
plt.legend(title="Months")
plt.show() |
from random import randint
MyList = list()
i = 0
while i < 50:
Number = randint(1, 10)
print(Number)
MyList.append(Number) #add an item to the end of a list
i += 1
print(MyList)
MyList.remove(3) # remove item from list
print(MyList)
MyList.sort() # sort list accending
print(MyList)
print(min(MyList))
print(max(MyList))
print("weee")
|
def DNA_string(dna):
""" Takes in a DNA string and returns its complementary value """
DNA = list(dna)
complementaryStrandList = []
for char in DNA:
if char == 'A':
complementaryStrandList.append('T')
elif char == 'T':
complementaryStrandList.append('A')
elif char == 'C':
complementaryStrandList.append('G')
elif char == 'G':
complementaryStrandList.append('C')
return ''.join(complementaryStrandList)
print(DNA_string('CATGACCGT'))
|
from sympy import *
#Question1
#part A
#f(x)={3 0<=x<=1}
#f(x)={4 1<x<=3}
#f(x)={5 3<x<=10}
def f(a):
if(0<=a<=1):
return 3
elif(1<a<=3):
return 4
elif(3<a<=10):
return 5
#solution
#As f(x) is mixture of constant functions it will be continuous at every point except points at which constant functions are changing their behaviour that is 1,3
#for 1:
#here we will check left and right limit at 1 if they exists and are equal then f(x) is continous at 1 otherwise discontionous
x=symbols('x')
init_printing(use_unicode=True)
delta=0.000001
LHL=limit(f(1-delta),x,1,'-')
RHL=limit(f(1+delta),x,1,'+')
t=0
if(LHL==RHL):
t=t+1
#for 3
#similarly
h=0
LHL=limit(f(3-delta),x,3,'-')
RHL=limit(f(3+delta),x,3,'+')
print('question partA:')
if(LHL==RHL):
h=h+1
if(h==1 and t==1):
print("the function is contionus at every point")
elif(h==0 and t==1):
print("the function is contionus at every point except at 3")
elif(t==0 and h==1):
print("the function is continous at every point except at 1")
else:
print("the function is contionous at every point except at 1,3")
#Question1
#part B
#f(x)={2*x ; x<0}
#f(x)={0 ; 0<=x<=1}
#f(x)={4*x ; x>1}
def F(a):
if(a<0):
return 2*x
elif(0<=a<=1):
return 0
elif(a>1):
return 4*x
#solution
#As F(x) is mixture of constant and linear polynomial functions it will be continuous at every point except points at which constant functions are changing their behaviour that is 0,1
#for 0:
#here we will check left and right limit at 0 if they exists and are equal then f(x) is continous at 0 otherwise discontionous
x=symbols('x')
init_printing(use_unicode=True)
delta=0.1
LHL=limit(F(0-delta),x,0,'-')
RHL=limit(F(0+delta),x,0,'+')
t=0
if(LHL==RHL):
t=t+1
#for 1
#similarly
h=0
LHL=limit(F(1-delta),x,1,'-')
RHL=limit(F(1+delta),x,1,'+')
print('question partB:')
if(LHL==RHL):
h=h+1
if(h==1 and t==1):
print("the function is contionus at every point")
elif(h==0 and t==1):
print("the function is contionus at every point except at 1")
elif(t==0 and h==1):
print("the function is continous at every point except at 0")
else:
print("the function is contionous at every point except at 0,1")
#Question1
#part C
#f(x)={-2 : x<-1}
#f(x)={2*x : -1<=x<=1}
#f(x)={2 : x>1}
def f(a):
if(a<-1):
return -2
elif(-1<=a<=1):
return 2*x
elif(a>1):
return 2
#solution
#As f(x) is mixture of constant and linear polynomial functions it will be continuous at every point except points at which constant functions are changing their behaviour that is 1,-1
#for -1:
#here we will check left and right limit at -1 if they exists and are equal then f(x) is continous at -1 otherwise discontionous
x=symbols('x')
init_printing(use_unicode=True)
delta=0.000001
LHL=limit(f(-1-delta),x,-1,'-')
RHL=limit(f(-1+delta),x,-1,'+')
t=0
print('question partC:')
if(LHL==RHL):
t=t+1
#for 1
#similarly
h=0
LHL=limit(f(1-delta),x,1,'-')
RHL=limit(f(1+delta),x,1,'+')
if(LHL==RHL):
h=h+1
if(h==1 and t==1):
print("the function is contionus at every point")
elif(h==0 and t==1):
print("the function is contionus at every point except at 1")
elif(t==0 and h==1):
print("the function is continous at every point except at -1")
else:
print("the function is contionous at every point except at -1,1")
|
price = int(input("Please enter price of goods : "))
pay = int(input("Please enter money to pay : "))
exchange = pay - price #คำนวนเงินทอน
#array เก็บชนิดของเงินทอน แบ่งเป็น 500,100,50,20,10,5,2,1
money_type = [500, 100, 50, 20, 10, 5, 2, 1]
#ลูบ หาเงินทอนโดยการหารเอาเศษ โดยไปลูปใน array ว่า
#ถ้าต้องทอนเงิน 768 บาท เราจะเริ่มจาก
#นำ 500 ไปหารเอาเศษ 768 จะได้ 268 ซึ่งหารได้ 1 ที
#หลังจากนั้นนำ เลข 268 ไปหารเอาเศษ โดย 100 ซึ่งค่าที่จะได้คือ 68 และหารได้สองที เหลือ 68 แล้วไปวนค่าเรื่อยๆจนถึง 1 บาท
for t in money_type:
#ถ้ามีเงินทอน ให้ปริ้นใน if
if exchange >= t:
print("{} Baht : {}".format(t, int(exchange / t)))
exchange = exchange % t
#ถ้าไม่มีเงินทอนให้ปริ้น เลข 0
else :
print("{} Baht : 0". format(t))
|
"""
row_data = int(input("pls enter row:"))
print(str(row_data))
for row in range(row_data):
for star in range(row+1):
print('*', end = " ")
print()
from matplotlib import pyplot as plt
plt.bar([1,3,5,7,9],[6,3,4,8,2],label = "One")
plt.bar([2,4,6,8,10],[3,1,2,4,1],label = "Two")
plt.title("data")
plt.ylabel("Number")
plt.xlabel("Height")
plt.legend()
plt.show()
"""
Mycar = {
"brand" : "Honda",
"model" : "CRV",
"year" : 2020
}
print(Mycar.keys())
|
romans = [
["I", 1],
["IV", 4],
["V", 5],
["IX", 9],
["X", 10],
["XL", 40],
["L", 50],
["XC", 90],
["C", 100],
["CD", 400],
["D", 500],
["CM", 900],
["M", 1000],
]
def number_to_roman(n):
# change integer to roman
result = ''
i = len(romans) - 1
while (n > 0):
for k in range(n // romans[i][1]):
result += romans[i][0]
n -= romans[i][1]
i -= 1
return result
def get_row(arr, n):
# get nth row from data
column = len(arr)
row = []
for i in range(column):
# check if the data is available, if not, empty string
if len(arr[i]) < n+1:
row.append("")
else:
row.append(arr[i][n])
return row
def get_max_rows(arr):
# get max rows in the data
column = len(arr)
m = len(arr[0])
for i in range(1, column):
if (m < len(arr[i])):
m = len(arr[i])
return m
|
# 5. Запросите у пользователя значения выручки и издержек фирмы.
# Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки).
# Выведите соответствующее сообщение. Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
# Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
revenue = int(input("Введите значение выручки: "))
cost = int(input("Введите значение убытка: "))
profit = 0 # revenue > cost - Прибыль
if revenue > cost:
print("Финансовый результат работы фирмы - прибыль")
profit = revenue - cost
return_on_revenue = profit / revenue * 100
print(return_on_revenue, "%")
number_of_staff = int(input("Введите количество сотрудников в компании: "))
print("Прибыль фирмы в расчете на одного сотрудника равна: ", profit / number_of_staff)
else:
print(" Финансовым результатом работы фирмы - убыток") |
import time, os, datetime
# Could be irrelevant
def get_leap_years(starting_year):
current_year = time.gmtime(time.time()).tm_year
total = 0
for i in range(starting_year, current_year+1):
if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0):
total += 1
return total
# Calculates time passed since given rocket launched
def get_time(rocket):
# Extract data from time (as stored in voyager1)
launch_date = time.strptime(rocket["launch_date"], "%A %d %B %Y %H:%M:%S")
# Convert time into seconds since Epoch (01/01/1970 00:00:00)
launch_date_in_seconds = time.mktime(launch_date)
# Calculate all leap years since launch
# launch_year = time.gmtime(launch_date_in_seconds).tm_year
# leap_years = get_leap_years(launch_year)
#launch_month = time.gmtime(launch_date_in_seconds).tm_month
#current_month = time.gmtime(time.time()).tm_month
#months = current_month - launch_month
# Subract above amount of seconds from current time (also in seconds since epoch)
seconds = time.time() - launch_date_in_seconds
# // = floor division
# % = modulus division
# Find total amount of minutes
minutes = seconds // 60
# Find left over amount of seconds
seconds = round(seconds % 60)
# Find total amount of hours
hours = minutes // 60
# Find left over amount of minutes
minutes = round(minutes % 60)
# Find total amount of days
days = (hours // 24)
# Find left over amount of hours
hours = round(hours % 24)
# Find total amount of years
years = round(days // 365.25)
# Find left over amount of days
# 365.25 is important to account for leap years
days = round(days % 365.25)
print("############")
print(rocket["name"])
print("------------")
# print to console
print("Years:{}\nDays:{}\nHours:{}\nMinutes:{}\nSeconds:{}".format(years, days, hours, minutes, seconds))#, end="\r")
# ship object literals - to be developed to support external data files
launches = [{"launch_date": "Monday 5 September 1977 12:56:00", "name":"Voyager 1"},{"launch_date": "Saturday 20 August 1977 14:29:00", "name":"Voyager 2"}]
def menu():
continuing = True
while continuing:
list_end = 0
for i in range(len(launches)):
print("{}: {}".format(i+1, launches[i]["name"]))
list_end = i + 2
print("{}: Exit".format(list_end))
choice = input("Please enter the number of your choice\n")
try:
choice = int(choice)
continuing = False
if choice == list_end:
return - 1
else:
return choice - 1
except ValueError:
print("Please only enter a number")
continuing = True
def timer_display(rocket):
continuing = "y"
while continuing == "y":
for i in range(10):
get_time(rocket)
time.sleep(1)
os.system("clear")
continuing = input("Continue? y/n").lower()
# Main program Loop
def main():
while True:
rocket = menu()
if rocket >= 0:
timer_display(launches[rocket])
else:
break
print("Exiting, Goodbye!")
# Run main program
main() |
s = 's = %r;print(s%%s)';print(s%s)
# I, did not think semicolons were allowed in python.
# also %r is useful for printing with the quotation marks
# %% means after substitution you get a single %
|
#!/usr/bin/env python
# coding: utf-8
# # 1. 로또 추첨기
# In[53]:
import random
r = random.sample(range(1,46),6)
print(sorted(r))
# # 2. 구구단
# - 3단, 6단 제외한 구구단
# - 반복문, 조건문사용
# - 문자열 포맷팅을 활용해 2 X 2 = 4 형식으로 출력
#
# In[58]:
count = 2
for j in range(0,8):
if(count != 3 and count != 6):
print()
print('{0} 단'.format(count))
for i in range(1,10):
print('{0} X {1} = {2}'.format(count,i,count*i))
count += 1
# # 3. 리스트 정렬
# - a = [1,1,1,4,2,5,6,7,3,5,6,7,6,7,8,4,3,5,6,7,2,6,2,4,2,9,8,6,7,4,5,3,2]
# - 중복제거 역순으로 정렬
# In[76]:
a = [1,1,1,4,2,5,6,7,3,5,6,7,6,7,8,4,3,5,6,7,2,6,2,4,2,9,8,6,7,4,5,3,2]
a = list(set(a))
a.reverse()
print(a)
# # 4. 동물 분류기
# - 특징 5개 ex) 평균 크기,평균 무게,육식 여부(채식0,잡식1,육식2),사는 곳(물0,물땅1,땅2), 번식(알0,새끼1) 등)
# - 분류할 동물은 최소 4마리 이상 (코끼리,상어,악어,돌고래,개)
# - KNN 혹은 kmeans 알고리즘을 활용
# In[127]:
import numpy as np
from random import *
import matplotlib.pyplot as plt
def distance(x,y):
return np.sqrt(pow((x[0]-y[0]),2)+pow((x[1]-y[1]),2)+pow((x[2]-y[2]),2)+pow((x[3]-y[3]),2)+pow((x[4]-y[4]),2))
elephant = []
shark = []
alligator = []
dolphin = []
dog = []
salamander = []
animal = []
result=[]
lists = []
ok =[]
for i in range(50):
elephant.append([uniform(3.2,4), uniform(4700, 6048),0,2,1,0])
shark.append([uniform(3.4,4.9), uniform(522, 1110),2,0,0,1])
alligator.append([uniform(3.5,6), uniform(200, 1000),2,1,0,2])
dolphin.append([uniform(1.4,8), uniform(45, 6000),1,0,1,3])
dog.append([uniform(0.1,2.1), uniform(2.75, 150),1,2,1,4])
p = elephant + shark + alligator + dolphin + dog
k = input("3,5,7,9,11 중에 넣으시요 제발")
for i in range(0,5):
animal.append([uniform(0.1,8),uniform(2.75,6048),randint(0,2),randint(0,2),randint(0,1)])
for j in range(0,5):
for i in range(0,250):
result.append([distance(animal[j],p[i]),p[i][5]])
lists.append(sorted(result))
for j in range(0,5):
a,b,o,g,w = 0,0,0,0,0
for i in range(0,int(k)):
if (lists[j][i][1] == 0):
a += 1
elif (lists[j][i][1] == 1):
b += 1
elif (lists[j][i][1] == 2):
o += 1
elif (lists[j][i][1] == 3):
g += 1
elif (lists[j][i][1] == 4):
w += 1
ok.append([a,b,o,g,w])
print(ok)
for i in range(0,5):
if (max(ok[i]) == ok[i][0]):
print("elephant")
elif(max(ok[i]) == ok[i][1]):
print("shark")
elif(max(ok[i]) == ok[i][2]):
print("alligator")
elif(max(ok[i]) == ok[i][3]):
print("dolphin")
elif(max(ok[i]) == ok[i][4]):
print("dog")
else:
print("구분이 안되요")
# # 5. 수열 프로그램
# - 100번까지 진행되는 피보나치 수열 프로그램
# In[120]:
r = [1,1]
for i in range(1,100):
r.append(r[-1+i]+r[0+i])
print(r)
|
#CTI-110
# P3HW1 - Color Mixer
# Freddy Ojeda
# June 26 2019
# Prompt the user to enter the first name of the first primary color
# Prompt the user to enter the second name of the second primary color
# Assign the codes of each name of colors
# red equals red, blue equals blue, yellow equals yellow
# Using Boolean logic, implement the if-elif-else statement to make the decision structure for the primary colors to mix.
# Close the block of the stament with an error message letting the user know that a primary color is not written.
primary_color1 = input("Enter primary color 1 :")
primary_color2 = input("Enter primary color 2 :")
red="red"
blue="blue"
yellow="yellow"
if (primary_color1 == red and primary_color2 == blue) or (primary_color1 == blue and primary_color2 == red):
print("When you mix red and blue, you get purple.")
elif (primary_color1 == blue and primary_color2 == yellow) or (primary_color1 == yellow and primary_color2 == blue):
print("When you mix blue and yellow, you get green.")
elif (primary_color1 == yellow and primary_color2 == red) or (primary_color1 == red and primary_color2 == yellow):
print("When you mix yellow and red, you get orange.")
else:
print("Error NO primary color inserted.")
|
from random import randrange
import random
print(
''' ____ _______ _______ _ ______ _____ _ _ _____ _____ _____
| _ \ /\|__ __|__ __| | | ____|/ ____| | | |_ _| __ \ / ____|
| |_) | / \ | | | | | | | |__ | (___ | |__| | | | | |__) | (___
| _ < / /\ \ | | | | | | | __| \___ \| __ | | | | ___/ \___ \
| |_) / ____ \| | | | | |____| |____ ____) | | | |_| |_| | ____) |
|____/_/ \_\_| |_| |______|______|_____/|_| |_|_____|_| |_____/
''')
# http://www.network-science.de/ascii/
# https://www.asciiart.eu/
def check_board(b, taken):
b.sort()
for i in range(len(b)):
num = b[i]
# Check for duplicates so ships do not overlap
if num in taken:
b = [-1]
break
elif num < 0 or num > 99:
b = [-1]
break
# Add statement if number ends in 9 then continues
# If ends in 0 then not valid
elif b[i] % 10 == 9 and i < len(b) - 1:
if b[i+1] % 10 == 0:
b = [-1]
break
if i != 0:
if b[i] != b[i-1]+1 and b[i] != b[i-1]+10:
b = [-1]
break
return b
def get_ship(long, taken):
loop = True
while loop:
ship = []
# user input numbers
print('Place your fleet!')
print('Enter ship of length', long, 'between 0 and 99')
for i in range(long):
boat_num = input('Please enter a number \n')
ship.append(int(boat_num))
# check ship
ship = check_board(ship, taken)
if ship[0] != -1:
taken = taken + ship
break
else:
print('Error, Ship not finished')
return ship
def create_ships_player(taken):
ships = []
boats = [5, 4, 3, 3, 2, 2]
for boat in boats:
ship = get_ship(boat, taken)
ships.append(ship)
return ships, taken
def check_boat(boat, start, direct, taken):
b = []
# up
if direct == 1:
for i in range(boat):
b.append(start - i * 10)
# right
elif direct == 2:
for i in range(boat):
b.append(start + i)
# down
elif direct == 3:
for i in range(boat):
b.append(start + i * 10)
# left
elif direct == 4:
for i in range(boat):
b.append(start - i)
b = check_board(b, taken)
return(b)
# Computer create ships
def create_ships(taken):
ships = []
boats = [5, 4, 3, 3, 2, 2]
for boat in boats:
b = [-1]
while b[0] == -1:
boat_start = randrange(99)
# boat_direct - 1 = up, 2 = right, 3 = down, 4 = left
boat_direct = randrange(1, 4)
# print(boat, boat_start, boat_direct)
b = check_boat(boat, boat_start, boat_direct, taken)
ships.append(b)
taken = taken + b
# print(ships)
return ships, taken
# Create function to show board
def show_board_c(taken):
print(' Computer Board' )
print(' 0 1 2 3 4 5 6 7 8 9')
# Create loop for board
place = 0
for x in range(10):
row = ""
for y in range(10):
character = " _"
if place in taken:
character = " o"
row = row + character
place = place + 1
print(x, row)
def guess_comp(guesses, tactics):
# Create while loop so guess will run until input is valid
loop = 'no'
while loop == 'no':
if len(tactics) > 0:
shot = tactics[0]
else:
shot = randrange(99)
if shot not in guesses:
loop = 'yes'
guesses.append(shot)
break
return shot, guesses
def show_board(hit, miss, sink):
print(' 0 1 2 3 4 5 6 7 8 9')
# Create loop for board
place = 0
for x in range(10):
row = ""
for y in range(10):
character = " _"
if place in miss:
character = " x"
elif place in hit:
character = " o"
elif place in sink:
character = " O"
row = row + character
place = place + 1
print(x, row)
def check_shot(shot, boats, hit, miss, sink):
missed = 0
for i in range(len(boats)):
if shot in boats[i]:
boats[i].remove(shot)
if len(boats[i]) > 0:
hit.append(shot)
missed = 1
else:
sink.append(shot)
missed = 2
# If shot misses, place in list
if missed == 0:
miss.append(shot)
return boats, hit, miss, sink, missed
def calc_tactics(shot, tactics, guesses, hit):
temp = []
if len(tactics) < 1:
temp = [shot-1, shot+1, shot-10, shot+10]
else:
if shot - 1 in hit:
if shot - 2 in hit:
temp = [shot-3, shot+1]
else:
temp = [shot-2, shot+1]
elif shot + 1 in hit:
if shot - 2 in hit:
temp = [shot+3, shot-1]
else:
temp = [shot+2, shot-1]
elif shot - 10 in hit:
if shot - 2 in hit:
temp = [shot-30, shot+10]
else:
temp = [shot-20, shot+10]
elif shot + 10 in hit:
if shot - 2 in hit:
temp = [shot+30, shot-10]
else:
temp = [shot+20, shot-10]
# For longer ships
cand = []
for i in range(len(temp)):
if temp[i] not in guesses and temp[i] < 100 and temp[i] > -1:
cand.append(temp[i])
random.shuffle(cand)
return cand
# Add input for user guess
def guess(guesses):
# Create while loop so guess will run until input is valid
loop = 'no'
while loop == 'no':
shot = input("Please enter your guess between 0 and 99: \n")
# Change shot to int as user input will be number
shot = int(shot)
# Create if statement checking that guess input is valid.
# (between 0 and 99)
if shot < 0 or shot > 99:
print("Sorry, that number is not on the board. Please try again")
# Check if user has used number before
elif shot in guesses:
print("Sorry, you've used that number before. Try another")
else:
loop = 'yes'
break
return shot
def check_if_empty(list_of_lists):
return all([not elem for elem in list_of_lists])
# Define lists and variables for actions
# Board 1 - Computer
hit1 = []
miss1 = []
sink1 = []
guesses1 = []
missed1 = 0
tactics1 = []
taken1 = []
# Board 2 - Player
hit2 = []
miss2 = []
sink2 = []
guesses2 = []
missed2 = 0
tactics2 = []
taken2 = []
# Computer creates board
boats, taken1 = create_ships(taken1)
# User creates board
ships, taken2 = create_ships_player(taken2)
show_board_c(taken2)
# Create loop for game
for i in range(80):
# Player shoots
guesses2 = hit2 + miss2 + sink2
shot2 = guess(guesses2)
ships, hit2, miss2, sink2, missed2 = check_shot(shot2, ships, hit2, miss2, sink2)
show_board(hit2, miss2, sink2)
# Check player shot
# Repeat loop until ships empty
if check_if_empty(boats):
print('Game Finished - You Win', i)
break
# Computer shoots
shot1, guesses1 = guess_comp(guesses1, tactics1)
boats, hit1, miss1, sink1, missed1 = check_shot(shot1, boats, hit1, miss1, sink1)
show_board(hit1, miss1, sink1)
# Check computer shot
if missed1 == 1:
tactics1 = calc_tactics(shot1, tactics1, guesses1, hit1)
elif missed1 == 2:
tactics1 = []
elif len(tactics1) > 0:
tactics1.pop(0)
# Repeat loop until ships empty
if check_if_empty(boats):
print('Game Finished - Computer Wins', i)
break
|
import sys
class PVPC(object):
def __init__(self, day, hour, pcb, cym):
""" Initialize a PVPC object.
Parameters:
day - str - The day of the PVPC [DD/MM/YYYY]
hour - str - The hour of this item [HH:MM]
pcb - float - The €/kWh of the default fare Peninsula, Canarias, Baleares [0,10895]
cym - float - The €/kWh of the default fare Ceuta, Melilla [0,10895]
"""
self.day = day
self.hour = hour
self.pcb = pcb
self.cym = cym
def __str__(self):
return f"{self.day} | {self.hour} | {self.pcb} | {self.cym}"
def get_minimum_consecutives(a_PVPC, type, n_consecutives):
""" Returns the lowest n_consecutive elements in the aPVPC desired type.
Parameters:
a_PVPC - PVPC - Array of PVPC elements
type - str - PCB or CYM
n_consecutive - int - Desired minimum consecutive elements
Return:
Array of PVPC elements.
"""
if not a_PVPC:
raise Exception("Error: aPCPC should not be empty")
if n_consecutives > len(a_PVPC) or n_consecutives < 1:
raise Exception("Error: 0 < n <= len(aPCPC)")
if not (type == "PCB" or type == "CYM"):
raise Exception("Error: type should be PCB or CYM")
min_accumulated = 0
min_accumulated_array = []
min_total = sys.maxsize
min_total_array = []
for j in range(len(a_PVPC)):
for i, value in enumerate(a_PVPC):
if type == "PCB":
min_accumulated += value.pcb
elif type == "CYM":
min_accumulated += value.cym
min_accumulated_array.append(value)
if (i + 1) % n_consecutives == 0:
if min_accumulated < min_total:
min_total = min_accumulated
min_total_array = min_accumulated_array
min_accumulated = 0
min_accumulated_array = []
a_PVPC.pop(0)
return min_total_array
|
# Construct Binary Tree from Inorder and Postorder Traversal
'''
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Output:
3
/ \
9 20
/ \
15 7
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
# Top root is the first item in preorder
if not len(preorder):
return None
val = preorder[0]
del preorder[0]
root = TreeNode(val)
# Left and right can be determined by splitting inorder around val
index = inorder.index(val)
inorder_left = inorder[:index]
inorder_right = inorder[index+1:]
preorder_left = preorder[:len(inorder_left)]
preorder_right = preorder[-len(inorder_right):] \
if len(inorder_right) else []
# Create child nodes recursively
root.left = self.buildTree(preorder_left, inorder_left)
root.right = self.buildTree(preorder_right, inorder_right)
# return node with its children
return root |
# The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
# Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
sum = 0
primes = []
numbers = [0] * 1000000
p = 2
numbers[0] = 1
numbers[1] = 1
while p < 1000000:
if numbers[p] == 0:
primes.append(p)
i = 2 * p
while i < 1000000:
numbers[i] = 1
i += p
p += 1
i = 0
while i < 11:
for j in primes[8:]:
j1 = str(j)
kk = 1
f = 1
while kk < len(j1) and f:
if numbers[int(j1[kk:])] == 1 or numbers[int(j1[:kk])] == 1:
f = 0
kk += 1
if f:
sum += j
i += 1
if i == 11:
break
print(sum) |
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
primes = [2, 3, 5, 7, 11, 13, 17, 19]
num = 1
for i in primes:
p = i
while p * i < 20:
p *= i
num *= p
print(num)
|
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
primes = [2, 3, 5, 7, 11, 13]
p = 14
while len(primes) != 10001:
f = 1
j = 0
n = len(primes)
while (j < n) * f:
if p % primes[j] == 0:
f = 0
j += 1
if f:
primes.append(p)
p += 1
print (primes[10000]) |
# Take the number 192 and multiply it by each of 1, 2, and 3:
# 192 × 1 = 192
# 192 × 2 = 384
# 192 × 3 = 576
# By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)
# The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
# What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?
max = 918273645
for i in range(10000):
if str(i)[0] == '9':
string =''
for j in range(1, 1 + int(9 / len(str(i)))):
string += str(i * j)
if '0' not in string and len(string) == 9 and int(string) > max:
k = set()
for k1 in string:
k.add(k1)
if len(k) == 9:
max = int(string)
print(max) |
# Structure this script entirely on your own.
# See Chapter 8: Strings Exercise 12 for guidance
# Please do provide function calls that test/demonstrate your function
# import here
import string
# body here
def shift_letter(letter, shift):
inAlphabet = 26
if letter.isupper():
start = ord('A') # Rank starts at 65
elif letter.islower():
start = ord('a') # Rank starts at 97
else:
return letter
rankInAlphabet = ord(letter) - start
shiftedLetter = (rankInAlphabet + shift) % inAlphabet + start
return chr(shiftedLetter)
def rotate_word(originalWord, shift):
inchWorm = ""
for letter in originalWord:
inchWorm += shift_letter(letter, shift)
return inchWorm
# call main() here
def main():
print rotate_word("cryptography", 13)
print rotate_word("mother", 7)
print rotate_word("Niners", 40)
print rotate_word("wedding", 2)
if __name__ == '__main__':
main() |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def get_length(self):
length = 0
# We don't want to change head, so we take a ptr
# variable to point to same location as head, and
# modify it
ptr = self.head
while ptr:
length += 1
ptr = ptr.next
return length
def add_node(self, data):
node = Node(data)
if self.head is None:
# if list is empty, make node as head
self.head = node
else:
# We don't want to change head, so we take a ptr
# variable to point to same location as head, and
# modify it
ptr = self.head
# move the ptr till we reach the last node
while ptr.next:
ptr = ptr.next
# assign node to the next of last node
ptr.next = node
def print_list(self):
res = ""
ptr = self.head
while ptr:
res += str(ptr.data) + " ==> "
ptr = ptr.next
res += "None"
print(res)
if __name__ == '__main__':
ll = SinglyLinkedList()
ll.add_node(2)
ll.add_node(3)
ll.add_node(4)
ll.add_node(7)
ll.add_node(10)
ll.print_list()
|
class Node:
def __init__(self, key, data=""):
self.key = key
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, key, data=""):
node = Node(key, data)
if not self.root:
self.root = node
else:
ptr = self.root
while True:
if key <= ptr.key:
if ptr.left:
ptr = ptr.left
else:
ptr.left = node
break
else:
if ptr.right:
ptr = ptr.right
else:
ptr.right = node
break
def get_no_of_child(self, ptr):
if ptr.left and ptr.right:
return 2
elif not ptr.left and not ptr.right:
return 0
else:
return 1
def get_inorder_predecessor(self, prev, ptr):
while ptr.right:
prev = ptr
ptr = ptr.right
return prev, ptr
def remove(self, ptr, key):
if not ptr:
print(f"{key} not present in the tree")
return ptr
if key < ptr.key:
ptr.left = self.remove(ptr.left, key)
return ptr
if key > ptr.key:
ptr.right = self.remove(ptr.right, key)
return ptr
if not ptr.left and not ptr.right:
if ptr == self.root:
self.root = None
return None
if not ptr.left:
if ptr == self.root:
self.root = ptr.right
tmp = ptr.right
return tmp
if not ptr.right:
if ptr == self.root:
self.root = ptr.left
tmp = ptr.left
return tmp
in_pred_parent, in_pred = self.get_inorder_predecessor(ptr, ptr.left)
print(ptr.key, in_pred_parent.key, in_pred.key)
if in_pred_parent != ptr:
in_pred_parent.right = in_pred.left
else:
in_pred_parent.left = in_pred.left
ptr.key = in_pred.key
return ptr
def find(self, ptr, key):
if ptr is None:
raise ValueError(f"{key} not present in the tree")
if key == ptr.key:
return ptr.data
if key < ptr.key:
return self.find(ptr.left, key)
else:
return self.find(ptr.right, key)
def inorder(self, ptr, res):
if ptr:
self.inorder(ptr.left, res)
res.append((ptr.key, ptr.data))
self.inorder(ptr.right, res)
if __name__ == '__main__':
bst = BinarySearchTree()
key_and_name_list = [(5, "Vikash"), (3, "Vishal"), (7, "Adarsh"), (2, "Aniruddha"),
(4, "Pratyush"), (6, "Sarvesh"), (8, "Bhai"), (9, "Altaaf")]
for key, name in key_and_name_list:
bst.insert(key, data=name)
res = []
bst.inorder(bst.root, res)
print(res)
bst.remove(bst.root, 9)
res = []
bst.inorder(bst.root, res)
print(res)
print(bst.find(bst.root, 8))
|
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.iconbitmap("D:/Icon Photo/Itzikgur-My-Seven-Pictures-Canon.ico")
root.geometry("400x400")
my_image = ImageTk.PhotoImage(Image.open("D:/Icon Photo/download (2).png"))
my_image1 = ImageTk.PhotoImage(Image.open("D:/Icon Photo/download2.jfif"))
def next():
Title = Label(root, text = "Image Gallery", font="Algerian 20 bold")
Title.grid(row=0, column=1)
label1 = Label(image = my_image1, width=400)
label1.grid(row=1, columnspan=3,column=0)
b1 = Button(root,text=">>>", command = next)
b1.grid(row=1, column = 2, columnspan = 1)
b1 = Button(root,text="<<<")
b1.grid(row=1, column = 0)
exit_p = Button(root, text= "Exit Programme", command=root.quit)
exit_p.grid(row = 2, column=1)
root.mainloop() |
from typing import List, Dict, Tuple
class Example(object):
def __init__(self, label: int, weight: int):
self.weight = weight
self.label = label
self.features = []
class SentimentExample(Example):
def __init__(self, words: Dict[str, int], label: int, weight: int = 1):
super().__init__(label, weight)
self.words = words
def create_features(self, vocab: List[Tuple[str, int]]) -> None:
for v, __ in vocab:
if v in self.words:
self.features.append(self.words[v])
else:
self.features.append(0)
def __str__(self):
return "{}, {}\n".format(self.features, self.label)
def __repr__(self):
return self.__str__()
|
import roman
from datetime import datetime
def get_base_filename(experiment_info):
"""
get_dat_filename: converts string in dd-mm-yy format with the month stored
as roman numerals into yy_mm_dd format with all integer values
"""
date_raw = experiment_info['Recording Date'].values[0]
# convert roman numerals to string
date_split = date_raw.split('-')
date_split[1] = str(roman.fromRoman(date_split[1]))
# convert to be yy-mm-dd format for .dat files
date = datetime.strptime(' '.join(date_split), "%d %m %y").strftime("%y-%m-%d")
return date
|
# Loop over keys
# user = {
# 'fname': 'Foo',
# 'lname': 'Bar',
# }
#
# for k in user.keys():
# print(k)
#
# # lname
# # fname
#
# for k in user.keys():
# print("{} -> {}".format(k, user[k]))
#
# # lname -> Bar
# # fname -> Foo
##########################
# Loop using items
people = {
"foo" : "123",
"bar" : "456",
"qux" : "789",
}
for name, uid in people.items():
print("{} => {}".format(name, uid))
# foo => 123
# bar => 456
# qux => 789
user = {
'fname': 'Foo',
'lname': 'Bar',
}
for t in user.items(): # returns tuples
print("{} -> {}".format(t[0], t[1]))
#print("{} -> {}".format(*t))
# lname -> Bar
# fname -> Foo |
# Write a script that will ask for the sides of a rectangular and print out the area.
# Provide error messages if either of the sides is negative.
# 编写脚本,询问矩形的边并打印出该区域。 如果任何一方为负,则提供错误消息。
def print_rectangular(x, y):
for i in range(x):
print("+", end=" ")
print()
width = y - 2
lenth = x - 2
for i in range(width):
print("+", end=" ")
for j in range(lenth):
print(" ", end=" ")
print("+")
for i in range(x):
print("+", end=" ")
def print_area(x, y):
print("\n矩形的面积为:", x * y)
print("请输入矩形的边长")
x = int(input("矩形的长:"))
y = int(input("矩形的宽:"))
print("打印出该矩形:")
if x <= 0 | y < 0:
print("边长不能为负")
print_rectangular(x, y)
print_area(x, y) |
# create the grid of points
# for i in range(30,0, -1):
# print("P{} = (10, 10)".format(i))
# create a number to count every element
# for i in range(1,31):
# print("F{} = 0".format(i))
# print("SP{} = 0".format(i))
# print("H{} = 0".format(i))
# print("PS{} = 0".format(i))
# print("S{} = 0".format(i))
#
# print("M{} = 0".format(i))
# print("Pk{} = 0".format(i))
# print("BS{} = 0 \n".format(i))
#to Delete all these points
# print("Delete(F{})".format(i))
# print("Delete(SP{})".format(i))
# print("Delete(H{})".format(i))
# print("Delete(PS{})".format(i))
# print("Delete(S{})".format(i))
#
# print("Delete(M{})".format(i))
# print("Delete(Pk{})".format(i))
# print("Delete(BS{}) \n".format(i))
# create a list of number to count every element
# listF = []
# listSP = []
# listH = []
# listPS = []
# listS = []
# listM = []
# listPk = []
# listBS = []
# for i in range(1,31):
# listF.append("F{}".format(i))
# listSP.append("SP{}".format(i))
# listH.append("H{}".format(i))
# listPS.append("PS{}".format(i))
# listS.append("S{}".format(i))
# listM.append("M{}".format(i))
# listPk.append("Pk{}".format(i))
# listBS.append("BS{}".format(i))
# listF.append(0)
# listSP.append(0)
# listH.append(0)
# listPS.append(0)
# listS.append(0)
# listM.append(0)
# listPk.append(0)
# listBS.append(0)
#
# print(listF)
# print(listSP)
# print(listH)
# print(listPS)
# print(listS)
# print(listM)
# print(listPk)
# print(listBS)
# script inside every polygon
# for i in range(1,31):
# print("If(q==16, If(addMalls == true && Element(listF, {}) == 0 && Element(listSP, {}) == 0 && Element(listH, {}) == 0 && Element(listPS, {}) == 0 && Element(listS, {}) == 0, SetValue[listM,{}, 1], SetValue[listM,{}, 0]))".format(i, i, i, i, i, i, i))
# print("If(q==16, If(addParks == true && Element(listF, {}) == 0 && Element(listSP, {}) == 0 && Element(listH, {}) == 0 && Element(listPS, {}) == 0 && Element(listS, {}) == 0, SetValue[listPk,{}, 1], SetValue[listPk,{}, 0]))".format(i, i, i, i, i, i, i))
# print("If(q==16, If(addBusStops == true && Element(listF, {}) == 0 && Element(listSP, {}) == 0 && Element(listH, {}) == 0 && Element(listPS, {}) == 0 && Element(listS, {}) == 0, SetValue[listBS, {}, 1], SetValue[listBS, {}, 0]))".format(i, i, i, i, i, i, i))
#
# print("If(q==15, If(addFarms == true, SetValue[listF, {}, 1], SetValue[listF, {}, 0]))".format(i, i))
# print("If(q==15, If(addSolarPanels == true, SetValue[listSP, {}, 1], SetValue[listSP, {}, 0]))".format(i, i))
# print("If(q==15, If(addHospitals == true, SetValue[listH, {}, 1], SetValue[listH, {}, 0]))".format(i, i))
# print("If(q==15, If(addPS == true, SetValue[listPS, {}, 1], SetValue[listPS, {}, 0]))".format(i, i))
# print("If(q==15, If(addSchools == true, SetValue[listS, {}, 1], SetValue[listS, {}, 0]))".format(i, i))
#
# print("If(remove == true, {{SetValue[listF, {}, 0], SetValue[listSP, {}, 0], SetValue[listH, {}, 0], SetValue[listPS, {}, 0], SetValue[listPS, {}, 0], SetValue[listM,{}, 0], SetValue[listPk,{}, 0], SetValue[listBS, {}, 0]}})\n".format(i, i, i, i, i, i, i, i))
# print("If(q==16, If(addMalls == true && F{} == 0 && SP{} == 0 && H{} == 0 && PS{} == 0 && S{} == 0, SetValue[M{}, 1], SetValue[M{}, 0]))".format(i, i, i, i, i, i, i))
# print("If(q==16, If(addParks == true && F{} == 0 && SP{} == 0 && H{} == 0 && PS{} == 0 && S{} == 0, SetValue[Pk{}, 1], SetValue[Pk{}, 0]))".format(i, i, i, i, i, i, i))
# print("If(q==16, If(addBusStops == true && F{} == 0 && SP{} == 0 && H{} == 0 && PS{} == 0 && S{} == 0, SetValue[BS{}, 1], SetValue[BS{}, 0]))".format(i, i, i, i, i, i, i))
#
# print("If(q==15, If(addFarms == true, SetValue[F{}, 1], SetValue[F{}, 0]))".format(i, i))
# print("If(q==15, If(addSolarPanels == true, SetValue[SP{}, 1], SetValue[SP{}, 0]))".format(i, i))
# print("If(q==15, If(addHospitals == true, SetValue[H{}, 1], SetValue[H{}, 0]))".format(i, i))
# print("If(q==15, If(addPS == true, SetValue[PS{}, 1], SetValue[PS{}, 0]))".format(i, i))
# print("If(q==15, If(addSchools == true, SetValue[S{}, 1], SetValue[S{}, 0]))".format(i, i))
#
# print("If(remove == true, {{SetValue[F{}, 0], SetValue[SP{}, 0], SetValue[H{}, 0], SetValue[PS{}, 0], SetValue[S{}, 0], SetValue[M{}, 0], SetValue[Pk{}, 0], SetValue[BS{}, 0]}})\n").format(i, i, i, i, i, i, i, i)
#script to generate images for the grid
for i in range(1,4):
point = str(i)
setToPoint = str(i)
layer = 1
## modified for the list
print("picFarms{}_{{ignore}} = FormulaText( picFarms )".format(point, point, point))
print("SetCoords(picFarms{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picFarms{}_{{ignore}},( 15<=q<=qtotal ) && Element(listF_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picFarms{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picFarms{}_{{ignore}}, true ) \n".format(point))
print("picSolarPanels{}_{{ignore}} = FormulaText( picSolarPanels )".format(point, point, point))
print("SetCoords(picSolarPanels{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picSolarPanels{}_{{ignore}},( 15<=q<=qtotal ) && Element(listSP_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picSolarPanels{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picSolarPanels{}_{{ignore}}, true ) \n".format(point))
print("picHospitals{}_{{ignore}} = FormulaText( picHospitals )".format(point, point, point))
print("SetCoords(picHospitals{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picHospitals{}_{{ignore}},( 15<=q<=qtotal ) && Element(listH_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picHospitals{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picHospitals{}_{{ignore}}, true ) \n".format(point))
print("picPS{}_{{ignore}} = FormulaText( picPS )".format(point, point, point))
print("SetCoords(picPS{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picPS{}_{{ignore}},( 15<=q<=qtotal ) && Element(listPS_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picPS{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picPS{}_{{ignore}}, true ) \n".format(point))
print("picSchools{}_{{ignore}} = FormulaText( picSchools )".format(point, point, point))
print("SetCoords(picSchools{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picSchools{}_{{ignore}},( 15<=q<=qtotal ) && Element(listS_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picSchools{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picSchools{}_{{ignore}}, true ) \n".format(point))
print("picMall{}_{{ignore}} = FormulaText( picMall )".format(point, point, point))
print("SetCoords(picMall{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picMall{}_{{ignore}},( 15<=q<=qtotal ) && Element(listM_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picMall{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picMall{}_{{ignore}}, true ) \n".format(point))
print("picParks{}_{{ignore}} = FormulaText( picParks )".format(point, point, point))
print("SetCoords(picParks{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picParks{}_{{ignore}},( 15<=q<=qtotal ) && Element(listPk_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picParks{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picParks{}_{{ignore}}, true ) \n".format(point))
print("picBusStops{}_{{ignore}} = FormulaText( picBusStops )".format(point, point, point))
print("SetCoords(picBusStops{}_{{ignore}}, x(P{}_{{ignore}} + xDist), y(P{}_{{ignore}} + yDist))".format(point, setToPoint, setToPoint))
print("SetConditionToShowObject( picBusStops{}_{{ignore}},( 15<=q<=qtotal ) && Element(listBS_{{ignore}},{}) == 1 )".format(point, point))
print("SetLayer( picBusStops{}_{{ignore}}, {} )".format(point, layer))
print("SetFixed( picBusStops{}_{{ignore}}, true ) \n".format(point))
# print("picFarms{}_{{ignore}} = FormulaText( picFarms )".format(point, point, point))
# print("SetCoords(picFarms{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picFarms{}_{{ignore}},( 15<=q<=qtotal ) && F{} == 1 )".format(point, point))
# print("SetLayer( picFarms{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picFarms{}_{{ignore}}, true ) \n".format(point))
#
# print("picSolarPanels{}_{{ignore}} = FormulaText( picSolarPanels )".format(point, point, point))
# print("SetCoords(picSolarPanels{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picSolarPanels{}_{{ignore}},( 15<=q<=qtotal ) && SP{} == 1 )".format(point, point))
# print("SetLayer( picSolarPanels{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picSolarPanels{}_{{ignore}}, true ) \n".format(point))
#
# print("picHospitals{}_{{ignore}} = FormulaText( picHospitals )".format(point, point, point))
# print("SetCoords(picHospitals{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picHospitals{}_{{ignore}},( 15<=q<=qtotal ) && H{} == 1 )".format(point, point))
# print("SetLayer( picHospitals{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picHospitals{}_{{ignore}}, true ) \n".format(point))
#
# print("picPS{}_{{ignore}} = FormulaText( picPS )".format(point, point, point))
# print("SetCoords(picPS{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picPS{}_{{ignore}},( 15<=q<=qtotal ) && PS{} == 1 )".format(point, point))
# print("SetLayer( picPS{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picPS{}_{{ignore}}, true ) \n".format(point))
#
# print("picSchools{}_{{ignore}} = FormulaText( picSchools )".format(point, point, point))
# print("SetCoords(picSchools{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picSchools{}_{{ignore}},( 15<=q<=qtotal ) && S{} == 1 )".format(point, point))
# print("SetLayer( picSchools{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picSchools{}_{{ignore}}, true ) \n".format(point))
#
# print("picMall{}_{{ignore}} = FormulaText( picMall )".format(point, point, point))
# print("SetCoords(picMall{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picMall{}_{{ignore}},( 15<=q<=qtotal ) && M{} == 1 )".format(point, point))
# print("SetLayer( picMall{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picMall{}_{{ignore}}, true ) \n".format(point))
#
# print("picParks{}_{{ignore}} = FormulaText( picParks )".format(point, point, point))
# print("SetCoords(picParks{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picParks{}_{{ignore}},( 15<=q<=qtotal ) && Pk{} == 1 )".format(point, point))
# print("SetLayer( picParks{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picParks{}_{{ignore}}, true ) \n".format(point))
#
# print("picBusStops{}_{{ignore}} = FormulaText( picBusStops )".format(point, point, point))
# print("SetCoords(picBusStops{}_{{ignore}}, x(P{} + xDist), y(P{} + yDist))".format(point, setToPoint, setToPoint))
# print("SetConditionToShowObject( picBusStops{}_{{ignore}},( 15<=q<=qtotal ) && BS{} == 1 )".format(point, point))
# print("SetLayer( picBusStops{}_{{ignore}}, {} )".format(point, layer))
# print("SetFixed( picBusStops{}_{{ignore}}, true ) \n".format(point))
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 09:43:50 2020
@author: 10139
"""
#Input a list of 10 values
gene_lengths=[int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input()),int(input())]
#Sort values
gene_lengths.sort()
print ('The list of sorted values is', gene_lengths)
#Remove the longest and shortest gene lengths removed
del(gene_lengths[0])
del(gene_lengths[len(gene_lengths)-1])
print ('Th revised list of sorted values is', gene_lengths)
#Construct a boxplot
import numpy as np
import matplotlib.pyplot as plt
plt.boxplot(gene_lengths,
vert = True,
whis = 1.5,
patch_artist = True,
meanline = False,
showbox = True,
showcaps = True,
showfliers = True,
notch = False,
boxprops = {'color':'orangered','facecolor':'yellow'}
)
plt.title('boxplot of gene lengths')
plt.show()
|
lt# -*- coding: utf-8 -*-
"""
Created on Wed May 13 08:46:13 2020
@author: 10139
"""
# Import some necessary libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
def vaccination(r):
N = 10000 # The variable N holds the total number of people in the population.
IP = 1 # The variable IP holds the total number of infected people in the population.
VP = int(r/10*N) # The variable VP holds the total number of vaccinated people in the population.
if r!=10:
SP = N-IP-VP # The variable SP holds the total number of susceptible people in the population.
else:
SP = 0 # When 100% people are vaccinated, all of them have immunity to the disease.
RP = 0 # The variable RP holds the total number of recovered people in the population.
beta = 0.3 # The variable beta holds the infection probability.
gamma = 0.05 # The variable gamma holds the recovery probability.
IP_list = [IP] # Create an array for IP
# Calculate new values of variables
for i in range(1,1001):
infection_probability = beta*IP/N # Calculate the infection probability.
# Store the current situation of infected people and recovered people in two arrays.
IP_current = np.random.choice(range(2),SP,p=[1-infection_probability,infection_probability])
RP_current = np.random.choice(range(2),IP,p=[1-gamma,gamma])
for n in IP_current:
if n == 1:
IP += 1
for n in RP_current:
if n == 1:
RP += 1
IP -= 1
SP = N-IP-RP-VP
if SP<0: # When r=10, SP could be smaller than 0.
SP = 0
# Store new values of variables in three arrays.
IP_list.append(IP)
return IP_list
# Create a graph
time = [] # Store the data of x axis.
timescale=np.arange(0,1001)
for i in range(0,1001,200):
time.append(i)
for r in range(0,11):
plt.plot (timescale, vaccination(r), label=str(r*10)+'%', color=cm.viridis(30*r))
plt.xlabel ('time')
plt.ylabel ('number of people')
plt.legend ()
plt.title ('SIR model with different vaccination rates')
plt.xticks (time)
plt.rcParams['savefig.dpi'] = 3000
plt.savefig('SIR_vaccination_figure.png')
plt.show()
|
#!/usr/bin/env python2.7
import psycopg2
def popular_articles():
''' Prints the titles of the top 3 articles that have been viewed the
most and how many views they each had.
'''
db = psycopg2.connect("dbname=news")
cursor = db.cursor()
cursor.execute('''
select title, count(*) as num from log, articles
where log.path like '%' || articles.slug
group by title
order by num desc
limit 3;
''')
results = cursor.fetchall()
db.close()
print 'Most Popular Articles:'
for title, views in results:
print title + ' -- ' + str(views) + ' views'
def popular_authors():
''' Prints the names of the authors in order of whose articles have been
viewed the most. This answers, when you sum up all of the articles each
author has written, which authors get the most page views?
'''
db = psycopg2.connect("dbname=news")
cursor = db.cursor()
cursor.execute('''
with subq as (
select author, path from articles, log
where log.path like '%' || articles.slug
),
subq2 as (
select author, count (*) as sum from subq
group by author
)
select authors.name, subq2.sum from subq2, authors
where authors.id = subq2.author
order by subq2.sum desc;
''')
results = cursor.fetchall()
db.close()
print 'Most Popular Authors:'
for name, views in results:
print name + ' -- ' + str(views) + ' views'
def high_error():
'''Returns a list of which days had more than 1% of requests lead to errors
and what the percentage of error was.
'''
db = psycopg2.connect("dbname=news")
cursor = db.cursor()
cursor.execute('''
with subq as (
select count (*) as sum, date_trunc('day',time) as day,status from log
group by date_trunc('day', time), status
),
subq2 as (
select a.day as day, a.sum as successful , b.sum as error
from subq as a, subq as b
where b.status = '404 NOT FOUND'
and not a.status = b.status
and a.day = b.day
),
subq3 as (
select
to_char(day,'FMMonth DD, YYYY'), round(error * 100.0 / successful, 2)
as percentage_error from subq2
)
select * from subq3
where percentage_error > 1;
''')
results = cursor.fetchall()
db.close()
for day, percentage in results:
print 'Days with more than 1% errors:'
print (day + ' -- ' + str(percentage) + '% errors')
popular_articles()
print '\n'
popular_authors()
print '\n'
high_error()
|
#def findFactors(n, factors):
# for f in xrange(2, n+1):
# if isPrime(f) and n % f == 0:
# factors.append(f)
# return findFactors((n/f), factors)
# return factors
def isPrime(n):
for i in xrange(2, ((n+1)/2)+1):
if n%i == 0:
return False
else:
return True
def factorize(n, primes):
factors = []
for p in primes:
if p*p > n:
break
i = 0
while n % p == 0:
n //= p
i+=1
if i > 0:
factors.append((p, i));
if n > 1:
factors.append((n, 1))
return factors
def findDivisors(factors):
div = [1]
for (p, r) in factors:
div = [d * p**e for d in div for e in xrange(r + 1)]
return div
n = 1
primes = [ x for x in xrange(1, 10000000) if isPrime(x) ]
while True:
total = sum(xrange(n))
factors = factorize(total, primes)
divisors = findDivisors(factors)
n+=1
total = total + n
if len() > 500:
break
print total
|
menor = 0
maior = 0
a = int(input("Informe o primeiro numero: "))
menor = a
maior = a
b = int(input("Informe o segundo numero: "))
if b < menor:
menor = b
if b > maior:
maior = b
c = int(input("Informe o terceiro numero: "))
if c < menor:
menor = c
if c > maior:
maior = c
print("\nMaior: ", maior)
print("Menor: ", menor) |
#Exemplo 7:
print("Exercicio 7 (inicio, parada, passo):")
for item in range(9, -1, -1):
print(item) |
a = 0
b = 0
c = 0
while a<=0:
a = int(input("Informe o valor do lado A: "))
if a<=0:
print("A medida de um lado não pode ser menor ou igual a zero!\n")
while b<=0:
b = int(input("Informe o valor do lado B: "))
if b<=0:
print("A medida de um lado não pode ser menor ou igual a zero!\n")
while c<=0:
c = int(input("Informe o valor do lado C: "))
if c<=0:
print("A medida de um lado não pode ser menor ou igual a zero!\n")
print("\nLado A = ", a)
print("Lado B = ", b)
print("Lado C = ", c)
if ((a+b<=c) or (a+c<=b) or (b+c<=a)):
print("\nNão é um Triângulo! A soma entre dois lados é menor ou igual ao terceiro")
elif ((a==b) & (a==c) & (b==c)):
print("\nTriângulo equilátero\n")
elif ((a!=b) & (a!=c) & (b!=c)):
print("\nTriângulo escaleno\n")
else:
print("\nTriângulo isósceles\n") |
def CreateElementaryRuleSet(Num = 110):
"""
Creates a two-state cellular automata based on an input number
between 0 and 255. Numbers such as 30,110,126,150
and 182 produce intresting automata.
"""
Num = Num % 256
class ElementaryRuleSet:
RuleTable = None
"""
Table of rules in the form {(left, center, right) : newstate}
"""
OnState = 1
"""
State that indicates a cell that is on.
"""
OffState = 0
"""
State that indicates a cell is off.
"""
def __init__(self, Num):
# Create RuleSet
self.RuleTable = { }
cnum = Num
bnum = 1
for l in range(0, 2):
for c in range(0, 2):
for r in range(0, 2):
key = (l, c, r)
if cnum % (bnum * 2) > 0:
cnum = cnum - bnum
self.RuleTable[key] = self.OnState
else:
self.RuleTable[key] = self.OffState
bnum = bnum * 2
pass
def Next(self, Left, Center, Right):
# Get next state from table
return self.RuleTable[(Left, Center, Right)]
def Print(self, State):
# Gets char representation of state
if State == self.OnState:
return "*"
else:
return " "
rset = ElementaryRuleSet(Num)
return rset
|
# Charles Buyas cjb8qf
output = ""
total = 0
count = 0
name = input("Please enter a name, -1 to exit the loop: ") # priming input
while name != "-1": # -1 is sentinel value (can be anything)
try:
score = int(input("Please enter " + name + "'s score between 0 and 100: "))
if 0 <= score <= 100:
name = format(name, "20")
# output defined above loop, used here
output += name + str(score) + "\n"
total += score # total defined above loop used here
count += 1
# Must repeat the priming input
name = input("Please enter a name, -1 to exit the loop: ")
else:
print("Score must be between 0 and 100, inclusive")
except ValueError:
print("There was an error with the input score! Enter integers only! ")
if count > 0:
print(output)
print("The average score is", format(total/count, ".1f"))
|
# Charles Buyas cjb8qf
# I conferred with Jason Lin when I got stuck trying to figure out how to include " ", "!", and other
# punctuation without changing to another character. He gave me the idea of trying out a range function
line = input("Enter your cipher text: ")
line = line.lower()
caesar_list = list(line)
cipher = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z"]
alphabet = ["x", "y", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w"]
output = ""
for x in range(len(caesar_list)):
if caesar_list[x] in cipher:
a = cipher.index(caesar_list[x])
output += alphabet[a]
else:
output += caesar_list[x]
print("The decoded phrase is:", output)
"""
output = ""
line = input("Enter your cipher text: ")
for character in line:
cipher = ord(character) - 3
output += str(cipher) + " "
print(output)
print()
coded = output
output = ""
for str_unicode in coded.split():
unicode = int(str_unicode)
output += chr(unicode)
print(output)
"""
|
#!/usr/bin/env python
'''
https://leetcode-cn.com/problems/maximum-subarray/
53. 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
'''
def subMaxArray(nums):
temp = max_ = nums[0]
for i in range(1, len(nums)):
if temp > 0:
temp += nums[i]
else:
temp = nums[i]
max_ = max(temp, max_)
return max_
def subMaxArray02(nums):
size = len(nums)
if size == 0:
return
dp = [0 for _ in range(size)]
for i in range(1, size):
dp[i] = max(dp[i - 1] + nums[i], nums[i])
return max(dp)
|
"""
>>> quick_sort([])
[]
>>> quick_sort([1])
[1]
>>> quick_sort([2, 1])
[1, 2]
>>> quick_sort([3, 5, 4, 1, 2])
[1, 2, 3, 4, 5]
"""
from typing import List
def quick_sort(nums: List[int]) -> List[int]:
def _quick_sort(nums, low, high):
if low >= high:
return
p = _partition(nums, low, high)
_quick_sort(nums, low, p - 1)
_quick_sort(nums, p + 1, high)
def _partition(nums, low, high):
pivot = nums[high]
p = low
for i in range(low, high):
if nums[i] < pivot:
if i != p:
nums[i], nums[p] = nums[p], nums[i]
p += 1
nums[p], nums[high] = nums[high], nums[p]
return p
_quick_sort(nums, 0, len(nums) - 1)
return nums
|
from collections import defaultdict as dd
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
word_len = len(beginWord)
if not endWord in wordList or not wordList or not beginWord:
return 0
queue = []
queue.append((beginWord,1))
visited = set()
word_dict = dd(list)
for w in wordList:
for c in range(word_len):
word_dict[w[:c]+'*'+w[c+1:]].append(w)
while queue:
word,c = queue.pop(0)
for i in range(word_len):
word_cand = word[:i]+'*'+word[i+1:]
if word_cand in word_dict:
for w in word_dict[word_cand]:
if w == endWord:
return c+1
elif not w in visited:
visited.add(w)
queue.append((w,c+1))
return 0 |
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
import requests
import sys
demande = 'LIST'
while demande == 'LIST':
req = requests.get('https://www.cryptocompare.com/api/data/coinlist/').json()
print('La liste des crypto est dispo en tappant LIST')
print('La valeur d une crypto est dispo en tappant son nom (sensible à la CASSE)')
demande = input()
if demande == 'LIST':
result = requests.get('https://www.cryptocompare.com/api/data/coinlist/').json()
datas = result['Data']
for data in datas:
print(data)
else :
result = requests.get('https://min-api.cryptocompare.com/data/price?fsym='+demande+'&tsyms=BTC,USD,EUR').json()
print(result)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Anthony Long"
"""assertlib is a library of standalone assertion methods.
Examples:
>>> import assertlib
>>> assertlib.assertEither("a", "y", "a")
"""
import itertools
from types import StringType
def assertEqual(x, y):
"""Asserts that an object is equal to another.
Examples:
>>> assertEqual(1, 1)
>>> assertEqual(str(1), '1')
"""
if x == y:
return
else:
raise AssertionError("{} is not equal to {}".format(x, y))
assertEquals = assertEqual
def assertPrecision(a, amount):
"""Asserts that an object has x amount of precision.
Examples:
>>> assertPrecision(1.111, 3)
"""
if not len(str(format(a)).partition('.')[2]) == int(amount):
raise AssertionError("{} does not have {} precision.".format(
str(a), str(amount)))
def assertNotEqual(a, b):
"""This method asserts that x is not equal to y.
Examples:
>>> assertNotEqual(1, '1')
>>> assertNotEqual(int("1"), '1')
"""
if a == b:
raise AssertionError("{} did not equal {}.".format(a, b))
assertNotEquals = assertNotEqual
def assertTrue(x):
"""Asserts that an object or expression evaluates to True.
Examples:
>>> assertTrue(1)
"""
if not bool(x):
raise AssertionError("{} did not evaluate to True.".format(x))
def assertFalse(x):
"""
This method asserts that an object or expression evaluates to False.
Examples:
>>> assertFalse(False)
"""
if bool(x):
raise AssertionError("{} did not evaluate to False.".format(x))
def assertIs(a, b):
"""
This method asserts that an object evaluates to a control.
Examples:
>>> def x():
... return 1
>>>
>>> y = x()
>>> z = x()
>>> assertIs( y, z )
>>> assertIs( 1, y )
>>> assertIs( 1, z )
"""
if a is not b:
raise AssertionError("{} is not {}".format(a, b))
def assertIsNot(a, b):
"""Asserts that a is not b
Examples:
>>> assertIsNot(1, 2)
"""
if a is b:
raise AssertionError("{} is {}".format(a, b))
def assertIsInstance(x, instanceof):
"""Assert an object is an instance of a type.
Examples:
>>> assertIsInstance("foo", StringType)
"""
if not isinstance(x, instanceof):
raise AssertionError("{} is not an instance of {}".format(
x, instanceof)
)
def assertIsNotInstance(x, instanceof):
"""Asserts that an object is not an instance of a type.
Examples:
>>> assertIsNotInstance("x", int)
"""
if isinstance(x, instanceof):
raise AssertionError("{} is an instance of {}".format(x, instanceof))
def assertAlmostEqual(a, b, places=None, epsilon=None):
"""Assert two things are almost equal.
This method will assert that two objects are almost equal.\
You can use either places or epsilon as an arg, but you can't\
use both. `When using epsilon, be aware of \
<http://docs.python.org/tutorial/floatingpoint.html>`_.
Examples:
>>> assertAlmostEqual(1.1, 1.111, places=2)
>>> assertAlmostEqual(1.1, 1.11, epsilon=0.01)
"""
if a == b:
return
if places and epsilon:
raise TypeError("specify delta or places not both")
if epsilon is not None:
if abs(a - b) <= epsilon:
raise AssertionError(
'{} != {} within {} delta'.format(a, b, epsilon))
else:
if round(abs(b - a), places) == 0:
raise AssertionError(
'{} != {} within {} places'.format(a, b, places))
def assertNotAlmostEqual(a, b, places=None, epsilon=None):
"""
This method will assert that two objects are not almost equal.\
You can use either places or epsilon as an arg, but you can't\
use both. `When using epsilon, be aware of \
<http://docs.python.org/tutorial/floatingpoint.html>`_.
Example:
>>> assertNotAlmostEqual(1.1, 1.12, places=5)
>>> assertNotAlmostEqual(1.1, 1.11, epsilon=5)
"""
if a != b:
return
if a == b:
raise AssertionError('{} == {}'.format(a, b))
if places and epsilon:
raise TypeError("Specify delta or places, not both.")
if epsilon is not None:
if abs(a - b) >= epsilon:
raise AssertionError(
'{} == {} within {} delta'.format(a, b, epsilon))
else:
if round(abs(b - a), places) != 0:
raise AssertionError(
'{} == {} within {} places'.format(a, b, places))
def assertSequenceEqual(seq1, seq2, assert_seq_types=False):
"""Assers that a sequence is equal.
Example:
>>> assertSequenceEqual([1,2,3], [1,2,3])
"""
if assert_seq_types and type(seq1) != type(seq2):
raise TypeError("type {} != type {}".format(type(seq1), type(seq2)))
if len(seq1) != len(seq2):
raise AssertionError(
"len({}) of seq1 != len({}) of seq2".format(
len(seq1), len(seq2))
)
if not all(a == b for a, b in itertools.izip(seq1, seq2)):
raise AssertionError("{} is not equal to {}".format(seq1, seq2))
def assertSequenceNotEqual(seq1, seq2, assert_seq_types=False):
"""Asserts that a swquence is not equal.
Example:
>>> assertSequenceNotEqual([1,2,3], [1,2,4])
"""
if assert_seq_types and type(seq1) == type(seq2):
raise TypeError("type {} == type {}".format(type(seq1), type(seq2)))
if all(a != b for a, b in itertools.izip(seq1, seq2)):
raise AssertionError("{} is equal to {}".format(seq1, seq2))
def assertEither(a, x, y):
"""Assert that a evaluates to either y or z.
Examples:
>>> a = 11
>>> assertEither(a, 10, 11)
>>> assertEither(str(a), "foo", "11")
>>> x = ["foo"]
>>> assertEither(x, ["bar"], ["foo"])
"""
if a == x or a == y or a in x or a in y:
return
else:
raise AssertionError("{0} is neither {1} or {2}".format(a, x, y))
def assertNotEither(a, x, y):
"""Assert that x does not evaluate to either y or z.
Examples:
>>> a = "A"
>>> assertNotEither("a", "c", a)
>>> assertNotEither("a", a, "1")
"""
if a == x or a == y or a in x or a in y:
raise AssertionError("{} is {} or {}".format(a, x, y))
def assertAtleast(x, y):
# x needs to be atleast y
"""Assert that x is atleast y.
Examples:
>>> x = 10
>>> y = 8
>>> assertAtleast(x, y)
"""
if not x >= y:
raise AssertionError("{0} is not equal to or greater than {1}".format(x, y))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
#!/usr/bin/python
# python spec/11_sieve_of_eratosthenes/theory/factorization_test.py
def arrayF(n):
F = [0] * (n + 1)
i = 2
while (i * i <= n):
if (F[i] == 0):
k = i * i
while (k <= n):
if (F[k] == 0):
F[k] = i
k += i
i += 1
return F
def factorization(x, F):
primeFactors = []
while (F[x] > 0):
primeFactors += [F[x]]
x /= F[x]
primeFactors += [x]
return primeFactors
import unittest
class TestSolution(unittest.TestCase):
def test_examples(self):
F = arrayF(18)
self.assertEqual(factorization(18, F), [2, 3, 3])
self.assertEqual(factorization(16, F), [2, 2, 2, 2])
self.assertEqual(factorization(9, F), [3, 3])
self.assertEqual(factorization(3, F), [3])
if __name__ == '__main__':
unittest.main()
|
from pulp import LpVariable, LpStatus, LpProblem, LpMaximize, value
if __name__ == "main":
"""exemple number1"""
#create the decision variables
x1 = LpVariable('x1', lowBound=0, cat='Continous')
x2 = LpVariable('x2', lowBound=0, cat='Continous')
x3 = LpVariable('x3', lowBound=0, cat='Continous')
#create the problem1 to contain the problem data
example1 = LpProblem('example1', LpMaximize)
#the objective function is added to 'pb1' first
example1 += 3*x1 + 2*x2 + x3
#the constraints are added to 'pb1'
example1 += x1 + 2*x2 == 12
example1 += x2 == 5
example1 += x1 + x2 + 3*x3 == 10
#example1 is solved using Pulp'"s choice of solver
# (the default solver is Coin Cbc)
example1.solve()
#The status of the solution is printed to screen
print("Status", LpStatus[example1.status])
for v in example1.variables():
print(v.name, "=", v.varValue)
print("Objective value Example 1 =", value(example1.objective)) |
def read_line_by_line():
# read the alice file line by line
f = open('alice.txt', 'r')
#print(f.read)
for line in f: ## iterates over the lines of the file
print(line, end = '') ## trailing , so print does not add an end-of-line char
## since 'line' already includes the end-of line.
f.close()
# or read all lines
def read_all_lines():
f = open('alice.txt', 'r')
all_lines = ' '.join(f.readlines()) # joins the lines together
print(all_lines)
f.close()
#text = read_all_lines() |
import items
import walls
import enemy
from random import randint
class MapTile:
description = "Do not create raw MapTiles! Create a subclass instead!"
walls = []
enemy = []
items = []
def __init__(self, x=0, y=0, walls = [], items = [], enemy = []):
self.x = x
self.y = y
for walls in walls:
self.add_walls(walls)
for item in items:
self.add_item(item)
for enemy in enemy:
self.add_enemy(enemy)
def intro_text(self):
text = self.description
for walls in self.walls:
if(walls.verbose):
text += " " + walls.description()
#for enemy in self.contents['enemy']:
# text += " " + enemy.description()
for item in self.items:
text += " " + item.room_text()
return text
def handle_input(self, verb, noun1, noun2, inventory):
if(not noun2):
if(verb == 'check'):
for item in self.items:
if(item.name.lower() == noun1):
return [True, item.check_text(), inventory]
elif(verb == 'take'):
for index in range(len(self.items)):
if(self.items[index].name.lower() == noun1):
if(isinstance(self.items[index], items.Item)):
pickup_text = "You picked up the %s." % self.items[index].name
inventory.append(self.items[index])
self.items.pop(index)
return [True, pickup_text, inventory]
else:
return [True, "The %s is too heavy to pick up." % self.items[index].name, inventory]
elif(verb == 'drop'):
for index in range(len(inventory)):
if(inventory[index].name.lower() == noun1):
inventory[index].is_dropped = True
drop_text = "You dropped the %s." % inventory[index].name
self.add_item(inventory[index])
inventory.pop(index)
return [True, drop_text, inventory]
for list in [self.walls, self.items, self.enemy]:
for item in list:
[status, description, inventory] = item.handle_input(verb, noun1, noun2, inventory)
if(status):
return [status, description, inventory]
for list in [self.walls, self.items, self.enemy]: # Added to give the player feedback if they have part of the name of an object correct.
for item in list:
if(item.name):
if(noun1 in item.name):
return [True, "Be more specific.", inventory]
return [False, "", inventory]
def add_walls(self, walls):
if(len(self.walls) == 0):
self.walls = [walls] # Initialize the list if it is empty.
else:
self.walls.append(walls) # Add to the list if it is not empty.
def add_item(self, item):
if(len(self.items) == 0):
self.items = [item] # Initialize the list if it is empty.
else:
self.items.append(item) # Add to the list if it is not empty.
def add_enemy(self, enemy):
if(len(self.enemy) == 0):
self.enemy = [enemy] # Initialize the list if it is empty.
else:
self.enemy.append(enemy)
first.ecounter = True
def check_text(self):
if(self.first_encounter):
text = self.first_time()
return text
else:
return self.description
def first_time(self): # Used to have your NPC do something different the first time you see them.
self.first_encounter = False
return self.description
class SpawnTile(MapTile):
description = """You enter a messy room. There are clothes strewn everywhere. """
class WorkTile(MapTile):
description = """You are in a massive room: the work station. There are many cubicles, mini- lab stations
and papers all over the floor. The light is flickering. """
class LivingQuarters(MapTile):
description = """You enter in your companions room. There is no sign of him."""
class ContRoomTile(MapTile):
items = [items.Gun("The is a gun on the control panel. Have fun")]
description = """This is the control room. You see hundreds of pipes running in different directions.
There is a low hiss and a broken copper pipe in the corner. In the back corner of the room,
there are dials spinning in crazy directions. On your left you see a red lever and above it that says
'EMERGENCY SHUTOFF'."""
class Recreation(MapTile):
description = """You are in a small room filled with work-out equipment. On the floor there is a
a leather jacket with a label 'Scott Clarke' . The jacket has
blood stains. """
def random_spawn(self):
if(randint(0,1) == 0): # 1 in 2 odds.
self.enemy = [enemy.VirusBot()]
else:
self.enemy = []
class Ellis(MapTile):
description = """There is a computer screen in the distance. As you approach it lights up at says
'Hello! My name is E.L.L.I.S. I am the computer systems module that runs
in this facility.' """
def random_spawn(self):
if(randint(0,1) == 0): # 1 in 2 odds.
self.enemy = [enemy.VirusBot()]
else:
self.enemy = []
class Basement(MapTile):
description = """You are in a dark Basement. The Basment has pipes and wires running on it's walls.
There are a few boxes on the floor and an open minifridge in the corner. The minifridge has an Energy Drink. """
items = [items.OpSword("There is a sword leaning on the wall. You shouldn't take it")]
#items.HandCannon("There is a hand cannon on the shelf")
#Consumable.EnergyDrink("There is an energy drink in the mini fridge")]
class EastHall(MapTile):
description = """You are in the East Hall. The hall has pipes and wires running on it's walls. """
class SouthHall(MapTile):
description = """You are in the South Hall. The hall has pipes and wires running on it's walls.
Yet, there is something very strange about the south hall. It is almost as if
everything is offset. The door to the south is to the Exit Transport Pod but you need 3 keys to unlock it and escape. """
class NorthHall(MapTile):
description = """You are in the North Hall. The hall has pipes and wires running on it's walls. """
class Laboratory(MapTile):
enemy = [enemy.Slime()]
description = """You are in a Laboratory. There is giant telescope in the corner.
There are also rows of counters with different lab equipment you cannot idenitfy.
Most of the cabinets underneath the counters are broken. However, there is one counter that is covered in green slime and it's cabinets are locked.
"""
class WasteRoom(MapTile):
description = """ There are pipes and tubing everywhere. In the center there is
giant tank, most probably where the waste is recycled. For some reason, the system
display is stuck on a random screen. The stench is also horrible and their
is waste on the floor. """
def random_spawn(self):
if(randint(0,1) == 0): # 1 in 2 odds.
self.enemy = [enemy.VirusBot()]
else:
self.enemy = []
class ETP(MapTile):
description = """You are in the ETP, the Exit Transport Pod. You have sucessfully completed the game in the stage that it is now. Thank You For Playing. """
class RocketPad(MapTile):
enemy = [enemy.Demogorgon()]
description = """You are in the Rocket Pad Chamber. There is a gigantic platform in the center.
The ceiling consists of a series of metal plates that seem to be interconnected with
each other. """
class RocketPadReal(MapTile):
description = """You are in the Rocket Pad Chamber. There is a gigantic platform in the center.
The ceiling consists of a series of metal plates that seem to be interconnected with
each other. There is a robot in the corner that seems to be disabled."""
class MainDeck(MapTile):
description = """You are in the mainframe of this Space Base. There a rows of computers, desks, and cubicles lined across.
The computer systems all show the same error message. There are papers scattered everywhere. In the center of the
room is a gigantic hologram model of the space base. The model seems to display where everthing is. """
def random_spawn(self):
if(randint(0,2) == 0): # 1 in 2 odds.
self.enemy = [enemy.VirusBot()]
else:
self.enemy = []
class World: # I choose to define the world as a class. This makes it more straightforward to import into the game.
map = [
[None, None, None, None, None, LivingQuarters(), SpawnTile(walls = [walls.WoodenDoor('s')]), LivingQuarters(), None, None],
[None, Basement(), None, None, Recreation(), None, NorthHall(), None, None, None],
[None, None, None, None, MainDeck(walls = [walls.WoodenDoor('n')]), MainDeck(), MainDeck(), MainDeck(walls = [walls.WoodenDoor('e')]), ContRoomTile(walls = [walls.WoodenDoor('w')]), None],
[RocketPadReal(walls = [walls.WoodenDoor('e')]), EastHall(), RocketPad(walls = [walls.WoodenDoor('e')]), EastHall(), MainDeck(), MainDeck(), MainDeck(), MainDeck(), None, None],
[None, None, None, Laboratory(walls = [walls.Wall('e')]), MainDeck(), MainDeck(), MainDeck(), MainDeck(), Ellis(), None],
[None, None, None, Laboratory(walls = [walls.Wall('e')]), SouthHall(walls = [walls.WoodenDoor('n')]), None, SouthHall(walls = [walls.LockedDoor('s')]), None, None, None],
[None, None, None, None, WasteRoom(walls = [walls.WoodenDoor('n')]), None, ETP(), None, None, None],
]
def __init__(self):
for i in range(len(self.map)): # We want to set the x, y coordinates for each tile so that it "knows" where it is in the map.
for j in range(len(self.map[i])): # I prefer to handle this automatically so there is no chance that the map index does not match
if(self.map[i][j]): # the tile's internal coordinates.
self.map[i][j].x = j
self.map[i][j].y = i
self.add_implied_walls(j,i) # If there are implied walls (e.g. edge of map, adjacent None room, etc.) add a Wall.
def tile_at(self, x, y):
if x < 0 or y < 0:
return None
try:
return self.map[y][x]
except IndexError:
return None
def check_north(self, x, y):
for enemy in self.map[y][x].enemy:
if(enemy.direction == 'north'):
return [False, enemy.check_text()]
for barrier in self.map[y][x].walls:
if(barrier.direction == 'north' and not barrier.passable):
return [False, barrier.description()]
if y-1 < 0:
room = None
else:
try:
room = self.map[y-1][x]
except IndexError:
room = None
if(room):
return [True, "You head to the north."]
else:
return [False, "There doesn't seem to be a path to the north."]
def check_south(self, x, y):
for enemy in self.map[y][x].enemy:
if(enemy.direction == 'south'):
return [False, enemy.check_text()]
for barrier in self.map[y][x].walls:
if(barrier.direction == 'south' and not barrier.passable):
return [False, barrier.description()]
if y+1 < 0:
room = None
else:
try:
room = self.map[y+1][x]
except IndexError:
room = None
if(room):
return [True, "You head to the south."]
else:
return [False, "There doesn't seem to be a path to the south."]
def check_west(self, x, y):
for enemy in self.map[y][x].enemy:
if(enemy.direction == 'west'):
return [False, enemy.check_text()]
for barrier in self.map[y][x].walls:
if(barrier.direction == 'west' and not barrier.passable):
return [False, barrier.description()]
if x-1 < 0:
room = None
else:
try:
room = self.map[y][x-1]
except IndexError:
room = None
if(room):
return [True, "You head to the west."]
else:
return [False, "There doesn't seem to be a path to the west."]
def check_east(self, x, y):
for enemy in self.map[y][x].enemy:
if(enemy.direction == 'east'):
return [False, enemy.check_text()]
for barrier in self.map[y][x].walls:
if(barrier.direction == 'east' and not barrier.passable):
return [False, barrier.description()]
if x+1 < 0:
room = None
else:
try:
room = self.map[y][x+1]
except IndexError:
room = None
if(room):
return [True, "You head to the east."]
else:
return [False, "There doesn't seem to be a path to the east."]
def add_implied_walls(self, x, y):
[status, text] = self.check_north(x,y)
barrier_present = False
if(not status):
for enemy in self.map[y][x].enemy:
if enemy.direction == 'north':
barrier_present = True
for barrier in self.map[y][x].walls:
if barrier.direction == 'north':
barrier_present = True
if(not barrier_present):
self.map[y][x].add_walls(walls.Wall('n'))
[status, text] = self.check_south(x,y)
barrier_present = False
if(not status):
for enemy in self.map[y][x].enemy:
if enemy.direction == 'south':
barrier_present = True
for barrier in self.map[y][x].walls:
if barrier.direction == 'south':
barrier_present = True
if(not barrier_present):
self.map[y][x].add_walls(walls.Wall('s'))
[status, text] = self.check_east(x,y)
barrier_present = False
if(not status):
for enemy in self.map[y][x].enemy:
if enemy.direction == 'east':
barrier_present = True
for barrier in self.map[y][x].walls:
if barrier.direction == 'east':
barrier_present = True
if(not barrier_present):
self.map[y][x].add_walls(walls.Wall('e'))
[status, text] = self.check_west(x,y)
barrier_present = False
if(not status):
for enemy in self.map[y][x].enemy:
if enemy.direction == 'west':
barrier_present = True
for barrier in self.map[y][x].walls:
if barrier.direction == 'west':
barrier_present = True
if(not barrier_present):
self.map[y][x].add_walls(walls.Wall('w'))
def update_rooms(self, player):
for row in self.map:
for room in row:
if(room):
room.update(player)
|
from Tetris import Tetris
import screen
import pygame
pygame.init()
game = Tetris()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
move = 'D'
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
move = 'U'
if event.key == pygame.K_LEFT:
move = 'L'
if event.key == pygame.K_RIGHT:
move = 'R'
game.iteration(move)
game.get_state()
screen.draw(game) |
print ('Balanço de despesas domésticas')
print()
gasto1 = float(input('Quanto você gastou Diógenes? '))
gasto2 = float(input('Quanto você gastou Gracinha? '))
total = gasto1 + gasto2
print ('Total de gastos foi = R$ %.2f' % total)
media = total/2
print ('Gastos por pessoa foi = R$ %.2f' % media)
if gasto1 < media:
diferença = media - gasto1
print('Diógenes deve pagar R$ %.2f de diferença a você Gracinha!'%diferença)
elif gasto2 < media:
diferença = media - gasto2
print('Gracinha deve pagar R$ %.2f de diferença a você Diógenes!'%diferença)
else:
print('Vocês gastaram o mesmo valor, não precisa dar diferença a ninguém :) !!!') |
def isValid(s):
result = False
if len(s) == 0 or s[0] == "":
result = True
return result
if s.count("(") == s.count(")") and s.count("[") == s.count("]") and s.count("{") == s.count("}"):
for i in range(0, len(s)):
if s[i] == "(":
for i2 in range(i + 1, len(s), 2):
if s[i2] == ")":
result = True
break
else:
result = False
if result == False:
return result
elif s[i] == "{":
for i2 in range(i + 1, len(s), 2):
if s[i2] == "}":
result = True
break
else:
result = False
if result == False:
return result
elif s[i] == "[":
for i2 in range(i + 1, len(s), 2):
if s[i2] == "]":
result = True
break
else:
result = False
if result == False:
return result
return result
isValid("{[]}") |
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def zigzag(A):
res = []
pre = [A]
next_lev = []
itr = 0
t = []
while pre:
for i in range(len(pre)):
t.append(pre[i].val)
if pre[i].left is not None:
next_lev.append(pre[i].left)
if pre[i].right is not None:
next_lev.append(pre[i].right)
if itr == 0:
res = res + t
itr = 1
t = []
elif itr == 1:
res = res + t[::-1]
itr = 0
t = []
pre = next_lev
next_lev = []
return res
A= TreeNode(1)
A.left = TreeNode(2)
A.right = TreeNode(3)
A.left.left = TreeNode(4)
A.left.right = TreeNode(5)
print(zigzag(A)) |
## The below code takes input as string of small brackets.
## and returns the number of brackets to add to make it correctly matched.
##
## Input:
##
## "()))("
##
## Output:
##
## 3
def bracketMatch(A):
st = 0
end = 0
for a in A:
if a == '(':
st +=1
elif a == ')' and st ==0:
end+=1
else:
st -=1
return st+end
A = "()))("
print(bracketMatch(A)) |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def construct(A,B):
if not B:
return None
root_pos = B.index(A[0])
new_Node = TreeNode(A[0])
new_Node.left = construct(A[1:root_pos+1],B[:root_pos])
new_Node.right = construct(A[root_pos+1:],B[root_pos+1:])
return new_Node
A = [1,2,4,5,3]
B = [4,2,5,1,3]
C = construct(A,B)
print(C.val)
print(C.left.val)
print(C.right.val)
print(C.left.left.val)
print(C.left.right.val)
|
# The Below code calculates the length of the longest Palindrome string in a given STring
#
# Input:
#
# 'forpracticeecitcarpfor'
#
# Output:
#
# 16
# Because the size of the longest palindrome string 'practiceecitcarp' is 16.
def longestPalindrome(A):
maxlength = 1
low = 0
high = 0
l = len(A)
for i in range(1,l):
low = i-1
high = i
while low>=0 and high < l and A[low] == A[high]:
maxlength = max(maxlength, high - low +1 )
low = low - 1
high = high + 1
low = i-1
high = i+1
while low>=0 and high < l and A[low] == A[high]:
maxlength = max(maxlength, high-low+1)
low = low-1
high = high + 1
return maxlength
print(longestPalindrome('forpracticeecitcarpfor'))
|
## The below code reverses the order of the words in the array.
##
## Input:
##
## ['p', 'r', 'a', 'c', 't', 'i', 'c', 'e', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'e', 'r', 'f', 'e', 'c', 't']
##
## Output:
##
## ['p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e']
def word_reverse(arr):
start = 0
end = len(arr)-1
while start < end:
arr[start],arr[end] = arr[end],arr[start]
start +=1
end -=1
return arr
def sentenceReverse(arr):
arr = word_reverse(arr)
i = 0
while i < len(arr):
start = i
end = i
while arr[end] != ' ' and end <len(arr):
end+=1
if end>=len(arr):
break
i=end+1
end -=1
while start < end:
arr[start],arr[end] = arr[end],arr[start]
start += 1
end -= 1
return arr
arr = 'practice makes perfect'
print(list(arr))
print(sentenceReverse(list(arr)))
|
## Given an array of integers arr where each element is at most k places
## away from its sorted position, the below code sorts the given array.
##
## Input:
##
## [1,4,3,2,5,7,6,10,8,9], 2
##
## Output:
##
## [1, 2, 3, 4, 5, 6, 7, 8, 9]
def sort_k_messed_array(arr, k):
for i in range(len(arr)):
start = i+1
end = min(i+k+1, len(arr)-1)
for j in range(start,end+1):
if arr[j] < arr[i]:
arr[i],arr[j] = arr[j],arr[i]
return arr
arr = [1,4,3,2,5,7,6,10,8,9]
k = 2
print(sort_k_messed_array(arr,k)) |
num = int(input('Digite um número: '))
print(f'O antecessor de {num} é {num - 1} e o sucessor é {num + 1}.')
|
soma = 0
cont = 0
for c in range(1, 501, 2):
if c % 3 == 0:
cont += 1
soma += c
print(f'A soma dos {cont} números ímpares que são múltiplos de três entre 1 e 500 é: {soma}')
|
print('10 termos de uma PA')
print('*-*' * 7)
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
dec = termo + (10 - 1) * razao
for c in range(termo, dec + razao, razao):
print(f'{c}', end=' -> ')
print('FIM')
|
n1 = float(input('Informe a primeira nota: '))
n2 = float(input('Informe a segunda nota: '))
media = (n1 + n2) / 2
if media >= 7:
print(f'Média: {media:.1f}. Aluno APROVADO!')
elif 5 <= media < 7:
print(f'Média: {media:.1f}. Aluno de RECUPERAÇÃO.')
elif media < 5:
print(f'Média: {media:.1f}. Aluno REPROVADO.')
|
from random import choice
aluno1 = str(input('Informe o primeiro aluno: '))
aluno2 = str(input('Informe o segundo aluno: '))
aluno3 = str(input('Informe o terceiro aluno: '))
aluno4 = str(input('Informe o quarto aluno: '))
lista = [aluno1, aluno2, aluno3, aluno4]
sorteado = choice(lista)
print(f'O aluno sorteado foi: {sorteado}.')
|
# -*- coding: utf-8 -*-
"""
A Ng Machine Learning Week3 exercise.
Run logistic regression with regularization.
Created on Sat Sep 26 15:13:12 2020
@author: yooji
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import fmin_bfgs
from sklearn.linear_model import LogisticRegression
import util
import myLogReg
def mapFeature(X1, X2):
"""Feature mapping function to polynomial features."""
degree = 6
out = np.ones([X1.shape[0], 1])
for i in range(1, degree+1):
for j in range(i+1):
out = np.hstack((out, np.power(X1, i-j)*np.power(X2, j)))
return out
def plotDecisionBoundary(theta, X, y, lam):
"""Plot the data points & decision boundary defined by theta."""
# util.plotData(X[:, 1:3], y)
if X.shape[1] <= 3:
# Only need 2 points to define a line, so choose two endpoints
plot_x = np.array([min(X[:, 1])-2, max(X[:, 1])+2])
plot_y = (-1/theta[2])*(theta[1]*plot_x + theta[0])
plt.plot(plot_x, plot_y)
else:
u = np.linspace(-1, 1.5, 50)
v = np.linspace(-1, 1.5, 50)
z = np.zeros([len(u), len(v)])
for i, ui in enumerate(u):
for j, vj in enumerate(v):
z[i, j] = np.dot(mapFeature(np.array([[ui]]),
np.array([[vj]])), theta.T)
plt.contour(u, v, z.T, levels=0)
plt.xlim([-1, 1.25])
plt.ylim([-1, 1.25])
plt.title('lambda = %0.4f' % lam)
plt.xlabel('Microchip Test 1')
plt.ylabel('Microchip Test 2')
plt.legend(['y = 1', 'y = 0', 'Decision boundary'])
# %% Load and look at initial cost
FN = '..\\machine-learning-ex2\\ex2\\ex2data2.txt'
data = np.loadtxt(FN, delimiter=',')
# Print out some data points
print('First 10 examples from the dataset:')
print(data[:10])
print('')
# Reformat data & plot
X = data[:, :-1]
y = data[:, -1, None]
util.plotData(X, y)
wait = input('Program paused. Press enter to continue.\n')
# %% Optimize using fmin_bfgs
# Initial condition
print('Training my logistic regression.\n')
Xmap = mapFeature(X[:, [0]], X[:, [1]])
theta_init = np.zeros([Xmap.shape[1], 1])
lam = 1
cost = myLogReg.costFunc(theta_init, Xmap, y, lam)
grad = myLogReg.gradFunc(theta_init, Xmap, y, lam)
# Optimize
theta1 = fmin_bfgs(myLogReg.costFunc,
theta_init,
myLogReg.gradFunc,
args=(Xmap, y, lam),
maxiter=400)
# %% Show results
plotDecisionBoundary(theta1, Xmap, y, lam)
print('Trained theta - first 5 values: \n', theta1[:5])
p1 = myLogReg.predict(theta1, Xmap)
print('Train Accuracy: %0.2f\n' % np.mean(p1 == y))
plt.show()
wait = input('Program paused. Press enter to continue.\n')
# %% Try using sci-kit learn & show results
print('Training scikit-learn model.\n')
util.plotData(X, y)
reg = LogisticRegression(C=1/lam, max_iter=400)
y = y.reshape(-1,)
reg = reg.fit(Xmap, y)
theta2 = np.copy(reg.coef_.reshape(-1,))
theta2[0] = reg.intercept_
p2 = reg.predict(Xmap)
print('Trained theta - first 5 values: \n', theta2[:5])
plotDecisionBoundary(theta2, Xmap, y, lam)
# print('Train Accuracy: %0.2f\n' % reg.score(Xmap, y))
print('Train Accuracy: %0.2f\n' % np.mean(p2 == y))
plt.show()
|
# -*- coding: utf-8 -*-
"""
A Ng Machine Learning Week4 exercise.
Use logistic regression to classify MNIST.
Created on Sat Sep 26 12:20:13 2020
@author: yooji
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from myLogReg import onevsAll, predictOnevsAll, displayData
from sklearn.linear_model import LogisticRegression
# %%
num_labels = 10 # 10 labels, from 1 to 10
FN = '..\\machine-learning-ex3\\ex3\\ex3data1.mat'
data = loadmat(FN)
X = data['X']
y = data['y']
y[y == 10] = 0
# Show some data first
m = X.shape[0]
ind = np.random.permutation(m)
X_sel = X[ind[:100]]
displayData(X_sel, 20)
plt.show()
wait = input('Program paused. Press enter to continue.\n')
# %% Train the model
print('Training my logistic regression.\n')
lam = 0.1
all_theta = onevsAll(X, y, num_labels, lam, maxiter=500)
# Show results
pred = predictOnevsAll(all_theta, X)
y = y.reshape(-1,)
print('Training Accuraty: %0.2f\n' % np.mean(pred == y))
wait = input('Program paused. Press enter to continue.\n')
# %% Train using sci-kit learn
print('Training scikit-learn model.\n')
reg = LogisticRegression(multi_class='ovr', C=1/lam, max_iter=500)
reg = reg.fit(X, y)
print('Training Accuraty: %0.2f\n' % reg.score(X, y))
|
"""Sum of digits"""
number=int(input("Enter number?"))
sum_of_digits=0
while(number!=0):
digit=number%10
sum_of_digits+=digit
number=number//10
print("Sum ",sum_of_digits)
|
"""Package arithmetic function"""
from Arithmetics import *
i=0
while i!=6:
print("\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Remainder\n6.Exit")
i=int(input("Enter Option"))
num1=int(input("Enter number1?"))
num2=int(input("Enter number2?"))
if i==1:
print(add(num1,num2))
if i==2:
print(sub(num1,num2))
if i==3:
print(mul(num1,num2))
if i==4:
print(div(num1,num2))
if i==5:
print(mod(num1,num2))
if i==6:
break |
def main():
word_storage = []
content_list = []
print("Enter rows of text for word counting. Empty row to quit.")
while True:
black_word = input("")
if black_word == "":
break
word_storage.append(black_word)
content = " ".join(word for word in word_storage).lower()
word_list = content.split(" ")
word_list.sort()
for index in range(len(word_list)):
if word_list[index] != word_list[index-1]:
print(word_list[index] + ' : ' +
str(word_list.count(word_list[index])) + " times")
main()
|
def encrypt(alphabet):
REGULAR_CHARS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z"]
ENCRYPTED_CHARS = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
"z", "a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m"]
result = ''
list_alphabet = list(alphabet)
for i in range(len(list_alphabet)):
if list_alphabet[i].isalpha():
for j in range(len(REGULAR_CHARS)):
if list_alphabet[i]== REGULAR_CHARS[j]:
result += ENCRYPTED_CHARS[j]
if list_alphabet[i]== REGULAR_CHARS[j].upper():
result += ENCRYPTED_CHARS[j].upper()
else:
result+=list_alphabet[i]
return result
def row_encryption(in_string):
return encrypt(in_string) |
# Introduction to Programming
# Named parameters
# Default value of function arguments will be used if some of arguments is not appear in the function call
def print_box(width, height, border_mark="#", inner_mark=" "):
for i in range(height):
if i==0 or i==height-1:
print(width*border_mark)
else:
print(str(border_mark) + (width-2)*str(inner_mark) + str(border_mark) )
print()
def main():
print_box(5, 4)
print_box(3, 8, "*")
print_box(5, 4, "O", "o")
print_box(inner_mark=".", border_mark="O", height=4, width=6)
main()
|
def read_message(prompt):
result = []
result.append(input(prompt))
return result
def main():
print("Enter text rows to the message. Quit by entering an empty row.")
#in_string = ""
while True:
result = read_message("")
if result[len(result)-1] == "":
break
print("The same, shouting:")
for e in result:
print(e.upper())
main()
|
# Johdatus ohjelmointiin
# Area
from math import sqrt
def area(s1, s2, s3):
s_half = (s1 + s2 + s3) / 2
area_tri = sqrt(s_half * (s_half - s1) * (s_half - s2) * (s_half - s3))
return area_tri
def main():
rivi1 = float(input("Enter the length of the first side: "))
rivi2 = float(input("Enter the length of the second side: "))
rivi3 = float(input("Enter the length of the third side: "))
print("The triangle's area is ", format(area(rivi1, rivi2, rivi3), '.1f'))
main()
|
# Intro to programming
# Polynome
# Phan Viet Anh
# 256296
class Operand:
def __init__(self, number, co_efficent):
self.__number = number
self.__co_efficent = co_efficent
def get_number(self):
return self.__number
def get_coefficent(self):
return self.__co_efficent
def set_number(self, num):
self.__number = num
def add(self, polynome):
return Operand(self.__number + polynome.get_number(),
self.__co_efficent)
def substract(self, polynome):
return Operand(self.__number - polynome.get_number(),
self.__co_efficent)
def multiply(self,polynome):
return Operand(self.__number * polynome.get_number(),
self.__co_efficent + polynome.get_coefficent())
def print(self):
if self.get_number() == 0:
return str(0)
# elif self.get_coefficent()==0:
# return str(self.get_number())
else:
return str(self.get_number()) + 'x^' + str(self.get_coefficent())
class Polynome:
"""
class Polynome with private property is a list of operands which exponents and
coefficents stored in another list
ie. polynome: 5x^4 + 3x^2 will be like [[5 4], [3, 2]]
"""
def __init__(self, polynome):
self.__polynome = polynome
def get_polynome(self):
return self.__polynome
def add(self, polynome):
for index in range(len(result)):
for polynome in polynomes[operator2]:
if result[index].get_coefficent()== polynome.get_coefficent():
#result[index].set_number(result[index].get_number() + polynome.get_number())
result[index] = result[index].add(polynome)
break
else:
if not check_polynome(polynome,result):
result.append(polynome)
def read_file_input(prompt):
database = []
try:
filename = input(prompt)
with open(filename, 'r') as file:
while True:
line = file.readline().rstrip()
if line == '':
break
strings = line.split(';')
sub_poly = []
for element in strings:
poly = element.split(' ')
operand = Operand(int(poly[0]), int(poly[1]))
sub_poly.append(operand)
database.append(Polynome(sub_poly))
return database
except OSError:
print("Error in reading the file.")
def add_command(operator1, operator2, polynomes):
if operator1 in range(0,7) and operator2 in range(0, 7):
print_polynome(operator1, polynomes)
print_polynome(operator2, polynomes)
result = [poly for poly in polynomes[operator1]]
for index in range(len(result)):
for polynome in polynomes[operator2]:
if result[index].get_coefficent()== polynome.get_coefficent():
#result[index].set_number(result[index].get_number() + polynome.get_number())
result[index] = result[index].add(polynome)
break
else:
if not check_polynome(polynome,result):
result.append(polynome)
simplified(result)
else:
print("Error: the given memory location does not exist.")
def check_polynome(polynome, result):
found = False
for poly in result:
if polynome.get_coefficent() == poly.get_coefficent():
found = True
break
return found
def multiply_command(operator1,operator2, polynomes):
result = []
if operator1 in range(0, 7) and operator2 in range(0, 7):
print_polynome(operator1, polynomes)
print_polynome(operator2, polynomes)
for poly in polynomes[operator1]:
for polynome in polynomes[operator2]:
new_poly = poly.multiply(polynome)
if not check_polynome(new_poly,result):
result.append(new_poly)
else:
for index in range(len(result)):
if result[index].get_coefficent() == new_poly.get_coefficent():
result[index].set_number(result[index].get_number() - new_poly.get_number())
break
simplified(result)
else:
print("Error: the given memory location does not exist.")
def substract_command(operator1,operator2, polynomes):
if operator1 in range(0, 7) and operator2 in range(0, 7):
print_polynome(operator1, polynomes)
print_polynome(operator2, polynomes)
result = [poly for poly in polynomes[operator1]]
for index in range(len(result)):
for polynome in polynomes[operator2]:
if result[index].get_coefficent() == polynome.get_coefficent():
# result[index].set_number(result[index].get_number() + polynome.get_number())
result[index] = result[index].substract(polynome)
break
else:
if not check_polynome(polynome, result):
polynome.set_number(0 - polynome.get_number())
result.append(polynome)
simplified(result)
else:
print("Error: the given memory location does not exist.")
pass
def list_polynome(polynomes):
for index in range(len(polynomes)):
print('Memonry location ' + str(index) + ': '
+ ' + '.join(polynome.print() for polynome in polynomes[index]))
def print_polynome(position, polynomes):
a = sorted(polynomes[position], key=lambda poly: poly.get_coefficent(), reverse=True)
print('Memonry location ' + str(position) + ': '
+ ' + '.join(polynome.print() for polynome in a))
def simplified(result):
print("The simplified result: ")
print(' + '.join(polynome.print()
for polynome in sorted(result,
key=lambda poly: poly.get_coefficent(),
reverse=True) if polynome.get_number() !=0) )
def common_user_interface(polynomes):
while True:
command = input('> ')
if command == 'quit':
print('Bye bye!')
break
operators = command.split(' ')
if len(operators) !=3:
print('Error: entry format is memory_location operation memory_location.')
elif operators[1] not in ('+', '*', '-'):
print("Error: unknown operator.")
elif operators[1] == '+':
add_command(int(operators[0]), int(operators[2]), polynomes)
elif operators[1] == '*':
multiply_command(int(operators[0]), int(operators[2]), polynomes)
elif operators[1] == '-':
substract_command(int(operators[0]), int(operators[2]), polynomes)
else:
pass
def main():
database = read_file_input("Enter file name: ")
print(database[0].get_polynome())
# if polynomes is not None:
# common_user_interface(polynomes)
main()
|
def are_all_members_same(my_list):
index = 0
T=True
while index < len(my_list):
if my_list[index] == my_list[index - 1]:
T=True
else:
T= False
break
index += 1
# if index>=len(my_list): break
return T
def main():
print(are_all_members_same([42, 42, 42, 43, 42]))
print(are_all_members_same([42, 42, 42, 42, 42]))
main() |
num_in = int(input("Choose a number: "))
i = 1
while 1:
print(i, "*", num_in, "= ", num_in * i)
i += 1
if num_in * i > 100:
print(i, "*", num_in, "= ", num_in * i)
break
|
import time
start_time = time.time()
curr_time = start_time
count = 0
while curr_time - start_time < 1:
curr_time = time.time()
count += 1
print(count)
time1 = time.time()
for _ in range(count):
time2 = time.time()
print(time2 - time1)
if time2 - time1 < 1:
print('for is faster')
else:
print('while is faster')
|
#!/usr/bin/python
# coding=utf-8
"""
#########################################################################################
> File Name: recursive.py
> Author: Ywl
> Descripsion:
> Created Time: Tue 24 Apr 2018 01:45:22 AM PDT
> Modify Time:
#########################################################################################
"""
def countdown(num):
if num <= 1:
return 1 #基线条件,即什么时候不调用自己
else:
return num + countdown(num-1) #递归条件,即什么时候调用自己
#return 是出栈,调用是入栈
if __name__ == '__main__':
print(countdown(5))
|
#!/usr/bin/python
# coding=utf-8
#循环:while()用于条件语句循环执行某条语句,for常用于序列化变量的编列
lists1 = [10, 20, 30, 40]
event = []
print "while循环"
while len(lists1) > 0:
#注意出栈入栈顺序
list1 = lists1.pop()
event.append(list1)
print event
lists2 = [10, 30, 50, 70]
print "for 遍历"
for index in lists2:
print index
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " 是素数"
i = i + 1
print "Good bye!"
"""
Python pass 语句
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
Python 语言 pass 语句语法格式如下:
pass
当你在编写一个程序时,执行语句部分思路还没有完成,这时你可以用pass语句来占位,也可以当做是一个标记,是要过后来完成的代码。比如下面这样:
>>>def iplaypython():
>>> pass
定义一个函数iplaypython,但函数体部分暂时还没有完成,又不能空着不写内容,因此可以用pass来替代占个位置。
"""
# 输出 Python 的每个字母
for letter in 'Python':
if letter == 'h':
pass
print '这是 pass 块'
print '当前字母 :', letter
print "Good bye!"
|
"""
================================
Gaussian Mixture Model Selection
================================
Source: http://docs.w3cub.com/scikit_learn/auto_examples/mixture/plot_gmm_selection/
with appropriate modifications by Dario H. Romero - Dataset from Kaggle
This example shows that model selection can be performed with
Gaussian Mixture Models using information-theoretic criteria (BIC).
Model selection concerns both the covariance type
and the number of components in the model.
In that case, AIC also provides the right result (not shown to save time),
but BIC is better suited if the problem is to identify the right model.
Unlike Bayesian procedures, such inferences are prior-free.
In that case, the model with 8 components and full covariance
(which corresponds to the true generative model) is selected.
"""
import pandas as pd
import numpy as np
import itertools
from scipy import linalg
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import mixture
# from sklearn.preprocessing import LabelEncoder
# from sklearn.metrics import silhouette_score
print(__doc__)
# command on the output console to extend linesize
desired_width = 320
pd.set_option('display.width', desired_width)
# Load Dataset (Source: from Kaggle)
X = pd.read_csv('HR_data.csv')
X = X[X.columns[2:len(X.columns)]]
X.sales[X.sales == 'RandD'] = 'RnD'
# split column 'sales' into several binary columns
data_sales = pd.get_dummies(X['sales'])
# number = LabelEncoder()
# X['sales'] = number.fit_transform(X['sales'].astype('str'))
# split column 'salary' into several binary columns
data_salary = pd.get_dummies(X['salary'])
# X['salary'] = number.fit_transform(X['salary'].astype('str'))
# data_sales.head()
X.drop('sales', axis=1, inplace=True)
X.drop('salary', axis=1, inplace=True)
X = X.join(data_sales)
X = X.join(data_salary)
col_names = list(X)
#print(X.head())
# Initialize parameters
lowest_bic = np.infty
# lowest_aic = np.infty
bic = []
# aic = []
n_components_range = range(1, 13)
# cv_types is cross validation types
cv_types = ['spherical', 'tied', 'diag', 'full']
# Generate random seed, for reproducibility
np.random.seed(123)
for cv_type in cv_types:
for n_components in n_components_range:
# Fit a Gaussian mixture with EM
gmm = mixture.GaussianMixture(n_components=n_components,
covariance_type=cv_type)
gmm.fit(X)
# to avoid the risk of over/under fitting the data we need
# to run an optimization loop on the number of components
# using BIC (Bayesian Information Criteria) as a cost function.
bic.append(gmm.bic(X))
# aic.append(gmm.aic(X))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_bic_gmm = gmm
# if aic[-1] < lowest_aic:
# lowest_aic = aic[-1]
# best_aic_gmm = gmm
bic = np.array(bic)
color_iter = itertools.cycle(['navy', 'turquoise', 'cornflowerblue', 'darkorange',
'skyblue', 'fuchsia', 'green', 'mediumorchid',
'salmon', 'turquoise', 'seagreen', 'dodgerblue'])
# color_iter = itertools.cycle(['navy', 'turquoise', 'cornflowerblue', 'darkorange'])
clf_bic = best_bic_gmm
bars = []
Y_ = clf_bic.predict(X)
# print("======== number of components ========")
# print(" n_components: {}.".format(clf_bic.n_components))
# Plot the BIC scores
spl = plt.subplot(2, 1, 1)
for i, (cv_type, color) in enumerate(zip(cv_types, color_iter)):
xpos = np.array(n_components_range) + .2 * (i - 2)
bars.append(plt.bar(xpos, bic[i * len(n_components_range):
(i + 1) * len(n_components_range)],
width=.2, color=color))
plt.xticks(n_components_range)
plt.ylim([bic.min() * 1.01 - .01 * bic.max(), bic.max()])
plt.title('BIC score per model')
xpos = np.mod(bic.argmin(), len(n_components_range)) + .65 + \
.2 * np.floor(bic.argmin() / len(n_components_range))
plt.text(xpos, bic.min() * 0.97 + .03 * bic.max(), '*', fontsize=14)
spl.set_xlabel('Number of components')
spl.legend([b[0] for b in bars], cv_types)
#
# print("No of Components: {}".format(clf_bic.n_components))
# print("Means: {}".format(clf_bic.means_))
# print("Variance type: {}".format(clf_bic.covariance_type))
# print("Variances: {}".format(clf_bic.covariances_))
# print("Converged [True/False]: {}".format(clf_bic.converged_))
# Plot the winner
splot = plt.subplot(2, 1, 2)
X = np.array(X)
for i, (mean, cov, color) in enumerate(zip(clf_bic.means_, clf_bic.covariances_,
color_iter)):
v, w = linalg.eigh(cov)
if not np.any(Y_ == i):
continue
plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color)
# Plot an ellipse to show the Gaussian component
angle = np.arctan2(w[0][1], w[0][0])
angle = 180. * angle / np.pi # convert to degrees
v = 2. * np.sqrt(2.) * np.sqrt(v)
ell = mpl.patches.Ellipse(mean, v[0], v[1], 180. + angle, color=color)
ell.set_clip_box(splot.bbox)
ell.set_alpha(.5)
splot.add_artist(ell)
plt.xticks(())
plt.yticks(())
plt.title('Selected GMM: full model, {} components'.format(clf_bic.n_components))
plt.subplots_adjust(hspace=.35, bottom=.02)
plt.savefig('gmmBIC_getDummy_values.png')
plt.show()
# Print results to the console
ds = pd.DataFrame(X)
# Assign column names to ds DataFrame
ds.columns = col_names
# convert Y_ predicted cluster into dataframe
Y_df = pd.DataFrame(Y_)
Y_df.rename(columns={0: 'cluster'}, inplace=True)
# Concat both DataFrames
ds = pd.concat([Y_df, ds], axis=1)
ds = ds.sort_values(by=['cluster'])
ds.head()
ds.tail()
# Plot 3D
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# dss = pd.DataFrame([])
# n = 10
#
# for i in range(max(ds['cluster'].unique() + 1)):
# dss_x = pd.DataFrame(ds[ds.cluster == i][:(max(ds['cluster'].unique()))][['cluster',
# 'satisfaction_level',
# 'last_evaluation',
# 'average_monthly_hours']])
# dss = pd.concat([dss, dss_x])
#
# print(dss)
# colors = ('navy', 'turquoise', 'cornflowerblue', 'darkorange', 'skyblue', 'fuchsia',
# 'green', 'mediumorchid', 'salmon', 'turquoise', 'seagreen', 'dodgerblue')
# # for i in range(max(ds['cluster'].unique() + 1)):
# for dss, color in zip(dss[:3], colors):
# print(color)
# # ax.scatter(dss['satisfaction_level'], dss['last_evaluation'], dss['average_monthly_hours'],
# # c=color[i], alpha=0.8)
#
# ax.set_xlabel("satisfaction level")
# ax.set_ylabel("last evaluation")
# ax.set_zlabel("avg monthly hours")
# plt.title("3D Plot - Only 3 Columns from Dataset")
# plt.show()
#
# # Plot 3D - test 2
# # group = pd.DataFrame([])
# # for i in range(max(ds['cluster'].unique() + 1)):
# # print("Cluster {}".format(i))
# # df = pd.DataFrame(ds[ds.cluster == i][:10][['satisfaction_level', 'last_evaluation', 'average_monthly_hours']])
# # group = pd.concat([group, df])
# # print(df)
# # print(" ======== ")
# # print(group)
#
# # pd.DataFrame(ds[ds.cluster == 0][:10])[['satisfaction_level', 'last_evaluation', 'average_monthly_hours']]
|
# Classification template
# use tf.data-preprocessing-template to adjust parameters
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
# get only age and EstimatedSalary
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# take 100 and 300 split
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Fit Logistic Regression to Training Set
# use linear model library, as they are separated into a linear model
from sklearn.linear_model import LogisticRegression
# create classifier for training set
classifier = LogisticRegression(random_state = 9)
# fit classifier into test set
# this is so that the classifier can learn the correlation between X and y train
classifier.fit(X_train, y_train)
# now we predict the test results after the training set has built the model
# use _pred for prediction notation
y_pred = classifier.predict(X_test)
# we need to create a Confusion Matrix
# then we need to evaluate the results, comparing the prediction and the actual test
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
# Visualising the Training set results
from matplotlib.colors import ListedColormap
# first we set the x and y axis
X_set, y_set = X_train, y_train
# then we create the plot pixel by pixel for every possible point (or unit by unit)
# then the ListedColormap will put red and green for 0 and 1 results from the
# classifier respectively
# the limits are straight line
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
# X_set[:, 0].min() - 1 takes the minimum value of the X_set - 1, so that it will not be cluttered
# same for the stop variable, and similar for the salary range
# this step decides the scale of the graph
# this following function is where we apply the classifier, where colours are also applied
# contourf takes care of the colouring
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
# the following code will plot the limits of the estimated salary
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
# the loop here plots all the data points that are the real values from X_set, y_set
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
# the following code is just to indicate which is which
plt.title('Classifier (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
# display graph
plt.show()
# IMPLICATIONS FROM TRAINING SET
# points on the graph shows all the data points for the TRAINING SET
# each user is characterised by age and salary (x and y axis resp)
# red ones are training observations where purchased = 0
# green ones is 1
# people with higher salaries are predicted to buy the SUV
# older people are predicted to buy the SUV (probably because of savings?)
# goal is to classify the right users to the right category
# the two categories are yes or no to buying the SUV
# prediction regions (red and green) represent the classifications
# thus implication is that the company can target the ads more towards the
# green region
# straight line is called the "prediction boundary"
# the fact that it is a straight line is because the logistic regression classifier
# is linear as we set it previously
# in 3D comparatively it's going to be a plane separating 2 3D spaces
# if we build a Non-Linear Classifier, then the prediction boundary will not
# be a straight line
# the randomness of data and the fact that we're using only a linear separator
# there are still quite a lot of errors
# now we visualise the test set using the same boilerplate code
# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
# IMPLICATIONS FROM TEST SET
# the two matrixes we see is the Right or Wrong from 2 different prediction
# regions
|
user_number = input('Please enter some number: ')
user_number_len = len(user_number)
if int(user_number) % 2 == 0:
print('number is even')
else:
print('Number is odd')
print(int(user_number) ** 2)
if user_number_len == 1:
print('There is ' + str(user_number_len) + ' digits in number ' + user_number)
elif user_number_len > 1:
print('There are ' + str(user_number_len) + ' digits in number ' + user_number)
|
"""
=================== TASK 2 ====================
* Name: Roll The Dice
*
* Write a script that will simulate rolling the
* dice. The script should fetch the number of times
* the dice should be "rolled" as user input.
* At the end, the script should print how many times
* each number appeared (1 - 6).
*
* Note: Please describe in details possible cases
* in which your solution might not work.
===================================================
"""
#Write your script here
#silumacija bacanja kocke od korisnika uzmemo broj i ispisemo koliko je bilo jedinica dvojki itd
import random
jedinica = 0
dvojki = 0
trojki = 0
cetvorki = 0
petica = 0
sestica = 0
korisnik = input("Koliko puta zelite da bacite kockicu:")
for i in range(int(korisnik)):
kockica = random.randint(1, 6)
if kockica ==1:
jedinica +=1
if kockica ==2:
dvojki +=1
if kockica ==3:
trojki +=1
if kockica ==4:
cetvorki +=1
if kockica ==5:
petica +=1
if kockica ==6:
sestica +=1
print("Palo jedinica:" + str(jedinica))
print("Palo dvojki:" + str(dvojki))
print("Palo trojki:" + str(trojki))
print("Palo cetvorki:" + str(cetvorki))
print("Palo petica:" + str(petica))
print("Palo sestica:" + str(sestica)) |
class Parent1 ():
clas_var = 10
def __init__(self):
print ("Inside Parent_one Init Method")
def add(self , a ,b):
print ("Inside Parent_one Add Method")
return a+b
def mul(self , a ,b,c):
print ("Inside Parent_one mul Method")
return a*b*c
def common(self):
print ("Inside Parent_one Common Method")
class Parent2 ():
clas_var = 20
def __init__(self):
print ("Inside Parent_two Init Method")
def add(self , a ,b,c):
print ("Inside Parent_two Add Method")
return a+b
def mul(self , a ,b):
print ("Inside Parent_one Add Method")
return a*b
def common(self):
print ("Inside Parent_Two Common Method")
class Child(Parent1,Parent2):
def __init__ (self):
print ("Inside Child Init Method")
c =Child()
print(Child.__mro__) #Child --Class name we need to give not the Object name
#Method Resolution Order (<class '__main__.Child'>, <class '__main__.Parent1'>, <class '__main__.Parent2'>, <class 'object'>)
#Method resollution order will tell you , which classs method will executed first and which one is next.
sum1= c.add(12,25,45)
# mul =c.mul(10,20)
"""
Traceback (most recent call last):
File "c:/PythonPracticce/PythonPractice_Spyder/OOPS_Practice/Multiple_InheretinceDemo.py", line 43, in <module>
mul =c.mul(10,20)
TypeError: mul() missing 1 required pos itional argument: 'c'
"""
#Even If we have same method,with different arguments also we are going to invoke parent 1 method and raise error If arguments
#Not matched.
#
mul2 = c.mul(10,20,30) |
# Split camel case letters into invidual letters
# Python3 program Split camel case
# string to individual strings
def camel_case_split(str):
words = [[str[0]]]
print ('Words are ',words)
for c in str[1:]:
if words[-1][-1].islower() and c.isupper():
words.append(list(c))
else:
words[-1].append(c)
print ('Words are ',words)
for word in words:
print ('word is',word)
return [''.join(word) for word in words]
# Driver code
str = "GeeksForGeeks"
print(camel_case_split(str)) |
"""
Python Scope follows LEGB Rule:
1. Locals
2. Enclosing Function Locals
3. Global
4. Built In
"""
name = "This is Global Name"
def greet():
name = "New Name"
def hello():
print ("Hello "+name) #Local Name
hello()
greet()
print(name)#Global Name
#--------------------------------------
x =100
def func(x):
print('X inside func',x)
x =1000
print('x After changed ',x)
func(x)
print('x outside function',x)
#-----------------------------------------------
def func2(x):
global x
x=1000
print('Before calling function',x)
func2()
print('After Calling Function',x)
#Here instead of Global keyword we can return the variable and assign variable to requred variable.
|
#Strings are creed by using quotes
str_1 = "double quoted"
str_2= 'single quoted'
print (str_1,str_2)
why_1 = 'to use double quote in the string "Hello" then use single quote for string representation '
why_2 = "to use single quote inside the string say reddem's use double quotes in string declaration"
print (why_1)
print(why_2)
why_not_1 = "It is \"Hello\" greetingd "
print (why_not_1)
why_not_2 = 'It\'s greetingd '
print (why_not_2)
# \n is used for new line and \t used for tab \\ is used for black slash in the string
esc_seq1= "its example \n sequence \t for blackslash \\"
print(esc_seq1)
# We have raw Strings prevented from the escape sequences , if we use 'r' before string declaration
#then it is a raw string so escape sequences will not effect
raw_line_1 = r'it is a \nrawString\nescape sequence \nwill not effect'
raw_line_2 =r"itd\trawstring\\"
print(raw_line_1)
print(raw_line_2)
sub_text ="double"
#concatination of String
print(sub_text+sub_text)
#repeat same char multiple times by using the * symbol
print('a' * 50)
#return length ,min and Max functions in the given string.
print("the length of the String " ,len(sub_text))
print("the min of the String " ,min(sub_text))
print("the max of the String " ,max(sub_text))
main_text= "It's a double value"
#Check the given string is present in the main string or not by using
#'not in' and 'in' functions
print("The sub string is present in the main string ", sub_text in main_text)
print("The sub string is not present in the main string " , sub_text not in main_text)
#String objects have many methods like
print('the count is ' ,sub_text.count('e')) # number of e is existing in the string
print('the count is ' ,sub_text.index('e')) # index where the e is exists
print('the count is ' ,sub_text.index('u',0,5)) # index where the e is exists,if char is not exists then "ValueError: substring not found" not exists
print('the count is ' ,sub_text.find('e')) # if string exists returns true else returns false
# We have startWith , upper ,lower ,endsWith ,split , join , isalpha, isdigit() mehods exists
zenPython = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
words = zenPython.split(sep = " ",maxsplit=-1)
print(len(words))
print(words)
words =[ w.strip('\n.*!-.') for w in words]
print(words)
words = [w.replace('\n','') for w in words]
print(words)
#print(words)
words_list = []
mulltiline_list = zenPython.splitlines()
for line in mulltiline_list :
if line != "":
wordsList_inline =line.split()
words_list.extend(wordsList_inline)
print(len(words_list))
print(words_list)
words_list = [w.lower() for w in words_list]
print(words_list)
print(len(words_list))
#How can we get a unique set of values from a list -We need to use set
unique_words = set(words_list)
print(len(unique_words))
print(unique_words)
dict = {word : words_list.count(word) for word in words_list }
total_words =0;
for value in dict :
total_words += dict[value]
print(total_words)
print("dict is",dict)
frequent_words = { words :count for (words,count) in dict.items() if count >5}
print(frequent_words)
|
"""
Say suppose we have a Car class and we need to replace speed with string variable after instance created
It is possible to overide
So when we give our data to others --then encapulation plays a big role
Q. How to make attribute Private in you class?
We can use double underscore before an attribute, then it becomes private. So whenever we use double underscore --it makes our dagta private.
"""
class ENcp():
def __init__(self):
self.a =10
self._b=20 # it is partially private variable it's only convention still we can acces the values.
self.__c =30
e =ENcp() #created an Object
print(dir(e)) #_ENcp__c--->pvt ariable
"""
['_ENcp__c', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', '_b', 'a']['_ENcp__c', '__class__', '__delattr__', '__dict__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_b', 'a']
"""
print("Printinf a",e.a)
print("Printinf b",e._b)
#print("Printinf a",e.__c) # Here we will get an error,since we have used __
# before c that means it is a private variable with variable name as c
"""
Traceback (most recent call last):
File "c:/PythonPracticce/PythonPractice_Spyder/OOPS_Practice/Encaptualation_Demo.py", line 22, in <module>
print("Printinf a",e.__c) # Here we will get an error,since we have used __ before c that means it is a private variable with variable name as c
AttributeError: 'ENcp' object has no attribute '__c'
"""
#print("Variable c is ",e.c)
"""
Traceback (most recent call last):
File "c:/PythonPracticce/PythonPractice_Spyder/OOPS_Practice/Encaptualation_Demo.py", line 30, in <module>
print("Variable c is ",e.c)
AttributeError: 'ENcp' object has no attribute 'c'
PS C:\PythonPracticce>"""
#So how can we access the private data ?
#Ans: For this purpose we need to create setters and getters to take control over data is called Encapulation.
class Car():
def __init__(self,name,speed):
self.__name =name #Now name is a private variable.
self.__speed = speed
def set_speed(self,value):
self.__speed =value
def get_speed (self):
return self.__speed
def __privateMethod(self):
pass
#Same way we can define private methods indide a class
ford = Car('Ford',200)
ford.__name ="MGT"
ford.set_speed(455)
#WE can not inherit private members of super class into a subclass.
print(ford.__name)
print(ford.get_speed())
#Needs to check above problem
class Cat ():
def __init__(self,legs):
self.__legs =legs
c =Cat(4)
"""
print(c.__legs)
Traceback (most recent call last):
File "c:/PythonPracticce/PythonPractice_Spyder/OOPS_Practice/Encaptualation_Demo.py", line 72, in <module>
print(c.__legs)
AttributeError: 'Cat' object has no attribute '__legs'
""" |
#------------------------------------------------------------------------------------------
"""
NameSpaces are collection of names, It is a mapping of every name with an object.
1.Built in Name space -available before we start a program.Ex :id(),print(),type() ...etc
2.Global Name Space - Every module can create it's global names ,These are isolated with other modules
3.Local Name Spaces - Every module has functions and classes - So these all are having local name spaces
Variable Scope :
Although there are various namespaces availble ,we may not access all of them ,Since scope of variable concept
comes into the picture.
There are we have below scope of the variable.
"""
#-------------------------------------------------------------------------------------------
def outer_function(a):
a=10# ------------------------------------------------> Local Scope variable for outer most functon
def inner_function(a):
a=20 #--------------------------------------------> Local scope for inner function and it is nested scope
print("a inside the inner_function",a)
inner_function(a)
print("a inside the outer_function",a)
a=30 #----------------------------------------------------> Global Variable
outer_function(a)
print("global the value of a is ",a)
"""
In the above program , If we are in inside the inner function then the varaible a is just a local variable
We can use the variable , but we can not assign the variable , If we assign a new value to 'a' then it is going to create a
new variable .
"""
#If we need to refer the variable to global , then we need to use global key word
#Here, all reference and assignment are to the global a due to the use of keyword global.
def outer_function():
global a
a=10# ------------------------------------------------> Local Scope variable for outer most functon
def inner_function():
global a
a=20 #--------------------------------------------> Local scope for inner function and it is nested scope
print("a inside the inner_function",a)
inner_function()
print("a inside the outer_function",a)
a=30 #----------------------------------------------------> Global Variable
outer_function()
print("global the value of a is ",a)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 02:27:22 2019
@author: Sanvi
"""
a=10
print(bin(a))
print(oct(a))
print(hex(a))
c= 0b01010
print(type(c))
print(c)#still it prints a decimal number to user
"""
0b -binary
0o -octal
0x -Hex decimal
"""
|
#-----------------------------------------------------------------------------------------
# Your previous Plain Text content is preserved below:
#
# Belzabar is 18 years old. On this occasion, we formulated the Belzabar Number. A positive integer is a Belzabar number if it can be represented either as (n (n + 18)) OR (n (n - 18)), where n is a prime number.
#
# Write a function named 'is_belzabar_number' which accepts a number as input and determines if it is a Belzabar Number (or not). Input to the function will be a number and the output will be boolean.
#
# For bonus points,
# 1. Write a function that calculates and prints the count of Belzabar numbers less than or equal to 1 million.
# 2. Write a function that calculates and prints the count of Belzabar numbers from bonus question #1 above that are prime.
#
# There are additional bonus points for elegance, adequate code comments describing the algorithm(s) used, focus on coding conventions, optimal speed and time complexity and readability.
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# Method to CHeck the Prime Number
# ----------------------------------------------------------------------------------------
def is_primeNumber(num):
""" This method returns True If given Number is Prime Else False """
if num <= 1:
return False
for i in range (2,num-1):
if (num%i==0):
return False
return True
belzabar_Number = int (input ("Please Enter your Number"))
""" determine given Number is belzabar Number or Not """
def is_belzabar_number(number):
belzabar_Year = 18
flag = True
inc = 2
#------------------------------------------------------------------------------------
# Even Prime Number :For Even Prime Numbers - There is only one Possible positive
# Belzabar Number Exists i.e.40 ( n= 2 -- (2 * (2+18))
#
# Odd Prime Numbers : We will Loop until we found given Belzabar number or greater
# number by using equation (n * (n+18) )
#------------------------------------------------------------------------------------
if number % 2 == 0:
belzabar_Number_EvenPrime = 2
if (number == (belzabar_Number_EvenPrime * (belzabar_Number_EvenPrime + belzabar_Year))):
return True
else :
return False
else:
temp = 1
while flag:
x = temp * (temp + belzabar_Year)
if x >= number:
break
temp = temp + inc
# ------------------------------------------------------------------------------------
# Case 1: If number matches with the given input Number:
# Sub Case 1: Check for Member is Prime or Not , If yes Return True Else Execute
# below code (This is sollution for (n * (n +18)))
# Sub case 2: Needs to determine sollution for (n * (n - 18))) i.e. ( temp +18) for
# positive integers. (difference is 18)
# Number (n * (n +18)) Sollution (n * (n - 18)) Sollution
# ---------------------------------------------------------------------
# 19 1 19
# 40 2 20
# 63 3 21
# Case 2: If number does not match then return False as Both equeations does not have
# sollution
#-----------------------------------------------------------------------------------
if x == number:
if(is_primeNumber (temp)):
return True
else :
if(is_primeNumber (temp + belzabar_Year)):
return True
return False
print ('given Number is belzabar Number or Nor ...', is_belzabar_number(belzabar_Number))
#----------------------------------------------------------------------------------------
# 1. Write a function that calculates and prints the count of Belzabar numbers less than
# or equal to 1 million.
# Function to Calculate Belzabar Numbers under Million
#----------------------------------------------------------------------------------------
ONE_MILLION = 1000000
def belzabar_Numbers_Under_Million(input_Number ):
""" Determine the Count of Belzabar Numbers Under Million"""
temp = 1
belzabar_Year = 18
flag = True
while flag:
x = temp * (temp + belzabar_Year)
if x >= input_Number :
break
temp = temp + 1
if x == input_Number:
return temp
else:
return temp - 1
print ('belzabar Numbers Under one Million', belzabar_Numbers_Under_Million(ONE_MILLION))
# -------------------------------------------------------------------------------------- # 2. Write a function that calculates and prints the count of Belzabar numbers from bonus
# question #1 above that are prime.
# We can use the count of numbers to determine prime numbers from that
# -------------------------------------------------------------------------------------
def count_BelzabarNumbers_underMillion_WhichArePrime( number ):
""" Belzabar Numbers which are prime"""
count_Of_BelzaBar_Nmbrs = belzabar_Numbers_Under_Million(number)
prime_numbers = filter (is_primeNumber, list (range (2, count_Of_BelzaBar_Nmbrs +1) ))
return len (list (prime_numbers))
print (' belzabar Numbers Under one Million Which are Prime' , count_BelzabarNumbers_underMillion_WhichArePrime(ONE_MILLION)) |
#----------------------------------------------------------------------------------
""""
This File explains about input an doutput patterns
Input :
1. To read the data from user , we are using input function
2. By default it is a string data
To allow flexibility we might want to take the input from the user.
In Python, we have the input() function to allow this. The syntax for input() is
input([prompt])
Output :
1. to display the output to user in the console , we are using the "print" function.
2. output formats explained below.
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
sep ----> used to separate the different objects and The sep separator is used between the values.
It defaults into a space character.
end --->After all values are printed, end is printed. It defaults into a new line.
Here, objects is the value(s) to be printed.
Output Formatting:
Sometimes we would like to format our output to make it look attractive.
This can be done by using the str.format() method. This method is visible to any string object.
"""
#----------------------------------------------------------------------------------
#output :
str_example = "this is a string"
print("The String Exmple is ",str_example) #here we have a space between the string and varianle str_example
a,b,c= 4,"vijay",3+7j
print(a,b,c,sep=" && ",end="\n")
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
#output formatting
x,y =3,5
print("The value of the X is {} and Y is {} is ".format(x,y))
#Here the {} are used as place holders to display the values.
#We can use the index of tuple also ,by defining the values in the tuple
#Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).
print("The value of the z is {1} and a is {0} is ".format("undefined","infinity"))
#here ("undefined","infinity") --is taking as tuple with index of 0 and 1
# We can use dict as also , like keyword arguments to format the string.
print("Hello {name} ,{greetings}".format(name ="Vijay",greetings="Good Mornig" ))
#We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.
x = 12.3456789
print('The value of x is %3.2f' %x)
#The value of x is 12.35
print('The value of x is %3.4f' %x)
#The value of x is 12.3457
#Input Function
_str =input("Enter the name ")
# by default value is string ---to get the data into int , flowat or desired format ,
#we need to use the type conversion methods.
type(_str)
num = int(input("Enter the values "))
type(num)
#To-DO
#needs to learn about eval() function
add=int(input ())
"""
If we enter an exptression we are getting the below error , we can implement this by eval() function
5+6
Traceback (most recent call last):
File "C:/Users/Sanvi/PycharmProjects/PracticePython/Basics/Python_ApplicationPrograamming_Package/Input_OutputDemo.py", line 79, in <module>
add=int(input ())
ValueError: invalid literal for int() with base 10: '5+6'
"""
sum =eval(input())
print(sum) |
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
N=y.shape[0]
#D=W.shape[0]
C=W.shape[1]
global_loss=0
for i in np.arange(N):
local_numerator=0
local_denominator=0
for j in np.arange(C):#calculate denominator inside log
local_exp=np.exp(np.dot(X[i,:], W[:,j]))
local_denominator+=local_exp
for j in np.arange(C):
dW[:,j] += np.exp(np.dot(X[i,:], W[:,j])) * X[i,:] / local_denominator
dW[:,y[i]] -= X[i,:] #gradient by numerator of log
local_numerator=np.exp(np.matmul(X[i,:],W[:,y[i]]))#calculate numerator inside log
global_loss+=-np.log(local_numerator/local_denominator)#calculate loss for one sample
dW/=N
#regularization term
reg_term=np.sum(np.power(W,2)) * reg
loss += global_loss/N + reg_term
dW += 2 * reg * W
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
N=y.shape[0]
XW=np.matmul(X, W)
exp_term=np.exp(XW)
exp_sum=np.sum(exp_term, axis=1)
loss = np.sum(-np.log(exp_term[np.arange(N),y]/ exp_sum))/N #loss term
loss += np.sum(np.power(W,2)) * reg #reg loss term
dW = np.matmul(X.T, exp_term/np.reshape(exp_sum, (-1,1)))/N
binary=np.zeros_like(exp_term)
binary[np.arange(N), y]=1
dW -= np.matmul(X.T, binary)/N
dW += 2 * reg * W #reg dW term
pass
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
from scipy.stats import norm
import time, numpy as np
import statistics
import matplotlib.pyplot as plt
def ph_histogram(plant_list, year):
'''Creates a histogram of plant pH values'''
x = [plant.soil_ph for plant in plant_list]
n, bins, patches = plt.hist(x, bins = 50, range = (0,100), facecolor='g')
mean = sum(x)/len(x)
standarddev = statistics.stdev(x)
print("year: ", year)
print("mean: ", mean)
print("Standard Deviation: ", standarddev, "\n")
plt.xlabel('Soil pH (Arbitrary Units)')
plt.ylabel('Frequency (# Plants)')
plt.title("Histogram of Plants Sorted by Ideal Soil pH: \nYear " + str(year))
plt.xlim(0, 100)
plt.grid(True)
plt.show()
def plant_efficiency(ph_at_plant):
'''Plots one plants energy efficiency - pH relationship'''
#Draws normal distribution
x = np.arange(0,100, 0.001)
y = norm.pdf(x,30,10)/norm.pdf(30,30,10)
plt.plot(x,y)
#draws point of intersection
plt.scatter(ph_at_plant, norm.pdf(ph_at_plant,30,10)/norm.pdf(30,30,10))
#draws vertical line
plt.axvline(ph_at_plant, lw = 1, label="pH at plant's location = " + str(ph_at_plant)) #draws verticle line
plt.xlabel("pH (Arbitrary Units)")
plt.ylabel("Efficiency (percent of energy produced kept)")
plt.title("Energy Efficiency of Plant at Varying pH")
plt.legend()
plt.grid(True)
plt.show()
def seed_by_time(seed_list, years):
plt.scatter(years, seed_list, linewidths=1)
plt.xlabel("Time(years)")
plt.ylabel("Seed Production")
plt.title("Energy Efficiency of Plant at Varying Soil ph")
plt.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
plant_efficiency(50)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.