text stringlengths 37 1.41M |
|---|
#Take 3 sides of the triangle, and decide whether it is SCALENE, EQUILATERAL or ISOSCELES
s1=int(input("Enter the first side number of triangle: "))
s2=int(input("Enter the second side number of triangle: "))
s3=int(input("Enter the third side number of triangle: "))
if s1==s2==s3:
print("It's a EQUILATERAL Triangle")
elif s1!=s2 and s1!=s3 and s2!=s3:
print("It's a SCALENE Triangle")
else:
if (s1==s2 and s1!=s3)or(s1==s3 and s1!=s2):
print("It's a ISOSCELES Triangle")
elif (s2==s1 and s2!=s3) or (s2==s3 and s2!=s1):
print("It's a ISOSCELES Triangle")
elif (s3==s1 and s3!=s2) or (s3==s2 and s3!=s1):
print("It's a ISOSCELES Triangle")
|
import random,pickle
from fileMerge1 import Record
from fileMerge3 import sortByBlocks
from fileMerge4 import merge
def writeRecord():
'''
OBJECTIVE : To write records a givenFile
INPUT PARAMETERS :
fileName: Name of the file
N: Number of Records to be written
OUTPUT :
None
'''
N=int(input('Enter number of records to be written: '))
f=open('mainFile.txt','wb')
keyList,i=[],1
while i<=N:
key=random.randint(1000000,2000000+N+1)
if key not in keyList:
keyList.append(key)
nonKey=str(key)*10
ob=Record(key,nonKey)
pickle.dump(ob,f)
i+=1
f.close()
def display(lower,upper):
'''
OBJECTIVE : To display records of sorted file "f1.txt" given lower and upper range
INPUT PARAMETERS :
lower: lower limit for the range to display records
upper: upper limit for the range to display records
OUTPUT :
None
'''
f1=open('file1.txt','rb')
ob=pickle.load(f1)
size=f1.tell()
i=lower
f1.seek(size*(lower-1))
for i in range(lower,upper+1):
ob=pickle.load(f1)
print('\nRecord Number:'+str(i)+':')
print(ob)
f1.close()
def main():
writeRecord()
sortByBlocks()
lower=int(input('Enter lower limit:'))
upper=int(input('Enter upper limit:'))
display(lower,upper)
if __name__=='__main__':
main()
|
'''
BEGIN CODE WRITTEN BY LIAM KINNEY FOR CRIME WAVES
'''
import math, random, collections, csv
from operator import itemgetter
# Function: Weighted Random Choice
# --------------------------------
# Given a dictionary of the form element -> weight, selects an element
# randomly based on distribution proportional to the weights. Weights can sum
# up to be more than 1.
def weightedRandomChoice(weightDict):
weights = []
elems = []
for elem in weightDict:
weights.append(weightDict[elem])
elems.append(elem)
total = sum(weights)
key = random.uniform(0, total)
runningTotal = 0.0
chosenIndex = None
for i in range(len(weights)):
weight = weights[i]
runningTotal += weight
if runningTotal > key:
chosenIndex = i
return elems[chosenIndex]
raise Exception('Should not reach here')
# Function: distance
# --------------------------------
# The distance formula
def distance(p0, p1):
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
# Functions:
# --------------------------------
# Functions for querying things from the data lines
def getDate(datum):
return datum[0].split(' ')[0]
def getDistrict(datum):
return datum[4]
def getCategory(datum):
return datum[1]
def getX(datum):
return abs(datum[7])
def getY(datum):
return abs(datum[8])
def getYear(datum):
year, month, day = map(int, getDate(datum).split('-'))
return year
def getMonth(datum):
year, month, day = map(int, getDate(datum).split('-'))
return month
def getDay(datum):
year, month, day = map(int, getDate(datum).split('-'))
return day
def isBefore(date1, date2):
year1, month1, day1 = map(int, date1.split('-'))
year2, month2, day2 = map(int, date2.split('-'))
if year1 < year2: return True
if year1 == year2 and month1 < month2: return True
if year1 == year2 and month1 == month2 and day1 < day2: return True
return False
def isAfter(date1, date2):
year1, month1, day1 = map(int, date1.split('-'))
year2, month2, day2 = map(int, date2.split('-'))
if year1 > year2: return True
if year1 == year2 and month1 > month2: return True
if year1 == year2 and month1 == month2 and day1 > day2: return True
return False
# Class: DataVisualizer
# ----------------------
# Maintain and update a belief distribution over the probability of a crime center
# being in a tile using a set of particles.
class DataBase(object):
def __init__(self, filename, numHotspots = 3):
# a lists of lists, where each lists is a single datapoint (a single crime) of
# the form [date, category, desc, day, district, resolution, address, x, y]
self.data = []
# a dictionary of dates to the normalized probabilities of crimes happening
# on that date
self.distributions = collections.defaultdict(dict)
# a list of the crime categories in the dataset
self.categories = []
# the number of unique dates in the dataset
self.numDates = 4511
# the number of days in a month
self.numDaysInMonth = 30
self.firstDate = ''
self.lastDate = ''
# boundaries of the grid/absolute values of long/lat
self.maxY = 37.8199754923
self.minY = 37.7078790224
self.maxX = 122.513642064
self.minX = 122.364937494
# the number of rows and columns to be in belief
self.numCols = 10
self.numRows = 10
# the average number of crimes per day, calculated over the entire dataset
# (used for weighting)
self.avgNumCrimesPerDay = {}
# transProbDict is a Counter of (oldTile, newTile) tuples to the probability of that transition happening
transProbDict = collections.Counter()
# the k to use for kmeans (i.e. the number of crime hotspots for each category)
self.k = numHotspots
# the iterations of kmeans
self.kmeansIters = 4
# open the file and load into the list "data"
with open(filename, 'r') as inputFile:
next(inputFile)
reader = csv.reader(inputFile, delimiter=',')
for date, category, desc, day, district, resolution, address, x, y in reader:
self.data.append([date, category, desc, day, district, resolution, address, float(x), float(y)])
if category not in self.categories: self.categories.append(category)
self.firstDate = getDate(self.data[-1])
self.lastDate = getDate(self.data[0])
# building average number of crimes per day dict
for cat in self.categories:
self.avgNumCrimesPerDay[cat] = sum(elem[1] == cat for elem in self.data)/float(self.numDates)
# build the distributions dict
runningDict = collections.Counter()
for i, line in enumerate(self.data):
runningDict[getCategory(line)] += 1
# if we're at the end of the dataset or we're about to switch dates, normalize
if i + 1 == len(self.data) or getDate(line) != getDate(self.data[i+1]):
newDict = collections.Counter()
# normalize
for key in runningDict.keys():
newDict[key] = runningDict[key] / float(sum(runningDict.values()))
self.distributions[getDate(line)] = newDict
runningDict.clear()
# Function: printCategoryDistributionOn
# ------------------
# prints the observed distributions of the crimes on a single date
def printCategoryDistributionOn(self, year, month, day):
#query the distributions dict
if month < 10: month = "0"+str(month)
if day < 10: day = "0"+str(day)
date = str(year) + "-" + str(month) + "-" + str(day)
#date = '2010-11-04'
print "on ", date, " we saw..."
if len(self.distributions[date].keys()) == 0: print "no data"
# sort data from most occurring to least occuring
sorted_dict = sorted(self.distributions[date].items(), key=itemgetter(1), reverse=True)
for key, value in sorted_dict:
print value, "percent chance of", key
# Functions: northernBorder, southernBorder, easternBorder, westernBorder
# ------------------
# extract the x/y borders from the dataset. In the easternBorder and
# northernBoarder functions, there are misreported data with long/lat pairs
# outside of San Francisco, so we sort the data to find borders that
# reflect the true boundaries of the city. After I used these to find
# the boundaries, I hard-coded them as the max/min X/Y values to save
# time.
def easternBorder(self):
# return max(elem[7] for elem in self.data)
lister = sorted(self.data, key=itemgetter(7))
for i, num in enumerate(lister):
if i == 0: continue
if float(num[7]) > float(-121):
return lister[i-1][7]
def westernBorder(self):
return min(elem[7] for elem in self.data)
def northernBorder(self):
lister = sorted(self.data, key=itemgetter(8))
for i, num in enumerate(lister):
if i == 0: continue
if float(num[8]) > 40:
return lister[i-1][8]
def southernBorder(self):
return min(elem[8] for elem in self.data)
# Function: avgDailyCrimes
# ------------------
# prints out the average number of crimes per day (averaged over the whole dataset)
def avgDailyCrimes(self):
print "on average, from", self.firstDate, "to", self.lastDate, "we see"
sorted_dict = sorted(self.avgNumCrimesPerDay.items(), key=itemgetter(1), reverse=True)
for key, value in sorted_dict:
print key, ": ", value, " per day"
# Function: Y to Row
# -------------------------
# Returns the row in the discretized grid, that the value y falls into.
# This function does not check that y is in bounds.
# Warning! Do not confuse rows and columns!
def yToRow(self, belief, y):
totalYDifference = self.maxY - self.minY # calculate y difference over whole map
currYDifference = y - self.minY # calculate current y offset from map's y-min
tileYSize = totalYDifference / belief.getNumRows() # calculate the size in y of a single tile
return int((currYDifference / tileYSize)) # divide current y offset by the size of a single tile
# Function: X to Col
# -------------------------
# Returns the col in the discretized grid, that the value x falls into.
# This function does not check that x is in bounds.
# Warning! Do not confuse rows and columns!
def xToCol(self, belief, x):
totalXDifference = self.maxX - self.minX # calculate x difference over whole map
currXDifference = x - self.minX # calculate current x offset from map's x-min
tileXSize = totalXDifference / belief.getNumCols() # calculate the size in x of a single tile
return int((currXDifference / tileXSize)) # divide current x offset by the size of a single tile
# Function: visualizeChangingBelief
# ------------------
# runs a command-line visualizer of the beliefs as they change
# monthly from the startDate to the endDate for a given category
def visualizeChangingBeliefMonthly(self, startDate, endDate, category):
belief = Belief(self.numRows, self.numCols)
# check that the input is valid
if category not in self.categories:
print category, "is not a valid category"
return
if isBefore(startDate, self.firstDate):
print startDate, "is before the first date of", self.firstDate
return
if isAfter(endDate, self.lastDate):
print endDate, "is after the end date of", self.lastDate
return
prunedDataset = [datum for datum in self.data if (isAfter(getDate(datum), startDate) and isBefore(getDate(datum), endDate) and getCategory(datum) == category)]
# the data comes in sorted by date in decreasing chronological order, so
# we reverse it
prunedDataset.reverse()
if prunedDataset == None:
print "no ", category, "happened in the months between", startDate, "and", endDate
return
# print "this dataset should only have", category, "and the dates should be in ascending order:"
# print prunedDataset[0]
# print prunedDataset[1]
# print prunedDataset[2]
# print prunedDataset[3]
# print prunedDataset[4]
# print prunedDataset[5]
# print prunedDataset[500]
# print prunedDataset[1000]
for i, datum in enumerate(prunedDataset):
# update belief for this crime
x = getX(datum)
y = getY(datum)
# check whether coordinates are valid
if x < self.minX or x > self.maxX or y < self.minY or y > self.maxY:
continue
row = self.yToRow(belief, y)
col = self.xToCol(belief, x)
if col == self.numCols: col = col - 1
if row == self.numRows: row = row - 1
belief.addProb(row, col, 1)
# if we're at the end of the dataset or we're about to switch months,
# normalize, print, and reset belief
if i + 1 == len(prunedDataset) or getMonth(datum) != getMonth(prunedDataset[i+1]):
# print out this previous month
print "for", getYear(datum), "/", getMonth(datum), "we saw:"
#belief.normalize()
for i in range(self.numRows):
row = ''
for j in range(self.numCols):
row += str(belief.getProb(i, j)) + ' '
print row
belief = Belief(self.numRows, self.numCols)
print ''
# Function: findNearestCenter
# ------------------
# given a grid and a location inside the grid, iteratively check
# a wider and wider range around the tile (i, j) until a tile is
# found with weight greater than 0
def findNearestCenter(self, centers, i, j):
if centers[i][j] > 0:
return (i, j)
for x in range(0, self.numCols):
for newi in range(i-x, i+x):
for newj in range(j-x, j+x):
if newi >= self.numCols or newi < 0 or newj >= self.numRows or newj < 0: continue
if centers[newi][newj] > 0:
# we've found the nearest center. Return it
return (newi, newj)
# Function: updateBelief
# ------------------
# adds the probability of the datum to the belief.
def updateBelief(self, belief, datum):
# update belief for this crime
x = getX(datum)
y = getY(datum)
# check whether coordinates are valid; don't update belief if not
if x < self.minX or x > self.maxX or y < self.minY or y > self.maxY: return
row = self.yToRow(belief, y)
col = self.xToCol(belief, x)
if col == self.numCols: col = col - 1
if row == self.numRows: row = row - 1
belief.addProb(row, col, 1)
# Function: normalizeCounter
# ------------------
# Given a counter where the values are probabilities, normalize it
def normalizeCounter(self, counter):
result = collections.Counter()
for key in counter.keys():
result[key] = counter[key] / float(sum(counter.values()))
return result
# Function: findLocalTransProbs
# ------------------
# Helper function to buildNewHotspots. Given a tile and a transProbs
# dictionary, create a new normalized dict with only transition
# probabilities from tile.
def findLocalTransProbs(self, transProbs, tile):
localTransProbs = collections.Counter()
for key, value in transProbs.iteritems():
if key[0] == tile:
# oldTile is the local tile we're looking for
localTransProbs[key] = value
# normalize
return self.normalizeCounter(localTransProbs)
# Function: viewNewHotspots
# ------------------
# A visualizer for buildNewHotspots
def viewNewHotspots(self, category, transProbs, month, year):
newHotspots = self.buildNewHotspots(category, monthlyTransProbs, month, year)
print "the", category, "hotspots for", year, "/", month, "given the previous month's data are"
for i in range(numRowsCols):
line = ''
for j in range(numRowsCols):
line += str(newHotspots[i][j]) + ' '
print line
# Function: getHotspots
# ------------------
# Given a category, month, and year, return a hotspot grid
def getHotspots(self, category, month, year):
belief = Belief(self.numRows, self.numCols)
oldMonth = month - 1
if oldMonth < 1:
oldMonth = 12
oldYear = year - 1
else:
oldYear = year
# create a dataset with just the data from this month for this category
prunedDataset = [datum for datum in self.data if (getCategory(datum) == category and getMonth(datum) == oldMonth and getYear(datum) == oldYear)]
# build the belief
for datum in prunedDataset:
self.updateBelief(belief, datum)
belief.normalize()
return self.kmeans(self.k, belief)
# Function: buildNewHotspots
# ------------------
# Given a category, it's transition probabilities, and a month, predict the hotspots
# for the next month
def buildNewHotspots(self, category, transProbs, month, year):
# Step 1: get the hotspots for the previous month
oldHotspots = self.getHotspots(category, month, year)
# Step 2: from those hotspots, use transProbs and weightedRandomChoice to come up with new hotspots
newHotspots = [[0 for _ in range(self.numCols)] for _ in range(self.numRows)]
# iterate through oldHotspots and figure out where the newHotspots will be
for i in range(self.numRows):
for j in range(self.numCols):
if oldHotspots[i][j] > 0:
# we're at a hotspot
localTransProbs = self.findLocalTransProbs(transProbs, (i, j))
# pick a weighted random transition to a new tile
if len(localTransProbs) == 0:
# if there's no transition information for this tile, keep the hotspot
# in the same place
newTile = (i, j)
else:
oldTile, newTile = weightedRandomChoice(localTransProbs)
# retain the weight from the previous month
newHotspots[newTile[0]][newTile[1]] = oldHotspots[i][j]
return newHotspots
# Function: buildMonthlyTransitionProbabilities
# ------------------
# Given a category, build a dictionary of (newTile, oldTile): monthly transition probability
# using the data from the entire dataset
def buildMonthlyTransitionProbabilities(self, category):
print "building transition probabilities for", category, "..."
# transProbDict
transProbs = collections.Counter()
lastMonthsCenters = None
thisMonthsCenters = None
belief = Belief(self.numRows, self.numCols)
# since we're recording the transitions between months,
# we can't do anything at the first month
firstMonth = True
prunedDataset = [datum for datum in self.data if (getCategory(datum) == category)]
for i, datum in enumerate(prunedDataset):
# update the belief with this data
self.updateBelief(belief, datum)
# if we're at the end of the dataset or we're about to switch months,
# normalize, perform kmeans to find new centers, and record the transitions
if i + 1 == len(prunedDataset) or getMonth(datum) != getMonth(prunedDataset[i+1]):
belief.normalize()
if firstMonth:
firstMonth = False
lastMonthsCenters = self.kmeans(self.k, belief)
continue
thisMonthsCenters = self.kmeans(self.k, belief)
for i in range(self.numRows):
for j in range(self.numCols):
if thisMonthsCenters[i][j] > 0:
# we're at a center; look for nearest center in last month's centers
newTile = (i, j)
oldTile = self.findNearestCenter(lastMonthsCenters, i, j)
# update transprobs
transProbs[(newTile, oldTile)] += 1.0
lastMonthsCenters = thisMonthsCenters
belief = Belief(self.numRows, self.numCols)
# at the end, normalize over the entire dictionary of transition probabilities and return
return self.normalizeCounter(transProbs)
# Function: kmeans
# ------------------
# A helper function to buildMonthlyTransitionProbabilities, kmeans
# uses the probabilities in the belief grid to locate k centers
# and returns their locations on a grid
def kmeans(self, k, belief):
# centers is a grid where k of the tiles are centers. A center is represented
# by a number corresponding to the sum of the tiles assigned to it
centers = [[0 for _ in range(self.numCols)] for _ in range(self.numRows)]
# assignments is a grid of tuples recording which center that tile belongs to
assignments = [[None for _ in range(self.numCols)] for _ in range(self.numRows)]
# a list of tuples where the first element is an (i, j) pair and the second
# is the weight of that tile. This records the k heaviest tiles in belief
# in order to initialize the centers to that position
heaviestTiles = [None]*k
for i in range(self.numRows):
for j in range(self.numCols):
if heaviestTiles[-1] == None:
# we haven't filled the heaviest tiles list yet
for i, elem in enumerate(heaviestTiles):
if elem == None:
heaviestTiles.insert(i, ((i, j), belief.getProb(i, j)))
del heaviestTiles[-1]
elif belief.getProb(i, j) > heaviestTiles[-1][1]:
# this new probability belongs in the heaviestTiles list
for i in range(len(heaviestTiles)):
if heaviestTiles[i][1] < belief.getProb(i, j):
heaviestTiles.insert(i, ((i, j), belief.getProb(i, j)))
del heaviestTiles[-1]
# initialize the centers to the heaviest tiles
for tile, weight in heaviestTiles:
centers[tile[0]][tile[1]] = weight
for iteration in range(self.kmeansIters):
# step 1: assign the tiles to centers
for i in range(self.numRows):
for j in range(self.numCols):
assignments[i][j] = self.findNearestCenter(centers, i, j)
# step 2: rearrange the centers according to the tiles assigned to it
newCenters = [[0 for _ in range(self.numCols)] for _ in range(self.numRows)]
for _ in range(k):
for i in range(self.numRows):
for j in range(self.numCols):
if centers[i][j] > 0:
# we're at a center; reassign it
# use the center of mass formula to find new center
totalWeight = 0
iBarNumerator = 0
jBarNumerator = 0
for x in range(self.numRows):
for y in range(self.numCols):
if assignments[x][y] == (i, j):
# we're at a point that's assigned to this center
totalWeight += belief.getProb(x, y)
iBarNumerator += belief.getProb(x, y)*x
jBarNumerator += belief.getProb(x, y)*y
iBar = int(float(iBarNumerator) / totalWeight)
jBar = int(float(jBarNumerator) / totalWeight)
# update the new center to have a weight that is the sum of the
# weights of the tiles assigned to it
newCenters[iBar][jBar] = totalWeight
centers = newCenters
return centers
# Function: checkAccuracy
# ------------------
# Given a predicted output myDistributions, measure it against
# the actual distributions for that day and output a percent accuracy
def checkAccuracy(self, myDistributions, month, year, x, y):
# build the hotspots for place and month given the data in the database
# run through categories and create a dictionary of categories : hotspot grids
trueDistributions = collections.Counter()
belief = Belief(self.numRows, self.numCols)
row = self.yToRow(belief, y)
col = self.xToCol(belief, x)
for cat in self.categories:
actualHotspots = self.getHotspots(cat, month, year)
# find coordinates of nearest hotspot to our x and y
i, j = self.findNearestCenter(actualHotspots, col, row)
# get the weight of that hotspot
hotspotWeight = actualHotspots[i][j]
# apply weighting formula
trueDistributions[cat] = self.avgNumCrimesPerDay[cat]*hotspotWeight*(1/distance((i, j), (x, y)))
normalizedTrueDistributions = self.normalizeCounter(trueDistributions)
# compare true distributions and myDistributions to get % error
totalPercentError = 0
for cat, trueProb in normalizedTrueDistributions.iteritems():
# percent error is difference divided by exact value
percentError = abs(trueProb - myDistributions[cat]) / trueProb
totalPercentError += percentError
avgPercentError = totalPercentError / float(len(self.categories))
percentAccuracy = 1 - avgPercentError
lowerXBound, upperXBound = self.getLongBounds(x)
lowerYBound, upperYBound = self.getLatBounds(y)
print "Our distribution formed for", year, "-", month, "between longitudes", lowerXBound, "and", upperXBound, "and latitudes", lowerYBound, "and", upperYBound, "has"
print "percent error:", avgPercentError
print "percent accuracy:", percentAccuracy
# Functions: getLongBounds, getLatBounds
# ------------------
# given longitudes and latitudes, return a tuple containing the bounds
# of the tile around it
def getLongBounds(self, x):
totalXDifference = self.maxX - self.minX # calculate x difference over whole map
currXDifference = x - self.minX # calculate current x offset from map's x-min
tileXSize = totalXDifference / self.numCols # calculate the size in x of a single tile
index = int((currXDifference / tileXSize)) # divide current y offset by the size of a single tile
return (self.minX + tileXSize * index, self.minX + tileXSize * (index+1))
def getLatBounds(self, y):
totalYDifference = self.maxY - self.minY # calculate x difference over whole map
currYDifference = y - self.minY # calculate current x offset from map's x-min
tileYSize = totalYDifference / self.numCols # calculate the size in x of a single tile
index = int((currYDifference / tileYSize)) # divide current y offset by the size of a single tile
return (self.minY + tileYSize * index, self.minY + tileYSize * (index+1))
# Function: showCrimeDistribution
# ------------------
# Visualizer for queryDatabase
def showCrimeDistribution(self, month, year, x, y):
distributions = database.queryDatabase(month, year, x, y)
print ''
lowerXBound, upperXBound = self.getLongBounds(x)
lowerYBound, upperYBound = self.getLatBounds(y)
print "on", year, "-", month, "between longitudes", lowerXBound, "and", upperXBound, "and latitudes", lowerYBound, "and", upperYBound, "a crime has a"
for key, value in sorted(distributions.iteritems(), key=itemgetter(1), reverse=True):
print value*100, "%% chance of being", key
# Function: queryDatabase
# ------------------
# Given a month and a year, query the dataset for a list of distributions
# showing the predicted probabilities of different categories of crime
# happening in that location in that month.
def queryDatabase(self, month, year, x, y):
# run through categories and create a dictionary of categories : hotspot grids
distributions = collections.Counter()
belief = Belief(self.numRows, self.numCols)
row = self.yToRow(belief, y)
col = self.xToCol(belief, x)
for count, cat in enumerate(self.categories):
# create the dicctionary of transition probabilities for this category
transProbs = self.buildMonthlyTransitionProbabilities(cat)
# create the predicted hotspots grid for this month
newHotspots = self.buildNewHotspots(cat, transProbs, month, year)
# find coordinates of nearest hotspot to our x and y
i, j = self.findNearestCenter(newHotspots, col, row)
# get the weight of that hotspot
hotspotWeight = newHotspots[i][j]
# apply weighting formula
distributions[cat] = self.avgNumCrimesPerDay[cat]*hotspotWeight*(1/distance((i, j), (x, y)))
print (float(count+1)/float(len(self.categories)))*100, "%% done"
return self.normalizeCounter(distributions)
# Function: predictCrimesForMonthAndLocation
# ------------------
# Given a set of distributions from a certain time and location, predict how
# many crimes of each category are going to happen in that location.
def predictCrimesForMonthAndLocation(self, distributions, month, year, x, y):
lowerXBound, upperXBound = self.getLongBounds(x)
lowerYBound, upperYBound = self.getLatBounds(y)
print ''
print "on", year, "-", month, "between longitudes", lowerXBound, "and", upperXBound, "and latitudes", lowerYBound, "and", upperYBound, "I predict:"
for key, value in sorted(distributions.iteritems(), key=itemgetter(1), reverse=True):
print str(value*self.numDaysInMonth*sum(self.avgNumCrimesPerDay.values()))+'s', str(key)+'s'
print ''
print "the actual data is:"
prunedDataset = [datum for datum in self.data if (getMonth(datum) == month and getYear(datum) == year)]
actualCrimeCount = collections.Counter()
for datum in prunedDataset:
actualCrimeCount[getCategory(datum)] += 1
for key, value in sorted(actualCrimeCount.iteritems(), key=itemgetter(1), reverse=True):
print str(value)+'s', str(key)+'s'
print ''
print "which gives us"
# compare true distributions and myDistributions to get % error
totalPercentError = 0
for cat, trueCount in actualCrimeCount.iteritems():
# percent error is difference divided by exact value
percentError = abs(trueCount - distributions[cat]*self.numDaysInMonth*sum(self.avgNumCrimesPerDay.values())) / trueCount
totalPercentError += percentError
avgPercentError = totalPercentError / float(len(self.categories))
percentAccuracy = 1 - avgPercentError
print "percent error:", avgPercentError
print "percent accuracy:", percentAccuracy
'''
END CODE WRITTEN BY LIAM KINNEY FOR CRIME WAVES
'''
'''
BELIEF CLASS TAKEN FROM THE STANFORD DRIVERLESS CAR PROJECT
'''
# Class: Belief
# ----------------
# This class represents the belief for a single inference state of a single
# car. It has one belief value for every tile on the map. You *must* use
# this class to store your belief values. Not only will it break the
# visualization and simulation control if you use your own, it will also
# break our autograder :).
class Belief(object):
# Function: Init
# --------------
# Constructor for the Belief class. It creates a belief grid which is
# numRows by numCols. As an optional third argument you can pass in the
# initial belief value for every tile (ie Belief(3, 4, 0.0) would create
# a belief grid with dimensions (3, 4) where each tile has belief = 0.0.
def __init__(self, numRows, numCols, value = None):
self.numRows = numRows
self.numCols = numCols
numElems = numRows * numCols
if value == None:
value = (1.0 / numElems)
self.grid = [[value for _ in range(numCols)] for _ in range(numRows)]
# Function: Set Prob
# ------------------
# Sets the probability of a given row, col to be p
def setProb(self, row, col, p):
self.grid[row][col] = p
# Function: Add Prob
# ------------------
# Increase the probability of row, col by delta. Belief probabilities are
# allowed to increase past 1.0, but you must later normalize.
def addProb(self, row, col, delta):
self.grid[row][col] += delta
assert self.grid[row][col] >= 0.0
# Function: Get Prob
# ------------------
# Returns the belief for tile row, col.
def getProb(self, row, col):
return self.grid[row][col]
# Function: Normalize
# ------------------
# Makes the sum over all beliefs 1.0 by dividing each tile by the total.
def normalize(self):
total = self.getSum()
for r in range(self.numRows):
for c in range(self.numCols):
self.grid[r][c] /= total
# Function: Get Num Rows
# ------------------
# Returns the number of rows in the belief grid.
def getNumRows(self):
return self.numRows
# Function: Get Num Cols
# ------------------
# Returns the number of cols in the belief grid.
def getNumCols(self):
return self.numCols
# Function: Get Sum
# ------------------
# Return the sum of all the values in the belief grid. Used to make sure
# that the matrix has been normalized.
def getSum(self):
total = 0.0
for r in range(self.numRows):
for c in range(self.numCols):
total += self.getProb(r, c)
return total
'''
BELIEF CLASS TAKEN FROM THE STANFORD DRIVERLESS CAR PROJECT
'''
'''
Tests for the individual components of the database module
'''
# filename = "train.csv"
# database = DataBase(filename)
# month = 12
# year = 2010
# x = 122.397744427103
# y = 37.7299346936044
# # test of printCategoryDistributionOn: print out the category distribution for a given day
# day = 4
# database.printCategoryDistributionOn(year, month, day)
# print ''
# # test of border-finding functions
# print "northern boarder: ", database.northernBorder()
# print "southern boarder: ", database.southernBorder()
# print "eastern Border: ", database.easternBorder()
# print "western Border: ", database.westernBorder()
# print ''
# # test of avgDailyCrimes: prints out the average number of crimes per day (averaged over the whole dataset)
# database.avgDailyCrimes()
# print ''
# # test of visualizeChangingBeliefMonthly: starts a visualizer of the normalized city grid containing the probability
# # distributions as they change month to month
# print "the list of categories: ", database.categories
# database.visualizeChangingBeliefMonthly("2010-01-01", "2012-01-01", "VANDALISM")
# print ''
# # test of buildMonthlyTransitionProbabilities
# monthlyTransProbs = database.buildMonthlyTransitionProbabilities("VANDALISM")
# for key, value in sorted(monthlyTransProbs.iteritems(), key=itemgetter(1), reverse=True):
# print key, ":", value
# print ''
# # test of buildNewHotspots
# monthlyTransProbs = database.buildMonthlyTransitionProbabilities("VANDALISM")
# numRowsCols = 10
# month = 12
# year = 2010
# database.viewNewHotspots("VANDALISM", monthlyTransProbs, month, year)
# print ''
# # test of queryDatabase
# database.showCrimeDistribution(month, year, x, y)
# distributions = database.queryDatabase(month, year, x, y)
# print ''
# # test of checkAccuracy
# database.checkAccuracy(distributions, month, year, x, y)
# print ''
# # test of predictCrimesForMonthAndLocation
# database.predictCrimesForMonthAndLocation(distributions, month, year, x, y)
'''
Tests for the individual components of the database module
'''
|
infile = open("a_study_in_scarlet.txt","r")
lines = infile.readlines()
infile.close()
words = {}
for line in lines:
word = line.strip("\n")
if word not in words:
words[word] = 1
else:
words[word] += 1
for key in sorted(words):
print(key, words[key]) |
# -*- coding: utf-8 -*-
__author__="Patrik Ahvenainen"
__date__ ="$31.7.2012 18:12:31$"
# tools for creating an abstract class in python
from abc import ABCMeta, abstractmethod, abstractproperty
if __name__ == "__main__":
print "This is an abstract class, implemented with the abc class"
class Tree(object):
__metaclass__ = ABCMeta
"""
This is an abstract class. Classes that inherit from this class should have
implementation for adding an item to a tree and finding an item from a tree.
This class is not strictly speaking necessary but it makes sure your tree
classes are working properly.
Guarantees that the following properties and methods have been defined:
properties:
wordCount: number of words added to the tree (not number of nodes)
type: finds 'exact' or 'partial' matches for words
public methods:
self.add(key, value): Adds one value with the given key to the tree
self.addFromReader(): Adds words from own reader if possible
self.clear(): Removes all words from the tree
self.find(key): Returns the hits when searching for key
"""
##################
### PROPERTIES ###
##################
@abstractproperty
def wordCount(self):
raise NotImplementedError( "WordCount not implemented" )
@abstractproperty
def type(self):
raise NotImplementedError( "Type not implemented" )
######################
### PUBLIC METHODS ###
######################
@abstractmethod
def add(self, key, value):
"""
This method is used to add items to the tree. Each item contains a key
which should be a string and an arbitrary value corresponding to that
key.
@param key: the key to the value to be added
@param value: the value to be added
"""
raise NotImplementedError( "Adding not implemented" )
@abstractmethod
def addFromReader(self, wordCount = None):
"""
This method should take the words from self.lukija and add them to the
tree. If wordCount is given this method should not increase the number
of additions to the tree over wordCount. Note that the actual number of
unique words in the tree does not equal wordCount.
@param wordCount: the maximum number of words added to the tree
"""
raise NotImplementedError( "Adding from reader not implemented" )
@abstractmethod
def clear(self):
"""
This method is used to clear all the words from the tree.
"""
raise NotImplementedError( "Clearing not implemented" )
@abstractmethod
def find(self, key, output='list', sanitized=False):
"""
Finds the key from the tree. Word is first sanitized unless sanitized is
set to True.
@param key: the key for the value to be found
@param output: the type of output desired
@type output: boolean
@param sanitized: if set to True words are assumed to be sanitized
@type sanitized: boolean
@return:
- output == 'boolean':
1: A boolean value indicating whether the file was found
- output == 'count':
1: Number of found instances
- output == 'full':
1: A list of positions where this word was found
2: Number of found instances
3: Number of lines where the word was found
- output == 'list': (default)
1: A list of positions where this word was found
"""
raise NotImplementedError( "Finding not implemented" )
|
from threading import *
def OddNumbersThread():
for i in range(1,101):
if i%2 == 0:
print(i)
def EvenNumbersThread():
for i in range(1,101):
if i%2 != 0:
print(i)
def MainThread():
for i in range(1,101):
print(i)
t1 = Thread(target=OddNumbersThread)
t2 = Thread(target=EvenNumbersThread)
t3 = Thread(target=MainThread)
t1.start()
t2.start()
t3.start()
|
print('------ Descontos -----')
def desconto(valor):
desconto = int(input('Qual o desconto em %: '))
valorComDesconto = valor - ((desconto/100)*valor)
print('Sua compra no valor de {} teve um desconto de {}% Totalizando:{} Reais'.format(valor,desconto,valorComDesconto))
valor = float(input('Valor da compra: '))
op = int(input('Desconto?: [1/0] '))
while(op != 1 and op!= 0):
print('Valor invalido, digite novamente:')
op = int(input('Desconto?: [1/0] '))
if 1 == op:
print('SIM')
desconto(valor)
elif 0 == op:
#print('NÃO')
print('Total a pagar: {}'.format(valor))
else:
print('Erro')
|
nome = input("Digite seu nome: ")
print("Olá " + nome + ", seja muioto bem vindo!") |
# -*- coding: utf-8 -*-
import numpy as np
# Signoid function with derivative
def sigmoid(x, deriv=False):
if deriv:
return x * (1 - x)
return (1 / (1 + np.exp(-x)))
def relu(x, deriv=False):
if deriv:
temp = x.copy()
x[x <= 0] = 0
return x
return np.maximum(x, 0)
def train(N, features, hidden_layer, output_dim, epochs, l_rate, a_func, dropout_percent, dataset=1):
# N is batch size; features is input dimension;
# hidden_layer is hidden dimension; output_dim is output dimension.
# Create random input and output data
if dataset == 1:
np.random.seed(1)
data = 2 * np.random.rand(N, features) - 1 # random normalized input
# random normalized output
y_target = 2 * np.random.rand(N, output_dim) - 1
# Randomly initialize weights
w1 = np.random.randn(features, hidden_layer)
w2 = np.random.randn(hidden_layer, output_dim)
else:
data = np.array([[0, 1, 0, 0] * (features // 4),
[1, 0, 1, 0] * (features // 4),
[1, 0, 0, 0] * (features // 4),
[0, 1, 1, 0] * (features // 4)])
y_target = np.array([[0] * output_dim,
[1] * output_dim,
[1] * output_dim,
[0] * output_dim])
w1 = 2 * np.random.rand(features, hidden_layer) - 1
w2 = 2 * np.random.rand(hidden_layer, output_dim) - 1
for t in range(epochs):
# Forward pass: compute predicted y
# Go to hidden layer
l1 = data.dot(w1)
# Relu as activation function
l1_out = a_func(l1)
# Apply dropout to turn off part of the hidden layer
# and compensate the turned off by increase others
if dropout_percent < 1:
l1_out *= np.random.binomial(
[np.ones((len(data), hidden_layer))],
1 - dropout_percent)[0] * (1.0 / (1 - dropout_percent)
)
l2 = l1_out.dot(w2)
y_pred = a_func(l2)
error = y_pred - y_target
# Compute and print loss
if t % 100 == 0:
loss = np.square(error).sum()
print(t, loss)
# print(y_pred)
# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * error * a_func(y_pred, deriv=True)
grad_w2 = l1_out.T.dot(grad_y_pred)
grad_h = grad_y_pred.dot(w2.T) * a_func(l1_out, deriv=True)
grad_w1 = data.T.dot(grad_h)
# Update weights
w1 -= l_rate * grad_w1
w2 -= l_rate * grad_w2
if __name__ == '__main__':
train(64, 1000, 100, 10, 500, 1e-6, a_func=relu, dropout_percent=1)
|
# Napisać iteracyjną wersję funkcji fibonacci(n)
# obliczającej n-ty wyraz ciągu Fibonacciego.
def Fibonaci(Fn):
if Fn == 0:
return 0
elif Fn == 1:
return 1
else:
F1 = 0
F2 = 1
m = 0
for i in range(Fn-1):
m = F1 + F2
F1 = F2
F2 = m
return m
Fib1 = Fibonaci(0)
Fib2 = Fibonaci(1)
Fib3 = Fibonaci(3)
Fib4 = Fibonaci(5)
Fib5 = Fibonaci(10)
print(Fib1)
print(Fib2)
print(Fib3)
print(Fib4)
print(Fib5)
|
"""
This module defines the Gene class and GeneProbabilities class.
The Gene class is an IntEnum with 3 options xx:0, xX or Xx:1, and XX=2.
This models the 3 unique (order is irrelevent) combinations of X and x
and can be represented in so-called ternary form as 0,1,2.
Thee GeneProbabilities is a dict which models the probabilities from
mixing genes from two parents. The keys in this dict are the three enums
from Gene.
The randomness from this module draws from the standard python
random module and a call to random.seed() can be done to
guarantee reproducible results.
If called as a main script, this module prints the probabilities
of all possible combinations of parent pairs and randomly draws
a number of times and shows the results after calling random.seed(0).
"""
from enum import IntEnum
import random
import itertools
class Gene(IntEnum):
"""
This class defines the three gene combinations xx, xX/Xx, XX
as 0,1,2.
Genes from this class follow "Punett Square" logic for combining
2 parents to breed a child.
The two methods of this IntEnum, breed and mixing_probabilities,
support their use when determining the probability of
each Gene from two parents' Genes
or to randomly select
a child's Gene based on the correct probabilities.
"""
xx = 0
xX = 1
Xx = 1
XX = 2
def breed(self, other):
"""
Return a dict of the probabilty after mixing this Gene with other.
Returns a dict (MixingProbabilities) whose keys, value
pairs are the gene, probability of a child's
after breeding this with another Gene.
"""
return self.mixing_probabilities(other).select_random()
def mixing_probabilities(self, other):
return mixing_probabilities(self, other)
def mixing_probabilities(gene1, gene2):
#prob = dict.fromkeys(list(Gene), 0.0)
prob = GeneProbabilities()
if gene1 > gene2:
q = gene1
gene1 = gene2
gene2 = q
if gene1 == Gene.xx and gene2 == Gene.xx:
prob[Gene.xx] = 1.0
elif gene1 == Gene.xx and gene2 == Gene.xX:
prob[Gene.xx] = 0.5
prob[Gene.xX] = 0.5
elif gene1 == Gene.xx and gene2 == Gene.XX:
prob[Gene.xX] = 1.0
elif gene1 == Gene.xX and gene2 == Gene.xX:
prob[Gene.xx] = 0.25
prob[Gene.xX] = 0.5
prob[Gene.XX] = 0.25
elif gene1 == Gene.xX and gene2 == Gene.XX:
prob[Gene.xX] = 0.5
prob[Gene.XX] = 0.5
elif gene1 == Gene.XX and gene2 == Gene.XX:
prob[Gene.XX] = 1.0
else:
raise AssertionError("Punett square probabilities cases does not cover all cases.")
cum_prob = sum(prob.values())
assert abs(cum_prob - 1) <= 1e-6, "Cumulative probability is not 1."
return prob
class GeneProbabilities(dict):
"""
A Dict whose up to three keys are the probabilities of having
each Gene after breeding two parent Genes together. Effectively
this is a probability mass function (PMF) on the three Gene combos.
If desired, trim_zeros() can be called to remove any impossible
gene combinations in the child. This can occur, for example,
when an two parents with XX and XX genes breed, which can only produce
offspring with the XX Gene. (This can
be helpful to avoid large numbers of options
after multiple Gene's.)
"""
def __init__(self):
#self.probs = self
self[Gene.xx] = 0.0
self[Gene.xX] = 0.0
self[Gene.XX] = 0.0
def _is_normalized(self):
cum_prob = sum(self.values())
return abs(cum_prob - 1) <= 1e-6
def _is_nonnegative(self):
return all([x >= 0 for x in self.values()])
def _is_valid(self):
return self._is_normalized() and self._is_nonnegative()
def trim_zeros(self):
"""
Remove as keys any Gene which has zero probability.
"""
assert self._is_valid()
to_delete = []
for k, v in self.items():
if abs(v) <= 1e-6:
to_delete.append(k)
for k in to_delete:
del self[k]
def select_random(self):
"""
Select a random child Gene using the probabilities defined by this
dict.
"""
assert self._is_valid(), "Probabilities are not a valid pmf."
#enumeration makes use of the guaranteed order of dict and the ordinal values from Gene.
r = random.random()
for i, v in enumerate(itertools.accumulate(self.values())):
if r <= v:
return Gene(i)
if __name__ == "__main__":
from collections import Counter
random.seed(0)
pairs = [[Gene.xx, Gene.XX],[Gene.xX, Gene.XX], [Gene.xX, Gene.xX]]
for pair in pairs:
g1, g2 = pair
probs = g1.mixing_probabilities(g2)
N = 100
samples = [probs.select_random() for i in range(N)]
cnt = Counter(samples)
print(f"{g1.name} cross {g2.name} ({g1}x{g2}) has mixing probabilites: {probs}")
print(f"{N} random draws gives:")
for k in Gene:
print(f"{Gene(k)}: {cnt[k]:4d}; {cnt[k]/N:4.1%}")
print()
|
import itertools
list1=map(int,input().split())
list2=map(int,input().split())
for i in itertools.product(list1,list2):
print(i,end="")
# from itertools import product
#
# A = map(int,input().split())
# B = map(int,input().split())
#
# for item in product(A,B):
# print(item,end=' ')
# def product(ar_list):
# if not ar_list:
# yield ()
# else:
# for a in ar_list[0]:
# for prod in product(ar_list[1:]):
# yield (a,)+prod
#
# print(list(product([[1,2],[3,4],[5,6]]))) |
"""def calculator(num1,operation,num2):
if (operation == "+"):
print (num1 + num2)
elif (operation == "-"):
print (num1 - num2)
elif (operation == "*"):
print (num1 * num2)
elif (operation == "/"):
print (num1 / num2)
else:
print("not a valid operation")
calculator(11,"*",9)"""
def add(num1, num2):
print (int(num1) + int(num2))
def subtract(num1, num2):
print (int(num1)-int(num2))
def multiply(num1, num2):
print(int(num1)*int(num2))
def divide(num1, num2):
print(int(num1)/int(num2))
def calculator():
check = False
while(check == False):
try:
num1 = int(input("first num: "))
num2 = int(input("second num: "))
op = input("put operation: ")
check = True
except:
check = False
print('needs to be a number')
if (op == "+"):
add(num1, num2)
elif (op == "-"):
subtract(num1, num2)
elif (op == "*"):
multiply(num1, num2)
elif (op == "/"):
divide(num1,num2)
else:
print("not a valid operation")
return
calculator() |
# here we are creating the Address class
class Address():
#initialize the attributes of the class
def __init__(self, street, city, state, zip_code):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
#create the user class
class User ():
#initialize the attributes of the User
def __init__(self,first_name, last_name, addresses=None):
self.first_name = first_name
self.last_name = last_name
if addresses is None:
self.addresses = []
else:
self.addresses = addresses
#we will pass in an address object as an argument for this method
def add_address(self,address):
#we check if the address we pass in is in our addresses array yet, if it is not then we add the address array to it
if address not in self.addresses:
self.addresses.append(address)
def display_address(self):
#looping to print the addresses
for i in range(0,len(self.addresses)):
print(f"{self.addresses[i].street}, {self.addresses[i].city}, {self.addresses[i].state}, {self.addresses[i].zip_code}")
a1 = Address('60 green hill', 'Springfield', 'New Jersey', '07081')
a2 = Address('70 fernhill hill', 'Springfield', 'New Jersey', '07081')
a3 = Address('100 worth hilt', 'Edison', 'New Jersey', '07081')
user = User('Luigi','Siopongco')
u2 = User('Rizelyn', 'Benito')
u2.add_address(a3)
user.add_address(a1)
user.add_address(a2)
u2.display_address()
|
# iterative approach
def reverse(A):
n = len(A)
r_list = A[:] # clone the original array
j = 0
for i in range(n-1, -1, -1):
r_list[j] = A[i]
j += 1
return r_list
# recursive approach
def reverse_recursive(A):
if len(A) == 0:
# base case
return []
else:
# recursive case
return [A.pop()] + reverse_recursive(A)
# driver code
print(reverse([1,2,3,4,5]))
print(reverse_recursive([1,2,3,4,5])) |
def bubble_sort(a):
n = len(a)
m = n - 1
while m > 0:
for i in range(m):
if (a[i] > a[i + 1]):
x=a[i]
a[i]=a[i + 1]
a[i + 1]=x
m = m - 1
return a
def quicksort(x):
if len(x) == 1 or len(x) == 0:
return x
else:
pivot = x[0]
i = 0
for j in range(len(x) - 1):
if x[j + 1] < pivot:
x[j + 1],x[i + 1] = x[i + 1], x[j + 1]
i += 1
x[0], x[i] = x[i], x[0]
first_part = quicksort(x[:i])
second_part = quicksort(x[i + 1:])
first_part.append(x[i])
return first_part + second_part
#print(buble_sort([0,7,2,10,2,5]))
#print(quicksort([0,7,2,10,2,5]))
if __name__ == "__main__":
import timeit
data = [0,7,2,10,2,5]
print(timeit.timeit("bubble_sort(data)", setup="from __main__ import bubble_sort, data", number = 10000))
print(timeit.timeit("quicksort(data)", setup="from __main__ import quicksort, data", number = 10000))
|
x = input("Enter First number");
y = input("Enter Second number");
z = input("Enter Third number");
if x > y:
if x > z:
print "%d is max" %x
else:
print "%d is max" %z
elif y>z:
print "%d is max" %y
else:
print "%d is max" %z |
menuPrice={'Cheeze':0.50,'Burger':1.50,'Pizza':2.50}
print menuPrice
for name,price in menuPrice.items():
print name,':$',format(price,'.2f') |
x = int(input("Enter the number to which you find prime number"))
if x > 1:
for i in range(2,x):
if x%i==0:
print "It is not prime"
break;
else:
print x; |
class Test:
def fun(self):
print "Hello"
obj = Test()
obj.fun()
class Person:
def __init__(self,name):
self.name=name
def say_hi(self):
print "Hello,my name is",self.name
p = Person('Rishav')
p.say_hi()
class CSStudent:
"""docstring for CSStudent"""
stream = 'cse'
def __init__(self, roll):
self.roll = roll
a = CSStudent(101)
b = CSStudent(102)
print a.stream
print b.stream
print a.roll
print b.roll
print CSStudent.stream
class CSStudents:
"""docstring for CSStudents"""
stream = 'cse'
def __init__(self,roll):
self.roll = roll
def setAddress(Self,address):
self.address=address
def getAddress(self):
return self.address
a = CSStudents(101)
a.setAddress("Brahmpura,Muzaffarpur")
print a.getAddress()
|
import math
a = 3.4536
print "The integer value of number is"
print math.trunc(a)
print "\n"
print math.ceil(a)
print "\n"
print math.floor(a)
print "\n"
print '%.2f'%a
print "\n"
print '{0:.2f}'.format(a)
print "\n"
print round(a,2) |
def fibonacci(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print fibonacci(11); |
#This func used global
def f():
print s
s="I hate"
f()
print "\n"
#This func has a both variable
def fg():
s= "Rishav"
print s
s="I hate"
fg()
print s
#global keyword
def fr():
global s
print s
s ="Looks handsome"
s ="Python mere jann"
fr()
print s |
def ascending(lst):
for i in range(0, len(lst) - 1):
if lst[i] > lst[i+1]:
return False
return True
print ascending([])
print ascending([3,3,4])
print ascending([7,18,17,19]) |
#Partial functions allow us to fix a certain number of arguments of a function and generate a new function.
from functools import partial
def f(a,b,c,x):
return 1000*a+100*b+10*c+x
g = partial(f,3,1,4)
print g(5)
#Another Example
def add(a,b,c):
return 100*a+10*b+c
add_part = partial(add,c=2,b=1)
print add_part(3) |
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def gcd(a, b):
while b != 0:
t = b
b = a % b
a = t
return a
def lcm(a,b):
return a*b/gcd(a,b)
n = 2
limit = 20
lcm_value = 1
while(n<=limit):
lcm_value = lcm(lcm_value,n)
n+=1
print lcm_value
|
#
# Task
# Given names and phone numbers, assemble a phone book that maps friends' names to their respective phone numbers.
# You will then be given an unknown number of names to query your phone book for.
# For each queried, print the associated entry from your phone book on a new line in the form name=phoneNumber;
# if an entry for is not found, print Not found instead.
#
# Note: Your phone book should be a Dictionary/Map/HashMap data structure.
n = int(input())
i = 0
book = dict() #Declare a dictionary
while(i < n):
name , number = input().split() #Split input for name,number
book[name] = number #Append key,value pair in dictionary
i+=1
while True: #Run infinitely
try:
#Trick - If there is no more input stop the program
query = input()
except:
break
val = book.get(query, 0) #Returns 0 is name not in dictionary
if val != 0:
print(query + "=" + book[query])
else:
print("Not found")
|
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return linear_search_iterative(array, item)
return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
# TODO: implement linear search recursively here
''' Time complexity is O(n) '''
# check if item is in array
if array[index] == item:
return index
# if item is not in array retun NONE
if index == len(array) -1 and array[index] != item:
return None
index += 1
return linear_search_recursive(array, item, index)
# save the index to a variable
# create a condition to check if array[index] == item
# if yes return index
#otherwise call the function again and update the index
# create another condition to check if the index is at the last item in the list
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# # implement binary_search_iterative and binary_search_recursive below, then
# # change this to call your implementation to verify it passes all tests
# return binary_search_iterative(array, item)
return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
# TODO: implement binary search iteratively here
''' Time complexity is O(log n) '''
# Sort the array
array = sorted(array)
# set the left value to the first index of the list which is zero
left = 0
# set the right to the last index in the array
right = len(array) - 1
while left <= right:
# get the middle index of the array
middle_value = (left + right) // 2
# if the middle value is less than item than move to the left index to the right once
if array[middle_value] < item:
left = middle_value + 1
# if the item is greater than the middle index move the right to the left once
if array[middle_value] > item:
right = middle_value - 1
# if the middle value == the target value return the middle value index
if array[middle_value] == item:
return middle_value
# if the item is not in the array return NONE
return None
# reasign array to sorted array
# only sort once
# create a variable named median and set it to int(len(array) / 2)
# once implemented, change binary_search to call binary_search_iterative
# to verify that your iterative implementation passes all tests
def binary_search_recursive(array, item, left=None, right=None):
# TODO: implement binary search recursively here
''' Time complexity is O(log n) '''
# Sort the array
array = sorted(array)
# get the middle index of the array
if left == None and right == None:
left = 0
right = len(array) -1
middle_value = (left + right) // 2
print('MIDDLE VALUE', middle_value)
if left > right:
return None
# if the middle value == the target value return the middle value index
if array[middle_value] == item:
print('---MIDDLE Value ---',middle_value)
return middle_value
# if the middle value is less than item than move to the left index to the right once
if array[middle_value] < item:
left = middle_value + 1
print('---LEFT----', left)
return binary_search_recursive(array, item, left, right)
# if the item is greater than the middle index move the right to the left once
if array[middle_value] > item:
right = middle_value - 1
print('----RIGHT 1----', right)
return binary_search_recursive(array, item, left, right)
# once implemented, change binary_search to call binary_search_recursive
# to verify that your recursive implementation passes all tests
|
from sys import stdin
import sys
import fileinput
#Para ejecutar se debe hacer desde consola lo siguente:
#python3 nombre.py
def main():
cond = "1"
while (cond=="1" or cond=="2"):
print("-----------------------------------------------------")
print("Bienvenido al Glosario de terminos de Criptomonedas.")
print("Digite 1 para buscar una palabra.")
print("Digite 2 para añadir una parabla.")
print("Digite otro valor para salir.")
print("-----------------------------------------------------")
cond = stdin.readline().strip()#Siguiente Menu
d = {}#Nuestro diccionario
name = 'glos.txt'·#Nombre del archivo que vamos a abir
file = open(name,"r")#Modo lectura
text = file.read()
file.close()
lines = text.strip().splitlines()
for line in lines:
l = line.strip().split("=")
d[l[0][:-1]]=l[1][1:]#Añadimos a nuestro diciconario todo lo que este en nuestro txt
if cond == "1":
print("Modo Busqueda")
pal = input("Ingrese la palabra a buscar")
if pal in d:
print(d[pal])
else:
print("La palabra no se encuentra en el Diccionario")
elif cond == "2":
print("Modo Añadir")
npal = input("Digite la palabra que va a añadir (Recuerde que las mayuculas son importantes)").strip()
if npal in d:
print("La palabra es INVALIDA ya que actualmente se encuentra en el diccionario.")
else:
ndef = input("Escriba de forma clara el significado").strip()
tex = "\n" + npal + ' = ' + ndef
file = open(name,"a")#Modo para añadir en la ultima linea
file.writelines(tex)
file.close()
else:
print("Adios !!")
main()
|
def is_float(dat):
try:
float(dat)
return True
except:
print("Error: Tipo de dato INVALIDO")
return False
def main():
criptos = ["BTC","BCC","LTC","ETH","ETC","XRP"]
i=0
total=0
for i in range(3):
cripto = input("Ingrese el nombre de la moneda: ").upper()
if cripto in criptos:
var = False
while not var:
cant = input("Indique la cantidad de "+cripto+":")
var = is_float(cant)
var = False
while not var:
cotiz = input("Indique la cotización en USD de "+cripto+":")
var = is_float(cotiz)
total = total + float(cant) * float(cotiz)
else:
print("Moneda invalida.")
print("El tota en USD que tiene el usuario es de ",str(total))
main()
|
import random
box1=[0,0,0]#1が当たりのアドレス、2がプレイヤーの選択、3がゲーム側からの開示
box2=[0,0,0]
box3=[0,0,0]
first=0
second=0
takes=input("takes:")
for i in range(int(takes)):
#あたりを混入
right=random.randrange(0,3)
box1[right]=1
#プレイヤーの選択
playerchoise=random.randrange(0,3)
box2[playerchoise]=1
#1つ開示当たりでなく選ばれていない
gamechoise=random.randrange(0,3)
while box1[gamechoise]==1 or box2[gamechoise]==1:
gamechoise=random.randrange(0,3)
box3[gamechoise]=1
#そのままの場合
if box1[playerchoise]==1:
first+=1
print(str(box1))
print(str(box2))
print(str(box3))
print("当たりと選択が一致している")
#自分の選択以外+開示されていない物を選択した場合あたりを選んでいたら外れ
while box2[playerchoise]==1 or box3[playerchoise]==1:
playerchoise=random.randrange(0,3)
box2=[0,0,0]
box2[playerchoise]=1
if box1[playerchoise]==1:
print(str(box1))
print(str(box2))
print(str(box3))
print("変更すると答えがあった")
second+=1
# print(str(box1)+"あたり")
# print(str(box2)+"プレイヤーの選択")
# print(str(box3)+"開示")
print("//////////////////")
box1=[0,0,0]
box2=[0,0,0]
box3=[0,0,0]
print(str(first)+"/"+takes)
print(str(second)+"/"+takes)
print("結果変えたほうが当たる確率は"+str(second/first)+"倍高くなる")
|
import time
valor = -3
print("valor absoluto:", abs(valor))
time.sleep(5) #execução para por 5 segundos
valor = 127
print("valor em hexadecimal:", hex(valor))
print("valor em binario:", bin(valor))
time.sleep(2) #execução para por 5 segundos
a1 =2
a2 = 5
menor = min(a1,a2)
menor = min(45,3,78,9,13)
maior = max(45,3,78,9,13)
print("menor:", menor," maior:", maior)
valor = 3.8
print("valor arredondado:", round(valor)) #arredonda para o inteiro + proximo
#para arredondar para baixo, deve-se empregar a função floor do modulo math
#neste caso, deve-se importar este modulo para fazer uso desta função...
import math
print("valor arredondado para baixo:", math.floor(valor))
print("valor arredondado para cima:", math.ceil(valor)) #arredonda p/ cima
#conversoes de tipo
val = 23.78 #val e´ do tipo float , isto e´, um numero real
valInt = int(val) #carrega em valInt um inteiro (sem parte fracionaria) de val
valString = "os valores sao: " + str(val) + " e " + str(valInt)
print(valString)
valorNumaString = "45.33"
valor = float(valorNumaString) #converte a string num float e atribui a valor
print (valor + 1000) #agora e´ possivel fazer calculos com o valor
#testando o tipo de uma variavel:
x = isinstance(valor, float) #isinstance verifica se valor é um float; retorna um booleano (True ou False)
print(x)
print(type(valString)) #função type retorna o tipo da variável
if isinstance(valString, str):
print("valString é uma string...")
import replit
replit.clear() #limpa a tela do console repl.it
print("fim.") |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 12:36:16 2020
@author: Amey
"""
def delete_zeros(arr):
for i in range(0,len(arr)):
try:
arr.remove(0)
except:
return
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 17:53:56 2020
@author: Amey
"""
def guess_thenumber():
import random
a=random.randint(1,20)
print('I am thinking of a number between 1 and 20 \n')
guess=input()
guesses=0;
while guess!=a:
if a>int(guess):
print('higher')
guess=input()
guesses=guesses+1
if a<int(guess):
print('lower')
guess=input()
guesses=guesses+1
if a==int(guess):
print('right on')
print(guesses+1)
break
guess_thenumber()
|
"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
called_codes = []
def is_a_bangalore_num(num):
'''
:param num: input phone number (str)
:return: True if input phone number belongs to someone in Bangalore else False (Bool)
'''
return num[1:4] == "080" and num[0] == "("
def is_num_mobile(num):
'''
:param num: input phone number (str)
:return: True if input phone number is a mobile else False (Bool)
'''
return len(num) == 11 and num[5] == " "
def is_num_fixed(num):
'''
:param num: input phone number (str)
:return: True if input phone number is a fixed line else False (Bool)
'''
return num[0] == "("
def get_mobile_prefix(num):
'''
:param num: input phone number (str)
:return: 4-digit mobile prefix (str)
'''
return num[:4]
def get_fix_areacode(num):
'''
:param num: input phone number (str)
:return: variable length area code for the fixed line (str)
'''
code_end = num.find(")")
if code_end == -1: # Defensive programming
print(f"Unknown number type found: {num}")
return num[1:code_end]
def is_num_telemarketer(num):
'''
:param num: input phone number (str)
:return: True if input phone number is a telemarketer else False (Bool)
'''
# return num[5] != " " and num[0] != "(" --- Works but erroneous numbers may exist!
if num[5] != " " and num[0] != "(":
if num[:4] != "140": # Defensive programming
print(f"Unknown number type found:{num}")
else:
return True
return False
from_bng_calls = 0 # Number of calls originating FROM Bangalore
to_bng_calls = 0 # Number of calls originating TO Bangalore FROM Bangalore
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
for c in calls:
if is_a_bangalore_num(c[0]):
from_bng_calls += 1
if is_num_mobile(c[1]):
called_codes.append(get_mobile_prefix(c[1]))
elif is_num_fixed(c[1]):
if is_a_bangalore_num(c[1]):
to_bng_calls += 1
called_codes.append(get_fix_areacode(c[1]))
elif is_num_telemarketer(c[1]):
called_codes.append("140")
else:
print(f"Unknown number:{c[1]} found in data!")
called_codes = list(set(called_codes))
called_codes.sort() # Python's sort arranges in increasing lexicographic order
print("The numbers called by people in Bangalore have codes:")
for cc in called_codes:
print(cc)
print(f"{to_bng_calls*100/from_bng_calls:.2f} percent of calls from fixed lines in Bangalore are calls to other fixed "
f"lines in Bangalore.")
"""
TASK 3:
(080) is the area code for fixed line telephones in Bangalore.
Fixed line numbers include parentheses, so Bangalore numbers
have the form (080)xxxxxxx.)
Part A: Find all of the area codes and mobile prefixes called by people
in Bangalore.
- Fixed lines start with an area code enclosed in brackets. The area
codes vary in length but always begin with 0.
- Mobile numbers have no parentheses, but have a space in the middle
of the number to help readability. The prefix of a mobile number
is its first four digits, and they always start with 7, 8 or 9.
- Telemarketers' numbers have no parentheses or space, but they start
with the area code 140.
Print the answer as part of a message:
"The numbers called by people in Bangalore have codes:"
<list of codes>
The list of codes should be print out one per line in lexicographic order with no duplicates.
Part B: What percentage of calls from fixed lines in Bangalore are made
to fixed lines also in Bangalore? In other words, of all the calls made
from a number starting with "(080)", what percentage of these calls
were made to a number also starting with "(080)"?
Print the answer as a part of a message::
"<percentage> percent of calls from fixed lines in Bangalore are calls
to other fixed lines in Bangalore."
The percentage should have 2 decimal digits
"""
|
correct = [[1, 2, 3],
[2, 3, 1],
[3, 1, 2]]
incorrect = [[1, 2, 3, 4],
[2, 3, 1, 3],
[3, 1, 2, 3],
[4, 4, 4, 4]]
incorrect2 = [[1, 2, 3, 4],
[2, 3, 1, 4],
[4, 1, 2, 3],
[3, 4, 1, 2]]
incorrect3 = [[1, 2, 3, 4, 5],
[2, 3, 1, 5, 6],
[4, 5, 2, 1, 3],
[3, 4, 5, 2, 1],
[5, 6, 4, 3, 2]]
incorrect4 = [['a', 'b', 'c'],
['b', 'c', 'a'],
['c', 'a', 'b']]
incorrect5 = [[1, 1.5],
[1.5, 1]]
correct6 = [[1]]
# Define a function check_sudoku() here:
def check_sudoku(sud):
if len(sud[0]) != len(sud) or sud is None:
return False
n = len(sud)
valid_set = {i + 1 for i in range(n)}
for row in sud:
if set(row) != valid_set:
return False
for i in range(len(sud)):
col = [j[i] for j in sud]
if set(col) != valid_set:
return False
return True
print(check_sudoku(incorrect))
# >>> False
print(check_sudoku(correct))
# >>> True
print(check_sudoku(incorrect2))
# >>> False
print(check_sudoku(incorrect3))
# >>> False
print(check_sudoku(incorrect4))
# >>> False
print(check_sudoku(incorrect5))
# >>> False
print(check_sudoku(correct6))
|
def rearrange_digits(input_list):
"""
Rearrange Array Elements so as to form two number such that their sum is maximum.
Assumption: All array elements are positive
Args:
input_list(list): Input List
Returns:
(int),(int): Two maximum sums
"""
if not input_list:
return None
for input in input_list: # Verifies the assumption to deal with only non-negative numbers
if input < 0 or input > 9:
return None
sorted_list = merge_sort(input_list)
num1 = get_alternate_places(0,sorted_list)
num2 = get_alternate_places(1,sorted_list)
return [num1, num2]
def get_alternate_places(index, arr):
'''
Returns a number composed of every alternate entries in arr starting from index
:param index: starting index (integer)
:param arr: list of integers
:return: Integer composed of every alternate entries in arr starting from index
'''
runner = index
result_list = []
while runner <= len(arr)-1:
result_list.append(arr[runner])
runner += 2
# reverse the list to get the max value, convert each entry to str to join and cast it to integer
return int(''.join(map(lambda x: str(x), result_list[::-1])))
def merge_sort(arr):
'''
Sorts the input list using merge sort
:param input_list: list of integers
:return: sorted list of integers
'''
if len(arr) == 1:
return arr
mid = len(arr)//2
arr1 = merge_sort(arr[:mid])
arr2 = merge_sort(arr[mid:])
return merge(arr1, arr2)
def merge(arr1, arr2):
'''
Helper function for merge sort
:param arr1: list of integers
:param arr2: list of integers
:return: merged & sorted ist of integers
'''
left_pointer = 0
right_pointer = 0
res = []
while left_pointer < len(arr1) and right_pointer < len(arr2):
if arr1[left_pointer] < arr2[right_pointer]:
res.append(arr1[left_pointer])
left_pointer += 1
else:
res.append(arr2[right_pointer])
right_pointer += 1
res += arr1[left_pointer:] # Easier to ask forgiveness than permission
res += arr2[right_pointer:]
return res
def test_function(test_case):
output = rearrange_digits(test_case[0])
solution = test_case[1]
if solution:
if sum(output) == sum(solution):
print("Pass")
else:
print("Fail")
else:
# Solution is None
if not output and not solution:
print("Pass")
else:
print("Fail")
test_function([[1, 2, 3, 4, 5], [542, 31]])
test_case2 = [[4, 6, 2, 5, 9, 8], [964, 852]]
test_case3 = [[1,2,1,2,1,1,1],[2111,211]]
test_case4 = [[0,0,0,0,0,0], [0,0]]
test_case5 = [[-1,2,4,5,3,3],None]
test_case6 = [[9,10,1,2,3,4,5], None]
test_case7 = [[],None]
test_function(test_case2)
test_function(test_case3)
test_function(test_case4)
test_function(test_case5)
test_function(test_case6)
test_function(test_case7) |
'''
Cree un programa que permita al usuario elegir entre las siguientes opciones:
1 - Agregar un alumno: debe solicitarse nombre, padrón y nota.
2 - Consultar aprobados: debe mostrar los alumnos con nota mayor a 4.
3 - Cantidad de alumnos totales y promedio general.
4 - Quitar a un alumno.
5 - Salir
'''
def quitar_alumno(lista_alumnos: list) -> None:
entrada_usuario = input("Ingrese el nombre del alumno que quieres eliminar: ")
for i in lista_alumnos:
if entrada_usuario == i[0]:
lista_alumnos.pop(i)
if input("Quieres volver al menu? (si/no): ") == "si": menu()
def cantidad_alumnos_totales_promedio(lista_alumnos: list) -> None:
print(f"La cantidad de alumnos total es: {len(lista_alumnos)}")
suma_notas = 0
for i in lista_alumnos:
suma_notas += i[2]
promedio = suma_notas / len(lista_alumnos)
print(f"El promedio de las notas de todos los alumnos es {promedio}")
if input("Quieres volver al menu? (si/no): ") == "si": menu()
def consultar_aprobados(lista_alumnos: list) -> None:
for i in lista_alumnos:
if i[2] >= 4:
print(i[0])
if input("Quieres volver al menu? (si/no): ") == "si": menu()
def agregar_alumno(lista_alumnos: list) -> None:
entrada_usuario = input("Ingrese nombre, padrón y nota separados por una coma ',': ")
entrada_usuario = entrada_usuario.split(",")
entrada_usuario[2] = int(entrada_usuario[2])
lista_alumnos.append(entrada_usuario)
if input("Quieres volver al menu? (si/no): ") == "si": menu()
def menu(lista_alumnos: list) -> None:
print('''
1 - Agregar un alumno: debe solicitarse nombre, padrón y nota.
2 - Consultar aprobados: debe mostrar los alumnos con nota mayor a 4.
3 - Cantidad de alumnos totales y promedio general.
4 - Quitar a un alumno.
5 - Salir
''')
eleccion = int(input("Ingrese el numero que corresponda a la opcion elegida: "))
if eleccion == 1: agregar_alumno(lista_alumnos)
elif eleccion == 2: consultar_aprobados(lista_alumnos)
elif eleccion == 3: cantidad_alumnos_totales_promedio(lista_alumnos)
elif eleccion == 4: quitar_alumno(lista_alumnos)
def main() -> None:
lista_alumnos = [["matias", "1061232", 10], ["lucas", "213123", 0]]
menu(lista_alumnos)
main() |
'''
Realizar un programa que permita jugar a adivinar un número entero.
El participante A elige el número a adivinar y luego hace jugar al participante B,
el cual deberá intentar adivinarlo arriesgando números.
El programa debe guiar al participante B indicándole, en cada intento,
si el número arriesgado es mayor o menor al definido por el participante A.
El juego debe concluir al acertar el número o superar los 20 intentos.
Al acertar el número debe indicar la cantidad de intentos que fueron utilizados para lograrlo.
En caso de no haber conseguido el objetivo, debe indicarle que ha superado los 20 intentos.
'''
contador = 1
print("Turno del participante A")
numero = int(input("Ingresar numero para que adivine el participante B: "))
print("\nTurno del participante B")
intento = int(input("Ingresar un numero para adivinar: "))
while intento != numero and contador < 20:
if intento > numero:
print("El numero ingresado es mayor al numero buscado")
elif intento < numero:
print("El numero ingresado es menor al numero buscado")
contador += 1
intento = int(input("Ingresar un numero para adivinar: "))
if numero == intento:
print("Acertaste en,", contador, "intentos!")
else:
print("Perdiste malo") |
cadena = "Qué lindo día que hace hoy"
def contar_palabras(cadena: str) -> dict:
diccionario_de_palabras = dict()
cadena = cadena.lower()
for i in cadena:
if i == "é":
i = "e"
elif i == "á":
i="a"
elif i == "í":
i="i"
elif i == "ó":
i="o"
elif i == "ú":
i="u"
cadena = cadena.split()
for i in cadena:
if i not in diccionario_de_palabras.keys():
diccionario_de_palabras[i] = 1
else:
diccionario_de_palabras[i] += 1
return print(diccionario_de_palabras)
contar_palabras(cadena) |
suma = 0
for i in range(10):
numero = int(input("Ingrese un numero: "))
suma = suma + numero
print(suma) |
while True:
a = input("Enter a standard list, Please:")
import pdb; pdb.set_trace() # breakpoint 70d01fab //
b = []
d = len(a)
i = 0
while (i < d):
j = 0
c = max(a)
b.append(c)
while (a[j] != c):
j = j + 1
del a[j]
i = i + 1
print "The list which sorted by Mr.Xie was become:",b
|
"""
https://projecteuler.net/problem=2
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
def _is_prime(number:int):
number_of_divisors = 0
for divisor in range(1, number+1):
if number%divisor == 0:
number_of_divisors += 1
return True if number_of_divisors == 2 else False
def _is_factor(number:int, divisor:int):
return True if number % divisor == 0 else False
def largest_prime_factor(number: int):
for candidate_largest_prime_factor in range(int(number/2), 1, -1):
if _is_factor(number, candidate_largest_prime_factor):
if _is_prime(candidate_largest_prime_factor):
return candidate_largest_prime_factor
if __name__ == "__main__":
number = 600851475143
result = largest_prime_factor(number)
print("result :", result) |
def binThreePrint(node):
'''
Example of recursion
The method returns string of node values of binary three in order (i.e. left-root-right)
:param node: binary tree in a list format [node, [left-three], [right-three]]
:return: string of node values of binary three in order
'''
mystr = ''
if node[1]:
mystr += str(binThreePrint(node[1]))
mystr += str(node[0])
if node[2]:
mystr += str(binThreePrint(node[2]))
return mystr |
import numpy as np
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
num_train = X.shape[0]
num_class = W.shape[1]
#scores = np.zeros(num_train,num_class)
scores = X.dot(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
for i in range(num_train):
# compute Li
fmax= np.max(scores[i])
scores[i] -= fmax
correct_class_score = scores[i,y[i]]
M = np.exp(correct_class_score)/np.sum(np.exp(scores[i]))
loss += -np.log(M)
for j in range(num_class):
N = np.exp(scores[i,j])/np.sum(np.exp(scores[i]))
if j ==y[i]:
dW[:,y[i]]+= (M-1)*X[i].T
else:
dW[:,j] += N*X[i].T
loss /= num_train
loss += reg*np.sum(W*W)
dW /= num_train
dW += 2*reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
num_train = X.shape[0]
num_class = W.shape[1]
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
scores = X.dot(W)
temp_matrix = np.zeros(scores.shape)
max_each_row = np.max(scores,axis=1).reshape(-1,1)
scores -= max_each_row
summation = np.sum(np.exp(scores),axis=1).reshape(-1,1)
scores = np.exp(scores)
scores = np.divide(scores,summation)
temp_matrix[range(num_train),list(y)] =-1
scores += temp_matrix
dW = X.T.dot(scores) / num_train + 2*reg*W
log_summation = np.log(summation)
vector = scores[range(num_train),list(y)].reshape(-1,1)
L = -vector+ log_summation
loss = np.sum(L)/num_train + reg*np.sum(W*W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from scipy.stats import levene, bartlett, iqr
import sklearn.preprocessing as preprocessing
import matplotlib.pyplot as plt
# constants for finding required indexes in the original data table
COMPLEX_AGE_INDEX = 2
TOTAL_ROOMS_INDEX = 3
TOTAL_BEDROOMS_INDEX = 4
COMPLEX_INHABITANTS_INDEX = 5
APARTMENTS_NR_INDEX = 6
MEDIAN_COMPLEX_VALUE_INDEX = 8
# optimization strategy choice constants
STANDARDIZATION_METHOD_INDEX = 1
GAUSSIAN_DISTRIBUTION_METHOD_INDEX = 2
QUANTILE_TRANSFORMATION_METHOD_INDEX = 3
NORMALIZATION_OF_INPUTS_METHOD_INDEX = 4
# init empty arrays for taking data from file
data = []
answers = []
primary_data_from_file = []
# ask about how to perform data reading from original file
print(
"Do you want to read all the data or only the part of the lab? Available answers:\n" +
"\ty - yes, read all the data\n"
"\tn - no, read only lab's part of the data"
)
choice_about_analyzable_data = input(">>>\t")
# read the data from file considering user's choice about how to make read (all the data or conform lab requirements)
with open("apartment_db.txt") as file_db:
if choice_about_analyzable_data == 'n':
for line in file_db:
row = line.split(",")
current_row_usable_data = [
float(row[COMPLEX_AGE_INDEX]),
float(row[TOTAL_ROOMS_INDEX]),
float(row[TOTAL_BEDROOMS_INDEX]),
float(row[COMPLEX_INHABITANTS_INDEX]),
float(row[APARTMENTS_NR_INDEX]),
float(row[MEDIAN_COMPLEX_VALUE_INDEX])
]
primary_data_from_file.append(current_row_usable_data)
elif choice_about_analyzable_data == 'y':
for line in file_db:
row = line.split(",")
current_row_usable_data = [
float(row[0]),
float(row[1]),
float(row[COMPLEX_AGE_INDEX]),
float(row[TOTAL_ROOMS_INDEX]),
float(row[TOTAL_BEDROOMS_INDEX]),
float(row[COMPLEX_INHABITANTS_INDEX]),
float(row[APARTMENTS_NR_INDEX]),
float(row[7]),
float(row[MEDIAN_COMPLEX_VALUE_INDEX])
]
primary_data_from_file.append(current_row_usable_data)
print(
"What data optimization method do you want to use? Available answers:\n"
"\t1 - Standardization;\n" +
"\t2 - Gaussian distribution;\n" +
"\t3 - Quantile transformer;\n" +
"\t4 - Normalization of the inputs;\n"
"\tAny other number - no optimization required"
)
method_for_data_optimization = input(">>>\t")
# get the data from primary taken data after optimizations conform user's choice made previously
if choice_about_analyzable_data == "y":
for i in range(len(primary_data_from_file)):
current_record = [
primary_data_from_file[i][0], primary_data_from_file[i][1],
primary_data_from_file[i][COMPLEX_AGE_INDEX],
primary_data_from_file[i][TOTAL_ROOMS_INDEX],
primary_data_from_file[i][TOTAL_BEDROOMS_INDEX],
primary_data_from_file[i][COMPLEX_INHABITANTS_INDEX],
primary_data_from_file[i][APARTMENTS_NR_INDEX],
primary_data_from_file[i][7]
]
data.append(current_record)
answers.append(primary_data_from_file[i][MEDIAN_COMPLEX_VALUE_INDEX])
elif choice_about_analyzable_data == "n":
for i in range(len(primary_data_from_file)):
current_record = [
primary_data_from_file[i][0],
primary_data_from_file[i][1],
primary_data_from_file[i][2],
primary_data_from_file[i][3],
primary_data_from_file[i][4]
]
data.append(current_record)
answers.append(primary_data_from_file[i][5])
# apply chosen optimization for the data (considering small amount of options "if-else" relation implemented
transformer = None
if int(method_for_data_optimization) == STANDARDIZATION_METHOD_INDEX:
transformer = preprocessing.StandardScaler()
data = transformer.fit_transform(data)
elif int(method_for_data_optimization) == GAUSSIAN_DISTRIBUTION_METHOD_INDEX:
transformer = preprocessing.PowerTransformer(method="box-cox", standardize=True)
data = transformer.fit_transform(data)
elif int(method_for_data_optimization) == QUANTILE_TRANSFORMATION_METHOD_INDEX:
transformer = preprocessing.QuantileTransformer(output_distribution="normal", random_state=0)
data = transformer.fit_transform(data)
if int(method_for_data_optimization) == NORMALIZATION_OF_INPUTS_METHOD_INDEX:
data = preprocessing.normalize(data)
# choose if there is IQR outliers filtering required
choice_of_outliers_filtering = input("Do you want to perform Outliers IQR filtering (y - yes, n - no)?\n>>>\t")
if choice_of_outliers_filtering == "y":
Q1 = np.quantile(answers, 0.25)
Q3 = np.quantile(answers, 0.75)
IQR = iqr(answers)
non_outliers_indexes = []
for i in range(len(answers)):
if (Q1 - (1.5 * IQR)) < answers[i] < (Q3 + (1.5 * IQR)):
non_outliers_indexes.append(i)
clean_answers = []
clean_data = []
for index in non_outliers_indexes:
clean_answers.append(answers[index])
clean_data.append(data[index])
answers = clean_answers
data = clean_data
# transform standard arrays into numpy arrays
data, answers = np.array(data), np.array(answers)
polynomial_degree = input(
"Choose a regression polynomial degree (recommended use of 1-5 degree, otherwise long processing occurs):\t"
)
# init polynomial features object
transformer = PolynomialFeatures(degree=int(polynomial_degree), include_bias=True)
# fit input for polynomial analysis
transformer.fit(data)
# polynomial variables values generation out of input
polynomial_data = transformer.transform(data)
# fit data with answers to the LinearRegression module for analysis
model = LinearRegression().fit(polynomial_data, answers)
# try to analyze data and get scores
r_sq = model.score(polynomial_data, answers)
# show variables that are inner part of linear regression module
print("\n\t\tcoefficient of determination (R_square): " + str(r_sq))
# generate possible answers using the same data as was provided to compare solutions
answers_predicted = model.predict(polynomial_data)
print("\t\tLevine's test result = " + str(levene(answers, answers_predicted)[1]))
print("\t\tBartlett's test result = " + str(bartlett(answers, answers_predicted)[1]))
representable_plot_size = len(data)
# calculate medium error
medium_error = 0
for i in range(representable_plot_size):
medium_error += abs(answers[i] - answers_predicted[i])
medium_error /= representable_plot_size
print("\t\tMedium error is " + str(medium_error))
# set all original answers as red dots on the diagram
plt.scatter(range(0, representable_plot_size), answers[:representable_plot_size], color="red")
# set predicted answers as blue plot on the diagram
plt.plot(range(0, representable_plot_size), answers_predicted[:representable_plot_size], color="blue")
plt.title("Graph for original answers and predictions (originals - red, predicted - blue)")
plt.xlabel("record ID")
plt.ylabel("Median Complex Value")
plt.grid(color="black")
plt.show() |
# coding=utf-8
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
__author__ = 'Vincent Dedoyard'
abc_product = 0
for a in range(1, 1000):
for b in range(1, 1000):
c = 1000 - (a + b)
if a ** 2 + b ** 2 == c ** 2:
abc_product = max(abc_product, a * b * c)
print abc_product
|
# coding=utf-8
"""
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
"""
__author__ = 'Vincent Dedoyard'
sum_of_squared = sum([x ** 2 for x in range(1, 101)])
squared_sum = sum([x for x in range(1, 101)]) ** 2
print squared_sum - sum_of_squared
|
n=int(input("Enter the number of trees:"))
tarun = input("Enter the height of trees separated by space: ")
list = tarun.split()
sum = 0
for num in list:
sum += int (num)
print("Sum = ",sum)
avg = sum/n
print(avg)
round(avg,3)
print("avg = ",avg) |
class Employee():
empCount = 0 #initialization of the data member
empSal = [];
def __init__(self,name,family,salary,department): #default constructor
self.empname = name
self.empfamily = family
self.empsalary = salary
self.empdepartment = department
Employee.empCount +=1 #counts the number of employees
Employee.empSal.append(salary) #appends salaray attribute
def avg_salary(self):
print('the average salary is')
sumSal = 0;
for sal in Employee.empSal:
sumSal = sumSal+ int(sal);
return sumSal/len(Employee.empSal)
class FulltimeEmployee(Employee):
def __init__(self,name,family,salary,department):
Employee.__init__(self,name,family,salary,department)
emp1 = FulltimeEmployee('lakshman',' kumar','7000','CS');
emp2 = FulltimeEmployee('praneeth','thota','5000','ee');
emp3 = FulltimeEmployee('tarun','kasturi','4000','CS');
print(FulltimeEmployee.empCount) #inherits characteristics from parent class
print(FulltimeEmployee.empSal)
avgSal = FulltimeEmployee.avg_salary(Employee);
print(avgSal) |
# an example for raw_input and int conversion
firstNo=10 #interger type
secondNo=20.0 #float type
name="UMKC"
print('welcome to',name)
print (firstNo,' plus ',secondNo,' equals ',firstNo+secondNo)
"""num1String = raw_input('Please enter an integer: ') #python 2
num2String = raw_input('Please enter a second integer: ') """
num1String = input('Please enter an integer: ')
num2String = input('Please enter a second integer: ')
num1 = int(num1String)
num2 = int(num2String)
print ('Here is some output')
#print num1,' plus ',num2,' equals ',num1+num2 --python2
#print 'Thanks for playing'
print (num1,' plus ',num2,' equals ',num1+num2)
print ('Thanks you. END') |
class Person: #base class
per_count=0
def __init__(self,name,email): #default constructor
self.name=name
self.email=email
Person.per_count+=1
def DisplayDetails(self):
print("Name: ",self.name,"Email: ",self.email)
def DispCount(self):
print("Total count of persons: ",Person.per_count)
class Employee(Person):#Inheritance Usage
def __init__(self,Emp_name,email,Employee_phone): #default init constructor
Person.__init__(self,Emp_name,email)
self.Employee_phone = Employee_phone
self.Employee_phone=Employee_phone
def DisplayDetails(self):
Person.DisplayDetails(self)
print("Employee_phone: ",self.Employee_phone)
class Passenger(Employee): #inheritance
def __init__(self,name,email,emp_phone,Emp_name,e_email,Employee_phone,time,date): #default Init constructor
super().__init__(name,email,Employee_phone) #usage of super call
self.emp_phone=emp_phone
self.name=name
self.email=email
self.ename=Emp_name
self.eemail=e_email
self.ephone=Employee_phone
self.time=time
self.date=date
def DisplayDetails(self):
Person.DisplayDetails(self)
print("Emp phone:", self.emp_phone)
print("The Airplane time is: ",self.time)
print("The Reserved date is: ",self.date)
class Book():
def __init__(self,per_name,Travel_date, travel_time): #default init constructor
self.person_name=per_name
self.travel=Travel_date
self.time=travel_time
def DisplayDetaails(self):
print("Person_name: ",self.person_name,"Travel date: ",self.travel,"Travel time: ",self.time)
class Flight(Person,Book): #multiple Inheritance
def __init__(self,name,email,per_name,blood_pressure,sugar_level): #default init constructor
# super().__init__(name,email)
Person.__init__(self,name,email)
Book.__init__(self,per_name,blood_pressure, sugar_level)
def DisplayDetails(self):
Book.DisplayDetaails(self)
Person.DisplayDetails(self)
#creation of instances for above classes
person1=Person('Lakshman','lakshman95@gmail.com')
person2=Person('Praneeth','praneeththota@gmail.com')
Employee1=Employee('Tarun','tarunkasturi@gmail.com','9162628454')
Employee2=Employee('Pavan','pavan123@gmail.com','916454585')
Book1=Book('Lakshman','15 march 2019','12 am')
Book2=Book('Praneeth','20 April 2019','2 pm')
print("##Persons Count##")
Person.DispCount(Person)
#Flight attending persons
Flight1=Flight('Lakshman','lakshman95@gmail.com','lakshman','15 march 2019', '12am')
Flight2=Flight('Praneeth','praneeththota@gmail.com','praneeth','20 April 2019','2 pm')
print("###Employee Details###")
Employee1.DisplayDetails();
Employee2.DisplayDetails();
print("##Person Details##")
person1.DisplayDetails();
person2.DisplayDetails();
print("##Book Details##")
Book1.DisplayDetaails();
Book2.DisplayDetaails();
print("#Flight attending person details")
Flight1.DisplayDetaails();
Passenger1=Passenger("brundha","brundha@gmail.com","9162625252","Tarun","tarunkasturi@gmail.com","12345","9 40 PM","16 JUNE")
print("passenger Appointments-1")
Passenger1.DisplayDetails()
Passenger2=Passenger("Yasritha","yasritha@gmail.com","990909876","pavan","pavan123@gmail.com","898976","8 00 AM","21 JUNE")
print("Passenger Appointments-2")
Passenger2.DisplayDetails() |
# -*- coding: utf-8 -*-
import datetime
class Util(object):
@staticmethod
def get_time_now():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@staticmethod
def get_time_from_str(time_str):
if '-' in time_str and ':' in time_str: # 06-18 21:07
date_today = datetime.date.today()
date_with_year = str(date_today.year) + '-' + time_str
date = datetime.datetime.strptime(date_with_year, "%Y-%m-%d %H:%M")
return date
elif '-' in time_str: # 2017-06-18
return datetime.datetime.strptime(time_str, "%Y-%m-%d")
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 23 13:02:41 2017
"""
def odd(x):
'''
x: int or float.
returns: True if x is odd, False otherwise
'''
# Your code here
return x % 2 != 0
|
import textwrap
def wrap(string, max_width):
l=textwrap.wrap(string,max_width)
str1=''
for i in l:
str1=str1+i+"\n"
return str1 |
#List - mutable sequence of objects
#Zero based index position
def main():
students = ["Sue","Kathy","sekar","Bryan"]
s1 = ["Sue","Kathy","sekar","Bryan"]
#add items to list use append
students.append("Steve")
students.append(s1)
print(students)
print(students[0])
del students[0]
print(students[0])
#Immutable list: Tuple: Sequence of immutable python objects.Same as lists but they can not be changed.
tup1 = ("Sue","Kathy","sekar","Bryan")
tup3 = ("Ryan",)
#Accessing values from Tuple
print(tup1[0])
#update tuples and list
students[0] = "brown"
tup4 = tup1 + tup3
print(tup4)
if __name__ == "__main__":
main() |
# -*- coding: utf-8 -*-
"""
PIC16 - Spring 2018
Final Project: Game
Grant Huang
"""
import re
from makeWordPatterns import wordPattern
from wordPatterns import allPatterns
from wordPatterns import dictionary
#1. Find the word pattern for each cipherword in the ciphertext.
#2. Find the list of English word candidates that each cipherword could decrypt to.
#3. Create one cipherletter mapping for each cipherword using the cipherword’s list of candidates. (A cipherletter mapping is just a dictionary value.)
#4. Intersect each of the cipherletter mappings into a single intersected cipherletter mapping.
#5. Remove any solved letters from the intersected cipherletter mapping.
def blankLetterMap():
'''creates ciphertext alphabet mapped to nothing'''
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'
,'P','Q','R','S','T','U','V','W','X','Y','Z']
return {i:[] for i in alphabet}
#map1 = blankLetterMap()
#print (map1)
def addLetters(mapping, codeword, plainword):
'''adds potential plaintext letters to a mapping based on a codeword
and a potential translation'''
for i in range(len(codeword)):
if plainword[i] not in mapping[codeword[i]]:
mapping[codeword[i]].append(plainword[i])
def intersectMaps(map1, map2, *maps):
'''finds the intersection in plaintext letters for multiple maps'''
intersectMap = {}
for k in map1:
mappings = [set(map1[k]), set(map2[k])] + [set(m[k]) for m in maps]
letterintersect = set()
for m in mappings:
if m:
if letterintersect:
letterintersect = letterintersect.intersection(m)
else:
letterintersect = m
intersectMap[k] = list(letterintersect)
return intersectMap
def removeSolvedLetters(intersectmap):
'''finds letters in intersected map with only one possible translation and
removes instances of that translation from elsewhere in map'''
mapping = dict(intersectmap)
loopAgain = True
solved = []
while loopAgain:
#print solved
loopAgain = False
solved = []
for k in mapping:
if len(mapping[k]) == 1:
solved.append(mapping[k][0])
for k in mapping:
for i in solved:
if len(mapping[k]) != 1 and i in mapping[k]:
mapping[k].remove(i)
if len(mapping[k]) == 1: #new letter revealed, must cycle through again
loopAgain = True
return mapping
def attemptDecryption(message, mapping):
'''attempts to decrypt a message with a letter mapping. Ambiguous letters/
missing letters replaced with _'''
translation =[]
for i in message:
if i in mapping:
if len(mapping[i]) == 1:
translation.append(mapping[i][0])
else:
translation.append('_')
else:
translation.append(i)
return ''.join(translation)
def cleanUp(message, decryption, mapping):
'''attempts to fill in for _ in a decrypted message and the most current
mapping'''
message = message.upper()
decryption = decryption.upper()
hiddenwords = re.findall('([A-Z]+)',message)
translated = re.findall('([A-Z\_]+)',decryption)
incomplete = {hiddenwords[i]:translated[i] for i in range(len(hiddenwords))
if '_' in translated[i]}
#print(incomplete)
remainingletters = {k:mapping[k] for k in mapping if len(mapping[k]) != 1}
#print (remainingletters)
loopAgain = True
#searches through dictionary for possible words for words containing _
while loopAgain:
loopAgain = False
for w in incomplete:
possiblewords = []
if incomplete[w].count('_') == 1:
#print w
i = incomplete[w].index('_')
possiblewords = [incomplete[w].replace('_',l) for l in remainingletters[w[i]]]
actualwords = [words for words in possiblewords if words in dictionary]
#print (actualwords)
if len(actualwords) == 1:
mapping[w[i]] = [actualwords[0][i]]
# print w
#print incomplete
incomplete.pop(w)
loopAgain = True
break
#print(mapping)
return attemptDecryption(message, mapping)
def masterDecode(message):
'''attempts to decode a simple substitution cipher. Returns decoded string
and mapping for fairly certain letters.'''
message = message.upper()
message = message.replace('_',' ')
words = re.findall('([A-Za-z]+)',message)
#print (words)
patterns = [wordPattern(w) for w in words]
codepatterns = {words[i]:patterns[i] for i in range(len(words))}
#print (codepatterns)
patternmap = {}
for i in patterns:
if i in allPatterns:
patternmap[i] = allPatterns[i]
else:
patternmap[i] = []
#print (patternmap)
wordchoices = {i:patternmap[codepatterns[i]] for i in codepatterns}
#print (wordchoices)
maps = []
for k in wordchoices:
lettermap = blankLetterMap()
for i in wordchoices[k]:
addLetters(lettermap,k,i)
maps.append(lettermap)
#print (maps)
intersection = intersectMaps(*maps)
#print (intersection)
finalmap = removeSolvedLetters(intersection)
#print (finalmap)
decryption = attemptDecryption(message, finalmap)
finaldecryption = cleanUp(message, decryption, finalmap)
#print (finalmap)
while decryption != finaldecryption:
decryption = finaldecryption
finaldecryption = cleanUp(message, finaldecryption, finalmap)
return finaldecryption, finalmap
def main():
message2 = 'Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm'
print(message2)
decoded2 = masterDecode(message2)[0]
print (decoded2)
if __name__ == '__main__':
main()
|
## Sum of zero
def sumzero1(l): ### As two loops so Compexity - O(n square)
for i in range(len(l)-2):
c = 0
for j in range(i+1,len(l)):
if l[j] + l[i] == 0:
print(l[j],l[i])
c += 1
break
if c > 0:
break
def sumzero2(l):
right_pointer = 0
left_pointer = len(l)-1
while right_pointer < left_pointer:
if l[right_pointer] + l[left_pointer] == 0:
print(l[right_pointer], l[left_pointer])
break
elif l[right_pointer] + l[left_pointer] > 0:
left_pointer -= 1
else:
right_pointer += 1
l = [-5,-4,-3,0,2,4,8,10]
### Bubble sort
# in ranadom and reversed - O(n**2)
#in sorted - O(n)
def bubble_sort(l):
for i in range(len(l)-1,0,-1):
swap = 0
for j in range(i):
if l[j] > l[j+1]:
l[j],l[j+1] = l[j+1],l[j]
swap += 1
if swap == 0:
break
return l
sample_list = [10, 50, 50, 100, 100, 100, 20, 30, 40, 20, 30, 90, 40]
print(bubble_sort(sample_list))
"""
Wap a program to remove all the element which are lesser than 5 in same list
"""
l1 = [0,1,2,3,4,5,6,7,8,9,0,1,1,2,3,4]
def remove_list_elements(l):
for j in (l):
if j > 5:
t = l.index(j)
l.remove(j)
l.insert(t,"to_be_deleted")
while "to_be_deleted" in l:
l.remove("to_be_deleted")
print(l)
remove_list_elements(l1)
|
from threading import Thread
from time import time
def factorize(number):
for i in range(1, number + 1):
if number % i == 0:
yield i
class FactorizeThread(Thread):
def __init__(self, number):
super().__init__()
self.number = number
def run(self):
self.factors = list(factorize(self.number))
numbers = [8402868, 2295738, 5938342, 7925426]
# Serial Calculation
start = time()
for number in numbers:
list(factorize(number))
end = time()
print('Took %.3f seconds for serial calculation' % (end - start))
# Threaded Calculation
start = time()
threads = []
for number in numbers:
thread = FactorizeThread(number)
thread.start()
threads.append(thread) # wait for all thread to finish
for thread in threads:
thread.join()
end = time()
print('Took %.3f seconds for threaded calculation' % (end - start)) |
#!/usr/bin/env python
"""mapper.py"""
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# parse the record into fields
fields = line.split(',')
# field 1 is the date while field 8 is Dry Bulb Temp
print('%s,%s' % (fields[1], fields[8]))
|
# PROBLEM
# Print the largest N numbers in an unbounded stream of numbers.
# Example run:
# python largestNumsInStream.py N ../input
import sys
cmdLineArgs = (sys.argv)[1:]
if len(cmdLineArgs) != 2:
sys.exit('Must supply 2 command line arguments. The first specifies the largest N numbers to return in the stream. The second specifies the input file to be read.')
N = int(cmdLineArgs[0])
inputFile = cmdLineArgs[1]
numsToKeep = list()
f = open(inputFile, 'r')
lineNumber = 0
for line in f:
lineNumber = lineNumber + 1
num = int(line.splitlines()[0])
needToSort = False
if lineNumber <= N:
numsToKeep.append(num)
needToSort = True
elif num > numsToKeep[0]:
numsToKeep[0] = num
needToSort = True
if needToSort:
numsToKeep.sort()
print numsToKeep
|
r"""
Only for 2D.
Calculate structure parameters like PDF(g(r)), Cordination Number (CN), Structure Factor S(Q) and .....
"""
import numpy as np
def neigh(i,j,k,dim=3):
nb=[]
list1 = [-1,0,1]
for x in list1:
for y in list1:
if dim==3:
for z in list1:
nb.append('x'+str(i+x)+'y'+str(j+y)+'z'+str(k+z))
else:
nb.append('x'+str(i+x)+'y'+str(j+y)+'z1')
return nb
def pdf(inpf,outf,xs,ys,zs,natom,cut,dr,CN_cut,dim=3):
r"""
Only for 2D
Calculate PDF(g(r)), Cordination Number (CN)
How to calculate the pair correlation function g(r)
This explanation is for three-dimensional data. To calculate g(r), do the following:
1.Pick a value of dr
2.Loop over all values of r that you care about:
3.Consider each particle you have in turn. Count all particles that are a distance between r and r + dr away from the particle you're considering. You can think of this as all particles in a spherical shell surrounding the reference particle. The shell has a thickness dr.
4.Divide your total count by N, the number of reference particles you considered -- probably the total number of particles in your data.
5.Divide this number by 4 pi r^2 dr, the volume of the spherical shell (the surface area 4 pi r^2, multiplied by the small thickness dr). This accounts for the fact that as r gets larger, for trivial reasons you find more particles with the given separation.
6.Divide this by the particle number density. This ensures that g(r)=1 for data with no structure. In other words, if you just had an arbitrarily placed spherical shell of inner radius r and outer radius r+dr, you'd expect to find about rho * V particles inside, where rho is the number density and V is the volume of that shell.
7.In 2D, follow the algorithm as above but divide by 2 pi r dr instead of step #3 above.
Parameters
----------
inpf : Input file name, [String] (format: id, atom_type, xs, ys, zs)
outf : Output file name, [String]
xs : x-scaling, [float]
ys : y-scaling, [float]
zs : z-scaling, [float]
natom : Number of atoms [int]
cut : Cut off distance, Angstrom [float]
dr : Step size, Angstrom [float]
CN_cut : Cutoff for CN, Angstrom [float]
----------
"""
import math
import os
os.makedirs(os.path.dirname(outf), exist_ok=True)
#load data
data=np.loadtxt(inpf,skiprows=1)
#scalling of coordinates i.e xs->x
data[:,2]=data[:,2]*xs
data[:,3]=data[:,3]*ys
data[:,4]=data[:,4]*zs
data[:,2] -= min(data[:,2])
data[:,3] -= min(data[:,3])
data[:,4] -= min(data[:,4])
Lx=max(data[:,2])
Ly=max(data[:,3])
Lz=max(data[:,4])
#Number of cells in all region(x and y)
if Lx>cut:
nx=math.floor(Lx/cut+0.000001)
xbin=Lx/nx
else:
nx=1
xbin=cut
print('Lx < cut')
if Ly>cut:
ny=math.floor(Ly/cut+0.000001)
ybin=Ly/ny
else:
ny=1
ybin=cut
print('Ly < cut')
if Lz>cut:
nz=math.floor(Lz/cut+0.000001)
zbin=Lz/nz
else:
nz=1
zbin=cut
print('Lz < cut')
x_c = 1*data[:,2]
y_c = 1*data[:,3]
z_c = 1*data[:,4]
ai = 1*data[:,0]
m1 = x_c<xbin
m2 = x_c>Lx-xbin
x_c = np.concatenate((x_c,x_c[m1]+Lx,x_c[m2]-Lx))
y_c = np.concatenate((y_c,y_c[m1],y_c[m2]))
z_c = np.concatenate((z_c,z_c[m1],z_c[m2]))
ai = np.concatenate((ai,ai[m1],ai[m2]))
m1 = y_c<ybin
m2 = y_c>Ly-ybin
x_c = np.concatenate((x_c,x_c[m1],x_c[m2]))
y_c = np.concatenate((y_c,y_c[m1]+Ly,y_c[m2]-Ly))
z_c = np.concatenate((z_c,z_c[m1],z_c[m2]))
ai = np.concatenate((ai,ai[m1],ai[m2]))
cuts=cut**2
#size of each cell(x and y)
print('nx,ny,nz',nx,ny,nz)
cells = {}
#insert index of each atom in every cell
for atom_index,x in enumerate(x_c):
kx= math.floor(x/xbin+1)
ky= math.floor(y_c[atom_index]/ybin+1)
kz= math.floor(z_c[atom_index]/zbin+1)
id = 'x'+str(kx)+'y'+str(ky)+'z'+str(kz)
try:
cells[id].append(atom_index)
except:
cells[id] = [atom_index]
#initialise zeros array for every atom (to insert no. of atoms at r distance)
gr=np.zeros((len(x_c),math.floor(cut/dr)+1))
#nested loop over all atoms to calculate CN and PDF
for i in range(nx):
for j in range(ny):
for k in range(nz):
name = 'x'+str(i+1)+'y'+str(j+1)+'z'+str(k+1)
neighbour = neigh(i+1,j+1,k+1,dim)
for atomid in cells[name]:
x0 = x_c[atomid]
y0 = y_c[atomid]
z0 = z_c[atomid]
for nb in neighbour:
x1 = x_c[cells[nb]]
y1 = y_c[cells[nb]]
z1 = z_c[cells[nb]]
r2 = (x1-x0)**2 + (y1-y0)**2 + (z1-z0)**2
val=gr[atomid]
for x in r2:
if x<cuts:
x=math.sqrt(x)
rr=math.floor(x/dr)
val[rr]=val[rr]+1
gr[atomid]=val
mask=[]
gr=gr[:,:-2]
for ind,row in enumerate(gr):
if row[0]==0:
mask.append(ind)
gr=np.delete(gr,mask,0)
if CN_cut<cut:
ind=math.floor(CN_cut/dr)
CN_all=np.sum(gr[:,1:ind],axis=1)
unique, counts = np.unique(CN_all, return_counts=True)
CN_dist=dict(zip(unique, counts))
CN_ar=np.average(CN_all)
bond_freq=np.sum(gr[:,1:ind],axis=0)/len(gr)
bond_length=0
for ind3,i in enumerate(bond_freq):
bond_length=bond_length+(ind3+1.5)*i
bond_length=bond_length*dr/CN_ar
print('Avg. Bond Length : ',bond_length)
print('CN : ',CN_dist)
print('Average CN : ',CN_ar)
else:
print('General cutoff is less than cutoff for cordination no.!!!')
#Average gr for all atom
s=gr[0,1:]*0
for x in gr:
s=x[1:]+s
grn=s/len(gr)
#calculating PDF
V2=Lx*Ly
V3=Lx*Ly*Lz
pdf=[]
rd=[]
tr=[]
for j in range(0,len(grn)):
rd.append((j+1)*dr+dr/2)
if dim==3:
pass
else:
dv=2*3.14*rd[j]*dr
rho = natom/V2
pdf.append((grn[j]/dv)/rho)
tr.append(pdf[j]*rd[j]*4*3.14*rho)
unique=np.asarray(unique)
counts=np.asarray(counts)
#np.savetxt(('grn_'+inpf),np.transpose(np.vstack((rd,grn))),header='r(A) average_atoms',comments='')
np.savetxt((outf+'_pdf'),np.transpose(np.vstack((rd,pdf))),header='r(A) g(r)',comments='')
#np.savetxt((outf+'_tr'),np.transpose(np.vstack((rd,tr))),header='r(A) t(r)',comments='')
np.savetxt((outf+'_CNh'),np.transpose(np.vstack((gr[:,0],CN_all))),header='atom_id CN',comments='')
np.savetxt((outf+'_CN'),np.transpose(np.vstack((unique,counts))),header='#Average Bond Length(A) : '+str(bond_length)+'#Average CN : '+str(CN_ar)+' #CN : '+str(CN_dist),comments='')
np.savetxt((outf+'_gr'),gr)
def SQ(inpf,outf,R,Q,dq,rho,drop=0):
r"""
Only for 2D
Structure Factor S(Q)
Parameters
----------
inpf : Input file name for pdf, [String]
outf : Output file name for SQ, [String]
rho : Density of atoms [String]
Q : Cut off distance, Angstrom [float]
dq : Step size, Angstrom [float]
R : Half of box size, Angstrom [float]
drop : Drop first few points [float]
----------
"""
import math
import os
os.makedirs(os.path.dirname(outf), exist_ok=True)
#rho = eval(rho)
p=np.loadtxt(inpf,skiprows=1)
pdf=p[:,1]
rd=p[:,0]
dr=rd[2]-rd[1]
sq=[]
q=[]
for j in range(0,int(Q/dq)):
sigma=0
q.append(dq*(j+1))
for i in range(0,len(pdf)-1):
pdfv=(pdf[i]+pdf[i+1])/2
rdv=(rd[i]+rd[i+1])/2
F=math.sin(math.pi*rdv/R) / (math.pi*rdv/R)
sig=2*math.pi*rdv * (pdfv-1) * (math.sin(q[j]*rdv)/(q[j]*rdv)) * F * dr
sigma=sigma+sig
sq.append(1+rho*sigma)
mask = 0
for ind,i in enumerate(sq):
if i>drop:
mask = ind
break
q=q[mask:]
sq=sq[mask:]
np.savetxt((outf+'_SQ'),np.transpose(np.vstack((q,sq))),header='Q S(Q)',comments='')
def plot(list1,shift=0,ymaximum='auto'):
r"""
Plot calculated structure parameters PDF(g(r)) and Structure Factor S(Q).
Parameters
----------
inpf : Input file name for pdf/SQ, [String]
----------
"""
import matplotlib.pyplot as plt
try:
for ind,inpf in enumerate(list1):
p=np.loadtxt(inpf ,skiprows=1)
head=np.genfromtxt(inpf,dtype='str',max_rows=1)
plt.plot(p[4:,0],[shift*ind+x for x in p[4:,1]])
if ymaximum=='auto':
pass
else:
plt.ylim(-1,ymaximum)
plt.xlabel(head[0], fontsize=18)
plt.ylabel(head[1], fontsize=18)
plt.savefig(inpf+'.png', dpi=600, facecolor='w', edgecolor='w',
orientation='portrait', papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None)
plt.show()
except:
print('failed!!!')
|
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def adjacent(self, other):
return ((self.x == other.x and abs(self.y - other.y) == 1) or
(self.y == other.y and abs(self.x - other.x) == 1))
def distance_sq(self, other):
return (self.x - other.x)**2 + (self.y - other.y)**2
|
#reads the stored data to input
#also processes the data produced by the RNN and grows the plants
#additionally gets feedback from the Robot and adds that as input
import tensorflow as tf
import numpy as np
import configuration as cf
def parsePflanzvariable(list):
"""Parses list with object pflanzvariable
Turns all the values into integers, as they can be processed by the KI
Additionally normalizes them? This is still all in python
Args: list, in the shape of [plant][timestep]
Returns:
A list in the shape of [plant][timestep][data]
"""
finallist = []
for plant in range(len(list)):
finallist[plant] = []
for timestep in range(len(list[0])):
finallist[plant][timestep] = []
finallist[plant][timestep][0] = list[plant][timestep].nlsg
finallist[plant][timestep][1] = list[plant][timestep].wasserstand
finallist[plant][timestep][2] = list[plant][timestep].lichtrot
finallist[plant][timestep][3] = list[plant][timestep].lichtweiss
finallist[plant][timestep][4] = list[plant][timestep].wachstum
finallist[plant][timestep][5] = list[plant][timestep].fitness
finallist[plant].append([])
finallist.append([])
return finallist
def tensorInputProducer(pass_data, name=None):
"""Iterate on the raw data
Produces a tensor based on raw data
Raw Data should be provided as a list of objects in the form of pflanzvariablen. The structure should be a list [plant][timestep].
Args: raw_data: as a list of pflanzvariables
batch_size: int
num_steps: int, number of unrolls
Returns:
A Tensor in the shape of [plant][timestep]
"""
raw_data = []
plants = len(pass_data)
timesteps = len(pass_data[0])
for plant_num in range(plants):
raw_data.append([])
for time_num in range(timesteps):
raw_data[plant_num].append([])
for i in range(6):
raw_data[plant_num] [time_num].append([])
raw_data[plant_num][time_num][0] = pass_data[plant_num][time_num].nlsg
raw_data[plant_num][time_num][1] = pass_data[plant_num][time_num].wasserstand
raw_data[plant_num][time_num][2] = pass_data[plant_num][time_num].lichtrot
raw_data[plant_num][time_num][3] = pass_data[plant_num][time_num].lichtweiss
raw_data[plant_num][time_num][4] = pass_data[plant_num][time_num].zustand
raw_data[plant_num][time_num][5] = pass_data[plant_num][time_num].wachstum
#batch_num = plants / batch_size
with tf.name_scope(name):
data = tf.convert_to_tensor(raw_data, name="raw_data", dtype=tf.float32);
#This is only possible bc there is a natural limit for timesteps (probs 14 or smth)
num_steps_total = timesteps
#I don't think we really need to reshape the data
#It would probably required, if we had more data (eg plants)
epoch_size = num_steps_total #I aint understanding this yet
#---Not really important just protocol--
assertion = tf.assert_positive(
epoch_size,
message="epoch_size == 0, decrease batch_size or num_steps")
"""
with tf.control_dependencies([assertion]):
epoch_size = tf.identity(epoch_size, name="epoch_size")
num_steps_total = tf.identity(num_steps_total, name="num_steps_total")"""
#---Not really important ends here --
print("Shape of final input tensor: ")
print(data.get_shape());
return data, plants, timesteps
if __name__ == "__main__":
tensorInputProducer(data, 4, 2);
|
'''
给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。
请你返回该链表所表示数字的 十进制值 。
示例 1:
输入:head = [1,0,1]
输出:5
解释:二进制数 (101) 转化为十进制数 (5)
示例 2:
输入:head = [0]
输出:0
示例 3:
输入:head = [1]
输出:1
示例 4:
输入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
输出:18880
示例 5:
输入:head = [0,0]
输出:0
提示:
链表不为空。
链表的结点总数不超过 30。
每个结点的值不是 0 就是 1。
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getDecimalValue(self, head):
"""
:type head: ListNode
:rtype: int
"""
cur = head
ans = 0
while cur:
ans = ans * 2 + cur.val
cur = cur.next
return ans |
'''
给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。
另有一个索引数组 indices,indices[i] = [ri, ci] 中的 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。
你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。
请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。
示例 1:
输入:n = 2, m = 3, indices = [[0,1],[1,1]]
输出:6
解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。
第一次增量操作后得到 [[1,2,1],[0,1,0]]。
最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。
示例 2:
输入:n = 2, m = 2, indices = [[1,1],[0,0]]
输出:0
解释:最后的矩阵是 [[2,2],[2,2]],里面没有奇数。
提示:
1 <= n <= 50
1 <= m <= 50
1 <= indices.length <= 100
0 <= indices[i][0] < n
0 <= indices[i][1] < m
'''
'''
如果用r代表进行了奇数次加法的行总数,用c代表进行了奇数次加法的列总数,那么我们的答案为:
ans = rm + cn - 2rc
我们用字典 row 来统计 indices 中出现的行的次数,用字典 col 来统计 indices 中出现的列的次数,
并计算出两个字典中出现了奇数次的行与列个数 r 与 c。
'''
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
row = {}
col = {}
for x, y in indices:
row[x] = row.get(x, 0) + 1 #统计在 indices 中出现的行与其次数
col[y] = col.get(y, 0) + 1 #统计在 indices 中出现的列与其次数
r = 0
c = 0
r = sum(1 for i in row if row[i] % 2) #统计字典 row 中值为奇数的行总数
c = sum(1 for i in col if col[i] % 2) #统计字典 col 中值为奇数的列总数
return r*m + c*n - 2*r*c |
'''
小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小A 猜对了几次?
输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。
示例 1:
输入:guess = [1,2,3], answer = [1,2,3]
输出:3
解释:小A 每次都猜对了。
示例 2:
输入:guess = [2,2,3], answer = [3,2,1]
输出:1
解释:小A 只猜对了第二次。
限制:
guess的长度 = 3
answer的长度 = 3
guess的元素取值为 {1, 2, 3} 之一。
answer的元素取值为 {1, 2, 3} 之一。
'''
# 1.直接方法:
class Solution(object):
def game(self, guess, answer):
"""
:type guess: List[int]
:type answer: List[int]
:rtype: int
"""
count = 0
for i in range(len(answer)):
if guess[i] == answer[i]:
count = count + 1
else:
pass
return count
# 2.布尔值相加的解法
class Solution:
def game(self, guess: List[int], answer: List[int]) -> int:
return (guess[0] == answer[0]) + (guess[1] == answer[1]) + (guess[2] == answer[2])
# 3.使用sum计算列表元素值相加和的解法
class Solution:
def game(self, guess: List[int], answer: List[int]) -> int:
return sum([guess[i] == answer[i] for i in range(0, len(answer))])
# 4.使用len获取列表长度的解法
class Solution:
def game(self, guess: List[int], answer: List[int]) -> int:
return len([guess[i] == answer[i] for i in range(0, len(answer))])
# 5.使用count计算列表元素值为True数量的解法
class Solution:
def game(self, guess: List[int], answer: List[int]) -> int:
return [guess[i] == answer[i] for i in range(0, len(answer))].count(True)
|
'''
自除数 是指可以被它包含的每一位数除尽的数。
例如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。
还有,自除数不允许包含 0 。
给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。
示例 1:
输入:
上边界left = 1, 下边界right = 22
输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
注意:
每个输入参数的边界满足 1 <= left <= right <= 10000。
'''
class Solution(object):
def selfDividingNumbers(self, left, right):
def self_dividing(n):
for d in str(n):
if d == '0' or n % int(d) > 0:
return False
return True
"""
Alternate implementation of self_dividing:
def self_dividing(n):
x = n
while x > 0:
x, d = divmod(x, 10)
if d == 0 or n % d > 0:
return False
return True
"""
ans = []
for n in range(left, right + 1):
if self_dividing(n):
ans.append(n)
return ans #Equals filter(self_dividing, range(left, right+1))
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
ans = []
for num in range(left,right + 1):
copy = num
while copy > 0:
copy , div = divmod(copy,10)
if div == 0 or num % div != 0: break
else: ans.append(num)
return ans |
def selectionSort(nums):
for i in range(len(nums) - 1): # 遍历len(nums)-1次
minIndex = i
for j in range(i + 1, len(nums)): # 更新最小值索引
if nums[j] < nums[minIndex]:
minIndex = j
nums[i], nums[minIndex] = nums[minIndex], nums[i] # 把最小数交换到前
return nums |
'''
给你两个长度相同的整数数组 target 和 arr 。
每一步中,你可以选择 arr 的任意 非空子数组 并将它翻转。你可以执行此过程任意次。
如果你能让 arr 变得与 target 相同,返回 True;否则,返回 False 。
示例 1:
输入:target = [1,2,3,4], arr = [2,4,1,3]
输出:true
解释:你可以按照如下步骤使 arr 变成 target:
1- 翻转子数组 [2,4,1] ,arr 变成 [1,4,2,3]
2- 翻转子数组 [4,2] ,arr 变成 [1,2,4,3]
3- 翻转子数组 [4,3] ,arr 变成 [1,2,3,4]
上述方法并不是唯一的,还存在多种将 arr 变成 target 的方法。
示例 2:
输入:target = [7], arr = [7]
输出:true
解释:arr 不需要做任何翻转已经与 target 相等。
示例 3:
输入:target = [1,12], arr = [12,1]
输出:true
示例 4:
输入:target = [3,7,9], arr = [3,7,11]
输出:false
解释:arr 没有数字 9 ,所以无论如何也无法变成 target 。
示例 5:
输入:target = [1,1,1,1,1], arr = [1,1,1,1,1]
输出:true
提示:
target.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
'''
# 排序解题
class Solution(object):
def canBeEqual(self, target, arr):
"""
:type target: List[int]
:type arr: List[int]
:rtype: bool
"""
target = sorted(target)
arr = sorted(arr)
return target == arr
# 哈希表解题
class Solution(object):
def canBeEqual(self, target, arr):
"""
:type target: List[int]
:type arr: List[int]
:rtype: bool
"""
dict = {}
for n in target:
if n not in dict:
dict[n] = 1
else:
dict[n] += 1
for n in arr:
if n not in dict or dict[n] <= 0:
return False
else:
dict[n] -= 1
return True |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
S = list(input())
p = 0
g = 0
w = 0
for s in S:
# 出せるのならpを出す
t = 'p' if p < g else 'g'
p += 1 if t == 'p' else 0
g += 1 if t == 'g' else 0
# あいこでない
if s != t:
# 負け確
if s == 'p':
w -= 1
# 勝ち確
elif s == 'g':
w += 1
print(w)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
A, B = map(int, input().split())
aa = A
bb = B
while aa != bb:
if aa < bb:
aa += A
else:
bb += B
print(aa)
|
"""
CISC 352: Assignment 3
April 2, 2018
Conway's Game of Life algorithm is determined by its initial sate, requiring no further input.
It is represented on a grid of cells that are alive (coloured), or dead(white). Every cell interacts
with its neighbours, and changes state depending on four rules:
1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
2. Any live cell with two or three live neighbours lives on to the next generation.
3. Any live cell with more than three live neighbours dies, as if by overpopulation.
4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
"""
#tkinter - a python graphics library
from tkinter import *
root = Tk()
"""Initializing graphics settings"""
root.title("CISC 352 Assignment 3 - Conway's Game of Life")
frame = Frame(root, width=1000, height=1000)
frame.pack()
canvas = Canvas(frame, width=1000, height=1000)
canvas.pack()
#global variable that represents each generation or cycle of life / death
generation = 0
#cell class in which the status of the cell (dead or alive)is tracked.
class Cell:
def __init__(self, x, y, i, j):
#current cell
self.isAlive = False
#neighbouring ce;;
self.nextStatus = None
self.pos_screen = (x, y)
self.pos_matrix = (i, j)
def __str__(self):
return str(self.isAlive)
def __repr__(self):
return str(self.isAlive)
def switchStatus(self):
self.isAlive = not self.isAlive
"""
The create graph function creates the board in which the game will exist.
All squares will start off as white (dead).
"""
def create_graph():
x = 10
y = 10
global grid #variable to store the Cell objects
global rectangles # Variable to store rectangles
rectangles= []
grid = []
#number of columns - the width of the input
for i in range(len(graph[0])):
grid.append([])
rectangles.append([])
#number of rows - the length of the input (could have used same value as above bc it's square)
for j in range(len(graph)):
rect = canvas.create_rectangle(x, y, x+10, y+10, fill="white")
rectangles[i].append(rect)
grid[i].append(Cell(x, y, i, j))
#moving to next column
x += 10
#moving the next row
x = 10
y += 10
"""
The setInput function loops through the input matrix of 1s and 0s
and marks the visual grid with a blue square if it is alive (1) or
white square if it is dead (0)
"""
def setInput():
global graph
for i in range(len(graph)):
for j in range(len(graph[i])):
#if the input at a certain locaiton is alive
if graph[i][j] == '1':
if i == -1 or j == -1: #index cannot be less than 1
raise IndexError
#if cell is not alive, set it to blue
if not grid[i][j].isAlive:
canvas.itemconfig(rectangles[i][j], fill="blue")
#swtich the status of the cell from dead to alive
grid[i][j].switchStatus()
return
"""
he colourSquares function loops through the grid defined by the cell
and colours the alive squares blue where neccessary and the dead ones white
"""
def colourSquares():
for i in grid:
for j in i:
#if neighour is not the same value as the current cell
if j.nextStatus != j.isAlive:
x, y = j.pos_matrix
#if neighbour is alive
if j.nextStatus:
canvas.itemconfig(rectangles[x][y], fill="blue")
else:
canvas.itemconfig(rectangles[x][y], fill="white")
j.switchStatus()
"""
The changeStatus function takes in the cell, and if the cell's status changes
in the next gen, return True. If it doesn't, return false.
"""
def changeStatus(cell):
numberAlive = 0
#get the position matrix of the cell
x, y = cell.pos_matrix
#checking left and right
for i in (x-1, x, x+1):
#checking up and down
for j in (y-1, y, y+1):
if i == x and j == y:
continue
if i == -1 or j == -1:
continue
try:
if grid[i][j].isAlive:
numberAlive += 1
except IndexError:
pass
if cell.isAlive:
return not(numberAlive == 2 or numberAlive == 3)
else:
return numberAlive == 3
"""
The startSim function begins the simulation and stops when the maximum amount
of generations given by the m value has been reached.
"""
def startSim():
global m
global generation
#loop through grid changing from alive to dead if neccessary
#by calling change status
for i in grid:
for j in i:
if changeStatus(j):
j.nextStatus = not j.isAlive
else:
j.nextStatus = j.isAlive
colourSquares()
global begin_id
#if the specified generations amount of generations have not yet been reached
if generation < int(m):
generation +=1
print("Generation", generation)
#recursive call to next generation. 300 is the amount of miliseconds between each generation
begin_id = root.after(300, startSim)
else:
endSim()
"""
The endSim funciton is called from startSim and calls root to
stop the simulation.
"""
def endSim():
root.after_cancel(begin_id)
"""
The readFile funciton finds the input file from a give folder, assigns the variable
m (amount of generations) from the first line, and creates a global variable called
graph which is a 2D list representing rows and columns.
"""
def readFile():
with open("C:\\Users\\taylo\\Desktop\\352Assignment3\\inLife.txt") as f:
content = f.readlines()
#strip off the line breaks
content = [x.strip() for x in content]
global m
global graph
#first line
m = content[0]
#all but the first line
graph = content[1:]
return
"""
The main file is the starting point of the program and calls other functions
in the neccessary order.
"""
def main():
readFile()
create_graph()
setInput()
startSim()
#continue to show the visual interface
root.mainloop()
main()
|
"""
Nora Mohamed
~*2015 FEB*~
Goes to BuzzFeed and puts article titles into .txt
"""
from pattern.web import *
def get_buzzfeed_titles(url):
""" Gets buzzfeed article titles and puts them into a text file or string
url: List of buzzfeed URLs that
return: string of buzzfeed article titles
"""
HTML = URL(url).download()
index = 0
title = ""
while index != -1:
index = HTML.find("rel:gt_act='post/title' >\n")
if index == -1:
break
HTML = HTML[index + 34:]
title += HTML[0:HTML.find(" </a>")]
return title
titles = ""
buzzfeed = ["http://www.buzzfeed.com/buzz", "http://www.buzzfeed.com/news",
"http://www.buzzfeed.com/entertainment", "http://www.buzzfeed.com/quizzes"]
for page in buzzfeed:
titles += get_buzzfeed_titles(page)
text_file = open("buzzfeed_titles.txt", "w")
text_file.write(titles)
text_file.close()
#use http://www.buzzfeed.com/archive/2014/1/2 !!! |
from sklearn.feature_selection import SelectKBest, chi2
import pandas as pd
# function that selects k best features using chi2 algorithm from X_features DataFrame provided as the parameter and returns another DataFrame which contains all the samples with only those selected features. DataFrame preserves feature names labels.
# Params: DataFrame, DataFrame, int
# Returns: DataFrame
def select_k_best_features(X_features, Y_diagnosis, k_best_features):
# create and fit selector
select_k_best_classifier = SelectKBest(score_func=chi2, k=k_best_features)
select_k_best_classifier.fit(X_features, Y_diagnosis)
# get columns to keep and create new DataFrame with those only
new_features = select_k_best_classifier.get_support(indices=True)
X_best_features = X_features.iloc[:, new_features]
return X_best_features
# function that is modification of the above function. selects k best features using chi2 algorithm from X_train (needs Y_train to do it as well). X_test is provided to this function only because this DataFrame needs to be stripped to the same features as the one selected from training set. test data ARE NOT USED for feature selection algorithm. the result of this algoritm is applied on this data set for compability with training data. int represents number of best features to select. function returns two DataFrames which are stripped train and test DataFrames respectively.
# Params: DataFrame, DataFrame, DataFrame, int
# Returns: (DataFrame, DataFrame)
def select_k_best_features_train_and_test(X_train, Y_train, X_test, k_best_features):
# create and fit selector
select_k_best_classifier = SelectKBest(score_func=chi2, k=k_best_features)
select_k_best_classifier.fit(X_train, Y_train)
# get columns to keep and create new DataFrame with those only
new_features = select_k_best_classifier.get_support(indices=True)
X_train_best_features = X_train.iloc[:, new_features]
# create second DataFrame from test set which contains only selected features
X_test_best_features = X_test.iloc[:, new_features]
return (X_train_best_features, X_test_best_features)
# function that creates feture ranking using chi2 algorithm. takes set of all samples that are used for ranking creation. returns DataFrame which contains the ranking in the form of 3 colums - feature name, chi2 value and p value. it is then sorted from the best to the worst features in the given set.
# Params: DataFrame, DataFrame
# Returns: DataFrame
def create_feature_ranking(X_features, Y_diagnosis):
(chi, pval) = chi2(X_features, Y_diagnosis)
result = pd.DataFrame(X_features.columns, columns=['Feature name'])
result["chi"] = chi
result["pval"] = pval
result.sort_values(by=['chi'], ascending=False, inplace=True)
return result
|
#!/usr/bin/env python
#coding:utf-8
from sets import Set
#grid graph
class Graph:
def __init__(self,xlen,ylen):
self.all_nodes = Set()
for x in range(xlen):
for y in range(ylen):
self.all_nodes.add((x,y))
self.walls([2,3,4,5,6])
def edges(self):
pass
def cost(self,start_node,end_node):
if(start_node[0]>2 and start_node[0]<6
and start_node[1]>2 and start_node[1]<6):
return 40
else:
return 1
# return self.edges(start_node,end_node)
#greedy cost
def gcost(self,node0,node1):
return abs(node0[0]-node1[0]) + abs(node0[1]-node1[1])
def neighbors(self,node):
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
result = []
for dir in dirs:
neighbor = (node[0] + dir[0], node[1] + dir[1])
if neighbor in self.all_nodes:
result.append(neighbor)
return result
def walls(self,indexs):
for x in indexs:
self.all_nodes.remove((x,4))
|
from battle import *
import pprint
import tree
# Create a knight
sir_cumstance = generateKnightStats()
# Tell us about him
print "Sir Cumstance is ", statsToString(sir_cumstance)
# Have an adventure
print "he was exploring the glade and meet an evil wizard, who atacked..."
# With a battle
# Python note: The * notation is unpacking e.g.
# battle(*sir_cumstance) = battle(sir_cumstance[0], sir_cumstance[1], sir_cumstance[2], sir_cumstance[3])
result = battle(*sir_cumstance)
print "the result is..."
print battleResultToText(result)
# Have 100 battles to collect some data to learn from
knightStats, battleResults = haveSomeBattles(1000)
i = 4
print "One of the battles (number %s) was %s resulting in %s" %(i, statsToString(knightStats[i]), battleResultToText(battleResults[i]))
print "%s%% of battles won" % (100*sum(battleResults)/len(battleResults))
# Create a decision tree by learning from the battle data
battleTree = tree.makeTree(knightStats, battleResults, 4)
# We can experiment with different tree depths, this can lead to over fitting the data,
# especially if we have a small data set.
# battleTree = tree.makeTree(knightStats, battleResults, 100)
# Remind our self's which index is which skill
print "strength (index 0), speed (index 1), weapon level (index 2), spells (index 3)"
# Print out tree
pprint.pprint(battleTree)
# Test the accuracy of out tree by having lots of battles
correct = []
for i in xrange(1000):
s = generateKnightStats()
p = tree.applyTree(battleTree, s)
r = battle(*s)
correct.append(1-abs(r - p))
#print "Given: " + (statsToString(s)) + "\nI predict: " + battleResultToText(p) + "\nResult is: " + battleResultToText(r) + "\n"
print "We predicted %s out of %s correct, that's %s%%" % (sum(correct), len(correct), ((sum(correct)*100.0)/len(correct)))
# If your not careful you can make the mistake of testing against your learning data which won't give you representative results!
# Try upping the tree depth and lowering the number of training examples to see the effect of over fitting.
correct = []
for s,r in zip(knightStats, battleResults):
p = tree.applyTree(battleTree, s)
correct.append(1-abs(r - p))
print "`testting` against my training data I got %s out of %s correct, that's %s%%." % (sum(correct), len(correct), ((sum(correct)*100.0)/len(correct)))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Estudiante:
def __init__(self, nombre, carnet, anyoNacimiento):
self.nombre = nombre
self.carnet = carnet
self.anyoNacimiento = anyoNacimiento
def saludar(self):
print ("Hola me llamo", self.nombre)
print ("Mi carné es: " + self.carnet)
def calcularEdad(self):
edad = 2019 - self.anyoNacimiento
return edad
#Instancias
estudiante1 = Estudiante("Karina", "B98765", 1997)
estudiante1.saludar()
print("La edad es: %d"%(estudiante1.calcularEdad()))
print()
estudiante1 = Estudiante("David", "B78909", 1994)
estudiante1.saludar()
print("La edad es: %d"%(estudiante1.calcularEdad())) |
# Python program to print all smaller than or equal to n using Sieve of Eratosthenes
from os import system, name
from time import sleep
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
#_ = call('clear' if os.name == 'posix' else 'cls')
def SieveOfErastothenes(n):
# create a boolean array "prime[0..n" and initialize all entries it as true
prime = [True for i in range (n+1)]
p = 2
while(p*p <= n):
if prime[p] is True:
for i in range(p*2, n+1, p):
prime[i] = False
p += 1
prime[0]=False
prime[1]=False
# print all prime numbers
for p in range(n+1):
if prime[p]:
print (p)
# main
if __name__ == '__main__':
clear()
sleep(2)
n = 50
print ("Following are the prime numbers smaller")
print ("Than or equal to " + str(n))
SieveOfErastothenes(n)
|
### Programa de Anagrama en python
def is_anagram(str1, str2):
list_str1 = list(str1)
list_str1.sort()
list_str2 = list(str2)
list_str2.sort()
return (list_str1 == list_str2)
def contador (str):
"""
La funcion contador lanza el conteo de la cadena a introducir
"""
cont = 0
for letra in str:
cont = cont + 1
return (cont)
print("La palabra introducida tiene " + str(contador('paso')) + " letras")
print(is_anagram('paso','sopa'))
print(is_anagram('top','pat')) |
# Python program to implement Binary Search
def binarySearch(A, target):
start,end,pivot,i = 0,len(A),0,0
target = int(target)
while start <= end:
pivot = int(start + (end - start) / 2)
if A[pivot] == target:
return pivot
if A[pivot] < target:
start = pivot + 1
if A[pivot] > target:
end = pivot - 1
return -1
if __name__ == '__main__':
arr = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
arr.sort()
print(arr)
val = input()
src = binarySearch(arr,val)
if src != -1:
print("The element ", val, " is located at index ",src)
else:
print("Element not found")
|
class Islas:
def __init__(self,arr):
self.arr = arr
def setArr(self,arr):
self.arr = arr
def getArr(self):
return self.arr
def numIslas(self,arr):
total = 0
nRows = len(arr)
nCols = len(arr[0])
visited = [[False for j in range(nCols)]for i in range(nRows)]
for i in range(nRows):
for j in range(nCols):
if arr[i][j] ==1 and visited[i][j] == False:
self.__findIslas__(arr,visited,i,j)
total +=1
return total
def __findIslas__(self,arr,visited,a,b):
if arr[a][b]==1 and visited[a][b] == False:
visited[a][b] = True
'''
#south
if a < (len(arr) - 1):
self.__findIslas__(arr,visited,a+1,b)
#east
if b < (len(arr) - 1):
self.__findIslas__(arr,visited,a,b+1)
#north
if a >= 1:
self.__findIslas__(arr,visited,a-1,b)
#west
if b >= 1:
self.__findIslas__(arr,visited,a,b-1)
'''
if a != 0:
self.__findIslas__(arr,visited,a-1,b)
if a != len(arr) - 1:
self.__findIslas__(arr,visited,a+1,b)
if b != 0:
self.__findIslas__(arr,visited,a,b-1)
if b != len(arr[0]) - 1:
self.__findIslas__(arr,visited,a,b+1)
A = [[0,1,1,0,1],
[0,1,0,0,1],
[1,0,1,1,1]]
miIslita = Islas(A)
print(miIslita.numIslas(miIslita.getArr()))
|
import matplotlib.pyplot as plt
friends = [ 70, 65, 72, 63, 71, 64, 60, 64, 67]
minutes = [175, 170, 205, 120, 220, 130, 105, 145, 190]
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
plt.scatter(friends, minutes)
for label, freind_count, minute_count in zip(labels, friends, minutes):
plt.annotate(
label,
xy=(freind_count, minute_count),
xytext = (5,5),
textcoords= 'offset points'
)
plt.title("Daily Minutes vs. Number of Friends")
plt.xlabel("# of friends")
plt.ylabel("daily minutes spent on the site")
plt.show() |
p=0
c=0
n=0
for x in range(0,10):
x=int(input("Digite Un Numero"))
if x==0:
c=c+1
else:
if x<0:
p= p+1
else:
n= n+1
print("La Cantidad Dee Ceros Es: ",c)
print("La Cantidad De positivos es: ", p)
print("La Cantidad De negativos es: ", n)
|
#Generate two csv files from a list of Illinois legislators, one containing legislators under 45 and the other containing legislators with both a Twitter and YouTube account on file.
import csv
from datetime import date, datetime
#define starting data set
legislator_data = "legislators.csv"
#define files to write filtered data to
filtered_age = "legislators_under_45.csv"
filtered_SM = "legislators_on_social_media.csv"
#define age threshold and cutoff
age_threshold = 45
age_cutoff = date.today()
def calculate_age(birthdate, cutoff):
try:
#parse ISO 8601 time to datetime format
b = datetime.strptime(birthdate, "%Y-%m-%d")
#compare years directly and subtract one if birthday hasn't happened yet this year
return cutoff.year - b.year - ((cutoff.month, cutoff.day) < (b.month, b.day))
except ValueError:
print("Was not able to calculate an age for the birthdate input " + birthdate + ". This may be an incorrectly formatted date.")
with open(legislator_data, "rb") as fin, open(filtered_age, "wb") as fout1, open(filtered_SM, "wb") as fout2:
#read source file and instantiate two csv files to write to
reader = csv.DictReader(fin)
writer_age = csv.DictWriter(fout1, reader.fieldnames)
writer_SM = csv.DictWriter(fout2, reader.fieldnames)
#write headers into both new files
writer_age.writeheader()
writer_SM.writeheader()
for row in reader:
#filter for age threshold
if ((calculate_age(row["birthdate"], age_cutoff) < age_threshold)):
writer_age.writerow(row)
#filter for social media presence
if (row['twitter_id'] and row["youtube_url"]):
writer_SM.writerow(row)
print("Filtering complete!") |
# greatest_number_divides_both
def main():
pass
n=list(map(int,input().split()))
list_1=[]
list_2=[]
list_3=[]
for num in range(1,n[0]+1):
if(n[0]%num==0):
list_1.append(num)
for num2 in range(1,n[1]+1):
if(n[1]%num2==0):
list_2.append(num2)
for i in list_1:
for j in list_2:
if(i==j):
list_3.append(i)
print(max(list_3))
if __name__ == '__main__':
main()
|
puzzle = [
[0, 0, 0, 1, 0, 5, 0, 6, 8],
[0, 0, 0, 0, 0, 0, 7, 0, 0],
[9, 0, 1, 0, 0, 0, 0, 3, 0],
[0, 0, 7, 0, 2, 6, 0, 0, 0],
[5, 0, 0, 0, 0, 0, 0, 0, 3],
[0, 0, 0, 8, 7, 0, 4, 0, 0],
[0, 3, 0, 0, 0, 0, 8, 0, 5],
[1, 0, 5, 0, 0, 0, 0, 0, 0],
[7, 9, 0, 4, 0, 1, 0, 0, 0]
]
print(f'{int(str(puzzle).count("0"))/81:.3f}')
# This code solves all sudokus that does NOT require guessing.
green = True
while green:
green = False
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9] # possible numbers
# to list possible number for each 0 in the each rows into the dictioanary row_possible.
row_possible = {}
for x in range(9):
for y in range(9):
sack = []
if puzzle[x][y] == 0:
for i in nums:
if i not in puzzle[x]:
sack.append(i)
key = 'p{}{}'.format(x, y)
row_possible[key] = sack
transpose_puzzle = [] # transpose the puzzle to go through the columns
row = [] # in the original puzzle.
for x in range(9):
row = [puzzle[i][x] for i in range(9)]
transpose_puzzle.append(row)
# to list possible number for each 0 in the each columns into the dictionary column_possible.
column_possible = {}
for x in range(9):
for y in range(9):
sack = []
if transpose_puzzle[x][y] == 0:
for i in nums:
if i not in transpose_puzzle[x]:
sack.append(i)
key = 'p{}{}'.format(y, x)
column_possible[key] = sack
# to turn grids into rows to be able to work on them and label cells with the same key
# to compare them with row_possible and column_possible dictionaries.
grid = []
grid_index = []
for x in [[0,1,2], [3,4,5], [6,7,8]]:
for y in [[0,1,2],[3,4,5], [6,7,8]]:
row_1 = []
row_2 = []
for z in x:
for t in y:
row_1.append(puzzle[z][t])
row_2.append([z, t])
grid.append(row_1)
grid_index.append(row_2)
# to list possible numbers for each 0 in the each grid into the dictionary grid_possible.
grid_possible = {}
for x in range(9):
for y in range(9):
sack = []
if grid[x][y] == 0:
for i in nums:
if i not in grid[x]:
sack.append(i)
key = 'p{}{}'.format(grid_index[x][y][0],grid_index[x][y][1])
grid_possible[key] = sack
# the code below compares row possible values, column possible values, and grid possible values
# and drops unqualified values for each 0 in the original puzzle.
unique = {}
for key in column_possible.keys():
all_vals = column_possible[key] + row_possible[key] + grid_possible[key]
unique_vals = []
for i in all_vals:
if all_vals.count(i) == 3 and i not in unique_vals:
unique_vals.append(i)
if len(unique_vals) == 1:
puzzle[int(key[1])][int(key[2])] = unique_vals[0]
green = True
unique[key] = unique_vals
if unique == {}: # when all possible values are distributed this code breaks the loop.
break
if str(puzzle).count('0') == 0:
for row in puzzle:
print(row)
else: print('Puzzle requires guessing!') |
#import functions
from turtle import *
import random
#define varable + pick a color and asign it to said variable
COL = random.choice(['red','orange','yellow','green','blue','magenta'])
COL2 = random.choice(['red','orange','yellow','green','blue','magenta'])
#set turtle color + window background color
color(COL)
bgcolor(COL2)
#mainloop
for i in range (10):
for i in range (2):
forward(100)
right(60)
forward(100)
right(120)
right(36)
|
sentence1 = "Hi all, my name is Tom...I am originally from Australia."
sentence2 = "I need to work very hard to learn more about algorithms in Python!"
def sentence(sent):
for p in "!?',;.":
sent = sent.replace(p, '')
words = sent.split()
print(words)
return round(sum(len(word) for word in words) / len(words), 2)
print(sentence(sentence1))
print(sentence(sentence2))
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('ML.csv')
X = dataset.iloc[:, 0:13].values
y = dataset.iloc[:, 12].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
input_test=X_test
X_test=X_test[:,3:12]
X_train=X_train[:,3:12]
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
X_test[:, 1] = labelencoder_X_1.fit_transform(X_test[:, 1])
labelencoder_X_2 = LabelEncoder()
X_test[:, 2] = labelencoder_X_2.fit_transform(X_test[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X_test = onehotencoder.fit_transform(X_test).toarray()
X_test = X_test[:, 1:]
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_11 = LabelEncoder()
X_train[:, 1] = labelencoder_X_11.fit_transform(X_train[:, 1])
labelencoder_X_12 = LabelEncoder()
X_train[:, 2] = labelencoder_X_12.fit_transform(X_train[:, 2])
onehotencoder1 = OneHotEncoder(categorical_features = [1])
X_train = onehotencoder1.fit_transform(X_train).toarray()
X_train = X_train[:, 1:]
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
import keras
from keras.models import Sequential
from keras.layers import Dense
classifier = Sequential()
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 10))
classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 10)
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
leen=len(X_test)
for i in range(leen):
if(y_pred[i]>0.5):
input_test[i][12]=1
else:
input_test[i][12]=2
import csv
myFile = open('ML-output.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(input_test)
result=pd.read_csv('ML-output.csv')
|
if Player.health <= 0:
print('You have lost, please restart and try again.')
else:
action = input('Please enter your next action:')
if Student.grade >= 90:
if Student.grade <= 94:
Student.letterGrade = "A-"
elif Student.grade <=97:
Student.letterGrade = "A"
else:
Student.letterGrade = "A+"
if Student.grade >= 70:
if Student.grade <= 74:
Student.letterGrade = "C-"
if Student.average <=75:
if Student.warningCount >= 2:
print(Student.name + ' requires a 3rd strike warning')
elif Student.grade <=77:
Student.letterGrade = "C"
else:
Student.letterGrade = "C+"
|
#python 2.7.14 -- urllib2
import urllib2
url = "http://www.baidu.com"
# urllib.request.urlopen(url).
data = urllib2.urlopen(url).read()
data = data.decode('UTF-8')
print(data)
# urlopen(url, data, timeout)
response = urllib2.urlopen("http://www.baidu.com")
data2=response.read().decode('UTF-8')
request = urllib2.Request("http://www.baidu.com")
response = urllib2.urlopen(request)
data3=response.read().decode('UTF-8')
# false false
print ('result:',data==data2,data==data3)
print len(data),len(data2),len(data3)
#urllib ,urllib2
import urllib
import urllib2
#等效于如下
values = {}
values['username'] = "1016903103@qq.com"
values['password'] = "XXXX"
#等效于如上
values = {"username": "1016903103@qq.com", "password": "XXXX"}
data = urllib.urlencode(values)
url = "https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn"
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
print response.read()
#以上是Post,这里是Get
values = {"username": "1016903103@qq.com", "password": "XXXX"}
data = urllib.urlencode(values)
geturl = "http://passport.csdn.net/account/login" + "?"+data
|
def rotate_word(s, n):
word = ''
for letter in s:
u = ord(letter) + n
s = chr(u)
word += s
return word
print rotate_word('cheer', 7) |
with open("input/day1", "r") as f:
frequency_changes = [int(line.strip()) for line in f]
all_frequencies = set()
current_frequency = 0
repeated_frequency = None
while repeated_frequency is None:
for frequency in frequency_changes:
current_frequency += frequency
if current_frequency in all_frequencies:
repeated_frequency = current_frequency
break
else:
all_frequencies.add(current_frequency)
print(repeated_frequency) |
def main():
print ("PYTHON GUESSING GAME")
main()
answer = "dog"
guess = ""
while not guess == answer:
print("I'm thinking of an animal")
guess = input("What animal am I thinking about?")
guess = guess.lower()
if guess == answer:
choice = input("Do you like the animal? Y for yes and N for no.")
if choice == "Y":
print ("I love them too.")
if choice == "N":
print("I don't like them either.")
break
elif guess[0] == "q":
break
else:
print ("Wrong! Try Again")
|
i = 1
while(True): # Here i made a normal WHile loop which is always TRUE which means its never ending
i = i+1 # Here i made a change to the variable
if (i > 10):
print(i)
break # This break staement means Forget about the loop and continue the other code
print("Lol hia bhai lol hai")
# This means that forget the code after this in the while loop and start the while loop again.
continue
print("Hello world")
print("This statement is not in the while loop and is being executed after breaak")
|
# While loop is easy!!!
# First I will make a variable
i = 1
# then i will satrt a while loop
while (i < 45): # This is how we make a while loop it's super easy. Youu have to type a condition in the brackets
print(i) # then the code which will execute whenever the condition is true
i = i+1
|
# Stone Paper Scissors
# Have to play 10 times
import random
i = 0
loose = 0
won = 0
print("********Play Stone Paper Scissors********")
while i != 11:
list1 = ["Stone", "Paper", "scissors"]
Options = random.choice(list1)
a = input("What do u choose(s=Stone, p=paper, c=scissors):\n")
if a == "s":# If u choose Stone
if Options == "Stone":
print("its a tie try again!")
# print(won, loose)
elif Options == "Paper":
print("Sad U lost")
i+=1
loose+=1
# print(won, loose)
elif Options == "scissors":
print("U won!!!")
won+=1
print(won)
i+=1
# print(won, loose)
elif a == "p": # If u choose paper
if Options == "Stone":
print("U won!!!")
i+=1
won+1
print(won)
# print(won, loose)
elif Options == "Paper":
print("its a tie try again!")
# print(won, loose)
elif Options == "scissors":
print("Sad U lost")
loose+=1
i+=1
# print(won, loose)
elif a == "c": # if u choose scissors
if Options == "Stone":
print("Sad U lost")
i+=1
loose+=1
# print(won, loose)
elif Options == "Paper":
print("U won!!!")
i+=1
won+=1
print(won)
# print(won, loose)
elif Options == "scissors":
print("its a tie try again!")
# print(won, loose)
if won>loose:
print("Congrats u won!!!!")
elif won == loose:
print("Its a tieee!!!")
else:
print("U lost u looser!!")
|
""" this is the code for a chat bot used for hospitals.
this chatbot has two services namely doctor appointment booking and medical tests services at home.
this chatbot greets the user according to the time of usage.
It also welcomes the user with their name.
Then it displays the services it can provide and asks the user to select one of them.
It collects the data required from the user.
It thanks the user for using its service. """
import random
from datetime import datetime
def greeting():
"""This method greets the user according to the time."""
time = datetime.now()
greetings = "Good Morning,"
if 12 < time.hour < 17:
greetings ="Good Afternoon,"
elif 17 <= time.hour < 22:
greetings ="Good Evening,"
elif 22 <= time.hour < 24:
greetings ="Hi,It's late,"
intro ="Welcome to ******* Hospitals.I am Alex an reception bot I am here to help you with your doctor appointments,medical needs.May I know your name?"
print (greetings, intro)
greets = ["Have a warm welcome.", "It's nice to meet you."]
def welcome(name):
""" This method welcomes the user with their name."""
responses = ["Have a warm welcome!","It's nice to meet you","It's good to meet you"]
print(random.choice(responses),name)
def doctorAppointment():
""" collects all the details of the patient which are needed for the doctor appointment."""
print("May I know the patient's details")
N=input("Name of the patient:")
rightAge=False
while(not(rightAge)):
try:
a=int(input("Age of the patient:"))
if(not(0<=a<=100)):
print("Invalid age")
else:
rightAge=True
except:
print("Invalid information given")
complaint=input("What is your health problem?\n")
rightNumb=False
while(not(rightNumb)):
try:
numb=int(input("Enter your contact number:"))
rightNumb=True
except:
print("Invalid information given")
rightTime=False
while(not(rightTime)):
try:
time = int(input("Select your time slot for the appointment: [1-3]\n 1. 9:00 am to 12:00 pm \n 2. 1:00 pm to 5:00 pm\n 3. 6:00 pm to 10:00 pm\n"))
if(1<=time<=3):
rightTime=True
else:
print("Only options 1,2,3 are available")
except:
print("Only given options should be selected")
print("Your appointment has been recorded after verification you will be contacted.Thank you for using our services.Have a nice day :).")
print("Do you need my assistance with anything else ?")
def medicalTest():
try:
n=int(input("We provide the following tests [1-4]: \n 1. Blood Test \n 2. Diabetes Test\n 3. Thyroid Test\n 4. Corona test\n Which test do you need?\n"))
if(1<=n<=4):
pName =input("Enter the name of patient: ")
address=input("Please Enter the address to get your test samples: \n")
rightNumb=False
while(not(rightNumb)):
try:
numb=int(input("Enter your contact number:"))
rightNumb=True
except:
print("Invalid information given")
print("You will receive a call from us soon.We will reach you as soon as possible.\nThank you for using our service")
else:
print("Select one from given tests.Sorry, if we couldn't provide the test you needed")
except:
print("Please select from given tests.Sorry, if we couldn't provide the test you needed")
def display_options():
n=0
while(n!=3):
try:
n=int(input("How can I help you? \n Choose one of the options [1-3] \n 1. Looking a doctor appointment ? \n 2. Medical tests\n 3.End the conversation\n"))
if n== 1:
doctorAppointment()
elif n==2:
medicalTest()
elif n==3:
print("Thank you for using our services.Have a pleasent day.")
break
else:
print("Only integers 1,2,3 are allowed!")
except Exception as e:
print("Only integers are allowed")
def main():
greeting()
name=input("")
welcome(name)
display_options()
main()
|
def f(l):
if len(l)!=1:
L=[]
a1=len(l)
L+=[a1]
count=1
while len(L)<max(l):
c=1
for j in range(2,max(l)+1):
for k in range(1, len(l)):
if l[k]>=j:
c+=1
L+=[c]
c=1
return L
else:
return l
n=int(input('Enter the number of integers\n'))
l=[]
for i in range(n):
l+=[int(input("Enter an integer:"))]
print(f(l))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.