text
stringlengths 37
1.41M
|
|---|
def show_big(somenumbers):
finallist = []
for i in range(1, len(somenumbers)):
if somenumbers[i] > somenumbers[i - 1]:
finallist.append(somenumbers[i])
return finallist
original_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
print(show_big(original_list))
### Alternative solution
print(list(original_list[i] for i in range(1, len(original_list)) if original_list[i] > original_list[i - 1]))
|
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(ar):
# Write your code here
pri = 0
sec = 0
for i, j in zip(ar,range(len(ar))):
pri += i[j]
for i, j in zip(ar,reversed(range(len(ar)))):
sec += i[j]
return abs(pri-sec)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
print(arr)
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
import pygame
from button2 import *
# initialize screen
pygame.init()
clock = pygame.time.Clock()
# create display
screen = pygame.display.set_mode((878, 878))
# title and icon
pygame.display.set_caption("Snake!")
icon = pygame.image.load('snake.png')
pygame.display.set_icon(icon)
# initialize board
board = Board()
types = {'empty': (0, 0, 0), 'food': (255, 0, 0), 'snake': (45, 175, 0)}
# game over text
font = pygame.font.Font('BalsamiqSans-Regular.ttf', 74)
def print_game_over():
text = font.render('GAME OVER', True, (0, 0, 0))
screen.blit(text, (218, 220))
running = True
key = prev = 'E'
while running:
# RGB background
screen.fill((240, 240, 240))
# check for key press
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN and prev != "N":
key = 'S'
elif event.key == pygame.K_UP and prev != "S":
key = 'N'
elif event.key == pygame.K_LEFT and prev != "E":
key = 'W'
elif event.key == pygame.K_RIGHT and prev != "W":
key = 'E'
elif board.game_over and event.key == pygame.K_SPACE:
key = 'SPACE'
elif event.type == pygame.QUIT:
running = False
# move snake
if not board.game_over:
board.move(key)
prev = key
# print board
for row in board.map:
for pix in row:
color = types[pix.type]
pygame.draw.rect(screen, color, pix.pos + (32, 32))
# print game over screen
if board.game_over:
pygame.draw.rect(screen, (255, 255, 255), (213, 213, 452, 102))
print_game_over()
if key == 'SPACE':
board = Board()
key = prev = 'E'
# update display
pygame.display.update()
# throttle frames per second and difficulty (higher FPS == harder)
clock.tick(8)
|
test_cases = int(input())
for i in range(0, test_cases):
number_of_shots = int(input())
movements = []
hits = 0
shots = input()
heights = shots.split()
moves = input()
for movement in moves:
movements.append(movement)
index = 0
for k in range(0, number_of_shots):
if (int(heights[index]) < 3) & (movements[index] == "S"):
hits += 1
elif (int(heights[index]) > 2) & (movements[index] == "J"):
hits += 1
index += 1
print(hits)
|
"""
Let's create a to do list. I know, thrilling.
Ask the user for 5 items to put into their to do list.
Once the user has provided 5 items, display the list back
to the user.
"""
print "Greetings Busy Bee! Let's get to work making that TO DO list!"
my_to_dos = []
list_len = 5
# HINT: You can see how many items are in the
# list by using the built-in function len!
# Example: len(my_to_dos)
# Now ask for user input, and remember we want **5 items**!!!
# How can we repeat asking the user to give us all the items?
while 1:
my_to_dos.append(raw_input("Please type in your to-do-list: > "))
if len(my_to_dos) > 4 :
break
print "Fantastic! Here is the list of things you have to do today:"
for item in my_to_dos:
print item
# Again, how can we repeat something? But this time
# it doesn't have to be tied to a specific condition.
# We just want to see everything in our list.
|
def stars(arr):
for x in arr:
print "*" * x
nums = [6,2,5,7,9]
stars(nums)
print "That was part 1, starting part 2"
def stars2(arr):
for x in arr:
if isinstance(x, int):
print "*" * x
elif isinstance(x, str):
length = len(x)
letter = x[0].lower()
print letter * length
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
stars2(x)
|
def pigLatinSimple(word):
if word[0] in "aeiou":
return word + "hay"
else:
return word[1:] + word[0] + "ay"
def pigLatinBest(word):
if word[0] in ['a','e','i','o','u']:
if word.isalnum():
return word + "hay"
else:
return word[:-1] + "hay" + word[-1]
elif word[0:2] in ['bl', 'br', 'ch', 'ck', 'cl', 'cr', 'dr', 'fl', 'fr', 'gh', 'gl', 'gr', 'ng', 'ph', 'pl', 'pr', 'qu', 'sc', 'sh', 'sk', 'sl', 'sm', 'sn', 'sp', 'st', 'sw', 'th', 'tr', 'tw', 'wh', 'wr']:
if word.isalnum():
return word[2:] + word[0:2] + "ay"
else:
return word[2:-1] + word[0:2] + "ay" + word[-1]
else:
if word.isalnum():
return word[1:-1] + word[0] + "ay"
else:
return word[1:-1] + word[0] + "ay" + word[-1]
def pigLatin(word):
if word[0] in ['a','e','i','o','u']:
return word + "hay"
elif word[0:2] in ['bl', 'br', 'ch', 'ck', 'cl', 'cr', 'dr', 'fl', 'fr', 'gh', 'gl', 'gr', 'ng', 'ph', 'pl', 'pr', 'qu', 'sc', 'sh', 'sk', 'sl', 'sm', 'sn', 'sp', 'st', 'sw', 'th', 'tr', 'tw', 'wh', 'wr']:
return word[2:] + word[0:2] + "ay"
else:
return word[1:] + word[0] + "ay"
def capitalizeSentence(s):
L = s.split(" ")
i = 0
while i < len(L):
L[i] = L[i].capitalize()
i += 1
return " ".join(L)
def pigLatinMultiple(s):
L = s.split()
i = 0
while i < len(L):
L[i] = pigLatin(L[i])
i += 1
return " ".join(L)
|
def isVowel(letter):
letter= letter.lower()
A = letter == 'a'
E = letter == 'e'
I = letter == 'i'
O = letter == 'o'
U = letter == 'u'
return A or E or I or O or U
def noVowels(s):
i = 0
result = ""
while i < len(s):
if not isVowel(s[i]):
result = result + s[i]
i = i + 1
return result
|
"""
def sumOfPowers(n):
power = 1
sumpower= 0
while 2**power <= n:
sumpower = sumpower + 2 ** power
power = power + 1
return sumpower
print sumOfPowers(0)
print sumOfPowers(10)
print sumOfPowers(2)
"""
def sumAtoB(a,b):
sumab = 0
while a <= b:
sumab = sumab + a
a = a + 1
return sumab
"""
print sumAtoB(0, 1)
print sumAtoB(1, 3)
print sumAtoB(2, 0)
"""
def sumRange(a,b):
if a < b:
return sumAtoB(a,b)
else:
return sumAtoB(b,a)
print sumRange(1, 2)
print sumRange(2, 1)
print sumRange(-3, -10)
|
def makeEvenList(n):
x = []
i = 0
while i < n:
x.append(i*2)
i += 1
return x
def makeHailList(n):
x = []
while n > 1:
if n%2 == 0:
x.append(n)
n = n / 2
else:
x.append(n)
n = 3 * n + 1
x.append(1)
return x
|
"""Creating cup pong"""
# from random import randint
CUP: str = '\U0001F964'
# SHOT: str = '\U00002716'
# first_row: str = CUP*4
# print(first_row)
# # print(len(first_row))
# second_row: str = CUP*3
# print("", second_row)
# # print(len(first_row) + len(second_row))
# third_row: str = CUP*2
# print(" ", third_row)
# # print(len(first_row) + len(second_row) + len(third_row))
# fourth_row: str = CUP
# print(" ", fourth_row)
# # print(len(first_row) +len(second_row) + len(third_row) + len(fourth_row))
# # cups: int = (len(first_row) +len(second_row) + len(third_row) + len(fourth_row))
# cups: str = first_row \
# + second_row \
# + third_row \
# + fourth_row
# print(cups)
print(CUP*4, "\n", CUP*3, "\n ", CUP*2, "\n ", CUP)
total_cups: str = CUP*4 + CUP*3
print(total_cups)
|
"""Challenge question 1."""
choice: int = int(input("Enter a number: "))
if choice < 50:
if choice < 25:
print ("A")
else:
print ("B")
else:
if choice > 75:
print ("C")
else:
print ("D")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-07-31 18:17:44
# @Author : Star ([email protected])
# @Link : https://github.com/chenstarsQ/My-Python-Study-Note
# @Version : $Id$
def dayUP(df):
dayup = 1
for i in range(1, 366):
if i % 7 in [6, 0]:
dayup = dayup * (1-0.01)
else:
dayup = dayup * (1+df)
return dayup
dayfactor = 0.01
while dayUP(dayfactor) < 37.78:
dayfactor += 0.001
print("工作日的努力参数是:{:.3f}".format(dayfactor))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-11-26 21:10:21
# @Author : Star ([email protected])
# @Link : https://github.com/chenstarsQ/My-Python-Study-Note
# @Version : $Id$
def getNum():
nums = []
iNumStr = input("请输入数字(回车退出):")
while iNumStr != "":
nums.append(eval(iNumStr))
iNumStr = input("请输入数字(回车退出):")
return nums
def mean(numbers):
s = 0.0
for num in numbers:
s = s+num
return s/len(numbers)
def dev(numbers, mean):
sdev = 0.0
for num in numbers:
sdev = sdev + (num-mean)**2
return pow(sdev/(len(numbers)-1), 0.5)
def median(numbers):
sorted(numbers)
size = len(numbers)
if size/2 == 0:
med = (numbers[size//2-1]+numbers[size//2])/2
else:
med = numbers[size//2]
return med
n = getNum()
m = mean(n)
print("平均值:{},方差:{:.2},中位数:{}.".format(m, dev(n, m), median(n)))
|
import re
# 使用 while 循环打印 1 3 5 7 9
i = 1
while i < 10:
if i % 2 == 1:
print(i)
i += 1
# 编写一个函数,查找数字 6 是否在列表 l 里,如果在,输出“found”,如果不在,输出“not found”
l = [1, 5, 7, 8, 9]
def found(lst):
if 6 in lst:
print('found')
else:
print('not found')
found(l)
# 将字符串 s 拆分成两个字符串 s1、s2,其中 s1 只包含字母,转换为小写,以 [a-z] 排序,s2 只包含数值,升序排序
s = "aAsnr3id2d4b6gs7DZsf9e1AF"
def split_seq(string):
s1 = re.findall('[a-z,A-Z]', string)
s1.sort()
s1 = [s.lower() for s in s1]
s2 = re.findall('\d+', string)
s2.sort()
print(''.join(s1), ''.join(s2))
split_seq(s)
|
class tree():
def __init__(self, p, root = 0, fathers = None, weigths = None):
self.__map = {}
self.__p = p
self.__root = root
if(fathers is not None and weigths is not None):
l = len(fathers)
self.__q = l
for i in range(1, l):
self.__map[i] = [fathers[i], weigths[i]]
elif(fathers is not None):
l = len(fathers)
self.__q = l
for i in range(1, l):
self.__map[i] = [fathers[i] , 0]
else:
self.__q = 0
def doesVHaveParent(self, v):
for i in self.__map:
if(i == v):
return True
return False
def add(self, v, parent ,weigth = 0):
if(v == self.__p):
self.__p += 1
elif(v > self.__p):
self.__p = v
if(self.doesVHaveParent(v) is False):
self.__map[v] = [parent, weigth]
self.__q += 1
def P(self):
return self.__p
def Q(self):
return self.__q
def root(self):
return self.__root
def climb(self, child):
path = [child]
v = child
while(v != self.__root):
path.append(self.__map[v][0])
v = self.__map[v][0]
return path
def isLeaf(self, v):
for i in self.__map:
if(self.__map[i][0] == v):
return False
return True
def pop(self, leaf):
if(self.isLeaf(leaf) is True):
self.__map.pop(leaf)
self.__q -= 1
def show(self):
print(self.__map)
|
'''
Created on 30 avr. 2018
@author: PASTOR Robert
'''
import numpy
import math
import random
from ForcesTorques import acceleration, angular_acceleration
from Controller import pid_controller
''' Simulation times, in seconds. '''
start_time = 0;
end_time = 10;
dt = 0.005;
times = [start_time,dt,end_time];
''' % Number of points in the simulation. '''
''' 'N = numel(times); '''
''' % Initial simulation state. '''
x = [0, 0, 10];
xdot = numpy.zeros(3, 1);
theta = numpy.zeros(3, 1);
'''% Simulate some disturbance in the angular velocity. '''
''' % The magnitude of the deviation is in radians / second. '''
deviation = 100;
'''thetadot = deg2rad(2 * deviation * rand(3, 1) - deviation); '''
thetadot = math.radians(2 * deviation * random.random(3, 1) - deviation);
'''% Step through the simulation, updating the state. '''
''' for t in times: '''
for t in numpy.arange(start_time, end_time + dt, dt):
''' % Take input from our controller. '''
print t
i = input(t);
omega = thetadot2omega(thetadot, theta);
''' % Compute linear and angular accelerations. '''
a = acceleration(i, theta, xdot, m, g, k, kd);
omegadot = angular_acceleration(i, omega, I, L, b, k);
omega = omega + dt * omegadot;
thetadot = omega2thetadot(omega, theta);
theta = theta + dt * thetadot;
xdot = xdot + dt * a;
x = x + dt * xdot;
''' end '''
def cost(theta):
'''% Create a controller using the given gains. '''
control = controller('pid', theta(1), theta(2), theta(3));
''' % Perform a simulation. '''
data = simulate(control);
''' % Compute the integral, $\frac{1}{t_f - t_0} \int_{t_0}^{t_f} e(t)^2 dt$ '''
t0 = 0;
tf = 1;
J = 1/(tf - t0) * sum(data.theta(data.t >= t0 & data.t <= tf) .^ 2) * data.dt;
return J
''' end '''
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from make_data import *
def validate_prediction(df_data, weight_vector):
a, b, c = weight_vector
df_data['pred'] = df_data.apply(lambda row : 1 if (a*row.x + b*row.y + c) >0 else 0, axis=1)
df_data['p'] = df_data.apply(lambda row : sigmoid(a*row.x + b*row.y + c), axis=1)
return df_data
|
def emoji_convertor():
emoji_dictionary = {
"happy": "😀",
"sad": "😐",
"excited": "🤓",
}
messages_list = message.split()
output = ""
for words in messages_list:
output = output + emoji_dictionary.get(words, words) + " "
print(output)
message = input("> ")
emoji_convertor()
|
import queue
from queue import PriorityQueue
import sys
import copy
# Sets the default recursion limit to satisfy the search
sys.setrecursionlimit(10**6)
# An object storing all the relevant information about the state,
# game board: stored as a single string
# g_n: the number of steps taken from the start to the current state
# h_n: the minimum number of steps needed to reach the goal state
# f_n: sum of g_n and h_n
# parent: the parent state which the current state derived from
class BoardState(object):
def __init__(self, board, g_n, h_n, f_n, parent):
self.board = board
self.g_n = g_n
self.h_n = h_n
self.f_n = f_n
self.parent = parent
# Overloads the less than comparator
# in order for the PriorityQueue to sort this class object
def __lt__(self, other):
return self.f_n < other.f_n
# This function provides an overall structure on the steps taken to solve
# the game Rush Hour
# @param:
# heuristic: the choice to heuristic to use in solve the game
# state: the initial state of the gameboard
def rushhour(heuristic, state):
# Converts the list of string into a single string for the initial board
initial_board = ""
for row in state:
initial_board += row
# Finds the h(n) of the initial state
cur_h_n = 0
if heuristic == 0:
cur_h_n = blocking_heuristic(initial_board)
else :
cur_h_n = custome_heuristic(initial_board)
# Creates the first state
initial_state = BoardState(initial_board, 0, cur_h_n, cur_h_n + 0, None)
# Creates a PriorityQueue to store all the states in order
frontier = PriorityQueue()
frontier.put(initial_state)
# Creates two lists to store the explored and unexplored states
explored_states = []
unexplored = []
# Uses the given choice of heuristics to determine the optimal solution
# Gets the end state
end_state = state_search(frontier,
heuristic,
explored_states,
unexplored)
# Creates a list to store the result gameboard in sequence
answer = []
# Fills up the list by getting the parent board repeatedly until reach the
# initial board
while end_state != initial_state:
answer.append(construct_board(end_state.board))
end_state = end_state.parent
answer.append(construct_board(initial_state.board))
answer = reverse(answer)
answer = complete_exit_move(answer) # In case it has not reach the exit
# Prints out the result of the game
for board in answer:
print_board(board)
print ('Total moves: ' + str(len(answer) - 1))
print ("Total states explored: " + str(len(explored_states)))
# This function performs a state search
# It follows the idea of A* algorithm
# @param:
# frontier: a PriorityQueue storing all the newly generated states
# heuristic: determine which heuristics to be used in the search
# explored_states: a list of explored_states
# (cannot iterator through PriorityQueue)
# unexplored: a list of unexplored states
#
# ***** returns only the end goal state *****
def state_search(frontier, heuristic, explored_states, unexplored):
if frontier.empty():
return []
curr_head = frontier.get()
if reach_goal(curr_head):
return curr_head
else:
new_boards = generate_new_boards(curr_head)
explored_states.append(curr_head)
# Adds the appropriate new states to the queue
for board in new_boards:
cur_h_n = compute_heuristic(heuristic, board)
cur_g_n = curr_head.g_n + 1
cur_f_n = cur_h_n + cur_g_n
state = BoardState(board, cur_g_n, cur_h_n, cur_f_n, curr_head)
if check_repeatition(state, unexplored) == True:
del state
elif check_repeatition(state, explored_states) == True:
del state
else:
frontier.put(state)
unexplored.append(state)
return state_search(frontier,
heuristic,
explored_states,
unexplored)
# This function determines whether the input state has reached the goal state
# ***** Here we think that as long as there is no
# blocking vehicles on the third row blocking
# the car X, it has reached the goal state. *****
# @param:
# curr_head: the state of the game to be determined
#
# returns True/False on whether it has reached the goal state
def reach_goal(curr_head):
cur_board = construct_board(curr_head.board)
if cur_board[2][4] == 'X' and cur_board[2][5] == 'X': return True
for char in cur_board[2]:
if char != 'X' and char != '-':
return False
return True
# This function checks for repeatition and eliminates redundant search
# @param:
# cur_state: the state to be checked for repeatitions
# states: a list of states to be searched
#
# returns True/False on whether it has repeatitions
def check_repeatition(cur_state, states):
for state in states:
if cur_state.board == state.board:
return True
return False
# This function compute the h_n of the given gameboard
# @param:
# heuristic: the choice of heuristic to adopt
# board: the current gameboard
#
# returns the computed h_n value
def compute_heuristic(heuristic, board):
if heuristic == 0:
return blocking_heuristic(board)
else:
return custome_heuristic(board)
# This function computes the customized heuristic
# ***** The central idea of this heuristic is to consider *****
# ***** the state of the blocking vehicles. *****
# First, find the information about the blocking vehicles
# Then, check whether these blocking vehicles have been blocked
# If they are blocked, compute the minimum steps needed to unblock
# so that they can move out of the way of the blocking vehicles
# so that the blocking vehicles can move out of the way of car X
# ***** In this heuristic, we also consider the exact number *****
# ***** of steps needed for car X to reach the exit, since X *****
# ***** could be very close but with more blocking vehicles *****
# ***** or could be far but with less blocking vehicles, and *****
# ***** former may be the optimal solution. *****
#
# @param:
# board: the current gameboard
#
# returns the h_n value
def custome_heuristic(board):
num_of_steps = 0
# This variable helps eliminate the vehicles before the X car
foundX = False
for i in range(12, 18):
if board[i] == 'X':
foundX = True
# Adds the number of steps needed to reach the exit
num_of_steps += 18 - i - 2
# If a vehicle is found, determine the type of the vehicle and
# whether the vehicle has been blocked by other vehicles
if (foundX == True and board[i] != 'X' and board[i] != '-'):
pos = find_vehicle_vertical(i, board)
# If the vehicle found is a truck
if pos[2] - pos[0] == 2:
num_of_steps += check_truck(pos, board)
# If the vehicle found is a car
else:
num_of_steps += check_car(pos, board)
return num_of_steps
# This function determines the minimum number of steps needed to move a
# vertical truck out of car X's way
# @param:
# pos: the coordinates of the truck
# in the form of [x_start, y_start, x_end, y_end]
# board: the current gameboard
#
# returns the minimum number of steps needed to move a vertical truck out
# of car X's way
def check_truck(pos, board):
steps = 0
# If it is positioned from the first row to the third row,
# the only choice to move it away is to move down 3 times
if pos[0] == 0:
steps += 3
# Check whether the spaces below the truck is empty
steps += check_space_below_truck(3-pos[0], board, pos)
# If it is positioned from the second row to the fourth row,
# the only choice to move it away is to move down 2 times
elif pos[0] == 1:
steps += 2
# Check whether the spaces below the truck is empty
steps += check_space_below_truck(3-pos[0], board, pos)
# If it is positioned from the third row to the fifth row,
# the only choice to move it away is to move down 1 time
else:
steps += 1
# Check whether the spaces below the truck is empty
steps += check_space_below_truck(3-pos[0], board, pos)
return steps
# This function checks whether the spaces below the truck are empty
# If not, how many steps minimum are needed to empty the spaces
# @param:
# space: the number of spaces to be checked
# board: the current gameboard
# pos: the coordinates of the truck
# in the form of [x_start, y_start, x_end, y_end]
#
# returns the minimum number of steps needed to empty the spaces
def check_space_below_truck(space, board, pos):
steps = 0
for i in range(1, space+1):
if board[(pos[2]+i)*6 + pos[1]] != '-':
steps += 1
# It the space is not empty,
# finds the position of the blocking vehicle
block_pos = find_vehicle_horizontal((pos[2]+i)*6 + pos[1], board)
steps += blocked_blocking_vehicle(pos, block_pos, board)
return steps
# This function detemines the minimum number of steps needed to move the
# blocking vehicle
# @param:
# pos: the coordinates of the truck (the blocking vehicle)
# in the form of [x_start, y_start, x_end, y_end]
# block_pos: the coordinates of the vehicle blocks the blocking vehicle
# in the form of [x_start, y_start, x_end, y_end]
# board: the current gameboard
#
# returns the minimum number of steps needed to move the blocking vehicle
def blocked_blocking_vehicle(pos, block_pos, board):
steps = 0
# If both sides of the blocking vehicle has been blocked or
# one side is blocked and the other side hits the wall
if ((block_pos[1] == 0 or board[block_pos[0]*6 + block_pos[1] - 1] == '-')
and (block_pos[3] == 5 or board[block_pos[2]*6 + block_pos[3] + 1] == '-')):
steps += 1
# Check how many steps needed to move the blocking vehicle
# if the blocking vehicle blocks the truck in the middle,
# then an extra step is needed
if (block_pos[1] < pos[1] and block_pos[3] > pos[1]):
steps += 1
# If one side of the vehicle hits the wall and it blocks the truck
# at some other position, an extra step is also needed
elif (block_pos[3] == 5 and pos[3] != 5):
steps += 1
return steps
# This function determines the minimum number of steps needed to move a
# vertical car out of car X's way
# @param:
# pos: the coordinates of the car
# in the form of [x_start, y_start, x_end, y_end]
# board: the current gameboard
#
# returns the minimum number of steps needed to move a vertical car out
# of car X's way
def check_car(pos, board):
steps = 1
# If the car is placed on the second and third row, and there is a
# vehicle blocking the car on top (the first row),
# then, an extra step is needed
if (pos[0] == 1 and board[pos[1]] != '-'):
steps += 1
# Finds the position of the vehicle blocking the car
block_pos = find_vehicle_horizontal(pos[1], board)
# If both sides of that vehicle has been blocked or
# one side is blocked and the other side hits the wall,
# then, an extra step is needed
if ((block_pos[1] == 0 or board[block_pos[1] - 1] != '-') and
(block_pos[3] == 5 or board[block_pos[3] + 1] != '-')):
steps += 1
# If the car is placed on the third and fourth row, and there is a
# vehicle blocking the car on the bottom (the fifth row)
# then, an extra step is needed
elif (pos[2] == 3 and board[(pos[2]+1)*6 + pos[3]] != '-'):
steps += 1
# Finds the position of the vehicle blocking the car
block_pos = find_vehicle_horizontal(pos[1], board)
# If both sides of that vehicle has been blocked or
# one side is blocked and the other side hits the wall,
# then, an extra step is needed
if ((block_pos[1] == 0 or board[block_pos[0]*6 + block_pos[1] - 1] != '-') and
(block_pos[3] == 5 or board[block_pos[2]*6 + block_pos[3] + 1] != '-')):
steps += 1
return steps
# This function computes the blocking heuristic
# @param:
# board: the current gameboard
#
# returns the computed h_n value
def blocking_heuristic(board):
num_of_vehicle_blocking = 0
# check the third row for the number of vehicles blocking the path
foundX = False
for i in range(12, 18):
if board[i] == 'X': foundX = True
if (foundX == True and board[i] != 'X' and board[i] != '-'):
num_of_vehicle_blocking += 1
if num_of_vehicle_blocking == 0: return 0
return 1 + num_of_vehicle_blocking
# This function generate new boards from the given board input
# We check for all the possible moves with every vehicle on the board
# @param:
# state: the base state
#
# returns a list of newly generated states
def generate_new_boards(state):
new_boards = []
visited = {}
cur_board = state.board
for i in range(0, len(cur_board)):
if cur_board[i] not in visited:
boards_moved = move_vehicle(i, cur_board)
for board in boards_moved:
new_boards.append(board)
visited[cur_board[i]] = True
return new_boards
# This function considers the movement possiblities for one specific vehicle
# @param:
# index: the index to detemine the specific vehicle
# board: gameboard stored in a single string
#
# returns a list of newly generated states for moving one vehicle
def move_vehicle(index, board):
boards_moved = []
# The vehicle is horizontal
if ((index > 0 and board[index-1] == board[index]) or
(index + 1 < len(board) and board[index+1] == board[index])):
start_end_pos = find_vehicle_horizontal(index, board)
# Checks for left and right with horizontal vehicle
left = move_left(board, start_end_pos)
if left != []:
boards_moved.append(left)
right = move_right(board, start_end_pos)
if right != []:
boards_moved.append(right)
# The vehicle is vertical
else:
start_end_pos = find_vehicle_vertical(index, board)
# Checks for up and down for vertical vehicle
up = move_up(board, start_end_pos)
if up != []:
boards_moved.append(up)
down = move_down(board, start_end_pos)
if down != []:
boards_moved.append(down)
return boards_moved
# This function finds the start and end coordinates of vertical vehicles
# @param:
# index: the index to detemine the specific vehicle
# board_string: gameboard stored in a single string
#
# return the coordinates of the vehicle in the form of a lists
# [x_start, y_start, x_end, y_end]
def find_vehicle_vertical(index, board_string):
board = construct_board(board_string)
row = int(index / 6)
col = int(index % 6)
# Creates a list storing the starting and ending position
res_pos = []
up = row
down = row
# Finds the starting position
while (up >= 0 and board[up][col] == board[row][col]):
up -= 1
# Adding the starting coordinates of the vehicle
if (up >= 0 and board[up][col] == board[row][col]):
res_pos.append(up)
else: res_pos.append(up+1)
res_pos.append(col)
# Finds the ending position
while (down < len(board) and board[down][col] == board[row][col]):
down += 1
# Adding the ending coordinates of the vehicle
if (down < len(board) and board[down][col] == board[row][col]):
res_pos.append(down)
else: res_pos.append(down-1)
res_pos.append(col)
return res_pos
# This function finds the start and end coordinates of horizontal vehicles
# and returns as list of [x_start, y_start, x_end, y_end]
# @param:
# index: the index to detemine the specific vehicle
# board_string: gameboard stored in a single string
#
# return the coordinates of the vehicle in the form of a lists
# [x_start, y_start, x_end, y_end]
def find_vehicle_horizontal(index, board):
row = int(index / 6)
col = int(index % 6)
# Creates a list storing the starting and ending position
res_pos = []
left = index
right = index
# Finds the starting position
while (left >= 0 and board[left] == board[index]):
left -= 1
# Adding the starting coordinates of the vehicle
res_pos.append(row)
if (left >= 0 and board[left] == board[index]):
res_pos.append(left % 6)
else: res_pos.append((left+1) % 6)
# Finds the ending position
while (right < len(board) and board[right] == board[index]):
right += 1
# Adding the ending coordinates of the vehicle
res_pos.append(row)
if (right < len(board) and board[right] == board[index]):
res_pos.append(right % 6)
else: res_pos.append((right-1) % 6)
return res_pos
# The following four functions move the vehicle in four different direcitons
# All the four functions have the same parameters
# @param:
# curr_board: a single string storing the current board state
# pos: the coordinates of the moving vehicle in the form of
# [x_start, y_start, x_end, y_end]
#
# All four functions return the new gameboard in the form of a single string
def move_up(curr_board, pos):
board = construct_board(curr_board)
# If the starting position is already on the first row
# or there is a vehicle blocking it moving up
if pos[0] == 0 or board[pos[0] - 1][pos[1]] != '-':
return []
# Move up
board[pos[0] - 1][pos[1]] = board[pos[0]][pos[1]]
board[pos[2]][pos[3]] = '-'
return board_to_string(board)
def move_down(curr_board, pos):
board = construct_board(curr_board)
# If the ending position is already on the last row
# or there is a vehicle blocking it moving down
if pos[2] >= len(board) - 1 or board[pos[2] + 1][pos[3]] != '-':
return []
# Move down
board[pos[2] + 1][pos[3]] = board[pos[2]][pos[3]]
board[pos[0]][pos[1]] = '-'
return board_to_string(board)
def move_left(curr_board, pos):
board = construct_board(curr_board)
# If the starting position is already on the first col
# or there is a vehicle blocking it moving left
if pos[1] == 0 or board[pos[0]][pos[1] - 1] != '-':
return []
# Move left
board[pos[0]][pos[1] - 1] = board[pos[0]][pos[1]]
board[pos[2]][pos[3]] = '-'
return board_to_string(board)
def move_right(curr_board, pos):
board = construct_board(curr_board)
# If the starting position is already on the last col
# or there is a vehicle blocking it moving right
if pos[3] == len(board) - 1 or board[pos[2]][pos[3] + 1] != '-':
return []
# Move right
board[pos[2]][pos[3] + 1] = board[pos[2]][pos[3]]
board[pos[0]][pos[1]] = '-'
return board_to_string(board)
# The following two functions are helper functions to switch the gameboard
# between a single string and a 2D array of characters
#
# Converts the board to a single string
# @param:
# board: an 2D array storing the gameboard
#
# returns the gameboard in the form of a single string
def board_to_string(board):
string = ""
for i in range(len(board)):
for j in range(len(board[0])):
string += board[i][j]
return string
# Constructs the board from a single string
# @param:
# string: the gameboard in the form of a single string
#
# returns an 2D array storing the gameboard
def construct_board(string):
board = [] * 6
for i in range(0, len(string)):
if i % 6 == 0:
new_row = [] * 6
new_row.append(string[i])
elif i % 6 == 5:
new_row.append(string[i])
board.append(new_row)
else:
new_row.append(string[i])
return board
# This functions prints the game board
# @param:
# state: 2D array representing the game board to be printed
def print_board(board):
for row in board:
for element in row:
print(element, end = ' ')
print()
print()
return
# This function completes the move from the current position to the exit
# when there is not blocking vehicles on the way
# Since we consider any state with no blocking vehicles blocking car X the
# goal state, car X might not reach the exit as we return the goal state
# Thus, we need to check and make sure that it reaches the exit
# @param:
# ans: a list of gameboard from the initial state to the goal state
#
# ***** we build on the last gameboard of the list to *****
# ***** complete the move to the exit. *****
#
# returns a complete step by step solution of the game
def complete_exit_move(ans):
cur_board = ans[len(ans) - 1]
car_pos_end = 0
for i in range(len(cur_board[2])):
if cur_board[2][i] == 'X':
car_pos_end = i + 1
break
for i in range(car_pos_end+1, len(cur_board[2])):
board = copy.deepcopy(cur_board)
board[2][i] = 'X'
board[2][i-2] = '-'
ans.append(board)
cur_board = board
return ans
# This helper function reverses the order of a list and is taken from
# professor's code on pegpuzzle
def reverse(st):
return st[::-1]
|
# Example:
# Read numbers until a sentinel (an empty string), and return their sum.
# JMR 2018
# This is a typical example of a "loop-and-a-half":
# a common situation where the exit condition
# should be tested in the middle of the loop body.
def inputTotal():
tot = 0.0
while True:
s = input("valor? ")
if s == "": break # if empty line, stop repeating!
v = float(s)
tot = tot + v
return tot
# MAIN PROGRAM
tot = inputTotal()
print(tot)
|
# Example: Listing directories and using file paths and metadata.
import os
import sys
# Ask the user for a directory name, and validate it.
def getDir(prompt):
while True:
name = input(prompt)
if os.path.isdir(name): break
print("{} não é diretório".format(name), file=sys.stderr)
return name
# Print a list of files (and their sizes) in the given directory.
def listDirSizes(dname):
lst = os.listdir(dname)
for name in lst:
# path = dir + "/" + name # not ideal...
path = os.path.join(dname, name) # this is better
st = os.stat(path) # get metadata about this path
print(name, path, st.st_size)
def main():
dname = getDir("Dir? ")
print("Listing:", dname)
listDirSizes(dname)
main()
|
# Example: Print truth tables of boolean expressions
# Consider three independent boolean variables A, B and C
# and two dependent variables X and Y given by:
# X = (A and not B) or C
# Y = A and (not B or C)
# Print the truth tables for these variables and check if X <=> Y.
#
# JMR 2019
boolValues = [False, True]
#boolValues = [0, 1] # another way to represent logical values...
for A in boolValues:
for B in boolValues:
for C in boolValues:
X = (A and not B) or C
Y = A and (not B or C)
print("{} {} {} {} {}".format(A,B,C,X,Y))
# Use format specifiers to align the columns
|
# Example: a simple translator
# A dict with translations of Portuguese words to English:
d = {"as": "the", "os": "the", "e": "and", "praia": "beach"}
# Try: as armas e os barões assinalados que da ocidental praia lusitana
s = input("Texto? ")
t = ""
for w in s.split():
if w in d: # check if word w is a key in dictionary d
w = d[w]
t = t + " " + w
print(t)
|
# Example:
# Write a function that counts down from N and then prints "Go!".
# Write both a recursive version and an iterative version.
# JMR 2018
# Recursive version
def countdownR(n):
if n > 0:
print(n)
countdownR(n-1)
else:
print("Go!")
# Iterative version
def countdown(n):
while n>0:
print(n)
n = n-1
print("Go!")
# MAIN PROGRAM
# Test both:
countdownR(5)
countdown(3)
|
# Example: loops inside loops
# JMR 2018
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def doSomething():
for c in letters:
for d in letters:
print(c+d)
# What does this print? How many lines?
doSomething()
|
import os
import pandas as pd
#print(courses)
def get_course_list():
courses = os.listdir('./data')
return courses
def get_departments_list(course):
courses = get_course_list()
if course not in courses:
return "Invalid course input"
departments = os.listdir('./data/' + course)
return departments
def get_papers_list(course, department):
departments = get_departments_list(course)
if departments == "Invalid course input":
return "Invalid course input"
if department not in departments:
return "Invalid department input"
papar_list = os.listdir('./data/' + course + '/' + department)
return papar_list
def get_departments_dict(course):
data = []
courses = get_course_list()
if course not in courses:
return "Invalid course input"
departments = os.listdir('./data/' + course)
for dep in departments:
temp = {}
temp["name"] = dep
temp["papers"] = get_papers_list(course,dep)
data.append(temp)
return data
# print(get_course_list())
#print(get_departments_list('apple'))
# print(get_departments_list('UG'))
print(get_papers_list('UG','community_medicine_1'))
|
# coding: utf-8
# 実行方法: python3 network.py < list.csv
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import sys
edge_list = []
for line in sys.stdin:
data_list = line.replace("\n", "").replace('"', '').split(",")
edge_list.append( (data_list[0], data_list[1]) )
G = nx.Graph()
# 辺の追加
for edge_pair in edge_list:
G.add_edge( edge_pair[0], edge_pair[1] )
print("頂点数:", G.number_of_nodes()) # 頂点数の表示
print("辺数:", G.number_of_edges()) # 辺数の表示
print("連結性", nx.is_connected(G)) # 連結性の確認
# 最大連結成分を調べる
print("### 以下,最大連結成分で計算 ###")
max_size = 0
connected_components_number_of_nodes = []
for c in list(nx.connected_components(G)):
connected_components_number_of_nodes.append(nx.number_of_nodes(G.subgraph(c)))
if nx.number_of_nodes(G.subgraph(c)) > max_size:
SG = G.subgraph(c)
max_size = nx.number_of_nodes(SG)
print("連結成分の頂点数:", connected_components_number_of_nodes)
print("最大連結成分の頂点数:", SG.number_of_nodes()) # 頂点数の表示
print("最大連結成分の辺数:", SG.number_of_edges()) # 辺数の表示
print("最大連結成分の平均次数:", np.average(list(dict(nx.degree(G)).values()))) # 平均次数の表示
print("最大連結成分の平均クラスタ係数:", nx.average_clustering(G)) # 平均クラスタ係数の表示
print("最大連結成分の平均頂点間距離:", nx.average_shortest_path_length(SG)) # 平均頂点間距離の表示
print("最大連結成分の連結性:", nx.is_connected(SG)) # 連結性の確認
nx.draw(SG, node_size=5) # ネットワークを描画
plt.savefig("network-visualization.png")
plt.clf()
|
# -*- coding: utf-8 -*-
#%% About
# Name: bikeshare.py (based on the template bikeshare_2.py by UDACITY)
# Author: Dr. Octavian Knoll (BMW Group/EP-413)
# Python: Anaconda/Spyder (Python 3.8)
# GitHub: https://github.com/OK-BMW/pdsnd_github.git
# Version: v1.2
# History: v1.0: Initial version
# v1.1: Including function display_data(df)
# v1.2: Modify function trip_duration_stats(df)
# Computations using pd functions
# Libary np removed
#%% Import
import time
import pandas as pd
#%% Available Cities
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#%% Function "Get Filters from User"
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('\n' + '-'*88 + '\n')
print('Hello! Let\'s explore some US bikeshare data!')
print('I have data obtained from Chicago, New York City and Washington.')
print('The data was recorded between January and June 2017.')
print('\n' + '-'*88)
# get user input for city (chicago, new york city, washington)
while True:
city = input('Which city do you want to analyse?\nPlease type the city [chicago, new york city, washington] and press enter: ').lower()
if city in CITY_DATA.keys():
break
else:
print('\nD\'oh! I haven\'t found the city. Let\'s go again')
# get user input for month (all, january, february, ... , june)
while True:
month = input('Which month do you want to analyse?\nPlease type the month [jan, feb, mar, apr, may, jun, all] and press enter: ').lower()
if month in ('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'all'):
break
else:
print('\nD\'oh! I haven\'t found the month. Let\'s go again')
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input('Which weekday do you want to analyse?\nPlease type the weekday [mon, tue, wed, thu, fri, sat, sun, all] and press enter: ').lower()
if day in ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun', 'all'):
break
else:
print('\nD\'oh! I haven\'t found the day. Let\'s go again!')
if month == 'all' and day == 'all':
print('\nOK. Let\'s analye {} without any time filter!'.format(city.title()))
elif month == 'all' and day != 'all':
print('\nOK. Let\'s analye {} filtered only by weekday {}!'.format(city.title(), day.title()))
elif month != 'all' and day == 'all':
print('\nOK. Let\'s analye {} filtered only by month {}!'.format(city.title(), month.title()))
else:
print('\nOK. Let\'s analye {} filtered by month {} and weekday {}!'.format(city.title(), month.title(), day.title()))
return city, month, day
#%% Function "Load Data"
def load_data(city, month, day):
"""
Loads data for a specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
print('\n' + '-'*88 + '\n')
if month == 'all' and day == 'all':
print('Data from {} without any time filter will be loaded...'.format(city.title()))
elif month == 'all' and day != 'all':
print('Data from {} filtered only by weekday {} will be loaded...'.format(city.title(), day.title()))
elif month != 'all' and day == 'all':
print('Data from {} filtered only by month {} will be loaded...'.format(city.title(), month.title()))
else:
print('Data from {} filtered by month {} and weekday {} will be loaded...'.format(city.title(), month.title(), day.title()))
start_time = time.time()
# load data
df = pd.read_csv(CITY_DATA[city])
# convert start time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# get month, weekday and hour from start time column to create new columns
df['ST Month'] = df['Start Time'].dt.month
df['ST Day'] = df['Start Time'].dt.weekday
df['ST Hour'] = df['Start Time'].dt.hour
# identify month index and day index
if month != 'all':
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun']
month = months.index(month) + 1
if day != 'all':
days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
day = days.index(day)
# filter data
if month != 'all' and day != 'all':
df = df[df['ST Month'] == month]
df = df[df['ST Day'] == day]
elif month != 'all' and day == 'all':
df = df[df['ST Month'] == month]
elif month == 'all' and day != 'all':
df = df[df['ST Day'] == day]
# convert end time column to datetime
df['End Time'] = pd.to_datetime(df['End Time'])
# get month, weekday and hour from end time column to create new columns
df['ET Month'] = df['End Time'].dt.month
df['ET Day'] = df['End Time'].dt.weekday
df['ET Hour'] = df['End Time'].dt.hour
# modify months and days columns
months_dic = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun'}
days_dic = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'}
df['ST Month'] = df['ST Month'].map(months_dic)
df['ET Month'] = df['ET Month'].map(months_dic)
df['ST Day'] = df['ST Day'].map(days_dic)
df['ET Day'] = df['ET Day'].map(days_dic)
# creat new column containing start station and end station
df['Trip Combination'] = df['Start Station'] + ' --> ' + df['End Station']
print('\nData was loaded successfully. Woah, this only took %.3f seconds!' % (time.time() - start_time))
return df
#%% Function "Display Data"
def display_data(df):
"""
Displays a window of a data frame.
Args:
df - data frame
"""
print('\n' + '-'*88)
while True:
data_info = input('Do you want to see the data before the analysis starts? Enter yes or no: ').lower()
if data_info in ('yes', 'no'):
break
else:
print('\nD\'oh! Please enter yes or no. Let\'s go again!')
i = 5
if data_info == 'yes':
while True:
if i < len(df):
print('\n')
print(df.head(i))
else:
print('The entire data set has already been shown!')
break
while True:
data_info = input('Do you want to see more data? Enter yes or no: ').lower()
if data_info == 'yes':
i +=5
break
elif data_info == 'no':
break
else:
print('\nD\'oh! Please enter yes or no. Let\'s go again!')
if data_info == 'no':
break
#%% Function "Most Common"
def most_common(dfc, name):
"""
Computes most common values of a data frame column.
Args:
dfc - data frame column
(str) name - name of data frame column
"""
dfc_mode = dfc.mode()
dfc_mode_l = len(dfc_mode)
dfc_mode_out = ''
c = 0
if dfc_mode_l == 1:
dfc_mode_out = dfc.mode()[0]
print('The most common {} is '.format(name) + str(dfc_mode_out) + '.')
else:
for i in dfc_mode:
c += 1
if c == dfc_mode_l:
dfc_mode_out = dfc_mode_out + str(i)
print('The most common {}s are '.format(name) + dfc_mode_out + '.')
else:
dfc_mode_out = dfc_mode_out + str(i) + ', '
#%% Function "Time Statstics"
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\n' + '-'*88 + '\n')
print('The most frequent times of travel will be computed...\n')
start_time = time.time()
# display the most common month
most_common(df['ST Month'], 'month')
# display the most common day of week
most_common(df['ST Day'], 'weekday')
# display the most common start hour
most_common(df['ST Hour'], 'hour')
print('\nMost frequent times were computed. Woah, this only took %.3f seconds!' % (time.time() - start_time))
#%% Function "Travel Statstics I"
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\n' + '-'*88 + '\n')
print('The most popular stations and trips will be computed...\n')
start_time = time.time()
# display most commonly used start station
most_common(df['Start Station'], 'start station')
# display most commonly used end station
most_common(df['End Station'], 'end station')
# display most frequent combination of start station and end station trip
most_common(df['Trip Combination'], 'trip')
print('\nMost popular stations and trips were computed. Woah, this only took %.3f seconds!' % (time.time() - start_time))
#%% Function "Travel Statstics II"
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\n' + '-'*88 + '\n')
print('Total and average trip duration will be computed...\n')
start_time = time.time()
# display total travel time
print('Total trip duration: %.2f' % df['Trip Duration'].sum())
# display mean travel time
print('Average trip duration: %.2f' % df['Trip Duration'].mean())
print('\nTotal and average trip duration were computed. Woah, this only took %.3f seconds!' % (time.time() - start_time))
#%% Function "User Statstics"
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\n' + '-'*88 + '\n')
print('User information will be computed...\n')
start_time = time.time()
# Display counts of user types
print('User type inforamtion (normalized):\n')
print(df['User Type'].value_counts(normalize=True).to_frame())
# Display counts of gender
print('\nUser gender information (normalized):\n')
try:
print(df['Gender'].value_counts(normalize=True).to_frame())
except:
print('No gender data available!')
# Display earliest, most recent, and most common year of birth
print('\nUser birth information:\n')
try:
print('Earliest birth: %4.0f' % df['Birth Year'].min())
print('Most recent birth: %4.0f' % df['Birth Year'].max())
print('Most common birth: %4.0f' % df['Birth Year'].mode()[0])
except:
print('No birth data available!')
print('\nUser inforamtion was computed. Woah, this only took %.3f seconds!' % (time.time() - start_time))
print('\n' + '-'*88 + '\n')
print('The entire analysis could be carried out successfully!')
print('I hope you are satisfied with the result and have all the information you need.')
print('See you next time!')
print('\n' + '-'*88)
#%% Function "Main Program"
def main():
while True:
try:
city, month, day = get_filters()
except KeyboardInterrupt:
print("\n\n\n#*! Interrupted by user!")
break
df = load_data(city, month, day)
try:
display_data(df)
except KeyboardInterrupt:
print("\n\n\n#*! Interrupted by user! Computation will be continued...")
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
try:
restart = input('Do you want to restart? Enter yes or no: ')
except KeyboardInterrupt:
print("\n\n\n#*! Interrupted by user!")
break
if restart.lower() != 'yes':
break
#%% Run program
if __name__ == "__main__":
main()
#city, month, day = get_filters()
#df = load_data(city, month, day)
#time_stats(df)
#station_stats(df)
#trip_duration_stats(df)
#user_stats(df)
#display_data(df)
|
from node import Node
class Queue:
def __init__(self, max_size=None):
self.size = 0
self.max_size = max_size
self.head = None
self.tail = None
def enqueue(self, value):
if self.has_space():
item_to_add = Node(value)
if self.is_empty():
self.head = item_to_add
self.tail = item_to_add
elif self.size == 1:
self.head.set_next_node(item_to_add)
self.tail = item_to_add
else:
self.tail.set_next_node(item_to_add)
self.tail = item_to_add
self.size += 1
else:
print("No more room.")
def peek(self):
if not self.is_empty():
return self.head.get_value()
else:
print("The queue is empty.")
def dequeue(self):
if not self.is_empty():
item_to_remove = self.head
if self.size == 1:
self.head = None
self.tail = None
else:
self.head = item_to_remove.get_next_node()
return item_to_remove.get_value()
def has_space(self):
if not self.max_size:
return True
elif self.size < self.max_size:
return True
else:
return False
# 왜 꼭 간단한 코드도 helper method로 만들어야 하나?
def is_empty(self):
if self.size == 0:
return True
else:
return False
gelato_queue = Queue(10)
gelato_queue.enqueue("Gichan")
gelato_queue.enqueue("Gimoon")
gelato_queue.enqueue("MK")
gelato_queue.enqueue("Andy")
print(gelato_queue.dequeue())
print(gelato_queue.dequeue())
|
class Vertex:
def __init__(self, id):
self.id = id
self.neighbors = {}
def __str__(self):
vertex_str = "I am " + self.id
if self.neighbors:
neighbors_result = ", ".join(self.neighbors.keys())
vertex_and_neighbors_str = vertex_str + "\nand my neighbors are: " + neighbors_result + "."
else:
return vertex_str
return vertex_and_neighbors_str
def add_neighbor(self, neighbor):
self.neighbors[neighbor.id] = neighbor
neighbor.neighbors[self.id] = self
def delete_neighbors(self):
if not bool(self.neighbors):
raise Exception("Your vertex have no neighbors.")
for vertex_id in self.neighbors.keys():
current_vertex = self.neighbors[vertex_id]
current_vertex.neighbors.pop(self.id)
self.neighbors = {}
|
p=input()
if((p>='a' and p<='z') or (p>='A' and p<='Z')):
if(p=='a' or p=='A' or p=='e'or p=='E'or p=='i'or p=='I'or p=='o'or p=='O'or p=='u'or p=='U'):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
beers = 5
covers = 0
bottles = 0
total = 0
while beers > 0:
print 'drinking %d beers'% beers
total += beers
covers += beers
bottles += beers
beers = 0
beers = (covers + 2*bottles)/4
covers = (covers + 2*bottles)%4
bottles = 0
print 'exchange %d beers'% beers
print 'You have drunk %d beers...'% total
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
G=1
M=1
m=1
class Planeta(object):
'''
Simula, con opcion de 3 distintos metodos de integracion (Euler, Runge-Kutta4 y Verlet),
el movimiento de un planeta que orbita al rededor del Sol, usando como base su pontecial.
'''
def __init__(self, condicion_inicial, alpha=0):
'''
__init__ es un metodo especial que se usa para inicializar las
instancias de una clase.
Ej. de uso:
>> mercurio = Planeta([x0, y0, vx0, vy0])
>> print(mercurio.alpha)
>> 0.
'''
self.y_actual = condicion_inicial
self.t_actual = 0.
self.alpha = alpha
def ecuacion_de_movimiento(self):
'''
Implementa la ecuacion de movimiento, como sistema de ecuaciones de
primer orden.
'''
x, y, vx, vy = self.y_actual
fx=lambda x,y,t: G*M*x*((2*self.alpha)/((x**2 + y**2)**2) - 1/((np.sqrt(x**2 + y**2))**3))
fy=lambda x,y,t: G*M*y*((2*self.alpha)/((x**2 + y**2)**2) - 1/((np.sqrt(x**2 + y**2))**3))
return np.array([vx, vy, fx, fy])
def avanza_euler(self, dt):
'''
Toma la condición actual del planeta y avanza su posicion y velocidad
en un intervalo de tiempo dt usando el método de Euler explícito. El
método no retorna nada, pero re-setea los valores de self.y_actual.
'''
t = self.t_actual
x, y, vx, vy = self.y_actual
fx = self.ecuacion_de_movimiento()[2]
fy = self.ecuacion_de_movimiento()[3]
fxn = fx(x,y,t)
fyn = fy(x,y,t)
self.y_actual = x + dt*(vx + fxn), y + dt*(vy + fyn), vx + dt*fxn, vy + dt*fyn
pass
def avanza_rk4(self, dt):
'''
Similar a avanza_euler, pero usando Runge-Kutta 4.
'''
t=self.t_actual
x,y,vx,vy=self.y_actual
fx=self.ecuacion_de_movimiento()[2]
fy=self.ecuacion_de_movimiento()[3]
k1x=dt*vx; k1y=dt*vy
fx1=fx(x,y,t)
fy1=fy(x,y,t)
k2x=dt*(vx+dt*fx1/2.); k2y=dt*(vy+dt*fy1/2.)
fx2=fx(x+k1x/2.,y+k1y/2.,t+dt/2.)
fy2=fy(x+k1x/2.,y+k1y/2.,t+dt/2.)
k3x=dt*(vx+dt*fx2/2.); k3y=dt*(vy+dt*fy2/2.)
fx3=fx(x+k2x/2.,y+k2y/2.,t+dt/2.)
fy3=fy(x+k2x/2.,y+k2y/2.,t+dt/2.)
k4x=dt*(vx+dt*fx3); k4y=dt*(vy+dt*fy3)
fx4=fx(x+k3x,y+k3y,t+dt)
fy4=fy(x+k3x,y+k3y,t+dt)
xn=x+(k1x+2*k2x+2*k3x+k4x)/6.
vxn=vx+(fx1+2*fx2+2*fx3+fx4)/6.
yn=y+(k1y+2*k2y+2*k3y+k4y)/6.
vyn=vy+(fy1+2*fy2+2*fy3+fy4)/6.
self.y_actual=xn,yn,vxn,vyn
pass
def avanza_verlet(self, dt):
'''
Similar a avanza_euler, pero usando Verlet.
'''
t=self.t_actual
x,y,vx,vy=self.y_actual
fx=self.ecuacion_de_movimiento()[2]
fy=self.ecuacion_de_movimiento()[3]
fxn = fx(x,y,t)
fyn = fy(x,y,t)
xn=x+vx*dt+(fxn*(dt**2))/2.
yn=y+vy*dt+(fyn*(dt**2))/2.
vxn=vx+((fxn+fx(xn,yn,t+dt))*dt)/2.
vyn=vy+((fyn+fy(xn,yn,t+dt))*dt)/2.
self.y_actual=xn,yn,vxn,vyn
pass
def energia_total(self):
'''
Calcula la enérgía total del sistema en las condiciones actuales.
'''
x, y, vx, vy = self.y_actual
r = np.sqrt(x**2 + y**2)
U = - G*M*m/r + self.alpha*G*M*m /r**2
E_total = m*(vx**2 +vy**2)/2. + U
return E_total
pass
|
import nltk
import math
import matplotlib.pyplot as plt
list = {"y'all", "y'alls", "y'all'd", "y'all'd've",
"y'all're", "y'all've", "you'd", "you'd've",
"you'll", "you'll've", "you're", "you've", "your"
}
alice = nltk.corpus.gutenberg.raw('carroll-alice.txt')
#print(alice)
for word in list:
alice = alice.lower().replace(word, "you")
#write to file output.txt
fout = open("output.txt", "w")
print (alice, file=fout)
word ="you"
tokens = alice.split() #all tokens in text
N=len(tokens) #the total number of token ie total size of text corpus
#find all the positions in text where the word "you" occurs
positions = [i for i, w in enumerate(tokens) if w == word]
#print(positions)
#the total number of times the word "you" occurs in text
wordcount= len(positions)
count = {}
correlation = []
#If the distance between 2 consecutive positions of "you" matches d+1, i.e. d tokens between them, then increment count[d]
for d in range(1,50):
count[d] = 0
for i in range(0,len(positions)-1):
if (positions[i+1]-positions[i]==d+1):
count[d]=count[d]+1
#print (count[d])
correlation.append((count[d]/wordcount)/math.pow((wordcount/N),2))
plt.plot(correlation)
plt.xlabel("distance")
plt.ylabel("correlation")
plt.show()
|
myList = list(map(int, input().split()))
myList.sort()
print(' '.join(map(str, myList)))
myList = list(map(int, input().split()))
sortedList = sorted(myList)
print(' '.join(map(str, sortedList)))
print(sorted((1, 3, 2)))
print(sorted(range(10, -1, -2)))
print(sorted("cba"))
|
myList = [1, 2, 3]
for i in iter(myList):
print(i)
for i in myList:
print(i)
def myRange(n):
i = 0
while i < n:
yield i
i += 1
for i in myRange(10):
print(i)
def genDecDigs(cntDigits, maxDigit):
if cntDigits > 0:
for nowDigit in range(maxDigit + 1):
for tail in genDecDigs(cntDigits - 1, nowDigit):
yield nowDigit * 10 ** (cntDigits - 1) + tail
else:
yield 0
print(*genDecDigs(2, 3))
|
class Man:
height = 0
name = ''
def manKey(man):
return (-man.height, man.name)
n = int(input())
peopleList = []
for i in range(n):
tempManData = input().split()
man = Man()
man.height = int(tempManData[0])
man.name = tempManData[1]
peopleList.append(man)
peopleList.sort(key=manKey)
for man in peopleList:
print(man.height, man.name)
|
name = input()
print('I love', name)
a = int(input())
b = int(input())
print(a + b)
a = int(input())
b = int(input())
c = int(input())
d = int(input())
cost1 = a * 100 + b
cost2 = c * 100 + d
totalCost = cost1 + cost2
print(totalCost // 100, totalCost % 100)
n = int(input())
print(n % 256)
n = int(input())
k = int(input())
print(n // 10**k)
|
"""
int - округляет в сторону нуля (отбрасывет дробную часть)
round - округляет до ближайшего целого, если ближайших целых несколько (дробная часть равно 0.5),
\то к чётному
floor - округляет в меньшую сторону
ceil - округляет в большую сторону
"""
import math
print(math.floor(-2.5))
print(math.ceil(-2.5))
from math import floor, ceil
print(floor(-2.5))
print(ceil(-2.5))
|
# List
lista = ['thing', 'thing1', 2, False]
add = input("Whatcha wanna do baby?: ")
lista.append(add)
#print(listb[3])
# Dictionary
listc = { 'first': 'zero', 'second': lista[1], 'third': 2, }
print( listc )
|
"""
Conversion Tool UTM - WGS84
This program is a command line tool to convert coordinates from one world coordinate system to the other one in both
directions. It asks the user in which direction to convert and in which angle format (Decimal or Degrees, Minutes, Seconds)
the user will enter the locations. The user inserts one coordinate per line and as many as he wants.
"""
import argparse
parser = argparse.ArgumentParser(description="Conversion Tool UTM - WGS84")
parser.add_argument("DIRECTION", type=str, help="Choose the target coordinate system (UTM or WGS84)")
parser.add_argument("ANGLE_FORMAT", type=str, help="Choose input/output format for WGS84 (decimal or DMS)")
args = parser.parse_args()
dir = args.DIRECTION
format = args.ANGLE_FORMAT
# TODO: Exception handling Input
coordinates = list()
if dir == "WGS84" and format == "decimal":
print("Type in your coordinates for conversion.\n" +
"Lat/Lon separated by comma, Multiple coordinates separated by Return\n" +
"(e.g. +50.77552, -6.08432)")
elif dir == "WGS84" and format == "DMS":
print("Type in your coordinates for conversion.\n" +
"North/East separated by comma, Multiple coordinates separated by Return\n" +
"(e.g. 50° 46' 30'' N, 6° 5' 2'' E)")
elif dir == "UTM" :
print("Type in your coordinates for conversion.\n" +
"North/East/Zonenumber/Hemisphere separated by comma, Multiple coordinates separated by Return\n" +
"(e.g. 5481745.123, 461344.432, 32U, N)")
while True:
number = input()
#number = "23.23, 34.34"
if number == '':
print("Thanx for your input!")
break
else:
print("Richtig!")
coord = number.split(", ")
if dir == "UTM":
else:
coordinates.append(coord)
print(coordinates)
|
import json
"""
This program will track the stats of characters such as wounds, strain and credits.
It will also keep track of a characters skill points and give the option to use the
default values provided thereby when making skill checks.
These values will be stored in a dictionary called char and the dictionary skills will
be contained within that dictionary in this format {gunnery: 1, 2} with the first
number being the number of yellow and the second being the number of green. I will
have to make another dieNum function in ffdice.py to handle these preassigned parameters
All of these values will be stored in seperate files called, for example, koss.char.
"""
def charCreate():
"""
Main function that sets up some variables. Could rewrite as a class.
"""
brawn=agility=intellect=cunning=willpower=presence=0
characterList = [brawn, agility, intellect, cunning, willpower, presence]
def charAssign(characterList):
"""
assigns values to characterList
"""
characterList[0] = int(input('Brawn? '))
characterList[1] = int(input('Agility? '))
characterList[2] = int(input('Intellect? '))
characterList[3] = int(input('Cunning? '))
characterList[4] = int(input('Willpower? '))
characterList[5] = int(input('Presence? '))
return characterList
charAssign(characterList)
def nameAssign(char):
"""
Assigns values to Name, Career Species.
"""
for key in char:
if type(char[key]) != (list or dict):
if type(char[key]) == str or int:
print('{}?'.format(key))
if type(char[key]) == str:
char[key] = input('> ')
elif type(char[key]) == int:
char[key] = int(input('> '))
else:
pass
else:
pass
#Initializes skills dicts
general = {'Astrogation': [characterList[2], 0], 'Athletics': [characterList[0], 0], 'Charm': [characterList[5], 0], 'Coercion': [characterList[4], 0],\
'Computers': [characterList[2], 0], 'Cool': [characterList[5], 0], 'Coordination': [characterList[1], 0], 'Deception': [characterList[3], 0],\
'Discipline': [characterList[4], 0], 'Leadership': [characterList[5], 0], 'Mechanics': [characterList[2], 0], 'Medicine': [characterList[2], 0],\
'Negotiation': [characterList[5], 0], 'Perception': [characterList[3], 0], 'Piloting: Planetary': [characterList[1], 0],\
'Piloting: Space': [characterList[2], 0], 'Resilience': [characterList[0], 0], 'Skullduggery': [characterList[3], 0], 'Stealth': [characterList[1], 0],\
'Streetwise': [characterList[3], 0], 'Survival': [characterList[3], 0], 'Vigilance': [characterList[4], 0]}
combat = {'Brawl': [characterList[0], 0], 'Gunnery': [characterList[1], 0], 'Melee': [characterList[0], 0], 'Ranged: Light': [characterList[1], 0],\
'Ranged: Heavy': [characterList[1], 0]}
knowledge = {'Knowldge: Core Worlds': [characterList[2], 0], 'Knowledge: Education': [characterList[2], 0], 'Knowledge: Lore': [characterList[2], 0],\
'Knowledge: Outer Rim': [characterList[2], 0], 'Knowledge: Underworld': [characterList[2], 0], 'Knowledge: Xeneology': [characterList[2], 0]}
def skillAssign(genearl, combat, knowledge):
"""
Assigns values for skill ranks.
"""
for key in general:
print('Ranks in {}?'.format(key))
general[key][1] = int(input('> '))
for key in combat:
print('Ranks in {}?'.format(key))
combat[key][1] = int(input('> '))
for key in knowledge:
print('Ranks in {}?'.format(key))
knowledge[key][1] = int(input('> '))
#Calls skillAssign() function to iterate through the different skills.
skillAssign(general, combat, knowledge)
#Combines the skills dicts into larger dict
skills = {'General': general, 'Combat': combat, 'Knowledge': knowledge}
#Creates a dict to contain all values
char = {'Name': '', 'Career': '', 'Species': '', 'WoundTH': 0, 'StrainTH': 0,\
'Skills': skills, 'Characteristics': characterList}
#Calls name assign to get final values
nameAssign(char)
#writes the char dict to a file with the name of the character name
f = open(char['Name'], 'w')
json.dump(char, f)
f.close()
charCreate()
|
# Amanda Arreola - #001067645
import Package
import datetime
# This function contains all the console interface that a user interacts with.
# It provides a option menu for the user.
# A user can use this interface to find information on a package, or multiple packages. : O(n)^2
def interface(hashmap):
print("WELCOME TO WGUPS")
print("------------------")
print('OPTION MENU')
print('1. FIND A PACKAGE')
print('2. STATUS OF ALL PACKAGES IN A TIME FRAME')
print('3. EXIT')
choice = int(input("Enter an option from the menu (1/2/3): "))
while choice != 3:
if choice == 1:
look_for_package = "yes"
while look_for_package == "yes":
if look_for_package == "yes":
user_input = int(input("What package are you looking for?"))
hashmap.lookup_in_hashtable(user_input, single_package=True)
look_for_package = input("Would you like to look for another package? (yes/no)").lower()
if look_for_package == "no":
choice = int(input("Enter an option from the menu (1/2/3):\n "))
if choice == 2:
time_frame = "yes"
while time_frame == "yes":
if time_frame == "yes":
start_time_hour, start_time_minutes = input("Enter a start time for timeframe (HH:MM): ").split(":")
end_time_hour, end_time_minute = input("Enter an end time for timeframe (HH:MM): ").split(":")
start_time = datetime.timedelta(hours=int(start_time_hour), minutes=int(start_time_minutes))
end_time = datetime.timedelta(hours=int(end_time_hour), minutes=int(end_time_minute))
status_check(hashmap, start_time, end_time)
time_frame = input("Would you like to look in another timeframe? (yes/no)\n").lower()
if time_frame == "no":
choice = int(input("Enter an option from the menu (1/2/3): "))
if choice == 3:
print("Thank you for visiting WGUPS. Goodbye!\n")
# This function is called to provide that status of all packages during a specific time frame. : O(n)
def status_check(hashmap, starttime, endtime):
for count in range(1, 41):
package = hashmap.get(count)
load_time = package.load_time
delivery_time = package.delivery_time
if (starttime < delivery_time < endtime) or starttime >= delivery_time:
package_info = (f'Package #{package.package_id} has been delivered.')
print(package_info, end=' ')
elif (starttime >= load_time) and (starttime < delivery_time > endtime):
package_info = (f'Package #{package.package_id} is on route.')
print(package_info, end=' ')
elif (starttime > load_time) and (delivery_time > endtime):
package_info = (f'Package #{package.package_id} is on route.')
print(package_info, end=' ')
elif (load_time > starttime) and (endtime < load_time):
package_info = (f'Package #{package.package_id} is at the hub.')
print(package_info, end=' ')
elif (load_time > starttime) and (endtime > load_time):
package_info = (f'Package #{package.package_id} is at the hub.')
print(package_info, end=' ')
hashmap.lookup_in_hashtable(count, single_package=False)
# This function provides the running time for the program.
# It can be called to provide a start, load, or delivery timestamp.
def running_time(hours, minutes):
start_time = datetime.timedelta(hours=8, minutes=00)
package_status_time = start_time + datetime.timedelta(hours=hours, minutes=minutes)
return package_status_time
def main():
Package.main()
main()
|
#function for calculate two numbers
def calculator():
num1 = float(input("Enter first number: ")) #user input the first number
op = input("Enter Operator: ") #user input the operator that are +,-,* or /
num2 = float(input("Enter second number: ")) #user input the second number
#if else statment for what kind of operator user choosed
if op == "+":
return num1+num2
elif op == "-":
return num1-num2
elif op == "*":
return num1*num2
elif op == "/":
return num1/num2
else:
return "Invalid Operator!"
#call function that print the result
print(calculator())
|
class Calculator:
def __repr__(self):
return "value: {0}, \nattributes: {1}".format(self.value, self.__dict__)
def __init__(self, init_value=0):
self.value = init_value
self.iter_flag = False
def __add__(self, other):
value = other.value if isinstance(other, Calculator) else other
return Calculator(self.value + value)
def __sub__(self, other):
value = other.value if isinstance(other, Calculator) else other
return Calculator(self.value - value)
def __mul__(self, other):
value = other.value if isinstance(other, Calculator) else other
return Calculator(self.value * value)
def __pow__(self, other):
value = other.value if isinstance(other, Calculator) else other
return Calculator(self.value ** value)
def __truediv__(self, other):
value = other.value if isinstance(other, Calculator) else other
self.value /= value
return self
def __setattr__(self, key, value):
if len(self.__dict__) < 12:
self.__dict__[key] = value
def power(self, *args): # последовательное возведение в степень
for x in args:
self.value **= x
return self
def root(self, *args): # последовательное извлечение корней из числа
for x in args:
self.value **= (1 / x)
return self
def multiply(self, *args):
for x in args:
self.value *= x
return self
def divide(self, *args, integer_divide=False):
for x in args:
if integer_divide:
self.value //= x
else:
self.value /= x
return self
def subtract(self, *args):
self.value -= sum(args)
return self
def __iter__(self):
return self
def __next__(self):
if self.iter_flag:
self.iter_flag = False
raise StopIteration
else:
self.iter_flag = True
return self.value
if __name__ == '__main__':
calculator = Calculator(6)
calculator.z = '33'
calculator.ff = 44
for i in calculator:
print(i)
|
import random
# main routine goes here
token = ["unicorn","horse","horse","horse","zebra","zebra","zebra","donkey","donkey","donkey"]
STARTING_BALANCE = 100
balance = STARTING_BALANCE
# Testing loop to generate 20 tokens
for item in range(0,500):
chosen = random.choice(token)
# Adjust balance
if chosen == "unicorn":
balance += 4
elif chosen == "donkey":
balance -= 1
else:
balance -= 0.5
print()
print("Starting Balance: ${:.2f}".format(STARTING_BALANCE))
print("Final Balance: ${:.2f}".format(balance))
|
p1 = input().split()
p2 = input().split()
def append(inp):
arr = []
for i in range(1, len(inp), 2):
arr.append(inp[i] + "," + inp[i + 1])
return arr
# 去除重复项
def removal(arr):
arr = to_int(arr)
new_arr = []
for i in range(0, len(arr), 2):
base = arr[i]
if base == 0:
continue
index = arr[i + 1]
for j in range(i + 3, len(arr), 2):
_index = arr[j]
if index == _index:
base += arr[j - 1]
arr[j - 1] = 0
if base != 0:
new_arr.append(base)
new_arr.append(index)
if len(new_arr) == 0:
return '0 0'
return ' '.join(to_string(new_arr))
# 多项式相乘法
def multip(arr1, arr2):
m = []
for p in arr2:
p_arr = to_int(p.split(','))
base = p_arr[0]
index = p_arr[1]
for pp in arr1:
pp_arr = to_int(pp.split(','))
_base = pp_arr[0] * base
_index = pp_arr[1] + index
m.append(_base)
m.append(_index)
return removal(m)
def to_int(arr):
new_arr = []
for s in arr:
new_arr.append(int(s))
return new_arr
def to_string(arr):
new_arr = []
for s in arr:
new_arr.append(str(s))
return new_arr
# 多项式相加
def addition(arr1, arr2):
m = []
i = 0
j = 0
while i < len(arr1) or j < len(arr2):
if i >= len(arr1):
node2 = to_int(arr2[j].split(','))
m.append(node2[0])
m.append(node2[1])
break
if j >= len(arr2):
node1 = to_int(arr1[i].split(','))
m.append(node1[0])
m.append(node1[1])
break
node1 = to_int(arr1[i].split(','))
node2 = to_int(arr2[j].split(','))
if node1[1] == node2[1]:
if node1[0] + node2[0] != 0:
m.append(node1[0] + node2[0])
m.append(node1[1])
i += 1
j += 1
elif node1[1] > node2[1]:
m.append(node1[0])
m.append(node1[1])
i += 1
elif node1[1] < node2[1]:
m.append(node2[0])
m.append(node2[1])
j += 1
return removal(m)
arr1 = append(p1)
arr2 = append(p2)
print(multip(arr1, arr2))
print(addition(arr1, arr2))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Python的函数定义非常简单,但灵活度却非常大。
# 除了正常定义的必选参数外,还可以使用默认参数、
# 可变参数和关键字参数,使得函数定义出来的接口,
# 不但能处理复杂的参数,还可以简化调用者的代码。
# 默认参数
# 默认参数应该放在必选参数后,这样才可以省略
def power(x, n=2):
s = 1
while n > 0:
s = s * x
n = n - 1
return s
print(power(3))
# 默认参数很有用,但也有坑啊
def add_end(L=[]):
"""TODO: Docstring for add_end.
:L: TODO
:returns: TODO
"""
L.append('END')
return L
# 正常调用
print(add_end([1, 2, 3]))
print(add_end(['x', 'y', 'z']))
# 使用默认参数调用
print(add_end()) # ['END']
# but 当你在此调用时
# 就不对了
print(add_end()) # ['END', 'END']
# Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。
# 所以,定义默认参数要牢记一点:默认参数必须指向不变对象!
# 下面来改一下
def add_end2(L=None):
"""add_end2
:L: TODO
:returns: TODO
"""
if L is None:
L = []
L.append('END')
return L
print(add_end2()) # ['END']
print(add_end2()) # ['END']
###########################################
# 可变参数
def calc(*numbers):
"""TODO: Docstring for calc.
:numbers: TODO
:returns: TODO
"""
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print(calc(1, 2, 3))
nums = [1, 2, 3]
print(calc())
print(calc(nums[0], nums[1], nums[2]))
# *nums表示把nums这个list的所有元素作为可变参数传进去。
# 这种写法相当有用,而且很常见。
print(calc(*nums))
# 关键字参数
# 可变参数允许传入多个参数,这些参数在函数内部自动组装为 tuple.
# 而关键字参数允许你传入 0 或多个含参数名的参数。
# 这些关键字参数在函数内部自动组装为一个dict。
def person(name, age, **kw):
"""TODO: Docstring for person.
:name: TODO
:age: TODO
:**kw: TODO
:returns: TODO
"""
print('name:', name, 'age:', age, 'other:', kw)
person('Michael', 30)
person('Bob', 35, city='Beijing')
person('Adam', 45, gender='M', job='Engineer')
# 它可以扩展函数的功能。比如,在person函数里,
# 我们保证能接收到name和age这两个参数,
# 但是,如果调用者愿意提供更多的参数,我们也能收到。
# 试想你正在做一个用户注册的功能,除了用户名和年龄是必填项外,
# 其他都是可选项,利用关键字参数来定义这个函数就能满足注册的需求。
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, city=extra['city'], job=extra['job'])
# 上面复杂的调用可以用简化的写法:
person('Jack', 24, **extra)
# **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数,
# kw将获得一个dict,注意kw获得的dict是extra的一份拷贝,
# 对kw的改动不会影响到函数外的extra。
#
# 命名关键字参数
|
import Parameters as param
import ResourceQuality
import BasicOperations as Ops
import copy
import math
import csv
res_dict = ResourceQuality.resourceDict
seed = param.seed
class Country:
"""
A class that defines the country object for every country in our countries dictionary. Each country object contains
all kinds of information for this country.
"""
def __init__(self, countryName, resources, init_state_quality, prob_parameter, war_ambition):
"""
Initializing the country's name, resources, initial state quality, and participation probability here.
:param countryName: String for the country's name
:param resources: A dictionary containing the amounts of resources in the country
:param init_state_quality: Int for the initial state quality of the country
:param prob_parameter: A list containing parameters for probability calculation in transfer successor function
:param war_ambition: Long indicating the war ambition level of a country
"""
self.name = countryName
self.resources = resources
self.init_state_quality = init_state_quality
self.first_round_quality = init_state_quality
self.participation_prob = -1
self.war_quality = self.warfare_quality()
self.prob_parameter = prob_parameter
self.war_ambition = war_ambition
def warfare_quality(self):
"""
The warfare_quality function returns a number corresponding to the
necessity of a country needing to resort to war to meet its needs.
Return: a double corresponding to the necessity for the country to go to war.
"""
war_Quality = 0
for res in res_dict:
set = res_dict[res]
thresh1 = set[3]
our_res = self.resources[res]
warweight = set[8]
#no the war weights yet
war_Quality += (((thresh1 - our_res)/thresh1) * warweight)
return war_Quality
def deterrence_score(self, country):
"""
The deterrence_score function returns a number corresponding to the fear
a country has in taking on another specific country based on the relative weighting
of the other's war power and the country's own war power.
country: the name of the country to which self is being compared to.
Return: a double representing the ratio of the potential opponent's power to the
war power of self.
"""
# Higher means other country is more powerful.
det = (Ops.war_power(country)/Ops.war_power(self))
return det
def relationship_score(self, country):
"""
The relationship_score function models the preference a country has to trading with
another specific country as opposed to war with that other country.
country: the name of the country to which self is being compared to.
Return: a double representing the strength of the preference
that self has to trading with the other country rather than
resorting to war.
"""
diff_dict = list()
for res in res_dict:
# Iterative look in dictionary
data = res_dict[res]
weight = data[0] # Economic weights
model = data[1]
scaling = data[2]
our_quantity = self.resources[res]
country_quantity = country.resources[res]
# Analyze diff (- of this is the advantage of other country to us)
diff = our_quantity - country_quantity
diff_dict.append(diff)
# Now find max, min in diff_dict. Negate min and apply to formula. This
# represents the amount of the difference between the countries most
# unequal resource.
MaxDiff_XY = max(diff_dict)
MaxDiff_YX = -min(diff_dict)
# Normalize by dividing max advantage over min advantage
# This is 1 when countries have equal imbalances of resources, symbolizing high
# potential for trade.
min_Diff = min(MaxDiff_YX, MaxDiff_XY)
max_Diff = max(MaxDiff_YX, MaxDiff_XY, 0.0000000001)
return min_Diff/max_Diff
def war_inclination(self, country):
"""
The war_inclination function returns a single numeric value representing the potential
gains vs. losses of self going to war with another specific country.
country: the name of the country to which self is considering war with.
Return: a double representing the inclination of self going to
war with another specific country. The closer this is to 1, the more inclined
the country is to war.
"""
det = self.deterrence_score(country)
rel = self.relationship_score(country)
# This approaches 1 when countries really want war.
# Countries can be really negative, but this doesn't matter to us.
return 1 - det * rel
class State:
"""
A class that defines the country object for every state in our search tree. Each state object contains information
of all countries' resources states and the path to get to the state from the starting state in the search tree.
"""
def __init__(self, depth, countries, schedule):
"""
Initializing the stat
e's countries dictionary, depth, path, and expected utility here.
:param depth: Int for the depth of the state in the search tree
:param countries: A dictionary containing country objects
:param schedule: A list for the initial schedule
"""
self.countries = countries
self.depth = depth
self.path = schedule
self.eu = 0
# Define the notion of '<' for a State, used in PriorityQueue when priority of
# two states is otherwise equal. We prefer the lower depth in that case
def __lt__(self, other):
return self.depth < other.depth
def findSuccessor(self, player, type):
"""
This function finds all possible successor states for the given state. It contains two inner functions:
successors_for_transform and successors_for_transfer which find successor states for different TRANSFORM and
TRANSFER operations respectively.
:param player: A string indicating the player/country
:param type: A string indicating the operation type
:return: A tuple containing all the states found.
"""
def successors_for_transform(path, countries, depth, player):
"""
This function finds all possible successor states after performing TRANSFORM for the given state. It explores
all possible TRANSFORM operations for the player in this state and only passes in states whose expected
utilities are higher than the threshold.
:param path: A list indicating the given state's path
:param countries: A dictionary indicating all of the countries in the given state's
:param depth: Int indicating the given state's schedule depth in the search tree
:param player: String indicating the country/player
"""
# go through the list of different quantities for TRANSFORM operator which determine the resource
# amount that MyCountry can get in this TRANSFORM
for quantity in quantity_choices:
# go through different types of resources that MyCountry can get in this TRANSFORM
for transform_type in transform_types:
# perform the TRANSFORM operator
a, b = Ops.transform(player, resources, quantity, transform_type)
# look at the new state if the operator is successfully performed
if a:
# get initial state quality of MyCountry in order to calculate the probability that the country
# participates in the schedule
init_state = countries[player].init_state_quality
# calculate the probability: d_r as the discounted reward and par_p as the probability
d_r, par_p = self.country_participation_probability(b, init_state, 0.9, depth + 1, 0, 1)
# get utility by multiply p with MyCountry's participation probability and discounted reward
eu = d_r
# only generate and append the state to the list if the expected utility is larger than the
# threshold
if eu > 0:
path_to_update = copy.deepcopy(path)
countries_to_update = copy.deepcopy(countries)
# update the path (schedule)
a += ("EU: %d" % eu, )
path_to_update.append(a)
# update MyCountry's resources dictionary
countries_to_update[player].resources = b
# update MyCountry's participation probability
countries_to_update[player].participation_prob = par_p
# create new state
new_state = State(depth + 1, countries_to_update, path_to_update)
# update expected utility of the new state
new_state.eu = eu
# append new state to the successor state list
successor_list.append(new_state)
def successors_for_transfer(path, countries, depth, player):
"""
This function finds all possible successor states after performing TRANSFER for the given state. It explores
all possible TRANSFER operations for the player in this state and only passes in states whose expected
utilities are higher than the threshold.
:param path: A list indicating the given state's path
:param countries: A dictionary indicating all of the countries in the given state's
:param depth: Int indicating the given state's schedule depth in the search tree
:param player: String indicating the country/player
"""
# go through the list of different quantities for TRANSFER operator which determine the resource
# amount that MyCountry can get in this TRANSFER
for quantity in quantity_choices_1:
# create a unit price list without the wastes
positive_resource_unit_prices = transfer_unit_prices[0:6]
# go through the list of different desired resources in this TRANSFER operation
for desired_resource in positive_resource_unit_prices:
# create a resource list for step 2 of the trade (give out resources or accept wastes) by removing
# the chosen desired resource in the resource list in order to explore different trading
# possibilities (we only trade for desired resources by giving other resources or accepting wastes)
other_resources = transfer_unit_prices.copy()
other_resources.remove(desired_resource)
# go though the dictionary of countries as potential target countries in this TRANSFER trade
for target_c in countries:
# only trade with other countries
if target_c != player:
# go through the list of resources without the desired resource to perform different
# possible trades
for r in other_resources:
# perform step 1 of the trade by doing one TRANSFER (MyCountry accepts desired
# resources from the target country)
a1, b1, c1 = Ops.transfer(target_c, player,
countries[target_c].resources, resources,
desired_resource[0], quantity)
# calculate the amount of resource we give out or the amount of waste we accept in the
# second phase of the trade
trade_amount = desired_resource[1] * quantity / abs(r[1])
# perform step 2 of the trade (when we choose to accept wastes)
if 'Waste' in r[0]:
a2, b2, c2 = Ops.transfer(target_c, player, b1,
c1, r[0], trade_amount)
# perform step 2 of the trade (when we choose to give out other resources)
else:
a2, c2, b2 = Ops.transfer(player, target_c, c1,
b1, r[0], trade_amount)
# look at the new state if the 2 TRANSFER operators for both steps of the trade are
# successfully performed
if a1 and a2:
# get initial state quality of MyCountry and the other country in the trade in
# order to calculate the probability that the countries participate in the schedule
init_state1 = countries[target_c].init_state_quality
init_state2 = countries[player].init_state_quality
# prob_parameter1 as the k, x_0 for not trading selective countries, prob_parameter2
# for selective countries
prob_parameter1 = countries[target_c].prob_parameter
prob_parameter2 = countries[player].prob_parameter
# calculate the probabilities for both countries: d_r as the discounted reward and
# par_p as the probability using the prob_parameter as an implementation of trading
# strategies here
d_r1, par_p1 = self.country_participation_probability(b2, init_state1, 0.9,
depth + 1, prob_parameter1[0],
prob_parameter1[1])
d_r2, par_p2 = self.country_participation_probability(c2, init_state2, 0.9,
depth + 1, prob_parameter2[0],
prob_parameter2[1])
# get utility by multiply p with both countries' participation probabilities and
# MyCountry's discounted reward
eu = par_p1 * d_r2
# only generate append the state to the list if the expected utility is larger than
# the threshold
if eu > 0:
path_to_update = copy.deepcopy(path)
countries_to_update = copy.deepcopy(countries)
# update the path (schedule)
a1 += ("EU: %d" % eu, )
a2 += ("EU: %d" % eu, )
path_to_update.append(a1)
path_to_update.append(a2)
# update both countries' resources dictionaries
countries_to_update[target_c].resources = b2
countries_to_update[player].resources = c2
# update both countries' participation probabilities
countries_to_update[target_c].participation_prob = par_p1
countries_to_update[player].participation_prob = par_p2
# generate new state
new_state = State(depth + 1, countries_to_update, path_to_update)
# update the expected utility in the new state
new_state.eu = eu
# append the new state to the successor state list
successor_list.append(new_state)
def successors_for_war(path, countries, depth, player):
"""
This function finds all possible successor states after performing WAR for the given state. It explores
all possible WAR operations for the player in this state and only passes in states when warfare quality
and war inclination function tell it that the war is appropriate.
:param path: A list indicating the given state's path
:param countries: A dictionary indicating all of the countries in the given state's
:param depth: Int indicating the given state's schedule depth in the search tree
:param player: String indicating the country/player
"""
# check warfare quality here
if countries[player].war_quality >= -1:
for target_c in countries:
if target_c != player:
war_inclination = countries[player].war_inclination(countries[target_c])
# comparing war inclination and the country's war ambition to decide if go to war
if war_inclination >= countries[player].war_ambition:
path_to_update = copy.deepcopy(path)
countries_to_update = copy.deepcopy(countries)
init_state1 = countries[player].init_state_quality
new_state = State(depth + 1, countries_to_update, path_to_update)
new_state = Ops.war(player, target_c, new_state, False, seed)
# calculate participation probability for expected utility
d_r1, par_p1 = self.country_participation_probability(new_state.countries[player].resources, init_state1, 0.9,
depth + 1, 0, 1)
advantage = countries[player].war_quality - countries[target_c].war_quality\
eu = d_r1 * advantage
new_state.eu = eu
# check expected utility before appending the new state into the list
if eu > (1000 - (countries[player].war_ambition * 700)):
successor_list.append(new_state)
# define quantity choices list for TRANSFORM successor function
quantity_choices = (2 ** 0, 2 ** 1, 2 ** 2, 2 ** 3, 2 ** 4, 2 ** 5, 2 ** 6)
# define quantity choices list for TRANSFER successor function
quantity_choices_1 = (1, 10, 100)
# define TRANSFORM type list for TRANSFORM successor function
transform_types = ('housing', 'food', 'electronics', 'metalAlloys')
# define unit prices list for TRANSFER successor function
transfer_unit_prices = [('metalElements', 2100), ('timber', 200), ('metalAlloys', 2200),
('electronics', 4300), ('food', 180), ('water', 2),
('metalAlloysWaste', -53), ('housingWaste', -53),
('electronicsWaste', -53), ('foodWaste', -53)]
# initialize the successor state list
successor_list = list()
# MyCountry's resources dictionary
resources = self.countries[player].resources
# finding all possible successor states from both TRANSFORM and TRANSFER
if type == "transform":
successors_for_transform(self.path, self.countries, self.depth, player)
if type == "transfer":
successors_for_transfer(self.path, self.countries, self.depth, player)
if type == 'war':
successors_for_war(self.path, self.countries, self.depth, player)
return tuple(successor_list)
def country_participation_probability(self, resources, init_s, gamma, depth, x_0, k, L=1):
"""
This function calculates the participation probability of a specific country.
:param resources: A dictionary for the country's resources
:param init_s: Int for the country's initial state
:param gamma: Int for gamma in calculating discounted reward
:param depth: Int for the successor state's depth
:param x_0: Int for x_0 in calculating the country participation probability
:param k: Int for k in calculating the country participation probability
:param L: Int for L in calculating the country participation probability
:return: An int for the discounted reward, an int for the country participation probability.
"""
# finding the state quality for the country in the current state
sq = ResourceQuality.getStateQuality(resources)
# using delta state quality to calculate the discounted reward for the country
dr = gamma ** depth * (sq - init_s)
# calculate the country's participation probability
if abs(dr) < 0.00001:
cpp = L / (1 + math.exp(-k * (dr - x_0))) if -k * (dr - x_0) < 100 else -1
else:
if -(k ** ((dr - x_0) / abs((dr - x_0)) * -1)) * (dr - x_0) < 100:
cpp = L / (1 + math.exp(-(k ** ((dr - x_0)/abs((dr - x_0)) * -1)) * (dr - x_0)))
else:
cpp = -1
return dr, cpp
def current_output(self, file_name):
"""
current_output is a helper function that prints the current best path, and best path EU
to a file.
file_name: the path to write to.
Return: void.
"""
csv_file = file_name
csv_columns = ['Name', 'population', 'metalElements', 'timber', 'landArea', 'water', 'metalAlloys',
'electronics', 'housing', 'food', 'metalAlloysWaste', 'housingWaste', 'electronicsWaste',
'foodWaste', 'score']
with open(csv_file, 'w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=csv_columns)
writer.writeheader()
for i in self.countries:
score = ResourceQuality.getStateQuality(self.countries[i].resources) - self.countries[i].first_round_quality
s = {'score': score}
a = {'Name': i}
a.update(self.countries[i].resources)
a.update(s)
writer.writerow(a)
csv_file.close()
|
from BaseAI_3 import BaseAI
import time
import math
import random
class PlayerAI(BaseAI):
"""This function manages the behaviour of the PlayerAI, uses alpha-beta prunining and minimax algorithm
to determine the optimal play, against an opponent who is playing optimally. It should work well
with randomized moves from the opponent."""
def __init__(self):
self.time_left = True
self.preferred_order = [0, 2, 3, 1]
self.max_move = 0
def maximize(self, state, a, b, depth=0):
if time.clock() - self.start > 0.098:
self.time_left = False
return 1,2
if depth == self.max_depth:
utility = self.evaluate(state)
return state, utility
max_child, max_utility = None, -float('inf')
available_moves = state.getAvailableMoves()
available_moves = [self.preferred_order[i] for i in range(len(self.preferred_order))
if self.preferred_order[i] in available_moves]
# if len(available_moves) > 1:
# try:
# for i in range(3):
# if state.map[i][0] == state.map[i + 1][0] or state.map[i][0] == 0 or state.map[3][0] == 0:
# available_moves.remove(1)
# break
# except ValueError:
# pass
#
# if len(available_moves) > 1:
# try:
# for i in range(3):
# if state.map[0][i] == state.map[0][i + 1] or state.map[0][i] == 0 or state.map[0][3] == 0:
# available_moves.remove(3)
# break
# except ValueError:
# pass
children = []
for i in available_moves:
children.append(state.clone())
children[-1].move(i)
for child in children:
*rest, utility = self.minimize(child, a, b, depth + 1)
if not self.time_left:
return 1,2
if utility > max_utility:
max_child, max_utility = child, utility
if depth == 0:
self.max_move = available_moves[children.index(child)]
if max_utility >= b:
break
if max_utility > a:
a = max_utility
return max_child, max_utility
def minimize(self, state, a, b, depth):
if time.clock() - self.start > 0.098:
self.time_left = False
return 1,2
if depth == self.max_depth:
utility = self.evaluate(state)
return state, utility
min_child, min_utility = None, float('inf')
def sorting(a):
return math.sqrt(a[0]**2 + a[1]**2)
available = state.getAvailableCells()
available.sort(key=sorting)
children = []
for position in available:
children.append(state.clone())
children[-1].setCellValue(position, random.choice([2,4]))
if len(children) > 5:
break
for child in children:
*rest, utility = self.maximize(child, a, b, depth + 1)
if not self.time_left:
return 1,2
if utility < min_utility:
min_child, min_utility = child, utility
if min_utility <= a:
break
if min_utility < b:
b = min_utility
return min_child, min_utility
def evaluate(self, state):
available = state.getAvailableCells()
return 10 * (self.max_tile_pos(state, available) + self.gradient(state) +
+ len(state.getAvailableCells())) + self.smoothness(state)
# HEURISTICS
# fix the ids with a dict
def max_tile_pos(self, state, available):
value = 0
max_tile = state.getMaxTile()
if max_tile == state.map[0][0]:
value = max_tile * 2
elif max_tile == state.map[0][1]:
value = 0
elif max_tile > 4:
value = -100
if len(state.getAvailableMoves()) <= 2 and (0,3) in available:
value -= 5
if max_tile > 1024:
value += max_tile
# elif max_tile > 512:
# value += 100
return value
def gradient(self, state):
value = 0
for x in range(3):
for y in range(3):
if state.map[x][y] >= state.map[x][y + 1]:
value += state.map[x][y + 1] * (1 / 2) ** (x + y)
else:
break
for x in range(3):
for y in range(3):
if state.map[y][x] >= state.map[y + 1][x]:
value += state.map[y+ 1][x] * (1 / 3) ** (y + x)
else:
break
return value
def smoothness(self, state, trigger=0):
value = 0
explored = dict()
cell_values = dict()
for x in range(3):
for y in range(3):
cell = state.map[x][y]
if cell == state.map[x][y + 1]:
if cell not in explored:
explored[cell] = 1
explored[cell] += 1
else:
if cell not in cell_values:
cell_values[cell] = 0
cell_values[cell] += 1
cell1 = state.map[y][x]
if cell1 == state.map[y + 1][x]:
if cell1 not in explored:
explored[cell1] = 0
explored[cell1] += 1
else:
if cell not in cell_values:
cell_values[cell] = 0
cell_values[cell] += 1
new_smooth = 0
for key in explored:
new_smooth += key * self.round_down(explored[key], 2)
solo_cell = 0
for key in cell_values:
solo_cell += key * cell_values[key]
if trigger == 1:
self.smooth = new_smooth
self.solo = solo_cell
if new_smooth + len(explored) == self.smooth and solo_cell == self.solo:
value = 0
else:
value += 2 * new_smooth + solo_cell
return value
def round_down(self, num, divisor):
return num - (num % divisor)
def getMove(self, grid):
"""Plays a move from the optimal strategy
Args:
grid: A current state of the grid
"""
self.start = time.clock()
self.max_depth = 4
move = 0
_ = self.smoothness(grid, 1)
while True:
_ = self.maximize(grid, -float('inf'), float('inf'))
if self.time_left is True:
move = self.max_move
else:
break
self.max_depth += 1
print(self.max_depth)
self.time_left = True
self.max_move = 0
return move
|
import random # импортируем модуль random
#import os # импортируем модуль os для очистки консоли. os.system("cls")
#####################################################################################
def multiplication():
multiplication_1 = random.randint(1, 10)
multiplication_2 = random.randint(1, 10)
result_1 = multiplication_1 * multiplication_2
print("Пример: " + str(multiplication_1) + " * " + str(multiplication_2))
entered = ""
while entered != result_1:
entered = int(input("Введите число: "))
if entered == result_1:
print("Верно.")
division()
elif entered != result_1:
print("Неправильно.")
multiplication()
#######################################################################################
#######################################################################################
def division():
division_1 = random.randint(1, 10)
division_2 = random.randint(1, 10)
# Пофиксить баг
# while division_1 < division_2:
# if division_1 < division_2:
# division_1 = random.randint(1, 10)
# division_2 = random.randint(1, 10)
# else:
# pass
result_2 = division_1 // division_2
print("Пример: " + str(division_1) + " / " + str(division_2))
entered = ""
while entered != result_2:
entered = int(input("Введите число: "))
if entered == result_2:
print("Верно.")
addition()
elif entered != result_2:
print("Неправильно.")
division()
#######################################################################################
#######################################################################################
def addition():
addition_1 = random.randint(1, 10)
addition_2 = random.randint(1, 10)
result_3 = addition_1 + addition_2
print("Пример: " + str(addition_1) + " + " + str(addition_2))
entered = ""
while entered != result_3:
entered = int(input("Введите число: "))
if entered == result_3:
print("Верно.")
subtraction()
elif entered != result_3:
print("Неправильно.")
addition()
#######################################################################################
#######################################################################################
def subtraction():
subtraction_1 = random.randint(1, 10)
subtraction_2 = random.randint(1, 10)
result_4 = subtraction_1 - subtraction_2
print("Пример: " + str(subtraction_1) + " - " + str(subtraction_2))
entered = ""
while entered != result_4:
entered = int(input("Введите число: "))
if entered == result_4:
print("Верно.")
break
elif entered != result_4:
print("Неправильно.")
#subtraction()
#######################################################################################
|
# Token types
#
#EOF token is used to indicate that
#there is no more input left for lexical analysis
INTEGER,PLUS,MINUS,MULTI,DIVISION,EOF='INTEGER','PLUS','MINUS','MULTI','DIVISION','EOF'
class Token(object):
def __init__(self,type,value):
#token type:INTEGER,PLUS,or EOF
self.type=type
self.value=value
def __str__(self):
"""String representation of the class instance.
Examples:
Token(INTEGER,3)
Token(PLUS '+')
"""
return 'Token({type},{value})'.format(
type=self.type,
value=self.value
)
#__repr__=__str__
class Interpreter(object):
def __init__(self,text):
#client string input,e.g."3+5"
self.text=text
#self.pos is an index into self.text
self.pos=0
self.current_token=None
self.current_char=text[self.pos]
#####################################
#Lexer Code #
#####################################
def error(self):
raise Exception('Error parsing input')
#手工引发异常
def advance(self):
"""
Advance the 'pos' Pointer and set the 'current_char' Variable.
"""
self.pos+=1
if self.pos>len(self.text)-1:
self.current_char=None
else:
self.current_char=self.text[self.pos]
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
"""
Return a (multidigit) integer consumed form the input.
"""
result=''
while self.current_char is not None and self.current_char.isdigit():
result+=self.current_char
self.advance()
return int(result)
def get_next_token(self):
"""
Lexical analyzer(also known as scanner or tokenizer)
This method is responsible for breaking a sentence
apart into tokens.One token at a time.
"""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(INTEGER,self.integer())
if self.current_char=='+':
self.advance()
return Token(PLUS,'+')
if self.current_char=='-':
self.advance()
return Token(MINUS,'-')
if self.current_char=='*':
self.advance()
return Token(MULTI,'*')
if self.current_char=='/':
self.advance()
return Token(DIVISION,'/')
self.error()
return Token(EOF,None)
###########################
#Parser/Interpreter Code #
###########################
def eat(self,token_type):
# compare the current token type with the passed token
# type and if they match then "eat" the current token
# and assign the next token to the self.current_token,
# otherwise raise an exception.
if self.current_token.type==token_type:
self.current_token=self.get_next_token()
else:
self.error()
def term(self):
'''
Return an INTERGER token value.
'''
token=self.current_token
self.eat(INTEGER)
return token.value
def expr(self):
'''
Arithmetic expression parser/Interpreter.
'''
# set current token to the first token taken from the input
self.current_token = self.get_next_token()
result=self.term()
while self.current_token.type in(PLUS,MINUS,MULTI,DIVISION):
token=self.current_token
if token.type==PLUS:
self.eat(PLUS)
result=result+self.term()
elif token.type==MINUS:
self.eat(MINUS)
result=result-self.term()
elif token.type==MULTI:
self.eat(MULTI)
result=result*self.term()
elif token.type==DIVISION:
self.eat(DIVISION)
result=result/self.term()
return result
def main():
while True:
try:
text=input('calc>')
except EOFError:
break
if not text:
continue
interpreter=Interpreter(text)
result=interpreter.expr()
print(result)
if __name__=='__main__':
main()
|
# 분류 ANN을 위한 인공지능 모델 구현
from keras import layers, models
#분산 방식 모델링을 포함하는 함수형 구현
def ANN_models_func(Nin, Nh, Nout):
x = layers.Input(shape=(Nin,))
h = layers.Activation('relu')(layers.Dense(Nh)(x))
y = layers.Activation('softmax')(layers.Dense(Nout)(h))
model = models.Model(x,y)
model.compile(loss = 'categorical_crossentropy',
optimizer = 'adam', metrics = ['accuracy'])
return model
# 분류 ANN에 사용할 데이터 불러오기
import numpy as np
from keras import datasets # mnist
from keras.utils import np_utils # to_categorical
def Data_func():
(X_train, y_train), (X_test, y_test) = datasets.mnist.load_data()
Y_train = np_utils.to_categorical(y_train)
Y_test = np_utils.to_categorical(y_test)
L, W, H = X_train.shape
X_train = X_train.reshape(-1, W*H)
X_test = X_test.reshape(-1, W*H)
X_train = X_train/255
X_test = X_test/255
return (X_train, Y_train), (X_test, Y_test)
# 분류 ANN 학습 결과 그래프 구현
import matplotlib.pyplot as plt
def plot_loss(history):
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model_loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc = 0)
def plot_acc(history):
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model_acc')
plt.ylabel('Acc')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc = 0)
# 분류 ANN 학습 및 성능 분석
def main():
Nin = 784
Nh = 100
number_of_class = 10
Nout = number_of_class
model = ANN_models_func(Nin, Nh, Nout)
(X_train, Y_train), (X_test, Y_test) = Data_func()
##############################
# Training
##############################
history = model.fit(X_train, Y_train, epochs = 15,
batch_size = 100, validation_split = 0.2)
performance_test = model.evaluate(X_test, Y_test, batch_size = 100)
print('Test Loss and Accuracy ->', performance_test)
plot_loss(history)
plt.show()
plot_acc(history)
plt.show()
# Run code
if __name__ == '__main__':
main()
|
def lcm(x, y):
return (x * y) / gcd(x,y)
def gcd(x, y):
while(y):
x, y = y, x % y
return x
|
with open('6_input.txt') as fp:
data = fp.read().splitlines()
# print(data)
def split_orbits(value):
centre, orbiter = value.split(')')
return centre, orbiter
def all_objects(map):
centres = []
orbiters = []
for value in map:
centre, orbiter = split_orbits(value)
centres.append(centre)
orbiters.append(orbiter)
all = list(set(centres + orbiters))
return all
def direct_orbits(map, centres):
direct_orbits_count = []
for i in map:
centre, orbiter = split_orbits(i)
if centre in centres:
direct_orbits_count[centres.index(centre)] += 1
else:
centres.append(centre)
direct_orbits_count.append(1)
return sum(direct_orbits_count), centres
def indirect_orbits(map, centres):
indirect_orbits_count = []
centres_all = []
orbiters_all = []
all = all_objects(map)
for i in map:
centre, orbiter = split_orbits(i)
centres_all.append(centre)
orbiters_all.append(orbiter)
for i in all:
current_object = i
if i in orbiters_all:
current_object = centres_all[orbiters_all.index(i)]
print('current object: ', current_object)
while current_object in orbiters_all:
current_object = centres_all[orbiters_all.index(current_object)]
indirect_orbits_count.append(current_object)
return len(indirect_orbits_count)
# centres here are now the orbiters
# find the index of the centre of any orbits of current_object
# add 1 to the indirect_orbits_count
# find any of the new "centre"s centres.
# continue until there are no more centres the "current_object" is orbiting.
# move onto next item in centres.
def total_orbits(map):
direct, centres = direct_orbits(map, [])
indirect = indirect_orbits(map, centres)
return direct + indirect
def you_to_santa(map):
dist_list = []
for i in map:
centre, orbiter = split_orbits(i)
dist_list.append((centre, orbiter, 1))
return dist_list
from collections import defaultdict
class Graph():
def __init__(self):
"""
self.edges is a dict of all possible next nodes
e.g. {'X': ['A', 'B', 'C', 'E'], ...}
self.weights has all the weights between two nodes,
with the two nodes as a tuple as the key
e.g. {('X', 'A'): 7, ('X', 'B'): 2, ...}
"""
self.edges = defaultdict(list)
self.weights = {}
def add_edge(self, from_node, to_node, weight):
# Note: assumes edges are bi-directional
self.edges[from_node].append(to_node)
self.edges[to_node].append(from_node)
self.weights[(from_node, to_node)] = weight
self.weights[(to_node, from_node)] = weight
graph = Graph()
def edge_to_graph(data):
for edge in you_to_santa(data):
graph.add_edge(*edge)
# dijsktra code by Ben Keen.
# http://benalexkeen.com/implementing-djikstras-shortest-path-algorithm-with-python/
def dijsktra(graph, initial, end):
# shortest paths is a dict of nodes
# whose value is a tuple of (previous node, weight)
shortest_paths = {initial: (None, 0)}
current_node = initial
visited = set()
while current_node != end:
visited.add(current_node)
destinations = graph.edges[current_node]
weight_to_current_node = shortest_paths[current_node][1]
for next_node in destinations:
weight = graph.weights[(current_node, next_node)] + weight_to_current_node
if next_node not in shortest_paths:
shortest_paths[next_node] = (current_node, weight)
else:
current_shortest_weight = shortest_paths[next_node][1]
if current_shortest_weight > weight:
shortest_paths[next_node] = (current_node, weight)
next_destinations = {node: shortest_paths[node] for node in shortest_paths if node not in visited}
if not next_destinations:
return "Route Not Possible"
# next node is the destination with the lowest weight
current_node = min(next_destinations, key=lambda k: next_destinations[k][1])
# Work back through destinations in shortest path
path = []
while current_node is not None:
path.append(current_node)
next_node = shortest_paths[current_node][0]
current_node = next_node
# Reverse path
path = path[::-1]
return path
print('part a solution: ', total_orbits(data))
def part_2_solution(data):
edge_to_graph(data)
total = dijsktra(graph, 'YOU', 'SAN')
print('path: ', total)
print('len: ', len(total) - 3)
return len(total) - 3
|
# The valuation model for a stock
# Author: Liang Tang
# License: BSD
import numpy as np
import sys
from sklearn import linear_model
from pyvalue import constants
from pyvalue.morningstar import financial
class StockIntrinsicValue:
def __init__(self):
return
@staticmethod
def intrinsic_value(fin, ys=10, risk_free_rate=constants.US_10Y_NOTE_YIELD, log=None):
"""
Compute the intrinsic value of a stock share
:param fin: the morningstar financial object of the stock
:type fin: financial.Financial
:param ys: the number of years for estimation
:type ys: int
:param risk_free_rate: the rate of US 10 years note (risk free 'ys' years return)
:type risk_free_rate: float
:param log: the log information
:type log: pyvalue.log_info.LogInfo
:return: the intrinsic value of a stock share
"""
dividend = StockIntrinsicValue._predict_annual_dividend(fin, log)
future_book_value = StockIntrinsicValue._predict_book_value(fin, 10, log)
if future_book_value is None:
return None
iv = 0
risk_free_ratio = (1 + risk_free_rate) ** ys
iv += dividend * (1.0 - 1.0 / risk_free_ratio) / risk_free_rate
iv += future_book_value / risk_free_ratio
return iv
@staticmethod
def _predict_book_value(fin, num_yrs, log=None):
"""
Compute the predicted book value after a number of years
:param fin: the morningstar financial object of the stock
:type fin: financial.Financial
:param num_yrs: the number of years
:type num_yrs: int
:param log: the log information
:type log: pyvalue.log_info.LogInfo
:return: the predicted book value after 'num_yrs' years
"""
n = len(fin.book_value_per_share)
if n < 2:
return None
x_vals = np.array(range(n))
x_vals.shape = (n, 1)
book_values = fin.book_value_per_share
sorted_dates = sorted(book_values.keys(), cmp=financial.cmp_date)
y_vals = [book_values.get(date_str) for date_str in sorted_dates]
# Create linear regression object
regr = linear_model.LinearRegression()
regr.fit(x_vals, y_vals)
[predicted_y] = regr.predict(n + num_yrs)
if log is not None:
log.println("The historical book value for " + fin.stock)
for date in sorted_dates:
log.println("\t" + date + " : " + str(book_values.get(date)))
log.println(
"The predicted " + str(n) + " years book value per share of " + fin.stock + " : " + str(predicted_y))
return predicted_y
#
#
# # Get the last years's book value
# sorted_dates = sorted(financial.book_value_per_share.keys(), cmp=morningstar_financials.cmp_date)
# this_yr_val = financial.book_value_per_share[sorted_dates[-1]]
# last_yr_val = financial.book_value_per_share[sorted_dates[-2]]
# return last_yr_val + (last_yr_val - this_yr_val)*num_yrs
@staticmethod
def _predict_annual_dividend(fin, log=None):
"""
Compute the predicted dividend (in dollar) per year in the next 10 years
:param fin: the morningstar financial object of the stock
:type fin: financial.Financial
:param log: the log information
:type log: pyvalue.log_info.LogInfo
:return:
"""
if 'TTM' not in fin.dividends:
predicted_dividend = 0
if log is not None:
log.println("No TTM in financial data for " + fin.stock
+ ", the predicted dividend is 0")
else:
predicted_dividend = fin.dividends['TTM']
if log is not None:
log.println("the predicted dividend for " + fin.stock + " : " + str(predicted_dividend))
return predicted_dividend
|
# https://leetcode.com/problems/binary-tree-level-order-traversal/
# Medium
# Notes: uses multiple lists and did it using iterative methods.
# Notes: 1 list to carry nodes and another to hold children. Must empty lists each iteration
# Notes: Good time and space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
answer = []
queue = []
queue.append(root)
children = []
while queue:
level_nodes = []
for node in queue:
level_nodes.append(node.val)
if node.left:
children.append(node.left)
if node.right:
children.append(node.right)
if level_nodes:
answer.append(level_nodes)
queue = children
children = []
return answer
|
# https://leetcode.com/problems/insertion-sort-list/
# Medium
# My interpretation of insertion sort of a linked list
# First, you shouldn't use a singly linked list for insertion sort because you often need to go back
# I got around this by removing the node and iterating from the start of the list until I found the correct placement. Such a method would take an extraordinary long time and would probably eliminate the only reason one would use insertion sort in the first place (for a mostly sorted list)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
currentNode = head
while currentNode:
if not currentNode.next:
break
if currentNode.next.val < currentNode.val:
... # Remove, find place, then continue
removed = currentNode.next
currentNode.next = removed.next
if removed.val < head.val:
removed.next = head
head = removed
else:
walker = head
while walker:
if removed.val < walker.next.val:
removed.next = walker.next
walker.next = removed
break
walker = walker.next
else:
currentNode = currentNode.next
return head
|
# Варіант 1
import random
arr = [random.randint(-100,100) for i in range(30)]
MaxNumb=max(arr)
arr.index(MaxNumb)
print(arr)
print("Max number is " + str(MaxNumb))
print("This number is in " + str(arr.index(MaxNumb)+1)+"th place")
for i in range(29):
if i%2 ==0:
odds =[ n for n in arr if n%2]
odds.sort(reverse = True)
print(odds)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This code is an adaptation of the algorithms provided by Professor Lucas Silva de Oliveira
('Controller_TF.py' and 'Tank_NL.py') and it simulates the open loop dynamics of a coupled tank system
with measurement noise and an inserted non-linearity (Gaussian), using the 'Python Control Systems' library.
This code also simulates the control loop with a first-order controller designed via the root location for the
system in question.
The main commands used in the Python Control Systems library are:
- NonlinearIOSystem (class)
- InterconnectedSystem (class)
- input_output_response (class)
-tf2io (function)
-input_output_response (function)
@authors: Izaías Alves, Lucas Silva Rodriges
"""
"""
Esse código é uma adaptação dos algoritmos fornecidos pelo professor Lucas Silva de Oliveira
('Controlador_TF.py' e 'Tanque_NL.py') e o mesmo simula a dinâmica em malha aberta de um sistema de tanques acoplados
com ruído de medição e uma não linearidade inserida (gaussiana), através do uso da biblioteca 'Python Control Systems'.
Este código ainda simula a malha de controle com um controlador de primeira ordem projetado via Lugar das raízes para o
sistema em questão.
Os principais comandos utilizados da biblioteca Python Control Systems são:
- NonlinearIOSystem (classe)
- InterconnectedSystem (classe)
- input_output_response (classe)
-tf2io (função)
-input_output_response (função)
@authors: Izaías Alves, Lucas Silva Rodriges
"""
import numpy as np # Importando a biblioteca numpy - para ambiente matemático com vetores
import matplotlib.pyplot as plt # Importando a biblioteca matplotlib - para plotagem
import control as clt # Importando a biblioteca control - para a simulação da função de transferência do model
plt.close('all') # Fechando todas as janelas com figuras
'----------------------------------------------------------------------------------------------------------------------'
#Definição do tempo de simulação e amostragem:
T = 1 # Período de amostragem (segundos)
tf = 3000 # Duração do teste (segundos)
t = np.arange(0, tf+T, T) # Vetor de tempo do experimento
'----------------------------------------------------------------------------------------------------------------------'
"""
A variável 'caso', define em qual situação o sistema será simulado:
caso = 0 : Simula o sistema em malha aberta com ruído.
caso = 1 : Simula o sistema em malha aberta com ruído, porém com amplitude diferente.
caso = 2 : Simula o sistema em malha aberta com ruído e perturbação (aumentou da vazão de saída 'q_out' em 5%).
"""
caso = 2 # Tipo de simulação do sistema
#Sequência de ruídos de medição da saída do sistema:
np.random.seed(55555555) # Define a propragação do gerador de números aleatórios da função random da biblioteca numpy
if caso == 0:
np.random.seed(55555555) # Define a propragação do gerador de números aleatórios
s1 = np.random.normal(0, 0.03, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 1)
np.random.seed(44444444) # Define a propragação do gerador de números aleatórios
s2 = np.random.normal(0, 0.025, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 2)
elif caso == 1:
np.random.seed(105050) # Define a propragação do gerador de números aleatórios
s1 = np.random.normal(0, 0.03, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 1)
np.random.seed(505010) # Define a propragação do gerador de números aleatórios
s2 = np.random.normal(0, 0.025, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 2)
else:
np.random.seed(1000) # Define a propragação do gerador de números aleatórios
s1 = np.random.normal(0, 0.03, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 1)
np.random.seed(250000) # Define a propragação do gerador de números aleatórios
s2 = np.random.normal(0, 0.025, len(t)) # Gera a sequencia de ruidos de mediçao da saida (tanque 2)
'----------------------------------------------------------------------------------------------------------------------'
# Função da equação diferencial do sistema que retorna os deltas das alturas dos níveis de água dos tanques 1 e 2:
def tanque_NL_update(t,x,u, params):
"""
Essa função simula a dinâmica do sistema de tanques acoplados e a mesma retorna os deltas das alturas dos níveis de
água dos tanques 1 e 2.
:param t: Vetor de tempo
:param x: Estados do sistema
:param u: Entradas do sistema
:param params: parametros do sistema
:return: dh1 - Delta de altura do tanque 1, dh2 - Delta de altura do tanque 2
"""
global caso # Importando a variável global 'caso' para definir se o sistema terá ou não perturbação
# Verificando qual valor será atribuido a variável 'ds', esta representa a perturbação inserida no sistema
if caso == 0:
ds = 1
elif caso == 1:
ds = 1
else:
ds = 1.025
h1 = x[0] # Altura do tanque 1
h2 = x[1] # Altura do tanque 2
us = u[0] # Sinal de controle que entra no sistema não linear (entrada)
s1 = u[1] # Sinal de ruído (seq. 1) (entrada)
s2 = u[2] # Sinal de ruído (seq. 2) (entrada)
# Parâmetos do sistema:
rd = params.get('rd', 31) # Raio do tanque (m)
mu = params.get('mu', 0) # Constante do sólido não linear
sig = params.get('sig', 0.25) # Constante do sólido não linear
A1 = (3 * rd / 5) * 2.7 * rd - (3 * rd / 5) * (1 / (sig * np.sqrt(2 * np.pi))) * np.cos(2.5 * np.pi * (h1 - mu)) \
* np.exp(-((h1 - mu) ** 2) / 2 * sig ** 2) # Área da não linearidade (gaussiana)
qin = 19 * us + 265.25 # Vazão de entrada no instante de tempo i
q21 = 37.4 * (h2 - h1) + 290.6 # Vazão entre os tanques 1 e 2 no instante i
qout = 8.8 * h1 + 556 # Vazão de saída do tanque 1
dh1 = ((q21 - ds * qout) / A1) # Delta da altura do tanque 1
dh2 = ((qin - q21) / 3019) # Delta da altura do tanque 2
dh1 = dh1 + s1 # Delta 1 acrescido do ruído de medição (saida)
dh2 = dh2 + s2 # Delta 2 acrescido do ruido de medição (saida)
return dh1, dh2
'----------------------------------------------------------------------------------------------------------------------'
# Instanciando o objeto ('tanque') do tipo 'NonlinearIOSystem' (classe), que é uma representação em espaço de estados
# de um sistema não linear:
tanque = clt.NonlinearIOSystem(tanque_NL_update, name='tanque', inputs = ('us', 's1', 's2'), outputs=('y1', 'y2'),
states=('h1', 'h2'))
print(f'------------Representação do sistema em espaço de estados------------\n{tanque}\n')
'----------------------------------------------------------------------------------------------------------------------'
# Função de trasferência do Controlador, usando a classe 'TransferFunction':
G_controller = clt.TransferFunction([1, 0.008],[1, 0.2, 0])
print(f'---------------Função de transferência do controlador----------------\nG_controller = {G_controller}\n')
'----------------------------------------------------------------------------------------------------------------------'
# Convertendo a função de transferência do controlador para um sistema do tipo I/O (entrada-saída).
controlador = clt.tf2io(G_controller, name='controlador', inputs='ys', outputs='uc')
'----------------------------------------------------------------------------------------------------------------------'
# Construindo a malha de controle por meio da classe 'InterconnectedSystem', que realiza as interconexões dos
# subsistemas (blocos) da malha e retorna um objeto do tipo sistema I/O (entrada-saída)
malha_controle = clt.InterconnectedSystem(
(controlador, tanque), name='malha_controle',
connections = (
('controlador.ys','-tanque.y1'),
('tanque.us','controlador.uc')),
inplist = ('controlador.ys', 'tanque.us','tanque.s1', 'tanque.s2'),
inputs = ('ref','u0', 's1', 's2'),
outlist = ('tanque.y1','tanque.y2','tanque.us'),
outputs = ('y1','y2','u'))
'----------------------------------------------------------------------------------------------------------------------'
# Definindo dos parâmetros de simulação:
amp = 27.808 # Amplitude do sinal de controle que leva o sistema para o ponto de operação (P.O)
u0 = amp*np.ones(len(t)) # Vetor do sinal de controle
#Sequência de degraus da referência (ref) aplicada ao sistema:
ref = 27*np.ones(len(t)) # Vetor da referência do sistema (Altura do nível de água do tanque 1)
ref[500:1000] = 31 # Degrau positivo de +4cm em relação ao ponto de operação
ref[1000:1500] = 27 # Degrau negativo de -4cm levando o sistema de volta para o ponto de operação
ref[1500:2000] = 23 # Degrau negativo de -4cm em relação ao ponto de operação
ref[2000:2500] = 29 # Degrau intermediário com amplitude de 6cm
ref[2500:3001] = 27 # Degrau negativo de -2cm levando o sistema de volta para o ponto de operação
h1 = 27 # Altura inicial do tanque 1
h2 = ((8.77 + 37.39) * h1 + 556 - 290.58)/37.39 # Altura inicial do tanque 2
X0 = [h1, h2] # Vetor de estados dos tanques 1 e 2
'----------------------------------------------------------------------------------------------------------------------'
#Simulação do sistema em malha fechada com controlador implementado:
t_out, y_out, x_out = clt.input_output_response(malha_controle, t, U=[ref, u0, s1, s2], X0=[0, 0, X0[0], X0[1]],
return_x=True)
'----------------------------------------------------------------------------------------------------------------------'
#Plotagem dos gráficos:
plt.figure(1)
plt.subplot(3, 1, 1)
plt.plot(t_out, y_out[0, :], "b", label="h1(t)") # Plotando a saída do sistema (tanque 1)
plt.plot(t_out, ref, 'k--', color='black', label='Referência') # Plotando o sinal de referência
#plt.plot(t_out, (ref + ref * 0.02), '--r',label='Margem de 2%') # Plotando a margem sup. de 2% em relação a referência
#plt.plot(t_out, (ref - ref * 0.02), '--r') # Plotando a margem inf. de 2% em relação a referência
plt.ylabel('h1(t)[cm]') # Nomeando o eixo vertical
plt.xlabel('Times$(s)$') # Nomeando o eixo horizontal
plt.xlim(0, tf) # Definindo os limites do tempo de simulação
plt.ylim(20, 35) # Definindo os limites de altura exibidos no gráfico
plt.legend(loc='lower right') # Posicionando a legenda no gráfico
plt.title('Resposta temporal do tanque em malha fechada com controlador') # Definindo o título do gráfico
plt.grid()
plt.subplot(3, 1, 2)
plt.plot(t_out, y_out[1, :], color='blue', label="h2(t)") # Plotando a saída do sistema (tanque 2)
plt.ylabel('h1(t)[cm]') # Nomeando o eixo vertical
plt.xlim(0, tf) # Definindo os limites do tempo de simulação
plt.ylim(30, 60) # Definindo os limites de altura exibidos no gráfico
plt.legend() # Definindo a legenda
plt.grid()
plt.subplot(3, 1, 3)
plt.plot(t_out, y_out[2, :],'b',label='u0') # Plotando o sinal de controle
plt.ylabel('u(t)[%]') # Nomeando o eixo vertical
plt.xlabel('Times$(s)$') # Nomeando o eixo horizontal
plt.xlim(0, tf) # Definindo os limites do tempo de simulação
plt.ylim(0, 100) # Definindo os limites de altura exibidos no gráfico
plt.legend() # Definindo a legenda
plt.grid()
plt.show()
|
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : break
try:
fValue = float(num)
except:
print("Invalid Input")
continue
if largest is None:
largest = fValue
elif fValue > largest:
largest = fValue
if smallest is None:
smallest = fValue
elif fValue < smallest:
smallest = fValue
print("Maximum", largest)
print("Minimum", smallest)
|
"""
置信区间
期望(均值/u)
标准差=均方差
区间估计可信度更高
参考 https://www.zhihu.com/question/26419030
Z校验值
Z P值 差异程度
>2.58 <0.01 非常显著
>1.96 <0.05 显著
<1.96 >0.05 不显著
"""
import math
# 两组的平均数都是70,但A组的标准差约为17.08分,B组的标准差约为2.16分,说明A组学生之间的差距要比B组学生之间的差距大得多
a = [95, 85, 75, 65, 55, 45]
b = [73, 72, 71, 69, 68, 67]
def avg(data):
s = sum(data)
return s / len(data)
def stand_dev(data):
d_v = avg(data)
s = 0
for d in data:
s += (d - d_v) * (d - d_v)
return math.sqrt(s / len(data))
a_v = avg(a)
b_v = avg(b)
print(a_v, b_v)
sd_a = stand_dev(a)
sd_b = stand_dev(b)
print(sd_a, sd_b)
print('计算Z校验值')
# 计算置信区间全过程
def cal_z(s1_avg, s1_num, s1_std, s2_avg, s2_num, s2_std):
di_avg = s1_avg - s2_avg
s_sum = s1_std * s1_std / s1_num + s2_std * s2_std / s2_num
return di_avg / math.sqrt(s_sum)
def cal_ci():
s1_num = 33771
s1_all = 777193
s2_num = 34190
s2_all = 755929
# 计算均值
s1_avg = s1_all / s1_num
s2_avg = s2_all / s2_num
# 23.013621154244767 22.109651945013162
print(s1_avg, s2_avg)
# 根据单个与均值计算
s1_std = 53.21
s2_std = 50.21
z = cal_z(s1_avg, s1_num, s1_std, s2_avg, s2_num, s2_std)
# 2.27 >1.96 <0.05 显著
print('z:{}'.format(z))
# 效果好坏 -0.039 提升为负数 效果差
d_avg = (s2_avg - s1_avg)
print('d_avg / s1_avg:{}'.format(d_avg / s1_avg))
# 差多少 置信空间
s_sum_sqrt = math.sqrt(s1_std * s1_std / s1_num + s2_std * s2_std / s2_num)
# -0.9039692092316045 0.3969567052843686 0.7780351423573625
print(d_avg, s_sum_sqrt, s_sum_sqrt * 1.96)
# 区间 即区间 [-1.678, -0.122] 有 95%(z=1.96) 查表可得 的可能性包含两个总体均值之差
print(d_avg - s_sum_sqrt * 1.96, d_avg + s_sum_sqrt * 1.96)
# 相对比与均值的变化
print((d_avg - s_sum_sqrt * 1.96) / s1_avg,
(d_avg + s_sum_sqrt * 1.96) / s1_avg)
cal_ci()
|
# Testing connections across a IP range on a specified port by attempting TCP three-way handshake
# Output: printing on the screen, consecutive successful connections will be shown with only one line and only the latest successful connection will be shown
# Program requirement: Python 2.7
import socket
from ipaddress import ip_network
def TCP_connect(IP, port_number, delay, x, count):
TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
TCPsock.settimeout(delay)
try:
TCPsock.connect((IP, port_number))
print("\rSuccessfully connect to %s" % (IP+":"+str(port_number))),
x = -1
count = count + 1
except:
if x:
print "\nUnable to connect to " + IP + ":" + str(port_number)
x = 0
else:
print "Unable to connect to " + IP + ":" + str(port_number)
return (x, count)
def test_TCP_connection(network_range, port_number, delay):
network = ip_network(network_range)
x = 0 # To control the printing output so that consecutive successful connections only show on one line
count = 0 # Count the number of successful connections
if network.network_address == network.broadcast_address:
x, count = TCP_connect(str(network.network_address), port_number, delay, x, count)
else:
x, count = TCP_connect(str(network.network_address), port_number, delay, x, count)
for host in network.hosts():
x, count = TCP_connect(str(host), port_number, delay, x, count)
x, count = TCP_connect(str(network.broadcast_address), port_number, delay, x, count)
if count == 0:
print "\n\nUnable to communicate to %s on port %s" % (network_range, port_number)
else:
print "\n\nTotal successful connection: %d" % count
def main():
network_range = raw_input("Please enter network range in CIDR: ")
port_number = int(raw_input("Please enter TCP port number: "))
delay = int(raw_input("Please enter how many seconds the socket is going to wait until times out: "))
test_TCP_connection(network_range, port_number, delay)
if __name__ == "__main__":
main()
|
import numpy as np
import matplotlib.pyplot as plt
# assume we have 1000 dogs
greyhounds = 500
labradors = 500
#greyhounds are usually 28 inches
grey_height = 28 + (4* np.random.randn(greyhounds))
# labradors are usually 24 inches
lab_height = 24 + (4* np.random.randn(labradors))
# plot a histogram of the two heights
plt.hist([grey_height,lab_height], stacked = True, color =['r','b'])
plt.show()
|
import operator
x="hai"
y="hello"
x=operator.iadd(x,y);
print(x)
y="kiran"
z="kumar"
y=operator.iconcat(y,z);
print(y)
y="kirankiran"
y+=z
print(y)
print('\n\n\n♥')
li=[5,4,3,2,1]
print('li: ',li)
li2=li
print('ids are same after assign') if li is li2 else print("not same after assing")
li2.append(0)
print('ids are same after append of li2') if li is li2 else print("not same after append ")
print('li2: ',li2)
print('li ele are also changed since both ids are same')
print('li: ',li)
print('\n\n\n♥')
print("normal addition of lists\n")
li=li+[1,2,3,4]
print('ids are same after li normal add') if li is li2 else print("ids are not same after li normal add new li is created ")
print('li: ',li)
print('after li update this is a new li')
print('li2',li2)
print('li2 ele are unchanged since this is same as old li not new li')
print('\n\n\n♥')
print('inplace addition')
list1=[1,2,3]
print('list1: ',list1)
list2=list1
print('list2',list2)
print('ids are same') if list1 is list2 else print("ids are not same ")
list1+=[1,2,3,4]
print('ids are same') if list1 is list2 else print("ids are not same ")
print('list1: ',list1)
print('list2',list2)
|
print('\n1♥importing module, using array() and printing')
from array import *
my_array1=array('i',[1,2,3])
print('trying to print direct arrayIdentifierName')
print(my_array1)# prints the total discription
import array as arr
my_array2=arr.array('i',[4,5,6])
print('using index')
for i in range(len(my_array2)):
print(my_array2[i],end=' ')
print("\nslice of array: ",my_array2[2:4])
import array
li_for_arr3=[7,8,9]
my_array3=array.array('i',li_for_arr3)
print('\nusing direct reference')
for i in my_array3:
print(i,end=' ')
print('\n\n\n2♥using append, extend and insert methods')
print('append: ')
my_array1.append(4)
print(my_array1)
print()
print('extend: ')
my_array2.extend(my_array3)
print(my_array2)
print('slicing works on arry anyhow all type of slicing')
for i in my_array2[:]:
print(i,end=" ")
print()
print('insert: takes pos and value to append at')
my_array3.insert(3,10)
print('inserted 10 at 3: ',my_array3)
print('\n\n\n3♥using pop and remove methods')
print("array: ",my_array1)
print('pop: can pop last by default or the position and it returns')
print("pop(): ",my_array1.pop())
print('pop(0): ',my_array1.pop(0))
print('pop(0): ',my_array1.pop(0))
print("array af pop: ",my_array1)
print()
print("array: ",my_array3)
print('remove:takes exactly one value and desont returns ')
my_array3.remove(8)
print("remove(8): ",my_array3)
my_array3.remove(9)
print('remove(9): ',my_array3)
my_array3.remove(7)
print('remove(7): ',my_array3)
print("array af remove: ",my_array3)
print('\n\n\n4♥using tolist and fromlist methods')
print('array: ',my_array2)
print('tolist: convert a array to list')
li=my_array2.tolist()
print('my_array2 to li: ',li)
print()
print('fromlist: append list at last to the array')
print('array,li:',my_array3,li)
my_array3.fromlist(li)
print(my_array3)
print('\n\n\n5♥using index, reverse and sorted methods')
print('array: ',my_array3)
print('index : takes value to finds its pos')
print('index of value 10: ',my_array3.index(10))
print('index of value 4: ',my_array3.index(4))
print('index of value 9: ',my_array3.index(9))
my_array3.insert(3,6)
print('now arr is insert with 6: ',my_array3)
print('index of value 6: ',my_array3.index(6))
print()
print('reverse: takes no arg and deosnot return')
my_array3.reverse()
print('reverse of my_array_3 is : ',my_array3)
print('reverse using split: ',my_array3[::-1])
print()
print('sorted fun: ')
print('reverse sort of the array is : ',sorted(my_array3,reverse=True))
print('\n\n\n6♥using buffer_info and count methods')
print("array: ",my_array3)
print('buffer_info: takes no arg return arr buffer addr and no of ele')
print('buffer_infor of myarrat3 is : ',my_array3.buffer_info())
print()
print('count: counts the no of occurances')
print('count of 6: ',my_array3.count(6))
|
import random
print('ROCK_PAPER_SCISSOS'.center(50, '*'))
choice = ['R', 'P', 'S']
win, loss, tie = 0, 0, 0
quit_kw=['stop','exit','quit','terminate']
play_kw=['yes','ok','yeah','play']
def winner(player, computer):
global win, loss, tie
if player == computer:
tie += 1;return 'you tie'
elif player == 'R' and computer == 'S':
win += 1;return 'you win'
elif player == 'P' and computer == 'R':
win += 1;return 'you win'
elif player == 'S' and computer == 'P':
win += 1;return 'you win'
else:
loss+=1
win-=1
return 'you loss..!'
while True:
if win==3:print('your are ultimate winner');break
if loss==3:print('your are ultimate looser');break
print(f"win:{win}\t loss:{loss}\t tie:{tie}")
print('enter R/rock p/paper s/scissors')
player_choice = input().upper()
stat1 = 'ROCK' if player_choice == 'R' else 'PAPER' if player_choice == 'P' else 'SCISSORS' if player_choice == 'S' else 'break'
computer_choice = choice[random.randint(0,2)]
stat2 = 'ROCK' if computer_choice == 'R' else 'PAPER' if computer_choice == 'P' else 'SCISSORS' if computer_choice == 'S' else 'break'
if stat1 != 'break':
print(f'{stat1} VERSUS...{stat2}')
else:
break
result = winner(player_choice, computer_choice)
print(f'guess what...{result}')
print('wanna play agian...y?n')
status = input().upper()
if status == 'N':
print(f"win:{win}\t loss:{loss}\t tie:{tie}")
print('take care..:-(')
break
|
import unittest
from .controller import Item
class UnitTestItem(unittest.TestCase):
def test_is_item_purchasable_true(self):
item_obj = Item()
item_list = [
{
"name": "Slurpee",
"price": 80,
"quantity": 18
},
{
"name": "Coca Cola",
"price": 120,
"quantity": 22
},
]
item_chosen = 0
coin_amount = 500
expected = True
self.assertEqual(expected, item_obj.is_item_purchasable(
item_chosen, coin_amount, item_list))
def test_is_item_purchasable_false(self):
item_obj = Item()
item_list = [
{
"name": "Slurpee",
"price": 80,
"quantity": 18
},
{
"name": "Coca Cola",
"price": 120,
"quantity": 22
},
]
item_chosen = 0
coin_amount = 10
expected = False
self.assertEqual(expected, item_obj.is_item_purchasable(
item_chosen, coin_amount, item_list))
def test_item_deduction(self):
item_obj = Item()
outlet = [
{
"idx": 0,
"name": "Slurpee",
},
{
"idx": 0,
"name": "Slurpee",
},
]
item_list = [
{
"name": "Slurpee",
"price": 80,
"quantity": 18
},
{
"name": "Coca Cola",
"price": 120,
"quantity": 22
},
]
expected = [
{
"name": "Slurpee",
"price": 80,
"quantity": 16
},
{
"name": "Coca Cola",
"price": 120,
"quantity": 22
},
]
self.assertEqual(expected, item_obj.item_deduction(
outlet, item_list))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 12:14:35 2019
@author: mluci
"""
import sqlite3
import os
####connect to the database####
def getdb(db_file):
try:
conn = sqlite3.connect(db_file)
c = conn.cursor()
return c
except:
return False
###check if database exists###
def check_db(db_file):
if os.path.exists(db_file):
return True
else:
return False
###Check if database is empty####
def checkIfTables(db_file):
c=getdb(db_file)
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
tablesInDb =(c.fetchall())
print(len(tablesInDb))
print(tablesInDb)
if len(tablesInDb) > 0:
print("Tables available.")
return True
else:
print("table unavailable")
return False
dbClose(db_file)
####Check if tables in database are empty###
def checkIfTableEmpty(db_file):
try:
c = getdb(db_file)
c.execute('SELECT * FROM business')
resultsRecords = c.fetchall()
if len(resultsRecords ) > 0:
print("Table not empty")
return True
else:
print("Table is empty")
return False
except sqlite3.OperationalError:
print("Table doesn't exist. Can't run check.")
dbClose(db_file)
####Close database####
def dbClose(db_file):
c =getdb(db_file)
conn = getdb(db_file)
c.close()
conn.close()
#dbClose()
|
##Brute Force Mockup of program used to crack Apple's firmware password (SIZE KNOWN)
##Steven Lamp
from itertools import permutations
def main():
psswrd = 'dts'
bruteish(psswrd,3)
def bruteish(crackMe, length):
#################################################
#guesses = forceish(length)
#for g in guesses:
#if(g == crackMe):
#print("PSWRD FOUND: "+g)
#################################################
################PROOF OF CONCEPT#################
guesses = forceish(length)
if crackMe in guesses:
print("PSWRD FOUND")
def forceish(l):
lowers = 'abcdefghijklmnopqrstuvwxyz'
uppers = lowers.upper()
nums = '0123456789'
return [''.join(p) for p in permutations(lowers+uppers+nums,l)]
if __name__ == "__main__":
main()
|
array = [['a','b','c'],['d','e','f']]
# this works for any two-level list
for sub in array:
for e in sub:
print e
'''
Here's another way which works just for this specific array.
print '\n'.join(array[0])
print '\n'.join(array[1])
'''
|
def Average(values):
"""
values must be an iterable yielding numbers.
"""
return sum(values)/len(values)
#end def average(values)
Mean = Average #alternative name
def WeightedAverage(values, weights):
"""
values: a listing of data points.
weights: a listing of weights for each data point corresponding to the data point in "values" with same index.
Both values must have equal length.
"""
lV = len(values)
lW = len(weights)
if lV != lW:
raise ValueError("Both values and weights must have the same length.")
vSum = 0
wSum = 0
for i in range(0,lV):
vSum += values[i]*weights[i]
wSum += weights[i]
return vSum/wSum
#end def weightedAverage(values, weights)
def Median(values, ordered=False, orderFunction=sorted):
"""
values: a listing of data points
ordered: for optmization purposes. Indicates whether values is already in order or not. It assumes it is not by default.
orderFunction: for optmization purposes. Should be a function able to return an ordered version of "values" if "ordered" is set to False. By default, it uses the standard function "sorted".
"""
if not ordered:
values = orderFunction(values)
length = len(values)
if length % 2: #if odd
return values[length//2]
else: #if even
return (values[length//2 - 1]+values[length//2])/2
#end def Median(values, ordered, orderFunction)
def FiveNumberSummary(values, ordered=False, orderFunction=sorted):
"""
values: a listing of data points
ordered: for optmization purposes. Indicates whether values is already in order or not. It assumes it is not by default.
orderFunction: for optmization purposes. Should be a function able to return an ordered version of "values" if "ordered" is set to False. By default, it uses the standard function "sorted".
"""
if not ordered:
values = orderFunction(values)
length = len(values)
firstHalf = values[0:(length//2)]
if length % 2:
secondHalf = values[(length//2)+1:]
else:
secondHalf = values[(length//2):]
#end if-else
return (values[0],Median(firstHalf,1),Median(values,1),Median(secondHalf,1),values[length-1])
#end def FiveNumberSummary(values, ordered, orderFunction)
FNS = FiveNumberSummary #just a shorter form
def Variance(values, sample=False):
"""
values: a listing of data points
sample: indicates whether values refer to a sample dataset. Default: False.
"""
m = Mean(values)
length = len(values)
subSum = 0
for x in values:
subSum += (x - m)**2
if sample:
length -= 1
return subSum/length
#end def Variance(values,sample)
def StandardDeviation(values, sample=False):
"""
values: a listing of data points
sample: indicates whether values refer to a sample dataset. Default: False.
"""
return Variance(values,sample)**0.5 #square root
#end def StandardDeviation(values,sample)
SD = StandardDeviation #shortcut
def MeanAbsoluteDeviation(values):
"""
values: a listing of data points
"""
m = Mean(values)
subSum = 0
for x in values:
subSum += abs(x - m)
return subSum/len(values)
#end def MeanAbsoluteDeviation(values)
MeanDeviation = MeanAbsoluteDeviation #alternative name
MAD = MeanAbsoluteDeviation #ShortCut
|
import random
import matplotlib.pyplot as plt
def horse_race():
horse_positions = [0,0,0,0,0,0,0,0,0,0,0]
dead_horses = []
while len(dead_horses) < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
dice_sum = die1 + die2
if dice_sum in dead_horses:
pass
else:
dead_horses.append(die1 + die2)
print("The dead horses are", dead_horses)
is_winner = False
winning_horse = -1
while not is_winner:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
dice_sum = die1 + die2
if dice_sum not in dead_horses:
horse_positions[die1+die2-2] += 1 #Need to minus 2 bc it's 0 based indexing, so the first element in the list represents snake eyes
if horse_positions[0]==2 or horse_positions[1]==3 or horse_positions[2]==4 or horse_positions[3]==5 or horse_positions[4]==6 or horse_positions[5]==7 or horse_positions[6]==6 or horse_positions[7]==5 or horse_positions[8]==4 or horse_positions[9]==3 or horse_positions[10]==2:
is_winner = True
winning_horse = dice_sum
print("The winning horse is", winning_horse)
return (dead_horses, winning_horse)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 10:37:16 2020
@author: dpatel
"""
def climbStairs(n):
dp = [0] * (n + 1)
dp [0] = 1
dp [1] = 1
if n > 1:
for i in range(2, n+1):
dp[i] = dp[i-1] + dp[i-2]
print(dp)
return dp[n]
if __name__ == "__main__":
print(climbStairs(4))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 15:57:44 2020
@author: dpatel
"""
def coinChange(coins, amount):
if not amount: return 0
dp = [amount + 1] * (amount+1)
for i in range(amount+1):
if i in coins:
dp[i] = 1
continue
candidates = [dp[i-coin]+1 for coin in coins if i-coin > 0]
if candidates:
dp[i] = min(candidates)
return -1 if dp[amount] > amount else dp[amount]
if __name__ == "__main__":
print(coinChange([1,2,5],11))
|
class Solution:
def isPerfectSquare(self, num: int) -> bool:
ansL = 0
ansR = 2 ** 31 - 1
while num != ansL ** 2 and num != ansR **2:
if ansR - ansL == 1:
return False
suppose = (ansR + ansL) // 2
if suppose ** 2 > num:
ansR = suppose
else:
ansL = suppose
print(f'num {num}\tansL {ansL}\tansR {ansR}')
return True
a = Solution
print(a.isPerfectSquare(a, 1))
'''
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
'''
|
# -*- coding:utf-8 -*-
'''
对列表插入操作的实现
'''
class myList(object):
'''
自己实现的list类
'''
__list=[]
def __init__(self,*value):
self.__list.extend(value)
def __str__(self):
return str(self.__list)
def myInsert(self,index,value):
'''
:function 利用切片方法实现list的insert()方法
:param index: give a index
:param value: the value you want to insert
example: mylist.myInsert(2,7)
'''
if index < 0 or index > len(self.__list):
raise IndexError('index out of list')
else:
list_in_1 = self.__list[:index]
list_in_2 = self.__list[index:]
list_in_1.append(value)
list_in_1.extend(list_in_2)
self.__list = list_in_1
|
def average(array):
set_number = set(arr)
total_distinct = len(set_number)
sum = 0
for i in set_number:
sum += i
return sum / total_distinct
if __name__ == '__main__':
n = int(input())
# map(function, iterable)
arr = list(map(int, input().split())) # change all input() to int()
result = average(arr)
print(result)
|
'''
Creat a function by name pallindrome need a paramenter s1, The function return true if it is pallindrome else retrun false
'''
def pallindrome(s1):
#logic
reverses1=s1[::-1]
print (reverses1)
if s1==reverses1:
return True
else:
return False
s1=(input("Enter first Word:- "))
result=pallindrome(s1)
print(result)
|
# Writing to a file
# One of the simplest ways to save data is to write to a file. When we write text to a file, the output will still be available after we close the terminal containing our programs output
# Writing to an empty file
# To write to a file, we need to call open() with a second argument telling python that you want to write to the file.
filename = "programming.txt"
# Here we 'open' a file like normal. The 'w' tells python that we want to open the file in 'write mode'. We can open in read mode 'r', write mode 'w', append mode 'a', and read and write 'r+'.
# If we leave out the argument, python defaults to read only.
# If the file doesn't exist, open() will automatically create the file. However, we need to be cautious as if we open a file in write mode, 'w', and the file exists, python will erase the contents of the file before returning the file object
with open(filename, "w") as file_object:
# Here we are writting a string to the file
file_object.write("I love programming.")
# Python cal only write string to a text file. If we want to store numerical data in a text file, we'll have to convert the data to string format first using the str() function
# Writing multiple lines
# The write() function doesn't add any newlines to the text we write. So if we want to write more than one line without including newline characters, our file won't look like the way we want it to
filename = "programming.txt"
with open(filename, "w") as file_object:
# When we open programming.txt after this code block runs, we'll see that the lines are squished together
# I love programming.I love creating new games.
# To solve the issues we need to include newlines \n
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
# Append to a file
# If we want to add content to a file instead of writing over existing content, we open the file in append mode.
# In append mode python doesn't erase any data, it adds it to the end of the file.
# If the file doesn't exist, it'll be created
filename = "programming.txt"
# We use the 'a' argument to open the file for appending rather than writing over the existing file
with open(filename, "a") as file_object:
# Here we are writing two news lines which get added at the end of our earlier lines
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
# 10-3. Guest: Write a program that prompts the user for their name. When they
# respond, write their name to a file called guest.txt.
filename = "guest.txt"
# with open(filename, "w") as file_object:
# username = input("What is your name? ")
# file_object.write(username)
# 10-4. Guest Book: Write a while loop that prompts users for their name. When
# they enter their name, print a greeting to the screen and add a line recording
# their visit in a file called guest_book.txt. Make sure each entry appears on a
# new line in the file.
filename = "guestBook.txt"
with open(filename, "a") as file_object:
while True:
print("What is your name?")
username = input("Enter 'q' at anytime to quit ")
if username == "q":
break
print(f"\nHello {username.title()}!")
file_object.write(f"{username}\n")
# 10-5. Programming Poll: Write a while loop that asks people why they like
# programming. Each time someone enters a reason, add their reason to a file
# that stores all the responses.
filename = "programmingPoll.txt"
with open(filename, "a") as file_object:
while True:
print("Why do you like programming?")
poll = input("Enter 'q' at anytime to quit ")
if poll == "q":
break
file_object.write(f"{poll}\n")
|
import json
# Here we set the file we write to, to a variable to open
filename = "numbers.json"
# We open the file in read mode (defaults to it if nothing is specified) as python only needs to read from the file
with open(filename) as f:
# json.load() loads the info stored in numbers.json and we assign it to a variable so we can print it.
numbers = json.load(f)
print(numbers)
|
# -*- coding: utf-8 -*-
import re
import os
from num2words import num2words
def int_to_en(num):
d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen',
19 : 'nineteen', 20 : 'twenty',
30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty',
70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
k = 1000
m = k * 1000
b = m * 1000
t = b * 1000
assert(0 <= num)
if (num < 20):
return d[num]
if (num < 100):
if num % 10 == 0: return d[num]
else: return d[num // 10 * 10] + ' ' + d[num % 10]
if (num < k):
if num % 100 == 0: return d[num // 100] + ' hundred'
else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100)
if (num < m):
if num % k == 0: return int_to_en(num // k) + ' thousand'
else: return int_to_en(num // k) + ' thousand ' + int_to_en(num % k)
if (num < b):
if (num % m) == 0: return int_to_en(num // m) + ' million'
else: return int_to_en(num // m) + ' million ' + int_to_en(num % m)
if (num < t):
if (num % b) == 0: return int_to_en(num // b) + ' billion'
else: return int_to_en(num // b) + ' billion ' + int_to_en(num % b)
if (num % t == 0): return int_to_en(num // t) + ' trillion'
else: return int_to_en(num // t) + ' trillion ' + int_to_en(num % t)
raise AssertionError('num is too large: %s' % str(num))
def preprocess2(filename):
# Open the file with read only permit
# I opened the file all at once b/c it was easier to parse this way, but
# for a larger file it would be neccesary to buffer in some way
f_in = open("./Gutenberg/txt/"+filename, 'r+', encoding="ISO-8859-1")
# f_in = open("test.txt", 'r+', encoding="ISO-8859-1")
f_out = open("thatFile.txt", 'a')
text = f_in.read()
# first, cut the text by sentences
sentences = []
# replace curly single quotes with straight single quotes
text = text.replace("‘", "'")
text = text.replace("’", "'")
# text = text.replace("_", " ")
# preserve punctuation with split
text = text.replace(".",".<stop>")
text = text.replace("?","?<stop>")
text = text.replace("!","!<stop>")
#text = re.sub(r"^[a-zA-Z0-9]+[\^\']*[a-zA-Z0-9]+[\^\']*[a-zA-Z0-9]*", "", text)
text = re.sub(r"[a-zA-Z]+[0-9]+", "", text)
text = re.sub(r"[0-9]+[il]", "[0-9]+[1]", text)
text = re.sub(r"[0-9]+[oO]", "[0-9]+[0]", text)
text = re.sub(r"[0-9]+[']+[0-9]*", "[0-9]+[ ]+[0-9]*", text)
text = text.replace("\n", " ")
sentences += re.split("<stop>", text)
# for each sentence, split into individual words
word_regex = r"\w[\w']*[\w]+|[.?!]|\w"
all_words = [re.findall(word_regex, sentence) for sentence in sentences]
num_list = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
ordinal_list = ["rd", "th", "nd", "st", "TH", "RD", "ND", "ST"]
ordinal_list_ = ["_rd", "_th", "_nd", "_st", "_TH", "_RD", "_ND", "_ST"]
for sentence in all_words:
for word in sentence:
# word = word.replace("_","")
if word[0] in num_list and word[-1] in num_list:
word = int_to_en(int(word))
if word[0] in num_list and word[-3:] in ordinal_list_:
word = word[:-3]
#word = re.findall('(\d+(st|nd|rd|th))', word)
word = num2words(int(word), ordinal=True)
word = word.replace("-", " ")
if word[0] in num_list and word[-2:] in ordinal_list:
word = word[:-2]
#word = re.findall('(\d+(st|nd|rd|th))', word)
word = num2words(int(word), ordinal=True)
word = word.replace("-", " ")
# if word == "." or word == "?" or word == "!":
# f_out.write(word + "\n")
# for char in word:
# char = char.replace("_", "")
# else:
# word = word.replace("_", " ")
# f_out.write(" " + word)
#word = (" " + word)
#word = word.replace("_", " ")
#f_out.write(" " + word)
for sentence in all_words:
for word in sentence:
if "_" in word:
word = word.replace("_", "")
if word == "." or word == "?" or word == "!":
f_out.write(word + "\n")
else:
f_out.write(" " + word)
# f2_in = open("thatFile.txt", 'r+', encoding="ISO-8859-1")
# f2_out = open("thatOtherFile.txt", "a")
#for line in f2_in:
# for char in line:
# char = char.replace("_", "")
# f2_out.write(char)
#f2_in.close()
#f2_out.close()
f_in.close()
f_out.close()
for f in os.listdir("./Gutenberg/txt/"):
print(f)
preprocess2(f)
|
# first find the BEST FIT line ( y=mx+b )
# m = ( (mean of x)*(mean of y) - (mean of xy) )/( (mean of x)^2 - (mean of x^2) )
# b = (mean of y) - m*(mean of x)
from statistics import mean
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
df = pd.read_excel('data/regression.xls')
print df
x = np.array(df.X)
y = np.array(df.Y)
def best_fit_slop(xs,ys):
m = (mean(xs)*mean(ys) - mean(xs*ys))/( mean(xs)**2 - mean(xs**2))
return m
def y_intercept(xs,ys,m):
b = mean(ys) - m*mean(xs)
return b
m = best_fit_slop(x,y)
b = y_intercept(x,y,m)
regression_line = [(m*xx)+b for xx in x]
plt.scatter(df.X,df.Y)
plt.plot(x,regression_line)
plt.show()
plt.show()
#What Is Goodness-of-Fit for a Linear Model?
#R-squared is a statistical measure of how close the data are to the fitted regression line.
#R-squared = Explained variation / Total variation
#R-squared is always between 0 and 100%:
# 0% indicates that the model explains none of the variability of the response data around its mean.
# 100% indicates that the model explains all the variability of the response data around its mean.
#if a model could explain 100% of the variance, the fitted values would always equal the observed values and, therefore, all the data points would fall on the fitted regression line.
#R^2 = 1-( squared_error( calculated y) / squared_error( mean of y))
def squared_error(ys_original , ys_line):
return sum ((ys_line - ys_original )**2)
def r_square(ys_original,ys_line):
y_mean_line = [mean(ys_original) for y in ys_original]
return 1 - (squared_error(ys_original,ys_line) / squared_error(ys_original, y_mean_line))
R_squared = r_square(y,regression_line)
print R_squared
|
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
import numpy as np
class kMeans:
def __init__(self):
print("Running kmeans Network")
def runModel(self, df):
clustering=KMeans(init="random", n_clusters=2, random_state=8675309)
features=df.drop(columns=['Output'])
labels=df['Output']
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=90210)
clustering.fit(X_train, y_train)
# apply the labels
train_labels = clustering.labels_
# predict labels on the test set
test_labels = clustering.predict(X_test)
print(np.array(y_test))
print(np.array(test_labels))
return
|
myList = [4, 3, 5.8, False, "hola"]
print(myList)
myList.append(8)
print(myList)
myList.append(9)
print(myList)
myList.extend(range(10,13))
print(myList)
conteo = myList.count(3)
print(conteo)
myList.insert(9, True)
print(myList)
myList.remove(12)
print(myList)
|
primerNumero = int(input("Ingrese el primer numero: "))
segundoNumero = int(input("ingresa el segundo numero"))
if segundoNumero != 0:
print(primerNumero /segundoNumero)
else:
print("Esta no puede ser realidad.")
print("Fin")
|
lst = [[x for x in range (3)] for y in range(3)]
for r in range(3):
for c in range (3):
if lst[r] [c] % 2 !=0:
print("#")
|
subjects = ["Matematica", "Fisica", "Quimica", "Historia", "Lengua"]
scores =[]
for subject in subjects:
score= input("¿Que nota has sacado en ", subject, "?")
scores.append(score)
for i in range(len(subjects)):
print("En", subjects[i] , "has sacado", scores[i])
|
try:
x= int(input("Ingrese un numero: "))
y = 1 / x
print(y)
except ZeroDivisionError:
print("No puedes dividir entre ceron, lo siento. ")
except ValueError:
print("Debes ingresar un valor entero. ")
print("FIN")
|
myList = []
for i in range(10):
myList.append(i + 1)
print(myList)
myList.reverse()
print(myList)
myList.sort()
print(myList)
ubicacion = myList.index(3)
print(ubicacion)
myList.pop()
print(myList)
myList.pop(0)
print(myList)
|
from sys import path
path.append("..\\directorio")
from directorio.area import areaCuadrado, areaCirculo, areaRectangulo
from directorio.perimetro import perCadrado, perCirculo, perRectangulo
def main():
print("--" * 30)
print("programa para calcular areas y perimetros de figuras geometricas")
print("--" * 30)
figura = input("Ingrese el nombre de la figura geometrica")
if figura.lower()=="circulo":
areaCirculo()
perCirculo()
elif figura.lower() == "Cuadrado":
areaCuadrado()
perCadrado()
elif figura.lower() == "Cuadrado":
areaRectangulo()
perRectangulo()
else:
print("no puedo calcular la figura")
if __name__==("__main__"):
main()
|
import random
class Game:
X = 'X'
O = '0'
EMPTY = ' '
TIE = 0
NUM_SQUARES = 9
TREE_DEPTH = 9
MAX, MIN = 1000, -1000
def __init__(self):
self.board = self.new_board()
def display_instruct(self):
"""Display game instructions."""
print(
"""
Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a number, 0 - 8. The number will correspond to the board position as illustrated:
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
Prepare yourself, human. The ultimate battle is about to begin. \n """
)
def new_board(self):
"""Create new game board."""
board = []
for square in range(self.NUM_SQUARES):
board.append(self.EMPTY)
return board
def display_board(self, board):
"""Display game board on screen."""
print("\n\t", board[0], "|", board[1], "|", board[2])
print("\t", "---------")
print("\t", board[3], "|", board[4], "|", board[5])
print("\t", "---------")
print("\t", board[6], "|", board[7], "|", board[8], "\n")
def legal_moves(self, board):
"""Create list of legal moves."""
moves = []
for square in range(self.NUM_SQUARES):
if board[square] == self.EMPTY:
moves.append(square)
return moves
def winner(self, board):
"""Determine the game winner."""
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != self.EMPTY:
winner = board[row[0]]
return winner
if self.EMPTY not in board:
return self.TIE
def ask_yes_no(self, question):
"""ask a yes or now question"""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(self, question, low, high):
"""Ask for a number within a range."""
response = None
while response not in range(low, high):
try:
response = int(input(question))
except ValueError:
pass
return response
def pieces(self):
"""Determine if player or computer goes first."""
go_first = self.ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = self.X
computer = self.O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = self.X
human = self.O
return computer, human
def next_turn(self, turn):
"""Switch turns"""
if turn == self.X:
return self.O
else:
return self.X
def human_move(self):
"""get human move"""
legal = self.legal_moves(self.board)
move = None
while move not in legal:
move = self.ask_number("Make a move? (0 - 8):", 0, self.NUM_SQUARES)
if move not in legal:
print("Can't move there")
print("Fine....")
return move
def check_terminal_state(self, board, computer):
winner = self.winner(board)
if winner is not None:
if winner == self.TIE:
return True, 0
elif winner == computer:
return True, 1
else:
return True, -1
else:
return False, None
def is_board_empty(self, board):
for space in board:
if space != self.EMPTY:
return False
return True
def computer_opening_move(self, board):
if self.is_board_empty(board):
corner_moves = [0,2,6,8]
return corner_moves[random.randrange(0,3)]
return -1
def minimax(self, computer, maximizing_player, turn, board, depth):
"""
created one function to handle entier mimimax algorithm, instead of having a starter function
"""
# beginning game moves
opening_move = self.computer_opening_move(board)
if opening_move > -1:
return opening_move
# get current legal moves
legal = self.legal_moves(board)
# terminal state - check for end of game move
# check for winner or tie
terminal, state = self.check_terminal_state(board, computer)
if terminal:
return state
if depth > self.TREE_DEPTH or len(legal) == 0:
return 0
# holds results for current board moves
minimax_list = []
# analyze all legal moves and append results to minimax_list
for move in legal:
new_board = board.copy()
new_board[move] = turn
if maximizing_player:
result = self.minimax(computer, False, self.X, new_board, depth+1 )
if result is not None:
minimax_list.append(result)
else:
result = self.minimax(computer, True, self.O, new_board, depth+1 )
if result is not None:
minimax_list.append(result)
# if back at top of tree return the best move
if depth == 0:
# print(f'max player {max(minimax_list)}')
return minimax_list.index(max(minimax_list))
else:
# return the max or min of the minimax_list
if maximizing_player:
return max(minimax_list)
else:
return min(minimax_list)
def minimax_decision_aima(self, computer, turn, board, depth):
"""
version of minimax that is closest to AIMA pseudocode, has a starter function
"""
opening_move = self.computer_opening_move(board)
if opening_move > -1:
return opening_move
moves = self.legal_moves(board)
best_scores = []
for move in moves:
new_board = board.copy()
new_board[move] = turn
best_score = self.minimax_aima(computer, False, self.O, new_board, depth )
best_scores.append(best_score)
print(f'best_scores {best_scores}')
return best_scores.index(max(best_scores))
def minimax_aima(self, computer, maximizing_player, turn, board, depth):
"""
version of minimax that is closest to AIMA pseudocode,
"""
# get current legal moves
legal = self.legal_moves(board)
# terminal state - check for end of game move
# check for winner or tie
terminal, state = self.check_terminal_state(board, computer)
if terminal:
return state
# depth check
if depth > self.TREE_DEPTH or len(legal) == 0:
return 0
if maximizing_player:
v = self.MIN
else:
v = self.MAX
# analyze all legal moves and append results to minimax_list
for move in legal:
new_board = board.copy()
new_board[move] = turn
if maximizing_player:
v = max(v, self.minimax_aima(computer, False, self.O, new_board, depth+1))
else:
v = min(v, self.minimax_aima(computer, True, self.X, new_board, depth+1 ))
return v
def minimax_alpha(self, computer, maximizing_player, turn, board, depth, alpha, beta):
"""
minimax alpha beta pruning algorithm.
"""
# check for opening move
opening_move = self.computer_opening_move(board)
if opening_move > -1:
return opening_move
# check terminal state
terminal, state = self.check_terminal_state(board, computer)
if terminal:
return state, 0
legal = self.legal_moves(board)
if depth > self.TREE_DEPTH or len(legal) == 0:
return 0, 0
if maximizing_player:
best = self.MIN
best_index = 0
for index, move in enumerate(legal):
new_board = board.copy()
new_board[move] = turn
result, not_used = self.minimax_alpha(computer, False, self.next_turn(turn), new_board, depth+1, alpha, beta)
if depth == 0:
print(result)
if result > best:
best_index = index
best = max(best, result)
# prune tree
if best >= beta:
return best, best_index
alpha = max(alpha, best)
return best, best_index
else:
best = self.MAX
best_index = 0
for index, move in enumerate(legal):
new_board = board.copy()
new_board[move] = turn
result, not_used = self.minimax_alpha(computer, True, self.next_turn(turn), new_board, depth+1, alpha, beta)
if result < best:
best_index = index
best = min(best, result)
# prune tree
if best <= alpha:
return best, best_index
beta = min(beta, best)
return best, best_index
def winner_message(self, human):
winner = game.winner(game.board)
if winner == human:
print('The human won')
elif winner == 0:
print('it was a tie')
else:
print('the computer won')
def run(self):
self.display_instruct()
computer, human = self.pieces()
turn = self.X
winner = None
while winner is None:
if turn == human:
move = self.human_move()
self.board[move] = human
else:
### change AI algorithm here
# alpha beta
# not_used, move_index = self.minimax_alpha(computer, True, computer, self.board, 0, self.MIN, self.MAX)
#mini max based of aima book
move_index = self.minimax_decision_aima(computer, computer, self.board, 0)
# mini max combined into one function
# move_index = self.minimax(computer, True, computer, self.board, 0)
# print(f'min final {move_index}')
legal = self.legal_moves(self.board)
self.board[legal[move_index]] = computer
self.display_board(self.board)
winner = self.winner(self.board)
turn = self.next_turn(turn)
# print(self.winner(self.board))
self.winner_message(human)
if __name__ == '__main__':
game = Game()
game.run()
|
#! /usr/bin/env python
contact_list = [ 'George:Hartwell:NY\n',
'Mary:Jones:NJ\n',
'Sue:Baker:PA\n',
'Hani:Ali:NJ\n',
'Gwen:Meyers:NJ\n',
'Druge:Gerrold:NY\n' ]
input = raw_input('Please enter requested state abbreviation')
input = input.upper()
result_count = 0
print 'individuals in {0}:' .format(input)
for line in contact_list:
line = line.rstrip()
els = line.split(':')
if els[-1] == input:
print "{0} {1}" .format(els[0], els[1])
result_count += 1
if result_count == 0:
print 'no results found for {0}'.format(input)
# print els[-1]
|
#! usr/bin/python
#memoizatin to make recursive fibonacci
MemoTable = {}
def MemoizedFib(n):
if n <= 2:
return 1
if n in MemoTable:
return MemoTable[n]
MemoTable[n] = MomoizedFib(n-1) + MemoizedFib(n-2)
return MemoTable[n]
res = MemoizedFib(10)
|
#! usr/bin/env python
""" This program is meant to accept 2 variables, multiply
exponentially and return a value. There should be appropriate top
and bottom borders on the return value.
Here are two runs of the program (bold is user input):
$ python homework_2.py
please enter an integer: 3
please enter another integer: 14
=======
4782969
=======
$ python homework_2.py
please enter an integer: 3
please enter another integer: 5
===
243
===
"""
print "Please enter an integer:"
basenumber = raw_input()
print "Please enter another integer:"
exponent = raw_input()
final_value = int(basenumber) ** int(exponent)
bar_len = len(str(final_value))
#final_value is an int so it needs to be changed to
#a string before it can be processed.
final_bar = bar_len * "="
print final_bar
print final_value
print final_bar
|
#!/usr/bin/env python
"""Example code note"""
def read_file(file_name):
f = open(file_name)
data = f.read()
f.close()
return data
def split_lyrics(x):
lyric_count = {}
lyrics_list = x.split(" ")
for word in lyrics_list:
if word in lyric_count:
pass
# lyric_count[word] +=1
else:
lyric_count[word] = 1
return lyric_count
if __name__ == '__main__':
lyrics = read_file("input1.txt")
lyrics_dictionary = split_lyrics(lyrics)
# print lyrics_dictionary
sorted_lyrics = sorted([(key,value) for (key,value) in lyrics_dictionary.items()])
sorted_lyrics.reverse()
print sorted_lyrics[0:100]
|
import math
import random
def next_time(average_time):
""" draw a time interval between two random events
assume Poisson distribution
"""
return -math.log(1.0 - random.random()) * average_time
def time_series(average_delta_time, N):
""" return a list of N event times from t = 0
assume Poission distribuition, average delta-time = average_time
"""
t_list = [0]
for event in range(N):
t = next_time(average_delta_time)
t_list.append(t+t_list[-1])
return t_list
if __name__=="__main__":
print "next_time.py!"
# print "test next_time(): the value below must be near 40:"
# print sum([next_time(40.0) for i in xrange(1000000)]) / 1000000
print "test time_series():"
print time_series(4,10)
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
pre_result = ListNode(0)
current = pre_result
carry = 0
while l1 is not None and l2 is not None:
sum_val = l1.val + l2.val + carry
current.next = ListNode(sum_val % 10)
carry = sum_val / 10
current = current.next
l1 = l1.next
l2 = l2.next
l = l1 or l2
while l is not None:
sum_val = l.val + carry
current.next = ListNode(sum_val % 10)
carry = sum_val / 10
current = current.next
l = l.next
if carry > 0:
current.next = ListNode(carry)
return pre_result.next
|
#!/usr/local/bin/python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def traversal(self):
num = 1
print(self.val,end='')
curr = self.next
while(curr and num < 5):
print(curr.val,end='')
curr = curr.next
num += 1
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ret = l3 = ListNode(0)
carry = 0
while (l1 or l2 or carry):
l3.next = ListNode(0)
v1 = v2 = 0
if l1:
l3.val += l1.val
l1 = l1.next
if l2:
l3.val += l2.val
l2 = l2.next
l3.val += carry
if l3.val > 9:
l3.val -= 10
carry = 1
else:
carry = 0
last = l3
l3 = l3.next
last.next = None
return ret
l1 = ListNode(2)
l1.next = ListNode(3)
l1.next.next = ListNode(9)
l2 = ListNode(6)
l2.next = ListNode(6)
l2.next = ListNode(8)
Solution().addTwoNumbers(l1,l2).traversal()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.