text
stringlengths 37
1.41M
|
---|
weight = raw_input("How much do you weight?: ")
try:
weight = int(weight) #if the input entered was an integer it will continue or...
except:
print "Invalid entry."
quit()
moonWeight = weight/6.0
print moonWeight
|
import sqlite3
# items.dbに接続
connectdb = sqlite3.connect('items.sqlite3')
cdbcursor = connectdb.cursor()
# テーブルの作成
cdbcursor.execute("create table items(id,name)")
# データの挿入
cdbcursor.execute("insert into items values(1,'あいてむ')")
cdbcursor.execute("insert into items values(2,'アイテム')")
cdbcursor.execute("insert into items values(3,'item')")
# 確定
connectdb.commit()
# 閉じる
connectdb.close()
|
input1 = input("Please enter the sentence")
print("The original sentence is : ",input1)
print("The modified sentence is : ", input1.replace("python", "pythons"))
|
in1 = input("Enter the string ")
# Defining function to be called
def string_alternative(in1):
out = ""
# Checking for even index and copy data only for even index's
for i in range(len(in1)):
if i%2 == 0:
out = out + in1[i]
# printing the input and processed output
print("input is : ", in1)
print("Modified output is : ", out)
#return out
#Function call
string_alternative(in1)
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
train = pd.read_csv('winequality-red.csv')
#Checking for Null values
print("before processing, null count is : " , sum(train.isnull().sum() != 0))
# handling null or missing value
data = train.select_dtypes(include=[np.number]).interpolate().dropna()
print("After removing, null count is : " , sum(data.isnull().sum() != 0))
numeric_features = train.select_dtypes(include=[np.number])
corr = numeric_features.corr()
print(corr['quality'].sort_values(ascending=False)[1:4], '\n')
##Build a linear model
y = np.log(train.quality)
X = data.drop(['quality'], axis=1)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=.33)
lr = linear_model.LinearRegression()
model = lr.fit(X_train, y_train)
##Evaluate the performance and visualize results
print ("R^2 is: \t", model.score(X_test, y_test))
predictions = model.predict(X_test)
print ('RMSE is: \t', mean_squared_error(y_test, predictions))
##visualizing the plot
actual_values = y_test
plt.scatter(predictions, actual_values, alpha=.75,color='b') #alpha helps to show overlapping data
plt.xlabel('Predicted quality')
plt.ylabel('Actual quality')
plt.title('Linear Regression Model')
plt.show()
|
from collections import defaultdict
import math
import sys
fileName = input("Enter file name : ")
source = input("Enter Origin_city: ")
destination = input("Enter Destination_city: ")
def Graph():
dictionary = defaultdict(list)
with open(fileName, 'r') as file:
for line in file:
(firstNode, secondNode, distance) = line.split()
if firstNode == 'END' and secondNode == 'OF' and distance == 'INPUT':
break
else:
dictionary[firstNode].append(secondNode)
dictionary[secondNode].append(firstNode)
return dictionary
#DFS starts here
graph = Graph()
def dfs_path(graph, source, dest):
result = []
DFS(graph, source, dest, [], result)
return result
def DFS(graph, source, dest, edge, result):
edge += [source]
if source == dest:
result.append(edge)
elif (source != dest):
for child in graph[source]:
if child not in edge:
DFS(graph, child, dest, edge[:], result)
dfsRoute = dfs_path(graph, source, destination)
#Dijkstra starts here
def graphForDijkstra():
dictionary = defaultdict(dict)
with open(fileName, 'r') as file:
for line in file:
(firstNode, secondNode, distance) = line.split()
if firstNode == 'END' and secondNode == 'OF' and distance == 'INPUT':
break
else:
dictionary[firstNode][secondNode] = int(distance)
dictionary[secondNode][firstNode] = int(distance)
return dictionary
graphForDijkstra = graphForDijkstra()
def dijkstra(graph, source, destination):
unreachedNode = graph
shortRoute = {}
ancestor = {}
infinite = math.inf
route = []
for node in unreachedNode:
shortRoute[node] = infinite
shortRoute[source] = 0
while unreachedNode:
lowNode = None
for node in unreachedNode:
if lowNode is None:
lowNode = node
elif shortRoute[node] < shortRoute[lowNode]:
lowNode = node
for childNode, edgeWeight in graph[lowNode].items():
if edgeWeight + shortRoute[lowNode] < shortRoute[childNode]:
shortRoute[childNode] = edgeWeight + shortRoute[lowNode]
ancestor[childNode] = lowNode
unreachedNode.pop(lowNode)
if shortRoute[destination] != infinite:
print("distance : " + str(shortRoute[destination]) + " km")
currNode = destination
while currNode is not None:
try:
route.insert(0, currNode)
currNode = ancestor[currNode]
except KeyError:
break
print("route : ")
for edge in range(1, len(route)):
print(route[edge - 1] + " to " + route[edge] + ", " + str(
shortRoute[str(route[edge])] - shortRoute[str(route[edge - 1])]) + " km")
else:
print("distance : infinity")
print("route: none")
dijkstra(graphForDijkstra, source, destination)
|
import abc
from abc import abstractmethod
import random
from insertData import InsertData
class Employee():
def __init__(self, name, address, salary):
self.name = name
self.address = address
self.salary = salary
self.codOnly = None
self.paymentMethod = None
self.belongUnion = None
self.idUnion = None
self.rateUnion = None
self.paymentSchedule = None
def paymentInfo(self, paymentMethod, belongUnion, idUnion, rateUnion,
PaymentSchedule = None):
insert = InsertData("Employees")
insert.paymentInfo(self.codOnly, paymentMethod, belongUnion,
idUnion, rateUnion, PaymentSchedule)
def serviceRate(self, date, rate):
insert = InsertData("Employees")
insert.serviceRate(self.codOnly, date, rate)
@abstractmethod
def payment(self):
"""Payment"""
def __str__(self):
return self.name
def __repr__(self):
return "<Code Only: {}\n" \
"Name: {}\n" \
"Address: {}\n" \
"Description: {}\n" \
"Salary: {}\n" \
"Commission: {}\n" \
"Payment Method: {}\n" \
"Belong Union: {}\n" \
"Id Union: {}\n" \
"Union Rate: {}\n"\
"paymentSchedule: {}>".format(self.codOnly, self.name,
self.address, self.description,
self.salary, self.commission,
self.paymentMethod, self.belongUnion,
self.idUnion, self.rateUnion,
self.paymentSchedule)
class Salared(Employee):
def __init__(self, name, address, salary):
super().__init__(name, address, salary)
self.description = "Salared"
def __str__(self):
return self.name
def __repr__(self):
return "<Code Only: {}\n" \
"Name: {}\n" \
"Address: {}\n" \
"Salared: {}\n"\
"Salary: {}\n"\
"Payment Method: {}\n" \
"Belong Union: {}\n" \
"Id Union: {}\n" \
"Union Rate: {}\n"\
"paymentSchedule: {}>".format(self.codOnly, self.name,
self.address, self.salary, self.description,
self.paymentMethod, self.belongUnion,
self.idUnion, self.rateUnion,
self.paymentSchedule)
class Commissioner(Salared):
def __init__(self, name, address, salary, commission):
super().__init__(name, address, salary)
self.commission = commission
self.description = "Commissioner"
def salesHistory(self, date, value):
insert = InsertData("Employees")
insert.salesHistory(self.codOnly, date, value)
def __str__(self):
return self.name
def __repr__(self):
return "<Code Only: {}\n" \
"Name: {}\n" \
"Address: {}\n" \
"Description: {}\n" \
"Salary: {}\n" \
"Commission: {}\n" \
"Payment Method: {}\n" \
"Belong Union: {}\n" \
"Id Union: {}\n" \
"Union Rate: {}\n"\
"paymentSchedule: {}>".format(self.codOnly, self.name,
self.address, self.description,
self.salary, self.commission,
self.paymentMethod, self.belongUnion,
self.idUnion, self.rateUnion,
self.paymentSchedule)
class Hourly(Employee):
def __init__(self, name, address, salary):
super().__init__(name, address, salary)
self.description = "Hourly"
def timecard(self, date, hourly):
insert = InsertData("Employees")
if self.codOnly == None:
return "Employee not exist!"
else:
insert.timecard(self.codOnly, date, hourly)
def __str__(self):
return self.name
def __repr__(self):
return "<Code Only: {}\n" \
"Name: {}\n" \
"Address: {}\n" \
"Description: {}\n" \
"Salary: {}\n" \
"Payment Method: {}\n" \
"Belong Union: {}\n" \
"Id Union: {}\n" \
"Union Rate: {}\n"\
"paymentSchedule: {}>".format(self.codOnly, self.name,
self.address, self.description,
self.salary, self.paymentMethod,
self.belongUnion, self.idUnion,
self.rateUnion, self.paymentSchedule)
|
'''
Simple Linear Regression
About this Notebook
In this notebook, we learn how to use scikit-learn to implement simple linear regression.
We download a dataset that is related to fuel consumption and Carbon dioxide emission of cars.
Then, we split our data into training and test sets,create a model using training set,
evaluate your model using test set, and finally use model to predict unknown value.
'''
#Importing Needed packages
import matplotlib.pyplot as plt
import pandas as pd
import pylab as pl
import numpy as np
%matplotlib inline
#Downloading Data
#To download the data, we will use !wget to download it from IBM Object Storage
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
#Reading the data in
df = pd.read_csv("FuelConsumption.csv")
# take a look at the dataset
df.head()
#Data Exploration
# summarize the data
df.describe()
#Lets select some features to explore more.
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
cdf.head(9)
#we can plot each of these features:
viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]
viz.hist()
plt.show()
#Now, lets plot each of these features vs the Emission, to see how linear is their relation:
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("FUELCONSUMPTION_COMB")
plt.ylabel("Emission")
plt.show()
plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("CYLINDERS")
plt.ylabel("Emission")
plt.show()
'''
Creating train and test dataset
Train/Test Split involves splitting the dataset into training and testing sets respectively, which are mutually exclusive.
After which, you train with the training set and test with the testing set.
This will provide a more accurate evaluation on out-of-sample accuracy because the testing dataset is not part of the dataset that have
been used to train the data. It is more realistic for real world problems.
This means that we know the outcome of each data point in this dataset, making it great to test with!
And since this data has not been used to train the model, the model has no knowledge of the outcome of these data points.
So, in essence, it is truly an out-of-sample testing.
Lets split our dataset into train and test sets, 80% of the entire data for training, and the 20% for testing.
We create a mask to select random rows using np.random.rand() function:
'''
msk = np.random.rand(len(df)) < 0.8
train = cdf[msk]
test = cdf[~msk]
'''
Simple Regression Model
Linear Regression fits a linear model with coefficients 𝜃=(𝜃1,...,𝜃𝑛) to minimize the 'residual sum of squares' between
the independent x in the dataset, and the dependent y by the linear approximation.
'''
#Train data distribution
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
#Modeling
#Using sklearn package to model data.
from sklearn import linear_model
regr = linear_model.LinearRegression()
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
regr.fit (train_x, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')
plt.xlabel("Engine size")
plt.ylabel("Emission")
'''
Evaluation
we compare the actual values and predicted values to calculate the accuracy of a regression model.
Evaluation metrics provide a key role in the development of a model, as it provides insight to areas that require improvement.
There are different model evaluation metrics, lets use MSE here to calculate the accuracy of our model based on the test set:
Mean absolute error: It is the mean of the absolute value of the errors. This is the easiest of the metrics to understand
since it’s just average error.Mean Squared Error (MSE): Mean Squared Error (MSE) is the mean of the squared error.
It’s more popular than Mean absolute error because the focus is geared more towards large errors.
This is due to the squared term exponentially increasing larger errors in comparison to smaller ones.
Root Mean Squared Error (RMSE): This is the square root of the Mean Square Error.
R-squared is not error, but is a popular metric for accuracy of your model.
It represents how close the data are to the fitted regression line.
The higher the R-squared, the better the model fits your data.
Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse).
'''
from sklearn.metrics import r2_score
test_x = np.asanyarray(test[['ENGINESIZE']])
test_y = np.asanyarray(test[['CO2EMISSIONS']])
test_y_hat = regr.predict(test_x)
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_hat - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_hat - test_y) ** 2))
print("R2-score: %.2f" % r2_score(test_y_hat , test_y) )
|
# Spiral Matrix
# Given aNXN matrix, starting from the upper right corner of the matrix start printingvalues in a
# counter-clockwise fashion.
# E.g.: Consider N = 4
# Matrix= {a, b, c, d,
# e, f, g, h,
# i, j, k, l, . visit 1point3acres.com for more.
# m, n, o, p}
# Your function should output: dcbaeimnoplhgfjk
def spiral_matrix(matrix):
res = []
while matrix:
for i in matrix[0]:
res.append(i)
#print res
del matrix[0]
for i in matrix:
res.append(i.pop())
if matrix:
res.extend(matrix.pop()[::-1])
for i in matrix:
res.append(i[0])
del i[0]
#print res
return res
matrix = [[1,2,3,11],[8,9,4,12],[7,6,5,13]]
for i in matrix:
print i
print spiral_matrix(matrix)
|
# possible password
# dfs problem
# Given an input N that tells you also how many digits are in the password, print all possible passwords
import string
import pdb
def possblePassword(N):
result = list()
path = list()
abc = list(string.ascii_lowercase)
dfs(0,N,result,path,abc,0)
print result
print len(result)
# recursive dfs solution
def dfs(step,N,result,path,abc,pos):
if step == N:
result.append("".join(path))
else:
for i in range(pos,26):
path.append(abc[i])
dfs(step+1,N,result,path,abc,i+1)
path.pop()
path.append(abc[i].upper())
dfs(step+1,N,result,path,abc,i+1)
path.pop()
return
possblePassword(2)
|
class person:
def __init__(x, name, age):
x.name = name
x.age = age
person1 = person("Muhammad Ali",25)
print(person1.name)
print(person1.age)
|
def two_complement(value : int, nb_bits : int):
"""Return the two's complement of value with nb_bits bits"""
assert -(2**(nb_bits-1)) <= value < 2**(nb_bits-1), "Value "+str(value) + " should have been between " + str(-2**(nb_bits-1)) + " and " + str(2**(nb_bits-1)-1)
return ("{0:{fill}" + str(nb_bits) + "b}").format(value%(2**nb_bits),fill='0')
print(f'-3 en binaire : {two_complement(-3,16)}')
print(f'-15 en binaire : {two_complement(-15,16)}')
print(f'-256 en binaire : {two_complement(-256,16)}')
print(f'-1024 en binaire : {two_complement(-1024,16)}')
n1 = -15
n2 = 16
somme = n1+n2
print('')
print("{0:{fill}3d}".format(n1,fill=0), f': {two_complement(n1,16)}')
print("{0:{fill}3d}".format(n2,fill=0), f': {two_complement(n2,16)}')
print('----------------------')
print("{0:{fill}3d}".format(somme,fill=0), f': {two_complement(somme,16)}')
|
def code_cesar(code):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
index = alphabet.index(code)
encodage = {}
for i, x in enumerate(alphabet):
#print(i,x)
encodage[x] = alphabet[(i + index) % len(alphabet)]
return encodage
def code_cesar_reverse(code):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
index = alphabet.index(code)
encodage = dict()
for i, x in enumerate(alphabet):
encodage[alphabet[(i + index) % len(alphabet)]] = x
return encodage
def encode_cesar(code, texte):
return encode(code_cesar(code), texte)
def decode_cesar(code, texte):
return encode(code_cesar_reverse(code), texte)
def encode(code_dict, texte):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
texte_encode = ""
for x in texte:
if x in alphabet:
texte_encode += code_dict[x]
else:
texte_encode += x
return texte_encode
def code_lettres(depart, arrivee):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return alphabet[(alphabet.index(arrivee) - alphabet.index(depart)) % len(alphabet)]
def test_code_cesar():
assert code_cesar('E') == {'A': 'E', 'B': 'F', 'C': 'G', 'D': 'H', 'E': 'I', 'F': 'J', 'G': 'K', 'H': 'L', 'I': 'M', 'J': 'N', 'K': 'O', 'L': 'P', 'M': 'Q', 'N': 'R', 'O': 'S', 'P': 'T', 'Q': 'U', 'R': 'V', 'S': 'W', 'T': 'X', 'U': 'Y', 'V': 'Z', 'W': 'A', 'X': 'B', 'Y': 'C', 'Z': 'D'}
def test_code_cesar_reverse():
assert code_cesar_reverse('E') == {'E': 'A', 'F': 'B', 'G': 'C', 'H': 'D', 'I': 'E', 'J': 'F', 'K': 'G', 'L': 'H', 'M': 'I', 'N': 'J', 'O': 'K', 'P': 'L', 'Q': 'M', 'R': 'N', 'S': 'O', 'T': 'P', 'U': 'Q', 'V': 'R', 'W': 'S', 'X': 'T', 'Y': 'U', 'Z': 'V', 'A': 'W', 'B': 'X', 'C': 'Y', 'D': 'Z'}
def test_encode_cesar():
assert encode_cesar('E', "LE VENDREDI C'EST ALGORITHMIE") == "PI ZIRHVIHM G'IWX EPKSVMXLQMI"
def test_decode_cesar():
assert decode_cesar('E', "PI ZIRHVIHM G'IWX EPKSVMXLQMI") == "LE VENDREDI C'EST ALGORITHMIE"
def test_code_lettres():
assert code_lettres('A', 'E') == 'E'
assert code_lettres('X', 'V') == 'Y'
code_cesar('E')
|
for value in range(1,21):
if value == 4 or value == 13:
print(f"{value} is unlucky")
elif value%2==0:
print (f"{value} is even")
else:
print(f"{value} is odd")
|
# Create a list called instructors
instructors = []
# Add the following strings to the instructors list
# "Colt"
# "Blue"
# "Lisa"
instructors.extend(["Colt", "Blue", "Lisa"])
print(instructors)
# Remove the last value in the list
instructors.pop()
print(instructors)
# Remove the first value in the list
instructors.remove(instructors[0])
print(instructors)
# Add the string "Done" to the beginning of the list
instructors.insert()
print(instructors)
# Run the tests to make sure you've done this correctly!
|
#!/usr/bin/python
"""Computes the reverse compliment of a DNA sequence"""
import sys
import string
argc = len(sys.argv)
toCompliment = string.maketrans("ACGT", "TGCA")
test = True
test_file_loc = "test_data"
usage = """revc.py [data file]
Computes the reverse compliment of the given DNA sequence in 'data file'"""
if(argc > 2):
print(usage)
sys.exit(1)
elif(argc == 2):
test_file_loc = sys.argv[1]
test = False
try:
test_file = open(test_file_loc)
except IOError, error:
print(error)
print(usage)
sys.exit(1)
data = test_file.readline()
if(data[-1] == '\n'):
data = data[:-1]
test_file.close()
if(test):
print("orig data: %s" % data)
answer = data[::-1].translate(toCompliment)
if(test):
print("revc data: %s" % answer)
else:
print(answer)
sys.exit(0)
|
#this programme generate a set of decision trees for Hangman according to all the English words
# I have used Python tree class implemented by Joowani https://github.com/joowani/binarytree
import pickle
from binarytree import tree, bst, convert, heap, Node, pprint
print 'Start reading the dictionary file...'
with open('words.txt') as f:
allWords = f.read().splitlines()
print 'There are '+str(len(allWords))+' words in the file'
maxlen = 0
for word in allWords:
if len(word) > maxlen:
maxlen = len(word)
print 'The longest word has '+str(maxlen)+' letters'
treelist=[];wordlengthlist=[];
height_tree = 18
for n in xrange(maxlen): #Create a list of binary search trees and a list of lists of different length words
treelist.append(heap(height=height_tree, max=True))
wordlengthlist.append([])
for word in allWords:
wordlengthlist[len(word)-1].append(word)
print 'There are '+str(len(wordlengthlist[8]))+' Word with 9 letters'
#This function aims at find the (rank)th frequent letter in a word's list
def find_most_frequent_letter(wordlist,rank):
count=[0]
for n in xrange(26):
count.append(0)
for word in wordlist: #find most frequent letter in 6 length word
for letter in list(word):
if letter.isalpha(): #to avoid the char <<'>>
count[ord(letter) - 97] += 1
new = count[:] #copy the rank list
for i in xrange(rank-1):
new.remove(max(new)) #delete the most biggest number in new list
return chr(count.index(max(new))+97) #return the (rank)th frequent letter in wordlist
# These twofunction used to delete word do/dont contains certain letter from the wordlist
def generate_new_list_with_letter_correct(letter, wordlist):
temp_list= []
for word in wordlist:
if letter in word:
temp_list.append(word.replace(letter,''))
wordlist[:] = []
for word in temp_list:
wordlist.append(word)
def generate_new_list_with_letter_wrong(letter, wordlist):
temp_list = []
for word in wordlist:
if letter in word:
temp_list.append(word)
for word in temp_list:
wordlist.remove(word)
# main iteration function to fill the tree
def fill_the_tree(node,wordlist,deepth,height):
if deepth == height+1:
return deepth-1
local_wordlist1 = wordlist[:] #this for wrong guess
local_wordlist2 = wordlist[:] #this for correct guess
#get the value for left node, wrong guess
generate_new_list_with_letter_wrong(node.value, local_wordlist1)
node.left.value = find_most_frequent_letter(local_wordlist1, 1) #left node contains the next most frequent letter if guess is wrong
deepth = fill_the_tree(node.left, local_wordlist1, deepth+1, height)
#get the value for right node, correct guess
generate_new_list_with_letter_correct(node.value, local_wordlist2)
node.right.value = find_most_frequent_letter(local_wordlist2, 1)
deepth = fill_the_tree(node.right, local_wordlist2, deepth+1, height)
return deepth-1
#list of 31 most common letter for different length
first_guess = ['a','a','a','a','s','e','e','e','e','e','e','e','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i','i']
find_most_frequent_letter(wordlengthlist[12],1)
# Fill the 31 binary trees for different length
for i in xrange(31):
print 'Building the tree for word length ',i
treelist[i].value = first_guess[i]
wordlist = wordlengthlist[i]
fill_the_tree(treelist[i], wordlist, 1, height_tree)
final_list = []
for tree in treelist:
final_list.append(convert(tree))
resultfile = open('result.txt', 'w')
pickle.dump(final_list, resultfile)
|
print("-" * 30 + " Begin Section 6 开场" + "-" * 30)
print("这是Python的第六次课程,主要讲数据的预处理")
print("1. 数据类型转换 \n2. 索引设置")
print("-" * 30 + "End Section 0 开场" + "-" * 30)
print("\n")
import pandas as pd
# Section 1 数据类型转换
df = pd.read_excel(r"/Users/yons/Desktop/py_help/04_lesson.xlsx", sheet_name="Sheet3")
df1 = df
# python 里面有六种主要的类型, int, float, object, string, unicode, datetime64[ns]
# 我们现在主要掌握四种 int, float, string, datetimes
# 查看某一列的数据类型, dtype
print(df["观看次数"].dtype, '\n')
print(df["发布时间"].dtype, '\n')
# 转换某一列的数据类型, astype()
# 将观看次数列的数据类型转换为float
print(df["观看次数"].astype("float64"))
print('\n')
# Section 2 索引设置
# 索引就是行标和列标
# 用columns, index 来设置
print(df, '\n')
df.index = [1,2,3,4,5]
print("给表格添加行索引:")
print(df, '\n')
# 用set_index() ,指明要用做行索引的列的名称
print("指明 观看次数 列当作行索引: ")
# 不会改变原先的表格, 所以要赋值
df = df.set_index("观看次数")
print(df, '\n')
df = df1
# 重命名列索引
df = df.rename(columns={"发布时间": "新发布时间"})
print(df, '\n')
# 改名行索引
df = df1
df = df.rename(index ={1:"一", 2:"二", 3:"三", 4:"四",5:"五"})
print(df, '\n')
|
#Variable
five = 5
six = 6
print(five* six)
#String Variable
person_one = 'I said the number: '
person_two = 'I have different number: '
print(person_one,five)
print(person_two,six)
print('Sum of their Number: ', five*six)
print(print(5)) #will print None
## creating custom Method
def print_something():
print('Who is there?')
print_something() #calling method
## Using parameter
def print_new(my_params):
print('What is the number: ',my_params)
print_new(five*six)
print_new(six)
## Using multiple Parameter
def print_multi(one,two):
return one*two
result = print_multi(five,six)
print('So, the new result is', result)
#nested method
print_new(print_multi(five,six))
|
def your_friends():
friend = input('Type your friends name separated by comma: \n')
friend_list = friend.split(',')
friend_without_space= []
for f in friend_list:
friend_without_space.append(f.strip())
return friend_without_space
def your_best_friend():
best_friend = input('Type your Best Friends name: \n')
if best_friend in your_friends():
print (f'{best_friend} is your best friend')
else:
print(f'{best_friend} is not even in your friend list')
your_best_friend()
|
def insertion_sort(*args):
# check type of the args (because type of args is tuple and it is immutable)
if type(args) is tuple:
array = list(args)
else:
array = args
for i in range(2, len(array)):
# hold to compare with others
hold = array[i]
# divide list to two parts ( [0:j] and [j:end])
j = i-1
# compare 'hold' with other variables in [0:j] part
while j >= 0 and array[j] > hold:
# shift variable
array[j+1] = array[j]
j -= 1
array[j+1] = hold
# return the sorted array
return array
if __name__ == "__main__":
print("\n\n ---------------- \n")
print("a simple test:\n")
array = [2, 10, 44, 0, -1, 23, -11, 77, 50, 100, 7, 16]
print(f"before sort: {array}")
array = insertion_sort(*array)
print(f"after sort: {array}")
print("\n ---------------- \n\n")
|
from random import randint
def partition(array: list, p: int, r: int) -> int:
x = array[r]
i = p-1
for j in range(p, r):
if array[j] <= x:
i += 1
array[i], array[j] = array[j], array[i]
array[i+1], array[r] = array[r], array[i+1]
return i+1
def randomized_partition(array: list, p: int, r: int) -> int:
i = randint(p, r)
array[i], array[r] = array[r], array[i]
return partition(array, p, r)
def randomized_quick_sort(array: list, p: int, r: int) -> None:
if p < r:
q = randomized_partition(array, p, r)
randomized_quick_sort(array, p, q-1)
randomized_quick_sort(array, q+1, r)
if __name__ == "__main__":
print("\n\n ---------------- \n")
print("a simple test:\n")
array = [1.5, -21, 45, 0, -1, -2.5, -11, 77, -50, 133, 88, 16, 29]
print(f"before sort: {array}")
randomized_quick_sort(array, 0, len(array)-1)
print(f"after sort: {array}")
print("\n ---------------- \n\n")
|
"""
Example script for connecting to the database.
- For an SQLite database, specifying a new filename will create a database
- For a MySQL database, connecting to an existing database will also create
any tables that are missing from the database schema.
"""
import os
import datetime
import numpy as np
import chmap.database.db_classes as db_class
import chmap.database.db_funs as db_funcs
import chmap.utilities.datatypes.datatypes as psi_dtypes
import chmap.utilities.plotting.psi_plotting as psi_plots
# INITIALIZE DATABASE CONNECTION
# Database paths
map_data_dir = "/Volumes/extdata2/CHMAP_DB_example/maps"
hdf_data_dir = "/Volumes/extdata2/CHMAP_DB_example/processed_images"
# Designate database-type and credentials
db_type = "sqlite" # 'sqlite' Use local sqlite file-based db
# 'mysql' Use a remote MySQL database
user = "turtle" # only needed for remote databases.
password = "" # See example109 for setting-up an encrypted password. In
# this case leave password="", and init_db_conn() will
# automatically find and use your saved password. Otherwise,
# enter your MySQL password here.
# If password=="", then be sure to specify the directory where encrypted credentials
# are stored. Setting cred_dir=None will cause the code to attempt to automatically
# determine a path to the settings/ directory.
cred_dir = "/Users/turtle/GitReps/CHD/chmap/settings"
# Specify the database location. In the case of MySQL, this will be an IP address or
# remote host name. For SQLite, this will be the full path to a database file.
# mysql
# db_loc = "q.predsci.com"
# sqlite
db_loc = "/Volumes/extdata2/CHMAP_DB_example/chmap_example.db"
# specify which database to connect to (unnecessary for SQLite)
mysql_db_name = "chd"
# Establish connection to database
sqlite_session = db_funcs.init_db_conn(db_type, db_class.Base, db_loc, db_name=mysql_db_name,
user=user, password=password, cred_dir=cred_dir)
mysql_session = db_funcs.init_db_conn("mysql", db_class.Base, "q.predsci.com", db_name=mysql_db_name,
user=user, password=password, cred_dir=cred_dir)
# SAMPLE QUERY
# use database session to query available pre-processed images
query_time_min = datetime.datetime(2011, 2, 1, 1, 0, 0)
query_time_max = datetime.datetime(2011, 2, 1, 3, 0, 0)
meth_name = 'LBCC'
meth_desc = 'LBCC Theoretic Fit Method'
method_id = db_funcs.get_method_id(sqlite_session, meth_name, meth_desc, var_names=None, var_descs=None, create=False)
# HISTOGRAM PARAMETERS TO UPDATE
n_mu_bins = 18 # number of mu bins
n_intensity_bins = 200 # number of intensity bins
lat_band = [- np.pi / 64., np.pi / 64.]
query_instrument = ["AIA", ]
sqlite_hists = db_funcs.query_hist(sqlite_session, meth_id=method_id[1], n_mu_bins=n_mu_bins,
n_intensity_bins=n_intensity_bins, lat_band=lat_band,
time_min=query_time_min, time_max=query_time_max,
instrument=query_instrument)
mu_bin_array, intensity_bin_array, sq_full_hist = psi_dtypes.binary_to_hist(
sqlite_hists, n_mu_bins, n_intensity_bins)
mysql_hists = db_funcs.query_hist(mysql_session, meth_id=method_id[1], n_mu_bins=n_mu_bins,
n_intensity_bins=n_intensity_bins, lat_band=lat_band,
time_min=query_time_min, time_max=query_time_max,
instrument=query_instrument)
mu_bin_array, intensity_bin_array, my_full_hist = psi_dtypes.binary_to_hist(
mysql_hists, n_mu_bins, n_intensity_bins)
# verify that the two databases return identical histograms
np.all((my_full_hist - sq_full_hist) == 0.)
# CLOSE CONNECTIONS
sqlite_session.close()
mysql_session.close()
|
class Player:
def __init__(self, intitalRow, initialColumn):
# Instance variables that contain the player's position in the maze.
self.rowPosition = intitalRow
self.columnPosition = initialColumn
# This method moves the player up.
# The player's row position is decremented by one.
def moveUp(self):
self.rowPosition -= 1
# This method moves the player down.
# The player's row position is incremented by one.
def moveDown(self):
self.rowPosition += 1
# This method moves the player left.
# The player's column position is decremented by one.
def moveLeft(self):
self.columnPosition -= 1
# This method moves the player right.
# The player's column position is incremented by one.
def moveRight(self):
self.columnPosition += 1
|
# Original code found: https://www.reddit.com/r/learnprogramming/comments/4w1duu/how_can_i_loop_through_every_pixel_in_an_image/
# Code was altered for project
# from PIL import Image
import cv2 # Imports OpenCV for image manipulation
import os # Imports the os class to use for directory navigation
from PIL import Image # Imports Pillow to get average pixel count
name_list = os.listdir('Grayscale') # Navigates to a folder called grayscale (this has all the rezised grayscale images)
num = 0 # Used this to itertate through the array of image names
# Iterates through every image in the folder
for i in name_list:
print('Starting image {0}'.format(i))
# im = Image.open(name_list[num])
im = Image.open('Grayscale\\{}'.format(name_list[num])) # Opens the current image
average = 0 # This is used hold the pixel color value
width, height = im.size # Get's the dimiensions of the images
# Iterates through each pixel
for x in range(width):
for y in range(height):
r = im.getpixel((x,y)) # Get's the pixel color data
average = average + r # Add all the pixel color data together
name = name_list[num] # Get's the name of the current card
save_name = ''
# Looks to find if either 'Eevee' or 'Mudkip' or 'Pikachu' is in the name
# It does this to append the name of the card to the dataset
if 'Squirtle' in name:
#print('Eevee Found')
save_name = 'Squirtle'
elif 'Charmander' in name:
#print('Mudkip Found')
save_name = 'Charmander'
elif 'Bulbasaur' in name:
#print("Pikachu found")
save_name = 'Bulbasaur'
with open('new_dataset_pool.txt', 'a+') as f:
f.write('{0}, {1}\n'.format(average, save_name)) # Saves the data to a file that looks like this '12341234123, pokemon_name' where {0} is total pixel image and {1} is the image name
num = num + 1 # Incriments num to go to the next image
|
# a = matrix, b = matrix, c = row_1, d = row_2
def swapRows(a, b, c, d):
n = len(a)
for i in range(n):
a[c][i], a[d][i] = a[d][i], a[c][i]
b[c], b[d] = b[d], b[c]
# i = column index
def notNullColumns(a, b, i):
j = 0
if a[i][i] == 0:
while a[i][i] == 0 and j < len(a):
if a[j][i] != 0 and a[i][j] != 0:
swapRows(a, b, i, j)
j += 1
print("---Gauss jordan---\n")
print("Enter the number of unknown variables.")
n = int(input("N: "))
print("Enter the matrix of coefficients .")
a = [[float(input("M[{}][{}]: ".format(j + 1, i + 1))) for i in range(n)] for j in range(n)]
print("Enter the result matrix.")
b = [float(input("C[{}]: ".format(i))) for i in range(n)]
for i in range(n):
notNullColumns(a, b, i)
i = 0
while i < n and a[i][i] != 0 :
i += 1
if i == n:
for i in range(n):
for j in range(n):
if i != j:
x = a[j][i] / a[i][i]
for k in range(n):
a[j][k] = a[j][k] - a[i][k] * x
b[j] = b[j] - b[i] * x
for i in range(n):
x = a[i][i]
for j in range(n):
a[i][j] /= x
b[i] /= x
for i in range(n):
print("x{} = {}".format(i + 1, b[i]))
|
import numpy as np
#MLP with 2-3 hidden layers from scratch
def process_data(data,mean=None,std=None):
# normalize the data to have zero mean and unit variance (add 1e-15 to std to avoid divide-by-zero)
if mean is not None:
# mean and std is precomputed with the training data
data = (data - mean)/(std + 1e-15)
data = np.nan_to_num(data)
return data
else:
# compute the mean and std based on the training data
mean , std = np.mean(data,axis=0), np.std(data, axis=0) # placeholder
data = (data - mean)/(std + 1e-15)
data = np.nan_to_num(data)
return data, mean, std
def process_label(label):
# convert the labels into one-hot vector for training
one_hot = np.zeros([len(label),10])
rows, cols = one_hot.shape[0], one_hot.shape[1]
for i in range(rows):
for j in range(cols):
one_hot[i,label[i]] = 1
return one_hot
def sigmoid(x):
# implement the sigmoid activation function for hidden layer
f_x = 1.0/(1.0 + np.exp(-x)) # placeholder
return f_x
def softmax(x):
# implement the softmax activation function for output layer
f_x = np.exp(x)/np.sum(np.exp(x)) # placeholder
return f_x
class MLP:
def __init__(self,num_hid):
# initialize the weights
self.weight_1 = np.random.random([64,num_hid]) #w 64 x num_hid
self.bias_1 = np.random.random([1,num_hid]) #w0 1 x num_hid
self.weight_2 = np.random.random([num_hid,10]) #v num_hid x 10
self.bias_2 = np.random.random([1,10]) #v0 1 x 10
def fit(self,train_x,train_y, valid_x, valid_y): #train_x shape: 1000x64
lr = 5e-3 # learning rate
count = 0 # counter for recording the number of epochs without improvement
best_valid_acc = 0
epochs = 100
while count<=epochs:
# training with all samples (full-batch gradient descents)
# implementing the forward pass
z_h = self.get_hidden(train_x) #1000 x num_hid
predicted_y = self.predict(train_x) # y probabilites
predicted_label = process_label(predicted_y) #labels
# implementing the backward pass (backpropagation)
# computing the gradients w.r.t. different parameters
diff_label = train_y - predicted_label #1000 x 10 (r^t - y^t)
##----update for v_h-----##
weight2_update = lr * np.dot(z_h.T,diff_label) # num_hid x 10
bias2_update = lr * np.sum(diff_label,axis=0)
##----update for w_h----##
inner_product = (np.dot(diff_label, self.weight_2.T)) #1000 x 10 x (num_hid x 10).T = 1000 x num_hid.
dz = (z_h * (1 - z_h)) #z_h: 1000 x num_hid
coeffs = (inner_product * dz) # 1000 x num_hid
weight1_update = lr * np.dot(train_x.T,coeffs) #64 x num_hid
bias1_update = lr * np.sum(coeffs, axis=0)
#update the parameters based on sum of gradients for all training samples
self.weight_1 += weight1_update
self.weight_2 += weight2_update
self.bias_1 += bias1_update
self.bias_2 += bias2_update
# evaluate on validation data
predictions = self.predict(valid_x)
valid_acc = np.count_nonzero(predictions.reshape(-1)==valid_y.reshape(-1))/len(valid_x)
# compare the current validation accuracy with the best one
if valid_acc>best_valid_acc:
best_valid_acc = valid_acc
count = 0
else:
count += 1
return best_valid_acc, predicted_label
def predict(self,x):
# generate the predicted probability of different classes
z_h = self.get_hidden(x)
# converting class probability to predicted labels
y = softmax(np.dot(z_h,self.weight_2) + self.bias_2) #1000 x 10
y_max = np.argmax(y, axis=1)
return y_max
def get_hidden(self,x):
# extract the intermediate features computed at the hidden layers (after applying activation function)
z = sigmoid(np.dot(x, self.weight_1) + self.bias_1)
return z
def params(self):
return self.weight_1, self.bias_1, self.weight_2, self.bias_2
|
# percorrer listas
nomes = [
"jose",
"talita",
"aline santos",
"jessica",
"sabrina",
"juliana",
"julia",
"sasha",
]
print("Listar todos os elementos:")
for nome in nomes:
# caso a condição seja satisfeita, é pulado para a próxima iteração com o 'continue'
if nome.startswith("S"):
continue
print(nome)
# percorrer intervalos com range()
# abaixo é percorrido a lista do indice 1 ao indice 7
print("\nElementos de um intervalo:")
for x in range(1, len(nomes)):
print(nomes[x])
# enumerando os elementos de uma coleção
print("\nEnumerando uma coleção:")
for i, nome in enumerate(nomes):
print(i, nome)
input("\nPress ENTER to leave...")
# iterar de forma decrescente
# O 3º parâmetro ali é o "passo". No caso o Python vai subtraindo de 1 em 1.
# imprime de 14 a 0
for i in range(14, -1, -1):
print(i)
# da mesma forma pode ser feito para ordem crescente
# imprime de 2 a 10, apenas os pares
for i in range(2, 11, 2):
print(i)
|
# Importando Matplotlib e Numpy
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
# Importando o módulo de Regressão Linear do scikit-learn
from sklearn.linear_model import LinearRegression
def preco_pizza():
# Diâmetros (cm)
Diametros = [[7], [10], [15], [30], [45]]
# Preços (R$)
Precos = [[8], [11], [16], [38.5], [52]]
# Vvisualizar estes dados construindo um plot
"""
plt.figure()
plt.xlabel('Diâmetro(cm)')
plt.ylabel('Preço(R$)')
plt.title('Diâmetro x Preço')
plt.plot(Diametros, Precos, 'k.')
plt.axis([0, 60, 0, 60])
plt.grid()
plt.show()
"""
# Preparando os dados de treino
# Vamos chamar de X os dados de diâmetro da Pizza.
X = [[7], [10], [15], [30], [45]]
# Vamos chamar de Y os dados de preço da Pizza.
Y = [[8], [11], [16], [38.5], [52]]
# Criando o modelo
modelo = LinearRegression()
# Treinando o modelo
modelo.fit(X, Y)
# Prevendo o preço de uma pizza de 20 cm de diâmetro
print(
"Uma pizza de 20 cm de diâmetro deve custar: R$%.2f" % modelo.predict([20][0])
)
# Construindo um scatter plot
# Coeficientes
print("Coeficiente: \n", modelo.coef_)
# MSE (mean square error)
print("MSE: %.2f" % np.mean((modelo.predict(X) - Y) ** 2))
# Score de variação: 1 representa predição perfeita
print("Score de variação: %.2f" % modelo.score(X, Y))
# Scatter Plot representando a regressão linear
plt.scatter(X, Y, color="black")
plt.plot(X, modelo.predict(X), color="blue", linewidth=3)
plt.xlabel("X")
plt.ylabel("Y")
# plt.xticks(())
# plt.yticks(())
plt.grid()
plt.show()
def boston_housing():
# O dataset boston já está disponível no scikit-learn. Assim, apenas carregá-lo.
boston = datasets.load_boston()
# Convertendo o dataset em um DataFrame pandas
df = pd.DataFrame(boston.data)
# Convertendo o título das colunas
df.columns = boston.feature_names
# Adicionando o preço da casa ao DataFrame
df["PRICE"] = boston.target
# Não queremos o preço da casa como variável dependente
x = df.drop("PRICE", axis=1)
# Definindo Y (preço das casas)
y = df.PRICE
# Criando o objeto de regressão linear
regr = LinearRegression()
x_treino, x_teste, y_treino, y_teste = train_test_split(x, y, test_size=0.3)
# Treinando o modelo
regr.fit(x_treino, y_treino)
# Prevendo o preço da casa
previsto = regr.predict(x_teste)
# Comparando preços originais x preços previstos
plt.scatter(y_teste, previsto)
plt.xlabel("Preço")
plt.ylabel("Preço Previsto")
plt.title("Preço Original x Preço Previsto")
plt.grid()
plt.show()
# MSE (Mean Squared Error)
mse1 = np.mean((y_teste - previsto) ** 2)
print(mse1)
# preco_pizza()
boston_housing()
|
"""
Em python um módulo é lido como se fosse um script. Deste modo, sempre que
um módulo for importado será executado como um script. Por isso tomar cuidado
ao importar módulos.
Se o objetivo for criar um módulo que funcione como um script, sendo executando
diretamente, pode ser necessário utilizar __name__ == "__main__". Com isso,
ao executar o módulo, a ordem de execução do script será definida de acordo com
o conteúdo desta condição.
The simplest explanation for the __name__ variable (imho) is the following:
Create the following files.
modulo a
# a.py
import b
and
modulo b
# b.py
print "Hello World from %s!" % __name__
if __name__ == '__main__':
print "Hello World again from %s!" % __name__
Running them will get you this output:
$ python a.py
Hello World from b!
As you can see, when a module is imported, Python sets globals()['__name__'] in this module to the module's name.
Executando o módulo b como se fosse um script.
$ python b.py
Hello World from __main__!
Hello World again from __main__!
As you can see, when a file is executed, Python sets globals()['__name__'] in this file to "__main__".
Só é executado o que está dentro da condição.
font: https://stackoverflow.com/questions/419163/what-does-if-name-main-do
"""
import sys
def erro(msg):
print("Erro:", msg)
sys.exit(1)
def inc(x):
return x + 1
def dec(x):
return x - 1
def quadrado(x):
return x**2
if __name__ == "__main__":
print(inc(10))
print(dec(10))
print(quadrado(5))
input("Presione ENTER para sair...")
|
# This program scrapes the Wikipedia page listing Armenian Artists for a list of their full names.
import urllib3
import certifi
from bs4 import BeautifulSoup
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
wiki="https://en.wikipedia.org/wiki/List_of_Armenian_artists"
# Open the URL. Throws exception if there's a certification error.
try:
page = http.urlopen('GET', wiki, preload_content=False)
except urllib3.exceptions.SSLError as e:
print (e)
# Here's the scraping.
# My target, the artist names, were the only links on the page with a comma "," in the link text.
# The function extracts all links, removing links with None text. It returns a list strings of the artists' names.
def get_names(opened_page):
soup = BeautifulSoup(opened_page,'html.parser')
links = soup.findAll('a')
links = [tag for tag in links if tag.string != None]
link_text = [a.string for a in links]
artists = [name for name in link_text if ',' in name]
return artists
armo_artists = get_names(page)
print(armo_artists)
|
list3 = 'listen'
list4 = 'silent'
def find_string_anagram(list3, list4):
if(sorted(list3) == sorted(list4)):
return 'string is anagram'
else:
return 'string is not anagrams'
print(find_string_anagram(list3, list4))
|
#!/usr/local/bin/python3
a = 'jitendra Ramdas More'
def reverse(a):
str = ""
for i in a:
str = i + str
return str
print(reverse(a))
s = 'jitendra Ramdas More'
def reverser(s):
if len(s) == 0:
return s
else:
return reverser(s[1:]) + s[0]
print(reverser(a))
string = ['b', 'c', 'd', 'e', 'f', 'g', 'h']
def reves(string):
string = string[::-1]
return string
print(reves(string))
|
def is_starts_or_ends_with(str,substr):
if str[0] == substr:
print(substr, ' is a Prefix')
elif str[-1] == substr:
print(substr, 'is a Suffix')
else:
print(substr, ' is neigher Prefix not Suffix')
a = ['h4ow','h8i', 'a23re','rajes34singh', 'yo76u']
substring = ['h', 'i', 'e', 'r', 'o']
for (inputlist,substring) in zip(a, substring):
is_starts_or_ends_with(inputlist, substring)
|
#!/usr/local/bin/python3
a = [10, 30, 20, 40, 50, 60, 70]
b = [10, 30, 40, 60, 80]
t = (10, 20, 30, 40, 50)
ts = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'xyz')
# the use of tuple() function
# when parameter is not passed
tuple1 = tuple()
print(tuple1)
# when an iterable(e.g., list) is passed
tuple2 = tuple(ts)
print(tuple2)
# when an iterable(e.g., dictionary) is passed
dict = { 1 : 'one', 2 : 'two' }
tuple2 = tuple(dict)
print(tuple2)
# when an iterable(e.g., string) is passed
string = 'thisisjitendramore'
tuple4 = tuple(string)
print(tuple4)
|
p1=int(input())
p2=int(input())
p3=int(input())
p4=int(input())
p5=int(input())
p6=int(input())
if(p1==p3):
if(p3==p5):
print ("yes")
else:
print("no")
else:
if(p2==p4):
if(p4==p6):
print ("yes")
else:
print ("no")
else:
print("no")
|
# coding: utf-8
# ## python 编程中一些常用的小技巧
#
# In[1]:
# 1. 原地交换两个数
x,y = 3, 5
print(x,y)
x,y = y,x
print(x,y)
# In[2]:
# 2. 序列数据的倒置
test_list = [1,2,3]
print(test_list)
test_list.reverse()
print(test_list)
test2_list = test_list[::-1]
print(test2_list)
test_str = "Hello world"
test2_str = test_str[::-1]
print(test_str,test2_str)
# In[3]:
# 3. 利用列表中的所有元素,创建一个字符串 "".join
str_list = ["利用","列表","中","的","all","elements"]
test3_str = " ".join(str_list)
print(test3_str)
test_set = {"Hello","world","what","are","you","doing"}
print(test_set)
print(" ".join(test_set)) # 注意 set是 无序的
# In[4]:
# 4. lambda 表达式
test_dict = {
"add": lambda x,y:x+y,
"sub": lambda x,y:x-y
}
print(test_dict["add"](3,5))
# In[5]:
# 5. * 展开
def f(a,b,c):
print(a+b+c)
test_list = ['hello',"world","!"]
print(test_list)
# f(test_list) # 报错
f(*test_list)
test_dict = {"x":1,"y":2,"z":3}
print(test_dict)
f(*test_dict)
# f(**test_dict) # 报错
# In[6]:
# 6. python 中的几种类型
test_range = range(5)
print(type(test_range))
test_list = list(test_range)
print(test_list)
# In[7]:
# 7. python 中的一些常用内置函数
# dir(__builtin__)
# In[8]:
# 8. functools 工具包
import functools as fts
# fts.reduce()
# In[9]:
# 9. 链状比较操作符
n = 3
test_bool = 1 <= n <= 10
print(test_bool)
# In[10]:
# 10. 使用三元操作符来进行条件赋值
y = 19
x = 10 if y is 9 else 20
print(x)
class classA:
def __init__(self,name = "",age = 0):
self.name = name
self.age = age
def show(self):
print("name:%s, age:%d."%(self.name,self.age))
class classB:
def __init__(self,name = "",sex = ""):
self.name = name
self.sex = sex
def show(self):
print("name:%s, sex:%s."%(self.name,self.sex))
pram1 = None
pram2 = None
obj = (classA if y is 19 else classB)(pram1,pram2)
# In[11]:
# 11. 计算三个数中的最小值
def small(a,b,c):
return a if a<b and a<c else(b if b<a and b<c else c)
print(small(1,2,3))
# print(small(1,1,0))
# print(small(1,2,3))
# print(small(1,1,1))
# print(small(4,2,3))
# print(small(1,4,1))
# print(small(1,5,3))
# print(small(1,6,0))
# print(small(1,6,1))
# print(small(1,0,1))
# In[12]:
# 12. 列表推导
test_list =[m**2 if m>10 else m**4 for m in range(20)]
print(test_list)
# In[13]:
# 13. 多行字符串
mult_str =("Hello world"
"Python 编程"
"2017-11-02")
print(mult_str)
# In[14]:
# 14. 存储列表元素到变量中
test_list =[1,2,3,4,5]
a,b,c,d,e = test_list
print(a,b,c,d,e)
# In[15]:
# 15. _ 操作符
# _1+1
# print(_)
# In[16]:
# 16. 查询导入模块的路径
import functools
print(functools)
# In[17]:
# 17. 字典/集合推导
test_dict = {i:i*i for i in range(10)}
print(test_dict)
test_set = {i*2 for i in range(10)}
print(test_set)
# In[18]:
# 18 调试脚本
# import pdb
x = 1
y = 2
# pdb.set_trace()
z = x + y
print(z)
# In[19]:
# 19. in 操作符 (关系操作符 in is not < <= !=)
test_set ={"Apple","Google","Baidu","Facebook"}
test_str ="Baidu"
print("yes") if test_str in test_set else print("No")
print(0 is not 1)
# In[20]:
# 20. 序列切片
test_list = list(range(10))
print(test_list)
print(test_list[8:1:-2])
# In[21]:
# 21. 序列翻转
test_dict = {i:i*2 for i in range(10)}
test_list = [1,2,3,4]
# r_test_dict = dict(reversed(test_dict))
r_test_list = list(reversed(test_list))
print(r_test_list)
print(test_dict)
# print(r_test_dict)
# In[22]:
# 22. 玩转枚举
test_list = [10,20,30]
print(test_list)
test_dict = dict(enumerate(test_list))
print(test_dict)
a,b,c = enumerate(test_list)
print(a,b,c)
print(type(a))
w,x,y,z = range(4)
print(x,y,z)
print(type(x))
# In[23]:
# 23. 使用一行代码计算任何数的阶乘
# reduce(func,list,num) ,func必须是二元操作函数,list 是一个列表,num是其实操作数
import functools as fts
result = (lambda k:fts.reduce(int.__mul__,range(1,k+1),1))(10)
print(result)
# In[24]:
# 24. 找出列表中出现最频繁的数
# count 计数
# max(iteration,key = func) 最大值
test_list = [1,2,2,3,4,1,0,1,1,2,4,4,2,3,1,0,4,2,0,3,1,2,0,4,2]
# test_set = set(test_list)
print(max(set(test_list),key = test_list.count))
print(test_list.count(5))
# In[25]:
# 25. 重置递归限制
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(999)
print(sys.getrecursionlimit())
sys.setrecursionlimit(1000)
print(sys.getrecursionlimit())
# In[26]:
# 26. 检查对象的内存使用情况
a = [1,2,3,4,8,1]
import sys
print(sys.getsizeof(a))
# In[27]:
# 27. 使用lambda 表达式模仿输出
# map(func,iters)
import sys
lprint = lambda *args: sys.stdout.write(" -> ".join(map(str,args))+"\n")
lprint(1,"hello world",'1',1.0)
print(1,"hello",'1',1.0)
print([1,"hello",'1',1.0])
# In[28]:
# 28. 从两个相关的序列构建一个字典
test_tuple1 = (1,2,3)
test_tuple2 = ('a','b','z')
# zip 方法
test_dict = dict(zip(test_tuple1,test_tuple2))
print(test_dict)
# In[29]:
# 29. 一行代码实现搜索字符串的多个前后缀
print("http://www.baidu.com".startswith(("http://","https://")))
print("http://www.baidu.com".endswith((".com",".cn")))
# In[30]:
# 30. 不适用循环构造一个列表
import itertools
test_list = [[1,2],[3,4],[0,1]]
new_list = itertools.chain.from_iterable(test_list)
print(list(new_list))
# In[31]:
# 31. 在python中实现一个真正的switch-case 语句
# switch(n)
# {
# case n1:
# code
# break
# case n2:
# code
# break
# ...
# default:
# code
# }
|
from LinkedList import LinkedList
from Stack import Stack
# 1. Use your linked list code and add a method called reverse() that will reverse the linked list. You can start with making a reversed copy and build up to reversing the linked list "in place" as a strecth goal. For example if your linked list is 3->5->6 your function will return 6->5->3
reverseList = LinkedList()
# add items to the list
reverseList.append(3)
reverseList.append(5)
reverseList.append(6)
# print the lsit
print("List")
reverseList.printList()
# reverse the items in the list
reverseList.reverse()
print("Reversed List")
reverseList.printList()
# add a number to the beginning of the reversd list
print("Prepend 7 to reversed list")
reverseList.prepend(7)
reverseList.printList()
print()
# 2. Write a function called reverse_num() that will reverse an integer using a stack. For example if the integer is 123 your function will return 321, make sure to use a stack!
def reverse_num(num):
"""Reverses an integer"""
# reverse an integer using a stack
stack = Stack()
numString = str(num)
reverseNum = ""
for digit in numString:
stack.push(digit)
for i in range(len(numString)):
reverseNum = f"{reverseNum}{stack.peek()}"
stack.pop()
try:
reverseNum = int(reverseNum)
return reverseNum
except ValueError:
raise ValueError("reverse_num expects valid integer input")
print("Reversed Number: 54784534")
print(reverse_num(54784534))
print("Reversed Number: 123456789")
print(reverse_num(123456789))
print()
# 3. Write a recursive function called sum_num that will take in a list and return the sum of all the elements in the list starting. For example if the list is [5, 4, 1] your funtion will return 10. Be sure to use recursion!
def sum_num(num_list, val=0):
"""Recursively sums numbers in an array"""
if len(num_list) < 1:
return val
# increment the value by the last item in the list
value = val + num_list[-1]
# remove the last item in the list
new_list = list(num_list)
new_list.pop()
# move on to the next item
return(sum_num(new_list, value))
print("Add a list: (10, 11, 12)")
add_list = (10, 11, 12)
print(sum_num(add_list))
print("Add a list: (7, 13, 21, 5, 51)")
add_list2 = (7, 13, 21, 5, 51)
print(sum_num(add_list2))
|
class Engine:
def start(self, starting_speed):
if starting_speed < 3000:
return False
else:
return True
class Battery:
def __init__(self):
self.power = 0
def charge(self, charging_power):
if charging_power < 1000:
return False
else:
self.power = charging_power
return True
class Starter:
def __init__(self):
self.speed = 0
def start(self, battery_power):
if battery_power >=1000:
self.speed = battery_power * 0.75
return True
else:
return False
class Car:
def __init__(self):
self.battery = Battery()
self.starter = Starter()
self.engine = Engine()
def charge_battery(self, charging_power):
self.battery.charge(charging_power)
def turn_key(self):
starter_started = self.starter.start(self.battery.power)
if starter_started:
print('Starter started..')
engine_started = self.engine.start(self.starter.speed)
if engine_started:
print('Engine Started..')
else:
print('Engine failed to start, no enough starter speed..')
else:
print('Starter failed to start, no enough battery power..')
if __name__ == "__main__":
import pdb; pdb.set_trace()
|
#!/usr/bin/python
import __future__
import sys
import getch
from PyDictionary import PyDictionary
try:
# for Python2
from Tkinter import *
except ImportError:
# for Python3
from tkinter import *
try:
# python 2
from tkFont import Font
except ImportError:
# python 3
from tkinter.font import Font
''' Code to get the user input (This might be redundent code for input)'''
# detect python version at runtime
if sys.version_info.major<3:
import thread as _thread
else:
import _thread
import time
def appendAllMeanings(text_list):
''' Append all meanings together '''
appended_text = '';
for values in text_list:
if(appended_text!=''):
appended_text += ";"
appended_text = appended_text + values
return appended_text
def getMeanings(text):
''' Get the meanings from PyDictionary Library '''
dictionary = PyDictionary(text)
meanings = dictionary.getMeanings()
return meanings
def main():
'''
Display with tkinter
'''
master = Tk()
master.withdraw()
clipboard_text = master.clipboard_get()
meaning_text = getMeanings(clipboard_text)
if meaning_text is not None or meaning_text!='':
word_heading = ''
word_meaning = ''
i=1
for words,elements in meaning_text.items():
word_heading = str(words) + ":" +"\n"
if elements is None:
word_meaning = "No meaning(s) available."
break
for parts_of_speech, meaning in elements.items():
meaning_text = appendAllMeanings(meaning)
word_meaning += str(i)+". "+parts_of_speech +": \n"+ meaning_text + "\n\n"
i+=1
# create frame for window
dict_frame = Frame(master, relief=GROOVE, width=50, height=100, bd=1)
dict_frame.place(x=10,y=10)
# create scrollbar
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)
# create text box
txt = Text(master, wrap=WORD,background="#e6ffff")
txt.pack(expand=1, fill=BOTH)
# create fonts
myFont = Font(family="Times New Roman", size=12)
txt.tag_configure("bold", font="wieght:bold")
txt.configure(font=myFont)
# insert text
txt.insert(END, "\n")
txt.insert(END, word_heading + "\n","bold")
txt.insert(END, word_meaning + "\n")
# configure text widget
txt.configure(state=DISABLED)
txt.config(yscrollcommand=scrollbar.set)
# assign scrollbar
scrollbar.config(command=txt.yview)
# show the tkinter window
master.deiconify()
mainloop()
def getSelectedMeanings():
''' begin main execution '''
# print("Press Ctrl+H to get the meaning")
# while True:
# char = getch.getch()
# key_char = ord(char)
# # print(key_char)
# if key_char==8:
main()
|
print('==== Desafio 35 ====')
#Desenvolva um programa que leia o comprimento de três retas e
# diga ao usuário se elas podem ou não formar um triângulo.
print('-=-'*20)
print('Analisador de Triângulos')
print('-=-'*20)
a = float(input('Insira o 1º comprimento: '))
b = float(input('Insira o 2º comprimento: '))
c = float(input('Insira o 3º comprimento: '))
if (b-c) < a < (b+c) and (a-c) < b < (a+c) and (a-b) < c < (a+b):
print('Os comprimentos PODEM formar um triângulo')
else:
print('Os comprimeiros NÃO PODEM formar um triângulo')
|
# Faça um programa que leia o peso de cinco pessoas. No final,
# mostre qual foi o maior e o menor peso lidos.
'''
lista = []
for i in range(1, 6):
peso = float(input(f'Peso da {i}º pessoa: '))
lista.append(peso)
print(f'O MAIOR peso foi: {sorted(lista, reverse=True)[0]}')
print(f'O MENOR peso foi: {sorted(lista, reverse=True)[-1]}')
'''
### SOLUÇÃO DO PROFESSOR
maior = 0
menor = 0
for p in range(1, 6):
peso = float(input(f'Peso da {p}º pessoa: '))
if p == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print(f'O maior peso lido foi {maior}Kg')
print(f'O menor peso lido foi {menor}Kg')
|
print('==== Desafio 8 ====')
#Escreva um programa que leia um valor em metros e o
#exiba convertido em centímetros e milímetros.
mt = float(input('Digite a metragem:: '))
to_dm = mt * 10 #decímetros
to_cem = mt * 100 #centímetros
to_mm = mt * 1000 #melímetros
to_dam = mt / 10 #Decâmetros
to_hm = mt / 100 #Hequitômetros
to_km = mt / 1000 #Kilometros
print('centimeters is {}cm\nMilimeters is {}mm\nDecimeters is {}dm. '.format(to_cem, to_mm, to_dm))
print('Decâmetros is {}dam\nHectômetros is {}hm\nKilômetros is {}km'.format(to_dam , to_hm, to_km ))
|
# Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem:
# - O primeiro valor é maior
# - O segundo valor é maior
# - Não existe valor maior, os dois são iguais
a = float(input('Digite o primeiro número: '))
b = float(input('Digite o segundo número: '))
if a > b:
print('O primeiro número é maior.')
elif a < b:
print('O segundo número é menor.')
else:
print('Não existe número maior, os dois são iguais.')
|
print('==== Desafio 11 ====')
#Faça um programa que leia a largura e a altura de uma
#parede em metros. Calcule a sua área e a quantidade de
#tinta necessária para pintá-la, sabendo que cada litro
#de tinta pinta uma área de 2m(2).
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area_t = larg * alt
#O oposto de potenciação é raiz, portanto,
#foi necessário a tranformação de mt² para ter-se mais
#exatidão no resultado. Normalmente o calculo é x**(1/2) para raiz quadrada,
#x**(1/3) para raiz cúbica e etc#
liter_per_meter = (2**0.5)**2
qtd_tinta = area_t / liter_per_meter
print('A parede possui {:.2f} mt².\nA quantidade de tinta para pintar a parede é {:.2f} lt por mt².'.format(area_t, qtd_tinta))
|
print('==== Desafio 9 ====\n')
#Faça um programa que leia um número inteiro
#qualquer e moestre na tela a sua tabuada.
num = int(input('Digite um número para ver a sua tabuada:: '))
print('-'*12)
print('{} x 1 = {}\n{} x 2 = {}\n{} x 3 = {}\n'.format(num, 1 * num, num, 2 * num, num, 3 * num))
print('-'*12)
|
#!/usr/bin/env python
"""
checkTicket.py
check current ticket list for winner
"""
from playLotto import *
import sys
def main(ticket,draw,game=PowerBall['parts']):
"play the game, get your score"
val=0
cost,playresdict=getWinners(ticket,draw)
for tkt in playresdict.keys():
if playresdict[tkt]['value']>0:
print "%16s\t%s"%(tkt,str(playresdict[tkt]))
#raw_input("hit return to play remaining %s plays"%(n-1))
val+=sum([playresdict[s]['value'] for s in playresdict.keys()])
cost=len(ticket.split("\n"))
winnings=val
return cost,winnings
if __name__=="__main__":
"run application"
print "getting ticket..."
ticket="".join("%s"%s for s in open("mynumbers.lst",'r').readlines())
try:
draw=sys.argv[1]
except IndexError:
draw=raw_input("what are the winning numbers?: ")
cost,resultdict=main(ticket,draw)
print "cost=$%s\twinnings=$%s"%(cost,resultdict)
|
"""
Programme principal du pendu
"""
#Import du module random pour pouvoir selectionner un mot au hasard dans les listes
import random
#Import des variables
from variables import *
#Import des fonctions
from fonctions import *
#Tant que le joueur ne quitte pas le jeu
while quitter != "o" and "O":
#Intro du jeu
print("Bienvenue dans le Bigbee Pendu." )
print("Voici les lettres dont le mot caché est composé : {0}".format(alphabet))
#Demande du pénom au joueur
pseudo = input("Quel est votre pseudo ? ")
#Demande de la difficulté
difficulte = input("Veuillez choisir votre difficulté : Pour Facile, taper 1, pour Intermédiaire, taper 2, pour Difficile, taper 3. Puis appuyer sur entrée : ")
#Tant qu'un chiffre n'a pas été saisi
while not difficulte.isdigit():
#On réaffiche les propositions
difficulte = input("Vous devez saisir 1 pour Facile, 2 pour Intermédiaire, 3 pour Difficile : ")
#Si la difficulté vaut 1
if difficulte == str(1):
#Sélection du mot parmi ceux de la BDD facile
mot = random.choice(liste_easy)
#On indique la longueur du mot
print("C'est un mot en {0} lettres ! ".format(len(mot)))
#On affiche le mot masque grace à sa fonction
dis_mot_masque(mot, liste_dits)
#Si la dificulté vaut 2
elif difficulte == str(2):
mot = random.choice(liste_medium)
print("C'est un mot en {0} lettres ! ".format(len(mot)))
dis_mot_masque(mot, liste_dits)
#Si la difficulté vaut 3
elif difficulte == str(3):
mot = random.choice(liste_hard)
print("C'est un mot en {0} lettres ! ".format(len(mot)))
dis_mot_masque(mot, liste_dits)
#Tant que le joueur n'a pas gagné ou perdu
while continuer_partie is True:
#Demande de saisie au joueur
lettre = input("Saississez une lettre de l'alphabet : ")
#PLUSIEURS LETTRES SAISIES + CONTROLE SUR ALPHABET
#Tant que plusieurs lettres sont tapés:
while len(lettre) > 1:
#Seule la première est prise en compte
lettre = lettre[0]
print("Vous avez tapés plusieurs lettres ! Seule la première a été prise en compte.")
#Tant que la lettre n'est pas autorisée
while lettre not in alphabet:
#Demande de saisie au joueur
print("Erreur ! Vous avez saisi au moins un caractère non autorisé (majuscule, chiffre ou autre)")
lettre = input("Saississez une lettre de l'alphabet : ")
#PLUSIEURS LETTRES SAISIES + CONTROLE SUR LISTE_DITS
#Tant que plusieurs lettres sont tapés:
while len(lettre) > 1:
#Seule la première est prise en compte
lettre = lettre[0]
print("Vous avez tapés plusieurs lettres ! Seule la première a été prise en compte.")
#Tant que la lettre a déjà été dictee
while lettre in liste_dits:
#On informe le joueur
print("Cette lettre a déjà été dite !")
#Il doit resaisir une lettre
lettre = input("Saississez une lettre de l'alphabet : ")
#UNE SEULE LETTRE SAISIE
#Tant que la lettre saisie est autorisée
while lettre not in alphabet:
#Demande de saisie au joueur
print("Erreur ! Vous avez saisi au moins un caractère non autorisé (majuscule, chiffre ou autre)")
lettre = input("Saississez une lettre de l'alphabet : ")
#Tant que la lettre a déjà été dictee
while lettre in liste_dits:
#On informe le joueur
print("Cette lettre a déjà été dite !")
#Il doit resaisir une lettre
lettre = input("Saississez une lettre de l'alphabet : ")
#Tant que plusieurs lettres sont tapés:
while len(lettre) > 1:
#Seule la première est prise en compte
lettre = lettre[0]
print("Vous avez tapés plusieurs lettres ! Seule la première a été prise en compte.")
#Tant que la lettre a déjà été dictee
while lettre in liste_dits:
#On informe le joueur
print("Cette lettre a déjà été dite !")
#Il doit resaisir une lettre
lettre = input("Saississez une lettre de l'alphabet : ")
#Si la lettre est contenu dans le mot:
if lettre in mot:
#Pour chaque indice avec sa lettre contenus dans le mot:
for indice, elem in enumerate(mot):
#Si une lettre du mot correspond avec celle donnee par l'utilisateur:
if lettre == elem:
#On incrémente le compteur de 1
compteur += 1
#On ajoute à la liste des lettres dites la lettre
liste_dits.append(lettre)
#On donne la position de la lettre au joueur:
print("Ok ! La lettre se trouve en position {0}".format(indice + 1))
#Affichage du mot masqué
dis_mot_masque(mot, liste_dits)
#Si notre compteur devient égal à la longueur du mot
if compteur == len(mot):
#On indique au joueur que c'est gagné ! Et on confirme le mot en majuscule
print("Bravo, c'est gagné ! C'était bien {0} !".format(mot.upper()))
#La partie se termine
continuer_partie = False
#Sinon
else:
#On désincremente nb_coups de 1
nb_coups -= 1
#Indique au joueur le nombre de coups restants
print("Zut ! Il vous reste {0} coup(s) ".format(nb_coups))
#Affichage d'un dessin du pendu
print(dessins[pendu])
#Incrémentation du compteur pendu pour pouvoir passer au dessin suiant en cas d'une autre erreur
pendu += 1
#Ajoute la lettre donnée à la liste de lettres déjà dictées
liste_dits.append(lettre)
#Affichage du mot masqué
dis_mot_masque(mot, liste_dits)
#Si le nombre de coups restants vaut zéro:
if nb_coups == 0:
#Le joueur ne peut plus continuer la partie car il a perdu
continuer_partie = False
#On indique au joueur qu'il n'a plus de coups et le mot qu'il devait trouver en majuscule
print("Vous avez épuisé tous vos coups ! C'est perdu.\nLe mot était {0}".format(mot.upper()))
#On indique que la partie est terminé
print("La partie est terminé.")
#Le nombre de coups restant devient le score du joueur
score = nb_coups
#Ouverture du fichier de sauvegarde des scores en ecriture avec ajout. S'il n'existe pas, il est crée dans le repertoire courant du jeu
fichier_score = open("score.txt", "a")
#Enregistrement des donnes relatives au score dans le fichier
fichier_score.write("\n" + pseudo + "\t" + str(score) + "\t" + mot)
#Fermeture du fichier
fichier_score.close()
#Indication de l'enregistrement du score
print("Votre score a été enregistré dans le répertoire du jeu")
#On demande au joueur si il veut quitter le programme, si non, il recommence à jouer et les paramètres sont réinitialisés
quitter = input("Voulez-vous quitter le jeu ? o / n. ")
continuer_partie = True
nb_coups = 10
compteur = 0
liste_dits = []
pendu = 0
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 22:36:10 2019
@author: cannybiscuit
"""
def bubble_sort_algorithm(array):
n = len(array)
# Loop through the entire array
for i in range(n):
# Here we repeatedly step through the list comparing adjacent pairs
# If an element is larger than the element to the right of it will get swapped
# The array is traversed until all elements have been sorted
for j in range(0, n-i-1):
# EXAMPLE:
# arr = [1, 5, 2, 6, 4]
# first iteration => [1,2,5,4,6]
# Second iteration = [1,2,4,5,6]
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
def main():
array = [25,66,1,4,77,55,13,5,3]
bubble_sort_algorithm(array)
for i in range(len(array)):
print("%d" %array[i])
main()
|
from helpers import find_manhattan_distance
file = open("input.txt", "r")
lines = file.readlines()
# parse coordinates to tuples
# (x, y, count_locations, is_outside)
coordinates = [ (int(line.split(",")[0]), int(line.split(",")[1]), 0, False) for line in lines]
# find min/max coordinates
min_x = coordinates[0][0]
min_y = coordinates[0][1]
max_x = coordinates[0][0]
max_y = coordinates[0][1]
for i in range(1, len(coordinates)):
x = coordinates[i][0]
y = coordinates[i][1]
if x < min_x:
min_x = x
elif x > max_x:
max_x = x
if y < min_y:
min_y = y
elif y > max_y:
max_y = y
# some extra margin to ensure reliability
min_x -= 5
min_y -= 5
max_x += 5
max_y += 5
# iterate over all locations
for curr_x in range(min_x, max_x + 1):
for curr_y in range(min_y, max_y + 1):
# find nearest coordinate
nearest_index = 0
nearest_dist = find_manhattan_distance(curr_x, curr_y, coordinates[0][0], coordinates[0][1])
multiple_nearest = False
for i in range(1, len(coordinates)):
(x, y, count_locations, is_infinite) = coordinates[i]
dist = find_manhattan_distance(curr_x, curr_y, x, y)
if dist < nearest_dist:
nearest_dist = dist
nearest_index = i
multiple_nearest = False
elif dist == nearest_dist:
multiple_nearest = True
# avoid incrementing if multiple coordinates owns a location
if not multiple_nearest:
(x, y, count_locations, is_infinite) = coordinates[nearest_index]
# increment
count_locations += 1
# find if coordinate is infinite in reach
is_infinite = is_infinite or (curr_x == min_x or curr_x == max_x or curr_y == min_y or curr_y == max_y)
# reassign coordinate
coordinates[nearest_index] = (x, y, count_locations, is_infinite)
# find largest non-infinite coordinate
coord = sorted([ c for c in coordinates if not c[3] ], key=lambda c: c[2], reverse = True)
print(coord[0][2])
|
orignal = [[[1],2],3,4,[5,[6,7]],8]
def flatten(nested):
try:
for sublist in nested:
for element in flatten(sublist):
yield element
except TypeError:
yield nested
print list(flatten(orignal))
|
#Write a Python program that takes mylist = [1, 2, 3, 4, 5] and print sum of all the items in the list.
mylist=[1, 2, 3, 4, 5]
x=sum(mylist)
print(x)
|
#Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and sort the list using list sort function.
mylist=["WA","CA","NY","IL","WA","CA","WA"]
mylist.sort()
print(mylist)
|
#Write a Python program that takes mylist = ["WA", "CA", "NY", “IL”, “WA”, “CA”, “WA”] and print how many times each state appeared in the list.
mylist=["WA", "CA", "NY","IL","WA","CA","WA"]
x=mylist.count("WA")
y=mylist.count("CA")
print("WA appeared :",x,"times")
print("CA appeared :",y,"times")
|
# Write Python program that asks for first name and last name seprately, then print the full name
FirstName = input("First Name:")
LastName = input("Last Name:")
print(FirstName,LastName)
|
from decimal import Decimal
from collections.abc import Callable
from typing import Union
Number = Union[float, Decimal]
def newton_method(
f: Callable[[Number], Number],
f_: Callable[[Number], Number],
x0: Number,
count: int = 20,
) -> Number:
'''
Newton's Method
f : target function
f_ : derivative of target function
x0 : Initial x value
'''
x = x0
print(f'{x=}')
for _ in range(count):
x = x - f(x)/f_(x)
print(f'{x=}')
return x
def secant_method(
f: Callable[[Number], Number],
f_: Callable[[Number], Number],
x0: Number,
x1: Number,
count: int = 20,
) -> Number:
'''
Secant Method
f : target function
f_ : derivative of target function
x0 : First x value
x1 : Second x value
'''
x_prev, x = x0, x1
print(f'{x=}')
for _ in range(count):
delta_f = f(x) - f(x_prev)
if delta_f == 0:
break
x_prev, x = x, x - f(x)*(x - x_prev)/delta_f
print(f'{x=}')
return x
newton_method(
f=lambda x: x**2 - 4,
f_=lambda x: 2*x,
x0=Decimal(10),
)
secant_method(
f=lambda x: x**2 - 4,
f_=lambda x: 2*x,
x0=Decimal(10),
x1=Decimal(9),
)
|
def func():
for i in range(0, 5):
try:
return i
finally:
if i != 3:
# SyntaxError: 'continue' not supported inside 'finally' clause
continue
print(func())
|
def solve(array):
mid = calc(array)
return (array[:mid+1], array[mid:])
def calc(array):
high = len(array)
low = 0
while low < high:
mid = (low + high)//2
if mid == 0:
return 0
elif mid == len(array) - 1:
return len(array) - 1
a, b, c = array[mid - 1], array[mid], array[mid + 1]
if a < b < c:
low = mid
elif a > b > c:
high = mid
else:
return mid
print(solve([1, 3, 4, 5, 6, 7, 9, 4, 1]))
|
def nthprime(n: int) -> int:
'''
Returns nth prime number.
Reference:
https://stackoverflow.com/a/48040385/13977061
'''
start = 2
count = 0
while True:
if all([start % i for i in range(2, int(start**0.5 + 1))]):
count += 1
if count == n:
return start
start += 1
print(nthprime(1) == 2)
print(nthprime(2) == 3)
print(nthprime(3) == 5)
print(nthprime(4) == 7)
print(nthprime(5) == 11)
print(nthprime(6) == 13)
print(nthprime(7) == 17)
print(nthprime(8) == 19)
print(nthprime(9) == 23)
print(nthprime(10) == 29)
print(nthprime(100) == 541)
|
import numpy as np
from position import Position
EMPTY_SPACE = '.'
class OutOfBoundsException(Exception):
pass
class Board:
BOARD_SIZE = 15
def __init__(self, ):
self.spaces = np.zeros((self.BOARD_SIZE, self.BOARD_SIZE), 'string')
# TODO: find a better way to initialize to spaces
for x in range(len(self.spaces)):
for y in range(len(self.spaces[x])):
self.spaces[x,y] = EMPTY_SPACE
def is_blank(self, position):
# Returns True if the block is empty
return self[position] == EMPTY_SPACE
def position_is_out_of_bounds(self, position):
return (position.down < 0 or position.down >= self.BOARD_SIZE) or \
(position.across < 0 or position.across >= self.BOARD_SIZE)
def __getitem__(self, position):
return self.spaces[position.down, position.across]
def __setitem__(self, position, letter):
self.spaces[position.down, position.across] = letter
def __str__(self):
string = ' \n'
for x in range(len(self.spaces)):
string += str(x % 10)
for y in range(len(self.spaces[x])):
string += self.spaces[x,y]
string += '\n'
string += '.'
for y in range(len(self.spaces[0])):
string += str(y % 10)
return string
def copy(self):
new_board = Board()
new_board.spaces = self.spaces.copy()
return new_board
def add_letters(self, letters, starting_position, direction):
'''Put letters on each blank space on the board, starting at
starting_position and moving in direction until all the letters are used
up. Throws OutOfBoundsException if the word starts or ends OOB.'''
position = starting_position.copy()
while len(letters) > 0:
if self.position_is_out_of_bounds(position):
raise OutOfBoundsException("trying to add a letter OOB")
if self.is_blank(position):
# There's nothing here- put a letter down
self[position] = letters[0]
letters = letters[1:]
# Move to the next position
position.add_in_direction(1, direction)
def get_word(self, position, direction):
def get_before_blank(starting_position, direction, travel_direction):
'''Returns the position of the last char before a blank (or edge of
board). Moves along direction (DOWN, ACROSS) in travel_direction
(left/up/-1 or down/across/+1).'''
assert(not self.is_blank(starting_position))
position = starting_position.copy()
while not (self.position_is_out_of_bounds(position) or
self.is_blank(position)):
position.add_in_direction(travel_direction, direction)
# We have the position of the blank/edge! Back up 1.
position.add_in_direction(-travel_direction, direction)
return position
position = get_before_blank(position, direction, -1)
end = get_before_blank(position, direction, +1)
word = self[position]
while position != end:
position.add_in_direction(1, direction)
word += self[position]
return word
def get_position_of_all_letters(self,):
'''Returns a Position for each letter currently placed on the board'''
position_list = []
for x in range(len(self.spaces)):
for y in range(len(self.spaces[0])):
position = Position(x, y)
if not self.is_blank(position):
position_list.append(position)
return position_list
def get_spaces_to_next_letter(self, position_with_direction):
"""Checks the space before and the spaces ahead for the closest letter"""
assert self.is_blank(position_with_direction.position)
# First, check if the space before has a letter
back_position = position_with_direction.position.copy()
back_position.add_in_direction(-1, position_with_direction.direction)
if not self.is_blank(back_position):
# The space before us has a letter!
return 1
# Nothing behind, so find the closest letter going forward
forward_position = position_with_direction.position.copy()
for spaces_away in range(1, self.BOARD_SIZE):
forward_position.add_in_direction(1, position_with_direction.direction)
if not self.is_blank(forward_position):
return spaces_away
assert False, "couldn't find a letter"
|
"""========================================================================================================================
Calvin is driving his favorite vehicle on the 101 freeway. He notices that the check engine light of his vehicle is on, and he wants to service it immediately to avoid any risks. Luckily, a service lane runs parallel to the highway. The length of the highway and the service lane is N units. The service lane consists of N segments of unit length, where each segment can have different widths.
Calvin can enter into and exit from any segment. Let's call the entry segment as index i and the exit segment as index j. Assume that the exit segment lies after the entry segment(j>i) and i ≥ 0. Calvin has to pass through all segments from index i to indexj (both inclusive).
Paradise Highway
Calvin has three types of vehicles - bike, car and truck, represented by 1, 2 and 3 respectively. These numbers also denote the width of the vehicle. We are given an array width[] of length N, where width[k] represents the width of kth segment of our service lane. It is guaranteed that while servicing he can pass through at most 1000 segments, including entry and exit segments.
If width[k] is 1, only the bike can pass through kth segment.
If width[k] is 2, the bike and car can pass through kth segment.
If width[k] is 3, any of the bike, car or truck can pass through kth segment.
Given the entry and exit point of Calvin's vehicle in the service lane, output the type of largest vehicle which can pass through the service lane (including the entry & exit segment)
Input Format
The first line of input contains two integers - N & T, where N is the length of the freeway, and T is the number of test cases. The next line has N space separated integers which represents the width array.
T test cases follow. Each test case contains two integers - i & j, where i is the index of segment through which Calvin enters the service lane and j is the index of the lane segment where he exits.
Output Format
For each test case, print the number that represents the largest vehicle type that can pass through the service lane.
Note
Calvin has to pass through all segments from index i to indexj (both inclusive).
Constraints
2 <= N <= 100000
1 <= T <= 1000
0 <= i < j < N
2 <= j-i+1 <= min(N,1000)
1 <= width[k] <= 3, where 0 <= k < N
Sample Input #00
8 5
2 3 1 2 3 2 3 3
0 3
4 6
6 7
3 5
0 7
Sample Output #00
1
2
3
2
1
Explanation for Sample Case #0
Below is the representation of lane.
|HIGHWAY|Lane| -> Width
0: | |--| 2
1: | |---| 3
2: | |-| 1
3: | |--| 2
4: | |---| 3
5: | |--| 2
6: | |---| 3
7: | |---| 3
(0, 3): Because width[2] = 1, only the bike represented as 1 can pass through it.
(4, 6): Here the largest allowed vehicle which can pass through the 5th segment is car and for the 4th and 6th segment it's the truck. Hence the largest vehicle allowed in these segments is a car.
(6, 7): In this example, the vehicle enters at the 6th segment and exits at the 7th segment. Both segments allow even truck to pass through them. Hence truck is the answer.
(3, 5): width[3] = width[5] = 2. While 4th segment allow the truck, 3rd and 5th allow upto car. So 2 will be the answer here.
(0, 7): Bike is the only vehicle which can pass through the 2nd segment, which limits the strength of whole lane to 1.
========================================================================================================================"""
def main():
parameters = map(int,raw_input().split(" "))
lanes = map(int,raw_input().split(" "))
for tests in range(parameters[1]):
test = map(int,raw_input().split(" "))
print min(lanes[(test[0]):(test[1])+1])
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-f",help="Interpret a brainfuck file")
args = parser.parse_args()
open_file = args.f
def get_symbols(file_name):
with open(file_name , 'r') as file:
return [char for char in file.read() if char != '\n']
def interpret(code):
i=0
memory = [0]
pointer_location = 0
string = ""
while i < len(code):
if(code[i]=='<'):
if pointer_location > 0:
pointer_location-= 1
elif(code[i]=='>'):
pointer_location +=1
if(len(memory)<=pointer_location):
memory.append(0)
elif(code[i]=='+'):
memory[pointer_location] += 1
elif(code[i]=='-'):
if(memory[pointer_location] > 0):
memory[pointer_location] -= 1
elif(code[i]=='.'):
string = string +chr(memory[pointer_location])
elif(code[i]==','):
inp = int(input("Input :"))
memory[pointer_location]= inp
elif(code[i]=='['):
if(memory[pointer_location]==0):
open_bracket = 1
while open_bracket > 0:
i+=1
if(code[i]==']'):
open_bracket -=1
elif(code[i]=='['):
open_bracket +=1
elif(code[i]==']'):
closed_bracket =1
while closed_bracket > 0:
i-=1
if code[i] == '[':
closed_bracket-=1
elif code[i] == ']':
closed_bracket+=1
i-=1
i+=1
print(string)
symbols = get_symbols(open_file)
interpret(symbols)
|
# 2019 카카오 개발자 겨울 인턴십 : 크레인 인형뽑기 게임
def solution(board, moves):
answer = 0
pre_dolls = ['']
line_dict = {idx: 0 for idx in range(1, len(board)+1)}
for mov in moves:
which_line = line_dict[mov]
if which_line > len(board) - 1:
continue
mov -= 1
while board[which_line][mov] == 0:
which_line += 1
append_doll = board[which_line][mov]
if pre_dolls[-1] == append_doll:
pre_dolls.pop()
answer += 2
else:
pre_dolls.append(append_doll)
line_dict[mov+1] = which_line + 1
return answer
|
def alpha_reverse(list):
f_output=input("Enter the file name with extension name(.txt) in which the decrypted code will be saved: ")
coding=list[0]+list[1]+list[2]+list[3]
a_list=list[5:]
dlist=[]
if coding=='#a1#':
for i in a_list:
if ord(i)>=97 and ord(i)<=122:
d=122-ord(i)
dlist.append(chr(97+d))
elif ord(i)>=0 and ord(i)<=31 :
d=31-ord(i)
dlist.append(chr(0+d))
elif ord(i)>=32 and ord(i)<=64:
d=64-ord(i)
dlist.append(chr(32+d))
elif ord(i)>=65 and ord(i)<=90:
d=90-ord(i)
dlist.append(chr(65+d))
elif ord(i)>=91 and ord(i)<=96:
d=96-ord(i)
dlist.append(chr(91+d))
elif ord(i)>=123 and ord(i)<=126 :
d=126-ord(i)
dlist.append(chr(123+d))
elif ord(i)>=128 and ord(i)<=255 :
d=255-ord(i)
dlist.append(chr(128+d))
dll=len(dlist)
k=open(f_output, 'a')
i=0
while i<dll:
k.write(str(dlist[i]))
i=i+1
k.close()
print("Decryption Completed!!")
else:
print('Cryptography code mismatch!!')
def morse_code(f_name):
f_output=input("Enter the file name with extension name(.txt) in which the decrypted code will be saved: ")
rlist=[]
f=open(f_name, "r")
array=f.readlines()
m_array=array[1:]
e_code=array[0]
#print(e_code)
CODE = {'.-\n':'A','-...\n':'B','-.-.\n':'C','-..\n':'D','.\n':'E','..-.\n':'F','--.\n':'G','....\n':'H','..\n':'I','.---\n':'J','-.-\n':'K','.-..\n':'L','--\n':'M','-.\n':'N','---\n':'O','.--.\n':'P','--.-\n':'Q','.-.\n':'R','...\n':'S','-\n':'T','..-\n':'U','...-\n':'V','.--\n':'W','-..-\n':'X','-.--\n':'Y','--..\n':'Z','-----\n':'0','.----\n':'1','..---\n':'2','...--\n':'3','....-\n':'4','.....\n':'5','-....\n':'6','--...\n':'7','---..\n':'8','----.\n':'9','@\n':' '}
if e_code=='#m1#\n':
for i in m_array:
#print(CODE[i.upper()])
rlist.append(CODE[i.upper()])
#print(rlist)
rdl=len(rlist)
k=open(f_output,'a')
i=0
while i<rdl:
k.write(str(rlist[i]))
i=i+1
k.close()
print("Decryption Completed!!")
else:
print('Crytography code mismatch!! ')
if __name__=="__main__":
while 1:
menuch=input("Go to the menu: Y/N: ")
if menuch=="y" or menuch=='Y':
f_name=input("Enter the the file name (with extension name (.txt))in which the encrypted code is present: ")
list=[]
fp=open(f_name,'r')
while 1:
char=fp.read(1)
if not char:
break
list.append(char)
print(list)
print("\n\n")
print(" a: Alpha reverse")
print(' b: Morse Code')
print(" x : Exit")
ch = input("Enter in which format the code is: ")
if ch == 'a':
alpha_reverse(list)
if ch=='b':
morse_code(f_name)
if ch == 'x':
break
elif ch!='a' and ch!='b' and ch!='x':
print('invalid choice')
else:
break
|
month = input("Enter the name of the month: ")
days_in_month = 31
if month == "April" or month == "June" or month == "September" or month == "November":
days_in_month = 30
elif month == "February":
days_in_month = "28 or 29"
print(month, "has", days_in_month, "days in it.")
|
import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv")
# code = data["code"].tolist()
# letter = data["letter"].tolist()
# nato_alpha = {letter[i]: code[i] for i in range(len(letter))}
# same thing as above but shorter
nato_alpha = {row.letter: row.code for (index, row) in data.iterrows()}
on = True
while on:
user_input = input("Enter a word:\n> ").upper()
try:
code_list = [nato_alpha[letter] for letter in user_input]
print(code_list)
except KeyError:
print("Please only enter letters.")
|
#!/usr/bin/env python3
# James Jessen
# CptS 434 - Assignment 1
# Due 2019-09-05
# Python Tutorial: https://docs.python.org/3.7/tutorial/index.html
# Python Documentation: https://docs.python.org/3.7/index.html
# python 1hw/hw1.py > 1hw/output.txt
from LinearRegression import linearRegression as linReg
dataPath = 'data/Cereals.csv'
target = 'Rating'
precision = 2
emptyMethods = ['zero', 'drop']
# Write a code for regression of nutritional rating vs sugar and fiber.
# Train with example from Cereals dataset on class web page
# Report bias and slopes for predictors sugar and fiber,
# coefficient of determination, R2, and standard error of estimation, s.
# Consider protein, fat, and sodium separately as a third attribute,
# in addition to sugar and fiber, to predict the nutritional rating cereals.
# Report the change in R2 and s relative to sugar and fiber only.
thirdAttributes = ['Protein', 'Fat', 'Sodium']
for emptyMethod in emptyMethods:
predictors = ['Sugars', 'Fiber']
baseR2, baseS = linReg(target, predictors, dataPath,
emptyCellHandling=emptyMethod, outputPrecision=precision)
print("R² = {}%".format(round(baseR2 * 100, precision)))
print("s = {}".format(round(baseS, precision)))
print('_'*43 + '\n')
for thirdAttribute in thirdAttributes:
predictors = ['Sugars', 'Fiber']
predictors.append(thirdAttribute)
r2, s = linReg(target, predictors, dataPath,
emptyCellHandling=emptyMethod, outputPrecision=precision)
print("R² = {0}% Δ({1:+}%)".format(round(r2 * 100, precision), round((r2 - baseR2)*100, precision)))
print("s = {0} Δ({1:+})".format(round(s, precision), round(s - baseS, precision)))
print('_'*43 + '\n')
print('\n' + '#'*43 + '\n')
|
print('''This is a car game. It can be played like this---
first You have to start the game by typing 'start' and
then the journey will be started. If you want to stop the
car, then just type "park".Finally if you want to quit,
then just type "q" to stop the game. ''')
while True:
a=input("")
if a=="start":
print ("\nThe journey is Started.")
p=input("Where do you want to go?\n")
print("we are going to "+p)
elif a=="park":
print("\nYour car is parked. Your journey is stopped.")
print("If you have reached Press \'q\' to stop. or press \'r\' to continue")
elif a=="r":
print("\nYour journey is continu")
pass
elif a=="q":
print("\nYou quit.")
break
else:
print("\nThe game didn't get it.")
print("\nThank you for playing.")
|
'''
Created on Mar 7, 2018
@author: awon
'''
# dynamic variable's declaration
# define functions using "def" key word
# No need to define return value to function'
# Indentation is very important
# ":" is written after a conditional or loop statement
def add(a,b):
return a+b
def add_fixed_value(a):
y=5
return y+a
def substract(a,b):
if a < b:
return a + b
return a-b
def loop_test():
i = 0
for i in range(20):
print i
def lower_case(a):
return a.lower()
def upper_case(a):
return a.upper()
print substract(3,2)
print loop_test()
print lower_case('AWON')
print upper_case('awon')
print 'this is a text plus a number ' + str(10)
|
cars = 100 #The variable for total cars in existence.
space_in_a_car = 4 #The variable for amount of people-space per car.
drivers = 30 #The amount of total drivers assigned to a car.
passengers = 90 #The amount of total passengers available to occupy car space.
cars_not_driven = cars - drivers #The remainder of cars remaining unoccupied by a driver.
cars_driven = drivers #The amount of currently occupied cars.
carpool_capacity = cars_driven * space_in_a_car #The amount of total space for all driven cars.
average_passengers_per_car = passengers / cars_driven #The average amount of passengers per driven car.
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")
|
from random import randrange
failNum = 4
skill = 4
def dieMaker(sides):
"""return a die roller function"""
def die():
return randrange(1, sides+1)
return die
def roll(numDice, die):
"""
Run game mechanic roll.
Roll a number of dice then check to see if any are
below the suceess threshold. The Skill value allows
a number of dice equal ot below the Skill to be re-rolled.
"""
rolls = [die() for x in range(numDice)]
fails = [x for x in rolls if x <= failNum]
if (len(fails) > skill):
return False
rerolls = [die() for x in fails]
fails = [x for x in rerolls if x <= failNum]
return len(fails) == 0
def test(min, max, die, trials=100):
"""
Run trials for different pool sizes, since I suck at prob-stat.
"""
results = dict()
for pool in range(min, max):
results[pool] = dict()
for trial in range(trials):
res = roll(pool, die)
results[pool][res] = results[pool].get(res, 0) + 1
return results
if __name__ == '__main__':
n = 10000
trials = test(1, 13, dieMaker(12), n)
prob_success = [float(x[True])/n for x in trials.values()]
print('d12:')
print([x for x in enumerate(prob_success, 1)])
trials = test(1, 13, dieMaker(10), n)
prob_success = [float(x[True])/n for x in trials.values()]
print('d10:')
print([x for x in enumerate(prob_success, 1)])
|
#
#author: Grace Hsu
#Date: 12/5/18 Edits
#
import os
import csv
import datetime
bank_path = os.path.join('Resources', 'budget_data.csv')
#create a file for the financial summary
financial_analysis_summary = open('financial_analysis.txt', 'w').close()
financial_output_path = os.path.join('financial_analysis.txt')
with open(bank_path, 'r', newline='') as bank_file:
bank_file = csv.reader(bank_file, delimiter=',')
file_header = next(bank_file)
#store monthly data in a list format
monthly_data = []
month=[]
profit=[]
for row in bank_file:
monthly_data.append(row)
month.append(row[0])
profit.append(row[1])
formatted_months = []
# #create for loop to change month list format from mon-yy to Mon-year
for each in month:
date = each
stripped_date = datetime.datetime.strptime(date, '%b-%y').date()
formatted_months.append(stripped_date.strftime('%b-%Y'))
total_months = len(month)
net_profit = 0
average_change = 0
greatest_inc = 0
greatest_dec = 0
#Calculate the average change.
#list to store changes
profit_change = []
previous_month = month[0]
previous_profit = profit[0]
for each in monthly_data:
current_profit = each[1]
current_month = each[0]
if current_month != previous_month:
profit_change.append(int(current_profit) - int(previous_profit))
previous_profit= current_profit
#average all the values in the list profit_change
for each in profit_change:
average_change += int(each)
average_change = average_change / len(profit_change)
average_change = "{:.2f}".format(average_change)
#create for loop to look in profit_change list to find max and min
# for each in profit_change:
for each in profit_change:
current_profit = each
if current_profit > greatest_inc:
greatest_inc = current_profit
greatest_inc_month_index = profit_change.index(each)
elif current_profit < greatest_dec:
greatest_dec = current_profit
greatest_dec_month_index = profit_change.index(each)
greatest_inc_month = formatted_months[greatest_inc_month_index+1]
greatest_dec_month = formatted_months[greatest_dec_month_index+1]
for each in profit:
net_profit += int(each)
print("Financial Analysis")
print("----------------------------------------------------------")
print(f'Total Months: {total_months}')
print(f'Total: $ {net_profit}')
print(f'Average change: $ {average_change}')
print(f'Greatest Increase in Profits: {greatest_inc_month} (${greatest_inc})')
print(f'Greatest Decrease in Profits: {greatest_dec_month} (${greatest_dec})')
with open(financial_output_path, 'w') as financial_output:
financial_output.write("Financial Analysis\n")
financial_output.write("-------------------------------------------------------\n")
financial_output.write(f"Total Months: {total_months}\n")
financial_output.write(f"Total: ${net_profit}\n")
financial_output.write(f"Average Change: ${average_change}\n")
financial_output.write(f"Greatest Increase in Profits: {greatest_inc_month} (${greatest_inc})\n")
financial_output.write(f"Greatest Decrease in Profits: {greatest_dec_month} (${greatest_dec})\n")
|
for i in range(1,100) :
msg = ''
if i%3 == 0 :
msg = 'Fizz'
if i%5 == 0 :
msg += 'Buzz'
if not msg :
print (i)
else :
print(msg)
|
'''
Timer.py
Written using Python 2.7.12
@ Matt Golub, August 2018.
Please direct correspondence to [email protected].
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import time
class Timer(object):
'''Class for profiling computation time.
Example usage:
t = Timer(3) # Build a timer object to profile three tasks.
t.start() # Start the timer.
run_task_1() # Run task 1 of 3.
t.split('Task 1') # Measure time taken for task 1.
run_task_2() # Run task 2 of 3.
t.split('Task 2') # Measure time taken for task 2.
run_task_3() # Run task 3 of 3.
t.split('Task 3') # Measure time taken for task 3.
t.disp() # Print profile of timing.
--> Total time: 16.00s
--> Task 1: 2.00s (12.5%)
--> Task 2: 8.00s (50.0%)
--> Task 3: 6.00s (37.5%)
'''
def __init__(self, n_tasks=1, n_indent=0, name='Total'):
'''Builds a timer object.
Args:
n_tasks: int specifying the total number of tasks to be timed.
n_indent (optional): int specifying the number of indentation
to prefix into print statements. Useful when utilizing multiple
timer objects for profile nested code. Default: 0.
name (optional): string specifying name for this timer, used only
when printing updates. Default: 'Total'.
Returns:
None.
'''
if n_tasks < 0:
raise ValueError('n_tasks must be >= 0, but was %d' % n_tasks)
if n_indent < 0:
raise ValueError('n_indent must be >= 0, but was %d' % n_indent)
self.n = n_tasks
'''Pre-allocate to avoid having to call append after starting the timer
(which might incur non-uniform overhead, biasing timing splits).
If more times are recorded than pre-allocated, lists will append.
Note that self.times has n+1 elements (to include a start value) while self.task_names has n elements
'''
self.times = [np.nan for idx in range(n_tasks + 1)]
self.task_names = [None for idx in range(n_tasks)]
self.print_prefix = '\t' * n_indent
self.name = name
self.idx = -1
def __call__(self):
'''Returns the time elapsed since the timer was started.
If start() has not yet been called, returns NaN.
'''
if self.is_running():
return time.time() - self.times[0]
else:
return 0.0
def start(self):
'''Starts the timer'''
if self.is_running():
self._print('Timer has already been started. '
'Ignoring call to Timer.start()')
else:
self.idx += 1
self.times[self.idx] = time.time()
def is_running(self):
'''Returns a bool indicating whether or not the timer has been started.
'''
return self.idx >= 0
def split(self, task_name=None):
'''Measures the time elapsed for the most recent task.
Args:
task_name (optional): A string describing the most recent task.
Returns:
None.
'''
if self.is_running():
self.idx += 1
if self.idx <= self.n:
self.times[self.idx] = time.time()
self.task_names[self.idx - 1] = task_name
else:
self.times.append(time.time())
self.task_names.append(task_name)
self.n += 1
self._print('Appending Timer lists. '
'This may cause biased time profiling.')
else:
self._print('Timer cannot take a split until it has been started.')
def disp(self, print_on_single_line=False):
'''Prints the profile of the tasks that have been timed thus far.
Args:
None.
Returns:
None.
'''
if not self.is_running():
self._print('Timer has not been started.')
elif self.idx == 0:
self._print('Timer has not yet taken any splits to time.')
else:
total_time = self.times[self.idx] - self.times[0]
split_times = np.diff(self.times)
print_data = (self.print_prefix, self.name, total_time)
if print_on_single_line:
print('%s%s time: %.2fs: ' % print_data, end='')
else:
print('%s%s time: %.2fs' % print_data)
# allows printing before all tasks have been run
for idx in range(self.idx):
if self.task_names[idx] is None:
task_name = 'Task ' + str(idx+1)
else:
task_name = self.task_names[idx]
if print_on_single_line:
print(' %s: %.2fs (%.1f%%); ' %
(task_name,
split_times[idx],
100*split_times[idx]/total_time),
end='')
else:
print('\t%s%s: %.2fs (%.1f%%)' %
(self.print_prefix,
task_name,
split_times[idx],
100*split_times[idx]/total_time))
if print_on_single_line:
print('')
def _print(self, str):
'''Prints string after prefixing with the desired number of indentations.
Args:
str: The string to be printed.
Returns:
None.
'''
print('%s%s' % (self.print_prefix, str))
|
/*
Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
/*
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
squares = []
for num in A:
squares.append(num*num)
squares.sort()
return squares
|
#!/usr/bin/env python
# coding: utf-8
# # Assessment 1: I can train and deploy a neural network
# At this point, you've worked through a full deep learning workflow. You've loaded a dataset, trained a model, and deployed your model into a simple application. Validate your learning by attempting to replicate that workflow with a new problem.
#
# We've included a dataset which consists of two classes:
#
# 1) Face: Contains images which include the face of a whale
# 2) Not Face: Contains images which do not include the face of a whale.
#
# The dataset is located at ```/dli/data/whale/data/train```.
#
# Your challenge is:
#
# 1) Use [DIGITS](/digits) to train a model to identify *new* whale faces with an accuracy of more than 80%.
#
# 2) Deploy your model by modifying and saving the python application [submission.py](../../../../edit/tasks/task-assessment/task/submission.py) to return the word "whale" if the image contains a whale's face and "not whale" if the image does not.
#
# Resources:
#
# 1) [Train a model](../../task1/task/Train%20a%20Model.ipynb)
# 2) [New Data as a goal](../../task2/task/New%20Data%20as%20a%20Goal.ipynb)
# 3) [Deployment](../../task3/task/Deployment.ipynb)
#
# Suggestions:
#
# - Use empty code blocks to find out any informantion necessary to solve this problem: eg: ```!ls [directorypath] prints the files in a given directory```
# - Executing the first two cells below will run your python script with test images, the first should return "whale" and the second should return "not whale"
# Start in [DIGITS](/digits/).
# In[16]:
#Load modules & set objects for dataset and model
import caffe
import cv2
import sys
MODEL_JOB_DIR = '/dli/data/digits/20190926-221500-abfc' ## Set this to be the job number for your model
DATASET_JOB_DIR = '/dli/data/digits/20190926-220654-3c91' ## Set this to be the job number for your dataset
get_ipython().system(u'ls $MODEL_JOB_DIR')
# In[17]:
get_ipython().system(u'ls $DATASET_JOB_DIR')
# In[18]:
ARCHITECTURE = MODEL_JOB_DIR + '/deploy.prototxt' # Do not change
WEIGHTS = MODEL_JOB_DIR + '/snapshot_iter_270.caffemodel' # Do not change
# In[19]:
#Build model
def deploy(img_path):
caffe.set_mode_gpu()
# Initialize the Caffe model using the model trained in DIGITS. Which two files constitute your trained model?
net = caffe.Classifier(ARCHITECTURE, WEIGHTS,
channel_swap=(2,1,0),
raw_scale=255,
image_dims=(256, 256))
# Create an input that the network expects.
input_image = caffe.io.load_image(DATASET_JOB_DIR+'/mean.jpg')
input_image = cv2.resize(input_image, (256,256))
mean_image = caffe.io.load_image('/dli/data/digits/20190926-220654-3c91/mean.jpg')
ready_image = input_image-mean_image
#spot for viz
# Make prediction
prediction = net.predict([ready_image])
# Create an output that is useful to a user. What is the condition that should return "whale" vs. "not whale"?
if prediction.argmax() == 0:
return "whale"
else:
return "not whale"
#Ignore this part
if __name__ == "__main__":
print(deploy(sys.argv[1]))
# In[20]:
get_ipython().system(u'python submission.py \'/dli/data/whale/data/train/face/w_1.jpg\' #This should return "whale" at the very bottom')
get_ipython().system(u'python submission.py \'/dli/data/whale/data/train/not_face/w_1.jpg\' #This should return "not whale" at the very bottom')
|
import urllib
from urllib . request import urlopen
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def is_connected(site):
try:
urlopen(site,timeout=1)
return True
except urllib.error.URLError as Error:
print(Error)
return False
urlSite= input('Enter http')
if is_connected(urlSite):
print('Internet is active')
else:
print('Internet is disconected')
|
from random import randint
T = int(raw_input())
Smax = int(raw_input())
print(T)
def randomString():
string =""
for i in range(Smax):
string += str(randint(0,3))
return string
for i in range(T):
print(str(Smax) + " "+randomString()+"1")
|
formatter = "{} {} {} {}"
# Replaces each of the individiual values below with each {} above.
# So 1 will replace the first {} and so on
print(formatter.format(1,2,3,4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
#For each formatter value below it adds {} {} {} {}
#So you should see 16 of those when you print
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"Or a song about fear"
))
|
#!/usr/bin python
# Program to multiply two matrices using nested loops
import random
import numpy as np
def matrixMaker(N,M):
X = np.random.random((N,M))
return X
def main():
N = 250
X = matrixMaker(N,N)
Y = matrixMaker(N,N+1)
result = np.matmul(X, Y)
# result is Nx(N+1)
# result = np.zeros((N,N+1))
# for i in range(N):
# # iterate through rows of X
# for i in range(len(X)):
# # iterate through columns of Y
# for j in range(len(Y[0])):
# # iterate through rows of Y
# for k in range(len(Y)):
# result[i][j] += X[i][k] * Y[k][j]
return result
|
#!/bin/env python
# input section
name = input('Please enter your name: ')
# output section
print ( "hello ", name, ". Nice to meet you." )
# Ask a couple of questions and assoc the result to a dictionary
res = {'more_csc': (input("Are you interested in pursuing CSC beyond this class? "))} # The developer has written too much Clojure, and concedes nesting the 'input' call in parens isn't necessary to force evaluation in the context of assignment.
res['other_major'] = (input("If pursuing another major, what would you like to major in? ")) # Also, the developer ought to ask more interesting questions.
print("OK, here's what we know so far:\nYour answer to whether you want to continue CSC beyond this class was %(more_csc)s.\nYour current major is %(other_major)s" % res)
|
#from abc import ABC
import abc
class Employee(abc.ABC):
def __init__(self, name, cpf, pay):
self._name = str(name)
self._cpf = str(cpf)
self._pay = float(pay)
@abc.abstractmethod
def get_bonus(self):
return self._pay * 0.10
class Manager(Employee):
def __init__(self, name, cpf, pay, password, number_of_managed):
super().__init__(name, cpf, pay)
self._password = int(password)
self._number_of_managed = int(number_of_managed)
def get_bonus(self):
return self._pay * 0.20
def authenticate(self, password):
if self._password == password:
print("access allowed")
return True
else:
print("access denied")
return False
class BonusControl:
def __init__(self, bonus_total=0):
self._bonus_total = bonus_total
def register(self, employee):
if hasattr(employee, "get_bonus"):
self._bonus_total += employee.get_bonus
else:
print(f"Instance {self.__class__.__name__} does not implement the get_bonus() method")
@property
def bonus_total(self):
return self._bonus_total
class Director(Employee):
def __init__(self, name, cpf, pay):
super().__init__(name, cpf, pay)
def get_bonus(self):
return self._pay * 0.15
class Client:
def __init__(self, name, cpf, password):
self._name = name
self._cpf = cpf
self._password = password
|
import argparse
import logging
import sys
log = open('assignment10.log', 'a')
sys.stdout = log
logging.basicConfig(filename='assignment10.log',level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--integer', action='store', dest='integer', type=int, help='this is the number we will find the sigma notation of')
args = parser.parse_args()
logging.info("Please enter desired number")
args = input()
print(args)
logging.info('This is your desired number.')
if int(args) >= 0:
arr = []
for i in range(int(args)):
arr.append(i)
x = (sum(arr))
y = int(args)
result = x + y
print(result)
logging.info('This is the sigma notation of your desired number.')
#I wasn't able to make this into a function. I couldn't get the variables to pass through. Not sure why. I have tried for hours.
|
# coding=UTF-8
# 415. 字符串相加 类似于链表相加
# 给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
# 注意:
# num1 和num2 的长度都小于 5100.
# num1 和num2 都只包含数字 0-9.
# num1 和num2 都不包含任何前导零。
# 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
'''
我的思路:
1、先将字符串都倒序,因为从个位数开始加起
2、用0在末尾填充,保证两个字符串长度一致
3、增加一个变量add,表示进位多少;res用来拼接结果
4、%取余数得到当前位的数字,//得到进位数字。
5、不能忘记最后还有一个进位要加上,如果进位是0,则不用加上
6、将结果字符串res翻转过来
'''
class Solution:
def addStrings(self, num1, num2):
num1_re = num1[::-1]
num2_re = num2[::-1]
l_m = max(len(num1), len(num2))
num1_re += "0" * (l_m-len(num1))
num2_re += "0" * (l_m-len(num2))
add = 0 ; res = ""
for i in range(l_m):
su = int(num1_re[i]) + int(num2_re[i]) + add
res += str(su % 10)
add = su // 10
# 考虑到最后一位是否需要进位
if add != 0:
res += str(add)
res = res[::-1]
return res
a = Solution()
b = a.addStrings("12","123")
print(b)
|
# coding=UTF-8
# 二维数组中的查找
# 题目描述:
# 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
# 请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
"""
从左上角开始入手之所以不可行的原因,是因为以左上角为基准遍历时,满足条件的数字可能分布在两侧,所以并不能很好的缩小搜索范围。
以左下角或右上角为锚点开始查找,满足条件的数字值只可能分布在一侧,可以缩小搜索范围。
从某种角度看,这种解法类似于“二分法”,只不过不是严格意义上均匀的二分。
"""
class Solution(object):
def find(self, array, target):
xend = len(array)-1
yend = len(array[0])-1
x = 0 # 初始化行值
while x <= xend and yend >= 0: # 从右上角开始搜索
if array[x][yend] == target:
# print(x,yend) 可输出目标值的位置索引
return True
elif array[x][yend] > target:
yend -= 1
else:
x += 1
return False
array1 = [[1,2,8,9],
[2,4,9,12],
[4,7,10,13],
[6,8,11,15]]
a = Solution()
b = a.find(array1, target = 7)
print(b)
# 代码搜索路径 9 → 8 → 2 → 4 → 7
|
# coding=UTF-8
# 二叉树的最大深度
"""
1. 迭代法:从上到下按层级遍历二叉树,有多少层即二叉树有多深(即为求二叉树的深度)
2. 递归法:比较每一条路径的长短
"""
class BiNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class BiTree:
def __init__(self):
self.root = None
# 添加节点
"""
判断根结点是否存在,如果不存在则插入根结点。否则从根结点开始,判断左子结点是否存在,如果不存在插入,
如果左子结点存在判断右结点,不存在插入。如果左右结点存在,再依次遍历左右子结点的子结点,直到插入成功。
"""
def add_node_in_order(self, element):
node = BiNode(element)
if self.root is None:
self.root = node
else:
# 需要一个队列对子结点进行入队与出队。在python上这很简单,一个list 就实现了
node_queue = list()
node_queue.append(self.root)
while len(node_queue):
q_node = node_queue.pop(0) # 从列表头部读取
if q_node.left is None:
q_node.left = node
break
elif q_node.right is None:
q_node.right = node
break
else:
node_queue.append(q_node.left)
node_queue.append(q_node.right)
def set_up_in_order(self, vals_list):
""" 通过列表对树进行顺序构造 """
for val in vals_list:
self.add_node_in_order(val)
# 方法一:迭代法 (其实就是求二叉树的深度)
def maxdepth_diedai(self, root):
if root is None:
return 0
else:
queue = []
queue.append(root)
maxdepth = 0
while queue:
n = len(queue)
while n:
node = queue.pop(0)
n = n-1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
maxdepth += 1
return maxdepth
# 方法二:递归法
def maxdepth_digui(self, root):
if root is None:
return 0
left = self.maxdepth_digui(root.left) + 1 # 其实 self.maxdepth_digui(root.left) 表示一个数字
right = self.maxdepth_digui(root.right) + 1
return max(left,right)
if __name__ == "__main__":
nodes = [1,2,3,4,None,5,None,None,6]
print('建立二叉树')
test1 = BiTree()
test1.set_up_in_order(nodes)
print('迭代法的二叉树最大深度:')
print(test1.maxdepth_diedai(test1.root))
print('递归法的二叉树最大深度:')
print(test1.maxdepth_digui(test1.root))
|
######################################### 反转链表 #########################################
# coding=UTF-8
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 迭代思想
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
cur = pHead
tmp = None
newhead = None
# 一共分为四步
while cur:
tmp = cur.next
cur.next = newhead
newhead = cur
cur = tmp
return newhead
# 递归思想
# 如果要倒转的链表有n个节点,那么如果第一个节点后面的n-1个节点已经正确倒转了的话,
# 只要处理第一个和第二个节点的指向关系就可以了。要使后面n-1个节点正确倒转,那么先要使得后面的n-2个节点正确倒转。
# 于是接这么递归下去。最后只剩一个节点的时候,就什么都不用做了,只需要改变其与原来的上一个节点之间的关系就可以了。
def RecurseList(head):
"""
递归的写法
递归重要的是你要学会倒着考虑问题
"""
if not head or head.next == None: # 递归终止条件(以及排除特殊值问题)
return head
else:
newhead = RecurseList(head.next) # newhead一直是指向最后一个节点
head.next.next = head
head.next = None # 仅仅在第一个元素时候起作用(递归就是一个栈,后进先出,所以先考虑末尾,最后考虑头)
return newhead # 最终返回原链表的第一个节点,后面使用next方法调用
p = ListNode(1) #测试代码
p1 = ListNode(2) #建立链表1->2->3->None
p2 = ListNode(3)
p3 = ListNode(4)
p.next = p1
p1.next = p2
p2.next = p3
# 输出链表 3->2->1->None
# 注意循环方法和递归方法不可以同时运行
# print("循环方法:")
# a = ReverseList(p)
# while a:
# print(a.val)
# a = a.next
print("递归方法:")
newhead = None
b = RecurseList(p)
while b:
print(b.val)
b = b.next
|
# coding=UTF-8
# 二叉树的最小深度
"""
1. 迭代法: 算法遍历二叉树每一层,一旦发现某层的某个结点无子树,就返回该层的深度,这个深度就是该二叉树的最小深度
2. 递归法: 用递归解决该题和"二叉树的最大深度"略有不同。
主要区别在于对“结点只存在一棵子树”这种情况的处理,在这种情况下最小深度存在的路径肯定包括该棵子树上的结点
"""
class BiNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
class BiTree:
def __init__(self):
self.root = None
# 添加节点
"""
判断根结点是否存在,如果不存在则插入根结点。否则从根结点开始,判断左子结点是否存在,如果不存在插入,
如果左子结点存在判断右结点,不存在插入。如果左右结点存在,再依次遍历左右子结点的子结点,直到插入成功。
"""
def add_node_in_order(self, element):
node = BiNode(element)
if self.root is None:
self.root = node
else:
# 需要一个队列对子结点进行入队与出队。在python上这很简单,一个list 就实现了
node_queue = list()
node_queue.append(self.root)
while len(node_queue):
q_node = node_queue.pop(0) # 从列表头部读取
if q_node.left is None:
q_node.left = node
break
elif q_node.right is None:
q_node.right = node
break
else:
node_queue.append(q_node.left)
node_queue.append(q_node.right)
def set_up_in_order(self, vals_list):
for val in vals_list:
self.add_node_in_order(val)
# 方法一:迭代法
"""
二叉树的最小深度需要从1开始,因为后面的循环是基于一层的节点来说的,只有把当前层的所有节点都遍历完成,
才会把深度加1
"""
def mindepth_diedai(self, root):
if root is None:
return 0
else:
queue = []
queue.append(root)
mindepth = 1
while queue:
n = len(queue)
while n:
node = queue.pop(0)
n = n-1
if node.left is None and node.right is None:
return mindepth
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
mindepth += 1
return mindepth
# 方法二:递归法
def mindepth_digui(self, root):
if root is None:
return 0
if not root.left and root.right is not None:
return self.mindepth_digui(root.right)+1
if root.left is not None and not root.right:
return self.mindepth_digui(root.left)+1
left = self.mindepth_digui(root.left)+1
right = self.mindepth_digui(root.right)+1
return min(left,right)
if __name__ == "__main__":
nodes = [1,2,3,4,None,5,None,None,6]
print('建立二叉树')
test1 = BiTree()
test1.set_up_in_order(nodes)
print('迭代法的二叉树最小深度:')
print(test1.mindepth_diedai(test1.root))
print('递归法的二叉树最小深度:')
print(test1.mindepth_digui(test1.root))
|
# coding=UTF-8
# 53. 最大子序和
# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
"""
解题思路:
1. 如果当前和大于0,则加上下一个数(当前和是正的 对后面的求和“有益处”)
2. 如果当前和小于或等于0,则将下一个数赋给当前和
3. 最后比较当前和与存储最大值的变量 取最大值
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sums = 0
max_num = nums[0]
for cur in nums:
if sums >= 0:
sums += cur
else:
sums = cur
max_num = max(max_num, sums)
return max_num
n = [-2,1,-3,4,-1,2,1,-5,4]
a = Solution()
b = a.maxSubArray(nums = n)
print(b)
|
# coding=UTF-8
# 4. 寻找两个有序数组的中位数
# 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
nums1.extend(nums2)
nums1.sort()
half = len(nums1) // 2
return (nums1[half] + nums1[~half]) / 2
a = Solution()
b = a.findMedianSortedArrays([1,7,9,16],[12,25,36,78])
print(b)
c = [1,2,3,4,5,6,7,8]
print(c[3])
print(c[~3])
|
# 28.实现strStr()
# 给定一个 haystack 字符串和一个 needle 字符串
# 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
class Solution:
def strStr(self, haystack, needle):
if needle not in haystack:
return -1
return haystack.find(needle)
# 切片法
def strStr(self, haystack, needle):
l = len(needle)
for i in range(len(haystack)-l+1):
if haystack[i:i+l] == needle:
return i
return -1
q = "a"
w = "a"
a = Solution()
b = a.strStr(q,w)
print(b)
|
# 347. 前K个高频元素
# 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
# 输入: nums = [1,1,1,2,2,3], k = 2
# 输出: [1,2]
"""
1. 建立哈希表(字典)存储数字及其出现的次数
2. 根据字典的值逆序排序
3. 拿出前K个元素的key
"""
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
d = {} ; res = []
for i in nums:
if i in d:
d[i] += 1
else:
d[i] = 1
a = sorted(d.items(), key = lambda x:x[1] ,reverse = True)
for i in a[:k]:
res.append(i[0])
return res
x = Solution()
y = x.topKFrequent([1,1,1,2,2,3],2)
print(y)
|
#def even_numbers(function):
#def wrap(numbers):
#print(function())
#if numbers % 2 == 0:
# return wrap
def even_numbers(function):
def wrap(numbers):
result = list(filter(lambda x: x % 2 == 0, numbers))
return function(result)
return wrap
@even_numbers
def get_numbers(numbers):
return numbers
print(get_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9]))
|
lst = []
num = int(input("Number of inputs:"))
for n in range (num):
Ascii_val = ord(input())
lst.append(Ascii_val)
print("The sum is :" ,sum(lst))
|
import random
heads = 1
tails = 0
valid_guesses = [heads, tails]
correct_statement = "Correct! The coin flip landed "
incorrect_statement = "incorrect! The coin flip landed "
guess_list = []
coin_flip_otcme = random.randint(0,1)
for guess in valid_guesses:
def coin_flip(user_guess):
if coin_flip_otcme == user_guess:
if user_guess == heads:
return (correct_statement + heads + "!")
else:
return (correct_statement + tails + "!")
elif coin_flip_otcme == 0:
if user_guess == tails:
return (correct_statement + tails + "!")
elif user_guess == tails:
return(correct_statement + tails + "!")
print(coin_flip(heads))
print(coin_flip(tails))
print(coin_flip("bat"))
print(coin_flip("Heads"))
print(coin_flip("Tails"))
|
input_string = input("Enter a list element separated by space ")
list = input_string.split()
print("print in reverse order")
print(list[::-1])
|
def num(X,N,n):
#print(pow(n,N))
if(pow(n,N)<X):
return num(X,N,n+1)+num(X-pow(n,N),N,n+1)
elif(pow(n,N)==X):
return 1;
else:
return 0;
x=int(input("enter the value of X = "))
y = int(input("enter the value of N = "))
#print(type(x),type(y))
print(num(x,y,1))
|
def takefirst(elem):
return elem[0]
# the first line of input is the number of rows of the array
n = int(input())
a = []
for i in range(n):
a.append([(j) for j in input().split()])
b=[]
for i in range(int(n/2)):
a[i][1] = '-'
a.sort(key=takefirst)
#print(a)
for j in range (n):
b.append(a[j][1])
print (" ".join(map(str,b)))
|
input_string = input("Enter a list of strings separated by space = ")
a = input_string.split()
x = input("Enter a list of queries separated by space = ")
b = x.split()
n=len(b)
c=[]
for i in range(n):
c.append(a.count(b[i]))
print("Resultant array = ",c)
|
import time
import itertools
from collections import OrderedDict
def information(element, item):
if item in element:
element[item] = element[item] + 1
else:
element[item] = 0
element = OrderedDict(sorted(element.items(), key=lambda x: x[1], reverse=True))
return element
def timeInfo():
initialTime = time.time()
element = {}
f = open("wholeFile.log", "r")
while True:
item = str(f.readline())[0:-1]
element = information(element, item)
if(time.time() >= (initialTime + 3)):
element = information(element, item)
# print(element)
print(dict(itertools.islice(element.items(),1, 3)))
for item in element:
element[item] = 0
initialTime = time.time()
if __name__ == '__main__':
timeInfo()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.