text stringlengths 37 1.41M |
|---|
"""
179. Update Bits
Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N start from i to j)
Example
Example 1:
Input: N=(10000000000)2 M=(10101)2 i=2 j=6
Output: N=(10001010100)2
Example 2:
Input: N=(10000000000)2 M=(11111)2 i=2 j=6
Output: N=(10001111100)2
Challenge
Minimum number of operations?
Clarification
You can assume that the bits j through i have enough space to fit all of M. That is, if M=10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j=3 and i=2, because M could not fully fit between bit 3 and bit 2.
Notice
In the function, the numbers N and M will given in decimal, you should also return a decimal number.
"""
class Solution:
"""
@param n: An integer
@param m: An integer
@param i: A bit position
@param j: A bit position
@return: An integer
"""
def updateBits(self, n, m, i, j):
neg_n = False
neg_m = False
if n >= 0:
bin_n = bin(n)[2:]
else:
bin_n = bin(n)[3:]
neg_n = True
if m >= 0:
bin_m = bin(m)[2:]
else:
bin_m = bin(m)[3:]
neg_m = True
neg = neg_n ^ neg_m
if neg:
return -int(bin_n[:-j-1]+bin_m+bin_n[-i:], 2)
return int(bin_n[:-j-1]+bin_m+bin_n[-i:], 2)
if __name__ == "__main__":
s = Solution()
|
"""
96. Partition List
中文
English
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example
Example 1:
Input: list = null, x = 0
Output: null
Explanation: The empty list Satisfy the conditions by itself.
Example 2:
Input: list = 1->4->3->2->5->2->null, x = 3
Output: 1->2->2->4->3->5->null
Explanation: keep the original relative order of the nodes in each of the two partitions.
"""
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution(object):
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
if not(head):
return head
l = []
node = head
while (node):
l.append(node)
node = node.next
print(l)
i = 0
j = 0
while (i < len(l) and j < len(l)):
while(l[i].val < x):
i += 1
print('i', i)
while(l[j].val >= x):
j += 1
print('j', j)
self.swap(l, i, j)
for i in range(len(l)-1):
l[i].next = l[i+1]
l[-1].next = None
return l[0]
def partition(self, head, x):
if not(head):
return head
fsmaller = ListNode(0)
flarger = ListNode(0)
larger = flarger
smaller = fsmaller
node = head
while node:
if node.val < x:
smaller.next = node
smaller = smaller.next
else:
larger.next = node
larger = larger.next
node = node.next
larger.next = None
smaller.next = flarger.next
return fsmaller.next
def swap(self, l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
if (__name__ == "__main__"):
s = Solution()
# l1 = ListNode(1)
# print(s.partition(l1, 0).val)
l5 = ListNode(4)
l4 = ListNode(2, l5)
l3 = ListNode(1, l4)
l2 = ListNode(3, l3)
l1 = ListNode(3, l2)
node = s.partition(l1, 3)
while (node):
print (node.val)
node = node.next
|
"""
54. String to Integer (atoi)
中文
English
Implement function atoi to convert a string to an integer.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Example
Example 1
Input: "10"
Output: 10
Example 2
Input: "1"
Output: 1
Example 3
Input: "123123123123123"
Output: 2147483647
Explanation: 123123123123123 > INT_MAX, so we return INT_MAX
Example 4
Input: "1.0"
Output: 1
Explanation: We just need to change the first vaild number
"""
import re
class Solution:
"""
@param str: A string
@return: An integer
"""
def atoi(self, str):
res = ""
found = False
for i in range(len(str)):
if re.search("[0-9]", str[i]):
found = True
res += str[i]
elif found:
break
elif re.search("[+-]", str[i]):
if re.search("[+-]", str[i+1]):
break
res += str[i]
found = True
if res:
res = int(res)
if res > 2147483647:
return 2147483647
elif res < -2147483648:
return -2147483648
return res
else:
return 0
if __name__ == "__main__":
s = Solution()
print(s.atoi('10'))
assert(s.atoi("10") == 10)
assert(s.atoi("1") == 1)
assert(s.atoi("1.0") == 1)
assert(s.atoi(" 15+6") == 15)
|
"""
670. Predict the Winner
中文
English
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example
Example1
Input: [1, 5, 2]
Output: false
Explanation:
Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example2
Input: [1, 5, 233, 7]
Output: true
Explanation:
Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Notice
1 <= length of the array <= 2000.
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
"""
class Solution:
"""
@param nums: nums an array of scores
@return: check if player 1 will win
"""
def PredictTheWinner(self, nums):
score_1 = 0
score_2 = 0
i = 0
j = len(nums)-1
turn = 0
while i < j:
score_difference_l = nums[i] - nums[i+1]
score_difference_r = nums[j] - nums[j-1]
if score_difference_l > score_difference_r:
added_score = score_difference_l
i += 1
else:
added_score = score_difference_r
j -= 1
if not turn % 2:
score_1 += added_score
else:
score_2 += added_score
turn += 1
return score_1 >= score_2
if __name__ == "__main__":
s = Solution()
print(s.PredictTheWinner([1, 20, 4]))
#assert(not s.PredictTheWinner([1, 5, 2]))
#assert(s.PredictTheWinner([1, 5, 233, 2]))
|
"""
408. Add Binary
中文
English
Given two binary strings, return their sum (also a binary string).
Example
Example 1:
Input:
a = "0", b = "0"
Output:
"0"
Example 2:
Input:
a = "11", b = "1"
Output:
"100"
"""
class Solution:
"""
@param a: a number
@param b: a number
@return: the result
"""
def addBinary(self, a, b):
carry = 0
added = min(len(a), len(b))
res = ""
for i in range(-1, -added-1, -1):
temp = int(a[i]) + int(b[i]) + carry
carry = 0
if temp >= 2:
carry = 1
temp -= 2
res = str(temp) + res
if len(a) > added:
if carry:
return self.addBinary(a[0:len(a)-added]+"0"*added, str(carry) + res)
return a[0:len(a)-added] + res
elif len(b) > added:
if carry:
return self.addBinary(b[0:len(b)-added]+"0"*added, str(carry) + res)
return b[0:len(b)-added] + res
elif carry:
res = str(carry) + res
return res
if __name__ == "__main__":
s = Solution()
assert(s.addBinary("0", "0") == '0')
assert(s.addBinary("11", "1") == '100')
assert(s.addBinary("110", "10") == "1000")
assert(s.addBinary("111", "1") == "1000")
assert(s.addBinary("1", "111") == "1000")
|
from typing import List
from cards.card import Deck, GameCard
class Player:
hand: List[GameCard]
id : int
def __init__(self, hand, id):
self.hand = hand
self.id = id
def draw(self) -> GameCard:
return self.hand.pop(0)
def out_of_cards(self) -> bool:
return len(self.hand) == 0
def take(self, card: GameCard):
self.hand.append(card)
class War:
deck: Deck
player_one: Player
player_two: Player
def __init__(self, deck: Deck):
self.deck = deck
def setup_game(self):
deck_one, deck_two = self.deck.split_deck()
self.deck.cards.clear()
self.player_one = Player(deck_one)
self.player_two = Player(deck_two)
def draw(self):
p1_card = self.player_one.draw()
print("Player 1 draws card {}".format(p1_card))
p2_card = self.player_two.draw()
print("Player 2 draws card {}".format(p2_card))
self.deck.cards += [p1_card, p2_card]
winner: Player
if p1_card > p2_card:
winner = self.player_one
elif p1_card < p2_card:
winner = self.player_two
else:
print("Equal!")
pass
if winner:
print("{} wins".format(winner))
for card in self.deck.cards:
winner.take(card)
self.deck.cards.clear()
|
import requests
import argparse
from bs4 import BeautifulSoup
def scrape(url):
page = requests.get(url)
assert page.status_code == 200
soup = BeautifulSoup(page.content, 'html.parser')
print("Overview: " + soup.article.find_all('h2')[0].nextSibling.text)
print("Symptoms: " + soup.article.find_all('h2')[1].nextSibling.text)
print("Causes: " + soup.article.find_all('h2')[2].nextSibling.text)
def crawl(url, disorder):
base = 'https://www.mayoclinic.org'
response = requests.get(url)
data = response.text
# Passing the source code to BeautifulSoup to create a BeautifulSoup object for it.
soup = BeautifulSoup(data, 'lxml')
# Extracting all the <a> tags into a list.
tags = soup.find_all('a')
# Extracting URLs from the attribute href in the <a> tags.
for tag in tags:
tag = tag.get('href')
if tag != None:
if disorder in tag :
print(base+tag)
return base+tag
return ''
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--disorder', nargs='*', type= str, default = ['bipolar','disorder'])
args = parser.parse_args()
dis = args.disorder
if len(dis) > 1:
dis = '-'.join(dis) # converts list to string
else:
dis = dis[0] # get string from list of size one
letter = dis[0].upper()
base_url = 'https://www.mayoclinic.org/diseases-conditions/index?letter=' + letter
dis_url = crawl(base_url, dis)
if dis_url != '':
scrape(dis_url)
else: print('disorder not found')
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 1 11:16:44 2018
@author:
"""
"""
KNN
(1) a description of how you formulated the problem:
Using knn algorithm, we will find n high-dimensional point which is nearst to the point we want to classify.Then, we will find out the label of most point we picke out to be the predict label.
(2) a brief description of how your program works:
This program including model_knn_train , model_knn_test and get_knn_train_result funtions. The other small funcions are called by them.
The structure of this program is:
module_knn_train(train_file='train-data.txt',model_file='nearest_model.txt',k_range = 3,times_train = 1)
readTrainData(train_file)
generateTrainReport(imgTrainIds,imgTrainOrientations,imgTrainVectors,times_train,k_range)
trainKNN(trainIds,trainOrientations,trainVectors,k)
testKNNAccurcy(partImgTrainIds,partImgTrainOrientations,partImgTrainVectors,partImgValIds,partImgValOrientations,partImgValVectors,k)
kNN_classify(imgTestVectors[i], imgTrainVectors, imgTrainOrientations, k)
save_train_result_to_excel.saveTrainResult()
generateTrainModelFile(model_file,bestK,imgTrainIds,imgTrainVectors,imgTrainOrientations)
model_knn_test(test_file='test-data.txt',model_file='nearest_model.txt')
readTrainModelFile(model_file)
readTrainData(test_file)
testKNNAccurcy(imgTrainIds,imgTrainOrientations,imgTrainVectors,imgTestIds,imgTestOrientations,imgTestVectors,bestK)
kNN_classify(imgTestVectors[i], imgTrainVectors, imgTrainOrientations, k)
generateTestOutputFile(outputFilename,predictSet)
show_image_to_html.show_result_on_html(predictTrueSet,htmlTrueFile,predictFalseSet,htmlFalseFile)
get_knn_train_result()
module_knn_train(train_file ,model_file ,k_range ,ratio_train)
(3) a discussion of any problems, assumptions, simplifications, and/or design decisions you made:
We find that if the training set is large, our training will cost a lot of time.
We design the function of 'get_knn_train_result()' to help us automaticly split the origin training set and get different training result and then generate the training result to excel file for analysis.
Besides, we save the classfication result both right and wrong in the html file to help us clearly find the patterns to the erros.
"""
import numpy as np
import time
import save_train_result_to_excel
import show_image_to_html
"""
@funciton:read data from dataset
@input:file address of dataset
@output:image ID,image orientation,image feature vector
"""
def readTrainData(filename):
fr = open(filename)
arrayLines = fr.readlines()
numberLines = len(arrayLines)
imgIds = []
imgLabels = []
imgDataSet = np.zeros((numberLines,192),dtype =int)
index = 0
for line in arrayLines:
line = line.strip()
listFromLine = line.split(' ')
imgIds.append(listFromLine[0])
imgLabels.append(listFromLine[1])
imgDataSet[index,:] = listFromLine[2:]
index = index + 1
return imgIds,imgLabels,imgDataSet
""""
@funciton:kNN classfication
@input:taraget : feature vector of taget image:,dataset,label of dataset,k value
@output:result of classfication
"""
def kNN_classify(targetImg, dataSet, labels, k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(targetImg, (dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDistances = sqDiffMat.sum(axis=1)
distances = sqDistances**0.5
#sort the index
sortedDistIndex = np.argsort(distances)
classCount={}
for i in range(k):
voteLabel = labels[sortedDistIndex[i]]
classCount[voteLabel] = classCount.get(voteLabel,0) + 1
sortedClassCount = sorted(classCount.items(), key = lambda classCount:classCount[1], reverse=True)
return sortedClassCount[0][0]
""""
@funciton:According to the training set and testing set,judge the accurcy in current k value
@input: trainset ,testset,k value
@output: accurcy
"""
def testKNNAccurcy(imgTrainIds,imgTrainOrientations,imgTrainVectors,imgTestIds,imgTestOrientations,imgTestVectors,k):
predictTrueNum = 0
predictFalseNum = 0
predictSet=[]
predictTrueSet = []
predictFalseSet = []
outputLines = []
for i in range(len(imgTestIds)):
guessOrientation = kNN_classify(imgTestVectors[i], imgTrainVectors, imgTrainOrientations, k)
outputLine = [imgTestIds[i],guessOrientation]
outputLines.append(outputLine)
if guessOrientation == imgTestOrientations[i]:
predictTrueNum = predictTrueNum + 1
predictTrueSet.append([imgTestIds[i],imgTestOrientations[i],guessOrientation])
else:
predictFalseNum = predictFalseNum +1
predictFalseSet.append([imgTestIds[i],imgTestOrientations[i],guessOrientation])
predictSet.append([imgTestIds[i],imgTestOrientations[i],guessOrientation])
accurcy = predictTrueNum/len(imgTestIds)
return accurcy,predictSet,predictTrueSet,predictFalseSet
"""
@function:According to the training set and k value, split the trainset to three set.One is validationset and two are training set.Then get the accuary
@input:training set and k value
@output:分类准确度
"""
def trainKNN(imgTrainIds,imgTrainOrientations,imgTrainVectors,k):
#Split the trainset to three set.One is validationset and two are training set
valDataSetSize = int(len(imgTrainIds)/3)
accuracyAverage = 0
for i in range(3):
#image ID
temp = imgTrainIds.copy()
partImgValIds = temp[i*valDataSetSize:(i+1)*valDataSetSize]
del temp[i*valDataSetSize:(i+1)*valDataSetSize]
partImgTrainIds = temp
#image orientation
temp = imgTrainOrientations.copy()
partImgValOrientations = temp[i*valDataSetSize:(i+1)*valDataSetSize]
del temp[i*valDataSetSize:(i+1)*valDataSetSize]
partImgTrainOrientations = temp
#image feature vector
partImgValVectors = imgTrainVectors[i*valDataSetSize:(i+1)*valDataSetSize]
partImgTrainVectors = np.zeros((len(imgTrainVectors)-valDataSetSize,192),dtype =int)
t = 0
temp1 = partImgValVectors.tolist()
temp2 = imgTrainVectors.tolist()
for vector in temp2:
if vector not in temp1:
partImgTrainVectors[t,:] = vector
t = t + 1
accurcy,predictSet,predictTrueSet,predictFalseSet = testKNNAccurcy(partImgTrainIds,partImgTrainOrientations,partImgTrainVectors,partImgValIds,partImgValOrientations,partImgValVectors,k)
accuracyAverage = accuracyAverage + accurcy
#average accuracy
accuracyAverage = accuracyAverage/3
return accuracyAverage,predictTrueSet,predictFalseSet
"""
@function: Generate knn_model.txt,which including best k value and data from training set
@input: best k value and data from training set
@output: knn_model.txt
"""
def generateTrainModelFile(modelFilename,bestK,dataIds,dataSet, labels):
file = open(modelFilename, 'w' )
file.write(str(bestK))
file.write('\n')
for i in range(len(dataSet)):
file.write(dataIds[i])
file.write(' ')
file.write(labels[i])
file.write(' ')
for element in dataSet[i]:
file.write(str(element))
file.write(' ')
file.write('\n')
"""
@function:Generate training result from different k value and different training set
@input:training set,number of different sizes of training set,range of k value
@output:result including: bestK,maxAccurcy,trainResult[splitTrainSetSize,k,accurcy,timeCost]
"""
def generateTrainReport(imgTrainIds,imgTrainOrientations,imgTrainVectors,ratio_train,k_range):
accurcyDict ={}
trainResult = []
maxAccurcy = 0
bestK = 1
#according to the size of training set and number of different training set,generate training set which can be divided by 100
trainSetSize = int(np.floor(len(imgTrainIds)*ratio_train/100))*100
#different size of training set
trainIds = imgTrainIds[0:trainSetSize]
trainOrientations = imgTrainOrientations[0:trainSetSize]
trainVectors = imgTrainVectors[0:trainSetSize]
t0 = time.time()
#get result
for k in range(1,k_range+1):
t1 = time.time()
accurcy,predictTrueSet,predictFalseSet = trainKNN(trainIds,trainOrientations,trainVectors,k)
t2 = time.time()
timeCost = round(t2-t1,2)
accurcy = round(accurcy,3)
accurcyDict[k] = accurcy
trainResult.append([trainSetSize,k,accurcy,timeCost])
print('trainSetSize: %d , k: %d , accurcy: %.3f , time cost: %.2f\n'%(trainSetSize,k,accurcy,timeCost))
sortedAccurcy = sorted(accurcyDict.items(), key = lambda accurcyDict:accurcyDict[1], reverse=True)
maxAccurcy = sortedAccurcy[0][1]
bestK = sortedAccurcy[0][0]
timeCost = round(time.time()-t0)
return trainSetSize,bestK,maxAccurcy,timeCost,trainResult
"""
@function:According to training set, get best k value.Then ouput the knn_model.txt
@input: train_file='train-data.txt'
@output: model_file='nearest_model.txt'
"""
def model_knn_train(train_file='train-data.txt',model_file='nearest_model.txt',k_range = 40,ratio_train = 0.5):
#Analysis the training set
imgTrainIds,imgTrainOrientations,imgTrainVectors = readTrainData(train_file)
print('Read %s for testing successfully!!\n'%(train_file))
#Generate the result in diffeent training set and different k value
trainSetSize,bestK,maxAccurcy,timeCost,trainResult = generateTrainReport(imgTrainIds,imgTrainOrientations,imgTrainVectors,ratio_train,k_range)
print('In the case of k_range = %d, ratio_train = %.3f, training process has done!!'%(k_range,ratio_train))
print('Result: best k value = %d, max accurcy = %.3f\n'%(bestK,maxAccurcy))
#generate the parameter file
generateTrainModelFile(model_file,bestK,imgTrainIds,imgTrainVectors,imgTrainOrientations)
print('Generate %s in training successfully!!\n'%(model_file))
return [trainSetSize,bestK,maxAccurcy,timeCost,trainResult]
"""
@funciton:read knn_model.txt
@input:model_file
@output:best k value, image ID ,image orientation,image feature vector
"""
def readTrainModelFile(model_file):
fr = open(model_file)
arrayLines = fr.readlines()
numberLines = len(arrayLines) -1
imgIds = []
imgLabels = []
imgDataSet = np.zeros((numberLines,192),dtype =int)
bestK = 1
index = 0
for line in arrayLines:
line = line.strip()
listFromLine = line.split(' ')
if len(listFromLine) == 1:
bestK = int(listFromLine[0])
else:
imgIds.append(listFromLine[0])
imgLabels.append(listFromLine[1])
imgDataSet[index,:] = listFromLine[2:]
index = index + 1
return bestK,imgIds,imgLabels,imgDataSet
"""
@function:generate output.txt ,format: test/124567.jpg 180
@input:output_filename , predictSet[imgTestIds[i],imgTestOrientations[i],guessOrientation]
@output:output.txt
"""
def generateTestOutputFile(outputFilename,predictSet):
file = open(outputFilename, 'w' )
for predict in predictSet:
file.write(predict[0])
file.write(' ')
file.write(predict[2])
file.write('\n')
"""
@funciton:According to testing set and knn model file to generate the accuary
@input:test_file='test-data.txt' , model_file='knn_model.txt'
@output: accurcy and the classfication result in the html file
"""
def model_knn_test(test_file='test-data.txt',model_file='nearest_model.txt'):
#analysis the model file
bestK,imgTrainIds,imgTrainOrientations,imgTrainVectors = readTrainModelFile(model_file)
print('Read nearest_model.txt for testing successfully!!\n')
#analysis the testing data
imgTestIds,imgTestOrientations,imgTestVectors = readTrainData(test_file)
print('Read test-data.txt for testing successfully!!\n')
#get result using knn model
accurcy,predictSet,predictTrueSet,predictFalseSet = testKNNAccurcy(imgTrainIds,imgTrainOrientations,imgTrainVectors,imgTestIds,imgTestOrientations,imgTestVectors,bestK)
print('Testing have finished')
print('Testing accurcy: %.3f\n'%(accurcy))
#generate output.txt file
outputFilename = 'nearest_output.txt'
generateTestOutputFile(outputFilename,predictSet)
print('Generate output.txt for testing successfully!!\n')
#show the classfication result in the html file
htmlTrueFile = 'knn_result_true.html'
htmlFalseFile = 'knn_result_false.html'
show_image_to_html.show_result_on_html(predictTrueSet,htmlTrueFile,predictFalseSet,htmlFalseFile)
print('Generate test_true_result.html and test_false_result.html for testing successfully!!\n')
"""
@funciton:In order to get training result under different parameters, we design this function to use module_knn_train function
@input:
@output: results: ['trainingSetSize','bestK','maxAccuracy','timeCost'] in excel file
"""
def get_knn_train_result():
train_file='train-data.txt'
model_file='nearest_model.txt'
k_ranges= list(range(1,81,10))
ratio_trains = list(range(2,12,4))
titles = ['trainingSetSize','bestK','maxAccuracy','timeCost']
trainResults = []
for k_range in k_ranges:
for ratio_train in ratio_trains:
ratio_train = ratio_train/100
print()
print()
print('start new training....\n')
print('k_range',k_range,'ratio_train',ratio_train)
print()
result = model_knn_train(train_file ,model_file ,k_range ,ratio_train)
trainResults.append(result)
trainResultsCopy = trainResults.copy()
wantedResults =[]
for i in range(len(trainResultsCopy)):
wantedResult = trainResultsCopy[i][4]
wantedResults.extend(wantedResult)
trainResultFilename = 'nearest_train_result_training.xls'
save_train_result_to_excel.saveTrainResult(trainResultFilename,titles,wantedResults) |
'''
This program provides something....
* 1. draw a box around a region-of-interest (ROI) to crop
* 2. roi is stored to disk (./cropped/)
* 3. x, y, w, h coordinates of ROI are stored in a txt file (./labels/)
Usage:
crop.py [<some_args>, here]
v - view cropped ROI (separate window)
c - close ROI window
r - refresh image (partial implementation)
s - save ROI
f - move forward
d - move back
q - quit
Output:
Stores a cropped ROI to ./rois/
Stores coords of cropped ROI as a .txt file corresponding to the img name to ./labels/
'''
import cv2
import numpy as np
import os, sys
from subprocess import check_output
''' CONSTANTS '''
LABEL = 11 # 1 - 9 reserved for DICE, 10 is old orange gate, 11 is new black and red
SQUARE = True
''' GLOBAL VARIABLES '''
drawing = False # true if mouse is pressed
ix, iy = -1, -1
roi = (0, 0, 0, 0) # null value - handles numerical calcs
img = None
# normalizes the x, y, w, h coords when dragged from different directions
def get_roi(x, y, w, h):
if (y > h and x > w): # lower right to upper left
return (w, h, x, y)
elif (y < h and x > w): # upper right to lower left
return (w, y, x, h)
elif (y > h and x < w): # lower left to upper right
return(x, h, w, y)
elif (y == h and x == w):
return (0, 0, 0, 0) # roi too small
else:
return (x, y, w, h) # upper left to lower right
# reshape an ROI to a square image
# tuple in, tuple out
def roi_to_square(x, y, w, h):
frame_y, frame_x, ch = img.shape # since img is global var
x_shape = w - x # size of x ROI
y_shape = h - y # size of y ROI
if(x_shape > y_shape):
y_diff = (x_shape - y_shape) // 2
if( (y - y_diff) < 0):
return (x, y, w, h + (y_diff * 2) ) # add only to bottom
elif( (h + y_diff) > frame_y):
return (x, y - (y_diff * 2), w, h) # add only to top
else:
return (x, y - y_diff, w, h + y_diff) # add to both top and bottom
elif(y_shape > x_shape):
x_diff = (y_shape - x_shape) // 2
if( (x - x_diff) < 0):
return (x, y, w + (x_diff * 2), h) # add only to right side
elif( (w + x_diff) > frame_x):
return (x - (x_diff * 2), y, w, h) # add only to left side
else:
return (x - x_diff, y, w + x_diff, h) # add to left and right side
else:
return (x, y, w, h) # already square
# gets file names from a dir - includes file extension
# returns as a list
def get_file_names_from_dir(file_path):
ls = []
with os.scandir(file_path) as it:
for entry in it:
if not entry.name.startswith(".") and entry.is_file:
ls.append(entry.name)
return sorted(ls)
# creates a txt file to append the label and ROI coordinates
# returns the file object
def create_txt_file(path):
try:
txt_file = open(path, "a+")
except:
print("File I/O error")
exit()
return txt_file
# mouse callback function for drawing boxes
def draw_rectangle(event, x, y, flags, param):
global ix, iy, drawing, roi
if (event == cv2.EVENT_LBUTTONDOWN):
drawing = True
ix, iy = x, y
elif (event == cv2.EVENT_MOUSEMOVE):
if drawing == True:
#tmp_img = param.copy()
tmp_img = img.copy()
cv2.rectangle(tmp_img, (ix, iy), (x, y), (0, 255, 0), 1)
cv2.imshow("image", tmp_img)
elif (event == cv2.EVENT_LBUTTONUP):
#tmp_img = param.copy()
tmp_img = img.copy()
drawing = False
roi = (ix, iy, x, y)
cv2.rectangle(tmp_img, (ix, iy), (x, y), (0, 255, 0), 1)
if __name__ == "__main__":
clear_screen_cmd = check_output(["clear", "."]).decode("utf8")
print(clear_screen_cmd) # clears terminal (ctrl + l)
print(__doc__)
try:
img_path = sys.argv[1]
except:
img_path = "../images/front10.jpg"
# counters
global_roi_counter = 0
local_roi_counter = 0
img_counter = 0
# dir stuff
labels_dir_path = "./labels/" # where to store label txt files
imgs_dir_path = "./images/" # where to grab images from
rois_dir_path = "./rois/" # where to store roi
file_names_with_ext = get_file_names_from_dir(imgs_dir_path)
file_names = [x.split(".")[0] for x in file_names_with_ext] # gets name only - discards extension
number_of_imgs = len(file_names)
# image stuff
img = cv2.imread(imgs_dir_path + file_names[img_counter] + ".jpg" )
img_l, img_w, ch = img.shape
tmp_img = img.copy()
# window/screen stuff
cv2.namedWindow("image")
cv2.setMouseCallback("image", draw_rectangle)
cv2.imshow("image", img)
while(1):
k = cv2.waitKey(1) & 0xFF
if (k == 27 or k == ord("q") ): # exit
print("\n\tQ was pressed - Quitting\n")
global_roi_counter += local_roi_counter
print(str(global_roi_counter) + " ROI(s) were stored!\n")
break
elif (k == ord("f") and (img_counter < number_of_imgs - 1) ): # move forward to next image
print("\n\tNext Image")
roi = (0, 0, 0, 0)
cv2.destroyWindow("roi")
img_counter += 1 # for file name purposes
global_roi_counter += local_roi_counter
local_roi_counter = 0
img_path = "./images/" + file_names[img_counter] + ".jpg"
img = cv2.imread(img_path)
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
elif (k == ord("d") and (img_counter > 0) ): # move back to prev image
print("\n\tPrevious Image")
roi = (0, 0, 0, 0)
cv2.destroyWindow("roi")
img_counter -= 1 # for file name purposes
global_roi_counter += local_roi_counter
local_roi_counter = 0
img_path = "./images/" + file_names[img_counter] + ".jpg"
img = cv2.imread(img_path)
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
elif (k == ord("r") ): # refresh image (remove all markings on img)
print("\n\tRefreshed Image")
roi = (0, 0, 0, 0)
cv2.destroyWindow("roi")
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
elif(k == ord("t") ): # toggle square resize
SQUARE = not SQUARE
print("\n\tSquare toggled:", SQUARE)
if (roi != (0, 0, 0, 0) ): # if ROI has been created
roi_x, roi_y, roi_w, roi_h = roi
x, y, w, h = get_roi(roi_x, roi_y, roi_w, roi_h) # returns the ROI from original image
if (SQUARE):
x, y, w, h = roi_to_square(x, y, w, h) # squares the bounding box
if ( (x, y, w, h) == (0, 0, 0, 0) ): # checks for bug when mouse is clicked but no box is created
img_roi = None
else:
img_roi = img[y:h, x:w, :]
if (img_roi is None): # bug check - need to identify small boxes
print("\nERROR:\tROI " + str(roi) + " is Out-of-Bounds OR not large enough")
cv2.destroyWindow("roi")
roi = (0, 0, 0, 0) # might already be set
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
elif(k == ord("v") ): # view roi
print("\n\tViewing ROI " + str(roi) )
print("\t\tShape", img_roi.shape)
cv2.imshow("roi", img_roi)
cv2.moveWindow("roi", img_w, 87)
elif(k == ord("s") ): # save roi after viewing it
local_roi_counter += 1
path = rois_dir_path + file_names[img_counter] + "_" + str(local_roi_counter) + ".jpg"
print("\n* Saved ROI #" + str(local_roi_counter) + " " + str(roi) + " to: " + path)
cv2.imwrite(path, img_roi)
txt_file_path = labels_dir_path + file_names[img_counter] + ".txt"
txt_file = create_txt_file(txt_file_path)
print(str(LABEL), x, y, w, h, file=txt_file)
cv2.destroyWindow("roi")
roi = (0, 0, 0, 0)
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
elif(k == ord("c") ): # clear roi
print("\n\tCleared ROI " + str(roi) )
roi = (0, 0, 0, 0)
cv2.destroyWindow("roi")
tmp_img = img.copy()
cv2.imshow("image", tmp_img)
if(txt_file is not None): # if no file was ever created
txt_file.close()
cv2.destroyAllWindows()
|
def merge_sort(array, array_size):
# array list to be sorted
# buffer temporary space needed during merge
buffer = [None] * array_size
n_if_statements = 0
return merge_sort_helper(
array,
buffer,
0, array_size-1,
n_if_statements
)
def merge_sort_helper(array, buffer, low, high, n_if_statements):
# array list to be sorted
# buffer temporary space needed during merge
# high, low bounds of sublist
# middle midpoint of sublist
if low < high:
n_if_statements += 1
middle = (low + high) // 2
# print ("low, middle, high = ", low, middle, high)
n_if_statements = merge_sort_helper(
array, buffer, low, middle, n_if_statements
)
n_if_statements = merge_sort_helper(
array, buffer, middle + 1, high, n_if_statements
)
# print ("lyst - copyBuffer =>", lyst, "===", copyBuffer)
n_if_statements += merge(array, buffer, low, middle, high)
return n_if_statements
def merge(array, buffer, low, middle, high):
n_if_statements = 0
#initialize left_idx and right_idx to the 1st items in each sublist
left_idx = low
right_idx = middle + 1
#interleave items from the sublists into the
#buffer in such a way that order is maintained.
for i in range(low, high + 1):
if left_idx > middle:
n_if_statements += 1
buffer[i] = array[right_idx] # 1st sublist exhausted
right_idx += 1
elif right_idx > high:
n_if_statements += 2
buffer[i] = array[left_idx]# 2nd sublist exhausted
left_idx += 1
elif array[left_idx] < array[right_idx]:# item in 1st sublist
n_if_statements += 3
buffer[i] = array[left_idx]
left_idx += 1
else:
n_if_statements += 3
buffer[i] = array[right_idx] # item in 2nd sublist
right_idx += 1
for i in range(low, high + 1): # copy sorted items back to
array[i] = buffer[i] # proer position in array
return n_if_statements
|
#Assignment 2: Algorithm Implementation and Analysis
#Abrie Halgryn
#Student number: 10496171
import time
#Question 1, 1(c):
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
#This will iterate through each item of the array - 1 the last element as it does not have to be comapred as there is nothing to compare it to
for i in range(n-1):
#If the range is set to range(n), the outer loop will repeat more than needed.
#The last i elements are already in place
#This will loop the array starting at the 0 and ending at n-1
for j in range(0, n-1):
#If it is found that they have to be swapped, the values of the array contents are switched accordingly:
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Question 1, 1(d):
# Python program for implementation of Bubble Sort
def optimalBubbleSort(arr):
n = len(arr)
#This will iterate through each item of the array - 1 the last element as it does not have to be comapred as there is nothing to compare it to
for i in range(n-1):
#If the range is set to range(n), the outer loop will repeat more than needed.
#The last i elements are already in place
#This will loop the array starting at the 0 and ending at n-i-1 QUESTION 1(D)
for j in range(0, n-i-1): #this removes i from n to avoid scanning the entire array over and over as i is the amount of elements that is already "bubbled up" so they cannot move more
#If it is found that they have to be swapped, the values of the array contents are switched accordingly:
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Below line read inputs from user using map() function
print("\nThese values have to be seperated by a space, e.g. 10 22 33 55 44")
arr = list(map(int,input("Enter the numbers : ").strip().split()))
#This line will call the bubble sort function, enter the list into the function
# START MY TIMER - will be used to calculate the amount of time the function takes to run
start_time = time.time()
bubbleSort(arr)
#optimalBubbleSort(arr)
elapsed_time = time.time() - start_time # in seconds, this value can be multiplied by 10 to give the answer in milliseconds
#This will print the sorted array
print ("Sorted array is:", arr)
print("Time Taken:", float(elapsed_time))
input(" ") #this line of code is here so that if its run in cmd the window doesnt instantly close
|
#code adapted from http://automatetheboringstuff.com/2e/chapter10/
#import library
import os
#Enter '.' to specify current directory
#Otherwise enter directory_name/subdirectory_name
directory = input("Enter directory:")
#create text file
fname = "all_listings.txt"
fhandle = open(fname,'w')
#loop using os.walk()
for folderName, subfolders, filenames in os.walk(directory):
fhandle.write('The current folder is ' + folderName+'\n')
for subfolder in subfolders:
fhandle.write('SUBFOLDER OF ' + folderName + ': ' + subfolder+'\n')
for filename in filenames:
fhandle.write('FILE INSIDE ' + folderName + ': '+ filename+'\n')
fhandle.write('---------------------------\n')
|
import pandas as pd
import json
# you can use this as a script with a json response stored as a file, or can just use same indexing on raw JSON resonse from YNAB server
# if you wanted to do this as a function just declare function and include parameter 'json' that must be passed into the function
# read in json file
json = pd.read_json('filename.json')
# declare counters and assign starting value
catgr_counter = 0
cat_counter = 0
# create empty lists - optional
my_cat_group_list = []
my_categories_list = []
# referencing category groups list and storing as variable (will loop through this list below)
category_group_list = json['data']['category_groups']
#outer for loop to go through all of the category groups
for catg in category_group_list:
# referencing category group name and updating the category list which will loop through as 'inner loop'
category_group_name = json['data']['category_groups'][catgr_counter]['name']
category_list = json['data']['category_groups'][catgr_counter]['categories']
# inner for loop to pull category group name and do other actions
for cat in category_list:
category_name = json['data']['category_groups'][catgr_counter]['categories'][cat_counter]['name']
# the action to be taken within inner for loop (here I am printing the variables we stored from outer and inner loop and appending the values to respective lists)
print(category_group_name, ': ', category_name)
my_categories_list.append(category_name)
cat_counter = cat_counter +1
#these below actions are part of outer loop
my_cat_group_list.append(category_gorup_name)
catgr_counter = catgr_counter + 1
cat_counter = 0 # resetting counter for innner loop
# can print out lists to see how they look
print(my_cat_group_list)
print(my_categories_list)
|
#!/usr/bin/env python3
# created by: Ryan Walsh
# created on: January 2021
# this program calculates the volume of a hexagonal prism
import math
def calculate_volume(base_edge, height):
# calculates volume
# process & output
volume_of_hexagonal_prism = ((3 * (math.sqrt(3))) / 2 * (base_edge) ** 2 *
(height))
return volume_of_hexagonal_prism
def main():
# this program calculates the volume of a hexagonal prism
while True:
try:
base_edge_from_user = input("Enter the base edge of the hexagonal"
" prism (cm):")
base_edge_from_user = float(base_edge_from_user)
height_from_user = input("Enter the height of the hexagonal"
" prism (cm):")
print("\n", end="")
height_from_user = float(height_from_user)
if base_edge_from_user < 0 or height_from_user < 0:
print("Please ensure all values are positive.")
print("\n", end="")
else:
break
except Exception:
print("Please enter a valid number.")
print("\n", end="")
# call function
volume = calculate_volume(base_edge_from_user, height_from_user)
print("The volume of a hexagonal prism with a base edge of {0}cm and a"
" height of {1}cm is {2:,.2f}cm³".format(base_edge_from_user,
height_from_user, volume))
if __name__ == "__main__":
main()
|
#Suppose you want to put all your functions into a module for organization purposes
class Math:
@staticmethod #dont need self because it only defines functions within the class
def add5(x):
return x+5
print(Math.add5(10))
from inheritance import Pet
s = Pet("Joe", 30)
print(s.name) |
import numpy as np
board_setups = [
'random',
'magnetised',
'checkerboard',
'stripes',
'two sides'
]
class Ising:
board_setups = board_setups
def __init__(self,
N: int = 32,
T: float=1,
M: float=0,
initial_board: board_setups = 'random'):
"""
Implements Metropolis-Hasting algorithm that simulates Ising model.
Algorithm runs over 2D square lattice with periodic boundary conditions.
:param N: int, size of side of lattice - whole lattice has N^2 spins
:param T: float, temperature in units critical temperature for infinite lattice
:param M: float, outside magnetic field
:param initial_board: str, one of options for initial state of lattice
"""
self.spins_board = self.set_spins_board(N, initial_board)
self.T_crit = 2/np.log(1 + 2**0.5)
self.T = self.T_crit*T
self.outM = M
self.step_count = 0
self.energy = self._energy()
self.magnetization = self._magnetization()
self.reseted = False
def set_spins_board(self,
N: int,
board_setup: board_setups = 'random') -> np.array:
"""
Creates square lattices of given size with spines {1,-1}.
State is chosen based on board_setup parameter
:param N: int, size of side of lattice - whole lattice has N^2 spins
:param board_setup:
:return: np.array, square array of spines in given state
"""
self.reseted = True
if board_setup == self.board_setups[0]:
return np.random.randint(0, 2, (N, N), int)*2 - 1
elif board_setup == self.board_setups[1]:
board = np.ones((N, N), int) * -1
return board
elif board_setup == self.board_setups[2]:
board = np.ones((N, N), int)
board[::2] *= -1
board[:, ::2] *= -1
return board
elif board_setup == self.board_setups[3]:
board = np.ones((N, N), int)
board[::2] *= -1
return board
elif board_setup == self.board_setups[4]:
board = np.ones((N, N), int)
board[N//2:] *= -1
return board
else:
raise ValueError
def _energy(self) -> float:
"""Calculates energy of the whole lattice"""
return self.H_board.sum() / 2
@property
def average_energy(self) -> float:
"""Calculates average energy per spin"""
return self.energy / self.spins_board.size
def _magnetization(self) -> int:
"""Calculates magnetisation of the whole lattice"""
return self.spins_board.sum()
@property
def average_magnetization(self) -> float:
"""Calculates average magnetisation per spin"""
return self.magnetization / self.spins_board.size
@property
def H_board(self) -> np.array:
"""Calculates energy for every spin"""
neighbours = np.roll(self.spins_board, 1, 0) + np.roll(self.spins_board, -1, 0) + \
np.roll(self.spins_board, 1, 1) + np.roll(self.spins_board, -1, 1)
h = -self.spins_board * (neighbours + self.outM)
return h
def _H(self, i: int, j: int) -> float:
"""Calculates energy for spin in position (i,j) """
N = self.spins_board.shape[0]
neighbours = self.spins_board[(i+1) % N, j] + self.spins_board[(i-1) % N, j] + \
self.spins_board[i, (j+1) % N] + self.spins_board[i, (j-1) % N]
h = -self.spins_board[i, j] * (neighbours + self.outM)
return h
def step(self):
"""
Performs single step of Metropolis-Hasting algorithm.
- randomly choices a spin
- calculate energy of this spin, dE
- calculate change of energy in case of flipping spin
- calculate Boltzmann probability of flipping
- pick random form 0 to 1
- spin flips if random is smaller then probability
- if spin flips state must be updated
"""
self.step_count += 1
x, y = np.random.randint(0, self.spins_board.shape[0], 2)
delta_energy, acceptance = self._random_acceptance(x, y)
if acceptance:
self.spins_board[x, y] *= -1
self.magnetization += 2 * self.spins_board[x, y]
if self.reseted:
self.energy = self._energy()
self.reseted = False
else:
self.energy += delta_energy
def _random_acceptance(self, i: int, j: int) -> (float, bool):
delta_energy = - self._H(i, j) * 2
acceptance_probability = np.exp(-delta_energy/self.T)
random_num = np.random.random()
return delta_energy, random_num < acceptance_probability
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
def is_symmetric_recursive(left: TreeNode, right: TreeNode) -> bool:
if not left and not right:
return True
elif not left or not right:
return False
else:
return (left.val == right.val) and left_right_symmetric(left.left, right.right) and left_right_symmetric(left.right, right.left)
def is_symmetric_iterative(left: TreeNode, right: TreeNode) -> bool:
queue = [left, right]
while len(queue) > 0:
left = queue.pop()
right = queue.pop()
if not left and not right:
continue
elif not left or not right:
return False
elif left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True
# return is_symmetric_recursive(root.left, root.right)
return is_symmetric_iterative(root.left, root.right)
|
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
start, stop = 1, n
mid = (start + stop) // 2
g = guess(mid)
while g != 0:
print(start, mid, stop)
if g == 1:
start, stop = mid+1, stop
elif g == -1:
start, stop = start, mid
mid = (start + stop) // 2
g = guess(mid)
return mid |
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
elif n == 2:
return 2
first, second, third = 1, 2, 3
for i in range(3,n+1):
third = first + second
first, second = second, third
return third
|
class Solution:
def isValid_replacements(self, s: str) -> bool:
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('()','').replace('[]','').replace('{}','')
return s == ''
def isValid_stack(self, s: str) -> bool:
stack = []
hashmap = {
")":"(",
"}":"{",
"]":"[",
}
for c in s:
if c in hashmap:
if stack and stack[-1] == hashmap[c]:
stack.pop()
else:
return False
else:
stack.append(c)
return len(stack) == 0
def isValid(self, s: str) -> bool:
return self.isValid_stack(s)
|
class Deque:
def __init__(self):
self.container = []
self.count = 0
def push_front(self, value):
self.container.insert(0, value)
self.count += 1
def push_back(self, value):
self.container.append(value)
self.count += 1
def pop_front(self):
if self.empty():
return -1
self.count -= 1
return self.container.pop(0)
def pop_back(self):
if self.empty():
return -1
self.count -= 1
return self.container.pop()
def size(self):
return self.count
def empty(self):
if self.count == 0 :
return 1
return 0
def front(self):
if self.empty():
return -1
return self.container[0]
def back(self):
if self.empty():
return -1
return self.container[-1]
import sys
deque = Deque()
N = int(sys.stdin.readline())
for _ in range(N):
c = sys.stdin.readline().split()
if c[0] == 'push_front':
deque.push_front(c[1])
elif c[0] == 'push_back':
deque.push_back(c[1])
elif c[0] == 'pop_front':
print(deque.pop_front())
elif c[0] == 'pop_back':
print(deque.pop_back())
elif c[0] == 'size':
print(deque.size())
elif c[0] == 'empty':
print(deque.empty())
elif c[0] == 'front':
print(deque.front())
elif c[0] == 'back':
print(deque.back()) |
words = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']
string = input()
cnt = 0
for i in range(len(string)):
for idx, j in enumerate(words):
if string[i] in j:
cnt += idx + 3
print(cnt) |
T = int(input())
for t in range(1, T+1):
N = int(input())
lst = [int(n) for n in input().split()]
lst = sorted(lst)
print(f"#{t} ", end = "")
for n in range(N):
print(lst[n], end = " ")
print() |
from collections import deque
def bfs(start, numbers, target):
q = deque([start])
cnt = 0
while q:
value, idx = q.popleft()
if idx == len(numbers):
if value == target:
cnt += 1
else:
q.append([value + numbers[idx], idx + 1])
q.append([value - numbers[idx], idx + 1])
return cnt
def solution(numbers, target):
answer = 0
answer += bfs([0, 0], numbers, target)
return answer |
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado un numero real R, intercambiar la parte entera por la parte decimal,
Desplegar ambos números.
'''
nroReal = float(input("Introduzca un número(Real): "))
# Separamos la parte entera de la parte decimal utilizando la funcion parte entera
entera = int(nroReal)
# Multiplicamos de forma sucesiva por 10 hasta que la parte parte decimal sea 0.
realTemp = nroReal - entera
parteDecimal = 0
while int(realTemp) != realTemp:
realTemp = realTemp * 10
parteDecimal = int(realTemp) * 10
print entera
print parteDecimal
|
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado un número X hallar su cuadrado con la suma de sus X numeros impares,
desplegar los números impares y su cuadrado.
'''
import sys
x = int(input("Introduzca un número: "))
imp = 1
cx = 0
for ca in range(1, x + 1, 1):
cx = cx + imp
sys.stdout.write(str(imp) + " ")
imp += 2
print "\nLa suma de impares", cx
|
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado tres números A, B, C determinar y desplegar cual es el mayor.
'''
a = int(input("Introduzca el primer número: "))
b = int(input("Introduzca el segundo número: "))
c = int(input("Introduzca el tercer número: "))
if a > b:
if a > c:
print a, " es el mayor"
else:
print c, " es el mayor"
else:
if b > c:
print b, " es el mayor"
else:
print c, " es el mayor"
|
#!/usr/bin/python
#Learning things about dictionary.
address = {
"Pincode":"272-0112",
"Country":"Japan",
"State":"Chiba",
"City":"Ichikawa",
"Street":"Shioyaki 2-1-35",
"Other":"Copo-Sunrse 105"
}
print address["Pincode"],
print address["Country"],
print address["State"],address["City"],address["Street"],address["Other"]
newAddress = {}
newAddress["Pincode"] = raw_input("Enter Pincode > ")
newAddress["Country"] = raw_input("Enter Country > ")
newAddress["State"] = raw_input("Enter State > ")
newAddress["City"] = raw_input("Enter City > ")
newAddress["Street"] = raw_input("Enter Street > ")
newAddress["Other"] = raw_input("Enter Other > ")
for key,val in newAddress.items():
print "%s %s" %(key,val),
print ""
del newAddress["Pincode"]
for key,val in newAddress.items():
print "%s %s" %(key,val),
|
#!/usr/bin/python
#we can access nth element of list l
#by l[n]
#we can find lenght of list using len function
element = [1,2,3,4]
print "0th element is ",element[0]
string = "ABCDEFGH"
print "second char in string is ",string[2]
|
#!/usr/bin/python
#This time we explore more functions from file
#seek -> to move to position
#readline -> to read one line
#read -> read all data
#open -> to open a file
#and we user all this in functions
from sys import argv
script,filename = argv
def printAll(f):
print f.read()
def printOneLine(count,f):
print "line %s -> %s" % (count,f.readline())
def rewind(f):
f.seek(0)
#open file
f = open(filename)
print "Printing all -----------------"
printAll(f)
print "rewind ----------------"
rewind(f)
print "line by line --------------"
printOneLine(1, f)
printOneLine(2, f)
|
#!/usr/bin/python
#Lets work with some pure logical statments
#and operators
#each print statment prints logic result of following statments
print True and False
print True and (0 == 0)
print True or (0 == 0)
print 1 == 1 and True
print 1 == 1 and False
print "test" == "test"
one = "test"
two = "test"
print one == two
print one != two
print "test" == "testing"
print not True
print not False
print not(one == two)
print 10 > 20
var = 10 > 30
print var
def compare(a,b):
print "comparing ",a," with ",b
return a == b
print compare(10,10)
print compare(12,10)
#note that compare is not called here
print False and compare(10,10)
#both comapres are called here
print compare(30,30) and compare(10,20)
#note that compare is not called here too
print True or compare(10,10)
#and only one compare here
print compare(10,10) or compare(10,10) |
def display(hash_table):
for i in range(len(hash_table)):
print(i, end = " ")
for j in hash_table[i]:
print("->", end = " ")
print(j, end = " ")
print()
def hash(key):
return key % len(hash_table)
def insert(hash_table, key, value):
hash_key = hash(key)
hash_table[hash_key].append(value)
def find(hash_table, key):
hash_key = hash(key)
print(hash_table[hash_key])
hash_table = [[] for _ in range(10)]
insert(hash_table, 50, 'Apple')
insert(hash_table, 25, 'Orange')
insert(hash_table, 10, 'Banana')
insert(hash_table, 4, 'Kiwi')
insert(hash_table, 30, 'Raspberry')
insert(hash_table, 38, 'Blueberry')
display(hash_table)
find(hash_table, 10)
|
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
def __init__(self):
self.head = None
def deleteNode(self, data):
temp = self.head
prev = self.head
if temp.data == data:
if temp.next is None:
print("Can't delete the node as it has only one node")
else:
temp.data = temp.next.data
temp.next = temp.next.nex
retur
while temp.next is not None and temp.data != data:
prev = temp
temp = temp.nex
if temp.next is None and temp.data !=data:
print("Can't delete the node as it doesn't exist")
# If node is last node of the linked list
elif temp.next is None and temp.data == data:
prev.next = Non
else:
prev.next = temp.nex
# To push a new element in the Linked List
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# To print all the elements of the Linked List
def PrintList(self):
temp = self.head
while(temp):
print(temp.data, end = " ")
temp = temp.next
# Driver Code
llist = LinkedList()
llist.push(3)
llist.push(2)
llist.push(6)
llist.push(5)
llist.push(11)
llist.push(10)
llist.push(15)
llist.push(12)
print("Given Linked List: ", end = ' ')
llist.PrintList()
print("\n\nDeleting node 10:")
llist.deleteNode(10)
print("Modified Linked List: ", end = ' ')
llist.PrintList()
print("\n\nDeleting first node")
llist.deleteNode(12)
print("Modified Linked List: ", end = ' ')
llist.PrintList()
|
def parse_years(years):
years_list = years.split(",")
for year in years_list:
if "-" in str(year):
start, end = year.split("-")
years_list.remove(year)
years_list.extend(range(int(start),int(end) + 1))
years_list = list(map(int, years_list))
return years_list
def dedupe_list(years_list):
return list(dict.fromkeys(years_list))
def quick_sort(years_list, starting_index, ending_index):
if starting_index < ending_index:
partition_index = partition(years_list, starting_index, ending_index)
quick_sort(years_list, starting_index, partition_index - 1)
quick_sort(years_list, partition_index + 1, ending_index)
def partition(years_list, starting_index, ending_index):
low_index = (starting_index - 1)
pivot = years_list[ending_index]
for current_element in range(starting_index, ending_index):
if years_list[current_element] < pivot:
low_index = low_index + 1
years_list[low_index], years_list[current_element] = years_list[current_element], years_list[low_index]
years_list[low_index + 1], years_list[ending_index] = years_list[ending_index], years_list[low_index + 1]
return low_index + 1
years = "1995,1990,1989,2000-2005,1492,2015,2020,1860-1865,1776,2020,1990"
years_list = parse_years(years)
print(years_list)
years_list = dedupe_list(years_list)
print(years_list)
#years_list.sort() #easy way if sorting algorithm doesnt have to be implemented
quick_sort(years_list,0,len(years_list) - 1)
print(years_list)
|
name = input("Enter Name : ").strip()
with open("name.txt","w") as fname:
fname.write(name)
print("--------")
print("Reading file : name.txt")
namefound = open("name.txt","r").read()
print("Your name is : %s" % namefound)
print("--------")
print("Writing 17 & 42 inside number.txt")
with open("numbers.txt","w") as number:
number.write(str(17)+"\n"+str(42)+"\n")
print("--------")
print("Reading and counting the sum")
numberlist = [int(i.strip("\n")) for i in open("numbers.txt","r").readlines()]
print("Sum is : %d" % sum(numberlist)) |
"""
taylor expansion examples
https://en.wikipedia.org/wiki/Taylor_series
taylor approximation of exponential function
exp(x) ≅ x^0 / 0! + x^1 / 1! + x^2 / 2! + x^3 / 3! + ...
taylor approximation of logarithmic function
log(1 - x) ≅ -x - x^2/2 - x^3/3 - ...
"""
import numpy as np
def taylor_exp(x, k=3):
approx = 0
for i in range(k):
approx += np.power(x, i) / np.math.factorial(i)
return approx
def taylor_log_one_minus(x, k=3):
approx = 0
for i in range(1, k):
approx -= np.power(x, i) / i
return approx
if __name__ == "__main__":
val = 3
for k in range(19):
yhat = taylor_exp(val, k=k)
y = np.exp(val)
print(f"true exponential function: {y}; taylor approximation at {k}th order: {yhat}")
val = .3
for k in range(19):
yhat = taylor_log_one_minus(val, k=k)
y = np.log(1 - val)
print(f"true log function: {y}; taylor approximation at {k}th order: {yhat}")
|
#Variables allow us to add trainable parameters to a graph. They are constructed with a type and initial value
import tensorflow as tf
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
lenear_model = W * x + b
#variables are not initialized when you call tf.Variable
#Constants are initialized when you call tf.constant, and their value can never change
#initialize all the variables in a TensorFlow program, you must explicitly call a special operat
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(lenear_model, {x:[1,2,3,4]}))
sess.close() |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
cnt = 0
def countUnivalSubtrees(self, root: TreeNode) -> int:
#print(root.val)
if (root==None) :
return 0
self.subTree(root)
return self.cnt
def subTree(self, root: TreeNode) :
if(root.left == None and root.right == None):
self.cnt += 1
return True
else:
lbe = False
rbe = False
if (root.left != None):
lbe = self.subTree(root.left)
if (root.right != None):
rbe = self.subTree(root.right)
if(((lbe and root.left.val==root.val) or root.left ==None) and ((rbe and root.right.val == root.val) or root.right==None)):
self.cnt += 1
return True
else:
return False
if __name__ == '__main__':
S = Solution()
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(1)
root.left.left = TreeNode(1)
print(S.countUnivalSubtrees(None)) |
class Solution:
"""
@param source: the input string
@return: the number of subsequences
"""
def countSubsequences(self, source):
# write your code here
blist = []
# first B
acnt, ccnt = 0,0
foundB = False
firstbindex = 0
for i in range(len(source)):
if source[i] == "a" and not foundB:
acnt += 1
if source[i] == "b" and not foundB:
foundB = True
firstbindex = i
if foundB and source[i] == "c":
ccnt += 1
blist.append((acnt,ccnt))
#print("------------",blist)
for i in range(firstbindex+1,len(source)):
if source[i] == "a" and i > firstbindex :
acnt += 1
if source[i] == "b":
blist.append((acnt,ccnt))
if source[i] == "c" and i > firstbindex:
ccnt -= 1
print(blist)
ans = 0
for i in range(len(blist)):
for j in range(i,len(blist)):
beforea = blist[i][0]
afterc = blist[j][1]
if i != j:
tmp = self.rangeR(beforea, afterc) * pow(2,(j-i)-1)
else:
tmp = self.rangeR(beforea, afterc)
print(tmp)
ans += tmp
return ans
def combine(self,n):
return pow(2,n) - 1
def rangeR(self,start,end):
return self.combine(start) * self.combine(end)
if __name__ == '__main__':
S = Solution()
import numpy as np
def triple_var_by_ref(x):
x[0]=x[0]*3
a=np.array([2])
triple_var_by_ref(a)
print(a+1)
#print(S.equalSubstring("abcd","bcdf",3))
#print(S.countSubsequences("abbbbbbc")) #abacbbcc
|
class QuickSort:
def quicksort(self,arr):
self.sort(arr,0,len(arr) - 1)
return arr
def sort(self,arr,left,right):
if right <= left:
return
low = left
high = right
pivot = arr[low]
while left < right :
while left < right and arr[right] > pivot:
right -= 1
arr[left] = arr[right]
while left < right and arr[left] <= pivot:
left += 1
arr[right] = arr[left]
arr[right] = pivot
self.sort(arr,low,left-1)
self.sort(arr,left+1,high)
def quick_sort2(self,array, left, right):
if left >= right:
return
low = left
high = right
key = array[low]
while left < right:
while left < right and array[right] > key:
right -= 1
array[left] = array[right]
while left < right and array[left] <= key:
left += 1
array[right] = array[left]
array[right] = key
self.quick_sort2(array, low, left - 1)
self.quick_sort2(array, left + 1, high)
if __name__ == '__main__':
S = QuickSort()
#print(S.equalSubstring("abcd","bcdf",3))
print(S.quicksort([4,2,7,4,9,5,7,0,1,12]))
|
#!/usr/bin/python3
from MySameTree import TreeNode;
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.maxLevel = 0
self.maxValue = 0
def dfs(root,level):
if not root:
return
if level > self.maxLevel:
self.maxLevel = level
self.maxValue = root.val
dfs(root.left,level+1)
dfs(root.right, level +1)
return
dfs(root,1)
return self.maxValue |
import numpy as np
# Create a range with min, max, and step
a = np.arange(10, 30, 5)
print(a) # [10 15 20 25]
b = np.arange(0, 2, 0.3)
print(b) # [0. 0.3 0.6 0.9 1.2 1.5 1.8]
# Create a evenly spaced numbers
c = np.linspace(0, 2, 9)
print(c) # [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2.]
# Function evaluation
x = np.linspace(0, 2*np.pi, 100)
f = np.sin(x)
|
import math
def soma(x: float, y: float) -> float:
return x + y
def main() ->None :
num = input('Entre com o numero: ')
try:
raiz = math.sqrt(int(num))
except (ValueError, EnvironmentError, SyntaxError, NameError) as E: # catch multiple exception
print(E)
print('Erro: Somente numeros')
exit(1)
print(f'A raiz quadrada de {num} é {raiz}')
if __name__ == '__main__':
main()
|
sum = lambda x, y: x + y
print(sum)
print(sum(4, 5))
can_vote = lambda age: True if age >= 18 else False
print(can_vote)
print(can_vote(17))
print(can_vote(19))
powerlist = [lambda x: x ** 2,
lambda x: x ** 3,
lambda x: x ** 4]
for func in powerlist:
print(func(4))
######################################################################################
attack = {
"quick": lambda:
print("Quick Attack"),
"power": lambda:
print("Power Attack"),
"miss": lambda:
print("Missed Attack")}
attack["quick"]()
attack["miss"]()
import random
attackKey = random.choice(list(attack.keys()))
attack[attackKey]()
######################################################################################
import random
flipList = []
for i in range(1, 1000):
flipList += random.choice(['H', 'T'])
print("Heads :", flipList.count("H"))
print("Tails :", flipList.count("T"))
######################################################################################
oneToTen = range(1, 11)
def dbl_num(num):
return num * 2
print(list(map(dbl_num, oneToTen)))
print(list(map((lambda x: x * 3), oneToTen)))
aList = list(map((lambda x, y: x + y), [1, 2, 3], [1, 2, 3]))
print(aList)
######################################################################################
alist0 = list(map((lambda x: x % 4 == 0 and x % 100 != 0), range(2000, 2020)))
alist1 = list(
filter((lambda x: x % 4 == 0 and x % 100 != 0), range(2000, 2020)))
print(alist0)
print(alist1)
######################################################################################
def f(x): return x ** 2
print(f(8))
g = lambda x: x ** 2
print(g(8))
######################################################################################
def make_incrementor(n): return lambda x: x + n
f = make_incrementor(2)
g = make_incrementor(6)
print(f(42), g(42))
print(make_incrementor(22)(33))
######################################################################################
from functools import reduce
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print(filter(lambda x: x % 3 == 0, foo))
print(map(lambda x: x * 2 + 10, foo))
print(reduce(lambda x, y: x * y, foo))
def bissextoarray(*args):
return map((lambda x: x % 4 == 0 and x % 100 != 0), args)
def bissextofilter(*args):
return filter((lambda x: x % 4 == 0 and x % 100 != 0), args)
def bissexto(arg):
return True in map((lambda x: x % 4 == 0 and x % 100 != 0), [arg])
def iif(condicao, condtrue, condfalse):
if condicao:
return condtrue
else:
return condfalse
anos = list(range(2000, 2017))
print(bissextoarray(*anos))
print(bissextoarray(2004, 2005, 2006))
print(bissexto(2004), bissexto(2005))
anobissexto = bissextofilter(*anos)
print(anobissexto)
for i in anobissexto:
print(bissexto(i))
for i in anos:
print(i, iif(bissexto(i), "Bissexto", "Normal"))
print('Tem {} anos bissextos desde {} ate {}'.format(len(anobissexto),
anos[0], anos[-1]))
|
courses = ['History', 'Math', 'Physics', 'CompSci']
teste = list(['Gato', 'Macaco', 'Leao', 'Zebra'])
# print(type(courses))
# print(courses)
# print(type(teste))
# print(teste)
# print(courses[0])
# print(courses[1])
# print(courses[2])
# print(courses[3])
# print(courses[-1]) # ultimo registro
# print(courses[0:2]) # ['History', 'Math']
# print(courses[:2]) # ['History', 'Math']
# print(courses[2:]) # ['Physics', 'CompSci']
# courses.append('Art')
# print(courses) # ['History', 'Math', 'Physics', 'CompSci', 'Art']
# courses.insert(0, 'Biology')
# print(courses) # ['History', 'Math', 'Physics', 'CompSci', 'Art']
# courses.insert(0, teste)
# print(courses) # [['Gato', 'Macaco', 'Leao', 'Zebra'], 'Biology', 'History', 'Math', 'Physics', 'CompSci', 'Art']
# print(courses[0]) # ['Gato', 'Macaco', 'Leao', 'Zebra']
# courses.extend(teste)
# print(courses) # [['Gato', 'Macaco', 'Leao', 'Zebra'], 'Biology', 'History', 'Math', 'Physics', 'CompSci', 'Art', 'Gato', 'Macaco', 'Leao', 'Zebra']
# courses.remove('History')
# print(courses) # ['Math', 'Physics', 'CompSci']
# popped = courses.pop()
# print(popped)
# print(courses) # ['History', 'Math', 'Physics']
# courses.reverse()
# print(courses) # ['CompSci', 'Physics', 'Math', 'History']
# courses.sort()
# print(courses) # ['CompSci', 'History', 'Math', 'Physics']
nums = [1, 5, 2, 4, 3]
# nums.sort()
# print(nums) # [1, 2, 3, 4, 5]
# courses.sort(reverse = True)
# nums.sort(reverse = True)
# print(courses) # ['Physics', 'Math', 'History', 'CompSci']
# print(nums) # [5, 4, 3, 2, 1]
# print(min(nums)) # 1
# rint(min(courses)) # CompSci
# print(max(nums)) # 5
# print(max(courses)) # Physics
# print(sum(nums)) # 15
# print(courses.index('CompSci')) # 3
# print('Art' in courses) # False
# print('Math' in courses) # True
# for item in courses:
# print(item) # History Math Physics CompSci
# for item in enumerate(courses):
# print(item)
# (0, 'History')
# (1, 'Math')
# (2, 'Physics')
# (3, 'CompSci')
for index, item in enumerate(courses, start = 1):
print(index, item)
# (1, 'History')
# (2, 'Math')
# (3, 'Physics')
# (4, 'CompSci')
courses_str = ', '.join(courses)
print(courses_str) # History, Math, Physics, CompSci
courses_str = ' - '.join(courses)
print(courses_str) # History - Math - Physics - CompSci
new_list = courses_str.split(' - ')
print(new_list) # ['History', 'Math', 'Physics', 'CompSci']
# mutaveis
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1
print(list_1)
print(list_2)
list_1[0] = 'Art'
print(list_1)
print(list_2)
# Imutaveis
tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# tuple_1[0] = 'Art' # Erro
print(tuple_1)
print(tuple_2)
# sets
cs_course = {'C', 'A', 'B', 'D'}
art_course = {'C', 'F', 'B', 'G'}
print(cs_course)
print("B" in cs_course)
print(cs_course.intersection(art_course))
print(cs_course.difference(art_course))
print(cs_course.union(art_course))
# cs_course[0] = 'Art' # 'set' object does not support item assignment
|
import random
l = [0, 1, 2]
new = zip("ABC", l)
print(new) # [('A', 0), ('B', 1), ('C', 2)]
new = map(lambda x: x * 10, l)
print(new) # [0, 10, 20]
new = filter(None, l)
print(new) # [1, 2]
# um gerador eh um objeto iteravel:
for par in zip('ABC', l):
print(par)
# para criar a lista, basta passar o gerador para o construtor
print(list(zip("ABC", l))) # [('A', 0), ('B', 1), ('C', 2)]
# varios construtores de colecoes aceitam iteraveis
print(dict(zip("ABC", l))) # 'A': 0, 'C': 2, 'B': 1}
# com expressao geradora
class Trem1(object):
def __init__(self, n):
self.vagoes = n
def __iter__(self):
return ('Vagao1 # %d' % (i + 1) for i in range(self.vagoes))
# com funcao geradora
class Trem2(object):
def __init__(self, n):
self.vagoes = n
def __iter__(self):
for i in range(self.vagoes):
yield 'Vagao2 # %d' % (i + 1)
def Trem3(vagoes):
for i in range(vagoes):
yield 'Vagao3 # %d' % (i + 1)
for vagao in Trem1(10): print(vagao)
for vagao in Trem2(10): print(vagao)
for vagao in Trem3(10): print(vagao)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib = fibonacci(10)
for i in range(10):
print(next(fib))
fib = list(fibonacci(10))
print(fib)
print(len(fib))
a, b, c = 'XYZ'
print(a, b, c)
g = (n for n in [1, 2, 3])
a, b, c = g
print(a, b, c)
print('-' * 100)
octetos = b'Python'
for oct in octetos:
print(oct)
print('-' * 100)
def d6():
return random.randint(0,6)
for dado in iter(d6, 6):
print(dado)
|
def greet_me(**kwargs):
if kwargs is not None:
for key, value in kwargs.iteritems():
print("%s == %s" % (key, value))
greet_me(name = "yasoob", idade = 30)
def table_things(**kwargs):
for name, value in kwargs.items():
print('{0} = {1}'.format(name, value))
table_things(
apple = 'fruta',
cabbage = 'vegetal'
)
def print_three_things(a, b, c):
print('a = {0}, b = {1}, c = {2}'.format(a, b, c))
mylist = ['aardvark', 'baboon', 'cat']
print_three_things(*mylist)
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print(value1, value2)
class MyFoo(Foo):
def __init__(self, *args, **kwargs):
# do something else, don't care about the args
print('myfoo')
super(MyFoo, self).__init__(*args, **kwargs)
alist = ['aardvark', 'baboon', 'cat']
MyFoo(alist, None)
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(
**locals()))
def sumFunction(*args):
result = 0
for x in args:
result += x
return result
num = [1, 2, 3, 4, 5]
soma = sumFunction(*num)
print(soma)
soma = sumFunction(3, 4, 6, 3, 6, 8, 9)
print(soma)
def someFunction(**kwargs):
if 'text' in kwargs:
print(kwargs['text'])
someFunction(text = "foo")
a = 'programar ou nao programar?'
a.replace('programar', 'ser')
print(a)
args = ['programar', 'ser']
# a.replace(args) # erro
a.replace(*args)
print(a)
def multiply(*args):
z = 1
for num in args:
z *= num
print(z)
multiply(4, 5)
multiply(10, 9)
multiply(2, 3, 4)
multiply(3, 5, 10, 6)
def print_kwargs(**kwargs):
print(kwargs)
print_kwargs(kwargs_1 = "Shark", kwargs_2 = 4.5, kwargs_3 = True)
def print_values(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
print_values(my_name = "Sammy", your_name = "Casey")
def print_values(**kwargs):
for key, value in kwargs.items():
print("The value of {} is {}".format(key, value))
print_values(
name_1 = "Alex",
name_2 = "Gray",
name_3 = "Harper",
name_4 = "Phoenix",
name_5 = "Remy",
name_6 = "Val"
)
def some_kwargs(kwarg_1, kwarg_2, kwarg_3):
print("kwarg_1:", kwarg_1)
print("kwarg_2:", kwarg_2)
print("kwarg_3:", kwarg_3)
kwargs = {"kwarg_1": "Val", "kwarg_2": "Harper", "kwarg_3": "Remy"}
some_kwargs(**kwargs)
print('#' * 80)
def print_everything(*args):
for count, thing in enumerate(args):
result = '{0}. {1}'.format(count, thing)
# print(result)
yield result
frutas = ['apple', 'banana', 'cabbage']
result = print_everything(*frutas)
print(result)
for i in result:
print (i)
|
#Import necessary module
from termcolor import colored
#Initialize a text variable
text = "Colored text using Python"
#Print the text with font and background colors
print(colored(text, 'red', 'on_cyan'))
|
""" DECORATORS
Nested Decorators
Class decorators
Note: Using functools.wraps retains original function's name and module
"""
from functools import wraps
def ex_decorator(func):
""" Decorator pattern """
@wraps(func)
def wrapper_decorator(*args, **kwargs):
# Do something before
value = func(*args, **kwargs)
# Do something after
return value
return wrapper_decorator
@ex_decorator
def test_function(num):
return num*num
print(test_function(5))
def try_several_times(no_attempts=5):
""" Decorator with keyword arg """
def decorator_try_func(func):
@wraps(func)
def wrap_try(*args, **kwargs):
vals = []
for i in range(no_attempts):
value = func(*args, **kwargs)
vals.append(value)
return vals
return wrap_try
return decorator_try_func
@try_several_times(no_attempts=5)
def print_a_word(word):
return word
print(print_a_word('now'))
def count_calls(func):
@wraps(func)
def wrapper_count_calls(*args, **kwargs):
wrapper_count_calls.num_calls += 1
print(f"Call {wrapper_count_calls.num_calls} of {func.__name__!r}")
return func(*args, **kwargs)
wrapper_count_calls.num_calls = 0
return wrapper_count_calls
def cache(func):
""" Keep a cache of previous function calls"""
@wraps(func)
def wrapper_cache(*args, **kwargs):
cache_key = args + tuple(kwargs.items())
if cache_key not in wrapper_cache.cache:
wrapper_cache.cache[cache_key] = func(*args, **kwargs)
return wrapper_cache.cache[cache_key]
wrapper_cache.cache = dict()
return wrapper_cache
@cache
@count_calls
def fibonacci(num):
if num < 2:
return num
return fibonacci(num - 1) + fibonacci(num - 2)
fibonacci(8)
""" JSON OBJECT VALIDATION """
from flask import Flask, request, abort
app = Flask(__name__)
def validate_json(*expected_args):
def decorator_validate_json(func):
@wraps(func)
def wrapper_validate_json(*args, **kwargs):
json_object = request.get_json()
for expected_arg in expected_args:
if expected_arg not in json_object:
abort(400)
return func(*args, **kwargs)
return wrapper_validate_json
return decorator_validate_json
import errno
import os
import signal
import time
def timeout(seconds=1, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wrapper
return decorator
# @timeout(seconds=1, error_message='too late')
@timeout()
def test():
time.sleep(4)
# test()
""" TIMEOUT CLASS IMPLEMENTATION
params:
- no_attempts
- list of acceptable exceptions
- total timeout
- timeout per attempt
"""
class TryMe:
def __init__(self, no_attempts=2, exc_list=[], tot_timeout=5, timeout_per_attempt=1):
self.no_attempts = no_attempts
self.exc_list = exc_list
self.tot_timeout = tot_timeout
self.timeout_per_attempt = timeout_per_attempt
self.error_msg_tot = 'total timed out'
self.error_msg = 'per attempt timed out'
def _handle_timeout_tot(self, signum, frame):
raise TimeoutError(self.error_msg_tot)
def _handle_timeout(self, signum, frame):
raise TimeoutError(self.error_msg)
def run_function(self, func, *args, **kwargs):
signal.signal(signal.SIGALRM, self._handle_timeout_tot)
signal.alarm(self.tot_timeout)
for i in range(self.no_attempts):
try:
result = self.run_single_attempt(func, args, kwargs)
except Exception as ex:
if type(ex) in self.exc_list:
continue
raise
else:
signal.alarm(signal.SIG_DFL)
return result
def run_single_attempt(self, func, args, kwargs):
# signal.signal(signal.SIGALRM, self._handle_timeout)
# signal.alarm(self.timeout_per_attempt)
signal.signal(signal.SIGPROF, self._handle_timeout)
signal.setitimer(signal.ITIMER_PROF, self.timeout_per_attempt)
try:
result = func(*args, **kwargs)
return result
finally:
signal.setitimer(signal.ITIMER_PROF, signal.SIG_DFL)
def return_word(word):
return word
def index_error_func():
test_list = [1, 2, 3]
return test_list[len(test_list)+1]
def sleep_func(time_to_sleep=5):
time.sleep(time_to_sleep)
return True
def divide(x, y):
return x / y
def sleep_divide(x, y, time_to_sleep):
time.sleep(time_to_sleep)
return x / y
def hang_func():
while True:
x = 1 + 1
def run_tests_class():
# Simple Example
assert(TryMe().run_function(return_word, 'word')) == 'word'
# Timeout
assert(TryMe().run_function(sleep_func, 0.5)) is True
# Simple Division
assert(TryMe().run_function(divide, 2, 1)) == 2.0
# Except an Error
assert(TryMe(exc_list=[ZeroDivisionError]).run_function(divide, 2, 0)) is None
# Pass Args
assert(TryMe(no_attempts=5, tot_timeout=5, timeout_per_attempt=1).run_function(sleep_func, 0.9)) is True
# Trigger Total Timeout
try:
TryMe(no_attempts=10, tot_timeout=3, exc_list=[ZeroDivisionError]).run_function(sleep_divide, 2, 0, 0.9)
except TimeoutError:
assert True
else:
assert False
# Per Attempt Timeout
try:
TryMe(timeout_per_attempt=0.5).run_function(hang_func)
except TimeoutError:
assert True
else:
assert False
# Unacceptable Exception
try:
TryMe().run_function(divide, '2', '1')
except TypeError:
assert True
else:
assert False
run_tests_class()
""" TIMEOUT DECORATOR IMPLEMENTATION """
def try_function(total_timeout=3, per_attempt_timeout=1, no_attempts=2, accepted_exceptions=[]):
def decorator(func):
def _handle_timeout_tot(signum, frame):
raise TimeoutError('Timed Out')
def _handle_timeout(signum, frame):
raise TimeoutError('Attempt Timed Out')
def _try_single_attempt(func, args, kwargs):
signal.signal(signal.SIGPROF, _handle_timeout)
signal.setitimer(signal.ITIMER_PROF, per_attempt_timeout)
try:
res = func(*args, **kwargs)
return res
finally:
signal.setitimer(signal.ITIMER_PROF, signal.SIG_DFL)
@wraps(func)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout_tot)
signal.alarm(total_timeout)
for i in range(no_attempts):
try:
result = _try_single_attempt(func, args, kwargs)
except Exception as ex:
if type(ex) in accepted_exceptions:
continue
raise
else:
signal.alarm(signal.SIG_DFL)
return result
# Alternatively:
# return wraps(func)(wrapper)
return wrapper
return decorator
print('Running Tests Class')
run_tests_class()
def run_tests_decorator():
# Simple Example
@try_function()
def return_word(word):
return word
assert return_word('word') == 'word'
# Timeout
@try_function()
def sleep_func(naptime):
time.sleep(naptime)
return True
assert sleep_func(0.5) is True
# Simple Division
@try_function()
def divide(x, y):
return x / y
assert divide(2, 1) == 2
# Except an Error
@try_function(accepted_exceptions=[ZeroDivisionError])
def divide_ex(x, y):
return x / y
assert divide_ex(2, 0) is None
# Pass Args
# assert(TryMe(no_attempts=5, tot_timeout=5, timeout_per_attempt=1).run_function(sleep_func, 0.9)) is True
@try_function(no_attempts=5, total_timeout=5, per_attempt_timeout=1)
def sleep_args(sleep_time):
time.sleep(sleep_time)
return True
assert sleep_args(0.9) is True
# Trigger Total Timeout
@try_function(no_attempts=10, total_timeout=3, accepted_exceptions=[ZeroDivisionError])
def sleep_divide_tot(x, y, naptime):
time.sleep(naptime)
return x / y
try:
# TryMe(no_attempts=10, tot_timeout=3, exc_list=[ZeroDivisionError]).run_function(sleep_divide, 2, 0, 0.9)
sleep_divide_tot(2, 0, 0.9)
except TimeoutError:
assert True
else:
assert False
# Per Attempt Timeout
@try_function(per_attempt_timeout=0.5)
def hang_func():
while True:
pass
try:
hang_func()
except TimeoutError:
assert True
else:
assert False
# Unacceptable Exception
@try_function()
def divide_ex2(x, y):
return x/y
try:
divide_ex2("2", "1")
except TypeError:
assert True
else:
assert False
print('Running Tests Decorator')
run_tests_decorator()
""" EXCEPTIONS """
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print('division by zero!')
else:
print('result is ', result)
finally:
print('executing finally clause')
""" GENERATORS """
def get_series_a_funds():
file_name = "techcrunch.csv"
lines = (line.rstrip() for line in open(file_name))
list_line = (s.split(",") for s in lines)
cols = next(list_line)
company_dicts = (dict(zip(cols, data)) for data in list_line)
funding = (
int(company_dict["raisedAmt"])
for company_dict in company_dicts
if company_dict["round"] == "a"
)
total_series_a = sum(funding)
print(f"Total series A fundraising: ${total_series_a}")
get_series_a_funds()
|
/* Task 1 */
def SomeFunction(n):
y = n**2 + 3*n + 1
return y
acc=0
for i in range(2, 6):
print(SomeFunction(i))
if i < 5:
print('+')
else:
print('=')
acc = acc + SomeFunction(i)
print(acc)
/* Task 2 */
import math
def taylor(x):
series = 0
for n in range (16):
z = ((-1)**n)*(x**(2*n))/(math.factorial(2*n))
series = series + z
return series
print('Pick any radian value of your choice:')
x = int(input())
print('The cosine of ' + str(x) +' is: ')
print(taylor(x))
/* Task 3 */
import math
def taylor(x):
series = 0
for n in range (16):
z = ((-1)**n)*(x**(2*n))/(math.factorial(2*n))
series = series + z
return series
def deg_rad(deg):
radians = deg * math.pi / 180
return radians
x = float(input('Pick any degree value of your choice:'))
x = deg_rad(x)
print('The cosine of ' + str(x) +', or your degree value put into radians, is: ')
print(taylor(x))
/* Task 4 */
import math
def taylor(x):
series = 0
for n in range(16):
z = ((-1)**n)*(x**(2*n))/(math.factorial(2*n))
series = series + z
return series
def deg_rad(deg):
radians = deg * math.pi / 180
return radians
print('Hello! Since I can calculate the cosine of any value you give me, do you prefer for me to use radians or degrees?')
decision1 = input('Type "rad" for Radians or "deg" for Degrees. ')
decision1 = decision1.lower()
if decision1 == "rad":
x = float(input('Please enter the value in radians:'))
elif decision1 == "deg":
x = float(input('Please enter the value in Degrees:'))
x = deg_rad(x)
print('The cosine of ' + str(x) +' is: ')
print(taylor(x))
/* Task 5 */
print('Hello! I will demonstrate the fibonacci sequence, if you give me the amount of numbers: ')
z = int(input())
def fib(n):
first = 1
second = 1
sum = 2
print (first)
print(second)
for i in range (n-2):
third = first + second
print (third)
first = second
second = third
sum = sum + third
print('The total sum of this equation is: ' + str(sum))
print('The numbers of this given sequence come out to: ')
fib(z)
/* Task 6 */
print('Enter the amount of numbers that you want added together after being multiplied by 3: ')
x = int(input())
def rec(n):
first = 1
rate = 3
sum = 1
print (first)
for i in range (n-1):
second = first * rate
print (second)
first = second
kiwi = first * rate
sum = sum + second
print('The sum of all these numbers is: ' + str(sum))
rec(x)
|
"""
Clone of 2048 game.
"""
import poc_2048_gui
from random import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1, 0),
LEFT: (0, 1),
RIGHT: (0, -1)}
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
# Control variable to limit additions to one occurence only
control = 5 * [True]
# copy the line to return_line with zeros
length = len(line)
return_line = line[:]
# remove zeroes
while (0 in return_line):
return_line.remove(0)
while (len(return_line) < length):
return_line.append(0)
# Start addition proces
for index_i in range(length - 1):
if return_line[index_i] != 0 and return_line[index_i] == return_line[index_i + 1] and control[index_i]:
return_line[index_i] = 2 * return_line[index_i];
control[index_i] = False
for index_l in range(index_i + 1, length - 1):
return_line[index_l] = return_line[index_l + 1]
return_line[-1] = 0
return return_line
class TwentyFortyEight:
"""
Class to run the game logic.
"""
def __init__(self, grid_height, grid_width):
"""init
"""
self.rows = grid_height
self.cols = grid_width
self.reset()
def reset(self):
"""
Reset the game so the grid is empty.
"""
self.grid = [[0 for dummy_x in range(self.cols)] for dummy_y in range(self.rows)]
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
return str(self.grid)
def get_grid_height(self):
"""
Get the height of the board.
"""
return self.rows
def get_grid_width(self):
"""
Get the width of the board.
"""
return self.cols
def move(self, direction):
"""
Move all tiles in the given direction and add
a new tile if any tiles moved.
"""
# copy the current grid
self.old_grid = [list(inner_list) for inner_list in self.grid]
if (direction == UP):
self.move_up()
elif (direction == DOWN):
self.move_down()
elif (direction == LEFT):
self.move_left()
else:
self.move_right()
# if the grid has changed, add a new tile
if (self.old_grid != self.grid):
self.new_tile()
def move_up(self):
"""
Move all tiles up
"""
for columns in range(0, self.cols, 1):
temp_list = []
for rows in range(0, self.rows, 1):
temp_list.append(self.grid[rows][columns])
# we have our list, let's merge
new_list = merge(temp_list)
# now put our new list back in grid
for rows in range(0, self.rows, 1):
self.grid[rows][columns] = new_list[rows]
def move_down(self):
"""
Move all tiles down
"""
for columns in range(0, self.cols, 1):
temp_list = []
for rows in range(self.rows - 1, -1, -1):
temp_list.append(self.grid[rows][columns])
# we have our list, let's merge
new_list = merge(temp_list)
# now put our new list back in grid
for rows in range(self.rows - 1, -1, -1):
self.grid[rows][columns] = new_list[self.rows - 1 - rows]
def move_left(self):
"""
Move all tiles left
"""
for rows in range(0, self.rows, 1):
temp_list = []
for columns in range(0, self.cols, 1):
temp_list.append(self.grid[rows][columns])
# we have our list, let's merge
new_list = merge(temp_list)
# now put our new list back in grid
for columns in range(0, self.cols, 1):
self.grid[rows][columns] = new_list[columns]
def move_right(self):
"""
Move all tiles right
"""
for rows in range(0, self.rows, 1):
temp_list = []
for columns in range(self.cols - 1, -1, -1):
temp_list.append(self.grid[rows][columns])
# we have our list, let's merge
new_list = merge(temp_list)
# now put our new list back in grid
for columns in range(self.cols - 1, -1, -1):
self.grid[rows][columns] = new_list[self.cols - 1 - columns]
def new_tile(self):
"""
Create a new tile in a randomly selected empty
square. The tile should be 2 90% of the time and
4 10% of the time.
"""
empty_spot_found = False
# check if there's an empty spot left
for list in self.grid:
if 0 in list:
empty_spot_found = True
while empty_spot_found:
# generate tile value
if random() < 0.9:
new_tile = 2
else:
new_tile = 4
# randomly pick a empty place on board
row = int(random() * self.rows)
col = int(random() * self.cols)
if self.grid[row][col] == 0:
self.grid[row][col] = new_tile
break
def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
self.grid[row][col] = value
def get_tile(self, row, col):
"""
Return the value of the tile at position row, col.
"""
return self.grid[row][col]
poc_2048_gui.run_gui(TwentyFortyEight(4, 4))
|
"""
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
class Puzzle:
"""
Class representation for the Fifteen puzzle
"""
def __init__(self, puzzle_height, puzzle_width, initial_grid=None):
"""
Initialize puzzle with default height and width
Returns a Puzzle object
"""
self._height = puzzle_height
self._width = puzzle_width
self._grid = [[col + puzzle_width * row
for col in range(self._width)]
for row in range(self._height)]
if initial_grid != None:
for row in range(puzzle_height):
for col in range(puzzle_width):
self._grid[row][col] = initial_grid[row][col]
def __str__(self):
"""
Generate string representaion for puzzle
Returns a string
"""
ans = ""
for row in range(self._height):
ans += str(self._grid[row])
ans += "\n"
return ans
#####################################
# GUI methods
def get_height(self):
"""
Getter for puzzle height
Returns an integer
"""
return self._height
def get_width(self):
"""
Getter for puzzle width
Returns an integer
"""
return self._width
def get_number(self, row, col):
"""
Getter for the number at tile position pos
Returns an integer
"""
return self._grid[row][col]
def set_number(self, row, col, value):
"""
Setter for the number at tile position pos
"""
self._grid[row][col] = value
def clone(self):
"""
Make a copy of the puzzle to update during solving
Returns a Puzzle object
"""
new_puzzle = Puzzle(self._height, self._width, self._grid)
return new_puzzle
########################################################
# Core puzzle methods
def current_position(self, solved_row, solved_col):
"""
Locate the current position of the tile that will be at
position (solved_row, solved_col) when the puzzle is solved
Returns a tuple of two integers
"""
solved_value = (solved_col + self._width * solved_row)
for row in range(self._height):
for col in range(self._width):
if self._grid[row][col] == solved_value:
return (row, col)
assert False, "Value " + str(solved_value) + " not found"
def update_puzzle(self, move_string):
"""
Updates the puzzle state based on the provided move string
"""
zero_row, zero_col = self.current_position(0, 0)
for direction in move_string:
if direction == "l":
assert zero_col > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col - 1]
self._grid[zero_row][zero_col - 1] = 0
zero_col -= 1
elif direction == "r":
assert zero_col < self._width - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row][zero_col + 1]
self._grid[zero_row][zero_col + 1] = 0
zero_col += 1
elif direction == "u":
assert zero_row > 0, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row - 1][zero_col]
self._grid[zero_row - 1][zero_col] = 0
zero_row -= 1
elif direction == "d":
assert zero_row < self._height - 1, "move off grid: " + direction
self._grid[zero_row][zero_col] = self._grid[zero_row + 1][zero_col]
self._grid[zero_row + 1][zero_col] = 0
zero_row += 1
else:
assert False, "invalid direction: " + direction
def legal_moves(self):
"""
Returns string with legal moves l,r,d,u
"""
answer = ''
zero_tile = self.current_position(0,0)
if zero_tile[0] != 0:
answer += 'u'
if zero_tile[1] != 0:
answer += 'l'
if zero_tile[0] != self._height -1:
answer += 'd'
if zero_tile[1] != self._width -1:
answer += 'r'
return answer
def solved(self):
"""
Check to see if puzzle is solved
"""
for row in range(self._height):
for col in range(self._width):
if (self.current_position(row, col) != (row, col)):
return False
return True
##################################################################
def solve_puzzle(self):
"""
Generate a solution string for a puzzle
Updates the puzzle and returns a move string
"""
import time
starttime = time.time()
# visited will be the set of board states that have already been considered. It uses board
# strings rather than boards to be sure duplicate boards are recognized as one
visited = set(str(self))
# Frontier is the set of visited puzzles whose children have not yet been explored. Frontier
# stores boards as puzzle items and their originating path
new_frontier = set([(self, 'x')]) # Start with 'x' to make redundancy detection easier
path_length_under_consideration = 0
if self.solved():
print ('Puzzle was already solved. No moves needed.')
return ''
while True:
### Refresh frontier, move to next solution length
old_frontier = new_frontier.copy()
new_frontier = set()
path_length_under_consideration += 1
### Running status updates (not operable in CodeSkulptor)
# print
# print 'Just refreshed the frontier.'
# print ' Running time:',round(time.time()-starttime)
# print ' Number of boards visited:', len(visited)
# print ' Length of frontier:', len(old_frontier)
# print ' Solution length under consideration:', path_length_under_consideration
for parent_tuple in old_frontier: # For each board in frontier, determine and consider children boards
possible_moves = parent_tuple[0].legal_moves()
for move in possible_moves:
if parent_tuple[1][-1] + move in ('ud', 'du', 'lr', 'rl'): # Check for move redundancy
pass
else:
child_puzzle = parent_tuple[0].clone() # Copy parent
child_puzzle.update_puzzle(move) # Make move
child_string = str(child_puzzle) # Make boardstring of new puzzle board
if child_string in visited: # If new board has already been considered, pass
pass
else: # This board state hasn't been previously visited.
if child_puzzle.solved(): # If child board is a solution, dance!
print ()
print ('WooHoo!')
print ('Time taken:', round(time.time() - starttime))
print ('Number of board states visited:', len(visited) + 1 )
print ('Solution length is', len(parent_tuple[1][1:]) + 1)
print ('Solution:',parent_tuple[1][1:] + move)
print ()
return parent_tuple[1][1:] + move
else: # Child board is not a solution. Add to visited list and to the new frontier
visited.add(child_string)
new_frontier.add((child_puzzle, parent_tuple[1] + move))
##################################################################
def scrambled_board(row, height, nummoves):
"""
Makes new puzzle and makes nummoves random moves.
"""
import random
jpuzz = Puzzle(row, height)
movecount = 0
movelist = 'x' # to streamline redundancy check
while movecount < nummoves:
while True:
move = random.choice(['u','d','l','r'])
if movelist[-1] + move not in ('du','ud','rl','lr'): # Avoid undoing the last move
break
try:
jpuzz.update_puzzle(move) # If move is legal, make it!
movelist += move
movecount += 1
except:
pass
print ('scrambling move count:', movecount)
print ('scrambling move list: ', movelist[1:])
return jpuzz
##################################################################
puzzle = scrambled_board(3,3,200) # Start with scrambled board
#poc_fifteen_gui.FifteenGUI(puzzle)
# Pearson challenge from discussion boards:
#puzzle=Puzzle(4,4,[[15,11,8,12],[14,10,9,13],[2,6,1,4],[3,7,5,0]]) # Needs 80 moves
sol=puzzle.solve_puzzle()
print (sol)
print (len(sol))
print (puzzle)
#Start interactive simulation
#poc_fifteen_gui.FifteenGUI(Puzzle(4, 4))
|
#to generate the text character by character after training the model
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import config as cf
import models as md
#importing tenserflow libraries
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM,Dense,Embedding,Dropout,GRU
from tensorflow.keras.losses import sparse_categorical_crossentropy
from tensorflow.keras.models import load_model
vocab= cf.vocab
#print(cf.length)
#From the above output we can infer that the entire text corpus consists of 84 unique characters.
#We know a neural network can't take in the raw string data,we need to assign numbers to each character.
# Let's create two dictionaries that can go from numeric index to character and character to numeric index.
char_to_ind = {u:i for i, u in enumerate(vocab)}
#print(char_to_ind)
#converting from index to character
ind_to_char = np.array(vocab)
#print(ind_to_char)
model=md.model
print(model.summary())
print("\n\n")
#code for generating text
def generate_text(model, start_seed,gen_size=100,temp=1.0):
'''
model: Trained Model to Generate Text
start_seed: Intial Seed text in string form
gen_size: Number of characters to generate
Basic idea behind this function is to take in some seed text, format it so
that it is in the correct shape for our network, then loop the sequence as
we keep adding our own predicted characters. Similar to our work in the RNN
time series problems.
'''
# Number of characters to generate
num_generate = gen_size
# Vecotrizing starting seed text
input_eval = [char_to_ind[s] for s in start_seed]
# Expand to match batch format shape
input_eval = tf.expand_dims(input_eval, 0)
# Empty list to hold resulting generated text
text_generated = []
# Temperature effects randomness in our resulting text
# The term is derived from entropy/thermodynamics.
# The temperature is used to effect probability of next characters.
# Higher probability == lesss surprising/ more expected
# Lower temperature == more surprising / less expected
temperature = temp
# Here batch size == 1
model.reset_states()
for i in range(num_generate):
# Generate Predictions
predictions = model(input_eval)
# Remove the batch shape dimension
predictions = tf.squeeze(predictions, 0)
# Use a cateogircal disitribution to select the next character
predictions = predictions / temperature
predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()
# Pass the predicted charracter for the next input
input_eval = tf.expand_dims([predicted_id], 0)
# Transform back to character letter
text_generated.append(ind_to_char[predicted_id])
return (start_seed + ''.join(text_generated))
print("\n\n")
#calling the function for generating text
print(generate_text(model,"flower",gen_size=1000))
|
from abc import ABC, abstractmethod
import requests
class HTTPRequestor(object):
"""The goal of the requestor object is to enable communication with a service in different ways.
The requestor needs to implement the CRUD methods.
Then the use would be as follows:
req = Requestor()
service = Service(req)
res = service.method()
where Service is defined something like:
def Service(requestor):
def __init__():
self.requestor = requestor
def method():
route = '/path/to/route'
res = self.requestor.get(route)
return res
The automation-infra implemented TunnelRequestor which enables interacting with a service via existing tunnel.
Other potential requestor could be a KongRequestor (to be implemented) or others as the need arises."""
@abstractmethod
def get(self, route, params=None, **kwargs) -> requests.Response:
"""route is the path of the url without the domainname"""
pass
@abstractmethod
def post(self, route, data=None, json=None, **kwargs) -> requests.Response:
pass
@abstractmethod
def put(self, route, data=None, **kwargs) -> requests.Response:
pass
@abstractmethod
def delete(self, route, **kwargs) -> requests.Response:
pass
@abstractmethod
def patch(self, url, data=None, **kwargs) -> requests.Response:
pass
class SimpleRequestor(HTTPRequestor):
def __init__(self, base_uri, verify_cert=False):
self.base_uri = base_uri
self.verify_cert = verify_cert
def build_url(self, route):
url = f"{self.base_uri}{route}"
return url
def get(self, route, params=None, **kwargs) -> requests.Response:
"""route is the path of the url without the domainname"""
return requests.get(self.build_url(route), params, verify=self.verify_cert, **kwargs)
def post(self, route, data=None, json=None, **kwargs) -> requests.Response:
return requests.post(self.build_url(route), data, json, verify=self.verify_cert, **kwargs)
def put(self, route, data=None, **kwargs) -> requests.Response:
return requests.put(self.build_url(route), data, verify=self.verify_cert, **kwargs)
def delete(self, route, **kwargs) -> requests.Response:
return requests.delete(self.build_url(route), verify=self.verify_cert, **kwargs)
def patch(self, route, data=None, **kwargs) -> requests.Response:
return requests.patch(self.build_url(route), data, verify=self.verify_cert, **kwargs)
|
import turtle
def drawSun():
"""
Draws a square, a circle, and then a triangle.
"""
def drawSquare(squareTurtle):
"""
Draws a white, filled square 100 pixels long with a white square cursor
"""
#color squareTurtle, its lines, and the filling of its square white, and make
#it a square
squareTurtle.color("white")
squareTurtle.pencolor("white")
squareTurtle.fillcolor("white")
squareTurtle.shape("square")
#tell python to fill following shapes drawn by squareTurtle
squareTurtle.begin_fill()
#have squareTurtle draw a square
for i in range(4):
#move forward 100 pixels
squareTurtle.forward(100)
#turn right 90 degrees
squareTurtle.right(90)
#Tells it that the shape is made so apply the filling
squareTurtle.end_fill()
def drawCircle(circleTurtle):
"""
Draws a blue unfilled circle with a blue circle cursor with radius 50px
"""
#color circleTurtle and its lines blue, and make it a circle
circleTurtle.color("blue")
circleTurtle.pencolor("blue")
circleTurtle.shape("circle")
#have circleTurtle make a circle of radius 50 pixels
circleTurtle.circle(50)
def drawTriangle(triangleTurtle):
"""
Draws an orange unfilled equilateral triangle with an orange triangle
cursor and sides 150px
"""
#color triangleTurtle and its lines orange, and make it a triangle
triangleTurtle.color("orange")
triangleTurtle.pencolor("orange")
triangleTurtle.shape("triangle")
#orient triangleTurtle away from other shapes
triangleTurtle.left(180)
#have triangleTurtle draw a triangle
for i in range(3):
#move forward 100 pixels
triangleTurtle.forward(150)
#turn left 120 degrees
triangleTurtle.left(120)
window = turtle.Screen()
window.bgcolor("gray") #color window background gray
brad = turtle.Turtle()
#draw 36 filled squares to make a sun
for i in range(36):
drawSquare(brad)
#turn right 10 degrees
brad.right(10)
#tell our window to close when clicked on
window.exitonclick()
drawSun()
|
def most_prolific(albums):
"""
Takes a dictionary with values formatted {'title': year} and returns
the year that occurs most often among the elements. IF there are years
that occur the same number of times, it returns a list of years.
years: dictionary. Holds the years albums were published and the number of
albums published in that year
most_prolific_years: list. Holds the years that tied for most albums
most_albums: integer. Holds the highest number of albums produced in a
single year.
"""
years = {} #dictionary that will hold our years and their number of occurences
most_prolific_years = [] #list to hold years that had the most albums
most_albums = 0 #value to hold the most albums produced in any one year
#for each element in our submitted dictionary, add its year to years with a
#count of one. If the year is already in years, add 1 to the count instead
for album in albums:
year = albums[album]
if year in years:
years[year] += 1
else:
years[year] = 1
#iterate through years to find highest count and set most_albums to that
#count
for year in years:
if years[year] > most_albums:
most_albums = years[year]
#add all years that qualify as most_albums to most_prolific_years
for year in years:
if years[year] == most_albums:
most_prolific_years.append(year)
if len(most_prolific_years) == 1:
return most_prolific_years[0]
else:
return most_prolific_years
|
import re
def create_cast_list(filename):
"""
Takes a cast list from IMDB and pulls a string up to the first comma
(actors' names), and puts that string into a list, which gets returned.
filename: txt file. The file containing the cast list
"""
cast_list = []
#use with to open the file filename
#use the for loop syntax to process each line
#and add the actor name to cast_list
regex = re.compile("[^,]*") #matches all values up to first comma
#open the file flying-circus-cast.txt
with open(filename) as txt:
#for each line in the file
for line in txt:
#use regex to find the characters up to the first comma, then export
#those characters as a string to cast_list
cast_list.append(regex.search(line).group())
return cast_list
print(create_cast_list("c:/version-control/learning-python/create-cast-list/flying-circus-cast.txt"))
|
class Node:
def __init__(self, x):
self.value = x
self.children = None
class Queue:
def __init__(self):
self.internal_ds = []
def enqueue(self, x):
if x is not None:
if isinstance(x, list):
self.internal_ds = self.internal_ds + x
elif isinstance(x, NodeLevel):
self.internal_ds = self.internal_ds + [x]
def dequeue(self):
if self.internal_ds:
popped = self.internal_ds[0]
self.internal_ds = self.internal_ds[1:]
return popped
def is_empty(self):
return False if self.internal_ds else True
def bfs(root):
if root is not None:
q = Queue()
q.enqueue(root)
while not q.is_empty():
e = q.dequeue()
print('exploring: ', e.value)
if e.children:
q.enqueue(e.children)
class NodeLevel:
def __init__(self, node, level):
self.node = node
self.level = level
def mod_bfs(root):
if root is not None:
q = Queue()
q.enqueue(NodeLevel(root, 1))
ret = []
while not q.is_empty():
e = q.dequeue()
if e.level - 1 < len(ret):
ret[e.level- 1].append(e.node.value)
else:
ret.append([e.node.value])
if e.node.children:
q.enqueue([NodeLevel(x, e.level + 1) for x in e.node.children])
return ret
'''
a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')
e = Node('e')
f = Node('f')
g = Node('g')
h = Node('h')
a.children = [b, c]
b.children = [d, e]
c.children = [f, g]
e.children = [h]
'''
a = Node(1)
b = Node(3)
c = Node(2)
d = Node(4)
e = Node(5)
f = Node(6)
g = Node(10)
h = Node(11)
i = Node(20)
a.children = [b, c, d]
b.children = [e, f]
c.children = [g]
g.children = [h]
d.children = [i]
# bfs(a)
print(mod_bfs(a))
|
if __name__ == "__main__":
string = input()
parts = input().split()
string_as_list = list(string)
index = int(parts[0])
print("".join(string_as_list[:index] + [parts[1]] + string_as_list[index+1:]))
|
tuple = (4, 'one item', -8)
def print_all(t):
for item in t:
print(item, end=' ')
print()
# sort() doesn't work on tuple
def sort_tuple(t):
t.sort()
print_all(tuple)
print(len(tuple))
print(tuple[0])
print(tuple[len(tuple)-1])
print_all((1, 2, 3, tuple))
print(tuple[0])
# sort_tuple(tuple)
print_all(tuple)
# tuples are not deletable
# del tuple[0]
print_all(tuple)
|
if __name__ == "__main__":
command_cnt = int(input())
lst = []
while command_cnt:
parts = input().split()
cmd = parts[0]
if cmd == "insert":
index = int(parts[1])
element_to_insert = int(parts[2])
lst = lst[:index] + [element_to_insert] + lst[index:]
elif cmd == "print":
print(lst)
elif cmd == "remove":
lst.remove(int(parts[1]))
elif cmd == "append":
lst = lst + [int(parts[1])]
elif cmd == "sort":
lst.sort()
elif cmd == "pop":
lst.pop()
else:
lst.reverse()
command_cnt = command_cnt - 1
|
def sort_by_first_element_then_by_():
q = [[1, 'd'], [0, 'b'], [1, 'c']]
print(q)
print(sorted(q, key=lambda x: (x[0], x[1])))
if __name__ == "__main__":
# sort_by_first_element_then_by_()
stdnt_cnt = int(input())
stdnt_list = []
while stdnt_cnt:
stdnt_list.append([input(), float(input())])
stdnt_cnt = stdnt_cnt - 1
# print(sorted(stdnt_list, key=lambda x: (-x[1], x[0])))
sorted_by_grade = sorted(stdnt_list, key=lambda x: (x[1], x[0]))
# print(sorted_by_grade[1][0], sorted_by_grade[2][0], end=' ')
second_lowest_grade = sorted(set([x[1] for x in sorted_by_grade]))[1]
# print(*[x[0] for x in sorted_by_grade if x[1] == second_lowest_grade], end='\n')
second_lowest_grade_scorers = [x[0] for x in sorted_by_grade if x[1] == second_lowest_grade]
for x in second_lowest_grade_scorers:
print(x)
|
import os
def write_to_file(lines, file_name):
if lines:
with open(file_name, 'w+') as f:
new_line = '\r\n'
for x in lines:
f.write(x + new_line)
f.write(new_line)
def copy_and_remove(file_to_copy):
import shutil
import os
shutil.copy(file_to_copy, 'text-file.txt')
os.remove(file_to_copy)
print(os.getcwd())
os.system('mkdir internal-dir')
os.chdir('internal-dir')
# get working directory
print(os.getcwd())
# change directory
os.chdir('./..')
os.rmdir('internal-dir')
# list given directory contents
print(os.listdir('./'))
print("dir(...)")
# print(dir(os))
import shutil
temp_file_name = 'temp-file.txt'
write_to_file(['asdf', 'vtpo'], temp_file_name)
# copy_and_remove(temp_file_name)
shutil.move(temp_file_name, 'text-file.txt')
import glob
# print(os.listdir('*.py'))
# wildcard can't be used with os.listdir(...)
print(glob.glob('./*.txt'))
|
from collections import deque
if __name__ == "__main__":
n = int(input())
dq = deque()
for _ in range(n):
parts = input().split()
op, v = parts[0], int(parts[1]) if len(parts) == 2 else None
if op == "append" and v is not None:
dq.append(v)
elif op == "pop":
dq.pop()
elif op == "popleft":
dq.popleft()
elif op == "appendleft" and v is not None:
dq.appendleft(v)
for x in dq:
print(x, end=' ')
|
import copy
class GoodBus():
def __init__(self, passengers):
self._passengers = copy.deepcopy(passengers) if passengers else []
def pick(self, p):
if p:
self._passenger.append(p)
def drop(self, p):
if p:
self._passengers.remove(p)
def __repr__(self):
return " ".join(map(str, self._passengers))
class HauntedBus():
# default list will be shared between multiple instances of HauntedBus
def __init__(self, passengers = []):
self._passengers = passengers
def pick(self, passenger):
self._passengers.append(passenger)
def drop(self, passenger):
self._passengers.remove(passenger)
def __repr__(self):
return " ".join(map(str, self._passengers))
def issue_with_default_function_argument():
b = HauntedBus(['charles'])
b.pick('osborn')
print(b)
c = HauntedBus()
c.pick('charles')
q = HauntedBus()
q.pick('james')
print(c, q)
print(dir(HauntedBus.__init__))
# following shows __defaults__ has empty list already populated
print(HauntedBus.__init__.__defaults__)
# both objects share the same underlying list
print(HauntedBus.__init__.__defaults__[0] is c._passengers, HauntedBus.__init__.__defaults__[0] is q._passengers)
def check_modifying_list():
passengers = ['charles', 'beki']
b = HauntedBus(passengers)
print(b)
# this will modify 'passengers' list also
b.drop('charles')
b.pick('jemmy')
print(b, passengers)
def func(a):
a = 78
print(a)
def f(a, b):
a += b
def test():
x, y = 10, 40
# will not have any impact on original value
f(x, y)
p, q = [9, 88], [67, 76]
# will modify the list as lists are mutable
f(p, q)
r, s = ('a', 'b'), ('t', 'y')
# will not have any impact on tuple as tuples are immutable
f(r, s)
print(x, y)
print(p, q)
print(r, s)
def test_good_bus():
passengers = ['charles', 'johny']
b = GoodBus(passengers)
hb = HauntedBus(passengers)
print(b)
# this will have impact on underlying data type of Bus
passengers.append('osborn')
print(b, hb)
def initialize_wth_tuple():
print(GoodBus((1, 3)))
print(HauntedBus((1, 2)))
test()
func(6)
issue_with_default_function_argument()
check_modifying_list()
test_good_bus()
initialize_wth_tuple()
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
# 9
# 1 2 3 4 5 6 7 8 9
# 10 11 21 55
# 1 2 3 4 5 6 7 8 9 10 11 21 55
input()
list_one = set(input().split())
input()
list_two = set(input().split())
unioned = list_one.union(list_two)
print(len(unioned))
|
import collections
def convert_to_collection(iterator):
if iterator:
return collections.Counter(iterator)
def find_uniqueness(seq):
if seq:
for _, count in collections.Counter(seq).items():
if count > 1:
return False
return True
return None
def find_uniqueness_using_dic(seq):
if seq:
dic = {}
for x in seq:
if x in dic:
return False
else:
dic[x] = 1
return True
return None
print(find_uniqueness([1, 2, 3, 3, 2, 1]))
print(find_uniqueness([1, 2, 3]))
print(find_uniqueness([1]))
print(find_uniqueness([1, 1]))
print()
print(find_uniqueness_using_dic([1, 2, 3, 3, 2, 1]))
print(find_uniqueness_using_dic([1, 2, 3]))
print(find_uniqueness_using_dic([1]))
print(find_uniqueness_using_dic([1, 1]))
def test_code():
print(convert_to_collection([1, 2, 3, 3, 2, 1]))
c = convert_to_collection(['q', 'r', 's', 's', 'r', 'q'])
for x in c.items():
print(x)
test_code()
|
class Solution(object):
def getConcatenation(self, nums):
if nums:
i = 0
l = len(nums)
while i < l:
nums.append(nums[i])
i = i + 1
return nums
s = Solution()
assert s.getConcatenation([1]) == [1, 1]
assert s.getConcatenation([1, 2]) == [1, 2, 1, 2]
assert s.getConcatenation([1,3,2,1]) == [1,3,2,1,1,3,2,1]
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def traverse_leaf(self, tree_root):
if not tree_root:
return None
else:
left_ret = self.traverse_leaf(tree_root.left)
right_ret = self.traverse_leaf(tree_root.right)
if not left_ret and not right_ret:
return [tree_root.val]
elif not left_ret:
return right_ret
elif not right_ret:
return left_ret
else:
return left_ret + right_ret
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
if root1 and root2:
left_leaves = self.traverse_leaf(root1)
right_leaves = self.traverse_leaf(root2)
# print(left_leaves, right_leaves)
return left_leaves == right_leaves
# left subtree
a = TreeNode(3)
b = TreeNode(5)
c = TreeNode(1)
d = TreeNode(6)
e = TreeNode(2)
f = TreeNode(7)
g = TreeNode(4)
h = TreeNode(9)
i = TreeNode(8)
a.left = b
a.right = c
b.left = d
b.right = e
e.left = f
e.right = g
c.left = h
c.right = i
# right subtree
_a = TreeNode(0)
_b = TreeNode(6)
_c = TreeNode(0)
_d = TreeNode(7)
_e = TreeNode(0)
_f = TreeNode(4)
_g = TreeNode(0)
_h = TreeNode(9)
_i = TreeNode(8)
_a.left = _b
_a.right = _c
_c.left = _d
_c.right = _e
_e.left = _f
_e.right = _g
_g.left = _h
_g.right = _i
s = Solution()
print(s.leafSimilar(a, _a))
# print(s.traverse_leaf(_a))
|
class MyQueue:
def __init__(self):
self.internal_stack = []
def push(self, x):
self.internal_stack.append(x)
def pop(self):
popped_element = self.internal_stack[:1]
self.internal_stack[:] = self.internal_stack[1:]
return popped_element[0] if popped_element else None
def peek(self):
first_element_arr = self.internal_stack[:1]
return first_element_arr[0] if first_element_arr else None
def empty(self):
return len(self.internal_stack) == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
queue = MyQueue()
queue.push(1)
queue.push(2)
print(queue.peek())
print(queue.pop())
print(queue.empty())
print(queue.internal_stack)
print(queue.pop())
print(queue.internal_stack)
print(queue.pop())
print(queue.internal_stack)
print(queue.peek())
|
def loop(n):
if n is not None:
return [x * x for x in range(n)]
if __name__ == "__main__":
n = int(input())
for x in loop(n):
print(x)
|
class Solution:
def is_alphanumeric(self, c):
c = c.lower()
return (ord(c) >= 97 and ord(c) <= 122) or (ord(c) >= 48 and ord(c) <= 57)
def isPalindrome(self, s):
if s is not None:
s = list(s)
head = 0
tail = len(s) - 1
while head < tail:
while head < len(s) and not self.is_alphanumeric(s[head]):
head = head + 1
while tail >= 0 and not self.is_alphanumeric(s[tail]):
tail = tail - 1
if head < len(s) and tail >= 0 and s[head].lower() != s[tail].lower():
return False
head = head + 1
tail = tail - 1
return True
s = Solution()
'''
print(s.isPalindrome("A man, a plan, a canal: Panama"))
print(s.isPalindrome("race a car"))
'''
print(s.isPalindrome(".,"))
print(s.isPalindrome("0P"))
|
'''
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
'''
class Solution(object):
def removeDuplicates_new(self, s):
if s is not None:
stck = []
i = 0
while i < len(s):
if len(stck) > 0:
top = stck[len(stck) - 1]
if s[i] == top:
stck = stck[:len(stck) - 1]
else:
stck.append(s[i])
else:
stck.append(s[i])
i = i + 1
return "".join(stck)
def removeDuplicates(self, s):
if s is not None:
stck = []
i = 0
while i < len(s):
if len(stck) > 0:
top = stck[len(stck) - 1]
if s[i] == top:
while i < len(s) and s[i] == top:
i = i + 1
stck = stck[:len(stck) - 1]
else:
stck.append(s[i])
i = i + 1
else:
stck.append(s[i])
i = i + 1
if len(stck) == 0:
stck = s[0]
return "".join(stck)
s = Solution()
print(s.removeDuplicates_new("aaaaaaaa"))
print(s.removeDuplicates_new("aaaaaaaaa"))
|
'''
Converts various weightings between 0 and 100 to an actual amount to stress particular resource to
ALL UNITS IN BITS
All functions accept:
1.) Current allocation of resource
2.) Percentage to change resource.
- A positive number means to increase the resource provisioning by a certain amount.
- A negative numbers means to decrease the resource provisioning by a certain amount
Returns the new bandwdith
'''
from modify_resources import *
from remote_execution import *
# Change the networking capacity
# Current Capacity in bits/p
def weighting_to_net_bandwidth(weight_change, current_alloc):
new_bandwidth = current_alloc + ((weight_change / 100.0) * current_alloc)
assert new_bandwidth > 0
return int(new_bandwidth)
# Change the weighting on the blkio
# Conducted for the disk stressing
def weighting_to_blkio(weight_change, current_alloc):
#+10 because blkio only accepts values between 10 and 1000
#Lower weighting must have lower bound on the blkio weight allocation
new_blkio = current_alloc + int((weight_change / 100.0) * current_alloc + 10)
assert new_blkio > 0
return int(new_blkio)
# Change the weighting of the CPU Quota
# TODO: Extend this to type of stressing to multiple cores
# Assumes a constant period
def weighting_to_cpu_quota(weight_change, current_alloc):
# We divide by 100 because CPU quota allocation is given as percentage
new_quota = current_alloc + int(current_alloc * weight_change/100.0)
assert new_quota > 0
return int(new_quota)
# Alternative method of changing the CPU stresing
# Reduces the number of cores
# This is a special case, unlike the other types of stressing
def weighting_to_cpu_cores(weight_change, current_alloc):
assert current_alloc > 0
new_cores = round(current_alloc + (weight_change / 100.0) * current_alloc)
if new_cores == current_alloc:
if weight_change < 0:
new_cores = current_alloc - 1
else:
new_cores = current_alloc + 1
return new_cores
# This probably belongs in a different function
# Leaving here for convenience
def get_num_cores(ssh_client):
num_cores_cmd = 'nproc --all'
_, stdout, _ = ssh_client.exec_command(num_cores_cmd)
return int(stdout.read())
|
from random import *
import os
def enemy_score_gen():
enemy_score = randint(1,21)
return enemy_score
def random_card_picker():
card_value = randint(1, 11)
return card_value
def game_starting():
global decision
print("Hello in blackjack! Your goal in blackjack is to get higher score then computer and don't pass 21 points. Do you want to draw a card")
print("1. Yes!")
print("2. No")
decision = input()
card = 0
crossing_point = False
game_starting()
if decision == "1":
os.system("cls")
while True:
print(f"Your score is {card}")
print("Do you want to draw a card?")
print("1. Yes!")
print("2. No")
in_game_decision = input()
if in_game_decision == "1":
os.system("cls")
card = card + random_card_picker()
else:
break
if card > 21:
print(f"Your points: {card}")
print("You accrosed 21 point. You lost!")
crossing_point = True
break
#Resultats
if crossing_point == False:
if card > enemy_score_gen():
print(f"Your score: {card}")
print(f"Enemy score: {enemy_score_gen()}")
print("You won congratulation!")
elif enemy_score_gen() > card:
print(f"Your score: {card}")
print(f"Enemy score: {enemy_score_gen()}")
print("You lost. Try again!")
elif enemy_score_gen() == card:
print(f"Your score: {card}")
print(f"Enemy score: {enemy_score_gen()}")
print("Tie! Try again!")
else:
exit
elif decision == "2":
exit
|
import sys
#print "Nbr args : %d" % (len(sys.argv))
if len(sys.argv)>=3:
readfrom=sys.argv[1]
writeto=sys.argv[2]
else:
print("Syntax: python %s <file_to_read> <file_to_write> [<id_label> <rest_of_cols> ['<char_sep>'] ]" % sys.argv[0])
print(" <rest_of_cols> : columns to include in output file (ex: 1,2,3), starting in 1. Use - for including all.")
exit(0)
if len(sys.argv)>=5:
label=int(sys.argv[3])
rest=sys.argv[4]
if len(sys.argv)>=6:
char_sep = sys.argv[5]
else:
char_sep = ' '
else:
label=1
rest="-"
char_sep = ' '
if rest!="-" :
some_cols=True
id_cols=rest.rstrip().split(",")
else:
some_cols=False
g = open(writeto, 'w')
print("Character separation: [%c]"%char_sep)
with open(readfrom, "r") as f:
for line in f:
cols = line.rstrip().split(char_sep)
if label>len(cols) :
print("ERROR, indicated column for label does not exist (%d columns detected in file)"% len(cols))
if cols[0].find("#") != -1 :
continue
cad='%s ' % (cols[label-1])
#raw_input("[%s]"% cad)
index=1
ind_w=1
for item in cols:
if (some_cols==True and (str(index) in id_cols)==False):
add = ""
elif (index==label):
add = ""
elif index!=label:
add = "%d:%s " % (ind_w,item)
ind_w=ind_w+1
index=index+1
if index-1 == 1 : # 1st col is nbr line
continue
if '\n' in item:
raw_input("ERROR: There should be no \n in item")
try:
if float(item)==0.:
continue
except ValueError:
continue
cad = cad + add
#g.write(cad+'\r')
g.write(cad+"\n")
print(cad)
#g.write('\r')
f.close()
g.close() |
v=[[1, 1], [2, 2], [1, 2]]
v2=[[1, 4], [3, 4], [3, 10]]
def solution(v):
x=list()
y=list()
for i in range(len(v[0])):
for j in range(len(v)):
if i==0:
x.append(v[j][i])
elif i==1:
y.append(v[j][i])
print(y)
result=list()
try:
remove=x.index(x[0],1)
x.pop(remove)
x.pop(0)
result.append(x[0])
except Exception:
result.append(x[0])
try:
remove=y.index(y[0],1)
y.pop(remove)
y.pop(0)
result.append(y[0])
except Exception:
result.append(y[0])
return result
print(solution(v2)) |
triangle=[[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]
def solution(triangle):
sum=[[0]*len(line) for line in triangle]
for i in range(len(triangle)):
for j in range(len(triangle[i])):
if(j==0):
sum[i][j]=sum[i-1][j]+triangle[i][j]
elif(i==j):
sum[i][j]=sum[i-1][j-1]+triangle[i][j]
else:
sum[i][j]=max(sum[i-1][j-1],sum[i-1][j])+triangle[i][j]
answer=max(sum[-1])
return answer
print(solution(triangle))
|
def fibo(num):
F=[0]*num
if num>0:
F[1]=1
for i in range(2,num):
F[i]=F[i-1]+F[i-2]
return F
if __name__ == "__main__":
max_num=15
Fibo_num=fibo(max_num+1)
for i in range(max_num+1):
print("Fibo( {}) = {}".format(i,Fibo_num[i]))
|
import turtle as t
import random as rd
height=300
width=300
def draw_screen():
screen=t.Turtle(visible=False)
screen.speed("fastest")
screen.penup()
screen.goto(-width,-height)
p=screen.pos()
screen.write(str(p),False)
screen.pendown()
screen.goto(width,-height)
p=screen.pos()
screen.write(str(p),False)
screen.goto(width,height)
p=screen.pos()
screen.write(str(p),False)
screen.goto(-width,height)
p=screen.pos()
screen.write(str(p),False)
screen.goto(-width,-height)
#https://m.blog.naver.com/PostView.nhn?blogId=mk1017sh&logNo=221593855270&proxyReferer=https:%2F%2Fwww.google.com%2F 터틀연습
class Turtle():
MAX=100
MIN=1
def __init__(self,color,num,shape='classic'):
self.color=color
self.num=num
self.T=t.Turtle()
self.shape=shape
self.T.turtlesize(0.5,0.5)
self.T.shape(self.shape)
self.T.pencolor(self.color)
self.T.speed('fastest')
self.T.fillcolor(self.color)
#https://stackoverflow.com/questions/14713037/python-turtle-set-start-position 시작위치
def __set_pos(self):
self.T.penup()
self.T.goto(rd.randint(-width/2,width/2),rd.randint(-height/2,height/2))
self.T.pendown()
#https://wikidocs.net/20396 터틀연습
#https://stackoverflow.com/questions/48123809/how-to-display-turtle-coordinates-on-the-canvas 좌표그리기
def draw(self,strmp=False,penup=False):
self.__set_pos()
for _ in range(self.num):
if penup==True:
self.T.penup()
if strmp==True:
self.T.stamp()
move=rd.randint(self.MIN,self.MAX)
angle=rd.randint(0,360)
self.T.right(angle)
self.T.forward(move)
x,y=self.T.position()
if abs(x)>=width-100 or abs(y)>=height-100:
self.T.goto(rd.randint(-width/2,width/2),rd.randint(-height/2,height/2))
coordinate="("+str('%.1f'%x)+","+str('%.1f'%y)+")"
self.T.write(coordinate,False)
if __name__ == "__main__":
draw_screen()
color_list=["black","red","blue","green","gray","pink"]
for i in color_list:
TT=Turtle(i,20,"turtle")
TT.draw(True,True)
t.done()
|
def Divisors(num):
divisors=list()
# 항상 범위 생각할것
for i in range(1,num+1):
if num%i==0:
divisors.append(i)
return divisors
def Perfect_Numbers(num):
perfect_nums=list()
for i in range(2,num):
temp=Divisors(i)
if temp.pop()==sum(temp):
print("Find perfect num :",sum(temp),"show list :",temp,"sum of divisors :",sum(temp))
perfect_nums.append(sum(temp))
return perfect_nums
if __name__=="__main__":
Range_num=10000
Perfect_Numbers(Range_num) |
## These are the steps that need to be followed
## Write out the pairs and singles
## Put the pairs above the single column
## If this is a valid partition, you're done, otherwise
## Shift the stuff below the pairs that are less than (3, 4, 6 ... 2, 5)
## the greatest left element of the pairs upwards, pushing stuff out as you go
## If there's an issue in the second row, resolve it now by bubbling
## similar to the first row
## Use gravity up, then left (assuming 3 rows)
##
##
##
##
## Takes [[1, 1, 2, 3, 4, 5, 5, 8], [2, 3, 4, 6, 6, 7, 7, 8]] <- MOT
## 1 3 6 7
## 2 5
## 4
## Goes to
##
## [[1, 3, 6, 7], [2, 5], [4]]
##
def bijection(MOT):
"""Takes a list with two sub-lists and transforms it into a SYT with 3 rows"""
return final_gravity(bubble_two(bubble_one(initial_transform(MOT))))
def initial_transform(MOT): # Verified
"""Transforms a MOT into a pseudo-SYT with pairs and singles"""
pairs = [[], []]
singles = []
top = MOT[0]
bot = MOT[1]
for i in range(1, 1+len(top)):
if i in top and i in bot:
singles.append(i)
elif i in top:
pairs[0].append(i)
else:
pairs[1].append(i)
final = rectify([pairs[0]+singles, pairs[1], []])
return final
def rectify(SYT): # Verified
"""Turns an SYT into the same SYT with Nones to make it a rect"""
max_len = max(len(SYT[0]), len(SYT[1]), len(SYT[2]))
top_row = SYT[0] + [None for i in range(max_len-len(SYT[0]))]
mid_row = SYT[1] + [None for i in range(max_len-len(SYT[1]))]
bot_row = SYT[2] + [None for i in range(max_len-len(SYT[2]))]
return [top_row, mid_row, bot_row]
'''def bubble_one(SYT): # Uses a rectified SYT, verified # Make efficient
"""The first bubbling step that moves the singles up"""
top_row = SYT[0]
mid_row = SYT[1]
bot_row = SYT[2]
while top_row != sorted(top_row):
for i, item in enumerate(top_row[:-1]):
if item > top_row[i+1]: # This means item 1+i is in the wrong place and should be bubbled
#print(top_row[i+1])
#print(top_row, mid_row, bot_row)
new_top_row = SYT[0]
new_mid_row = SYT[1]
new_bot_row = SYT[2] # Shifting begins here
new_bot_row[i] = new_mid_row[i]
new_mid_row[i] = new_top_row[i]
new_top_row[i] = new_top_row[i+1]
new_top_row[i+1] = new_mid_row[i+1]
new_mid_row[i+1] = new_bot_row[i+1]
new_bot_row[i+1] = None
#print(top_row, mid_row, bot_row)
while None in new_top_row: # Removes Nones from top row and all other rows in equal quantity
new_top_row = remove_final(new_top_row, None)
new_mid_row = remove_final(new_mid_row, None)
new_bot_row = remove_final(new_bot_row, None)
top_row = new_top_row
mid_row = new_mid_row
bot_row = new_bot_row
#print(top_row, mid_row, bot_row)
break
#print([top_row, mid_row, bot_row])
return [top_row, mid_row, bot_row]'''
def bubble_one(SYT): # Uses a rectified SYT, verified # Made efficient
"""The first bubbling step that moves the singles up"""
top_row = SYT[0]
mid_row = SYT[1]
bot_row = SYT[2]
while top_row != sorted(top_row):
for i, item in enumerate(top_row[:-1]):
if item > top_row[i+1]: # This means item 1+i is in the wrong place and should be bubbled
#print(top_row[i+1])
#print(top_row, mid_row, bot_row) # Shifting begins here
bot_row[i] = mid_row[i]
mid_row[i] = top_row[i]
top_row[i] = top_row[i+1]
top_row[i+1] = mid_row[i+1]
mid_row[i+1] = bot_row[i+1]
bot_row[i+1] = None
#print(top_row, mid_row, bot_row)
while None in top_row: # Removes Nones from top row and all other rows in equal quantity
top_row = remove_final(top_row, None)
mid_row = remove_final(mid_row, None)
bot_row = remove_final(bot_row, None)
#print(top_row, mid_row, bot_row)
break
#print([top_row, mid_row, bot_row])
return [top_row, mid_row, bot_row]
def remove_final(array, val): # Make efficient
"""Returns the list where the final instance of val has been removed"""
array.reverse()
array.remove(val)
array.reverse()
return array
'''def bubble_two(SYT): # Uses a rectified SYT
"""The second bubbling step that fixes row two"""
mid_row = SYT[1]
bot_row = SYT[2]
while None in mid_row: # Removes Nones from top row and all other rows in equal quantity
mid_row = remove_final(mid_row, None)
bot_row = remove_final(bot_row, None)
while mid_row != sorted(mid_row):
for i, item in enumerate(mid_row[:-1]):
if item > mid_row[i+1]: # This means item 1+i is in the wrong place and should be bubbled
#print(top_row[i+1])
#print(top_row, mid_row, bot_row)
new_mid_row = SYT[1]
new_bot_row = SYT[2] # Shifting begins here
new_bot_row[i] = new_mid_row[i]
new_mid_row[i] = new_mid_row[i+1]
new_mid_row[i+1] = new_bot_row[i+1]
new_bot_row[i+1] = None
#print(top_row, mid_row, bot_row)
while None in new_mid_row: # Removes Nones from top row and all other rows in equal quantity
new_mid_row = remove_final(new_mid_row, None)
new_bot_row = remove_final(new_bot_row, None)
mid_row = new_mid_row
bot_row = new_bot_row
#print(top_row, mid_row, bot_row)
break
return [SYT[0], mid_row, bot_row]'''
def bubble_two(SYT): # Uses a rectified SYT
"""The second bubbling step that fixes row two"""
mid_row = SYT[1]
bot_row = SYT[2]
while None in mid_row: # Removes Nones from top row and all other rows in equal quantity
mid_row = remove_final(mid_row, None)
bot_row = remove_final(bot_row, None)
while mid_row != sorted(mid_row):
for i, item in enumerate(mid_row[:-1]):
if item > mid_row[i+1]: # This means item 1+i is in the wrong place and should be bubbled
#print(top_row[i+1])
#print(top_row, mid_row, bot_row) # Shifting begins here
bot_row[i] = mid_row[i]
mid_row[i] = mid_row[i+1]
mid_row[i+1] = bot_row[i+1]
bot_row[i+1] = None
#print(top_row, mid_row, bot_row)
while None in mid_row: # Removes Nones from top row and all other rows in equal quantity
mid_row = remove_final(mid_row, None)
bot_row = remove_final(bot_row, None)
#print(top_row, mid_row, bot_row)
break
return [SYT[0], mid_row, bot_row]
def final_gravity(SYT): # Uses a rectified SYT
"""Does the gravity step to finish the partition""" # Removes all None
new_SYT = SYT
while None in new_SYT[0] + new_SYT[1] + new_SYT[2]:
if None in new_SYT[2]:
new_SYT[2].remove(None)
if None in new_SYT[1]:
new_SYT[1].remove(None)
if None in new_SYT[0]:
new_SYT[0].remove(None)
return new_SYT
def valid_SYT(SYT):
"""Checks is SYT is valid"""
if not ((sorted(SYT[0]) == SYT[0]) and (sorted(SYT[1]) == SYT[1]) and (sorted(SYT[2]) == SYT[2])): # Checks if rows are sorted
print(SYT)
return False
if len(SYT) != 3: # Checks for 3 or less rows
print(SYT)
return False
for col in felxible_zip(SYT[0], SYT[1], SYT[2]): # Checks if columns are sorted
if not (list(col) == sorted(col)):
print(SYT)
return False
return True
def felxible_zip(l1, l2, l3):
"""Assumes l1 >= l2 >= l3"""
while min(len(l1), len(l2), len(l3)) > 0:
yield (l1.pop(0), l2.pop(0), l3.pop(0))
while min(len(l1), len(l2)) > 0:
yield (l1.pop(0), l2.pop(0))
while len(l1) > 0:
yield (l1.pop(0),)
def MOT_Gen(size, cur_n = 1, cur_t = [[], []]):
"""Takes size of MOT, number to be added, and the current"""
if cur_n > size: # We're Done!
return [cur_t]
if len(cur_t[0]) == size: # If top row is completed, call again with bigger bottom row
return MOT_Gen(size, cur_n+1, [cur_t[0], cur_t[1]+[cur_n, cur_n]])
elif len(cur_t[0])+1 == size: # One away from completion of the top row
if len(cur_t[1])+1 == size: # One away from bottom row completion?
return MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n], cur_t[1]+[cur_n]])
else:
return (MOT_Gen(size, cur_n+1, [cur_t[0], cur_t[1]+[cur_n, cur_n]])
+ MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n], cur_t[1]+[cur_n]]))
elif len(cur_t[0])+2 <= size:
if len(cur_t[0]) == len(cur_t[1]):
return (MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n, cur_n], cur_t[1]])
+ MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n], cur_t[1]+[cur_n]]))
elif len(cur_t[0]) >= len(cur_t[1])+2:
return (MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n, cur_n], cur_t[1]])
+ MOT_Gen(size, cur_n+1, [cur_t[0], cur_t[1]+[cur_n, cur_n]])
+ MOT_Gen(size, cur_n+1, [cur_t[0]+[cur_n], cur_t[1]+[cur_n]]))
def duplicate_checker(lis):
"""Returns True if there's a duplicate"""
while len(lis) != 0:
if lis.pop() in lis:
return True
return False
def duplicate_checker(lis):
"""Returns True if there's a duplicate""" # runs in O(n*k) time UNLIKE SOME CODE
seen = set()
for item in lis:
tupleitem = deeptupler(item)
if tupleitem in seen:
return True
seen.add(tupleitem)
return False
def deeptupler(lis): # only for 2d arrays
total = []
for item in lis:
total.append(tuple(item))
return tuple(total)
#print(MOT_Gen(3))
#print(MOT_Gen(4))
##print(bijection([[1, 2, 3],
## [1, 2, 3]]))
##
##print(bijection([[1, 2, 3],
## [1, 2, 3]]))
##
##print(bijection([[1, 2, 2],
## [1, 3, 3]]))
##
##print(bijection([[1, 1, 3],
## [2, 2, 3]]))
for i in range(19, 30): # 15 works
print(i)
x = [bijection(MOT) for MOT in MOT_Gen(i)]
print(not duplicate_checker(x))
y = set()
for SYT in x:
y.add(valid_SYT(SYT))
print(not (False in y))
#print(bijection([[1, 1, 2],
# [2, 3, 3]]))
|
class Stack:
def __init__(self):
self.stack = []
self.top = -1
def push(self, data):
self.stack.append(data)
self.top += 1
def pop(self):
temp = self.stack[self.top]
del self.stack[self.top]
self.top -= 1
return temp
def __str__(self):
count = 0
string = ""
for item in self.stack[::-1]:
string += (str(item) + " ")
if count == 0:
string += "TOP"
string += "\n"
count += 1
return string
def readString(string):
stack = Stack()
for c in string:
decision = decide(c)
if decide(c) == False:
stack.push(int(c))
else:
b = stack.pop()
a = stack.pop()
val = decision(a,b)
stack.push(val)
return stack.pop()
def decide(char):
def doMult(a,b):
return a * b
def doDiv(a,b):
return a / b
def doPlus(a,b):
return a + b
def doSub(a,b):
return a - b
switcher = {
"+": doPlus,
"-": doSub,
"*": doMult,
"/": doDiv
}
return switcher.get(char, False)
print(readString("34+"))
print(readString("34+7*"))
print(readString("777+-842-/*"))
|
def fib(index):
if index in {0, 1}:
return index
else:
return fib(index-1) + fib(index-2)
print([fib(i) for i in range(10)][::-1])
|
import datetime
import jarvis as jv
import smtplib # this module is used to send email through gmail but for that you have to
import json
import pywhatkit
def wishMe():
'''
This function can greet you as per time
'''
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour <12:
jv.speak("Good Morning Sir!")
elif hour >= 12 and hour <18:
jv.speak("Good Afternoon Sir!")
else :
jv.speak("Good Evening Sir!")
def sendEmail(to,content):
'''
This function takes two argument sendEmail(email_address,content to be send..)
And send the email to the person whose argument is read with the content
which is also read form the parameters
'''
with open("data.json") as f:
data = json.load(f)
mailAdd = data[to]["email"] # here it will find the mail of person which is given to it in json file
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
with open('D:\\Riyank\\project\\jarvis\\password.txt','r') as f:
passcontent = f.read() # passcontent is email password that is used to send the mail
server.login('rajmalhotra7086@gmail.com',passcontent)
server.sendmail('rajmalhotra7086@gmail.com',mailAdd,content)
server.close()
def sendMsgWhatsapp(person,msg):
"""
This function takes two argument sendMsgWhatsapp(person name or phone number,content to be send..)
And send the message to the person whose argument is read with the content
which is also read form the parameters
"""
hr = datetime.datetime.now().hour
mnt = datetime.datetime.now().minute
with open("data.json") as f:
data = json.load(f) # here it will find the number of person which is given to it in json file
phone_num=data[person]["phone"]
try:
pywhatkit.sendwhatmsg(phone_num,msg,hr,mnt+1)
speak("Message has been sent Successfully!")
print("Message has been sent Successfully!")
except :
print("An Unexpected Error!")
def write_json(data,filename="data.json"):
"""
This function generally takes the data and store it to the specific json file
"""
with open(filename,"w") as f :
json.dump(data, f,indent=4)
def saveEmail(email,key):
"""
This function takes two argument, the first is email address that want to save
and the other is key or person's name that the email of,and both the arguments are string
saveEmail('123@gmail.com','riaynk')
and send it to the write_json function
"""
with open("data.json") as f:
data = json.load(f)
if key in data.keys():
e = {"email":email}
data[key].update(e)
else :
y = {key:{
"email":email
}}
data.update(y)
data=sorted(data.items())
data=dict(data)
write_json(data)
def savePhoneNumber(phone,key):
"""
This function takes two argument, the first is mobile number that want to save
and the other is key or person's name that the mobile number of,and both the arguments are string
saveEmail('+919837263727','riaynk')
and send it to the write_json function
"""
phone_num = "+91"+phone
with open("data.json") as f:
data = json.load(f)
if key in data.keys():
p = {"phone":phone_num}
data[key].update(p)
else :
y = {key:{
"phone":phone_num
}}
data.update(y)
data=sorted(data.items())
data=dict(data)
write_json(data)
def checkPassword(password):
""""
it checks the passsword with the password store in the json file
"""
with open('data.json') as f :
data = json.load(f)
p = data["password"]
if password == p:
return True
else :
return False
def setPassword(password):
"""
it strores the new password in the json file
"""
with open('data.json') as f :
data = json.load(f)
data["password"] = password
write_json(data)
|
# Solved HW Budget Data
# Approach is to create a third list with the monthly delta in Profit/Losses
import csv
month_date = []
monthly_profit = []
monthly_delta =[0]
with open('budget_data.csv','r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
# Reading all columns into the lists
for row in csvreader:
month_date.append(row[0])
monthly_profit.append(int(row[1]))
# Find Total Number of Months in Analysis
total_months = len(monthly_profit)
print("Total Months =",total_months)
# Find Total Net Profit in Analysis Period
Net_Profit = sum(monthly_profit)
print('{:,.2f}'.format(Net_Profit))
# Find the Largest Profit, Largest Loss, and Average Profit
Max_Profit = max(monthly_profit)
Min_Profit = min(monthly_profit)
Mean_Profit = Net_Profit/total_months
print('{:,.2f}'.format(Max_Profit))
print('{:,.2f}'.format(Min_Profit))
print('{:,.2f}'.format(Mean_Profit))
# Compute the Monthly Delta and Save into a New List
for x in range(1, total_months):
delta = (monthly_profit[x]-monthly_profit[x-1])
monthly_delta.append(delta)
# Find the Largest Monthly (+)Change, Largest Monthly (-)Change, Average Delta
Max_ProfitDelta = max(monthly_delta)
Min_ProfitDelta = min(monthly_delta)
deltamonths = len(monthly_delta)-1
print(deltamonths)
Mean_ProfitDelta = sum(monthly_delta)/deltamonths
print(Mean_ProfitDelta)
print('{:,.2f}'.format(Max_ProfitDelta))
print('{:,.2f}'.format(Min_ProfitDelta))
# Find the Date of the Largest Positive and Negative Monthly Delta
for x in range(1, total_months):
if monthly_delta[x] == Max_ProfitDelta:
MaxProfitDelta_Date = month_date[x]
if monthly_delta[x] == Min_ProfitDelta:
MinProfitDelta_Date = month_date[x]
print("Max Profit Delta Date= ", MaxProfitDelta_Date)
print("Min Profit Delta Date= ", MinProfitDelta_Date)
# Summarized Terminal Output
print("---------------------------------------------")
print("P&L High Level Summary Report")
print(" ")
print("---------------------------------------------")
print("Total Months =",total_months)
print("Total Net Profit =",'{:,.2f}'.format(Net_Profit))
print("Largest Monthly Profit =",'{:,.2f}'.format(Max_Profit))
print("Largest Monthly Loss =",'{:,.2f}'.format(Min_Profit))
print("Average Monthly Profit= ",'{:,.2f}'.format(Mean_Profit))
print(" ")
print("---------------------------------------------")
print("Largest Positive Monthly Change: ",'{:,.2f}'.format(Max_ProfitDelta)," Occured on: ", MaxProfitDelta_Date)
print("Largest Negative Monthly Change: ",'{:,.2f}'.format(Min_ProfitDelta)," Occurred on: ", MinProfitDelta_Date)
print("Average Monthly Change: ", Mean_ProfitDelta)
print(" ")
print("---------------------------------------------")
# Writing Results to a text file
with open('Financial_summary.txt','w') as f:
f.write("P&L High Level Summary Report" + "\n" + "---------------------------------------" + "\n"
+ "Number of Periods Analyzed: " + str(total_months) + "\n"
+ "Total Net Profit: " + str(Net_Profit) + "\n"
+ "Largest Monthly Profit: " + str(Max_Profit) + "\n"
+ "Largest Monthly Loss: " + str(Min_Profit) + "\n"
+ "Mean Monthly Profit: " + str(Mean_Profit) + "\n"
+ " ---------------------------------------------------" + "\n"
+ "Largest Positive Profit Monthly Change: " + str(Max_ProfitDelta) + " Occurred on " + str(MaxProfitDelta_Date) + "\n"
+ "Largest Negative Profit Monthly Change: " + str(Min_ProfitDelta) + " Occurred on " + str(MinProfitDelta_Date) + "\n"
+ " Mean Profit Monthly Change: " + str(Mean_ProfitDelta) + "\n"
+ " ---------------------------------------------------")
|
# https://www.youtube.com/watch?v=iV-4F0jGWak&list=PLU8oAlHdN5BlvPxziopYZRd55pdqFwkeS&index=10
print("Programa de evaluacion de notas de alumnos")
nota_Alumno=input("Introduce la nota del alumno: ")
def evaluacion(nota):
valoracion="aprobado"
if nota<5 :
valoracion="Suspendido"
return valoracion
print(evaluacion(int(nota_Alumno)))
f=input() |
#Libreria de matematicas match
import math
def calculaRaiz(num1):
if num1 <0:
raise ValueError("El numero no puede ser negativo")
else:
return math.sqrt(num1)
op1= int(input("Digite un numero: "))
try:
print(calculaRaiz(op1))
except ValueError as ErrorDeNumeroNegativo:
print(ErrorDeNumeroNegativo)
print("Programa terminado.") |
import random
def numAleatorio(num1,num2):
resultado = random.randint(num1,num2)
return resultado
respuesta = input("¿Quieres un numero de la suerte? S/N --> ")
while respuesta != "S" and respuesta != "N" and respuesta != "s" and respuesta != "n":
respuesta = input("ERROR: debes digitar 'S' o 'N':")
#el or, es como si respuesta es igual a "S" o igual a "s"
if respuesta == "S" or respuesta == "s":
print("tu numero de la suerte es:", str(numAleatorio(1,100)))
else:
print("Vuelve cuando quieras un numero aleatorio")
|
from collections import deque
from random import shuffle
def max_window(arr, k):
dq = deque()
out = []
for i in range(len(arr)):
if dq and dq[0] <= i - k:
dq.popleft()
while dq and arr[dq[-1]] < arr[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
out.append(arr[dq[0]])
return out
if __name__ == '__main__':
print(max_window([9, 4, 6, 3, 1, 2, 8, 7, 5], 4))
print(max_window([10, 5, 2, 7, 8, 7], 3))
print(max_window([10, 5, 2, 7, 8, 7], 4))
print(max_window(list(range(10)), 3))
print(max_window(list(range(9, -1, -1)), 3))
"""
i = [0, 1, 2, 3, 4, 5, 6, 7, 8]
arr = [9, 8, 7, 6, 5, 4, 3, 2, 1]
k = 4
q = [0, 1, 2, 3]
out = arr[q[0]] = 9
i = 4; i - q[0] = 4 >= k -> q.popleft()
q -> [1, 2, 3]
arr[i] < q[arr[-1]] -> q.append(i)
q = [1, 2, 3, 4]
""" |
"""
compute running median
"""
import heapq
def balance(bottom_half, top_half):
if len(bottom_half) > len(top_half):
promote = -1*heapq.heappop(bottom_half)
heapq.heappush(top_half, promote)
if len(bottom_half) < len(top_half):
demote = heapq.heappop(top_half)
heapq.heappush(bottom_half, demote)
def add(num, bottom_half, top_half):
if not bottom_half or -1*bottom_half[0] > num:
heapq.heappush(bottom_half, -num)
else:
heapq.heappush(top_half, num)
if abs(len(bottom_half) - len(top_half)) > 1:
balance(bottom_half, top_half)
def extract(bottom_half, top_half):
if len(bottom_half) - len(top_half) == 1:
return -1*bottom_half[0]
if len(top_half)-len(bottom_half) == 1:
return top_half[0]
return (-1*bottom_half[0] + top_half[0])/2
def running_median(stream):
bottom_half, top_half, out = [], [], []
for num in stream:
add(num, bottom_half, top_half)
median = extract(bottom_half, top_half)
out.append(median)
return out
if __name__ == '__main__':
print(running_median([4,6,9,3,1,0,3,4,6,6,2,4]))
"""
4
b = [4]
t = [] -> 4
6
b = [4]
t = [6] -> 5
9
b = [4],
t = [6, 9] -> 6
3
b = [4, 3]
t = [6, 9] -> 5
1
b = [4, 3, 1]
t = [6, 9] -> 4
0
b = [4, 3, 1, 0]
t = [6, 9]
b = [3, 1, 0]
t = [4, 6, 9] -> 3.5
""" |
"""
Saya Sudirman Nur Putra mengerjakan Tugas Praktkm 3 dalam Praktikum Desain dan Pemrograman Berorientasi Objek untuk
keberkahan-Nya maka saya tidak melakukan kecurangan yang seperti yang telah dispesifikasikan. Aamiin
"""
# mengimfor library
from Biodata import Biodata
from tkinter import *
data = []
# tkinter untuk tampilan GUI
root = Tk()
root.title("PENDATAAN CALON ALUMNI")
# menampilkan semua data calon alumni
def semuaData():
prof = Toplevel()
prof.title("DATA CALON ALUMNI")
p_frame = LabelFrame(prof, text="Data calon alumni", padx=15, pady=10)
p_frame.pack(padx=15, pady=10)
prof_nama = Label(p_frame, text="Data Semua Calon Alumni", anchor="w").grid(row=0, column=0, sticky="w")
# body untuk tampilan
body = LabelFrame(root, borderwidth=0)
body.grid(column=0, row=0)
# untuk form inputan
masuk = LabelFrame(body, padx=10, pady=10, borderwidth=0)
masuk.pack(padx=10, pady=10)
masuk.grid(column=0, row=0)
# untuk tampilan navigasi
navigasi = LabelFrame(masuk, padx=5, borderwidth=0, pady=3, width=50)
navigasi.grid(column = 0, row = 0)
# untuk menampilkan semua data calon alumni
b_alumni = Button(navigasi, text="Calon alumni", command=lambda: semuaData())
b_alumni.grid(row=0, column=0)
# menghapus semua data calon
b_haspu = Button(navigasi, text="Hapus Semua")
b_haspu.grid(row=0, column=2)
# menampilkan tentang pembuat perangkat
def Profil():
# tampilan baru
prof = Toplevel()
prof.title("Profil Pembuat")
# data mahasiswa
p_frame = LabelFrame(prof, text="Data mahasiswa", padx=15, pady=10)
p_frame.pack(padx=15, pady=10)
# data yang ditampilkan
prof_nama = Label(p_frame, text="Nama : Sudirman Nur Putra", anchor="w").grid(row=0, column=0, sticky="w")
prof_nim = Label(p_frame, text="NIM : 1900457", anchor="w").grid(row=1, column=0, sticky="w")
prof_kelas = Label(p_frame, text="Kelas : C1", anchor="w").grid(row=2, column=0, sticky="w")
# untuk menampilkan tentang pembuat
b_simpan = Button(navigasi, text="Tentang Perangkat", command=lambda: Profil())
b_simpan.grid(row=0, column=4)
# keluar dari aplikasi
b_simpan = Button(navigasi, text="Keluar", command=root.quit)
b_simpan.grid(row=0, column=6)
# variabel untuk inputan
nama = StringVar()
alamat = StringVar()
var1 = "Olahraga"
var2 = "Seni"
var3 = "Travel"
var4 = "Keilmuan"
var5 = "dll"
var = StringVar()
options = StringVar()
kesan = StringVar()
pesan = StringVar()
# mengambil data
# def getValue():
# prof = Toplevel()
# prof.title("data input")
# # data mahasiswa
# p_frame = LabelFrame(prof, text="Data mahasiswa", padx=15, pady=10)
# p_frame.pack(padx=15, pady=10)
# prof_nama = Label(p_frame, text= nama.get(), anchor="w").grid(row=0, column=0, sticky="w")
# prof_nama = Label(p_frame, text= alamat.get(), anchor="w").grid(row=0, column=0, sticky="w")
# prof_nama = Label(p_frame, text= kesan.get(), anchor="w").grid(row=0, column=0, sticky="w")
# prof_nama = Label(p_frame, text= pesan.get(), anchor="w").grid(row=0, column=0, sticky="w")
# bungkusan form input calon alumni
frame = LabelFrame(masuk, text="CALON ALUMNI", padx=5, pady=3, width=50)
frame.grid(column = 0, row = 1)
# bungkusan untuk tombol
frame_b = LabelFrame(masuk, padx=5, pady=3, width=50, borderwidth=0)
frame_b.grid(column = 0, row = 3)
# opts = LabelFrame(root, padx=10, pady=10)
# opts.pack(padx=10, pady=10)
# label dan inputan untuk nama
label = Label(frame, text="Nama ", pady=5, width = 20)
label.grid(column=0, row=0)
namaEntered = Entry(frame, width = 30, textvariable = nama)
namaEntered.grid(column = 2, row = 0)
# label dan inputan untuk alamat
label = Label(frame, text="Alamat ", pady=5, width = 20)
label.grid(column=0, row=1)
alamatEntered = Entry(frame, width = 30, textvariable = alamat)
alamatEntered.grid(column = 2, row = 1)
# label dan inputan untuk hobi berupa checkbox
label = Label(frame, text="Hobi ", pady=5, width = 20)
label.grid(column=0, row=2)
check = LabelFrame(frame, padx=5, pady=3, width=50, borderwidth=0)
check.grid(column = 2, row = 2)
check1 = Checkbutton(check, text='Olahraga',variable=var1, onvalue=1, offvalue=0).grid(column=0, row=0)
check2 = Checkbutton(check, text='Seni',variable=var2, onvalue=1, offvalue=0).grid(column=1, row=0)
check3 = Checkbutton(check, text='Travel',variable=var3, onvalue=1, offvalue=0).grid(column=2, row=0)
check4 = Checkbutton(check, text='Keilmuan',variable=var4, onvalue=1, offvalue=0).grid(column=0, row=1)
check5 = Checkbutton(check, text='lainnya',variable=var5, onvalue=1, offvalue=0).grid(column=1, row=1)
# label dan inputan untuk jenis kelamin
label = Label(frame, text="Jenis Kelamin ", pady=5, width = 20)
label.grid(column=0, row=3)
radio = LabelFrame(frame, padx=5, pady=3, width=50, borderwidth=0)
radio.grid(column = 2, row = 3)
R1 = Radiobutton(radio, text="Laki-laki", variable=var, value="Laki-laki")
R1.grid(column=0, row=0)
R2 = Radiobutton(radio, text="Perempuan", variable=var, value="Perempuan")
R2.grid(column=1, row=0)
# label dan inputan untuk kelas
label = Label(frame, text="Kelas ", pady=5, width = 20)
label.grid(column=0)
options.set("Kelas") # default value
om1 = OptionMenu(frame, options, "RPL","TKJ", "Telin", "Farmasi", "TMO", "TKRO")
om1.grid(row=4,column=2)
# label dan inputan untuk kesan
label = Label(frame, text="Kesan ", pady=5, width = 20)
label.grid(column=0, row=5)
kesanEntered = Entry(frame, width = 30, textvariable = kesan)
kesanEntered.grid(column = 2, row = 5)
# label dan intpuan untuk pesan
label = Label(frame, text="Pesan ", pady=5, width = 20)
label.grid(column=0, row=6)
pesanEntered = Entry(frame, width = 30, textvariable = pesan)
pesanEntered.grid(column = 2, row = 6)
# tombol untuk tambah gambar, mesi tidak bisa di tambahkan gambar
b_add = Button(frame_b, text="Tambah Foto", width=40)
b_add.grid(row=0, column=0)
# tombol untuk menyimpan data
b_simpan = Button(frame_b, text="Simpan", width=40)
b_simpan.grid(row=1, column=0)
root.mainloop() |
#!/usr/local/bin/python3
import sys
from Field import Field
from queue import Queue
class MineSweeper():
def __init__(self, num_cols, num_rows, num_mines):
self._num_cols = num_cols
self._num_rows = num_rows
self._field = Field(num_cols, num_rows, num_mines)
self._image = []
for row_index in range(num_rows):
row = ['?'] * num_cols
self._image.append(row)
self.flags_used = 0
def in_bounds(self, row, col):
return row >= 0 and row < self._num_rows and col >= 0 and col < self._num_cols
def get_image(self):
return self._image
def render(self):
init_str = '|'
for col_index in range(self._num_cols):
init_str += '-'
init_str += '|'
print(init_str)
for row_index in range(self._num_rows):
row_str = "|"
for col_index in range(self._num_cols):
row_str += str(self._image[row_index][col_index])
row_str += '|'
print(row_str)
print(init_str)
return
def test_cell_rec(self, row, col):
if not self._field.cell_is_bomb(row, col):
num_adjacent_bombs = self._field.get_num_adjacent_bombs(row,col)
self._image[row][col] = num_adjacent_bombs
if num_adjacent_bombs == 0:
d_col = -1
while d_col < 2:
d_row = -1
while d_row < 2:
if row + d_row >= 0 and row + d_row < self._num_rows and col + d_col >= 0 and col + d_col < self._num_cols:
if self._image[row + d_row][col + d_col] == '?':
self.test_cell_rec(row + d_row, col + d_col)
d_row += 1
d_col += 1
return True
else:
self._image[row][col] = 'X'
return False
def test_cell_iter(self, row, col):
if not self._field.cell_is_bomb(row, col):
cell_queue = Queue()
cell_queue.put([row, col])
traveled_coords = []
while not cell_queue.empty():
cell_coords = cell_queue.get()
row = cell_coords[0]
col = cell_coords[1]
if [row, col] in traveled_coords:
continue
num_adjacent_bombs = self._field.get_num_adjacent_bombs(row, col)
if num_adjacent_bombs == 0:
self._image[row][col] = ' '
else:
self._image[row][col] = num_adjacent_bombs
traveled_coords.append([row, col])
if num_adjacent_bombs == 0:
d_col = -1
while d_col < 2:
d_row = -1
while d_row < 2:
if self.in_bounds(row + d_row, col + d_col):
if self._image[row + d_row][col + d_col] == '?':
cell_queue.put([row + d_row, col + d_col])
d_row += 1
d_col += 1
return True
else:
self._image[row][col] = 'X'
return False
def flag_cell(self, row, col):
if self._image[row][col] == '?':
self._image[row][col] = 'f'
self.flags_used += 1
return True
else:
return False
def unflag_cell(self, row, col):
if self._image[row][col] == 'f':
self._image[row][col] = '?'
self.flags_used -= 1
return True
else:
return False
def get_image_cell(self, row, col):
return self._image[row][col]
def get_flags_used(self):
return self.flags_used
if __name__ == '__main__':
do_prompt = True
while do_prompt:
try:
num_cols = int(input("Enter number of columns for field: "))
num_rows = int(input("Enter number of rows for field: "))
num_mines = int(input("Enter number of mines: "))
do_prompt = False
except ValueError:
print("Please only enter integers larger than zero!")
mine_sweeper = MineSweeper(num_cols, num_rows, num_mines)
mine_sweeper.render()
is_playing = True
while is_playing:
try:
col = int(input("Enter col: "))
row = int(input("Enter row: "))
except ValueError:
print("Please enter only integers")
is_playing = mine_sweeper.test_cell_iter(row, col)
mine_sweeper.render()
sys.exit(0)
|
import socket
import string
import secrets
def string_to_binary(parametru):
res = ''
for x in parametru:
aux = format(ord(x), 'b')
while len(aux) < 8:
aux = '0' + aux
res += aux
return res
def binary_to_string(parametru):
rezultat = ''
for i in range(0, len(parametru), 8):
aux = parametru[i:i + 8]
decoded = 0
pow = 1
for _ in range(len(aux)):
decoded += int(aux[-1]) * pow
pow = pow * 2
aux = aux[:-1]
rezultat += chr(decoded)
return rezultat
def xor(first, second):
result = ''
for i in range(len(first)):
result += str(int(first[i]) ^ int(second[i]))
return result
def CBC_encrypting(initialization_vector, key, text):
number_of_iterations = len(text) // 128
previous = ""
result = ""
if len(text) % 128:
number_of_iterations += 1
while len(text) % 128 != 0:
text += string_to_binary("t")
for i in range(number_of_iterations):
if i == 0:
block_cipher = xor(text[i*128 : (i+1)*128],initialization_vector)
ciphertext = xor(block_cipher, key)
result += ciphertext
previous = ciphertext
else:
block_cipher = xor(text[i * 128: (i + 1) * 128],previous)
ciphertext = xor(block_cipher,key)
result += ciphertext
previous = ciphertext
return result
def CBC_decrypting(initialization_vector, key, text):
number_of_iterations = len(text) // 128
previous = ""
result = ""
for i in range(number_of_iterations):
if i == 0:
block_cipher = xor(text[i * 128: (i + 1) * 128],key)
plaintext = xor(block_cipher,initialization_vector)
result += plaintext
previous = text[i * 128: (i + 1) * 128]
else:
block_cipher = xor(text[i * 128: (i + 1) * 128],key)
plaintext = xor(block_cipher,previous)
result += plaintext
previous = text[i * 128: (i + 1) * 128]
return result
def OFB_encrypting(initialization_vector, key, text):
number_of_iterations = len(text) // 128
previous = ""
ciphertext = ""
if len(text) % 128:
number_of_iterations += 1
while len(text) % 128 != 0:
text += "0"
for i in range(number_of_iterations):
if not i:
previous = xor(initialization_vector,key)
result = xor(previous, text[i*128 : (i+1)*128])
ciphertext += result
else:
previous = xor(previous, key)
result = xor(previous, text[i * 128: (i + 1) * 128])
ciphertext += result
return ciphertext
def OFB_decrypting(initialization_vector, key, text):
number_of_iterations = len(text) // 128
previous = ""
plaintext = ""
if len(text) % 128:
number_of_iterations += 1
while len(text) % 128 != 0:
text += "0"
for i in range(number_of_iterations):
if not i:
previous = xor(initialization_vector, key)
result = xor(previous, text[i * 128: (i + 1) * 128])
plaintext += result
else:
previous = xor(previous, key)
result = xor(previous, text[i * 128: (i + 1) * 128])
plaintext += result
return plaintext
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(16))
key_k = string_to_binary(password) #random 128
key_k_prime = "01010100011010000110100101110011001000000110100101110011001000000111010001101000011001010010000001110000011100100110100101101101" #This is the prim
initialization_vector = "01001001011011100110100101110100011010010110000101101100011010010111101001100001011101000110100101101111011011100010000001101011" #Initialization k
key_type = ''
message = "I am the node B"
s.send(message.encode('ascii'))
data = s.recv(1024)
print('Received from the server :', str(data.decode('ascii')))
key_type = data.decode('ascii')
s.send("OK".encode('ascii'))
key_k = s.recv(1024)
key_k = key_k.decode('ascii')
if len(key_k) < 128:
message = "ERROR"
else:
message = "OK"
print("I tell him I received a valid key")
s.send(message.encode('ascii'))
text = s.recv(12228)
text = text.decode('ascii')
if key_type == "CBC":
text = CBC_decrypting(initialization_vector, key_k, text)
else:
text = OFB_decrypting(initialization_vector, key_k, text)
print("This is what I received from A:")
print(binary_to_string(text))
s.close() |
#mayor_menor
i = 1
mayor=0
menor=0
suma=0
while i<=3:
numero = int(input(" ingresen un numero " + str(i) + "= "))
if numero >= 0:
if numero > 0:
if numero> mayor:
mayor =numero
if numero < menor or i == 1:
menor = numero
if i==1:
numero1= numero
if i==2:
numero2= numero
if i==3:
numero3= numero
i += 1
else:
print("escribio mal el numero")
suma= numero1+ numero2
if suma> numero3:
print ("la suma de los dos primeros numeros es mayor al tercer numero ingresado = ")
else:
print("la suma de los dos primeros numeros es menor al tercer numero ingresado ")
print("El número MAYOR es el " + str(mayor))
print("El número MENOR es el " + str(menor))
|
#hdg
numero=int(input("ingrese un numero ="))
print("los numeros son:")
for n in range(1,numero,2):
print(n)
for i in range(0,numero,2):
print(-i) |
#ecuacion cuadratica
a=float(input("ingrese el valor de a = "))
b=float(input("ingrese el valor de b = "))
c=float(input("ingrese el valor de c = "))
discriminante= b**2-4*a*c
if discriminante < 0 :
print("no tiene soluciones reales")
elif discriminante==0:
x = -b / (2 *a)
print ("la solucion unica es x = ",x)
else:
x1=(-b-(discriminante**0.5))/(2*a)
x2=(-b+(discriminante**0.5))/(2*a)
print("tiene dos soluciones reales que son:")
print("primera solucion = ",x1)
print("la segunda solucion = ",x2)
|
#indicar ciertas cantidades
suma=0
suma2=0
suma3=0
suma4=0
suma5=0
i=1
n=int(input("ingrese la cantidad de numeros que quiere digitar = "))
while i<=n:
numero = int(input(" ingresen un numero " + str(i) + "= "))
if numero <=0:
suma= suma+1
if numero >=0:
suma2= suma2+1
if numero%2 ==0:
suma3=suma3+1
else:
suma4=suma4+1
if numero%8 ==0:
suma5=suma5+1
i=i+1
print("los numeros negativos que hay son = ",suma)
print("los numeros positivos que hay son = ", suma2)
print("los numeros pares que hay son = ",suma3)
print("los numeros impares que hay son = ",suma4)
print("los numeros multiplos de 8 que hay son = ",suma5) |
#cadena invertida utilizando la posicion
frase=str(input("ingrese la frase que desee invertir = "))
print(frase [::-1 ]) |
kj#numero por cual es divisible
numero=int(input("ingrese un numero = "))
if numero%2==0:
print("el numero es divisible por 2")
if numero%3==0:
print("el numero es divisible por 3")
if numero%5==0:
print("el numero es divisible por 5")
if numero%7==0:
print("el numero es divisible por 7")
if numero%9==0:
print("el numero es divisible por 9") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.