text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 12 11:35:32 2019
@author: Boyan Zhang
Updated by: Mingyuan
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#%%
beer_df = pd.read_csv('beer.txt')
#%%
X = np.linspace(1, len(beer_df), len(beer_df))
y = beer_df['Sales']
plt.figure()
plt.plot(X, y)
plt.title("Beer Sales")
#%%
X = np.reshape(X, (len(beer_df), 1))
#y = np.reshape(y, (len(beer_df), 1))
#y = y.values.reshape(len(beer_df),1)
#%%
lm = LinearRegression()
#%%
lm.fit(X, y)
#lm.predict(X_test)
#%%
# The coefficients
print("Coefficients: {0}".format(lm.coef_))
# .format(): transfer a float or an interger (int) to a string (for a word)
# The intercept
print("Intercept: {0}".format(lm.intercept_))
print("Total model: y = {0} + {1} X".format(lm.intercept_, lm.coef_[0]))
print("Variance score (R^2): {0:.3f}".format(lm.score(X, y)))
#{0},{1},{2},etc: the first position, the second position, the third position,etc
# {0:.nf}: the floats with n decimal points
#%%
trend = lm.predict(X)
#%%
#given the values X, trend is the y's from lm function: y = 155.40974026 + -0.21425154 X
plt.figure()
plt.plot(X, y, label = "Beer Sales")
plt.plot(trend, label="Trend")
plt.legend()
plt.title("Beer Sales Trend from Linear Regression Model")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
#%%
sse1 = np.sum( np.power(y - trend,2), axis=0)
#along the first dimension (columns), calculate (y-trend)^2
sse2 = lm._residues
#sum of squared residuals
#%%
beer_df['residuals'] = y - trend
#%%
acf_vals = [beer_df['residuals'].autocorr(i) for i in range(1,25) ]
# calculate the autocorrelation between the residuals across 1 to 15 lags
# i.e., e_t and e_{t+1}, e_{t} and e_{t+2},...,e_{t} and e_{t+15}
#%%
plt.figure()
plt.bar(np.arange(1,25), acf_vals)
plt.title("ACF of Beer Sales")
plt.xlabel("Month delay/lag")
plt.ylabel("Correlation Score")
plt.show(block=False)
#%%
plt.figure()
plt.title("Residual plot")
plt.scatter(X, trend - y)
plt.xlabel("Month")
plt.ylabel("Residuals")
plt.show(block=False)
# it looks that there is no relationship between any data points: the residuals are
# independent to each other
#%%
data = np.arange(1, 72)
forecast = lm.predict(np.reshape(np.arange(72), (72,1)))
# forecast 16 steps ahead, since predict on 72 time steps from the initial time period
# t=x=0 until the 72nd step
#%%
plt.figure()
plt.plot(X, y, label="Beer Sales")
plt.plot(trend, label="Trend")
plt.plot(forecast, linestyle='--', label="Forecast")
plt.legend()
plt.title("Beer Sales Forecast from Trend Only Linear Regression Model")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show(block=False)
#%%Find the seasonal index
T = beer_df.rolling(12, center = True).mean().rolling(2, center = True).mean().shift(-1)
S_additive = beer_df['Sales'] - T['Sales']
#%%
safe_S = np.nan_to_num(S_additive)
monthly_S = np.reshape(np.concatenate((safe_S, [0,0,0,0]), axis = 0), (5,12))
# we want to form the seasonal index for 5 years, so we add on 4 extra points
#%%
monthly_avg = np.mean(monthly_S[1:4,], axis=0)
#ignore the ones with missing values
mean_allmonth = monthly_avg.mean()
monthly_avg_normed = monthly_avg - mean_allmonth
tiled_avg = np.tile(monthly_avg_normed, 6)
#lm.fit(X[7:50], T['Sales'].iloc[7:50])
#use the data which are not missing values to re-estimate the trend
linear_trend = lm.predict(np.reshape(np.arange(1, 72), (72,1)))
linear_seasonal_forecast = linear_trend + tiled_avg
plt.figure()
plt.plot(X, y, label="Original Data")
plt.plot(linear_trend, label="Linear Model trend")
plt.plot(linear_seasonal_forecast, label="Linear+Seasonal Forecast")
plt.title("Beer Sales Forecast from Trend+Seasonal Linear Regression Model")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.legend()
plt.show(block=False)
#%%
# we start from January
seasons = []
for i in range(y.size):
if i % 12 == 0:
seasons = np.append(seasons, 'Jan')
if i % 12 == 1:
seasons = np.append(seasons, 'Feb')
if i % 12 == 2:
seasons = np.append(seasons, 'Mar')
if i % 12 == 3:
seasons = np.append(seasons, 'Apr')
if i % 12 == 4:
seasons = np.append(seasons, 'May')
if i % 12 == 5:
seasons = np.append(seasons, 'Jun')
if i % 12 == 6:
seasons = np.append(seasons, 'Jul')
if i % 12 == 7:
seasons = np.append(seasons, 'Aug')
if i % 12 == 8:
seasons = np.append(seasons, 'Sep')
if i % 12 == 9:
seasons = np.append(seasons, 'Oct')
if i % 12 == 10:
seasons = np.append(seasons, 'Nov')
if i % 12 == 11:
seasons = np.append(seasons, 'Dec')
#%%
#dummies1 = pd.get_dummies(seasons)
dummies = pd.get_dummies(seasons, drop_first=True)
#Whether to get k-1 dummies out of k categorical levels by removing the first level
# In this case, we treat
# b0 + b1 * t as April
# b0 + b1 * t + b2 * x1 as August
# b0 + b1 * t + b3 * x2 as Dec, etc...
# please refer to the dummies column name
#%%
#Please note dummier is a pandas DataFrame, we shall take values out by
dummies = dummies.values
#%%
# make sure the size of X and dummies match
# If you are using numpy version below than 1.10, you need to uncomment the following statement
# X = X[:, np.newaxis]
#[:,np.newaxis]: make it as column vector by inserting an axis along second dimension
# Now we add these dummy features into feature, stacking along the column
Xnew = np.hstack((X,dummies))
#%%
# Create linear regression object (model)
regr = LinearRegression()
# Train the model using the training sets
regr.fit(Xnew,y)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The intercept
print('Intercept: \n', regr.intercept_)
#%%
Ypred = regr.predict(Xnew)
plt.figure()
plt.plot(y, label='Observed')
plt.plot(Ypred, '-r', label='Predicted')
plt.legend()
#plt.close("all") #close all previous figures
#%% Remove Jan
dummies1 = pd.get_dummies(seasons)
#%%
dummies1 = dummies1.drop(['Jan'], axis=1)
#%%
#dummies1 = dummies1.values
Xnew1 = np.hstack((X,dummies1))
regr1 = LinearRegression()
regr1.fit(Xnew1,y)
Ypred1 = regr.predict(Xnew1)
# The coefficients
print('Coefficients: \n', regr1.coef_)
# The intercept
print('Intercept: \n', regr1.intercept_)
plt.plot(Ypred1, '-g', label='Predicted new')
plt.legend()
#%% Do not remove anything
dummies2 = pd.get_dummies(seasons)
#dummies1 = dummies1.drop(['Jan'], axis=1)
dummies2 = dummies2.values
Xnew2 = np.hstack((X,dummies2))
#%%
regr2 = LinearRegression()
regr2.fit(Xnew2,y)
Ypred2 = regr2.predict(Xnew2)
#%%
# The coefficients
print('Coefficients: \n', regr2.coef_)
# The intercept
print('Intercept: \n', regr2.intercept_)
plt.plot(Ypred2, '-b', label='Predicted new 2')
plt.legend()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 11:38:41 2018
@author: Professor Junbin Gao
adopted from
https://machinelearningmastery.com/develop-first-xgboost-model-python-scikit-learn/
xgboost Installation Guide
https://xgboost.readthedocs.io/en/latest/build.html
"""
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score
# load data
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=",")
# split data into X and y
X = dataset[:,0:8]
Y = dataset[:,8]
# split data into train and test sets
seed = 7
test_size = 0.33
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
# fit model no training data
# Actually we follow the exactly same way as we do modelling with sklearn-kit
model = XGBClassifier()
model.fit(X_train, y_train)
print(model)
# make predictions for test data
y_pred = model.predict(X_test)
predictions = [round(value) for value in y_pred]
# evaluate predictions
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
F1_score = f1_score(y_test, predictions)
print("Accuracy: %.2f%%" % (F1_score * 100.0))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 29 18:03:45 2017
@author: steve
"""
name_list = ["david", "jess", "mark", "laura"]
for name in name_list:
if name != "mark":
print(name) |
# Testing keys
l = ['key1', 'key2', 'key3']
d = {}
d['key1'] = '1'
d['key2'] = '2'
d['key3'] = '3'
if all (k in d for k in l):
print('All there')
|
from main import Piece, Board
from random import randint
# ======================== Class Player =======================================
class Player:
# student do not allow to change two first functions
def __init__(self, str_name):
self.str = str_name
def __str__(self):
return self.str
# Student MUST implement this function
# The return value should be a move that is denoted by:
# piece: selected piece
# (row, col): new position of selected piece
def next_move(self, state):
currentState = state
if self.str == "black":
# find next moves
nextMoves = possibleNextMoves(state, "black")
if nextMoves == list():
return False
bestMove = None
playerMaxScore = -1000000
opponentMinScore = 1000000
for move in nextMoves:
# print("DEBUG: " + str(move[0][0]) + " to " + str(move[0][1]))
if playerMaxScore > move[1]:
continue
if playerMaxScore == move[1]:
r = randint(0, 100)
if r > 70:
# print("HAHA SKIP " + str(move[0][0]) + str(move[0][1]))
bestMove = move
playerMaxScore = move[1]
continue
else:
pass
nextState = doMove((move[0][0], move[0][1]), currentState)
opponentMoves = possibleNextMoves(nextState, "red")
# find opponent best move
for oppMove in opponentMoves:
if opponentMinScore <= oppMove[1]:
continue
elif opponentMinScore > oppMove[1]:
opponentMinScore = oppMove[1]
bestMove = move
playerMaxScore = move[1]
if self.str == "red":
# find next moves
nextMoves = possibleNextMoves(state, "red")
if nextMoves == list():
return None
bestMove = None
playerMaxScore = -1000000
opponentMinScore = 1000000
for move in nextMoves:
if playerMaxScore > move[1]:
continue
if playerMaxScore == move[1]:
r = randint(0, 100)
if r > 70:
# print("HAHA SKIP " + str(move[0][0]) + str(move[0][1]))
bestMove = move
playerMaxScore = move[1]
continue
else:
pass
nextState = doMove((move[0][0], move[0][1]), currentState)
opponentMoves = possibleNextMoves(nextState, "black")
# find opponent best move
for oppMove in opponentMoves:
if opponentMinScore <= oppMove[1]:
continue
elif opponentMinScore > oppMove[1]:
opponentMinScore = oppMove[1]
bestMove = move
playerMaxScore = move[1]
return bestMove[0][0], bestMove[0][1]
# CONSTANTS:
Voi = 'Voi'
SuTu = 'SuTu'
Ho = 'Ho'
Bao = 'Bao'
Soi = 'Soi'
Cho = 'Cho'
Meo = 'Meo'
Chuot = 'Chuot'
blackWinPosition = (1, 4)
redWinPosition = (9, 4)
trapPosition = [(1, 3), (1, 5), (2, 4), (9, 3), (9, 5), (8, 4)]
waterPosition = [(4, 2), (4, 3), (4, 5), (4, 6), (5, 2), (5, 3), (5, 5), (5, 6), (6, 2), (6, 3), (6, 5), (6, 6)]
pieceScore = {
Voi: 8,
SuTu: 7,
Ho: 6,
Bao: 5,
Soi: 4,
Cho: 3,
Meo: 2,
Chuot: 1,
}
# return a list of possible next state
def possibleNextMoves(state, side):
list_pieces = {}
if side == "black":
list_pieces = {
"player": state.list_black,
"opponent": state.list_red
}
elif side == "red":
list_pieces = {
"player": state.list_red,
"opponent": state.list_black
}
currentScore = evalute(state, side)
nextMoves = []
for piece in list_pieces.get('player'):
pieceType = piece.type
# print(pieceType + ":")
# move up
nextScore = currentScore
nextPos = (piece.position[0] + 1, piece.position[1])
# check special moves
if nextPos in waterPosition:
if pieceType == SuTu or pieceType == Ho:
# jump up 4
nextPos = (piece.position[0] + 4, piece.position[1])
elif pieceType == Bao:
# cant jump that far
continue
elif pieceType == Meo:
# Meo cant swim
continue
captureScore = checkNextPos(nextPos, list_pieces, piece, pieceType)
if captureScore is not None:
# can go there
if nextPos in trapPosition:
nextScore -= pieceScore.get(pieceType)
elif nextPos in waterPosition:
nextScore -= pieceScore.get(pieceType) / 2
else:
# nextScore not change
pass
nextScore += captureScore
# print(str(piece) + " to (" + str(nextPos[0]) + "," + str(nextPos[1])+ "), score: " + str(nextScore))
nextMoves.append(((piece, nextPos), nextScore))
# move down
nextScore = currentScore
nextPos = (piece.position[0] - 1, piece.position[1])
# check special moves
if nextPos in waterPosition:
if pieceType == SuTu or pieceType == Ho:
# jump down 4
nextPos = (piece.position[0] - 4, piece.position[1])
elif pieceType == Bao:
# cant jump that far
continue
elif pieceType == Meo:
# Meo cant swim
continue
captureScore = checkNextPos(nextPos, list_pieces, piece, pieceType)
if captureScore is not None:
# can go there
if nextPos in trapPosition:
nextScore -= pieceScore.get(pieceType)
elif nextPos in waterPosition:
nextScore -= pieceScore.get(pieceType) / 2
else:
# nextScore not change
pass
nextScore += captureScore
# print(str(piece) + " to (" + str(nextPos[0]) + "," + str(nextPos[1])+ "), score: " + str(nextScore))
nextMoves.append(((piece, nextPos), nextScore))
# move left
nextScore = currentScore
nextPos = (piece.position[0], piece.position[1] - 1)
# check special moves
if nextPos in waterPosition:
if pieceType == SuTu or pieceType == Ho:
# jump left 3
nextPos = (piece.position[0], piece.position[1] - 3)
elif pieceType == Bao:
# jump left 3
nextPos = (piece.position[0], piece.position[1] - 3)
elif pieceType == Meo:
# Meo cant swim
continue
captureScore = checkNextPos(nextPos, list_pieces, piece, pieceType)
if captureScore is not None:
# can go there
if nextPos in trapPosition:
nextScore -= pieceScore.get(pieceType)
elif nextPos in waterPosition:
nextScore -= pieceScore.get(pieceType) / 2
else:
# nextScore not change
pass
nextScore += captureScore
# print(str(piece) + " to (" + str(nextPos[0]) + "," + str(nextPos[1])+ "), score: " + str(nextScore))
nextMoves.append(((piece, nextPos), nextScore))
# move right
nextScore = currentScore
nextPos = (piece.position[0], piece.position[1] + 1)
# check special moves
if nextPos in waterPosition:
if pieceType == SuTu or pieceType == Ho:
# jump left 3
nextPos = (piece.position[0], piece.position[1] + 3)
elif pieceType == Bao:
# jump left 3
nextPos = (piece.position[0], piece.position[1] + 3)
elif pieceType == Meo:
# Meo cant swim
continue
captureScore = checkNextPos(nextPos, list_pieces, piece, pieceType)
if captureScore is not None:
# can go there
if nextPos in trapPosition:
nextScore -= pieceScore.get(pieceType)
elif nextPos in waterPosition:
nextScore -= pieceScore.get(pieceType) / 2
else:
# nextScore not change
pass
nextScore += captureScore
# print(str(piece) + " to (" + str(nextPos[0]) + "," + str(nextPos[1])+ "), score: " + str(nextScore))
nextMoves.append(((piece, nextPos), nextScore))
return nextMoves
def checkNextPos(nextPos, list_pieces, piece, pieceType):
if not inRange(nextPos):
# print('not in range: ' + str(nextPos))
return None
# check if nextPos have other player's piece
invalidMove = False
for otherPiece in list_pieces.get('player'):
if nextPos == otherPiece.position:
# invalid moves
invalidMove = True
return None
# check if capture any opponent's piece
captureScore = 0
for otherPiece in list_pieces.get('opponent'):
if nextPos == otherPiece.position:
# check if capturable
if piece.position in waterPosition: # check if piece in water
if otherPiece.position in waterPosition and pieceScore.get(pieceType) >= pieceScore.get(otherPiece.type):# check if other piece in water, still can capture
captureScore = pieceScore.get(otherPiece.type)
break
return None
elif otherPiece.position in waterPosition:# check if other piece in water
return None
elif otherPiece.position in trapPosition: # check if other piece in trap
captureScore = pieceScore.get(otherPiece.type)
break
elif pieceType == Chuot and otherPiece.type == Voi: # Chuot > Voi
captureScore = pieceScore.get(otherPiece.type)
break
elif pieceScore.get(pieceType) >= pieceScore.get(otherPiece.type):
captureScore = pieceScore.get(otherPiece.type)
break
else:
break
return captureScore
# Evaluate a state
def evalute(state, side):
blackScore = 0
redScore = 0
for piece in state.list_black:
pieceType = piece.type
if piece.position in trapPosition:
blackScore += 0
elif piece.position in waterPosition:
blackScore += pieceScore.get(pieceType) / 2
else:
blackScore += pieceScore.get(pieceType)
for piece in state.list_red:
pieceType = piece.type
if piece.position in trapPosition:
redScore += 0
elif piece.position in waterPosition:
redScore += pieceScore.get(pieceType) / 2
else:
redScore += pieceScore.get(pieceType)
if side == "black":
return blackScore - redScore / 2
else:
return redScore - blackScore / 2
# do the move
def doMove(move, board):
# blackList = board.list_black
# redList = board.list_red
blackList = []
redList = []
for piece in board.list_black:
blackList.append(Piece(piece.type, piece.position))
for piece in board.list_red:
redList.append(Piece(piece.type, piece.position))
piece, nextPos = move
# Find piece in board
thePiece = None
for x in blackList:
if x.type == piece.type and x.position == piece.position:
thePiece = x
if thePiece is None:
for x in redList:
if x.type == piece.type and x.position == piece.position:
thePiece = x
# Check if any piece at next pos
theOtherPiece = None
for x in blackList:
if x.position == nextPos:
theOtherPiece = x
blackList.remove(theOtherPiece);
if theOtherPiece is None:
for x in redList:
if x.position == nextPos:
theOtherPiece = x
redList.remove(theOtherPiece)
# Move the Piece to next Pos
thePiece.position = nextPos
newState = Board(blackList, redList)
return newState
# check in range
def inRange(pos):
y = pos[0]
x = pos[1]
if x < 1 or x > 7 or y < 1 or y > 9:
return False
else:
return True
# Check if win
def isGoal(state, side):
if side == "black":
for piece in state.list_black:
if piece.position == blackWinPosition:
# Game over, black won
pass
if side == "red":
for piece in state.list_red:
if piece.position == redWinPosition:
# Game over, red won
pass |
def currency_converter(quantity: float, source_curr: str, target_curr: str):
""" Calculate value after converting money from one currency to
another
Args:
quantity (float): amount of money in the original currency
source_curr (str): original currency
target_curr (str): currency after exchange
Returns:
float:
"""
conversions = {
"USD": 1,
"EUR": .9,
"CAD": 1.4,
"GBP": .8,
"CHF": .95,
"NZD": 1.66,
"AUD": 1.62,
"JPY": 107.92
}
print(conversions)
print(conversions.keys())
print(conversions.values())
target_amount = quantity * conversions["USD"] / conversions[source_curr] \
* conversions[target_curr]
return target_amount
print(f"\nForeign Exchange Rate (from USD to CAD) is: ",currency_converter(1,"USD","CAD"))
r"""
--- Sample Run ---
{'USD': 1, 'EUR': 0.9, 'CAD': 1.4, 'GBP': 0.8, 'CHF': 0.95, 'NZD': 1.66, 'AUD': 1.62, 'JPY': 107.92}
dict_keys(['USD', 'EUR', 'CAD', 'GBP', 'CHF', 'NZD', 'AUD', 'JPY'])
dict_values([1, 0.9, 1.4, 0.8, 0.95, 1.66, 1.62, 107.92])
Foreign Exchange Rate (from USD to CAD) is: 1.4
""" |
import re
class docCrawler():
"""This object will go through a single document and perform the following
operations:
1. It will find any newly declared functions and add them to a list
2. It will find where in the document a function is called, an object
is created, or the method for an object is called. These will be
stored in a dict.
"""
def __init__(self, p):
self.p = p
self.function_dict = []
self.func_lines = ''
def check_for_funct(self, line):
"""Input:
line: string - a single line of the document.
Output:
If a function declaration begins on the given line AND the function
declaration ends on the same line, this method will return True.
If a function declaration begins but does not end on the given line,
the current line is appended to self.func_lines, and the method
returns False.
If no function is delcared on the given line, this method returns
True.
This method will check to see if a function has been declared in the
given line. If it has been, it will add the name of the function and the
arguments for that function to self.function_dict:
key value
----------------------------------------
name of function arguments for the
function (as a list)
It determines whether a function declaration begins on the current line
by looking for 1 or mor tabs followed by 'def '. It will then check to
see whether the function ends on the current line by looking for the
string pattern '):'.
"""
def_match = re.match('\t*def ', line)
arg_match = re.search('\(', line)
end_match = re.search('\):', line)
if def_match: # Checks if a function definition begins on this line
if end_match: # Checks if the function def also ends on this line
a, name_start = def_match.span()
name_end, arg_start = arg_match.span()
arg_end, c = end_match.span()
# We extract the function name and the arguments from the line
func_name = line[name_start:name_end]
temp = line[arg_start:arg_end].split(',')
func_args = [i.strip() for i in temp] # turn args into neat list
if func_name not in self.function_dict:
self.function_dict[func_name] = func_args
else: # this probably won't happen, but just in case...
raise RuntimeError('Multiple functions with the same name \
encountered by docCrawler within \
single document.')
self.func_lines = ''
return True # I don't need these return True/False statements,
else: # but I'll leave them for now.
self.func_lines += line
return False
return True
def find_functions(self):
"""This method will open the file path given by self.p, which gives the
location of a python document. It then goes through the file line by
line and feeds each line to the check_for_funct() method. This will
build a dictionary containing the name of each function defined within
the file as keys, and the arguments for that function - in the form
of a list - as values.
"""
with open(self.p, 'r') as f:
for line in f:
line = line + self.func_lines
if check_for_funct(line):
continue
class dirCrawler():
"""This object will go through an entire directory
"""
pass
|
# -*- coding: utf-8 -*-
import numpy as np
def ls(x, y, rank):
"""
use least square method to calculate the parameter omega in the polynomial function
:param x: the x coordinate of the training sample, which is a row vector [x1, x2, ..., xn]
:param y: the y coordinate of the training sample, which is a row vector [y1, y2, ..., yn]
:param rank: he rank of the polynomial function
:return: omega we get using least square method
"""
# generate a transpose of vandermonde matrix
tran_van_matrix = np.tile(x, (rank + 1, 1))
for r in range(rank + 1):
tran_van_matrix[r] = tran_van_matrix[r] ** r
reverse = np.linalg.inv(tran_van_matrix.dot(tran_van_matrix.transpose()))
ls_omega = y.dot(tran_van_matrix.transpose()).dot(reverse)
return ls_omega
|
"""
The following code follows the treatment in "Theory of X-Ray Diffraction in Crystals" by William H. Zachariasen
"""
import numpy as np
from scipy import constants
class Crystal(object):
"""
This class stores crystal data read from a data file (e.g. Si.txt, Ge.txt, etc.)
"""
# TODO: asymmetry angle not needed here, used in Diffraction
def __init__(self, crystal_type, asymmetry_angle):
"""
Initializer.
:param crystal_type: <class 'str'> string specifying which crystal is being used
:param asymmetry_angle: <class 'float'> angle in degrees
"""
self._crystal_type = crystal_type
self._asymmetry_angle = asymmetry_angle * np.pi / 180 # converting into radians
"""
The files are structured in the following way (each row has 11 elements):
(0, 0)-(0, 4) -> 5x{a_i} | (0, 5) -> c | (0, 6)-(0, 10) -> 5x{b_i} goal:f0 calculation
(1, 0)-(1, 5) -> a b c alpha beta gamma | (1, 6)-(1, 10) -> 5x0 goal:unit cell volume calculation
(2-9, 0-10) -> atomic_number fraction x y z 6x0 goal:structure factor calculation
"""
self._data_array = np.loadtxt("{}.txt".format(self._crystal_type), dtype='float')
self._a = [] # parameters a_i (x5)
self._b = [] # parameters b_i (x5)
self._unit_cell = [] # unit cell sides (x3) and angles (x3)
self._atom_coordinates = np.zeros((8, 3)) # each row holds the x, y, z coordinates of one atom in the unit cell
# there are 8 atoms in the silicon unit cell
for i in np.arange(self._data_array.shape[0]):
for j in np.arange(self._data_array.shape[1]):
if i == 0:
if j < 5:
self._a.append(self._data_array[(i, j)])
elif 5 < j < self._data_array.shape[1]:
self._b.append(self._data_array[(i, j)])
elif j == 5:
self._c = self._data_array[(i, j)]
elif i == 1 and j < 6:
self._unit_cell.append(self._data_array[(i, j)])
else:
if j in [2, 3, 4]:
self._atom_coordinates[(i - 2, j - 2)] = self._data_array[(i, j)]
def unit_cell_volume(self):
"""
calculates the unit cell volume.
Conventions: alpha is the angle between b and c, beta between a and c, gamma between a and b,
with a, b being on the horizontal plane.
Volume = a * b * c * sin(alpha) * sin(beta) * sin(gamma)
:return: unit cell volume in Angstroms^3
"""
a = self._unit_cell[0]
b = self._unit_cell[1]
c = self._unit_cell[2]
alpha = self._unit_cell[3] * np.pi / 180 # converting into radians
beta = self._unit_cell[4] * np.pi / 180 # converting into radians
gamma = self._unit_cell[5] * np.pi / 180 # converting into radians
return a * b * c * np.sin(alpha) * np.sin(beta) * np.sin(gamma) # Angstroms ^ 3
class Diffraction(Crystal):
"""
This class defines a diffraction geometry for the crystal and the incoming x-ray beam.
In particular, this class is initialized by specifying the wavelength of the beam and then this is used to calculate
the Bragg angle, the b parameter and the structure factors.
"""
# todo: not here: global variables?? use "import scipy.constants as constants" and use "constants.c" etc
e = constants.elementary_charge # charge of the proton
c = constants.speed_of_light # speed of light in vacuum
m = constants.electron_mass # mass of the electron
h = constants.Planck # Planck's constant
def __init__(self, crystal_type, asymmetry_angle, miller_h, miller_k, miller_l, wavelength, polarization):
"""
:param miller_h: < class 'int'> Miller index H
:param miller_k: < class 'int'> Miller index K
:param miller_l: < class 'int'> Miller index L
:param wavelength: < class 'float'> wavelength of the x-ray beam in keV
:param polarization: < class 'bool'> True = normal polarization (s), False = parallel polarization (p)
"""
super(Diffraction, self).__init__(crystal_type, asymmetry_angle)
self._wavelength = self.h * self.c * 1e+7 / (self.e * wavelength) # conversion keV -> Angstrom
self._polarization = polarization
self._miller_h = miller_h
self._miller_k = miller_k
self._miller_l = miller_l
def d_spacing(self):
"""
calculates the spacing between the Miller planes in the special case of a cubic unit cell
:return: d spacing in Angstroms
"""
return self._unit_cell[0] / np.sqrt(self._miller_h ** 2 + self._miller_k ** 2 + self._miller_l ** 2)
def bragg_angle(self):
"""
calculates the Bragg angle using Bragg's law: lambda = 2 * d_spacing * sin(theta_Bragg) (Zachariasen [3.5])
:return: Bragg angle in radians
"""
d_spacing = self.d_spacing() # in Angstroms
return np.arcsin(0.5 * self._wavelength / d_spacing)
def parameter_f_0(self):
"""
calculates f0 following the 5-gaussian interpolation by D. Waasmaier & A. Kirfel
:return: atomic scattering power, f0 @ specified wavelength
"""
f = self._c
s = np.sin(self.bragg_angle()) / self._wavelength # in Angstrom ^ -1
for i in np.arange(5):
f += self._a[i] * np.exp(-self._b[i] * s ** 2)
return f
def parameter_b(self):
"""
calculates b = gamma_0 / gamma_h (Zachariasen [3.115])
:return: b
"""
gamma_h = - np.sin(self.bragg_angle())
gamma_0 = np.sin(self.bragg_angle() + self._asymmetry_angle)
return gamma_0 / gamma_h
def parameter_k(self):
"""
k = 1 for normal polarization; k = |cos(2*theta_Bragg)| for parallel polarization (Zachariasen [3.141])
:return: k
"""
if self._polarization:
return 1
if not self._polarization:
return np.absolute(np.cos(2*self.bragg_angle()))
def parameter_psi_0(self):
"""
psi_0 = num_atoms_in_unit_cell * f_0 (Zachariasen [3.95])
:return: psi_0
"""
f_0 = self.parameter_f_0()
v = self.unit_cell_volume() * 1e-30 # Angstrom ^3 -> m ^3
wavelength = self._wavelength * 1e-10 # Angstrom -> metre
e_radius = 2.8179403267e-15 # cgs units
psi_0 = - e_radius * wavelength ** 2 / (v * np.pi) * f_0
return (self._data_array.shape[0] - 2) * psi_0 # this only holds for crystals with atoms all of the same kind
def parameter_f_h(self):
"""
F_H = f_0 * SUM(i) { exp[ (i*2*pi) * (h*a_i + k*b_i + l*c_i) ] }
where a_i, b_i, c_i are the coordinates of the i-th atom in the unit cell (Zachariasen [3.52])
and h, k, l are the Miller indices.
:return: F_H
"""
f_h = 0 + 0j
for i in np.arange(self._data_array.shape[0] - 2):
j = 0
f_h += np.exp(1j * 2 * np.pi * (self._miller_h * self._atom_coordinates[(i, j)]
+ self._miller_k * self._atom_coordinates[(i, j + 1)]
+ self._miller_l * self._atom_coordinates[(i, j + 2)]))
return f_h * self.parameter_f_0()
def parameter_psi_h(self):
"""
calculates psi_H starting from F_H, the wavelength and the unit cell volume (Zachariasen [3.95])
:return: psi_H
"""
v = self.unit_cell_volume() * 1e-30 # Angstrom ^3 -> m ^3
wavelength = self._wavelength * 1e-10 # Angstrom -> metre
f_h = self.parameter_f_h()
e_radius = 2.8179403267e-15 # cgs units
return - e_radius * (wavelength ** 2 / (v * np.pi)) * f_h
def darwin_profile_theta(self,theta_diff):
num = theta_diff.size
theta_bragg = self.bragg_angle()
alpha = 2 * theta_diff * 1e-6 * np.sin(2 * theta_bragg) # Zachariasen [3.116]
b = self.parameter_b()
k = self.parameter_k()
psi_0 = np.ones(num) * self.parameter_psi_0()
psi_h = self.parameter_psi_h()
y = ((0.5 * (1-b) * psi_0) + (0.5 * b * alpha)) / (np.sqrt(np.absolute(b)) * k * np.absolute(psi_h))
reflectivity = np.ones(num)
for i in range(num): # Zachariasen [3.192b]
if y[i] < -1:
reflectivity[i] = (-y[i] - np.sqrt(y[i] ** 2 - 1)) ** 2
elif y[i] > 1:
reflectivity[i] = (y[i] - np.sqrt(y[i] ** 2 - 1)) ** 2
else:
y[i] = 1
return reflectivity
def darwin_profile_y(self,y_array):
pass
|
"""My convolution implementations."""
import math
import numpy as np
from typing import List
INITIAL_VALUE = 0.0
def pad_tensor(x: List[List[List[List[float]]]], n: int, c_i: int, h_i: int, w_i: int,
pad: int) -> None:
"""Pad elements to the tensor.
Args:
x (List[List[List[List[float]]]]):
n (int):
c_i (int):
h_i (int):
w_i (int):
pad (int):
Returns:
None
"""
for nn in range(n):
for cc_i in range(c_i):
for pp in range(pad):
x[nn][cc_i].insert(pp,
[INITIAL_VALUE for _i in range(w_i + 2 * pad)])
x[nn][cc_i].insert(h_i + pp + 1,
[INITIAL_VALUE for _i in range(w_i + 2 * pad)])
for hh_i in range(1, h_i + pad):
for pp in range(pad):
x[nn][cc_i][hh_i].insert(pp, INITIAL_VALUE)
x[nn][cc_i][hh_i].insert(w_i + pp + 1, INITIAL_VALUE)
def im2col(x: List[List[List[List[float]]]], h_k: int, w_k: int, pad: int = 0, stride: int = 1) \
-> List[List[List[List[List[List[float]]]]]]:
"""Convert the tensor to a vector.
Args:
x (List[List[List[List[float]]]]):
h_k (int):
w_k (int):
pad (int):
stride (int):
Returns:
List[List[List[List[List[List[float]]]]]]
"""
n = len(x)
c_i = len(x[0])
h_i = len(x[0][0])
w_i = len(x[0][0][0])
h_o = math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1
w_o = math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1
if pad > 0:
pad_tensor(x, n, c_i, h_i, w_i, pad)
result = [[[[[[INITIAL_VALUE for _i in range(w_o)]
for _j in range(h_o)]
for _k in range(h_k)]
for _l in range(w_k)]
for _m in range(c_i)]
for _n in range(n)]
for nn in range(n):
for cc_i in range(c_i):
for hh_o in range(h_o):
for ww_o in range(w_o):
for hh_k in range(h_k):
for ww_k in range(w_k):
result[nn][cc_i][hh_k][ww_k][hh_o][ww_o] = \
x[nn][cc_i][hh_o * stride + hh_k][ww_o * stride + ww_k]
return result
def convolution_with_numpy(x: np.ndarray, W: np.ndarray, stride: int = 1, pad: int = 0) \
-> np.ndarray:
r"""Convolution implementation using Numpy.
Args:
x (numpy.ndarray): Input image whose shape consists of ``n``, ``c_i``, ``h``, and ``w``,
where ``n`` is the size of batch, ``c_i`` is the size of input channel,
``h`` is the size of height of the image,
and ``w`` is the size of width of the image.
W (numpy.ndarray): Kernel whose shape consists of ``c_o``, ``c_i``, ``h``, and ``w``,
where ``c_o`` is the size of output channel, ``c_i`` is the size of
input channel, ``h`` is the size of height of the kernel,
and ``w`` is the size of width of the kernel.
stride (int): stride size. The default value is ``1``.
pad (int): padding size. The default value is ``0``.
Returns:
numpy.nadarray: ndarray object whose shape consists of ``n``, ``c_o``,
``h_o``, ``w_o``, where ``h_o`` is
the result of ``math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1``,
and `w_o` is the result of ``math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1``.
Raises:
AssertionError: If ``h_k > h_i or w_k > w_i`` or
``stride > (h_i - h_k + 2 * pad + 1)`` or ``stride > (w_i - w_k + 2 * pad + 1)``
"""
n, c_i, h_i, w_i = x.shape
c_o, c_i, h_k, w_k = W.shape
if h_k > h_i or w_k > w_i:
raise AssertionError('The height and width of x must be smaller than W')
if stride > (h_i - h_k + 2 * pad + 1) or stride > (w_i - w_k + 2 * pad + 1):
raise AssertionError('The value of stride must be smaller than output tensor size')
h_o = math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1
w_o = math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1
if pad > 0:
new_x = np.zeros((n, c_i, h_i + 2 * pad, w_i + 2 * pad), dtype=np.float32)
for nn in range(n):
for cc_i in range(c_i):
new_x[nn][cc_i] = np.pad(x[nn][cc_i], pad, 'constant')
x = new_x
result = np.zeros((n, c_o, h_o, w_o), dtype=np.float32)
for nn in range(n):
for cc_i in range(c_i):
for cc_o in range(c_o):
for h in range(h_o):
for w in range(w_o):
for k_h in range(h_k):
for k_w in range(w_k):
result[nn, cc_o, h, w] += \
x[nn][cc_i][h * stride + k_h][w * stride + k_w] * \
W[cc_o][cc_i][k_h][k_w]
return result
def convolution_with_standard_library(x: List[List[List[List[float]]]],
W: List[List[List[List[float]]]], stride: int = 1,
pad: int = 0) \
-> List[List[List[List[float]]]]:
r"""Convolution implementation using only Python standard library.
Args:
x (List[List[List[List[float]]]]): Input image whose shape consists of ``n``, ``c_i``,
``h``, and ``w``,
where ``n`` is the size of batch, ``c_i`` is the size of input channel,
``h`` is the size of height of the image,
and ``w`` is the size of width of the image.
W (List[List[List[List[float]]]]): Kernel whose shape consists of ``c_o``, ``c_i``, ``h``,
and ``w``, where ``c_o`` is the size of output channel, ``c_i`` is the size of
input channel, ``h`` is the size of height of the kernel,
and ``w`` is the size of width of the kernel.
stride (int): stride size. The default value is ``1``.
pad (int): padding size. The default value is ``0``.
Returns:
List[List[List[List[float]]]]: list object whose shape consists of ``n``, ``c_o``,
``h_o``, ``w_o``, where ``h_o`` is
the result of ``math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1``,
and `w_o` is the result of ``math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1``.
Raises:
AssertionError: If ``h_k > h_i or w_k > w_i`` or
``stride > (h_i - h_k + 2 * pad + 1)`` or ``stride > (w_i - w_k + 2 * pad + 1)``
"""
n = len(x)
c_i = len(x[0])
h_i = len(x[0][0])
w_i = len(x[0][0][0])
c_o = len(W)
c_i = len(W[0])
h_k = len(W[0][0])
w_k = len(W[0][0][0])
if h_k > h_i or w_k > w_i:
raise AssertionError('The height and width of x must be smaller than W')
if stride > (h_i - h_k + 2 * pad + 1) or stride > (w_i - w_k + 2 * pad + 1):
raise AssertionError('The value of stride must be smaller than output tensor size')
h_o = math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1
w_o = math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1
if pad > 0:
pad_tensor(x, n, c_i, h_i, w_i, pad)
result = [[[[INITIAL_VALUE for _i in range(w_o)]
for _j in range(h_o)]
for _k in range(c_o)]
for _h in range(n)]
for nn in range(n):
for cc_i in range(c_i):
for cc_o in range(c_o):
for h in range(h_o):
for w in range(w_o):
for k_h in range(h_k):
for k_w in range(w_k):
result[nn][cc_o][h][w] += \
x[nn][cc_i][h * stride + k_h][w * stride + k_w] * \
W[cc_o][cc_i][k_h][k_w]
return result
def convolution_with_im2col(x: List[List[List[List[float]]]], W: List[List[List[List[float]]]],
stride: int = 1, pad: int = 0) \
-> List[List[List[List[float]]]]:
r"""Convolution implementation with im2col.
Args:
x (List[List[List[List[float]]]]): Input image whose shape consists of ``n``, ``c_i``,
``h``, and ``w``,
where ``n`` is the size of batch, ``c_i`` is the size of input channel,
``h`` is the size of height of the image,
and ``w`` is the size of width of the image.
W (List[List[List[List[float]]]]): Kernel whose shape consists of ``c_o``, ``c_i``, ``h``,
and ``w``, where ``c_o`` is the size of output channel, ``c_i`` is the size of
input channel, ``h`` is the size of height of the kernel, and ``w`` is the size of width
of the kernel.
stride (int): stride size. The default value is ``1``.
pad (int): padding size. The default value is ``0``.
Returns:
list: list object whose shape consists of ``n``, ``c_o``,
``h_o``, ``w_o``, where ``h_o`` is
the result of ``math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1``,
and `w_o` is the result of ``math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1``.
Raises:
AssertionError: If ``h_k > h_i or w_k > w_i`` or ``stride > (h_i - h_k + 2 * pad + 1)``
or ``stride > (w_i - w_k + 2 * pad + 1)``
"""
n = len(x)
c_i = len(x[0])
h_i = len(x[0][0])
w_i = len(x[0][0][0])
c_o = len(W)
c_i = len(W[0])
h_k = len(W[0][0])
w_k = len(W[0][0][0])
if h_k > h_i or w_k > w_i:
raise AssertionError('The height and width of x must be smaller than W')
if stride > (h_i - h_k + 2 * pad + 1) or stride > (w_i - w_k + 2 * pad + 1):
raise AssertionError('The value of stride must be smaller than output tensor size')
h_o = math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1
w_o = math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1
result = [[[[INITIAL_VALUE for _i in range(w_o)]
for _j in range(h_o)]
for _k in range(c_o)]
for _h in range(n)]
col = im2col(x=x, h_k=h_k, w_k=w_k, pad=pad, stride=stride)
for nn in range(n):
for cc_i in range(c_i):
for cc_o in range(c_o):
for hh_k in range(h_k):
for ww_k in range(w_k):
for hh_o in range(h_o):
for ww_o in range(w_o):
result[nn][cc_o][hh_o][ww_o] += \
col[nn][cc_i][hh_k][ww_k][hh_o][ww_o] * \
W[cc_o][cc_i][hh_k][ww_k]
return result
def convolution_with_im2col_and_gemm(x: List[List[List[List[float]]]],
W: List[List[List[List[float]]]],
stride: int = 1, pad: int = 0) \
-> List[List[List[List[float]]]]:
r"""Convolution implementation with im2col.
Args:
x (List[List[List[List[float]]]]): Input image whose shape consists of ``n``, ``c_i``,
``h``, and ``w``,
where ``n`` is the size of batch, ``c_i`` is the size of input channel,
``h`` is the size of height of the image,
and ``w`` is the size of width of the image.
W (List[List[List[List[float]]]]): Kernel whose shape consists of ``c_o``, ``c_i``, ``h``,
and ``w``, where ``c_o`` is the size of output channel, ``c_i`` is the size of
input channel, ``h`` is the size of height of the kernel, and ``w`` is the size of width
of the kernel.
stride (int): stride size. The default value is ``1``.
pad (int): padding size. The default value is ``0``.
Returns:
list: list object whose shape consists of ``n``, ``c_o``,
``h_o``, ``w_o``, where ``h_o`` is
the result of ``math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1``,
and `w_o` is the result of ``math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1``.
Raises:
AssertionError: If ``h_k > h_i or w_k > w_i`` or ``stride > (h_i - h_k + 2 * pad + 1)``
or ``stride > (w_i - w_k + 2 * pad + 1)``
"""
n = len(x)
c_i = len(x[0])
h_i = len(x[0][0])
w_i = len(x[0][0][0])
c_o = len(W)
c_i = len(W[0])
h_k = len(W[0][0])
w_k = len(W[0][0][0])
if h_k > h_i or w_k > w_i:
raise AssertionError('The height and width of x must be smaller than W')
if stride > (h_i - h_k + 2 * pad + 1) or stride > (w_i - w_k + 2 * pad + 1):
raise AssertionError('The value of stride must be smaller than output tensor size')
h_o = math.floor((h_i - h_k + 2 * pad) / float(stride)) + 1
w_o = math.floor((w_i - w_k + 2 * pad) / float(stride)) + 1
# n x c_o x (h_o * w_o)
result = [[[INITIAL_VALUE for _i in range(w_o * h_o)]
for _k in range(c_o)]
for _h in range(n)]
# n x c_i x h_k x w_k x h_o x w_o
col = im2col(x=x, h_k=h_k, w_k=w_k, pad=pad, stride=stride)
# convert to the matrix whose shape is `n x (k * k * c_i) x (h_o * w_o)`
col = np.reshape(col, (n, h_k * w_k * c_i, h_o * w_o)).tolist()
# convert to the matrix whose shape is `c_o x (k * k * c_i) `
W = np.reshape(W, (c_o, h_k * w_k * c_i)).tolist()
for nn in range(n):
for i in range(c_o):
for k in range(h_k * w_k * c_i):
for j in range(h_o * w_o):
result[nn][i][j] += W[i][k] * col[nn][k][j]
return np.reshape(result, (n, c_o, h_o, w_o)).tolist()
|
# Given two strings s and t which consist of only lowercase letters.
# String t is generated by random shuffling string s and then add one more letter at a random position.
# Find the letter that was added in t.
# Example:
# Input:
# s = "abcd"
# t = "abcde"
# Output:
# e
# Explanation:
# 'e' is the letter that was added.
s = "a"
t = "aa"
def makeDict(string):
d = {}
for i in string:
if i in d:
d[i] += 1
else:
d[i] = 1
return d
d1 = makeDict(s)
d2 = makeDict(t)
for i in d2.keys():
if i not in d1.keys():
print(i)
break
else:
if d1[i] != d2[i]:
print(i)
break
|
#运算符
a=21
b=input('请输入b:')
if(a==b):
print('a等于b')
else:
print('a不等于b') |
# coding: utf-8
# 设损失函数loss = (w + 1)^2 , 令 w 是常数 5。反向传播就是求最小
# loss 对应的 w 值
import tensorflow as tf
# 定义待优化参数 w 初值赋予5
w = tf.Variable(tf.constant(5, dtype=tf.float32))
# 定义损失函数 loss
loss = tf.square(w+1)
# 定义反向传播方法
# 学习率为:0.2
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
# 生成会话,训练40轮
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
for i in range(40):
sess.run(train_step)
W_val = sess.run(w)
loss_val = sess.run(loss)
print("After %s steps: w: is %f, loss: is %f." %(i, W_val, loss_val)) |
# 案例v7百度翻译
# 使用Request
from urllib import request,parse
import json
baseurl = 'http://fanyi.baidu.com/sug'
keyword = input("请输入需要翻译的内容:")
data = {
'kw': keyword
}
# 需要使用parse模块对data进行编码
data = parse.urlencode(data)
data = data.encode('utf-8')
header = {
'Content-Length':len(data)
}
# 构造Request实例
req = request.Request(url=baseurl,data=data,headers=header)
# 发出请求
rsp = request.urlopen(req)
json_data = rsp.read().decode()
# 把json字符串转换为字典
json_data = json.loads(json_data)
for item in json_data['data']:
# if item['k'] == keyword:
print(item['k'], ": ", item['v']) |
# 案例v7百度翻译
from urllib import request,parse
# 导入json包,负责处理json格式的模块
import json
'''
大致流程:
1.利用data构造内容,然后urlopen打开
2.返回一个json格式的结果
3.结果就应该是服务器返回的释义
'''
baseurl = 'http://fanyi.baidu.com/sug'
# 存放用来模拟form的数据,一定是dict格式
keyword = input("请输入需要翻译的内容:")
data = {
'kw': keyword
}
# print(data)
# 需要使用parse模块对data进行编码
data = parse.urlencode(data)
data = data.encode('utf-8')
# print("编码后的data:",data)
# print("编码后的data类型:",type(data))
# 当需要类型为bytes时:在数据的后面加上: data = data.encode('utf-8')
# 构造请求头,请求头部至少包含:
# 1.传入数据的长度
# 2.request要求传入的请求是一个dict格式
# 有了headers,data,url就可以尝试发出请求
rsp = request.urlopen(baseurl,data=data)
json_data = rsp.read().decode()
# 把json字符串转换为字典
json_data = json.loads(json_data)
# print(json_data)
for item in json_data['data']:
if item['k'] == keyword:
print(item['k'], ": ", item['v'])
|
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
query="CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,username text, password text)"
cursor.execute(query)
query="CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY,name text, price real)"
cursor.execute(query)
connection.commit()
connection.close()
|
#Learn more at stack @ https://www.hackerearth.com/practice/data-structures/stacks/basics-of-stacks/tutorial/
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == [] # or len(self.items == 0)
def peek(self):
if self.isEmpty():
raise "Error peeking at empty stack"
return self.items[self.size() - 1]
def size(self):
return len(self.items)
s = Stack()
print("Initializing stack")
print(s.isEmpty()) # True
s.push('L') #L
s.push('e') #Le
s.push('v') #Lev
s.push('e') #Leve
s.push('l') #Level
print(s.peek())
print(s.size())
print(s.isEmpty())
print(s.pop()) #Leve
print(s.pop()) #Lev
print(s.pop()) #Le
print(s.pop()) #L
print(s.pop()) #[]
print(s.size())
|
import collections
class Point:
def __init__(self, point):
coordinates = point.split(" ")
self.x = int(coordinates[0])
self.y = int(coordinates[1])
def __str__(self):
return str(self.x) + " " + str(self.y)
def get_data_from_file(path_to_file="in.txt"):
matrix_str = ""
with open(path_to_file,"r") as file:
rows_count = file.readline()
columns_count = file.readline()
matrix_str = file.read()
maze = []
lines = matrix_str.split("\n")
last_point = lines.pop()
firts_point = lines.pop()
for line in lines:
elements = line.split(" ")
maze.append(elements)
return int(rows_count), int(columns_count),firts_point, last_point, maze
def find_path_with_dfs(maze, first_point, last_point, rows_count, columns_count):
visited_points = collections.deque()
visited_points.append(first_point)
# словарь, где лежит предыдущая вершина для каждой вершины(из которой в нее пришли)
# заполняю словарь пустотой
prev_points = {str(x) + " " + str(y): None for x in range(1, rows_count + 1) for y in range(1, columns_count + 1)}
# print(prev_points)
current_point = "start"
prev_points[str(first_point)] = current_point
while len(visited_points) != 0:
current_point = visited_points.pop()
if str(current_point) == str(last_point):
return get_path_from_chain(prev_points, first_point, last_point), "Y"
left_y = current_point.y - 1
right_y = current_point.y + 1
up_x = current_point.x - 1
down_x = current_point.x + 1
# смотрим возможность пойти в стороны, в обратном порядеке,
# чтобы преимущество было у последней вершины в стеке(первой по приоритету)
if down_x <= rows_count:
next_point = Point(str(down_x) + " " + str(current_point.y))
if maze[down_x-1][current_point.y-1] == "0" and prev_points[str(next_point)] is None:
prev_points[str(next_point)] = current_point
visited_points.append(next_point)
# print("down")
if up_x > 0:
next_point = Point(str(up_x) + " " + str(current_point.y))
if maze[up_x-1][current_point.y-1] == "0" and prev_points[str(next_point)] is None:
prev_points[str(next_point)] = current_point
visited_points.append(next_point)
# print("up")
if right_y <= columns_count:
next_point = Point(str(current_point.x) + " " + str(right_y))
if maze[current_point.x-1][right_y - 1] == "0" and prev_points[str(next_point)] is None:
prev_points[str(next_point)] = current_point
visited_points.append(next_point)
# print("right")
if left_y > 0:
next_point = Point(str(current_point.x) + " " + str(left_y))
if maze[current_point.x-1][left_y-1] == "0" and prev_points[str(next_point)] is None:
prev_points[str(next_point)] = current_point
visited_points.append(next_point)
# print("left")
# проверяем, дошли мы до точки, или просто закончили обход своей компоненты связанности
if str(current_point) != str(last_point):
return [], "N"
return get_path_from_chain(prev_points, first_point, last_point), "Y"
def get_path_from_chain(prev_points, first_point, last_point):
path = []
current_point = last_point
while True:
path.insert(0, str(current_point))
current_point = prev_points[str(current_point)]
if current_point == "start":
break
# print(path)
return path
def write_in_file(data):
with open('out.txt', '+w') as file:
file.write(data)
rows_count, columns_count, first_point, last_point, maze = get_data_from_file()
first_point = Point(first_point)
last_point = Point(last_point)
# print(first_point.x,first_point.y)
# print(last_point.x,last_point.y)
path, is_reachable = find_path_with_dfs(maze, first_point, last_point, rows_count, columns_count)
path.insert(0, is_reachable)
write_in_file("\n".join(path))
|
import tkinter
from tkinter.filedialog import *
top = tkinter.Tk()
def print_file():
f = tkinter.filedialog.askopenfilename(
parent=top, initialdir ='/',
title='choose file',
filetypes=[('text files', 'txt')]
)
fc = open(f, 'r')
print(fc.read())
b1 = tkinter.Button(top, text='Print file content', command=print_file)
b1.pack(anchor="w")
top.mainloop()
|
import numpy as np
import matplotlib.pyplot as plt
from plot_decision import plot_decision_boundaries
from neuralnets import NeuralNet
def generate_spiral(n, C):
'''Generate n points forming a spiral with C classes. Taken from cs231n
course notes.'''
X = np.zeros((n * C, 2))
y = np.zeros(n * C, dtype='uint8')
for j in range(C):
ix = range(n * j, n * (j + 1))
r = np.linspace(0.0, 1, n) # radius
t = np.linspace(j*4,(j + 1) * 4, n) + np.random.randn(n)*0.2 # theta
X[ix] = np.c_[r * np.sin(t), r * np.cos(t)]
y[ix] = j
return X, y
C = 3
X, y = generate_spiral(100, C)
clf = NeuralNet(n_neurons=[X.shape[1], 100, C],
activations='relu',
learning_rate=.1,
n_epochs=20,
batch_size=0,
lambda_reg=.001,
init_strat='He',
solver='adam',
verbose=2)
clf.fit(X, y)
plt.figure()
plot_decision_boundaries(clf, X, y)
plt.show()
|
from thirdMatchClass import thirdMatch
thirdMatchList = thirdMatch.createThirdMatch()
class thirdMatchClass2(object):
def __init__(self,thirdMatchList):
self.thirdMatchList= thirdMatchList
def createGrup(self):
# print(self.thirdMatchList)
# for i in self.thirdMatchList:
# print(i)
j=0
package=[]
while j< len(self.thirdMatchList):
uniqList=[]
for i in range(len(self.thirdMatchList[j])):
if self.thirdMatchList[j][i] not in uniqList:
uniqList.append(self.thirdMatchList[j][i])
# print(uniqList)
counter=0
for liste in uniqList:
if counter < self.thirdMatchList[j].count(liste):
counter= self.thirdMatchList[j].count(liste)
# print(counter)
for liste in uniqList:
if counter == self.thirdMatchList[j].count(liste):
package.append(liste)
# print(liste)
j+=1
# print(package)
return package
thirdMatchClass2= thirdMatchClass2(thirdMatchList)
thirdMatchClass2.createGrup()
|
class Arena:
def __init__(self, username, health, mana, attack, balance, experience, level, job):
self.username = username
self.health = health
self.mana = mana
self.attack = attack
self.balance = balance
self.experience = experience
self.level = (level)
self.job = job
def arena(self):
if self.level == 1:
LevelOne(self.username, self.health, self.mana, self.attack, self.balance, self.experience, self.level, self.job).fight()
if self.level == 2:
LevelTwo(self.username, self.health, self.mana, self.attack, self.balance, self.experience, self.level, self.job).fight()
if self.level >= 3:
LevelThree(self.username, self.health, self.mana, self.attack, self.balance, self.experience, self.level, self.job).fight()
class LevelOne(Arena):
def __init__(self, username, health, mana, attack, balance, experience, level, job):
super().__init__(username, health, mana, attack, balance, experience, level, job)
@property
def goblin(self):
attack = 1000
health = 10000
experience = 50
balance = 2000
return attack, health, experience, balance
def fight(self):
print("Enemy is a Goblin!!!")
attack, health, experience, balance = self.goblin
while True:
print(f"{self.username} health is {self.health}")
print(f"Goblins health is {health}")
action = input("Attack(1) Escape(2) ")
if action.lower() == "attack" or action == '1':
self.health -= attack
health -= self.attack
if health <= 0:
print("well done you killed the goblins!!!")
print(f"reward is exp: {experience} money: {balance}")
self.experience += experience
self.balance += balance
if self.experience >= 100:
self.experience = 0
self.level += 1
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health, self.experience, self.level, self.balance, self.username)
query = ''' UPDATE Users SET health= ?, experience= ?, level= ?, balance= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
if self.health <= 0:
print("you are dead!")
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health)
query = ''' UPDATE Users SET health= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
elif action.lower() == "escape" or action == '2':
break
else:
pass
class LevelTwo(Arena):
def __init__(self, username, health, mana, attack, balance, experience, level, job):
super().__init__(username, health, mana, attack, balance, experience, level, job)
@property
def orc(self):
attack = 2000
health = 10000
experience = 75
balance = 2000
return attack, health, experience, balance
def fight(self):
print("Enemy is a orc!!!")
attack, health, experience, balance = self.orc
while True:
print(f"{self.username} health is {self.health}")
print(f"orcs health is {health}")
action = input("Attack(1) Escape(2) ")
if action.lower() == "attack" or action == '1':
self.health -= attack
health -= self.attack
if health <= 0:
print("well done you killed the orcs!!!")
print(f"reward is exp: {experience} money: {balance}")
self.experience += experience
self.balance += balance
if self.experience >= 100:
self.experience = 0
self.level += 1
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health, self.experience, self.level, self.balance, self.username)
query = ''' UPDATE Users SET health= ?, experience= ?, level= ?, balance= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
if self.health <= 0:
print("you are dead!")
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health)
query = ''' UPDATE Users SET health= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
elif action.lower() == "escape" or action == '2':
break
else:
pass
class LevelThree(Arena):
def __init__(self, username, health, mana, attack, balance, experience, level, job):
super().__init__(username, health, mana, attack, balance, experience, level, job)
@property
def uruk(self):
attack = 3000
health = 10000
experience = 100
balance = 2000
return attack, health, experience, balance
def fight(self):
print("Enemy is a uruk!!!")
attack, health, experience, balance = self.uruk
while True:
print(f"{self.username} health is {self.health}")
print(f"uruks health is {health}")
action = input("Attack(1) Escape(2) ")
if action.lower() == "attack" or action == '1':
self.health -= attack
health -= self.attack
if health <= 0:
print("well done you killed the uruks!!!")
print(f"reward is exp: {experience} money: {balance}")
self.experience += experience
self.balance += balance
if self.experience >= 100:
self.experience = 0
self.level += 1
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health, self.experience, self.level, self.balance, self.username)
query = ''' UPDATE Users SET health= ?, experience= ?, level= ?, balance= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
if self.health <= 0:
print("you are dead!")
import sqlite3
conn = sqlite3.connect("user.db")
c = conn.cursor()
data = (self.health)
query = ''' UPDATE Users SET health= ?
WHERE username= ? '''
c.execute(query, data)
conn.commit()
conn.close()
break
elif action.lower() == "escape" or action == '2':
break
else:
pass
|
from graphics import*
win=GraphWin("Home",1200,700)
def draw_roof(x,y,increase=1,color="#efe3af",has_roof_window1=True,has_roof_edging_w1=True): #Крыша
p=Polygon(Point(x-260*increase,y),Point(x,y-300*increase),Point(x+260*increase,y))
p.setWidth(3)
p.setFill(color)
p.draw(win)
if has_roof_edging_w1==True:
draw_edging_w1(x,y-155*increase)
if has_roof_window1==True:
draw_window1(x,y-155*increase)
def draw_edging_w1(x,y,increase=1,color="#b77a5d"): #Окантовка верхнего окна
k=Polygon(Point(x-70*increase,y),Point(x,y-78*increase),Point(x+70*increase,y),Point(x,y+78*increase))
k.setWidth(3)
k.setFill(color)
k.draw(win)
def draw_lamp(x,y,increase,color="yellow"): #Фонарь
o=Circle(Point(x,y),26*increase)
o.setWidth(3)
o.setFill(color)
o.draw(win)
def draw_window1(x,y,increase=1,color="#98daea"): #Верхнее окно
g=Polygon(Point(x-50*increase,y),Point(x,y-50*increase),Point(x+50*increase,y),Point(x,y+50*increase))
z=Line(Point(x-50*increase,y),Point(x+50*increase,y))
b=Line(Point(x,y-50*increase),Point(x,y+50*increase))
g.setWidth(3)
z.setWidth(3)
b.setWidth(3)
g.setFill(color)
g.draw(win)
z.draw(win)
b.draw(win)
def draw_window2(x,y,increase=1,color1="#b77a5d",color2="#98daea",color3="#b77a5d"): #Нижнее окно
q=Rectangle(Point(x-90*increase,y-7*increase),Point(x+90*increase,y+7*increase))
q.setWidth(3)
q.setFill(color1)
w=Rectangle(Point(x-78*increase,y+7*increase),Point(x+78*increase,y+183*increase))
w.setWidth(3)
w.setFill(color2)
e=Rectangle(Point(x-90*increase,y+183*increase),Point(x+90*increase,y+197*increase))
e.setWidth(3)
e.setFill(color3)
t=Line(Point(x-78*increase,y+56*increase),Point(x+78*increase,y+56*increase))
t.setWidth(3)
y=Line(Point(x,y+56*increase),Point(x,y+189*increase))
y.setWidth(3)
q.draw(win)
w.draw(win)
e.draw(win)
t.draw(win)
y.draw(win)
def draw_door(x,y,increase=1,color1="#b77a5d",color2="#880016",color3="#b77a5d"): #Дверь
u=Rectangle(Point(x,y),Point(x+163*increase,y+13*increase))
u.setWidth(3)
u.setFill(color1)
i=Rectangle(Point(x+11*increase,y+15*increase),Point(x+151*increase,y+218*increase))
i.setWidth(3)
i.setFill(color2)
a=Rectangle(Point(x+120*increase,y+88*increase),Point(x+129*increase,y+136*increase))
a.setFill(color3)
a.setWidth(3)
u.draw(win)
i.draw(win)
a.draw(win)
def draw_trumpet(x,y,increase=1,color1="#7f7f7f",color2="#da4800"): #Труба
s=Rectangle(Point(x,y),Point(x+110*increase,y+29*increase))
s.setWidth(3)
s.setFill(color1)
d=Polygon(Point(x+26*increase,y+192*increase),Point(x+26*increase,y+30*increase),Point(x+88*increase,y+30*increase),Point(x+88*increase,y+120*increase))
d.setWidth(3)
d.setFill(color2)
s.draw(win)
d.draw(win)
def draw_house(x,y,increase=1,color1="red",color2="blue",color3="green",color4="brown"):
r=Rectangle(Point(x-231*increase,y), Point(x+231*increase, y+308*increase)) #Первый этаж
r.setWidth(3)
r.setFill(color1)
r.draw(win)
color='pink'
draw_roof(x+3,y,increase,color)
draw_lamp(x+116,y+55,increase,color)
draw_window2(x-89,y+31,increase,color1,color2,color3)
draw_door(x+30,y+89,increase,color1,color2,color3)
draw_trumpet(x-179,y-315,increase,color1,color2)
def draw_tree(x,y,t_i=1,trunk_color="brown",needles_color="green"): #Дерево (координаты центра верхней стороны ствола, увеличение, цвет ствола, цвет иголок)
tree_trunk=Rectangle(Point(x-10*t_i,y),Point(x+10*t_i,y+50*t_i)) #Ствол ёлки (контур)
tree_trunk.setFill(trunk_color)
christmas_tree_needles=Polygon(Point(x,y),Point(x-45*t_i,y),Point(x-20*t_i,y-30*t_i),Point(x-35*t_i,y-30*t_i),Point(x-10*t_i,y-60*t_i),Point(x-25*t_i,y-60*t_i),Point(x,y-90*t_i),Point(x+25*t_i,y-60*t_i),Point(x+10*t_i,y-60*t_i),Point(x+35*t_i,y-30*t_i),Point(x+20*t_i,y-30*t_i),Point(x+45*t_i,y)) #Ёлки иголки (контур дерева)
christmas_tree_needles.setFill(needles_color)
tree_trunk.draw(win)
christmas_tree_needles.draw(win)
def draw_sun(x,y,sun_radius,sun_color,sun_increase=1): #Солнце (координаты, радиус, цвет, увеличение)
solar_corona=Circle(Point(x,y),sun_radius*sun_increase)
solar_corona.setFill(sun_color)
advertisement_YOTA=Text(Point(x,y),"Реклама YOTA на Солнце")
solar_corona.draw(win)
if sun_radius>=95:
advertisement_YOTA.draw(win)
def draw_cloud(x,y,A,B,cloud_color,c_i=1): #Облако (координаты центра, большие оси, цвет, увеличение)
cloud=Oval(Point(x-A/2*c_i,y-B/2*c_i),Point(x+A/2*c_i,y+B/2*c_i))
cloud.setFill(cloud_color)
cloud.draw(win)
def draw_person(x,y,size=1,this_person_is_a_man=True): #Человек (координаты центра, размер, пол)
head=Circle(Point(x,y),15*size)
head.setFill("white")
eye_r=Circle(Point(x-4*size,y-4*size), 1*size)
eye_l=Circle(Point(x+4*size,y-4*size), 1*size)
roth=Line(Point(x-4*size,y+4*size),Point(x+4*size,y+4*size))
head.draw(win)
eye_r.draw(win)
eye_l.draw(win)
roth.draw(win)
if this_person_is_a_man==True:
body1=Polygon(Point(x,y+65*size),Point(x-30*size,y+15*size),Point(x+30*size,y+15*size))
body1.setFill("red")
body1.draw(win)
hand_r1=Line(Point(x-30,y+15*size),Point(x-45*size,y+40*size))
hand_r1.draw(win)
hand_l1=Line(Point(x+30,y+15*size),Point(x+45*size,y+40*size))
hand_l1.draw(win)
leg_r1=Line(Point(x-12*size,y+45*size),Point(x-12*size,y+80*size))
leg_r1.draw(win)
leg_l1=Line(Point(x+12*size,y+45*size),Point(x+12*size,y+80*size))
leg_l1.draw(win)
if this_person_is_a_man==False:
body2=Polygon(Point(x,y+15*size),Point(x-30*size,y+65*size),Point(x+30*size,y+65*size))
body2.setFill("green")
body2.draw(win)
hand_r2=Line(Point(x,y+15*size),Point(x-25*size,y+40*size))
hand_r2.draw(win)
hand_l2=Line(Point(x,y+15*size),Point(x+25*size,y+40*size))
hand_l2.draw(win)
leg_r2=Line(Point(x-10*size,y+65*size),Point(x-10*size,y+95*size))
leg_r2.draw(win)
leg_l2=Line(Point(x+10*size,y+65*size),Point(x+10*size,y+95*size))
leg_l2.draw(win)
draw_cloud(50,300,50,20,"gray")
draw_sun(768,108,100,"yellow")
draw_house(324,355)
draw_tree(1000,300)
draw_person(850,200)
win.getMouse()
win.close()
|
class Solution:
def factorial(self, n):
if n < 2:
return 1
i = 1
res = 1
while i <= n:
res *= i
i += 1
return res
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex < 1:
return [1]
facn = self.factorial(rowIndex)
i = 0
res = []
while i <= rowIndex:
res.append(
int(facn/(self.factorial(i)*self.factorial(rowIndex - i))))
i += 1
return res
if __name__ == '__main__':
s = Solution()
print(s.getRow(13))
|
class Dog(object):
def __init__(self,name,age,color):
self.name=name
self.age=age
self.color=color
def __str__(self):
return('name:%s age:%d color:%d' % (self.name,self.age,self.color))
dog = Dog("wangcai",5,000)
print(dog) |
#https://stackoverflow.com/questions/36550812/how-can-i-detect-multiple-words-from-a-string-python
stringword = "My favorite board games are Puerto Rico, Dominion, Pandemic, Mahjong, Chess, and Settlers of Catan."
findthesewords = ["Puerto","Mahjong","Settlers"]
if any(eachfindthesewords in stringword for eachfindthesewords in findthesewords):
print("True") #print True
findthesewords2 = ["UNO","Monopoly","Jacks"]
if any(eachfindthesewords2 in stringword for eachfindthesewords2 in findthesewords2):
print("True 2")
findthesewords3 = ["Candyland","Chutes And Ladders","Pandemic"]
if any(eachfindthesewords3 in stringword for eachfindthesewords3 in findthesewords3):
print("True 3") #print True 3
for eachstringword in stringword.split():
if any(eachfindthesewords in eachstringword for eachfindthesewords in findthesewords):
print(eachstringword,"for true") #print Puerto for true\n Mahjong, for true\n Settlers for true
stringword = "My favorite board games are Puerto Rico, Dominion, Pandemic, Mahjong, Chess, and Settlers of Catan."
findthesewords = ["Puerto","Mahjong","Settlers"]
if all(eachfindthesewords in stringword for eachfindthesewords in findthesewords):
print("All True") #print All True
findthesewords2 = ["UNO","Monopoly","Jacks"]
if all(eachfindthesewords2 in stringword for eachfindthesewords2 in findthesewords2):
print("All True 2")
#https://stackoverflow.com/questions/16505456/how-exactly-does-the-python-any-function-work/16505590
names = ["King","Queen","Joker"]
print(any(anynames in "King and John" for anynames in names)) #print True
print(all(allnames in "King and John" for allnames in names)) #print False
print(all(allnames in "King and Queen" for allnames in names)) #print False
print(any(anynames in "King Queen" for anynames in names)) #print True
print(all(allnames in "King Queen" for allnames in names)) #print False
print(all(allnames in "King Queen Joker" for allnames in names)) #print True
print("\n")
#https://thepythonguru.com/python-builtin-functions/any/
#The any() function test whether any item in the iterable evaluates to True or not. It accepts an iterable and returns True, if at least one item in the iterable is true, otherwise, it returns False. any(iterable)-->returns boolean
print(any([10, "", "one"])) #print True
print(any(("",{}))) #print False
print(any([])) #print False
numbergenerator = [i for i in range(0,5)]
print(numbergenerator) #print [0, 1, 2, 3, 4]
print(any(numbergenerator)) #print True
print("\n")
#https://www.programiz.com/python-programming/methods/built-in/all
#The all() function returns True when all elements in the given iterable are true. all(iterable). The iterable can be a list, tuple, dictionary which contains elements.
l = [1, 3, 4, 5]
print(all(l)) #print True
l = [0, False]
print(all(l)) #print False
l = [1, 3, 4, 0]
print(all(l)) #print False
l = [0, False, 5]
print(all(l)) #print False
l = []
print(all(l)) #print True RM: empty iterable True if all() and False if any()
string = "This is good"
print(all(string)) #print True
#In case of dictionaries, if all keys (not values) are true or the dictionary is empty, all() returns True. Else, it returns false
dictionaryd = {0: 'False', 1: 'False'}
print(all(dictionaryd)) #print False
dictionaryd = {1: 'True', 2: 'True'}
print(all(dictionaryd)) #print True
dictionaryd = {1: 'True', False: 0}
print(all(dictionaryd)) #print False
dictionaryd = {}
print(all(dictionaryd)) #print True
# 0 is False
# '0' is True
dictionaryd = {'0': 'True'}
print(all(dictionaryd)) #print True
print("\n")
#https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work
#all checks for elements to be False (so it can return False), then it returns True if none of them were False. All stops when there is a False.
#any checks for elements to be True (so it can return True), then it returns False if none of them were True. Any stops when there is a True.
print(any([])) #print False
print(all([])) #print True
def noisy_iterator(iterable):
for i in iterable:
print('yielding ' + repr(i))
yield i
all(noisy_iterator([1, 2, 3, 4])) #print yielding 1\n yielding 2\n yielding 3\n yielding 4
print(all(noisy_iterator([1, 2, 3, 4]))) #print yielding 1\n yielding 2\n yielding 3\n yielding 4\n True
all(noisy_iterator([0, 1, 2, 3, 4])) #print yielding 0. all stops on the first False boolean check.
print(all(noisy_iterator([0, 1, 2, 3, 4]))) #print yielding 0\n False. all stops on the first False boolean check.
def noisy_iterator(iterable):
for i in iterable:
#print('yielding ' + str(i))
print('yielding ' + repr(i))
yield i
any(noisy_iterator([0, 0.0, '', (), [], {}])) #print yielding 0\n yielding 0.0\n yielding ''\n yielding ()\n yielding []\n yielding {}
print(any(noisy_iterator([0, 0.0, '', (), [], {}]))) #print yielding 0\n yielding 0.0\n yielding ''\n yielding ()\n yielding []\n yielding {}\n False
any(noisy_iterator([1, 0, 0.0, '', (), [], {}])) #print yielding 1. any stops on the first True boolean check.
print(any(noisy_iterator([1, 0, 0.0, '', (), [], {}]))) #print yielding 1\n True. any stops on the first True boolean check. |
#Iterate at least two lists at once. Use the zip function zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
# lista = [3, 9, 17, 15, 19]
# listb = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
# for eachlista, eachlistb in zip(lista, listb):
# print(eachlista)
# print(eachlistb)
# print(eachlista, eachlistb)
#enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence. It's very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we've seen so far.
choices = ["pizza","pasta","salad","nachos"]
print("Your choices are: ")
for index, eachchoices in enumerate(choices):
print(index+1,eachchoices) #eachchoices should start at index 1. #print 1 pizza\n 2 pasta\n 3 salad\n 4 machos
fruits = ['banana', 'apple', 'orange', 'pear', 'grape']
for eachfruits in fruits:
if eachfruits == "tomato":
print(eachfruits+" is not a fruit. It actually is a fruit")
break
else:
print(eachfruits)
else:
print("A fine selection of fruits!") #not printed because tomato broke the for eachfruits in fruits
fruits = ['banana', 'apple', 'tomato', 'orange', 'pear', 'grape']
for eachfruits in fruits:
if eachfruits == "tomato":
print(eachfruits+" is not a fruit. It actually is a fruit")
break
else:
print(eachfruits)
print("A fine selection of fruits!") #printed because it's the next line after the for eachfruits in fruits loop
integerdecimal = 7.0
print(type(integerdecimal)) #print <class 'float'>
integerseven = 7
print(type(integerseven)) #print <class 'int'>
integerseven = integerseven + 0.0
print(integerseven) #print 7.0
print(type(integerseven)) #print <class 'float'>
|
#https://docs.python.org/3.5/library/itertools.html, https://stackoverflow.com/questions/41680388/how-do-i-iterate-through-combinations-of-a-list, https://stackoverflow.com/questions/16384109/iterate-over-all-combinations-of-values-in-multiple-lists-in-python
#RM: there are more functions in itertools. I selected the product(), combinations(), permutations(), chain(), chain.from_iterable(). 08/02/18: there are more itertools below the selected functions.
#product creates a cartesian products from a series of iterables
import itertools
firstlist = [1,5,8]
secondlist = [0.5, 4]
print(list(itertools.product(firstlist, secondlist))) #print [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
print(list(itertools.product(firstlist, secondlist))) #print [(1, 0.5), (1, 4), (5, 0.5), (5, 4), (8, 0.5), (8, 4)]
#combinations sorts lexicographicaly
list1234 = [1, 2, 3, 4]
for combopairs in itertools.combinations(list1234, 2):
print(combopairs) #print (1, 2)\n (1, 3)\n (1, 4)\n (2, 3)\n (2, 4)\n (3, 4)
for combotriplets in itertools.combinations(list1234, 3):
print(combotriplets) #print (1, 2, 3)\n (1, 2, 4)\n (1, 3, 4)\n (2, 3, 4)
for combopairs in itertools.combinations(list1234, 2):
print(sum(combopairs)) #print 3\n 4\n 5\n 5\n 6\n 7
list12345 = [1, 2, 3, 4, 5]
for comboquads in itertools.combinations(list12345, 4):
print(comboquads) #print (1, 2, 3, 4)\n (1, 2, 3, 5)\n (1, 2, 4, 5)\n (1, 3, 4, 5)\n (2, 3, 4, 5)\n
#combinations_with_replacement elements repeat
for comboquads in itertools.combinations_with_replacement(list12345, 4):
print(comboquads) #print (1, 1, 1, 1)\n (1, 1, 1, 2)\n (1, 1, 1, 3)\n (1, 1, 1, 4)\n . . . (1, 1, 2, 2) . . . .
list1234 = [1, 2, 3, 4]
for productpairs in itertools.permutations(list1234, 2):
print(productpairs,end=";") #print (1, 2);(1, 3);(1, 4);(2, 1);(2, 3);(2, 4);(3, 1);(3, 2);(3, 4);(4, 1);(4, 2);(4, 3); RM: prints 1,2 and 2,1
#product creates a cartesian products from a series of iterables
list1234 = [1, 2, 3, 4]
for productpairs in itertools.product(list1234, repeat=2):
print(productpairs,end=",") #print (1, 1),(1, 2),(1, 3),(1, 4),(2, 1),(2, 2),(2, 3),(2, 4),(3, 1),(3, 2),(3, 3),(3, 4),(4, 1),(4, 2),(4, 3),(4, 4), RM: prints all combinations such as 1,1; 1,2; 2,1
print("\n")
#product creates a cartesian products from a series of iterables product(*iterables, repeat=1)
firstlist = [1,5,8]
secondlist = [0.5, 4]
thirdlist = [10,11,12]
print(list(itertools.product(firstlist, secondlist, thirdlist))) #print [(1, 0.5, 10), (1, 0.5, 11), (1, 0.5, 12), (1, 4, 10), (1, 4, 11), (1, 4, 12), (5, 0.5, 10), (5, 0.5, 11), (5, 0.5, 12), (5, 4, 10), (5, 4, 11), (5, 4, 12), (8, 0.5, 10), (8, 0.5, 11), (8, 0.5, 12), (8, 4, 10), (8, 4, 11), (8, 4, 12)]
print(list(itertools.product(firstlist, secondlist, thirdlist, repeat=3)))
threelist = list(itertools.product(firstlist, secondlist, thirdlist))
print(threelist)
for eachthreelist in threelist:
print(sum(eachthreelist)) #print the sum for eachthreelist entry; e.g. (8,4,12) print 24
listone = [3]
listtwo = [7, 4]
listthree = [2, 4, 6]
listfour = [8, 5, 9, 3]
fourlist = list(itertools.product(listone, listtwo, listthree, listfour))
maxsum = 0
for eachfourlist in fourlist:
#print(sum(eachfourlist))
if sum(eachfourlist) > maxsum:
maxsum = sum(eachfourlist)
print(maxsum) #print 25
print(itertools.chain("ABC","DEF")) #print <itertools.chain object at 0x7f0169a21198>
love = itertools.chain("ABC","DEF")
print("".join(map(str, love))) #print ABCDEF
love = itertools.chain("ABC","DEF")
print(list(map(str,love))) #print ['A', 'B', 'C', 'D', 'E', 'F']
love = itertools.chain("ABC","DEF")
print(" ".join(map(str, love))) #print A B C D E F
print(itertools.chain.from_iterable(["ABC","DEF"])) #print <itertools.chain object at 0x7f0d500351d0>
listlove = itertools.chain.from_iterable(["ABC","DEF"])
print("".join(map(str, listlove))) #print ABCDEF
listlove = itertools.chain.from_iterable(["ABC","DEF"])
print(list(map(str,listlove))) #print ['A', 'B', 'C', 'D', 'E', 'F']
listlove = itertools.chain.from_iterable(["ABC","DEF"])
print(" ".join(map(str, listlove))) #print A B C D E F
from itertools import combinations
p = {int((num * ((3 * num) - 1)) / 2) for num in range(1, 10)}
for x, y in combinations(p, 2):
diff = abs(x - y)
print(x,y,diff) #print 35 70 35\n 5 70 65\n 22 92 70\n examples
_sum = x + y
if diff in p and _sum in p:
print(diff, _sum, x, y) #print
#38. Write a Python program to change the position of every n-th value with the (n+1)th in a list. Sample list: [0,1,2,3,4,5]. Expected Output: [1, 0, 3, 2, 5, 4]. RM: copied solution. New functions from a module.
from itertools import zip_longest, chain, tee
def replace2copy(lst):
lst1, lst2 = tee(iter(lst), 2)
return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))
n = [0,1,2,3,4,5]
print(replace2copy(n)) #print [1, 0, 3, 2, 5, 4]
#https://www.blog.pythonlibrary.org/2016/04/20/python-201-an-intro-to-itertools/
#https://medium.com/@jasonrigden/a-guide-to-python-itertools-82e5a306cdf8
#https://realpython.com/python-itertools/
#The count iterator will return evenly spaced values starting with the number you pass in as its start parameter. Count also accept a step parameter. count(start=0,step=1). RM: =number is default
from itertools import count
for i in count(10):
if i > 12:
break
else:
print(i) #print 10\n 11\n 12\n
for i in count(10,2):
if i > 21:
break
else:
print(i) #print 10\n 12\n 14\n 16\n 18\n 20\n
#Limit the output using islice. islice(loop,end loop number of items iterated).
from itertools import count, islice
for i in islice(count(10),3):
print(i) #print 10\n 11\n 12\n
for i in islice(count(10,2),6):
print(i) #print 10\n 12\n 14\n 16\n 18\n 20\n
#The cycle iterator create an iterator that will cycle through a series of values infinitely. cycle(iterable)
from itertools import cycle
count = 0
for eachletter in cycle("xyz"):
if count > 7:
break
else:
print(eachletter) #print x\n y\n z\n x\n y\n z\n x\n y\n
count += 1
colors = ["red","orange","yellow","green","blue"]
stopper = len(colors)
counter = 0
for eachcolors in cycle(colors):
#RM: counter must be included to stop cycle making for loop infinite. Obviously no need for cycle because for eachcolors in colors: iterates colors list once.
if counter == stopper:
break
print(eachcolors)
counter += 1
shapes = ["triangle","square","pentagon","rectangle"]
iterator = cycle(shapes)
print(next(iterator)) #print triangle
print(next(iterator)) #print square
print(next(iterator)) #print pentagon
print(next(iterator)) #print rectangle
print(next(iterator)) #print square
print(next(iterator)) #print triangle
#The repeat iterators will return an object an object over and over again forever unless you set its times argument. repeat(object[,times]) RM: brackets means optional
# from itertools import repeat
# iterator = repeat(5,5)
# print(next(iterator)) #print 5
# print(next(iterator)) #print 5
# print(next(iterator)) #print 5
# print(next(iterator)) #print 5
# print(next(iterator)) #print 5
print(next(iterator)) #error message StopIteration
from itertools import repeat
for i in repeat("spam",4):
print(i) #print spam\n spam\n spam\n spam
print(repeat(1,5)) #print repeat(1,5)
repeatonefive = repeat(1,5)
print(repeatonefive) #print repeat(1,5)
for i in repeat(1,5):
print(i) #print 1\n 1\n 1\n 1\n 1
for i in repeatonefive:
print(i) #print 1\n 1\n 1\n 1\n 1
#The accumulate iterator will return accumulated sums or the accumulated results of a two argument function. accumulate(iterable[,func]). Default is sum or operator.add.
from itertools import accumulate
#addfromindexnumbers = [x ]
print(list(accumulate(range(0,10)))) #[0, 1, 3, 6, 10, 15, 21, 28, 36, 45] RM: adds the numbers from index position starting at 0 accumulating the sum. 0+0, 0+1, 1+2, 3+3, 6+4, 10+5, 15+6 . . . . Default is sum.
import operator
print(list(accumulate(range(1,5), operator.mul))) #[1, 2, 6, 24] #operator.mul multiplies the numbers from index position. Instructors says look at accumulate documentation.
data = [789, 10, 25, 54, 99]
result = accumulate(data,operator.mul)
print(list(result)) #print [789, 7890, 157800, 7890000, 781110000] or [789, 789*10, 789*10*25, 789*10*25*54, 789*10*25*54*99]
data = [1, 2, 3, 4, 5]
result = accumulate(data,operator.mul)
for eachresult in result:
print(eachresult) #print 1\n 2\n 6\n 24\n 120\n
data = [5, 2, 6, 4, 5, 9, 1]
result = accumulate(data,max)
for eachresult in result:
print(eachresult) #print 5\n 5\n 6\n 6\n 6\n 9\n 6\n
data = [5, 2, 6, 4, 5, 9, 1]
for eachresult in accumulate(data,min):
print(eachresult) #print 5\n 2\n 2\n 2\n 2\n 2\n 1\n
#The chain iterator will take a series of iterables and basically flatten them down into one long iterable. chain(*iterables) RM: * means multiple objects
from itertools import chain
list1 = ["foo","bar"]
list2 = list(range(0,5))
list3 = ["ls","/some/dir"]
print(list1+list2+list3) #print ['foo', 'bar', 0, 1, 2, 3, 4, 'ls', '/some/dir']
print(chain(list1,list2,list3)) #print <itertools.chain object at 0x7f947c64df98>
list123 = chain(list1,list2,list3)
print(list123) #print <itertools.chain object at 0x7f367dd71780>
listlist123 = list(chain(list1,list2,list3))
print(listlist123) #print ['foo', 'bar', 0, 1, 2, 3, 4, 'ls', '/some/dir']
#You can also use a method of chain called from_iterable. Pass in a nested list. chain.from_iterable(iterable).
from itertools import chain
list1 = ["foo","bar"]
list2 = list(range(0,5))
list3 = ["ls","/some/dir"]
print(chain.from_iterable([list1,list2,list3])) #print <itertools.chain object at 0x7f8dcd5f4f98>
passnestedlist = chain.from_iterable([list1,list2,list3])
print(passnestedlist) #print <itertools.chain object at 0x7f72c0a21f60>
passnestedlistlist = list(chain.from_iterable([list1,list2,list3]))
print(passnestedlistlist) #print ['foo', 'bar', 0, 1, 2, 3, 4, 'ls', '/some/dir']
#The compress sub-module is useful for filtering the first iterable with the second. This works by making the second iterable a list of Booleans (or ones and zeroes which amounts to the same thing). Filters one iterable with another. compress(data, selectors)
from itertools import compress
letters1 = "abcdefg"
letters2 = "abcdefg"
letters3 = "afg"
truefalse = [True, False, True, True, False]
oneszeroes = [1, 0, 1, 1, 0]
print(list(compress(letters1,letters2))) #print ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(list(compress(letters1,letters3))) #print ['a', 'b', 'c']
print(list(compress(letters1,truefalse))) #print ['a', 'c', 'd'] #second list truefalse is Booleans
print(list(compress(letters1,oneszeroes))) #print ['a', 'c', 'd'] #second list oneszeroes is ones and zeroes
#Dropwhile will drop elements as long as the filter criteria is True. Because of this, you will not see any output from this iterator until the predicate becomes False. This can make the start-up time lengthy. dropwhile(predicate, iterable). RM: I believe dropwhile drops all elements when True. When False, dropwhile returns the rest of the elements. Makes iterator drops elements from iterable as long as the predicate is true; otherwise, returns every rest of elements.
from itertools import dropwhile
def greaterthanfive(x):
return x>5
print(list(dropwhile(greaterthanfive,[6, 7, 8, 9, 1, 2, 3, 10]))) #print [1, 2, 3, 10]
#The filterfalse function from itertools is very similar to dropwhile. However instead of dropping values that match True, filterfalse will only return those values that evaluated to False. filterfalse(predicate,iterable)
from itertools import filterfalse
def greaterthanfive(x):
return x>5
print(list(filterfalse(greaterthanfive,[6, 7, 8, 9, 1, 2, 3, 10]))) #print [1, 2, 3]
#The groupby iterator will return consecutive keys and groups from your iterable. Groups things together. groupby(iterable, key=None). RM: =None is default
from itertools import groupby
vehicles = [('Ford', 'Taurus'), ('Dodge', 'Durango'), ('Chevrolet', 'Cobalt'), ('Ford', 'F150'), ('Dodge', 'Charger'), ('Ford', 'GT')]
sortvehicles = sorted(vehicles)
for key, group in groupby(sortvehicles,lambda make: make[0]):
print(key, group) #print Dodge <itertools._grouper object at 0x7fb77439a160>
for make, rightsidetuple in group:
print(make, rightsidetuple) #print Dodge Charger\n Dodge Durango
#40. Write a Python program to split a list based on first character of word. RM: return the list of words by the first letter for each word. The answer is not a list. The answer is words grouped by the first letter for each word.
from itertools import groupby
from operator import itemgetter
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
for letter, words in groupby(sorted(word_list), key=itemgetter(0)):
print(letter)
for word in words:
print(word)
"""print
a
ask
b
be
c
call
come
d
do
. . .
"""
#count frequency elements in a list count. List must be sorted.
#Source: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elements-in-a-list
#The python groupby creates new groups when the value it sees changes. In this case [1,1,1,2,1,1,1] would return [3,1,3]. If you expected [6,1] then just be sure to sort the data before using groupby
countnumbers = [1,1,1,1,2,2,2,2,3,3,4,5,5]
poodlecolors = ["black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "brown", "gold", "gold", "gold", "gold", "gold", "gold", "gold", "gold", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "grey", "white", "white", "white", "white", "white", "white", "white", "white", "white", "white"]
frequencycountnumbers = [len(list(group)) for key, group in groupby(countnumbers)]
print(frequencycountnumbers) #print [4, 4, 2, 1, 2]
dictionaryfrequencycountnumbers = {key: len(list(group)) for key, group in groupby(countnumbers)}
print(dictionaryfrequencycountnumbers) #print {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
frequencypoodlecolors = [len(list(group)) for key, group in groupby(poodlecolors)]
print(frequencypoodlecolors) #print [17, 13, 8, 52, 10]
dictionaryfrequencypoodlecolors = {key: len(list(group)) for key, group in groupby(poodlecolors)}
print(dictionaryfrequencypoodlecolors) #print {'black': 17, 'brown': 13, 'gold': 8, 'grey': 52, 'white': 10}
#bonus Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.
countnumbers = [1,1,1,1,2,2,2,2,3,3,4,5,5]
d = {x:countnumbers.count(x) for x in countnumbers}
print(d) #print {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
countnumberskeyes, countnumbersvalues = d.keys(), d.values()
print(countnumberskeyes) #print dict_keys([1, 2, 3, 4, 5])
print(countnumbersvalues) #print dict_values([4, 4, 2, 1, 2])
#islice is an iterator that returns selected elements from the iterable. islice take a slice by index of your iterable (the thing you iterate over) and returns the selected items as an iterator. Allows you to cut out a piece of an iterable. There are actually two implementations of islice. There’s itertools.islice(iterable, stop) and then there’s the version of islice that more closely matches regular Python slicing: islice(iterable, start, stop[, step]).
from itertools import islice, count
for i in islice(count(),3, 15):
print(i) #print 3\n 4\n 5\n . . . 12\n 13\n 14
for i in islice(count(),3, 15,3):
print(i) #print 3\n 6\n 9\n 12
n=45
for i in islice(count(),n,70,5):
print(i) #print 45\n 50\n 55\n 60\n 65
colors = ["red","orange","yellow","green","blue"]
number = 3
fewercolors = islice(colors,number)
for eachfewercolors in fewercolors:
print(eachfewercolors) #print red\n orange\n yellow
counter = count()
print(list(next(counter) for x in range(0, 5))) #print [0, 1, 2, 3, 4]
evens = count(step=2)
print(list(next(evens) for x in range(0, 5))) #print [0, 2, 4, 6, 8]
odds = count(start=1, step=2)
print(list(next(odds) for x in range(0, 5))) #print [1, 3, 5, 7, 9]
floats = count(start=.5, step=.75)
print(list(next(floats) for x in range(0, 5))) #print [0.5, 1.25, 2.0, 2.75, 3.5]
negatives = count(start=-1, step=-.5)
print(list(next(negatives) for x in range(0, 5))) #print [-1, -1.5, -2.0, -2.5, -3.0]
print(list(zip(count(),["a","b","c"]))) #print[(0, 'a'), (1, 'b'), (2, 'c')]
print(list(zip(count(start=1),["a","b","c"]))) #print[(1, 'a'), (2, 'b'), (3, 'c')]
ten = count(start=10, step=3)
for x in range(10,21):
print(next(ten)) #print 10\n 13\n 16\n 19\n 22\n 25\n 28\n 31\n 34\n 37\n 40
#The starmap tool will create an iterator that can compute using the function and iterable provided. Makes an iterator that computes the function using arguments obtained from the iterable. starmap(function, iterable).
from itertools import starmap
def add(a,b):
return a+b
for x in starmap(add,[(2,3),(4,5)]):
print(x) #print 5\n 9
from itertools import starmap
import operator
data = [(2,6),(8,4),(7,3)]
result = starmap(operator.mul, data)
for eachresult in result:
print(eachresult) #print 12\n 32\n 21
#The takewhile module is basically the opposite of the dropwhile iterator that we looked at earlier. takewhile will create an iterator that returns elements from the iterable only as long as our predicate or filter is True. Makes an iterator and returns elements from the iterable as long as the predicate is true. takewhile(predicate, iterable).
from itertools import takewhile
def lessthanfive(x):
return x<5
print(list(takewhile(lessthanfive,[1, 4, 2, 3, 6, 4, 1, 0]))) #print [1, 4, 2, 3]
#The tee tool will create *n* iterators from a single iterable. What this means is that you can create multiple iterators from one iterable. Returns n independent iterators from a single iterable. tee(iterable,n=2).
from itertools import tee
data = "abcde"
iter1, iter2, iter3 = tee(data,3)
for eachiter1 in iter1:
print(eachiter1) #print a\n b\n c\n d\n e
for eachiter2 in iter2:
print(eachiter2) #print a\n b\n c\n d\n e
for eachiter3 in iter3:
print(eachiter3) #print a\n b\n c\n d\n e
#we use multiple assignment to acquire the three iterators that are returned from tee. Finally we loop over each of the iterators and print out their contents. The content are the same.
colors = ["red","orange","yellow","green","blue"]
alphacolors1, betacolors2 = tee(colors,2)
for eachalphacolors1 in alphacolors1:
print(eachalphacolors1) #print red\n orange\n yellow\n green\n blue
for eachbetacolors2 in betacolors2:
print(eachbetacolors2) #print red\n orange\n yellow\n green\n blue
#The **zip_longest** iterator can be used to zip two iterables together. If the iterables don’t happen to be the same length, then you can also pass in a **fillvalue**. Makes an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration stops when the longest iterable is exhausted. zip_longest(*iterables, fillvalue=None).
from itertools import zip_longest
for item in zip_longest("abcd","xy",fillvalue="blank"):
print(item) #print ('a', 'x')\n ('b', 'y')\n ('c', 'blank')\n ('d', 'blank')
for item in zip_longest("abcdefg","vwxy", "quick",fillvalue="blank"):
print(item) #print ('a', 'v', 'q')\n ('b', 'w', 'u')\n ('c', 'x', 'i')\n ('d', 'y', 'c')\n ('e', 'blank', 'k')\n ('f', 'blank', 'blank')\n ('g', 'blank', 'blank')
colors = ["red","orange","yellow","green","blue"]
data = [1,2,3,4,5,6,7,8,9,10]
for eachcolorsdata in zip_longest(colors, data, fillvalue=None):
print(eachcolorsdata) #print ('red', 1)\n ('orange', 2)\n ('yellow', 3)\n ('green', 4)\n ('blue', 5)\n \n (None, 6)\n (None, 7)\n (None, 8)\n (None, 9)\n (None, 10)
print(list(zip(colors,data))) #print [('red', 1), ('orange', 2), ('yellow', 3), ('green', 4), ('blue', 5)]
#The built-in zip() function, which takes any number of iterables as arguments and returns an iterator over tuples of their corresponding elements. Lists are iterables which means they can return their elements one at a time. zip() function aggregates the results into tuples.
print(list(zip([1, 2, 3],["a","b","c"]))) #print [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(map(len,["abc","de","fghi"]))) #print [3, 2, 4]
from itertools import zip_longest
x = [1, 2, 3, 4, 5]
y = ["a","b","c"]
print(list(zip(x,y))) #print [(1, 'a'), (2, 'b'), (3, 'c')]
print(list(zip_longest(x,y))) #print [(1, 'a'), (2, 'b'), (3, 'c'), (4, None), (5, None)]
def grouper(inputlist, n, fillvalue=None):
print(inputlist) #print [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
iters = [iter(inputlist)] * n
print(iter(inputlist)) #print <list_iterator object at 0x7fc62ddb5780>
print(iters) #print [<list_iterator object at 0x7f3168c5b7f0>, <list_iterator object at 0x7f3168c5b7f0>, <list_iterator object at 0x7f3168c5b7f0>, <list_iterator object at 0x7f3168c5b7f0>]
print(list(iters)) #print [<list_iterator object at 0x7fbcb4c897f0>, <list_iterator object at 0x7fbcb4c897f0>, <list_iterator object at 0x7fbcb4c897f0>, <list_iterator object at 0x7fbcb4c897f0>]
print([iter(inputlist)] * n) #print [<list_iterator object at 0x7fb99c9e6748>, <list_iterator object at 0x7fb99c9e6748>, <list_iterator object at 0x7fb99c9e6748>, <list_iterator object at 0x7fb99c9e6748>]
print((inputlist)*n) #print [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
return zip_longest(*iters, fillvalue=fillvalue)
numberlist = [1,2,3,4,5,6,7,8,9,10]
#print(grouper(numberlist,4)) #print <itertools.zip_longest object at 0x7f422d6b9d18>
print(list(grouper(numberlist,4))) #print [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, None, None)]
#group by https://stackoverflow.com/questions/773/how-do-i-use-pythons-itertools-groupby
#data must be sorted first.
from itertools import groupby
things = [("vehicle", "speed boat"), ("animal", "duck"), ("plant", "cactus"), ("animal", "bear"), ("vehicle", "school bus")]
print(things) #print [('vehicle', 'speed boat'), ('animal', 'duck'), ('plant', 'cactus'), ('animal', 'bear'), ('vehicle', 'school bus')]
things.sort() #data must be sorted first.
print(things) #print [('animal', 'bear'), ('animal', 'duck'), ('plant', 'cactus'), ('vehicle', 'school bus'), ('vehicle', 'speed boat')]
for key, group in groupby(things, lambda x: x[0]):
print("key {}. group{}".format(key, group))
for thing in group:
print("thing[0] {}".format(thing[0]))
print("A {} is a {}".format(thing[1], key))
print("A {} is a {}".format(thing[1], thing[0]))
'''
key animal. group<itertools._grouper object at 0x7f2a1ca90518>
thing[0] animal
A bear is a animal
A bear is a animal
thing[0] animal
A duck is a animal
A duck is a animal
key plant. group<itertools._grouper object at 0x7f2a1e786908>
thing[0] plant
A cactus is a plant
A cactus is a plant
key vehicle. group<itertools._grouper object at 0x7f2a1e786ac8>
thing[0] vehicle
A school bus is a vehicle
A school bus is a vehicle
thing[0] vehicle
A speed boat is a vehicle
A speed boat is a vehicle
'''
#things is a list of tuples where the first item in each tuple is the group the second item belongs to.
#The groupby() function takes two arguments: (1) the data to group things and (2) the function to group it with lambda x: x[0]. lambda x: x[0] tells groupby() to use the first item in each tuple as the grouping key.
#The first for statement groupby returns three (key, group iterator) pairs - once for each unique key which are animal, plant, and vehicle. You can use the returned iterator to iterate over each individual item in that group.
for key, group in groupby(things, lambda x: x[0]):
listofthings = " and ".join([thing[1] for thing in group])
print(key + "s: "+listofthings+".")
'''
animals: bear and duck.
plants: cactus.
vehicles: school bus and speed boat.
'''
#itertools.groupby is a tool for grouping items.
for key, group in groupby("AAAABBBCCDAABBB"):
print(key)
print(group)
#print(key+":",", ".join(list(group)))
listgroupvariable = list(group)
print(key+":",", ".join(listgroupvariable))
print(listgroupvariable)
'''
A
<itertools._grouper object at 0x7fb35a221518>
A: A, A, A, A
['A', 'A', 'A', 'A']
B
<itertools._grouper object at 0x7fb35a2215c0>
B: B, B, B
['B', 'B', 'B']
C
<itertools._grouper object at 0x7fb35bf17908>
C: C, C
['C', 'C']
D
<itertools._grouper object at 0x7fb35a221518>
D: D
['D']
A
<itertools._grouper object at 0x7fb35bf17908>
A: A, A
['A', 'A']
B
<itertools._grouper object at 0x7fb35a2215c0>
B: B, B, B
['B', 'B', 'B']
'''
letters = ["AAAABBBCCDAABBB"]
print(letters) #print ['AAAABBBCCDAABBB']
lettersstring = "".join(letters)
print(lettersstring) #print AAAABBBCCDAABBB
print(type(lettersstring)) #print <class 'str'>
letterslist = [x for x in lettersstring]
print(letterslist) #print ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'A', 'A', 'B', 'B', 'B']
letterslist.sort()
print(letterslist) #print ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'C', 'C', 'D']
for key, group in groupby(letterslist):
print(key)
print(group)
#print(key+":",", ".join(list(group)))
listgroupvariable = list(group)
print(key+":",", ".join(listgroupvariable))
print(listgroupvariable)
'''
A
<itertools._grouper object at 0x7f69b62265c0>
A: A, A, A, A, A, A
['A', 'A', 'A', 'A', 'A', 'A']
B
<itertools._grouper object at 0x7f69b7f237f0>
B: B, B, B, B, B, B
['B', 'B', 'B', 'B', 'B', 'B']
C
<itertools._grouper object at 0x7f69b62265c0>
C: C, C
['C', 'C']
D
<itertools._grouper object at 0x7f69b7f237f0>
D: D
['D']
'''
letters = ["AAAABBBCCDAABBB"]
numberofrepetitions = [(key,len(list(group))) for key, group in groupby(letters)]
print(numberofrepetitions) #print [('AAAABBBCCDAABBB', 1)] |
import numbers
x = 4
x2 = 4.1
love = isinstance(x, numbers.Integral)
print(love) #print True
love = isinstance(x2, numbers.Integral)
print(love) #print False
love = isinstance(3, int)
print(love,"no numbers.Integral") #print True
love = isinstance(x, int)
print(love,"no numbers.Integral") #print True
love = isinstance(x2, int)
print(love,"no numbers.Integral") #print False
fivex = 5
fiveonex = 5.1
fivezerox = 5.0
#print(fivex.is_integer()) #error message
#print(int(fivex).is_integer()) #error message
print(float(fivex).is_integer()) #print True
print(float(fiveonex).is_integer()) #print False
print(float(fivezerox).is_integer()) #print True
def isinteger(variable):
if type(variable) == int:
print("Is integer")
else:
print("Is not integer")
isinteger(fivex) #return Is integer
isinteger(fiveonex) #return Is not Integer
#Do not use type(). It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism.
|
#How to easily convert a list to a string for display
#https://www.decalage.info/en/python/print_list
mylist = ["spam","ham","eggs"]
print(", ".join(mylist)) #print spam, ham, eggs
print("\n".join(mylist)) #print spam\n ham\n eggs
print(" is from the cat in the hat\n".join(mylist)) #print spam is from the cat in the hat\n ham is from the cat in the hat\n eggs
#to obtain a comma-separated string
integerslist = [80, 443, 8080, 8081]
print(integerslist) #print [80, 443, 8080, 8081]
print(str(integerslist).strip("[]")) #print 80, 443, 8080, 8081
print(str(integerslist)[1:-1]) #print 80, 443, 8080, 8081
whatisthis = str(integerslist).strip("[]")
print(type(whatisthis)) #print string
print(whatisthis) #print 80, 443, 8080, 8081
print("\n")
#you may use map() to convert each item in the list to a string, and then join them
integerslist = [80, 443, 8080, 8081]
print(", ".join(map(str, integerslist))) #print 80, 443, 8080, 8081
print("\n".join(map(str, integerslist))) #print 80\n 443\n 8080\n 8081
print("".join(map(str, integerslist))) #print 8044380808081
#extract values from a dictionary to one string
planetdictionarycomprehension = {'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'M', 'Jupiter': 'J', 'Saturn': 'S', 'Uranus': 'U', 'Neptune': 'N'}
print(" ".join(planetdictionarycomprehension.values())) #print M V E M J S U N |
#Finding the index of an item given a list
#https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python
thelist = ["foo","bar","baz","bar"]
print(thelist.index("bar")) #print 1. .index() returns only the first element which matches in the list. ValueError appears if the target is not found. .index(value, [start, [stop]])
thelist2 = ["foo","bar","baz","bar","bear","cat","nat","bar"]
print(thelist2.index("bar", 4,len(thelist2))) #print 7
thelist3 = ["foo","bar","baz","bar","bear","cat","nat","bar","pin","fan"]
for i, j in enumerate(thelist3): #Useful than index if there are duplicates. index() only returns the first occurrence, while enumerate returns all occurrences.
if j == "bar":
print(i) #print 1\n 3\n 7\n
#it appears numpy works, too.
import numpy as np
array = [1,2,1,3,4,5,1]
item = 1
nparray = np.array(array)
itemindex = np.where(nparray==item)
print(itemindex) #print (array([0, 2, 6]),)
thelist4 = ["foo","bar","baz","bar","bear","cat","nat","bar","pin","fan"]
item = "bar"
nparray = np.array(thelist4)
itemindex = np.where(nparray==item)
print(itemindex) #print (array([1, 3, 7]),)
print(itemindex[0]) #print [1, 3, 7]
print(itemindex[0][1]) #print 3
foritemindex = itemindex[0]
for n in range(0,len(foritemindex)):
print(foritemindex[n]) #print 1\n 3\n 7\n
print("\n")
#05/24/2018 take two
animallist = ["dog","cat","cow","bird","mouse","bear","rabbit"]
findanimal = "bear"
if findanimal in animallist:
print(findanimal+" exists") #print bear exists
print(animallist.index(findanimal)) #print 5
else:
print(None)
def findindexes(value, indexlist):
indicesinindexlist = []
indexnumber = -1
while True:
try:
print("value before: ",value)
print("indexnumber before: ",indexnumber)
print(indicesinindexlist)
indexnumber = indexlist.index(value, indexnumber+1) #.index(value, [start, [stop]])
print("value after: ",value)
print("indexnumber after: ",indexnumber)
indicesinindexlist.append(indexnumber) #appending the indexnumber to list indicesinindexlist
print(indicesinindexlist)
except ValueError:
print("Let's break")
break
return indicesinindexlist
print(findindexes("mouse",["dog","cat","cow","bird","mouse","bear","rabbit"]))
print(findindexes("cat",["dog","cat","cow","bird","mouse","bear","rabbit"]))
print(findindexes("cow",["cow","cat","cow","bird","mouse","cow","rabbit"])) #print [0, 2, 5]
print("\n")
#side note on .index()
thelist = []
templist = ["baseball","basketball","football","hockey"]
indexnumber = templist.index("football",2) #start search index position 2
thelist.append(indexnumber) #appending the indexnumber to list thelist
print(thelist) #print [2]
def findindexes2(value, indexlist):
try:
indexelement = indexlist.index(value)
return indexelement
except ValueError:
print(None)
print(findindexes2("mouse",["dog","cat","cow","bird","mouse","bear","rabbit"])) #print 4
print(findindexes2("cow",["dog","cat","cow","bird","mouse","bear","rabbit"])) #print 2
print(findindexes2("cow",["cow","cat","cow","bird","mouse","cow","rabbit"])) #print 0 #findindexes2 function doesn't work multiple items
print("\n")
approvedsums = [5, 11, 19]
for eachnumber in range(5,20):
try:
print(isinstance(approvedsums.index(eachnumber),int) == True)
print(eachnumber,"in list")
except ValueError:
print(eachnumber,"not in list")
continue
for eachnumber in range(5,20):
sums = eachnumber + 1
try:
print(isinstance(approvedsums.index(sums),int) == True)
print(sums,"sums in list")
except ValueError:
print(sums,"sums not in list")
continue
print("\n")
mylist = ["blue","black","white","red","brown","orange","yellow"]
myterm = "white"
#get the index position for myterm
for i in range(0,len(mylist)):
if mylist[i]==myterm:
print(i) #print 2
#get the value or item from mylist
for eachmylist in mylist:
if eachmylist==myterm:
print(eachmylist) #print white
#get the first value or item from mylist only
print(mylist.index(myterm)) #print 2
#also
if myterm in mylist:
print(mylist.index(myterm)) #print 2
else:
None
|
from map import Map
import math
import pygame as pg
from time import sleep
from datetime import datetime
from collections import defaultdict
WALL_HEIGHT = 300
PLAYER_HEIGHT = 32
FOV = math.pi / 2
W = 600
H = 600
VIEW_RANGE = 20
EMPTY = float('inf')
CIRCLE = 2 * math.pi
class Player(object):
"""Handles the player's position, rotation, and control."""
def __init__(self, x, y, direction):
"""
The arguments x and y are floating points. Anything between zero
and the game map size is on our generated map.
Choosing a point outside this range ensures our player doesn't spawn
inside a wall. The direction argument is the initial angle (given in
radians) of the player.
This class was blatantley copied from: https://github.com/Mekire/pygame-raycasting-experiment
"""
self.keys = defaultdict(list)
self.x = x
self.y = y
self.direction = direction
self.fov = FOV
self.view = VIEW_RANGE
self.speed = 4 # Map cells per second.
self.rotate_speed = CIRCLE * 2 / 3 # 180 degrees in a second.
def rotate(self, angle):
"""Change the player's direction when appropriate key is pressed."""
self.direction = (self.direction + angle + CIRCLE) % CIRCLE
def walk(self, distance, game_map):
"""
Calculate the player's next position, and move if he will
not end up inside a wall.
"""
dx = distance * math.sin(self.direction)
dy = distance * math.cos(self.direction)
map_x = (math.floor(self.x + dx), math.floor(self.y))
if game_map.get(map_x, 1) <= 0:
self.x += dx
map_y = (math.floor(self.x), math.floor(self.y + dy))
if game_map.get(map_y, 1) <= 0:
self.y += dy
def update(self, dt, game_map):
"""Execute movement functions if the appropriate key is pressed."""
if self.keys[pg.K_RIGHT]:
self.rotate(-self.rotate_speed * dt)
if self.keys[pg.K_LEFT]:
self.rotate(self.rotate_speed * dt)
if self.keys[pg.K_UP]:
self.walk(self.speed * dt, game_map)
if self.keys[pg.K_DOWN]:
self.walk(-self.speed * dt, game_map)
class Raycast:
''' A class to handle ray casting, and the required calculations.'''
def __init__(self, width, height):
''' initialize the class with width and height.'''
self.width = width
self.height = height
def cast_rays(self, player, map):
''' "Casts" rays and returns the distances from walls in the map as an array.
Rays are calculated based on player's direction, where an angle of 0 is facing down.'''
step_size = player.fov / (self.width - 1)
walls = []
# Calculate starting angle based on player's facing direction and FOV
angle = (player.direction - player.fov / 2 + CIRCLE) % CIRCLE
# For each pixel in width
for _ in range(self.width):
# Get the distance from the wall at given angle
dist = self.cast_ray((player.x, player.y), angle, map, player.view)
# Fix the bobeye effect based on the player's angle and append it.
walls.append((dist[0] * math.cos(abs(player.direction - angle)), dist[1]))
# Advance the angle one tick.
angle = (angle + step_size) % CIRCLE
return walls
def cast_ray(self, start, angle, map, max_distance):
''' Cast an individual ray from start position at given angle.
Return the distance from the closest wall.
Return float('inf') if no wall is found with max distance'''
def get_vertical(start, angle, map):
x_orig, y_orig = start
# Will be positive for angle < pi/2 or angle > 3pi / 2
ydelta = math.cos(angle)
if ydelta > 0:
y_next = math.ceil(y_orig)
y_step = 1
dist_multiplier = 1 # Used to flip the sign of distance calculations
else:
y_next = math.floor(y_orig) - 0.001
y_step = -1
dist_multiplier = -1 # Used to flip the sign of distance calculations
# Calculate next x, knowing that tan(angle) = dx-px / dy-py
x_next = x_orig + (y_next - y_orig) * math.tan(angle)
# Calculate step of x the same way.
x_step = y_step * math.tan(angle)
for _ in range(max_distance):
# Get the tile at the given location (The floor of x and y)
# Return a wall if nothing is found, to create an artifical border
tile = map.get((math.floor(x_next), math.floor(y_next)), 1)
if tile:
# Get the length of the y perpendicular
ydist = abs(y_next - y_orig)
# Calculate distance using cos(angle).
# Using the dist multiplier to correct the sign
return ydist * dist_multiplier / math.cos(angle)
# Move to the next vertical intersection.
x_next += x_step
y_next += y_step
# if no wall was found in range, return infinity
return float('inf')
def get_horizontal(start, angle, map):
x_orig, y_orig = start
#print('checking horizontally from ', x_orig, y_orig, 'at', angle*180/math.pi)
# Will be positive for angle < pi/2 or angle > 3pi / 2
xdelta = math.sin(angle)
if xdelta > 0:
x_next = math.ceil(x_orig)
x_step = 1
dist_multiplier = 1 # Used to flip the sign of distance calculations
else:
x_next = math.floor(x_orig) - 0.001
x_step = -1
dist_multiplier = -1 # Used to flip the sign of distance calculations
# Calculate next y, knowing that tan(angle) = dx-px / dy-py
y_next = y_orig + (x_next - x_orig) / math.tan(angle)
# Calculate step of y the same way.
y_step = x_step / math.tan(angle)
for _ in range(max_distance):
# Get the tile at the given location (The floor of x and y)
# Return a wall if nothing is found, to create an artifical border
tile = map.get((math.floor(x_next), math.floor(y_next)), 1)
if tile:
# Get the length of the y perpendicular
xdist = abs(x_next - x_orig)
# Calculate distance using cos(angle).
# Using the dist multiplier to correct the sign
return xdist * dist_multiplier / math.sin(angle)
# Move to the next vertical intersection.
x_next += x_step
y_next += y_step
# if no wall was found in range, return infinity
return float('inf')
vertical = (get_vertical(start, angle, map), 0)
horizontal = (get_horizontal(start, angle, map), 1)
# Return the minimum distance
#input()
return min(vertical, horizontal)
def pygame_draw(screen, dists):
screen.fill((0, 0, 0))
floor = pg.Rect(0, H/2, W, H/2)
pg.draw.rect(screen, (100, 100, 100), floor)
width = 1
base_alpha = 50
color = (220, 210, 255)
for idx, dist in enumerate(dists):
if dist[0] == float('inf'):
continue
z = max(dist[0], WALL_HEIGHT / H)
wall_height = WALL_HEIGHT / (z)
wall_alpha = min(250, base_alpha * (dist[1] + dist[0]/2 ))
top = H / 2 - wall_height / 2
scale_rect = pg.Rect(W - idx, top, width, wall_height)
next_color = tuple(max(0, i - wall_alpha) for i in color)
pg.draw.rect(screen, next_color , scale_rect)
pg.display.flip()
def main():
pg.init()
screen = pg.display.set_mode((W, H))
map = Map.Random(20, 20, 0.3, (1, 1))
p = Player(*map.start, direction=0)
world = Raycast(W, H)
map.pprint()
clock = pg.time.Clock()
p.direction = math.pi
a = datetime.now()
for _ in range(600):
dt = clock.tick() / 1000
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
elif event.type == pg.KEYDOWN:
p.keys[event.key] = True
elif event.type == pg.KEYUP:
p.keys[event.key] = False
heights = world.cast_rays(p, map)
p.update(dt, map)
pygame_draw(screen, heights)
#sleep(10)
print (datetime.now() - a)
if __name__ == '__main__':
main()
pg.quit()
|
#총합
userinput=input("숫자를넣어주세요:")
total=0
numbers=userinput.split(',')
for x in numbers:
total+=int(x)
print(total) |
class Node:
def __init__(self, item, left=None, right=None):
self.item = item
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = None
def preorder(self, n):
if n != None:
print(str(n.item), ' ', end='')
if n.left:
self.preorder(n.left)
if n.right:
self.preorder(n.right)
def inorder(self, n):
if n != None:
if n.left:
self.inorder(n.left)
print(str(n.item), ' ', end='')
if n.right:
self.inorder(n.right)
def postorder(self, n):
if n != None:
if n.left:
self.postorder(n.left)
if n.right:
self.postorder(n.right)
print(str(n.item), ' ', end='')
def levelorder(self, root):
q = []
q.append(root)
while len(q) != 0:
t = q.pop(0)
print(str(t.item), ' ', end='')
if t.left != None:
q.append(t.left)
if t.right != None:
q.append(t.right)
def height(self, root):
if root == None:
return 0
return max(self.height(root.left), self.height(root.right)) + 1
t = BinaryTree()
n1 = Node(100)
n2 = Node(200)
n3 = Node(300)
n4 = Node(400)
n5 = Node(500)
n6 = Node(600)
n7 = Node(700)
n8 = Node(800)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
n3.left = n6
n3.right = n7
n4.left = n8
t.root = n1
print('트리 높이 =', t.height(t.root))
print('전위순회:\t', end='')
t.preorder(t.root)
print('\n중위순회:\t', end='')
t.inorder(t.root)
print('\n후위순회:\t', end='')
t.postorder(t.root)
print('\n레벨순회:\t', end='')
t.levelorder(t.root)
|
import ast
def solution(s):
s = ast.literal_eval(s.replace('{', '[').replace('}', ']'))
s.sort(key=lambda x: len(x))
s = list(map(lambda x: set(x), s))
answer = list()
temp = set()
for i in s:
answer.append(i.difference(temp).pop())
temp = i
return answer
_s = "{{2},{2,1},{2,1,3},{2,1,3,4}}"
# _s = "{{1,2,3},{2,1},{1,2,4,3},{2}}"
# _s = "{{20,111},{111}}"
# _s = "{{123}}"
# _s = "{{4,2,3},{3},{2,3,4,1},{2,3}}"
print(solution(_s))
|
from collections import deque
'''
Python3 implementation of unweighted directed graph data type
'''
class Digraph():
def __init__(self, V):
self._V = V # Number of vertices in the graph
self._E = 0 # Number of edges in the graph
self.adj = [[] for _ in range(0, V)] # Adjacency list setup
def __str__(self):
s = f'{self.V} vertices, {self.E} edges \n'
for v in range(0, self.V):
s += f'{v}: '
for w in self.adj[v]:
s += f'{w} '
s += '\n'
return s
@property
def V(self):
return self._V
@V.setter
def V(self, V):
self._V = V
@property
def E(self):
return self._E
@E.setter
def E(self, E):
self._E = E
def add_edge(self, v, w):
'''
Adds a directed edge v->w to the digraph
Parameters:
v Int integer representing from vertex
w Int integer representing to vertex
Return:
void
'''
self.adj[v].append(w)
self.E += 1
def reverse(self):
'''
Returns a copy of the graph with all edges reversed
Return:
Digraph Reversed digraph
'''
R = Digraph(self.V)
for v in range(0, self.V):
for w in self.adj[v]:
R.add_edge(w, v)
return R
class DirectedDFS():
def __init__(self, G, sources):
self.G = G # A Digraph
self.sources = sources # A list of sources
self._marked = [False for v in range(G.V)]
for s in sources:
if not self.is_marked(s):
self._dfs(G, s)
for v in range(self.G.V):
if self.is_marked(v):
print(f'{v} ')
def _dfs(self, G, v):
self._marked[v] = True
for w in G.adj[v]:
if not self._marked[w]:
self._dfs(G, w)
def is_marked(self, v):
return self._marked[v]
class DirectedCycle():
def __init__(self, G):
self.on_stack = [False for v in range(G.V)]
self.edge_to = [v for v in range(G.V)]
self.marked = [False for v in range(G.V)]
self._cycle = []
for v in range(G.V):
if not self.marked[v]:
self._dfs(G, v)
def _dfs(self, G, v):
self.on_stack[v] = True
self.marked[v] = True
for w in G.adj[v]:
if self.has_cycle():
return
elif not self.marked[w]:
self.edge_to[w] = v
self._dfs(G, w)
elif self.on_stack[w]:
x = v
while x != w:
self._cycle.append(x)
x = self.edge_to[x]
self._cycle.append(w)
self._cycle.append(v)
self.on_stack[v] = False
def has_cycle(self):
return len(self._cycle) > 0
@property
def cycle(self):
return self._cycle
class DepthFirstOrder():
def __init__(self, G):
self._pre = deque()
self._post = deque()
self._reverse_post = deque()
self.marked = [False for v in range(G.V)]
for v in range(G.V):
if not self.marked[v]:
self._dfs(G, v)
def _dfs(self, G, v):
self._pre.appendleft(v)
self.marked[v] = True
for w in G.adj[v]:
if not self.marked[w]:
self._dfs(G, w)
self._post.appendleft(v)
self.reverse_post.append(v)
@property
def pre(self):
return list(self._pre)
@property
def post(self):
return list(self._post)
@property
def reverse_post(self):
return list(self._reverse_post)
class Topological():
def __init__(self, G):
self._order = []
cycle_finder = DirectedCycle(G)
if not cycle_finder.has_cycle():
dfs = DepthFirstOrder(G)
self._order = dfs.reverse_post
def order(self):
return self._order
def is_DAG(self):
return len(self._order) > 0
class KosarajuSCC():
''' Kosaraju's algo for computing strongly connected components '''
def __init__(self, G):
self._marked = [False for v in range(G.V)]
self._id = [v for v in range(G.V)]
self._count = 0
order = DepthFirstOrder(G.reverse())
for s in order.reverse_post:
if not self._marked[s]:
self._dfs(G, s)
self._count += 1
def _dfs(self, G, v):
self._marked[v] = True
self._id[v] = self._count
for w in G.adj[v]:
if not self._marked[w]:
self._dfs(G, w)
def strongly_connected(self, v, w):
return self._id[v] == self._id[w]
def identifier(self, v):
return self._id[v]
@property
def count(self):
return self._count
class Hamiltonian():
''' Tests for Hamiltonian Path by taking the topological order and checking
to see if edges exist for each consecutive pair
'''
def __init__(self, G):
self.path = True
topo = Topological(G)
if topo.is_DAG():
order = topo.order()
for idx, v in enumerate(order):
if (idx == len(order) - 1):
continue
if order[idx+1] not in G.adj(v):
self.path = False
else:
self.path = False
def exist(self):
return self.path
|
num_list = [1, 2, 3, 4, 5, -1]
def smallest_num(list):
small_num = list[0]
for num in list:
if num < small_num:
small_num = num
return small_num
print(smallest_num(num_list))
|
# Author --dahai--
# 编写一个根据提示,猜成语名字的小程序
import riddleMessage as ridMess
welcome_info = '''
=========================================
【欢迎小朋友参加根据信息,猜语言故事的小游戏】
=========================================
计分规则:
1. 如果根据一条信息,猜对答案,计4分;
2. 如果根据二条信息,猜对答案,计4分;
3. 如果根据三条信息,猜对答案,计4分;
4. 如果根据四条信息,猜对答案,计4分;
5. 如果没有猜到答案,计0分;
'''
def guess_riddle(guessCount):
score = 0
riddleMessage = ridMess.riddle_list[guess_count]
# for line in riddleMessage:
# print(line)
for i in range(1,5):
for j in range(i):
print("%s. %s" %(j+1,riddleMessage[j]))
ans_c = input("请输入你的答案:")
if ans_c == riddleMessage[4]:
print("你太棒了,答对了...")
score = 4 - j
return score
print("你没有答对这个题目,答案是:%s" %riddleMessage[4])
return score
guess_count = 0 # 猜题计数
guess_score = []
guess_score_totle = 0
if __name__ == "__main__":
print(welcome_info)
# guess_total = ridMess.readRiddleMessageFromFile()
ans = input("你准备好答题了吗?(Y or N):")
if ans == 'Y' or ans == 'y':
guess_total = ridMess.riddle_total_cnt
for i in range(guess_total):
print("本次答题总共有%s个谜语,现在开始第%s个谜语" %(guess_total,guess_count+1))
riddle_score = guess_riddle(guess_count)
guess_score_totle += riddle_score
guess_score.append(riddle_score)
print("\033[43:2m第%s个谜语,你得了%s分,共计%s分...\033[0m" %(guess_count+1,riddle_score,guess_score_totle))
guess_count += 1
print("共计%s分,你答题情况如下:" %guess_score_totle)
for index,i in enumerate(guess_score):
if i > 2:
print("第%s题: %s分" %(index, i))
else:
ridMess.colorPrint(("第%s题: %s分" %(index, i)),1)
else:
ridMess.colorPrint("你还没准备好答题,下次再来吧...",1)
|
"""
Following is a program that uses all of the insertion methods to create a linked list.
"""
class Node:
def __init__(self,value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self,new_value):
new_node = Node(new_value)
new_node.next = self.head
self.head = new_node
def insertAfter(self,prev_node,new_value):
if prev_node is None:
print("Previous node must be in LinkedList")
return
new_node = Node(new_value)
new_node.next = prev_node.next
prev_node.next = new_node
def append(self,new_value):
new_node = Node(new_value)
if self.head is None:
self.head = new_node
return
last = self.head
while(last.next):
last = last.next
last.next = new_node
def printlist(self):
temp = self.head
while(temp):
print(temp.value)
temp = temp.next
llist = LinkedList()
llist.append(6)
llist.push(7)
llist.push(1)
llist.append(4)
llist.insertAfter(llist.head.next,8)
llist.printlist()
|
"""
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.
Example 1:
Input: arr = [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
Example 2:
Input: arr = [2,2,2]
Output: 0
Explanation: There is no mountain.
"""
"""
Time Complexity: O(n) | Space Complexity: O(1)
"""
class Solution:
def longestMountain(self, arr: List[int]) -> int:
cnt = 0
for peak in range(1,len(arr) - 1):
if arr[peak - 1] < arr[peak] > arr[peak + 1]:
left = right = peak
while left > 0 and arr[left] > arr[left-1]:
left -= 1
while right + 1 < len(arr) and arr[right] > arr[right+1]:
right += 1
cnt = max(cnt,(right-left+1))
return cnt
|
"""
This program is to sort the arrays an n-D array (value of n given by the user) by the last index of each sub array within the array.
For Example;
n = 3
arr = [[1,5,1],[0,2,-1],[5,5,5,6]]
The output of the above example is;
[[0,2,-1],[1,5,1],[5,5,5,6]]
"""
#code
n = int(input('enter the number of arrays :'))
arr = []
a = []
for i in range(0,n):
a = list(input("enter : ").split(" "))
arr.append(a)
print("The array before sorting:",arr)
arr.sort(key=lambda x:x[-1]) #the code to sort the above array
print("The sorted array is:",arr)
|
def print_columns(columns):
print()
for index in range(3):
print(columns[0][index], columns[1][index], columns[2][index])
def read_columns(columns):
round_1_result = ""
for num1 in range(3):
for num2 in range(3):
round_1_result += round_1_result.join((columns[num1][num2]))
return round_1_result
def plaintext_into_columns(plaintext):
# Creation of empty columns
column_1 = []
column_2 = []
column_3 = []
#Remove spaces from the plaintext input
plaintext_spaceless = plaintext.replace(" ","")
# Add the plaintext to the columns
# string[start:stop:step] start position. end position. the increment
column_1 = [[letter] for letter in plaintext_spaceless[::3]]
column_2 = [[letter] for letter in plaintext_spaceless[1::3]]
column_3 = [[letter] for letter in plaintext_spaceless[2::3]]
#print(column_1, column_2, column_3)
# Add the columns into a list for ease of access when doing rounds
columns = [column_1, column_2, column_3]
return columns
def transposition(columns, round):
# Perform the first column transposition round
columns[0], columns[1], columns[2] = columns[round[0]-1], columns[round[1]-1], columns[round[2]-1]
return columns
def simple_columnar_transposition(plaintext):
# Random selection of columns for the rounds
round_1 = [2, 3, 1]
round_2 = [2, 3, 1]
# Write the plaintext into the columns
columns = plaintext_into_columns(plaintext)
# Perform the first column transposition round
columns = transposition(columns, round_1)
# Read in columns
round_1_result = read_columns(columns)
print(f"Result of round 1 of SCTTMR: {round_1_result}")
# Write the plaintext into the columns
columns = plaintext_into_columns(round_1_result)
# Perform the second column transposition round
columns = transposition(columns, round_2)
# Read in columns
round_2_result = read_columns(columns)
print(f"Result of round 2 of SCTTMR: {round_2_result}")
columns = shift_row(columns)
last_round_result = read_columns(columns)
print(f"Result of row shift: {last_round_result}")
return last_round_result
# Simple permutation
def shift_row(rows):
# First row is not altered.
# Second row is circular left shifted 1 byte
rows[1][0], rows[1][1], rows[1][2] = rows[1][1], rows[1][2], rows[1][0]
# Third row is circular left shifter 2 bytes
rows[2][0], rows[2][1], rows[2][2] = rows[2][2], rows[2][0], rows[2][1]
return rows
|
if __name__ == "__main__":
print("lets do some meth")
x = 1
y = 2
z = x + y
subtract = z - x
multiply = y * z
print("one plus 2 equals " + str(z))
print("z minus x equals" + str(subtract))
print("y times z equals " + str(multiply))
|
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
if len(word) == 0:
return 0
# Returns beginning index if "th" is found within word, else returns -1
th_index = word.find("th")
if th_index == -1:
return 0
else:
return 1 + count_th(word[th_index + 2:])
|
def Ans():
d = {} # dictionary
tem = {} # template
with open("Answer.txt") as f:
for line in f:
tem = line.split() # eachline is a tuple
d[tem[0]] = tem[1] # assign to the dictionary
#return value of the answer as array
arr = list(d.values())
return (arr)
# Mark : detemine the incorrect answer
#
def Mark(StdAns,A):
mark=0
trace = [] # arr contains position of incorrect ans and number of correct ans in last element
# arr=[incorrect ans,...., mark]
for i in range(0,20):
if str(StdAns[i].upper())==A[i]: # check ans
mark+=1
else:
trace.append(i+1)
trace.append(mark)
return trace
def getStdAns():
StdAns=[]
with open("Exam.txt") as f:
for line in f:
print('')
print(line) # display question
a=input("your answer: ") # get input
StdAns.append(a)
return StdAns
def Pass(m):
if (m>= 15):
print("congratulation! you Passed")
else:
print("you Failed!")
if __name__=="__main__":
choice=True
while choice:
arr= getStdAns()
Trace=Mark(arr, Ans())
mark=Trace[len(Trace)-1]
Pass(mark)
#print result:
print('your score: ',mark)
print("incorrect: ",end='')s
for i in range(0,len(Trace)-1):
print(Trace[i],end=', ')
print("",end='')
ch=input(("do u want try again? Yes/NO:"))
if ch== 'yes':
choice=True
else:
choice=False
|
def pr(pho):
for i in range(0,len(pho)):
print(str(dic(pho[i])),end="")
def dic(a):
if a=='A' or a=='B' or a=='C':
return 2
if a=='D' or a=='F' or a=='E':
return 3
if a=='G' or a=='H' or a=='I':
return 4
if a=='J' or a=='K' or a=='L':
return 5
if a=='M' or a=='N' or a=='O':
return 6
if a=='P' or a=='Q 'or a=='R' or a=='S':
return 7
if a=='T' or a=='U' or a=='V':
return 8
if a=='W' or a=='X' or a=='Y' or a=='Z':
return 9
else:
return a
def containDash(date):
return date.find("-")
if __name__=='__main__':
num=str(input("enter phone number XXX-XXX-XXXX:"))
if containDash!=-1 and len(num)==12:
pr(num)
else:
print("it's not a valid phonenumber")
|
def month(m):
if m=="01":
return "January"
if m=="02":
return "February"
if m=="03":
return "March"
if m=="04":
return "April"
if m=="05":
return "May"
if m=="06":
return "June"
if m=="07":
return "Junly"
if m=="08":
return "August"
if m=="09":
return "September"
if m=="10":
return "October"
if m=="11":
return "November"
if m=="01":
return "December"
def form(date):
d= date.strip().split("/")
print(month(d[1])+ " , "+d[0]+ " "+d[2])
def containSlash(date):
return date.find("/")
if __name__=='__main__':
d=input("date in the form mm/dd/yyyy:")
if(len(d)==10) and containSlash(d)!=-1 :
form(d)
else:
raise ValueError |
"""Unit test for readCIGAR.py"""
import readCIGAR
import unittest
class readCIGARBadInput(unittest.TestCase):
def testBadColumn(self):
"""read should fail with incorrect column count"""
self.assertRaises(readCIGAR.InvalidColumnCount, readCIGAR.read, 'test/test_bad_column_input1.txt')
def testBadStartingPosition(self):
"""read should fail with invalid starting position"""
self.assertRaises(readCIGAR.InvalidStartingPosition, readCIGAR.read, 'test/test_bad_startingposition_input1.txt')
def testEmptyInput(self):
"""read should fail if the input file is empty"""
self.assertRaises(readCIGAR.InvalidInputFile, readCIGAR.read, 'test/test_empty_input.txt')
if __name__ == "__main__":
unittest.main()
|
def ubah_jumlah(array_data1, array_data2):
id_item = input("Masukkan ID: ")
operasi_jumlah = int(input("Masukkan jumlah: "))
i = 0
check = False
for lines in array_data1:
if(lines[i] == id_item):
check = True
if(operasi_jumlah < 0):
check_validasi = lines[3] + operasi_jumlah
if(check_validasi < 0):
print("Jumlah dari barang tersebut kurang.")
else:
lines[3] = check_validasi
else:
lines[3] = lines[3] + operasi_jumlah
for lines in array_data2:
if(lines[i] == id_item):
check = True
if(operasi_jumlah < 0):
check_validasi = lines[3] + operasi_jumlah
if(check_validasi < 0):
print("Jumlah dari barang tersebut kurang.")
else:
lines[3] = check_validasi
else:
lines[3] = lines[3] + operasi_jumlah
if(check == False):
print("Maaf ID yang Anda input tidak terdaftar di sistem.")
return array_data1, array_data2
|
# F04 Cari Gadget Berdasarkan Tahun Ditemukan
def caritahun(gadget):
# Mencari gadget yang tahun ditemukannya yang cocok dengan spesifikasi tahun yang diinput.
# Output: (array of [string,string,integer,string,integer])
# KAMUS LOKAL
# VARIABEL
# Thn : integer (Input tahun ditemukannya gadget yang akan dicari.)
# Kateg : string (Input spesifikasi terhadap tahun input (lebih besar, lebih kecil, sama dengan, dll.))
# i,j,a : integer (Counter untuk iterasi.)
# HasilPencarian : Array (Array untuk menyimpan gadget yang tahun ditemukannya cocok dengan spesifikasi input.)
# ALGORITMA
HasilPencarian = [] # Array yang mengumpulkan yang akan di output.
while True:
try: # Pengecekan apakah tahun yang dimasukkan berupa integer.
Thn = int(input("Masukkan Tahun: "))
except ValueError:
print("Masukkan invalid. Masukkan yang benar.")
continue
Kateg = input("Masukkan kategori: ")
if Kateg == ">" or Kateg == "<" or Kateg == ">=" or Kateg == "<=" or Kateg == "=": # Pengecekan apakah input berupa kategori valid.
for i in range(len(gadget)):
for j in range(len(gadget[i])):
if j == 5 and Kateg == ">": # Pengelompokkan gadget berdasarkan spesifikasi yang diinput.
if Thn < int(gadget[i][j]):
HasilPencarian.append(gadget[i])
elif j == 5 and Kateg == "<":
if Thn > int(gadget[i][j]):
HasilPencarian.append(gadget[i])
elif j == 5 and Kateg == ">=":
if Thn <= int(gadget[i][j]):
HasilPencarian.append(gadget[i])
elif j == 5 and Kateg == "<=":
if Thn >= int(gadget[i][j]):
HasilPencarian.append(gadget[i])
elif j == 5 and Kateg == "=":
if Thn == int(gadget[i][j]):
HasilPencarian.append(gadget[i])
print()
print("Hasil pencarian:")
print()
if len(HasilPencarian) != 0: # Pengecekan apakah HasilPencarian kosong atau tidak.
for a in range(len(HasilPencarian)):
print("Nama : ", HasilPencarian[a][1])
print("Deskripsi : ", HasilPencarian[a][2])
print("Jumlah : ", HasilPencarian[a][3])
print("Rarity : ", HasilPencarian[a][4])
print("Tahun Ditemukan : ", HasilPencarian[a][5])
print()
break
else:
print("Tidak ada gadget yang ditemukan.")
break
else:
print("Masukkan invalid. Masukkan yang benar")
continue
|
import math
class Vector2(object):
def __init__(self, x, y):
def setval(name, value):
super(Vector2, self).__setattr__(name, value)
setval('x',x)
setval('y',y)
mag2 = self.x*self.x + self.y*self.y
theta = math.degrees(math.atan2(self.y,self.x))
if theta < -360 or theta > 360:
theta = theta % 360
if theta < 0:
theta = 360 + theta
setval('mag2',mag2)
setval('mag', math.sqrt(mag2))
setval('theta',theta)
def __str__(self):
return "<"+str(self.x)+", "+str(self.y)+">"
def __repr__(self):
return str(self)
def __setattr__(self, *args):
raise TypeError("Can't modify immutable vector")
__delattr__ = __setattr__
def __getitem__(self, key):
if key is 0:
return self.x
elif key is 1:
return self.y
elif key is "x":
return self.x
elif key is "y":
return self.y
def __len__(self):
return 2
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector2(self.x * other, self.y * other)
def __rmul__(self, other):
return self.__mul__(other)
def __div__(self,other):
return Vector2(self.x / other, self.y / other)
def __neg__(self, other):
return Vector2(-self.x, -self.y)
def __or__(self, other):
return self.magnitude
def __ror__(self,other):
return self.magnitude
def dot(v1, v2):
return v1.x*v2.x + v1.y*v2.y
def to(self, other):
return other-self
__iadd__ = __setattr__
__isub__ = __setattr__
__imul__ = __setattr__
__idiv__ = __setattr__
|
numberList = []
for i in range(0, 3):
numberList.append(int(input("Numero: ")))
for numbers in numberList:
print(numbers) |
def sumar_lista(lista):
suma = 0
for x in range(len(lista)):
suma = suma + lista[x]
return suma
def mayor_lista(lista):
may = lista[0]
for x in range(1,len(lista)):
if lista[x] > may:
may = lista[x]
return may
def menor_lista(lista):
men = lista[0]
for x in range(1,len(lista)):
if lista[x] < men:
men = lista[x]
return men
#bloque principal
lista_valores = [10, 56, 23, 120, 94]
print("la lista completa es: ")
print(lista_valores)
print("la suma de todos los valores es: ", sumar_lista(lista_valores))
print("el mayor elemento de la lista es: ", mayor_lista(lista_valores))
print("el menor elemento de la lista es: ", menor_lista(lista_valores))
|
def payment(bill, ppl):
"""
this is the function for determining how much each person pays.
args: bill(the total bill), ppl(number of people).
return = the individual payment per person
"""
try:
return round((bill/ppl),2)
except:
print("an error occured with the payment calculation")
def tip(bill, perc, ppl):
"""
this is the function for determmining the tip.
it also splits the tip over a group of ppl
args: bill(the total of bill), perc(the percentage of the tip to give), ppl(the number of people)
return = the individual payment per person
"""
try:
return round((bill * (perc/100.00)/ppl), 2)
except:
print("an error occured with the tip calculation")
def main():
"""this is the main function"""
print("how much is the bill ?")
while True:
try:
total_bill = float(raw_input(">>$"))
break
except:
print(" ")
print("must be a number value")
print(" ")
print(" ")
print "how many people ?"
while True:
try:
num_ppl = int(raw_input(">>"))
break
except:
print(" ")
print("must be a number value")
print(" ")
print(" ")
print "what percentage of tip"
while True:
try:
perc = int(raw_input(">> %"))
break
except:
print(" ")
print("must be a number value")
print(" ")
print(" ")
print("calculation payment")
bill_payment = payment(total_bill, num_ppl)
tip_payment = tip(bill, perc, num_ppl)
total_payment = float(bill_payment) + float(tip_payment)
print("each person pays $%s for the bill" % \str(bill_payment))
print("each person pays $%s for the tip" % \str(tip_payment))
print("which means each person will pay a total of %s" % \str(total_payment))
if __name__=='__main__':
main()
|
import operator
#get each word - turn to lower case (.lower())
#count duplicates of words
#dictionary {word: count, word2: count2}
#sort this based on most used word
#print the top 20 words
def sorted_dict(d, reverse = True):
return sorted(d.iteritems(), reverse = reverse, \
key = operator.itemgetter(1))
def rank_word_from_file(f):
"""
take in a file, then rank all the words within the file
args: a file
return: a dictionary of all the word as the key and the ranking as the value
"""
word_dict = {}
words = []
for line in f:
list_of_word = line.split()
for w in list_of_word:
word.append(w.lower())
for word in words:
if word_dict.has_key(word):
word_dict[word]+= 1
else:
word_dict[word] = 1
return word_dict
def main():
#title
print("the word game")
print("="*30)
print(" ")
#game setup
f = open('alice.txt', 'rU')
print("loading words...")
orig_ranked_word_dict = rank_word_from_file(f)
f.close()
print("loading complete")
print("game starting")
print(" ")
#game loop
while True: #loop for each game
#determine what the round limits is
while True:
try:
round_limit = int(input("choose game length, how many round?[enter a number larger then 0]:"))
if int(round_limit) <= 0:
print("answer must be more than 0, please try again")
print(" ")
else:
break
except:
print("an error occured, make sure you enter an integer")
print(" ")
#setup initial variables
point = [0,0]
cur_player = 1
cur_word = " "
cur_round = 1
round_over = False
#important create a copy of the dictionary
ranked_word_dict = orig_ranked_word_dict.copy()
while True: #loop for each round
print("round", cur_round)
print("player 1: %d", "player 2: %d" % (point[0], point[1]))
print(" ")
print(" ")
while True: #loop for each word
if len(cur_word) > 0:
print(" ")
print(" ")
print(" "*5) + 'Current string = %s' % cur_word
print(" ")
#get the new letter
new_letter = str(input("player %d, please enter a letter: " % cur_player))
if len(new_letter) > 1:
new_letter = new_letter[0]
#add it to the current word
cur_word = str(cur_word) + str(new_letter).lower()
#check if word in ranked word dict
potential_word = False
for key, value in ranked_word_dict.items()
#found = re.match((str(cur_word), str(key))
if len(cur_word) <= len(key) and str(cur_word)== str(key[:len(cur_word)]):
potential_word = True
if str(cur_word) == str(key) and len(cur_word) > 3:
round_over = True
round_points = value
del ranked_word_dict[key]
#check if the cur_word is not valid using the variable potential_word
if potential_word == False:
round_over = True
round_points = int(5)
print(" ")
print(" ")
print("%s - will not make valid word, player %d lost that round!!" % \
(cur_word, cur_player))
#check if round_over is true
if round_over:
#statement to determine list position of winning player
if cur_player == 2:
p = 0
winning_player = 1
else:
p = 1
winning_player = 2
#assign points to winning player
point[p] += round_points
print(" ")
print("!#YAH#!"*10)
print(" ")
cur_word = " "
#exit round
break
else:
#change the player
if cur_player == 1:
cur_player = 2
else:
cur_player = 1
#back inside of the rounds loop
if cur_round == round_limit:
print(" ")
print("round limit reached")
print(" ")
print("player 1: %d player 2: %d" % (points[0], points[1]))
print(" ")
print(" ")
if points[0] > points[1]:
print("player 1 wins!!!!")
elif point[0] < points[1]:
print("player 2 wins !!!")
else:
print("it's a tie!!!")
print(" ")
break
#back in the game loop
user_input = str(input("type 'q' to quit or <any key> to play again: "))
if user_input.lower() == 'q':
break
print(" ")
print(" ")
print("thank your playing")
if __name__== '__main__:
main()
|
class Student(object): # Make sure the class name is capitalized
"""
The first statement inside of class is the docstring and it documents
the program and explains what the class will do. The Student class will define:
StudentID, First Name, Last Name and Email as the attributes.
"""
# Classes can be used by using instantiation
# The object is the instance
logic = Student()
# Assign the values you wish to use
logic.studentID = ""
logic.firstname = ""
logic.lastname = ""
logic.email = ""
# reference the object by typing logic.(insert value like email here)
print logic.studentID
def student_info():
s = Student()
s.studentID = raw_input("Please enter your student id number: ")
s.firstname = raw_input("Please enter your first name: ")
s.lastname = raw_input("Please enter your last name: ")
s.email = raw_input("Please enter your email address: ")
return s
student1 = student_info()
print ("\n" + student1.studentID + " " + student1.firstname + " " + student1.lastname + " " + student1.email + "\n")
student2 = student_info()
print ("\n" + student2.studentID + " " + student2.firstname + " " + student2.lastname + " " + student2.email + "\n")
student3 = student_info()
print ("\n" + student3.studentID + " " + student3.firstname + " " + student3.lastname + " " + student3.email + "\n")
|
from tkinter import *
import tkinter.messagebox as mb
def say_hello():
mb.showinfo('挨拶', 'おはようございます')
def say_goodnight():
mb.showinfo('挨拶', 'おやすみなさい')
root = Tk()
root.title('挨拶')
desc_label = Label(text='以下のボタンを押してください')
desc_label.pack()
hello_button = Button(text='朝', width=8, height=1, command=say_hello)
hello_button.pack()
goodnight_button = Button(text='寝る前', width=8, height=1, command=say_goodnight)
goodnight_button.pack()
root.mainloop()
|
cat_name = []
while True:
print('猫{}の名前を入力してください。(終了するにはEnterキーだけ押してください)'.format(str(len(cat_name) + 1)))
name = input()
if name == "":
break
cat_name = cat_name + [name]
print("猫の名前は次の通り:")
for name in cat_name:
print(" " + name)
|
#!/usr/bin/python3
# 画面に300本の縦線を引く
#
# グラフィックライブラリを取り込む
from tkinter import*
# 画面の初期化
w = Canvas(Tk(), width=900, height=400)
w.pack()
for i in range(300):
x = i * 3
w.create_line(x, 0, x, 400, fill="#FF0000")
mainloop()
|
import sys
sys.path.append('../linked_list')
from linked_list import LinkedList
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
#adding items
def enqueue(self, item):
self.storage.add_to_tail(item)
self.size += 1
#deleting items
def dequeue(self):
# is a node in storage?
if self.storage.head == None:
return None
else:
prev_head = self.storage.head.value
self.storage.remove_head()
return prev_head
#size of
def len(self):
current_head = self.storage.head
if current_head == None:
self.size = 0
return self.size
if current_head.get_next() == None:
self.size = 1
return self.size
else:
count = 1
while current_head.get_next() != None:
count += 1
current_head = current_head.get_next()
self.size = count
return self.size
return self.size
|
import datefinder
# function to get the date of birth from the desciption
def get_birth_date(description):
matches = list(datefinder.find_dates(description))
if len(matches) > 0:
date = matches[0]
return date
else:
return ('undefined') |
#Stephen Wang
#Math Modeling Project 3, Homework Question 1
import math
decimal = 1
ans = 0
digit = 0
floor = 0
unit = 0
remainder = -1
visitednum = []
saveddigits = []
print("Enter a fraction in the form of A/B")
numerator = int(input("Enter your numerator: "))
denominator = int(input("Enter your denominator: "))
repeatedindex = 0
numofrepeateddigits = 0
firstTime = True
while remainder != 0:
if numerator > denominator:
floor = math.floor(numerator/denominator)
ans = ans + floor * decimal
if not firstTime:
saveddigits.append(floor)
digit += 1
else:
firstTime = False
unit = floor
remainder = numerator%denominator
if remainder in visitednum:
repeatedindex = visitednum.index(remainder)
numofrepeateddigits = len(visitednum) - repeatedindex
print('Finished!')
break
visitednum.append(remainder)
numerator = remainder * 10
decimal = decimal * 0.1
else:
if firstTime:
firstTime = False
visitednum.append(numerator)
if decimal < 1.0:
saveddigits.append(0)
numerator = numerator*10
decimal = decimal * 0.1
if remainder != 0:
print('')
print("# of repeating digits: ", numofrepeateddigits)
print("# of non-repeating digits: ", len(visitednum)-numofrepeateddigits)
print("The answer is: ", unit,".", end="")
for i in range(len(saveddigits)):
print(saveddigits[i], end='')
for i in range(len(saveddigits)):
if i > repeatedindex-1:
print(saveddigits[i], end='')
print('...')
elif remainder == 0:
print('')
print("# of non-repeating digits: ", digit)
print("The answer is: ", unit,".", end="")
for i in range(len(saveddigits)):
print(saveddigits[i], end='')
|
#Stephen Wang
#Calc - 10 Essential Problems Project
#Summation calculator for select series
#Harmonic Series
terms = int(input('Enter a number of terms for summing the harmonic series: '))
#WARNING: It is advisable to enter terms not exceeding 100000
i = 0
harmonicseries = []
for i in range(1, terms+1):
harmonicseries.append(1/i)
print('')
print('Harmonic Series: ', sum(harmonicseries))
#Alternating Harmonic Series
j = 0
altharmonicseries = []
for j in range(1, terms+1):
altharmonicseries.append(((-1)**(j-1))*(1/j))
print('')
print('Alt Harmonic Series: ', sum(altharmonicseries))
print('ln 2 = ', 0.69314718056)
print('Error(Alt Series): ', ((0.69314718056-sum(altharmonicseries))/0.69314718056)*100, '%')
#as 'terms' goes to infinity, the error will go to 0 and so the alternating harmonic series converges to ln 2
|
#Stephen Wang
#Calculus Programming Week
#Newton's Method
from math import *
def f(x):
return (x**3)-7*(x**2)+(8*x)-3
order = int(input('Enter a number of iterations to estimate the point: '))
guess = float(input('Enter an initial point: '))
def NewtonMethod(a):
estimation = 0
for i in range(1, (order+1)):
estimation = (a - (f(a)/derivative(a)))
a = estimation
print(estimation)
def derivative(a):
h = 1/1000
rise = f(a+h)-f(a)
run = h
slope = rise/run
return slope
NewtonMethod(guess)
derivative(guess)
"""
Newton's Method: x(n+1) = xn - f(xn)/f'(xn)
"""
|
import random
class Game():
line = '-' * 60
def __init__(self):
self.player = None
self.rolls = None
def loop(self, p1, p2):
self.rolls = self.build_three_rolls()
cnt = 1
while cnt < 4:
p2.roll = self.random_roll()
p1.roll = self.get_roll(input("Select a roll: "))
print(f'{p1.name}-{p1.roll.name} vs. {p2.name}-{p2.roll.name}')
winner = self.get_winner(p1, p2)
if winner == p1:
p1.score += 1
print(f'{p1.name} wins this round!')
elif winner == p2:
p2.score += 1
print(f'{p2.name} wins this round!')
else:
print('Draw round!')
print()
cnt += 1
if p1.score > p2.score:
print(f'{p1.name} wins the match!')
elif p1.score < p2.score:
print(f'{p2.name} wins the match!')
else:
print("Match draw!")
def get_winner(self, p1, p2):
if p1.roll.name == p2.roll.lose:
return p1
elif p2.roll.name == p1.roll.lose:
return p2
else:
return None
def build_three_rolls(self):
return {'rock': Roll(name='rock', beat='scissor', lose='paper'),
'paper': Roll(name='paper', beat='rock', lose='scissor'),
'scissor': Roll(name='scissor', beat='paper', lose='scissor')}
def random_roll(self):
return random.choice(list(self.rolls.values()))
def get_roll(self, name):
while True:
if name in self.rolls:
return self.rolls[name]
elif name == 'random':
return self.random_roll()
else:
name = input("Please enter a valid choice: ")
def print_header(self):
print(f'Welcome to Rock, Paper, Scissors!\n{self.line}')
def get_player_name(self):
self.player = Player(input("Please enter your name: "))
class Player():
def __init__(self, name):
self.name = name
self.roll = None
self.score = 0
class Roll():
def __init__(self, name='', beat='', lose=''):
self.name = name
self.beat = beat
self.lose = lose
|
# Day 3 Project
import datetime
def run():
inp = ''
while inp.lower() != 'y':
inp = input('Start stopwatch? Y/N: ')
start = datetime.datetime.now()
inp = ''
while inp.lower() != 'y':
inp = input('Stop stopwatch? Y/N: ')
end = datetime.datetime.now()
tdelta = end - start
seconds = tdelta.seconds
mseconds = tdelta.microseconds
print(f'{seconds}.{mseconds}')
|
from abc import ABCMeta, abstractmethod
class Person:
# 对接口的依赖
def receive(self, IReceiver):
print(IReceiver.getInfo())
# 定义接口
class IReceiver(object):
__mataclss__ = ABCMeta # 指定这是一个抽象类
@abstractmethod # 抽象方法
def getInfo(self):
pass
class Email(IReceiver):
def getInfo(self):
return "电子邮件:hello,world"
class WeiChar(IReceiver):
def getInfo(self):
return "微信:hello,world"
if __name__ == '__main__':
# 客户端无需改变
Person().receive(Email())
Person().receive(WeiChar())
# 依赖关系传递:接口传递,构造方法传递,setter传递
# 底层模块经量都要有抽象类或接口,或者两者都有,程序稳定性更好
# 变量的声明类型经量是抽象类或接口,这样我们的变量引用和实际对象间,就存在了一个缓存层,利于程序扩展和优化
# 继承时遵循里氏替换原则
|
from Evento import *
# Clase lugar: esta clase sera usada para los datos de algun lugar donde
# se realizara un evento.
# Los atributos de la clase son:
# nombre: Nombre del lugar donde se presentara un veneto
# ubicacion: Ubicacion donde se hara el evento
# cap_max: Capacidad maxima de personas que caben en un lugar
class Lugar:
def __init__(self,nombre=None, ubicacion=None,cap_max=None):
self.__nombre = nombre
self.__ubicacion = ubicacion
self.__cap_max = cap_max
def get_nombre(self):
return self.__nombre
def get_ubicacion(self):
return self.__ubicacion
def get_cap_max(self):
return self.__cap_max
def imprimir(self):
print "Nombre del espacio: " +str(self.__nombre)
print "Ubicacion del espacio: " +str(self.__ubicacion)
print "Capacidad maxima del espacio " +str(self.__cap_max)
#Funcion para registrar los espacios designados para los eventos
def registrar_espacios(espacios):
while 1:
while 1:
nombre_espacio = raw_input('Nombre del espacio: ')
if nombre_espacio=='':
print "Indique nuevamente"
else:
#pasar todo a minuscula
break
while 1:
ubicacion = raw_input('Ubicacion del espacio: ')
if ubicacion =='':
print "Indique nuevamente"
else:
break
while 1:
capacidad = raw_input('Capacidad maxima de personas del espacio: ')
if capacidad.isdigit():
capacidad = int(capacidad)
break
else:
print "Indique nuevamente"
lugar = Lugar(nombre_espacio,ubicacion,capacidad)
espacios[nombre_espacio] = lugar
lugar.imprimir()
otro = raw_input('Agregara otro espacio a la conferencia? s|n ')
if otro != 's':
break
return espacios
#Imprime en pantalla todos los espacios que han sido registrados
def mostrar_espacios(espacios):
if espacios =={}:
print "No hay espacios registrados"
else:
print "Espacios ya registrados para la conferencia"
for elemento in espacios:
print elemento
#Me devuelve un diccionario con diccionarios 3 niveles
# diccionario[fecha][lugar][hora_inicio_evento]
# con este diccionario asignare dependiendo de la fecha, del lugar y de la
# ocupacion que tenga el lugar a la hora de inicio de un evento
def asignar_todo(calendario,espacios):
asignados = DiccionarioDeDiccionario()
lista_lugares = espacios.keys()
i = 1
while i<=5:
asignados[calendario[i]] = {}
for elemento in lista_lugares:
asignados[calendario[i]][elemento] = {}
hora = 1
while hora<=12:
asignados[calendario[i]][elemento][hora]={}
hora=hora+1
i = i+1
return asignados
#Funcion que imprime un diccionario para ser mostrado como un menu de opciones
def imprimir_menu(menu):
o = 1
while 1:
try:
print str(o)+") "+menu[o]
o = o+1
except KeyError:
break
# Con este metodo se realiza un diccionario que utilizaremos como un menu de
# opciones para ser presentado al usuario luego
def hacer_menu(lista):
menu = {}
k =1
for elemento in lista:
menu[k] = elemento
k = k+1
return menu
# Funcion verifica un entero que viene de entrada estandar y compara que este en
# el rango especificado
def verificar_entero_rango(entrada,minimo,maximo):
while 1:
numero = raw_input(entrada)
if numero.isdigit():
numero = int(numero)
if numero>=minimo and numero<=maximo:
return numero
print "Esta opcion no es correcta"
#verifica la entrada de un entero
def verificar_entero(entrada):
while 1:
numero = raw_input(entrada)
if numero.isdigit():
numero = int(numero)
return numero
print "Esta opcion no es correcta"
#Funcion que revisa la opcion que marco el usuario y verifica que la clave
#este en el menu
def verificar_en_menu(entrada,menu):
while 1:
num = raw_input(entrada)
if num.isdigit():
num = int(num)
try:
clave = menu[num]
return clave
except KeyError:
print "No esta entre las opciones"
#Verifica la disponibilidad del lugar segun hora de inicio y duracion del evento
def verificar_disponibilidad_de_lugar(asignados,fecha,lugar,hora_inicio,duracion):
hora = hora_inicio
contador = 0
esta_libre = True
while esta_libre == True and contador<duracion:
ocupacion = asignados[fecha][lugar][hora]
if ocupacion == {}:
if hora == 11:
hora = 1
elif hora==7:
esta_libre = False
else:
hora = hora+1
contador = contador+1
else:
esta_libre = False
return esta_libre
#Agrega el evento con su lugar y horas asignadas
def agregar_evento(asignados,fecha,lugar,hora_ini,duracion,evento):
hora = hora_ini
contador = 0
while contador<duracion:
ocupacion = asignados[fecha][lugar][hora] = evento
if hora == 11:
hora = 1
else:
hora = hora+1
contador = contador+1
return asignados
#Metodo para asignar los espacios a los eventos
def asignar_espacios(eventos_entrada,calendario,espacios):
eventos = eventos_entrada
#Asigno a todos los dias de la conferencia todos los lugares y horas posibles
#que luego seran asignadas a un evento
asignados = asignar_todo(calendario,espacios)
#obtengo los nombres de todos los espacios registrados
lista_lugares = espacios.keys()
#hago un menu de opciones de los espacios
lugares = hacer_menu(lista_lugares)
while 1:
#Muestro al usuario
imprimir_menu(calendario)
#Pregunto a cual fecha del evento va asignarle lugares
fecha_evento = verificar_entero_rango('Indique el dia para ver que eventos se presentan: ',1,5)
fecha = calendario[fecha_evento]
print ("En esta fecha " +str(fecha)+ " se presentan los siguientes eventos\n")
#Guardo en una lista los eventos que se presentaran para esa fecha
lista = eventos[fecha].keys()
#Condicional si hay eventos ya registrados para la fecha
if lista == []:
print "No se presentaran eventos para esa fecha\n"
else:
#Realizo un menu de los eventos que se presentan para la fecha especificada
evento_en_fecha = hacer_menu(lista)
#Muestro en pantalla
imprimir_menu(evento_en_fecha)
#Pide la opcion por pantalla al usuario y verifica en menu
cual_evento = verificar_en_menu('A que evento le asignara un espacio ',evento_en_fecha)
if cual_evento=='Taller' or cual_evento=='Sesiones Ponencia':
print str(cual_evento) + " son los siguientes: "
lista_eventos_simultaneo = eventos[fecha][cual_evento].keys()
evento_simultaneo = hacer_menu(lista_eventos_simultaneo)
imprimir_menu(evento_simultaneo)
respuesta = verificar_en_menu('Escoja a cual '+str(cual_evento),evento_simultaneo)
evento_dia = eventos[fecha][cual_evento][respuesta]
else:
#Obtengo el evento con sus datos
evento_dia = eventos[fecha][cual_evento]
while 1:
print "Estos son los espacios registrados para la conferencia\n"
#Imprimir menu de los lugares que ya habian sido aignados previamente
imprimir_menu(lugares)
#Pregunto el lugar que le quiere asignar a un evento
lugar_respuesta = verificar_en_menu('Indique el lugar para el evento '+str(cual_evento)+" ",lugares)
#Obtengo de lugar la hora y duracion del evento
hora_ini = evento_dia.get_hora_inicio()
duracion = evento_dia.get_duracion()
#Verificar disponibilidad del lugar
agregar = verificar_disponibilidad_de_lugar(asignados,fecha,lugar_respuesta,hora_ini,duracion)
if agregar == True: #El espacio esta disponible a esa hora
asignados = agregar_evento(asignados,fecha,lugar_respuesta,hora_ini,duracion,evento_dia)
break
else:#Espacio no disponible
print "Disculpe,no hay disponibilidad del lugar para la hora del evento"
si_no = raw_input('Desea asignarle otro lugar al evento s|n ')
if si_no != 's' and si_no!='S':
break
si_no = raw_input('Desea hacer otra asignacion? s|n ')
if si_no != 's' and si_no!='S':
break
return asignados
#Mostrar eventos con lugares asignados
def mostrar_eventos_con_lugares(asignados,calendario):
n =1
while n<=5:
print "Para la fecha " + str(calendario[n])
lugares = asignados[calendario[n]].keys()
for lugar in lugares:
am = 8
pm = 1
nombre =''
while am<=11:
presenta = asignados[calendario[n]][lugar][am]
if presenta != {}:
if nombre != presenta.get_nombre():
nombre = presenta.get_nombre()
print "Evento: "+ str(nombre)
print "Lugar: "+ str(lugar)
print "Hora: " +str(am) +"am "
print "Duracion: "+str(presenta.get_duracion())+" hora(as)"
am = am+1
while pm<=7:
presenta = asignados[calendario[n]][lugar][pm]
if presenta != {}:
if nombre != presenta.get_nombre():
nombre = presenta.get_nombre()
print "Evento: "+ str(nombre)
print "Hora: " +str(pm)+"pm"
print "Lugar: "+ str(lugar)
print "Duracion: "+str(presenta.get_duracion())+" hora(as)"
pm = pm+1
n = n +1
|
def squareOfNumbers(n):
dict = {}
if(n > 0 and n < 100):
for i in range(1,n+1):
dict[i] = i*i
return dict
squareOfNumbers(5)
|
import math
def isPrime(n):
if n <= 1:
return False
sqrt_n = math.sqrt(n)
if sqrt_n.is_integer():
return False
for i in range(2, int(sqrt_n)+1):
if n%i == 0:
return False
return True
num_test_cases = int(input())
for i in range(num_test_cases):
n = int(input())
if isPrime(n):
print('Prime')
else:
print('Not prime')
|
user_name = {"first_name": 'Игорь', "last_name":'Ярмомедов'}
print(user_name["first_name"])
x = 0
while x < 10:
print(x)
x += 1 |
"""
Contains all menu related classes. Menus prompt the user from standard output
(console) and get the user input from standard input (console).
Depending on the user response, the response is processed and the appropriate
actions are taken to navigate through the program.
"""
from typing import Callable, Dict
from util import Singleton, wrap
from text import Color, Style, color, style, modify
class Menu:
"""
Prompts the user for input.
Depending on the reponse, the menu will either reprompt or exit
and return some value based on the response.
This is an abstract singleton class. Do not instantiate.
All subclasses must implement create_prompts() and create_responses().
"""
cursor_prompt = "\n\n> " # This is appended to the end of every prompt
__metaclass__ = Singleton
def __init__(self):
self.main_prompt = str
self.prompt = ""
self.valid_responses = Dict[str, Callable]
self.next_menu = None
self.create_prompts()
self.create_responses()
def start(self) -> 'Menu':
"""
Initialize the menu
Returns:
the next menu to go to
or None if the program is to be exited
"""
self.prompt = self.main_prompt
while self.prompt:
# returning a None prompt exits the prompt loop and this
# specific menu.
self.get_user_input()
return self.next_menu
def get_user_input(self) -> None:
"""
Parameters:
String prompt: to the user that is printed to standard output
without a trailing newline before reading input.
Returns:
void: However, it modifies self.prompt which allows
the user to exit the prompt loop in start().
"""
response = input(self.prompt + self.cursor_prompt)
if response in self.valid_responses.keys():
# Call function value in self.valid_responses dictionary
self.valid_responses.get(response)()
elif self.matches_range(response):
self.evaluate(response)
else:
# Prompt use that an invalid response was issued
self.prompt_invalid_response(response)
def create_prompts(self) -> None:
"""
This is to be implemented by children classes
"""
raise NotImplementedError("Subclass must implement this method.")
def create_responses(self) -> None:
"""
Creates a dictionary of all valid responses.
self.valid_responses
keys String valid responses
values Function what the menu does when those response are
issued
"""
raise NotImplementedError("Subclass must implement this method.")
def matches_range(self, response: str) -> bool:
"""
If the user response does not match a specifc value in the
self.valid_responses dictionary, then check that it is contained
within a certain range of values.
Parameters:
String response
Returns:
boolean True if response matches range
"""
return False
def evaluate(self, response: str) -> None:
"""
If the user input matches the desired range, then evaluate it here.
This is a special case where the user input is not to be evaluated by
calling the response function in self.valid_responses.
Parameters:
String response
Returns:
void
"""
raise NotImplementedError("Has not been implemented.")
def prompt_invalid_response(self, response: str) -> None:
"""
Prompts that the user has issued an invalid response.
By default, this lists the possible response options to the user.
"""
options = ""
response_keys = list(self.valid_responses.keys())
if len(response_keys) > 1:
for i in range(len(response_keys) - 1):
options += color(response_keys[i], Color.CYAN) + color(", ", Color.RED)
options += color("or ", Color.RED) + color(response_keys[len(response_keys) - 1], Color.CYAN)
else:
options = color(response_keys[0], Color.CYAN)
message = color("Please choose ", Color.RED) + options + color(".", Color.RED)
self.prompt = self.main_prompt + "\n" + message
class MainMenu(Menu):
"""
The main menu that will let the user:
- Start a new game
- Learn more about the program
- Exit the program
It is the first menu that the user interacts with when the program starts.
"""
def create_prompts(self) -> None:
self.main_prompt = modify("""
_ __ _
| |/ / | |
| ' /_ _ _ __ ___| | __
| <| | | | '__/ __| |/ /
| . \\ |_| | | \\__ \\ <
|_|\\_\\__,_|_| |___/_|\\_\\
_____ _ _ _
/ ____(_) | | | |
| (___ _ _ __ ___ _ _| | __ _| |_ ___ _ __
\\___ \\| | '_ ` _ \\| | | | |/ _` | __/ _ \\| '__|
____) | | | | | | | |_| | | (_| | || (_) | |
|_____/|_|_| |_| |_|\\__,_|_|\\__,_|\\__\\___/|_|
__ ___ _ _ ____
/_ |/ _ \\| || ||___ \\
| | (_) | || |_ __) |
| |\\__, |__ _|__ <
| | / / | | ___) |
|_| /_/ |_||____/
""", Color.YELLOW, Style.BOLD) + \
" " + color("1. ", Color.CYAN) + \
modify("Start", Color.YELLOW, Style.UNDERLINE) + " " + \
color("2. ", Color.CYAN) + \
modify("About Kursk Simulator", Color.YELLOW, Style.UNDERLINE) + " " + \
color("3. ", Color.CYAN) + modify("Quit", Color.YELLOW, Style.UNDERLINE) + "\n"
about_message = wrap("""
Kursk Simulator: 1943 is a tank gunnery simulator built in Python. Tank armour
layouts and weapon penetration are modeled based on historical data collected
by the Allied governments after WWII. Kursk Simulator models the overmatch
mechanics (the interactions between weapons and armour that determine the
penetration, or non-penetration of a shell through armour) of tank gunnery,
with a simplified and stylized model based on elementary physics.
""")
self.about_prompt = self.main_prompt + "\n" + about_message
def create_responses(self) -> None:
def go_to_start_menu():
self.prompt = None
self.next_menu = SelectTankMenu()
def about():
self.prompt = self.about_prompt
def quit():
print("Bye!")
exit()
self.valid_responses = {
"1": go_to_start_menu,
"2": about,
"3": quit
}
class SelectTankMenu(Menu):
"""
The user is prompted with a selection of tanks they can choose from and
get information about each tank.
"""
def create_prompts(self) -> None:
self.main_prompt = """
TODO: This is just for debugging stuff.
Select a tank or learn more about it.
Debug tank
1. Choose
2. About
m. Return to main menu
"""
self.about_debug_prompt = "Debug tank description"
def create_responses(self) -> None:
def go_to_main_menu():
self.prompt = None
self.next_menu = MainMenu()
def about_debug():
self.prompt = self.main_prompt + "\n" + self.about_debug_prompt
self.valid_responses = {
"2": about_debug,
"m": go_to_main_menu
}
class GameMenu(Menu):
"""
General game menu.
Allows gives the option to restart, or return to main menu.
"""
def create_responses(self) -> None:
# TODO
# Figure out how children will add to these responses
def go_to_main_menu():
self.prompt = None
self.next_menu = MainMenu()
def restart():
# TODO
# this need to set the valid locations, health and ammo racks
# to their default states before the game started.
# This means that these values need to be saved before the
# game starts so they can be retrieved.
pass
class GameMoveMenu(Menu):
"""
In game, the user can choose what direction and how far to move.
"""
def create_prompts(self) -> None:
self.main_prompt = """
TODO: Choose where to move.
"""
# TODO: Show the maximum range to move backwards and forwards, depending
# on current tank selected.
def create_responses(self) -> None:
def go_to_main_menu():
self.prompt = None
self.next_menu = MainMenu()
class GameShellMenu(Menu):
"""
In game, the user can choose what shell to load for their upcoming shot.
"""
def create_prompts(self) -> None:
self.main_prompt = """
TODO: Choose the next shell to fire.
"""
# TODO: Iterate through tank ammo rack
def create_responses(self) -> None:
def go_to_main_menu():
self.prompt = None
self.next_menu = MainMenu()
self.valid_responses = {
"m": go_to_main_menu
}
class GameAimMenu(Menu):
"""
In game, the user can pick the angle at which they aim their upcoming shot.
"""
MIN_ANGLE = 0 # degrees from horizontal
MAX_ANGLE = 90
def create_prompts(self) -> None:
self.main_prompt = """
Choose an angle to fire at (0° - 90°)
"""
def create_responses(self) -> None:
def go_to_main_menu():
self.prompt = None
self.next_menu = MainMenu()
def restart():
# TODO
# this need to set the valid locations, health and ammo racks
# to their default states before the game started.
# This means that these values need to be saved before the
# game starts so they can be retrieved.
pass
self.valid_responses = {
"r": restart,
"m": go_to_main_menu
}
def matches_range(self, response: str) -> bool:
"""
valid input is any int from 0 to 90
"""
try:
return GameAimMenu.MIN_ANGLE <= int(response) <= GameAimMenu.MAX_ANGLE
except Exception:
return False
def evaluate(self, response: str) -> None:
degrees = int(response) # guaranteed int due to matches_range()
# TODO: set the angle to int(response)
pass
def prompt_invalid_response(self) -> None:
message = "Please choose an angle between 0° and 90°, r, or m."
self.prompt = self.main_prompt + "\n" + message
class FillAmmoMenu(Menu):
"""
The user can pick what ammo to fill their tank's ammo rack with.
"""
def create_prompts(self) -> None:
pass
def create_responses(self) -> None:
pass
|
#!/usr/bin/env python
# input -> [1, 2, 3, [1, 2], [3, 4]] -> output should come number of list being used inside this list i.e. 2
def list_count(listarg):
l_count = 0
for i in listarg:
if type(i) == list:
l_count = l_count + 1
return l_count
numbers = [1, 2, 3, [1, 2], [3, 4]]
print(list_count(numbers))
|
#!/usr/bin/env python
# count
# sort
# sorted Function
# clear
# copy
fruits = ["grapes", "mango", "apple", "banana", "kiwi", "apple", "king"]
print(fruits.count("apple")) # count method to count how may time apple appears in the list
fruits = ["grapes", "mango", "apple", "banana", "kiwi", "apple", "king"]
fruits.sort() # sort method to sort in alphabetic order
print(fruits)
numbers = [3, 5, 7, 1, 9]
numbers.sort() # sort method to sort in alphabetic order
print(numbers)
numbers = [3, 5, 7, 1, 9]
print(sorted(numbers)) # sorted function print the in alphabetic order while original list remains same
print(numbers) # This prints the numbers list as it is, sorted function only prints in sorted order while original list is in same order as it is
numbers = [3, 5, 7, 1, 9]
numbers.clear() # clear method to clear the list
print(numbers)
numbers = [3, 5, 7, 1, 9]
numbers_new = numbers.copy() # copy method to copy the contents of a list in a new list
print(numbers_new)
|
#!/usr/bin/env python
# using append method we can append data to our list
# suppose we want to add 1 more item called mango in our list fruits, use:
fruits = ["grapes", "apple"]
fruits.append("mango") # append method always appends data in the end of the list
print(fruits)
# But in realtime we don't know how many data we are going to add/store/append in our list.
# so, we take a empty list like below and keep appending data into it:
real_list = []
real_list.append("data1")
real_list.append("value")
real_list.append("five")
print(real_list)
|
# how we will create a list inside list using LC
# example = [[1,2,3], [1,2,3], [1,2,3]] # we want this list to be craeted using LC
# Normal
new_list = []
for i in range(3):
new_list.append([1,2,3])
print(new_list)
# Using LC
nest_list = [[i for i in range(1,4)] for j in range(3)]
print(nest_list)
|
#!/usr/bin/env python
# This is very important
# In Python at many places we must have seen, just written as:
# if name:
# print("anything")
# So what's this ?
# Explanation below:
name = "amitesh"
if name: # This is used to check if string is empty or not. True, if string is not empty
print("string is not empty")
else:
print("string is empty")
# Suppose in below case if string is empty
name1 = ""
if name1: # This is used to check if string is empty or not. True, if string is not empty
print("string is not empty")
else:
print("string is empty")
# Where it is useful?, FOr the scenarios like below:
username = input("Enter your name: ")
if username:
print(f"Your name is {username}")
else:
print("you didn\'t enterted your name")
|
#!/usr/bin/env python
# 'in' keyword is used to check if a particular character exists in a string or not.
name = "Amitesh"
if 'A' in name:
print("A is present in the string")
else:
print("A is not present in the string")
# Can also directly use the string itself
name = "Amitesh"
if 'Z' in "Amitesh":
print("Z is present in the string")
else:
print("Z is not present in the string")
|
#!/usr/bin/env python
# 1. Looping in tuples:
mixed = (1, 2, 3, 4.0)
for i in mixed: # we can also use while loop with tuples
print(i)
print("\n")
# 2. Declare Tuple with one element:
# num = (1) # This is int
# word = ('word1') # This is str
# print(type(num))
# print(type(word))
# print("\n")
# To declare one element inside tuple we should use comma
num1 = (1,) # This is <class 'tuple'>
word1 = ('word1',) # This is <class 'tuple'>
print(type(num1))
print(type(word1))
print("\n")
# 3. Tuple without parenthesis
mixed1 = 'one', 'two', 'three' # if we use like this it will conside it as tuple
print(type(mixed1))
print("\n")
# 4. Tuple unpacking: we will take here 3 variables and store elements of tuple inside variables
# we should exactly take the varibales, like here we have 3 elements in tuple so take 3 varibales
# if we take 2 variables, it will throw an error
guitarists = ('Maneli Jamal', 'Eddie Van Der Meer', 'Andrew Foy')
guitarists1, guitarists2, guitarists3 = (guitarists)
print(guitarists1)
print(guitarists2)
print(guitarists3)
print("\n")
# 5. List inside tuples: (this is a tuple in which there is a list inside it)
favorites = ('southern mangolia', ['tokyo ghoul times', 'landscape'])
# Actually with tuples we can't do pop(), append() or any method, but with the list inside this tuple we can use those methods:
favorites[1].pop() # favorites[1] means at 1st position list is there inside this tuple
print(favorites)
print("\n")
# 6. we can use min, max and sum methods with tuples:
mixed = (1, 2, 3, 4.0)
print(min(mixed))
print(max(mixed))
print(sum(mixed))
|
# List comprehension is one of the most powerful way to create and work in a list.
# This is the pythonic way of working with lists
# Suppose we want to create a list which will give us the square of, from 1 to 10
# Using Normal way:
square = []
for i in range(1,11):
square.append(i**2)
print(square)
print('\n')
# Using List comprehension:
square_list = [i**2 for i in range(1,11)]
print(square_list)
print('\n')
# Explanation: first we should think what ouput we want in our list. Here we want square of numbers. So first add i**2
# then range from 1 to 10 , so accordingly add for loop.
# Suppose we want to create list which gives us negative numbers from 1 to 10
# Using Normal way:
negative = []
for i in range(1,11):
negative.append(-i)
print(negative)
print('\n')
# Using List comprehension:
negative_list = [-i for i in range(1,11)]
print(negative_list)
print('\n')
# Same here also, first we need to think what we want in our list. we want negative numbers, so add -i
# then from where to where i.e. range,so add range function in for loop
# Suppose we want to create a list which gives us the 1st letter of each name from below list
# Using Normal way:
names = ['Amitesh', 'Saanvi', 'Manisha']
name = []
for i in names:
name.append(i[0])
print(name)
print('\n')
# Using List comprehension:
name_list = [i[0] for i in names]
print(name_list)
# same way first add what we want in output, we want first letter of each name so that would be i[0] and then for loop from that variable where we have stored the names.
|
#!/usr/bin/env python
# Diff b/w strings and lists:
# String is immutable(can't change the string) but list is mutable
# suppose we have a string:
s = 'amitesh' # immutable means we can't change the same string s. suppose if i apply a method title, let see:
t = s.title()
print(t) # output is Amitesh, as title method will convert first letter into capital
print(s) # output is amitesh, we can see string s is same, no change in the original string s
# list is mutable:
l = ['word1', 'word2', 'word3']
l.pop()
print(l) # output is ['word1', 'word2'], we can see original list l itself is changed now. means list is mutable
# 1 more example. Can we add a character in string, no we don't have any method to do that
# but using append() method we can add a character in list
ll = ['word4', 'word5', 'word6']
ll.append('word7')
print(ll) # output is ['word4', 'word5', 'word6', 'word7'], here the word7 got added in the original list itself
|
# suppose we want to add 2 numbers:
def add(a,b):
return a+b
print(add(2,3))
print("\n")
# But suppose we want to add 10 numbers then it will give error becoz we are passing only 2 argument in above function
# To overcome we use *args: means we can pass n number of arguments
# Here * will do this job, instead of args we can write anything but as per convention use args only
def all_total(*args):
total = 0
for i in args:
total = total + i # OR, total += i
return total
print(all_total(1,2,3,4)) # here we can enter any numbers, it will add all
|
#!/usr/bin/env python
name, letter = input("Enter the name and the letter you wish: ").split()
# print(name)
# print(letter)
length = len(name)
print(f"The count of your name is: {length}")
# Here counting number of letter regardless of lower or upper case, explanation below
low = name.lower()
concat = low+letter
length1 = concat.count("a")
print(f"The count of letter a and A is: {length1}")
# Explanation below:
# ⇒ python3 exercise3.py
# Enter the name and the letter you wish: Amitesh a
# The count of your name is: 7
# The count of letter a and A is: 2
|
#!/usr/bin/env python
# in keyword is used to check if any item is present in the list
fruits = ["grapes", "mango", "kiwi"]
if "grapes" in fruits:
print("grapes present in the list")
else:
print("not present")
|
# Exercise is that pass a list as input ['amitesh', 'ranjan']
# And output should be ['Amitesh', 'Ranjan'] # First letter of string should be Caps
# And 1 more output we should get using some function ['Hsetima', 'Najnar'] # It should reverse the string and first letter of should be Caps
def rev_func(lis, **kwargs):
if kwargs.get('reverse_str') == True:
return [i[::-1].title() for i in lis]
else:
return [i.title() for i in lis]
names = ['amitesh', 'ranjan']
print(rev_func(names, reverse_str = True)) # output would be ['Hsetima', 'Najnar']
print(rev_func(names)) # Output would be ['Amitesh', 'Ranjan']
print("\n")
# Explanation:
# Using this: reverse_str = True makes our input string as reverse.
# Line #5, Passing a list and **kwargs becoz we don't know if user has used reverse_str = True
# Line #6, **kwargs stores Key:value pair as dictionary and to check if user has used key:value 'reverse_str = True' or not, we will use get method on dictionary to check if that key:value is there or not
# Line #7, If it's there means 'reverse_str = True' in dictionary then reverse the names in list and first letter as Caps
# Else just Print the names and first Letter as Caps.
# Line#7 is LC, just breaking in Normal function to understand better:
def normal_func(lis):
output = []
for i in lis:
output.append(i[::-1].title()) # first value of i is amitesh, then i[::-1] reverses the string 'amitesh' , applying the function title() makes first letter of reversed string as caps
return output
names = ['amitesh', 'ranjan']
print(normal_func(names)) # Output would be ['Hsetima', 'Najnar']
|
def multiply_nums(*args):
multiply = 1
print(args)
for i in args:
multiply = multiply*i
return multiply
print(multiply_nums(3,4,5))
print("\n")
# Below Example:
def multiply_nums(*args):
multiply = 1
print(args)
for i in args:
multiply = multiply*i
return multiply
num = [2,3,4] # suppose if we have a list as num and we pass num in the function, the function multiply_nums won't work. we will get list num as output.
print(multiply_nums(num))
print("\n")
# So, to pass a list as *args , we should pass *num as argument
def multiply_nums(*args):
multiply = 1
print(args)
for i in args:
multiply = multiply*i
return multiply
num = [2,3,4]
print(multiply_nums(*num))
print("\n")
|
#!/usr/bin/env python
number = input("Enter the number: ")
number = int(number)
addition = 0
i = 1
while i <= number:
addition = addition + i
i = i + 1
print(addition)
|
import numpy as np
from constrained_examples import *
# Steepest Descent Algorithm for Constrained Optimization
# The code is the same as the one in the Unconstrained Optimization Algos
# This function takes the extra parameter sigma for Barrier and Penalty function evaluations
def steepest_constrained(cost, diff_cost, x0, w=0.01, sigma=0.0, report_print=False):
x, i = x0, 0
while np.linalg.norm(diff_cost(x, sigma)) > 10**-6:
i = i + 1
x = x - w*diff_cost(x, sigma)
if i > 10000: # Break if exceeds number of iteration limit
break
if report_print:
print("Iterations: ", i, ", Grad norm = ", np.linalg.norm(diff_cost(x)))
return x
if __name__ == '__main__':
print("Something")
# # Penalty Function Method for Ex1 of Part2
# print("Penalty Function Method for Ex1 of Part2")
# xc1 = np.array([1, 0])
# for i in range(10):
# xc1 = steepest_constrained(cost=vc1, diff_cost=diff_vc1, x0=xc1, sigma=2*i)
# print(i, xc1, "Cost:", vc1(xc1), " Const1:", (xc1[0]-xc1[1]**2), "Const2:", (xc1[0]**2+xc1[1]**2))
# # Barrier Point Method for Ex2 of Part 2
# print("Penalty Function Method for Ex2 of Part2")
# xc2 = np.array([0.5, 0.5])
# for i in range(9):
# xc2 = steepest_constrained(cost=vc2, diff_cost=diff_vc2, sigma=0.5**i, x0=xc2)
# print(i, ") ", xc2, "Cost:", vc2(xc2), " Const1:", (xc2[0] + xc2[1]), "Const2:", (xc2[0]**2 + xc2[1]**2))
# # Penalty Function Method for Ex2 of Part2
# print("Penalty Function Method for Ex3 of Part2")
# xc3 = np.array([2, 0])
# for i in range(7):
# xc3 = steepest_constrained(cost=vc3, diff_cost=diff_vc3, x0=xc3, sigma=7)
# print(i, xc3, "Cost:", vc3(xc3), " Const1:", (xc3[0]), "Const2:", (xc3[0]**2+xc3[1]**2))
|
m,n=map(int,raw_input().split())
num=m*n
if num%2==0:
print "even"
else:
print "odd"
|
jobs = []
file = open("jobs.txt","r")
data = file.readlines()
for line in data:
job = line.split()
weight = float(job[0])
length = float(job[1])
difference = weight - length
ratio = weight / length
jobs.append([weight, length, difference, ratio])
#print(jobs)
def compute():
completionTime = 0
weightedCompletionTime = 0
for job in jobs:
weight = job[0]
length = job[1]
completionTime += length
weightedCompletionTime += (weight*completionTime)
return weightedCompletionTime
index = 2
def criteria(a,b):
if a[index] > b[index]:
return -1
elif a[index] < b[index]:
return 1
else:
if a[0] > b[0]:
return -1
elif a[0] < b[0]:
return 1
else:
if a[1]>b[1]:
return -1
else:
return 1
jobs = sorted(jobs, cmp=criteria)
#print(jobs)
print('difference', compute()) # 69119377652.0
index = 3
jobs = sorted(jobs, cmp=criteria)
#print(jobs)
print('ratio', compute()) # 67311454237.0
|
"""
EECS 445 - Introduction to Machine Learning
Winter 2017 - Project 2
Build CNN - Skeleton
Build TensorFlow computation graph for convolutional network
Usage: `from model.build_cnn import cnn`
"""
import tensorflow as tf
import math
# TODO: can define helper functions here to build CNN graph
def conv2d(x, in_length, in_channels, out_channels, filter_len=5, stride=2, activation='relu'):
b = tf.Variable(tf.constant(0.01, shape=[ out_channels ]))
W = tf.Variable(tf.truncated_normal([filter_len, filter_len, in_channels, out_channels], stddev = 0.1 / tf.sqrt(tf.cast(filter_len * filter_len * in_channels, tf.float32))))
im = tf.reshape(x, [-1, in_length, in_length, in_channels])
c = tf.nn.conv2d(im, W, strides=[1, stride,stride, 1], padding='SAME') + b
if activation == 'tanh':
c = tf.nn.tanh(c)
elif activation == 'sigmoid':
c = tf.nn.sigmoid(c)
elif activation == 'relu':
c = tf.nn.relu(c)
elif activation == 'linear':
c = c
result = tf.reshape(c, [tf.shape(c)[0], -1])
return result
def buildNet(x, in_size, out_size, activation='relu'):
b = tf.Variable(tf.constant(0.1, shape=[out_size]))
W = tf.Variable(tf.truncated_normal([in_size, out_size], stddev=1.0 / tf.sqrt(tf.cast(in_size, tf.float32))))
c = tf.matmul(x, W) + b
if activation == 'tanh':
c = tf.nn.tanh(c)
elif activation == 'sigmoid':
c = tf.nn.sigmoid(c)
elif activation == 'relu':
c = tf.nn.relu(c)
elif activation == 'linear':
c = c
result = tf.reshape(c, [-1, out_size])
return result
# def conv2d(x, W, b, strides=2, activation='relu'):
# x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
# x = tf.nn.bias_add(x, b)
# if activation == 'relu':
# conv = tf.nn.relu(x)
# elif activation == 'tanh':
# conv = tf.nn.tanh(x)
# elif activation == 'sigmoid':
# conv = tf.nn.sigmoid(x)
# return conv
def normalize(x):
''' Set mean to 0.0 and standard deviation to 1.0 via affine transform '''
shifted = x - tf.reduce_mean(x)
scaled = shifted / tf.sqrt(tf.reduce_mean(tf.multiply(shifted, shifted)))
return scaled
def cnn():
''' Convnet '''
# TODO: build CNN architecture graph
inputSize = 1024
classSize = 7
input_layer = tf.placeholder(tf.float32, shape=[None, inputSize])
act = 'linear'
#may change to other activation
linearAct = 'linear'
c1 = conv2d(input_layer, 32, 1, 16, activation=act)
c2 = conv2d(c1, 16, 16, 32, activation=act)
c3 = conv2d(c2, 8, 32, 64, activation=act)
net = buildNet(c3, inputSize, 100, activation=act)
result = buildNet(net, 100, classSize, activation=linearAct)
pred_layer = normalize(result)
return input_layer, pred_layer
|
#可否除掉?
num = int(input('請輸入一個數字:'))
if num%2 ==0:
if num%3 ==0:
print('你輸入的數字可以整除2和3')
else:
print('你輸入的數字可以整除2,但不能整除3')
else:
if num%3 == 0:
print('你輸入的數字可以整除3,但不能整除2')
else:
print('你輸入的數字不能整除2和3') |
t = 2
n=int(input())
while n > 1:
while n % t == 0:
n /= t
t = t + 1
print(t)
|
import sys
sys.stdin = open('input.txt', 'r')
def paper_count(n): # 1 -> 1, 2 -> 3, 3 -> 5, 4 -> 11, 5 -> 21 # 재귀 각
if n == 1:
return 1
elif n == 2:
return 3
else:
return paper_count(n - 2) * 2 + paper_count(n - 1)
testcase = int(input())
for i in range(testcase):
N = int(input())
N = N // 10
# print(N)
print('#{} {}'.format(i + 1, paper_count(N)))
# 1 -> 1, 2 -> 3, 3 -> 5, 4 -> 11, 5 -> 21 |
import sys
from os import path
from bisect import bisect_right,insort_right
ORDER = 3
class BPlusTree(object) :
#INITIALISE THE TREE BY CREATING A ROOT NODE
def __init__(self) :
self.root = BPlusTreeNode()
self.all_keys_count = {} #keeps track of number of occurrences of a key
#INSERT A NEW KEY VALUE IN THE TREE
def insert(self,key) :
#If a key already exists, just increase its count, don't insert it
if(key in self.all_keys_count) :
#print("inside already", key)
self.all_keys_count[key] += 1
else :
self.all_keys_count[key] = 1
mid_val, new_node = self.insert_helper(key, self.root)
#check if root needs a split
if mid_val :
new_root = BPlusTreeNode()
new_root.keys = [mid_val]
new_root.pointers = [self.root, new_node]
new_root.is_leaf = False
self.root = new_root
#HELPER FUNCTION FOR INSERTING A NEW KEY
def insert_helper(self,key,node) :
'''If node is leaf
1. Insert the key at its correct position
2. If order exceeds, split the leaf
'''
if node.is_leaf:
insort_right(node.keys, key)
if len(node.keys) > ORDER:
return node.split()
return None, None
#If node is not a leaf, recursively find the appropriate leaf
mid_val, new_node = self.insert_helper(key, node.pointers[bisect_right(node.keys, key)])
if mid_val:
#insert key at its place
location = bisect_right(node.keys, mid_val)
node.keys.insert(location, mid_val)
node.pointers.insert(location + 1, new_node)
#check if split is required
if len(node.keys) > ORDER:
return node.split()
return None, None
return None, None
def get_leftmost_leaf(self,search_key, node) :
#If the node is leaf,return
if(node.is_leaf):
return node
#Else, find the leaf recusrively
for i in range(len(node.keys)):
#If search key is less than node's first key, go to the left child of current node
if(i == 0 and search_key <= node.keys[i] ):
return self.get_leftmost_leaf(search_key,node.pointers[0])
#If search key is greater than the last key of current node, go to the right child of current node
elif((search_key > node.keys[i]) and i+1==len(node.keys)):
return self.get_leftmost_leaf(search_key,node.pointers[i+1])
# If search key lies between smallest and largest key values of current node
elif(search_key <= node.keys[i+1] and node.keys[i] <= search_key ):
return self.get_leftmost_leaf(search_key,node.pointers[i+1])
#COUNT NO OF KEY IN A RANGE -
def count_keys_in_range(self,min_key,max_key) :
#get the left most leaf that has key >= min_key
node = self.get_leftmost_leaf(min_key, self.root)
count = 0
#traverse every leaf until there is no leaf left or the key > max_key
while node:
#print("inside while")
for i in range(len(node.keys)) :
if(node.keys[i] > max_key) :
break
if(node.keys[i] <= max_key and node.keys[i] >= min_key) :
count += self.all_keys_count[node.keys[i]]
node = node.next
return count
'''count = 0
for i in self.all_keys_count :
if(i >= min_key and i <= max_key) :
count += self.all_keys_count[i]
return count'''
#FIND IF A KEY EXISTS -
def find_key(self,key) :
if(key in self.all_keys_count) :
return True
return False
#COUNT THE NUMBER OF OCCURRENCES OF A KEY IN THE TREE -
def count_occurrences_of_key(self,key) :
if(key in self.all_keys_count) :
return self.all_keys_count[key]
return 0
class BPlusTreeNode :
#INITIALISE THE NODE
def __init__(self) :
self.pointers = []
self.is_leaf = True
self.next = None
self.keys = []
#SPLIT THE NODE
def split(self) :
#create a new node
splitted_node = BPlusTreeNode()
#find the mid position
mid_position = len(self.keys) // 2
mid_val = self.keys[mid_position]
#If the node is a leaf
if self.is_leaf :
insertion_position = mid_position
#If the node to be splitted is an internal node
else :
insertion_position = mid_position + 1
#distribute key valeus to the new node and current node
splitted_node.keys = self.keys[insertion_position : ]
splitted_node.pointers = self.pointers[insertion_position : ]
self.keys = self.keys[ : mid_position]
self.pointers = self.pointers[:insertion_position]
#point current node to the next node
splitted_node.next = self.next
self.next = splitted_node
#update is_leaf
splitted_node.is_leaf = self.is_leaf
#return the key over which split occured and the new node formed after split
return mid_val,splitted_node
#CHECK IF A QUERY IS IN VALID FORMAT -
def check_if_valid(query_parts) :
length = len(query_parts)
command = query_parts[0].lower()
if(length > 1) :
if(command == "range" and length == 3) :
return True
if((command == "insert" or command == "find" or command == "count") and length == 2) :
return True
return False
#PROCESS QUERIES -
def processQueries(queries) :
flag = True
with open("output.txt",'w') as out_file :
b_plus_tree = BPlusTree()
for i in queries :
query_parts = i.strip().split()
#check if the query is valid -
if(check_if_valid(query_parts)) :
command = query_parts[0].lower()
element = int(query_parts[1])
if(command == "insert") :
b_plus_tree.insert(element)
result = str(element) + " inserted"
elif(command == "find") :
if(b_plus_tree.find_key(element)) :
result = "YES"
else :
result = "NO"
elif(command == "count") :
result = str(b_plus_tree.count_occurrences_of_key(element))
elif(command == "range") :
result = str(b_plus_tree.count_keys_in_range(element,int(query_parts[-1])))
else :
result = "Invalid query"
#write the result og the query to the output file
out_file.write(result + "\n")
#MAIN FUNCTION -
def main() :
#check if input file is provided :
if(len(sys.argv) < 2) :
print("Provide the input file name")
sys.exit(0)
input_file = sys.argv[1]
#check if file exits :
if(path.exists(input_file)) :
with open(input_file,'r') as inp :
queries = inp.readlines()
processQueries(queries)
else :
print("File doesn't exist")
sys.exit(0)
if __name__ == "__main__" :
main()
|
# Step 0: Bring the data in.
data = "faculty.csv"
import pandas as pd
faculty_df = pd.read_csv(data)
# ----------------------------------------------------------------------
# Q1. Find how many different degrees there are, and their frequencies:
# Ex: PhD, ScD, MD, MPH, BSEd, MS, JD, etc.
# ----------------------------------------------------------------------
# Step 1 : Collapse multiple entries in a column to a string.
degree_string = str()
for set_of_degrees in faculty_df[" degree"]:
degree_string += set_of_degrees + " " #The space is added as a precaution
# 2) Clean-Up -
# Note: 'replace' method only works on strings.
degree_string = degree_string.replace("Ph.D ", "Ph.D. ")
degree_string = degree_string.replace("Ph.D.", "Ph.D.")
degree_string = degree_string.replace("PhD", "Ph.D.")
degree_string = degree_string.replace("ScD", "Sc.D.")
degree_string = degree_string.replace("MS", "M.S.")
degree_string = degree_string.replace("0", "")
# Step 3 : Convert string into list via regex. This breaks up the string into "words"
# ... all continuous non-whitespace
import re
degrees_list = re.findall( "\S+", degree_string)
# Step 4 : Define & use a function to convert lists into dictionary counts
def dict_counts(list):
"""Adapted from 'Python for Everybody' - Chapter on Dictionaries.
Basically, this takes a list as an input, and outputs a dictionary of
counts for each item in the list.
Note: this assumes the inputed list is itself clean to begin with...
Logic: When we encounter a new item, we need to add a new entry in the
dictionary and if this the second or later time we have seen the item,
we simply add one to the count in the dictionary under that item."""
dictionary = {}
for item in list:
if item not in dictionary:
dictionary[item] = 1
else :
dictionary[item] = dictionary[item] + 1
return dictionary
print dictionary
print dict_counts(degrees_list)
# ----------------------------------------------------------------------
# Q2. Find how many different titles there are, and their frequencies:
# Ex: Assistant Professor, Professor
# ----------------------------------------------------------------------
# Method 1: Using pandas built in series method 'value_counts().' This is
# less favorable for the degrees question because while ppl generally have
# only 1 title, they may and the dataset confirms not infrequently have
# multiple degrees.
print faculty_df[" title"].value_counts()
# Method 2: Original Method, creating a dictionary of counts
# Step 1: Collapse multiple entries in a column to a list & clean up/remove extra info.
titles_list = []
for title in faculty_df[" title"]:
title = title.replace("of Biostatistics", "")
title = title.replace("is Biostatistics", "")
titles_list.append(title.rstrip()) #rstrip removes any extra spaces hanging around...
# Step 2: Convert list into dicitonary of counts...
print dict_counts(titles_list)
# ----------------------------------------------------------------------
# Q3. Search for email addresses and put them in a list.
# Print the list of email addresses.
# ----------------------------------------------------------------------
email_list = []
for email in faculty_df[" email"]:
email_list.append(email.rstrip())
print email_list
# ----------------------------------------------------------------------
# Q4. Find how many different email domains there are (Ex:
# mail.med.upenn.edu, upenn.edu, email.chop.edu, etc.).
# Print the list of unique email domains.
# ----------------------------------------------------------------------
email_domain_list = []
for email in email_list:
######## Part 1: Extract the domain out of the email ######################
# Method 1: This uses regex to capture everything which comes after the @
#email_domain = re.findall('.*@([^ ]*)',email)
#print email_domain
# Method 2: This splits the email into two parts, everything to the left
# of the @ and everything to the right. The stuff to the right is the email domain
z = email.split("@")
email_domain = z[1]
####### Part 2: Check if the email_email has already been added to the domain list.
# If it hasn't, add it. ############################################
if email_domain in email_domain_list:
continue
else:
email_domain_list.append(email_domain)
print email_domain_list |
def has_no_e(string):
if string.find("e") == -1:
return True
else:
return False
fin = open("words.txt")
total_words = 0
no_e_words = 0
for line in fin:
line = line.strip()
total_words += 1
if has_no_e(line):
no_e_words += 1
print line
total_words = float(total_words)
print "Percentage of Words w/o an E:", no_e_words / total_words
|
#https://leetcode.com/problems/search-a-2d-matrix-ii/submissions/
import bisect
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for i in matrix:
if max(i) < target or min(i) > target:
continue
else:
aa = bisect.bisect_left(i, target)
if aa < len(i) and i[aa] == target:
return True
return False |
'''
Programa: Jogo do NIM em que a computador sempre vence
Autor: José Wesley Feitosa Oliveira
Concluída em: 11/2019
Breve descricao:
Você conhece o jogo do NIM? Nesse jogo, n peças são inicialmente dispostas numa mesa ou tabuleiro. Dois jogadores jogam alternadamente,
retirando pelo menos 1 e no máximo m peças cada um. Quem tirar as últimas peças possíveis ganha o jogo.
Existe uma estratégia para ganhar o jogo que é muito simples: ela consiste em deixar sempre múltiplos de (m+1) peças ao jogador oponente.
O objetivo é criar um jogo em Python que permita a uma "vítima" jogar o NIM contra o computador. O computador, é claro, deverá seguir a
estratégia vencedora descrita acima.
Sejam n o número de peças inicial e m o número máximo de peças que é possível retirar em uma rodada. Para garantir que o computador ganhe
sempre, é preciso considerar os dois cenários possíveis para o início do jogo:
Se n é múltiplo de (m+1), o computador deve ser "generoso" e convidar o jogador a iniciar a partida com a frase "Você começa"
Caso contrário, o computador toma a inciativa de começar o jogo, declarando "Computador começa"
Uma vez iniciado o jogo, a estratégia do computador para ganhar consiste em deixar sempre um número de peças que seja múltiplo de (m+1) ao
jogador. Caso isso não seja possível, deverá tirar o número máximo de peças possíveis.
'''
''' Função computador_escolhe_jogada que recebe, como parâmetros, os números n e m descritos acima e devolve um inteiro correspondente à
próxima jogada do computador de acordo com a estratégia vencedora. '''
def computador_escolhe_jogada(n,m):
aux = n%(m+1)
jogada = peças_restantes = 0
if aux == 0 or aux >= m:
jogada = m
else:
jogada = aux
peças_restantes = n - jogada
print("Computador tirou",jogada,"peças")
print("Agora restam",peças_restantes,"peças no tabuleiro.\n")
return jogada
''' Função usuario_escolhe_jogada que recebe os mesmos parâmetros, solicita que o jogador informe sua jogada e verifica se o valor informado
é válido. Se o valor informado for válido, a função deve devolvê-lo; caso contrário, deve solicitar novamente ao usuário que informe uma
jogada válida. '''
def usuario_escolhe_jogada(n,m):
jogada = int(input("Quantas peças você vai tirar? "))
peças_restantes = 0
while jogada > m or jogada > n or jogada <= 0:
print("Oops! Jogada inválida! Tente de novo. \n")
jogada = int(input("Quantas peças você vai tirar? "))
peças_restantes = n - jogada
print("Voce tirou",jogada,"peças.")
print("Agora restam",peças_restantes,"peças no tabuleiro. \n")
return jogada
''' A função partida não recebe nenhum parâmetro, solicita ao usuário que informe os valores de n e m e inicia o jogo, alternando entre
jogadas do computador e do usuário (ou seja, chamadas às duas funções anteriores). A escolha da jogada inicial deve ser feita em função da
estratégia vencedora, como dito anteriormente. A cada jogada, deve ser impresso na tela o estado atual do jogo, ou seja, quantas peças foram
removidas na última jogada e quantas restam na mesa. Quando a última peça é removida, essa função imprime na tela a mensagem "O computador ganhou!"
ou "Você ganhou!" conforme o caso. '''
def partida():
n_digitado = int(input("Quantas peças? "))
m_digitado = int(input("Limite de peças por jogada? "))
jogada = 0
usuario_jogou = True
peças_restantes = 0
while m_digitado >= n_digitado:
n_digitado = int(input("Quantas peças? "))
m_digitado = int(input("Limite de peças por jogada? "))
if n_digitado%(m_digitado + 1) == 0:
print("\n Voce começa! \n")
jogada = usuario_escolhe_jogada(n_digitado,m_digitado)
usuario_jogou = True
else:
print("\n Computador começa! \n")
jogada = computador_escolhe_jogada(n_digitado,m_digitado)
usuario_jogou = False
n_digitado = n_digitado - jogada
while n_digitado != 0:
if usuario_jogou:
jogada = computador_escolhe_jogada(n_digitado,m_digitado)
usuario_jogou = False
else:
jogada = usuario_escolhe_jogada(n_digitado,m_digitado)
usuario_jogou = True
n_digitado = n_digitado - jogada
if usuario_jogou:
print("\n Você ganhou! \n")
return False
else:
print("\n O computador ganhou! \n")
return True
''' A função campeonato realiza três partidas seguidas do jogo e, ao final, mostrar o placar dessas três partidas e indicar o vencedor do campeonato '''
def campeonato():
rodada1 = rodada2 = rodada3 = True
voce = computador = 0
print("\n **** Rodada 1 **** \n")
rodada1 = partida()
if rodada1:
computador = 1
else:
voce = 1
print("\n **** Rodada 2 **** \n")
rodada2 =partida()
if rodada2:
computador = computador + 1
else:
voce = voce + 1
print("\n **** Rodada 3 **** \n")
rodada3 =partida()
if rodada3:
computador = computador + 1
else:
voce = voce + 1
print("\n **** Final do campeonato! **** ")
print("\n Placar: Você",voce,"X",computador," Computador")
return
print("\n Bem-vindo ao jogo do NIM! Escolha: ")
print("\n1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
tipo_jogo = int(input(" "))
while tipo_jogo != 1 and tipo_jogo != 2:
print("\n1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
tipo_jogo = int(input(" "))
if tipo_jogo == 1:
print("\n Você escolheu uma única partida ")
partida()
else:
print("\n Voce escolheu um campeonato! ")
campeonato()
|
a=input("enter a string\t")
if(a=='q'):
print('end')
else:
while (True):
print("looping")
'''
sample input & output
enter a string a
looping
looping
looping
looping
looping
looping
looping
looping
looping
looping
looping
.
.
.
(loop continues)
sample input & output 2
enter a string q
end
>>>
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.