text
stringlengths 37
1.41M
|
---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
keys_1=[]
keys_2=[]
keys_3=[]
def checkAvail(se,pat):
patr=r''+pat
mf=re.search(patr,se)
'''if mf:
print "found"
else:
print "not found"'''
return mf
def rescoreSent(sen,keys):
scr=0;
for tri in keys['tri']:
res=checkAvail(sen,tri[0])
if(res):
scr=tri[1]/10
for bi in keys['bi']:
res = checkAvail(sen, bi[0])
if (res):
scr = bi[1]/(2*10)
for uni in keys['uni']:
res = checkAvail(sen, uni[0])
if (res):
scr = uni[1]/(3*10)
return scr
def rescoringDoc(text,keys):
rescrDoc=[]
for sen in text.keys():
text[sen]+=rescoreSent(sen,keys)
rescrDoc.append(text[sen])
#print text[sen]
return rescrDoc
if __name__=='__main__':
sent=raw_input("Enter the sentence list")
keys_1=raw_input("Enter unigram keyphrases")
keys_2=raw_input("Enter bigram keyphrases")
keys_3=raw_input("Enter trigram keyphrases")
sent="இறை நம்பிக்கைகள் தோன்றிய காலம் தொட்டே, அத்தகைய நம்பிக்கைகளை கேள்விக்குட்படுத்திய, ஐயப்பட்ட, மறுத்த நிலைப்பாடுகளும் இருந்து வந்திருக்கின்றன. இந்திய மெய்யியலில் பொருளியவாத, இறைமறுப்புக் கொள்கையை உலகாயதம் முன்னிறுத்தியது.[1] பெளத்தம், சமணம் ஆகியவையும் உலகை படைக்கும், பாதுகாக்கும், அழிக்கும் பண்புகளைக் கொண்ட கடவுளை அல்லது கடவுள்களை நிராகரித்தன. மேற்குலக, கிரேக்க மெய்யியலில் Epicureanism, Sophism போன்று மெய்யியல்கள் இறைமறுப்பு கொள்கைகளைக் கொண்டிருந்தன. அறிவொளிக் காலத்தைத் தொடந்த அறிவியலின் வளர்ச்சி பல்வேறு வகைகளில் பொருளியவாத, இறைமறுப்புக் கோட்படுகளுக்கு கூடிய ஆதாரங்களையும் வாதங்களையும் வழங்கி உள்ளது. 2000 களில் ஐக்கிய அமெரிக்காவிலும், ஐரோப்பாவிலும் அப்போது விரிபு பெற்று வந்த சமய தீவரவாதத்தை எதிர்த்து புதிய இறைமறுப்பு எழுந்தது"
pat="காலம் தொட்டே"
|
"""Test the convert functions to ensure that they work correctly."""
from pytest import approx
from converter import convert
from converter import units
def test_convert_celsius_to_fahrenheit():
"""Check to ensure that Celsius to Fahrenheit conversion works."""
temperature = 0
converted_temperature = convert.convert_celsius_to_fahrenheit(temperature)
assert converted_temperature == 32
def test_convert_celsius_to_fahrenheit_floating_point():
"""Check to ensure that Celsius to Fahrenheit conversion works."""
temperature = 26.667
converted_temperature = convert.convert_celsius_to_fahrenheit(temperature)
assert converted_temperature == approx(80, rel=1e-3)
def test_convert_celsius_to_fahrenheit_wrapper():
"""Use the wrapper to ensure that Celsius to Fahrenheit works."""
temperature = 0
from_unit = units.TemperatureUnitOfMeasurement.celsius
to_unit = units.TemperatureUnitOfMeasurement.fahrenheit
converted_temperature = convert.convert_temperature(temperature, from_unit, to_unit)
assert converted_temperature == 32
def test_convert_celsius_to_fahrenheit_wrapper_floating_point():
"""Use the wrapper to ensure that Fahrenheit to Celsius works."""
temperature = 26.667
from_unit = units.TemperatureUnitOfMeasurement.celsius
to_unit = units.TemperatureUnitOfMeasurement.fahrenheit
converted_temperature = convert.convert_temperature(temperature, from_unit, to_unit)
assert converted_temperature == approx(80, rel=1e-3)
def test_convert_fahrenheit_to_celsius():
"""Check to ensure that Celsius to Fahrenheit conversion works."""
temperature = 32
converted_temperature = convert.convert_fahrenheit_to_celsius(temperature)
assert converted_temperature == 0
def test_convert_fahrenheit_to_celsius_floating_point():
"""Check to ensure that Celsius to Fahrenheit conversion works."""
temperature = 80
converted_temperature = convert.convert_fahrenheit_to_celsius(temperature)
assert converted_temperature == approx(26.667, rel=1e-3)
def test_convert_fahrenheit_to_celsius_wrapper():
"""Use the wrapper to ensure that Fahrenheit to Celsius works."""
temperature = 32
from_unit = units.TemperatureUnitOfMeasurement.fahrenheit
to_unit = units.TemperatureUnitOfMeasurement.celsius
converted_temperature = convert.convert_temperature(temperature, from_unit, to_unit)
assert converted_temperature == 0
def test_convert_fahrenheit_to_celsius_wrapper_floating_point():
"""Use the wrapper to ensure that Fahrenheit to Celsius works."""
temperature = 80
from_unit = units.TemperatureUnitOfMeasurement.fahrenheit
to_unit = units.TemperatureUnitOfMeasurement.celsius
converted_temperature = convert.convert_temperature(temperature, from_unit, to_unit)
assert converted_temperature == approx(26.667, rel=1e-3)
|
class Gun:
def __init__(self,model):
self.model = model
self.bullet_count = 0
def add_bullet(self,count):
self.bullet_count+=count
def shoot(self):
if self.bullet_count<=0:
print('没有子弹了。。。')
return
self.bullet_count-=1
print("%s 发射子弹%d..." % (self.model, self.bullet_count))
ak47 = Gun('ak47')
ak47.add_bullet(50)
ak47.shoot()
class Solider:
def __init__(self,name):
self.name = name
self.gun = None
def fire(self):
if self.gun is None:
print("%s 还没有枪..." % self.name)
return
print('冲啊。。。%s'%self.name)
self.gun.add_bullet(100)
self.gun.shoot()
ak47 = Gun('ak47')
xusanduo = Solider('许三多')
xusanduo.fire()
|
class BinaryHeap:
def __init__(self):
self.heap = [[-1, -1]]
def insert(self, e, p):
self.heap.append([e, p])
self._up_heap(len(self.heap) - 1)
def find_min(self):
return self.heap[1]
def del_min(self):
var = self.heap[1]
if len(self.heap) > 2:
self.heap[1] = self.heap.pop()
self._down_heap(1)
return var
def _up_heap(self, i):
if i > 0:
key = self.heap[i]
parent = i // 2
while (parent > 0) and (self.heap[parent][1] > key[1]):
self.heap[i] = self.heap[parent]
i = parent
parent = parent // 2
self.heap[i] = key
def _down_heap(self, i):
left = 2 * i
right = 2 * i + 1
if left <= len(self.heap) - 1 and self.heap[left][1] < self.heap[i][1]:
minimum = left
else:
minimum = i
if right <= len(self.heap) - 1 and self.heap[right][1] < self.heap[minimum][1]:
minimum = right
if minimum != i:
self.heap[i], self.heap[minimum] = self.heap[minimum], self.heap[i]
self._down_heap(minimum)
def find_vertex(e, data):
for value in data:
if value[0] == e:
return value
return None
def Prim(data, start):
tree = [(data[start][0], None)]
heap = BinaryHeap()
for value in data[start][1]:
heap.insert(value[0], value[1])
while len(tree) < len(data):
minimal_node = heap.del_min()
if find_vertex(minimal_node[0], tree) is None:
tree.append((minimal_node[0], minimal_node[1]))
vertex = find_vertex(minimal_node[0], data)
for adjacent in vertex[1]:
if find_vertex(adjacent[0], tree) is None:
heap.insert(adjacent[0], adjacent[1])
return tree
graph1 = [
(0, [(3, 13), (2, 13), (1, 24), (4, 22)]),
(1, [(3, 13), (0, 24), (2, 22), (4, 13)]),
(2, [(0, 13), (3, 19), (1, 22), (4, 14)]),
(3, [(0, 13), (2, 19), (4, 19), (1, 13)]),
(4, [(1, 13), (3, 19), (2, 14), (0, 22)])
]
graph2 = [
(0, [(2, 12), (1, 8)]),
(1, [(0, 8), (2, 13), (3, 25), (4, 9)]),
(2, [(0, 12), (1, 13), (6, 21), (3, 14)]),
(3, [(2, 14), (1, 25), (4, 20), (5, 8), (7, 12), (8, 16), (6, 12)]),
(4, [(1, 9), (3, 20), (5, 19)]),
(5, [(4, 19), (3, 8), (7, 11)]),
(6, [(2, 21), (3, 12), (8, 11)]),
(7, [(8, 9), (3, 12), (5, 11)]),
(8, [(6, 11), (3, 16), (7, 9)])
]
graph3 = [
(0, [(2, 75), (1, 9)]),
(1, [(0, 9), (2, 95), (3, 19), (4, 42)]),
(2, [(0, 75), (1, 95), (3, 51)]),
(3, [(2, 51), (1, 19), (4, 31)]),
(4, [(1, 42), (3, 31)])
]
print(Prim(graph3, 0))
|
# TASK 8
# (HL) Define data structures to represent J1 programs, with pretty printers.
# e::= v|(e e...)|(if e e e)
# v::= number|boolean|prim
# prim ::= + | * | / | - | <= | < | = | > | >=
prim_list = ['+', '*', '/', '-', '<=', '<', '=', '>', '>=']
class E_v:
def __init__(self, n):
if str(n).isnumeric() or isinstance(n, bool) or str(n) in prim_list:
self.n = n
else: self.n = 'error'
def __str__(self):
return str(self.n)
class E_if:
def __init__(self, n):
if str(n)[0:2] == 'if':
self.n = n
else: self.n = 'error'
def __str__(self):
return str(self.n)
class E_ne:
def __init__(self, n):
if len(str(n)) > 1:
self.n = n
else:
self.n = 'error'
def __str__(self):
return str(self.n)
print(E_v('+'))
print(E_if('if e e e'))
print(E_ne('e e e e e e e e e e e'))
print(E_ne('e'))
|
# TASK 4
# Implement a big-step interpreter for J0.
# Connect to your test suite.
class Num:
def __init__(self, n):
self.n = n
def interp(self):
return self.n
def __str__(self):
return str(self.interp())
class Add:
def __init__(self, l, r):
self.l = l
self.r = r
def interp(self):
n1 = Num(self.l).interp()
n2 = Num(self.r).interp()
return Num(n1.n + n2.n)
def __str__(self):
return '(' + '+ ' + str(self.l) + ' ' + str(self.r) + ')'
class Sub:
def __init__(self, l, r):
self.l = l
self.r = r
def interp(self):
n1 = Num(self.l).interp()
n2 = Num(self.r).interp()
return Num(n1.n - n2.n)
def __str__(self):
return '(' + '- ' + str(self.l) + ' ' + str(self.r) + ')'
class Mult:
def __init__(self, l, r):
self.l = l
self.r = r
def interp(self):
n1 = Num(self.l).interp()
n2 = Num(self.r).interp()
return Num(n1.n * n2.n)
def __str__(self):
return '(' + '* ' + str(self.l) + ' ' + str(self.r) + ')'
class Div:
def __init__(self, l, r):
self.l = l
self.r = r
def interp(self):
n1 = Num(self.l).interp()
n2 = Num(self.r).interp()
return Num(n1.n / n2.n)
def __str__(self):
return '(' + '/ ' + str(self.l) + ' ' + str(self.r) + ')'
# test suit
# (+ 3 4)
print(Add(Num(3), Num(4)))
print(Add(Num(3), Num(4)).interp())
# (* 3 4)
print(Mult(Num(3), Num(4)))
print(Mult(Num(3), Num(4)).interp())
# (- 3 4)
print(Sub(Num(3), Num(4)))
print(Sub(Num(3), Num(4)).interp())
# (/ 3 4)
print(Div(Num(3), Num(4)))
print(Div(Num(3), Num(4)).interp())
''' result
(+ 3 4)
7
(* 3 4)
12
(- 3 4)
-1
(/ 3 4)
0.75
'''
|
# (HL) Write a dozen test J5 programs that use the standard library.
prim_list = ['+', '*', '/', '-', '<=', '<', '=', '>', '>=', 'pair', 'fst', 'snd', 'inl', 'inr']
class x:
def __init__(self, x):
self.x = x
def __str__(self):
return str(self.x)
class V:
def __init__(self, v):
if isinstance(v, (int, bool)) or str(v) in prim_list or isinstance(v, str) or isinstance(v, list):
self.v = v
else:
self.v = 'error'
def interp(self):
return self.v
def __str__(self):
return str(self.interp())
class E:
def __init__(self, list):
self.list = list
def __str__(self):
return str(self.list)
# Extend your standard library to include options and basic list functions, like map, filter, and fold.
def Add1(n):
return n + 1
class Maybe:
def __init__(self, val):
self.val = val
def __str__(sefl):
return str(1) + '+ ' + sefl.val
class List:
def __init__(self, li):
self.li = list(li.split(' '))
def __str__(self):
return str(self.li)
test_1 = ['case', str(V('inl')), 'as', ['inl', 'e1'], ['inr', 'e2']]
test_2 = ['case', str(V('inl')), 'as', ['inl', 2], ['inr', 3]]
test_3 = ['pair', 1, 2]
test_4 = [str(V('fst')), [1, 2]]
test_5 = [str(V('snd')), [1, 2]]
print(E(test_2))
print(E(test_3))
print(E(test_4))
print(E(test_5))
print(Maybe('A'))
print(List('1 2 3'))
|
# TASK 2
# Write a pretty-printer for J0 programs.
class Add:
def __init__(self, l, r):
self.l = l
self.r = r
def __str__(self):
return '(' + '+ ' + str(self.l) + ' ' + str(self.r) + ')'
class Num:
def __init__(self, n):
self.n = n
def __str__(self):
return str(self.n)
class Mult:
def __init__(self, l, r):
self.l = l
self.r = r
def __str__(self):
return '(' + '* ' + str(self.l) + ' ' + str(self.r) + ')'
print(Mult(Num(3), Num(4)))
print(Add(1, Mult(Num(3), Num(4))))
# result
# (* 3 4)
# (+ 1 (* 3 4))
|
"""day26_contiguous_array.py
Created by Aaron at 26-May-20"""
from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
mx=0
count=0
dict={0: -1}
for x,val in enumerate(nums):
count-=1 if val==0 else -1
if count in dict:
mx=max(mx, x-dict[count])
else:
dict[count]=x
return mx
run=Solution()
# a=[1,0]
a=[0,0,1,0,0,0,1,1]
print(run.findMaxLength(a))
# idea can be retrieve from day5 best time to buy and sell stock where let 0 and 1 as the movement of graph going down and up
# each time a point reencounter means there is a subarray
|
## 1. 集合的特性
## 1.1 set是无序的,没有下表索引,不支持列表的所有方法
type({1,2,3,4,5,6}) ## class 'set'
## 1.2 集合是不重复的
{1,1,2,2,3,3} ## {1,2,3}
## 2. 集合的方法
1 in {1,2,3} ## true
1 not in {1,2,3} ## false
## 集合的差集
{1,2,3,4,5,6} - {3,4} ## {1,2,5,6}
## 集合的交集
{1,2,3,4,5,6} & {3,4} ## {3,4}
## 集合的合集
{1,2,3,4,5,6} | {3,4,7} ## {1,2,3,4,5,6,7}
## 空的集合
type({}) ## class 'dict'
type(set()) ## class 'set'
len(set()) ## 0
|
# -*- coding: UTF-8 -*-
# randrange() 方法返回指定递增基数集合中的一个随机数,基数默认值为1
import random
# random.randrange ([start,] stop [,step])
# start -- 指定范围内的开始值,包含在范围内。
# stop -- 指定范围内的结束值,不包含在范围内。
# step -- 指定递增基数
print "randrange(100, 1000, 2): ", random.randrange(100, 1000, 2)
print "randrange(0, 1000, 3): ", random.randrange(0, 1000, 3);
|
class Todo():
def __init__(self):
self.tasks = []
def add(self, task):
if task in self.tasks: # check if task was added
return "task already exists" # if added, return error
else:
self.tasks.append(task) # otherwise add task to list
def remove(self, task):
# check if task exists
# if not return error
# if exists, remove task and do not return anything
if task not in self.tasks:
return "task was not added"
else:
self.tasks.remove(task)
|
'''
The Antique Comedians of Malidinesia prefer comedies to tragedies.
Unfortunately, most of the ancient plays are tragedies. Therefore the
dramatic advisor of ACM has decided to transfigure some tragedies into
comedies. Obviously, this work is very hard because the basic sense of
the play must be kept intact, although all the things change to their
opposites. For example the numbers: if any number appears in the tragedy,
it must be converted to its reversed form before being accepted into the comedy play.
Reversed number is a number written in arabic numerals but the order of digits is reversed.
The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries
in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means
if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that
the reversed number never has any trailing zeros.
ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum,
Of course, the result is not unique because any particular number is a reversed form of several numbers
(e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing
(e.g. assume that the original number was 12).
'''
num_runs = int(input())
for i in range(0, num_runs):
rev_1, rev_2 = input().split()
sum = int(str(rev_1)[::-1]) + int(str(rev_2)[::-1])
print( int(str(sum)[::-1]))
|
import numpy as np
from DecisionTree import ClassificationTree, RegressionTree
from abc import ABCMeta
from scipy.stats import mode
"""
References
----------
.. [1] Murphy, K. P. (2012). Machine learning: A probabilistic perspective.
Cambridge, MA: MIT Press.
.. [2] The Elements of Statistical Learning: Data Mining, Inference, and Prediction (Second Edition)
by Trevor Hastie, Robert Tibshirani and Jerome Friedman (2009)
.. [3] https://perso.math.univ-toulouse.fr/motimo/files/2013/07/random-forest.pdf
"""
class RandomForest(metaclass=ABCMeta):
"""
Attributes
----------
num_trees : the number of trees to be made in the forest
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
Note
----
This class is not to be instantiated. It is simply a base class for the
classification and regression forest classes
"""
def __init__(self, num_trees, seed, max_depth, cost_func, min_size, sample_percentage):
"""
Initializes the random forest
Parameters
----------
num_trees : the number of trees to be made in the forest
seed : the seed from which the random sample choices will be made
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
"""
self.num_trees = num_trees
self.max_depth = max_depth
self.cost_func = cost_func
self.min_size = min_size
self.sample_percentage = sample_percentage
np.random.seed(seed)
def fit(self, X, y):
"""
Grows a forest of decision trees based off the num_trees
attribute
Parameters
----------
X : N x D matrix of real or ordinal values
y : size N vector consisting of either real values or labels for corresponding
index in X
"""
data = np.column_stack((X, y))
self.forest = np.empty(shape=self.num_trees, dtype='object')
sample_size = int(X.shape[0] * self.sample_percentage)
for i in range(self.num_trees):
sample = data[np.random.choice(data.shape[0], sample_size, replace=True)]
sampled_X = data[:, :data.shape[1] - 1]
sampled_y = data[:, data.shape[1] - 1]
if isinstance(self, RegressionForest):
tree = RegressionTree(
max_depth=self.max_depth,
min_size=self.min_size,
in_forest=True)
else:
tree = ClassificationTree(
cost_func=self.cost_func,
max_depth=self.max_depth,
min_size=self.min_size,
in_forest=True)
tree.fit(sampled_X, sampled_y)
self.forest[i] = tree
def predict(self, X):
"""
Predicts the output (y) of a given matrix X
Parameters
----------
X : numerical or ordinal matrix of values corresponding to some output
Returns
-------
The predict values corresponding to the inputs
"""
votes = np.zeros(shape=(self.num_trees, X.shape[0]))
for i, tree in enumerate(self.forest):
votes[i] = tree.predict(X)
predictions = np.zeros(shape=X.shape[0])
if isinstance(self, RegressionForest):
predictions = votes.mean(axis=0)
else:
# print(votes)
predictions = np.squeeze(mode(votes, axis=0)[0])
return predictions
class RegressionForest(RandomForest):
"""
Attributes
----------
num_trees : the number of trees to be made in the forest
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
"""
def __init__(self, num_trees=10, seed=0, max_depth=None, min_size=1, sample_percentage=1):
"""
Initializes Regression Forest
Parameters
----------
num_trees : the number of trees to be made in the forest
seed : the seed from which the random sample choices will be made
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
"""
self.num_trees = num_trees
self.cost_func = 'mse'
self.max_depth = max_depth
self.min_size = min_size
self.sample_percentage = sample_percentage
super().__init__(
num_trees=num_trees,
seed=seed,
max_depth=max_depth,
cost_func=self.cost_func,
min_size=min_size,
sample_percentage=sample_percentage
)
class ClassificationForest(RandomForest):
"""
Attributes
----------
num_trees : the number of trees to be made in the forest
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
"""
def __init__(self, num_trees=10, seed=0, max_depth=None, cost_func='mcr', min_size=1, sample_percentage=1):
"""
Initializes Regression Forest
Parameters
----------
num_trees : the number of trees to be made in the forest
seed : the seed from which the random sample choices will be made
max_depth : the maximum depth that each tree is allowed to grow
cost_func : function that determines the cost of each split in the trees
min_size : the minimum number of data observations needed in each split
sample_percentage : size of data to be sampled per tree
"""
self.num_trees = num_trees
self.cost_func = cost_func
self.max_depth = max_depth
self.min_size = min_size
self.sample_percentage = sample_percentage
super().__init__(
num_trees=num_trees,
seed=seed,
max_depth=max_depth,
cost_func=cost_func,
min_size=min_size,
sample_percentage=sample_percentage
)
|
"""
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the
array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
"""
__author__ = 'Danyang'
class Solution:
def threeSum_duplicate(self, num):
"""
Hash
O(n^2)
:param num: array
:return: a list of lists of length 3, [[val1,val2,val3]]
"""
reverse_map = {}
for ind, val in enumerate(num):
if val not in reverse_map:
reverse_map[val] = [ind]
else:
reverse_map[val].append(ind)
result = []
for i in xrange(len(num)):
for j in xrange(i, len(num)):
target = 0-num[i]-num[j]
if target not in reverse_map:
continue
for index in reverse_map[target]:
if i != index and j != index:
result.append([num[i], num[j], target])
break
return result
def threeSum_TLE(self, num):
"""
Hash
O(n^2)
:param num: array
:return: a list of lists of length 3, [[val1,val2,val3]]
"""
# hash
reverse_map = {}
for ind, val in enumerate(num):
if val not in reverse_map:
reverse_map[val] = [ind]
else:
reverse_map[val].append(ind)
result = {}
for i in xrange(len(num)):
for j in xrange(i, len(num)):
target = 0-num[i]-num[j]
if target not in reverse_map:
continue
for index in reverse_map[target]:
if index != i and index != j:
lst = sorted([num[i], num[j], target])
lst = tuple(lst)
result[lst] = 1 # hash
break
return result.keys()
def threeSum(self, num):
"""
Brute force first, then determine whether sorting time complexity exceeds the brute force
Three pointers
Algorithm:
1. sort everything first
2. three pointers, i, j, k
3. notice JUMP
Palantir Technology Interview Question
http://en.wikipedia.org/wiki/3SUM
O(n^2)
Notice:
0. duplicated element will cause "Output Limit Exceeded" error
1. avoid using set
:param num: array
:return: a list of lists of length 3, [[val1,val2,val3]]
"""
# record result
result = []
num.sort() # sorting first, avoid duplicate,
i = 0
while i < len(num)-2:
j = i+1
k = len(num)-1
while j < k:
lst = [num[i], num[j], num[k]]
if sum(lst) == 0:
result.append(lst)
k -= 1
j += 1
# JUMP remove duplicate
while j < k and num[j] == num[j-1]:
j += 1
while j < k and num[k] == num[k+1]:
k -= 1
elif sum(lst) > 0:
k -= 1
else:
j += 1
i += 1
# remove duplicate
while i < len(num)-2 and num[i] == num[i-1]:
i += 1
return result
if __name__ == "__main__":
print(Solution().threeSum([-1, 0, 1, 2, -1, -4]))
|
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room, items=[]):
self.name = name
self.current_room = current_room
self.items = items
def __str__(self):
if len(self.items) == 0:
return f'{self.name} doesn\'t have any items.'
else:
output = 'The player has the following items:'
for item in self.items:
output += f'{item.name}\n'
return output
def move(self, direction):
if getattr(self.current_room, f"{direction}_to") == None:
print(f"You cannot move in such direction. Try another one")
elif getattr(self.current_room, f"{direction}_to") != None:
setattr(self, "current_room", getattr(
self.current_room, f"{direction}_to"))
self.current_room.explain()
|
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
def __init__(self, **kwargs):
self.name = kwargs["name"]
self.description = kwargs["description"]
self.items = kwargs["items"]
# Declare all the rooms
all_rooms = {
'outside': Room(name="Outside Cave Entrance",
description="North of you, the cave mount beckons",
items=["stick", "heavy stone"]),
'foyer': Room(name="Foyer",
description="""Dim light filters in from the south. Dusty
passages run north and east.""",
items=["rope", "lit torch"]),
'overlook': Room(name="Grand Overlook",
description="""A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm.""",
items=["knight's armour", "shield", "sword", "dagger"]),
'narrow': Room(name="Narrow Passage",
description="""The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
items=[]),
'treasure': Room(name="Treasure Chamber",
description="""You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south.""",
items=["empty treasure chest"]),
}
# Link rooms together
all_rooms['outside'].n_to = all_rooms['foyer']
all_rooms['foyer'].s_to = all_rooms['outside']
all_rooms['foyer'].n_to = all_rooms['overlook']
all_rooms['foyer'].e_to = all_rooms['narrow']
all_rooms['overlook'].s_to = all_rooms['foyer']
all_rooms['narrow'].w_to = all_rooms['foyer']
all_rooms['narrow'].n_to = all_rooms['treasure']
all_rooms['treasure'].s_to = all_rooms['narrow']
|
import periodictable as pt
absolute_difference_function = lambda list_value : abs(list_value - given_value)
# Because .isnumeric() returns false for floats, we create this new
# function that will allow us to check for floats
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
while True:
element = None
user_input = input("Enter an element, atomic mass (whole number), atomic number (non-whole number), or atomic symbol:")
if user_input in [ele.name for ele in pt.elements]:
element = pt.elements.name(user_input)
elif user_input.capitalize() in [ele.symbol for ele in pt.elements]:
element = pt.elements.symbol(user_input.capitalize())
elif user_input.isnumeric():
element = pt.elements[int(user_input)]
elif is_number(user_input):
given_value = float(user_input)
mass_list = [ele.mass for ele in pt.elements]
closest_value_index = mass_list.index(min(mass_list, key=absolute_difference_function))
element = pt.elements[closest_value_index]
else:
print(' '* 5 + 'Invalid Input')
if element != None :
print(' '* 5 + element.symbol + ' - ' + element.name.capitalize())
print(' '* 5 + "Atomic mass : " + str(element.mass))
|
# link - http://www.geeksforgeeks.org/greedy-algorithms-set-5-prims-minimum-spanning-tree-mst-2/
# April 18, 2017
class Prims:
def __init__(self):
self.__V = 5
def __get_min(self, dist, visited):
minimum = float("inf")
for i in range(0,self.__V):
if visited[i] is False and dist[i] < minimum:
minimum = dist[i]
min_index = i
return min_index
def __print_solution(self, parent, dist, graph):
print "Path Distance";
for v in range(0, self.__V):
print "%d - %d %d" % ( parent[v], v, graph[v][parent[v]] )
def prim_mst(self, graph, source):
dist, visited, parent = [float("inf")]*self.__V, [False]*self.__V, [False]*self.__V
dist[0] = 0
for c in range(0, self.__V-1):
u = self.__get_min(dist, visited)
visited[u] = True
for v in range(0, self.__V):
if visited[v] is False and graph[u][v] and dist[v] > graph[u][v]:
dist[v] = graph[u][v]
parent[v] = u
self.__print_solution(parent, dist, graph)
if __name__ == "__main__":
graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
obj = Prims()
obj.prim_mst(graph, 0)
|
# Felipe Martins Gomes
# Comp 20
# Exercício 7.26.13
# Programa compilado com PyCharm 2018.1.2
import turtle
import turtle
def fazer_janela (cor, titulo):
janela = turtle.Screen()
janela.bgcolor(cor)
janela.title(titulo)
return janela
def fazer_turtle (cor, tamanho):
tartaruga = turtle.Turtle()
tartaruga.color(cor)
tartaruga.pensize(tamanho)
return tartaruga
def fazer_movimento (tartaruga, x, y):
tartaruga.left(x)
tartaruga.forward(y)
def desenhar_figura (tartaruga, x, y):
tartaruga.left(x)
tartaruga.forward(y)
janela = fazer_janela("white", "casas")
felipe = fazer_turtle("black", 8)
#felipe.left(90)
#felipe.penup()
#felipe.forward(300)
#felipe.right(90)
#felipe.pendown()
movimento1 = [(270, 100), (90, 100), (90, 100), (45, 50*2**0.5), (90, 50*2**0.5), (135, 100)]
for (x,y) in movimento1:
desenhar_figura(felipe, x, y)
felipe.penup()
felipe.forward(130)
felipe.pendown()
movimento2 = [(270, 100), (270, 100), (270, 100), (315, 50*2**0.5), (270, 50*2**0.5),
(225, 100), (135, 100*2**0.5)]
for (x,y) in movimento2:
desenhar_figura(felipe, x, y)
felipe.penup()
felipe.left(90)
felipe.forward(100)
felipe.left(45)
felipe.pendown()
movimento3 = [(225, -50*2**0.5), (270, -100*2**0.5), (270, -100*2**0.5), (270, -50*2**0.5),
(315, -100), (270, -100), (270, -100), (270, -100)]
for (x,y) in movimento3:
desenhar_figura(felipe, x, y)
felipe.penup()
felipe.right(45)
felipe.forward(240)
felipe.pendown()
felipe.left(180)
movimento4 = [(90, -50*2**0.5), (90, -100*2**0.5), (90, -50*2**0.5), (135, -100), (270, -100),
(315, -50*2**0.5), (270, -50*2**0.5), (225, -100), (135, -100*2**0.5), (135, -100),
(135, -100*2**0.5)]
for (x,y) in movimento4:
desenhar_figura(felipe, x, y)
janela.mainloop()
|
# Felipe Martins Gomes
# Comp 20
# Exercício 15.12.3
# Programa compilado com PyCharm 2018.1.2
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def slope_from_origin(self):
return print("{}".format(self.y/self.x))
print("Point(4,10).slope_from_origin()")
Point(4, 10).slope_from_origin()
print("\nPoint(5,5).slope_from_origin()")
Point(5, 5).slope_from_origin()
print("\nPoint(10,1).slope_from_origin()")
Point(10, 1).slope_from_origin()
|
from classes.Ability import Ability
from classes.Enemy import Enemy
class Chicken(Enemy):
# https://www.youtube.com/watch?v=miomuSGoPzI
name = "Chicken"
strength = 5
defense = 0.1
max_mana = 10
max_health = 50
def __init__(self, action_log):
super(Chicken, self).__init__(action_log, self.name, self.strength, self.defense, self.max_mana, self.max_health)
self.abilities += [
Ability(self.action_log, "Chicken Attack", 10, 3),
Ability(self.action_log, "Eat Bug", 0, 1),
Ability(self.action_log, "Peck", 5, 2)
]
|
class ActionLog:
def __init__(self):
self.action_list = []
def write_action_log_to_file(self):
# with statement opens text file, writes action_list in file then closes file.
with open("log.txt",'w') as log:
log.writelines(self.action_list)
# Appends action_list with actions
def add_to_action_list(self, action):
self.action_list.append(action)
|
#!/usr/bin/python
from exercise_1 import fnv
class Dictionary:
def __init__(self, initial_capacity):
self.capacity = initial_capacity
self.hash_table = [[] for _ in range(initial_capacity)] # generate a list of empty lists with the give capacity
def insert(self, string):
position = self.get_key(string)
hash_values = self.hash_table[position] # List of strings that are have been mapped to the same hash key.
if string in hash_values:
raise Exception('The string {} already exists in the dictionary.'.format(string))
hash_values.append(string)
if self.size() > self.capacity/2:
self.capacity *= 2
old_hash_table = self.hash_table
self.hash_table = [[] for _ in range(self.capacity)]
for hash_values in old_hash_table:
for s in hash_values:
self.insert(s)
def remove(self, string):
position = self.get_key(string)
hash_values = self.hash_table[position]
if not string in hash_values:
raise Exception("The string {} is not in the dictionary".format(string))
hash_values.remove(string)
def lookUp(self, string):
position = self.get_key(string)
hash_values = self.hash_table[position]
if string in hash_values:
return string
return None
def size(self):
size = 0
for x in self.hash_table:
if x:
size += 1
return size
def capacity(self):
return self.capacity
def get_key(self, string):
return (fnv(string) % self.capacity)
|
#!/usr/bin/python
class MyComplex:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self): # can be used by invoking "print(...)" on a MyComplex instance
if (self.y >= 0):
sign = "+"
else:
sign = ""
return str(self.x) + "*i" + sign + str(self.y)
def AddSub(self, complexNumber):
add = MyComplex(self.x + complexNumber.x, self.y + complexNumber.y)
sub = MyComplex(self.x - complexNumber.x, self.y - complexNumber.y)
return (add,sub)
|
# list test
classmates = ['Micheal', 'Bob', 'Tracy']
classmates.append('Adam')
classmates.insert(1, 'Jack')
tmp = classmates.pop(1)
print("classmates:", classmates, '\nlen=%d' % len(classmates))
print(tmp)
# tuple test
classtuple = ('Micheal', 'Bob', 'Tracy')
tuple1 = (1, ['Micheal', 'Bob', 'Tracy'])
print(classtuple, tuple1, tuple1[1][2])
# practice
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# 打印Apple:
print(L[0][0])
# 打印Python:
print(L[1][1])
# 打印Lisa:
print(L[2][2])
|
#!/usr/bin/env python
from platform import python_version
print('This is Python version',python_version(),'\n')
mainString = "Python is the best language for String manipulation!"
print(mainString,'\n')
print(mainString[::-1],'\n')
print(mainString[::-2],'\n')
print(mainString.swapcase(),'\n')
print("The sentence '"+mainString+"' contains \n{} 'a' letters, and \n{} 'A' letters!\n".format(mainString.count('a'),mainString.count('A')))
print(mainString.replace(' ', '\n'),'\n')
print(mainString.replace(' ', '\n').upper())
|
import sys
lst = sys.argv[1:]
str1 = " ".join(lst)
summ = eval(str1.replace(" ","+"))
print("The sum of ",str1," is ",summ)
|
#!usr/bin/env python
abbr = input('What is the three letter abbreviation of this course? ')
answer_status = 'wrong'
if abbr == 'ECL': answer_status = 'correct'
if answer_status == 'correct':
print('Your answer is correct')
else:
print('Your answer is wrong')
|
from string import ascii_lowercase
from typing import List, Tuple, Dict
class Stack:
def __init__(self, values=None):
self._values = values or []
def push(self, x):
self._values.append(x)
def pop(self):
return self._values.pop()
def copy(self):
return type(self)(self._values[:])
def plus(*args):
b, a = args
return a + b
def minus(*args):
b, a = args
return a - b
def multiply(*args):
b, a = args
return a * b
def divide(*args):
b, a = args
if b == 0:
return 0
return a // b
def eq(*args):
b, a = args
return a == b
def more(*args):
b, a = args
return int(a > b)
def less(*args):
b, a = args
return int(a < b)
def choose(*args):
b, a, cond = args
return a if cond else b
operation_mapping = {
'+': (plus, 2),
'-': (minus, 2),
'*': (multiply, 2),
'/': (divide, 2),
'<': (less, 2),
'>': (more, 2),
'=': (eq, 2),
'?': (choose, 3),
}
LETTERS = set(ascii_lowercase)
def calc(expression: List[str], values: Dict[str, int], stack: Stack):
""" Calculate given expression with variable values and prepared stack. """
stack = stack.copy()
for symbol in expression:
if symbol in values:
stack.push(values[symbol])
elif symbol in operation_mapping:
func, arg_cnt = operation_mapping[symbol]
args = []
for _ in range(arg_cnt):
# at this moment we have only `int` or `variable` on stack
x = stack.pop()
if isinstance(x, str):
x = values[x]
args.append(x)
stack.push(func(*args))
else:
stack.push(int(symbol))
return stack.pop()
def pre_calc(expression: List[str]) -> Tuple[List[str], Stack]:
""" Simplify expression before first variable. """
stack = Stack()
idx = 0
for idx, symbol in enumerate(expression):
if symbol in LETTERS:
stack.push(symbol)
elif symbol in operation_mapping:
func, arg_cnt = operation_mapping[symbol]
args = [stack.pop() for _ in range(arg_cnt)]
if any((isinstance(x, str)) for x in args):
# cannot process expression because it has variable,
# return values back to stack
for x in reversed(args):
stack.push(x)
# operation hasn't been processed yet,
# we should place it back to expression list
idx -= 1
break
stack.push(func(*args))
else:
stack.push(int(symbol))
return expression[idx + 1:], stack
def main_calc(expression: List[str], values_list: List[Dict[str, int]]) -> List[int]:
pre_expression, pre_stack = pre_calc(expression)
return [calc(pre_expression, values, pre_stack) for values in values_list]
def convert_values_to_dict(expression: str, value_rows: List[str]) -> List[Dict[str, int]]:
variables = sorted({x for x in expression.split() if x.isalpha()})
return [
{var: int(value) for var, value in zip(variables, value_row.split())}
for value_row in value_rows
]
def read() -> Tuple[str, List[str]]:
_ = input()
expression = input()
cases_cnt = int(input())
var_values = [input() for _ in range(cases_cnt)]
return expression, var_values
def main():
expression, var_values = read()
values = convert_values_to_dict(expression, var_values)
for r in main_calc(expression.split(), values):
print(r)
if __name__ == '__main__':
main()
|
# list_avg.py
# Average user-submitted numbers
# Jeff Smith
import math
# Create empty list
nums = []
# Ask user for numbers to evaluate
# Ensure all text is converted to lowercase
ele = input('Enter a number or type done: ').lower()
if ele == 'done':
# If user types 'done', exit
print('Ok. Perhaps another time.')
# If user submits numbers, ask for further numbers
while ele != 'done':
nums.append(ele)
ele = input('Enter a number or type done: ').lower()
# Convert list from strings to ints
nums = [int(x) for x in nums]
# Average user input and pass results to console
print(sum(nums)/len(nums))
|
# lotto.py
# Pick 6-style lottery simulator
# Jeff Smith
'''
Steps
/Loop 100,000 times, for each loop:
/Generate a list of 6 random numbers representing the ticket
/Subtract 2 from the balance (for price of ticket)
/Find how many numbers match
/Add winnings from matches to balance
/After loop, print final balance
/Calculate ROI
'''
import random
def wins():
cost = 2 # Cost of lotto ticket
count = 0 # Tally of number of tickets purchased
# Generate random 6-digit lotto number
lotto = random.sample(range(1, 100), 6)
print(f'The winning numbers are: {lotto}') # Pass lotto number to console
while count < 1000: # Set limit on number of attempts to 1,000
count += 1 # Keep tally of attempts
bal = -2 # Deduct lotto cost from balance
# Generate random 6-digit lotto pick
tix = random.sample(range(1, 100), 6)
# Define the number of matches between ticket and lotto
nums = [i for i, j in zip(tix, lotto) if i == j]
# Define return on investment
roi = 2 * 1000
roi1 = bal - roi
roi2 = roi / roi1
roi3 = int(roi2 * 100)
# Calculate winnings based on number of matches
if len(nums) == 6:
bal += 25000000
elif len(nums) == 5:
bal += 1000000
elif len(nums) == 4:
bal += 50000
elif len(nums) == 3:
bal += 100
elif len(nums) == 2:
bal += 7
elif len(nums) == 1:
bal = + 4
# Pass the results to the console
return(
f'Based on your balance of ${bal} and the ${cost} you spent, the return on your investment is ${roi3}%')
print(wins())
|
# is => es
# is not => no es
frutas = ['carambola','guayaba','higo','melocoton']
fruta = 'carambola'
print(id(fruta))
print(id(frutas))
#el 'is' e 'is not' se usa mas que todo pra validar si las variables a comparar estan apuntando a la misma direccion de memoria o no
#las variables que son colecciones de datos como listas,tuplas y diccionarios son variables mutables
#las otras variables (int, str, float) son variables inmutables
frutas2 = frutas
frutas2.append('fresa')
print(frutas)
print(id(frutas2))
print(id(frutas))
print(frutas2 is frutas)
#las dos variables NO COMPARTEN las misma ubicacion de memoria
print(fruta is frutas)
#variables mutables e inmutables
#para hacer la copia de la lista sin que se ubique en la misma posicion de memoria hacemos uso del copy(propio de las listas)
frutas_variadas = frutas.copy()
print(id(frutas_variadas))
print(id(frutas))
print(frutas_variadas is frutas)
|
import os
import pathlib as Path
from collections import defaultdict
import csv
# os.walk() returns the generator which is of type path, directory, filename
#to check for the unique files in a csv
# from more_itertools import unique_everseen
# with open('1.csv','r') as f, open('2.csv','w') as out_file:
# out_file.writelines(unique_everseen(f))
path = '/Users/mac_admin/Desktop/MIDAS/testing'
def create_list_for_csv(path):
"""
takes path and returns the list containing
the list mapping of parent directory of image : image file name
"""
mapping_dir_img = []
for directory in os.listdir(path):
if directory == '.DS_Store':
continue
else:
newp = path+'/'+directory
for images in os.listdir(newp):
mapping_dir_img.append([directory,images])
return mapping_dir_img
def create_csv(images_list, csv_name):
"""
creates csv file and stores the data..
"""
print('the csv is created in path:', os.getcwd())
with open(csv_name, 'w') as csvfile:
ff = ['labels','images']
writer = csv.writer(csvfile)
writer.writerow(ff)
for images in images_list:
writer.writerow(images)
print('csv file create!')
def checkdirfordir(path,name):
obj = os.scandir(path)
for files in obj:
if files.name == name and files.is_dir:
print('directory is present in the given path..')
print('printing the path to the directory...')
temp = path+str(files.name)
print('Path is::',temp)
print('files/directories in that path:')
print('.....')
print(os.listdir(temp))
temp = create_list_for_csv(path)
create_csv(temp,'mark2.csv')
[('img001-005.png', 'small_o', tensor(0.7097)), ('img001-015.png', 'O', tensor(0.6159)), ('img001-041.png', 'O', tensor(0.5871)), ('img001-028.png', '00', tensor(0.5985)), ('img001-040.png', '00', tensor(0.8653)), ('img001-031.png', 'O', tensor(0.5443)), ('img001-006.png', 'small_o', tensor(0.4994)), ('img001-039.png', '00', tensor(0.5399)), ('img001-048.png', 'O', tensor(0.6689)), ('img001-035.png', 'small_o', tensor(0.6379)), ('img001-032.png', '00', tensor(0.6969)), ('img001-038.png', 'O', tensor(0.8594)), ('img001-020.png', '00', tensor(0.7054)), ('img001-023.png', 'O', tensor(0.7565)), ('img001-022.png', '00', tensor(0.6484))]
[('img002-033.png', '01', tensor(0.9472)), ('img002-022.png', '01', tensor(0.9492)), ('img002-014.png', '01', tensor(0.9988)), ('img002-016.png', 'I', tensor(0.4381)), ('img002-015.png', '01', tensor(0.9963)), ('img002-027.png', 'I', tensor(0.3958)), ('img002-039.png', '01', tensor(0.9915)), ('img002-005.png', '01', tensor(0.5947)), ('img002-051.png', '01', tensor(0.4819)), ('img002-023.png', '01', tensor(0.9996)), ('img002-044.png', 'I', tensor(0.5023)), ('img002-054.png', '01', tensor(0.7846)), ('img002-036.png', 'I', tensor(0.5451)), ('img002-029.png', '01', tensor(0.9852)), ('img002-030.png', '01', tensor(0.8619))]
[('img003-001.png', '02', tensor(1.0000)), ('img003-035.png', '02', tensor(0.9243)), ('img003-014.png', '02', tensor(0.8923)), ('img003-029.png', '02', tensor(0.9993)), ('img003-013.png', '02', tensor(0.9885)), ('img003-038.png', '02', tensor(1.0000)), ('img003-052.png', '02', tensor(0.9948)), ('img003-018.png', '02', tensor(0.9973)), ('img003-051.png', '02', tensor(1.0000)), ('img003-021.png', '02', tensor(0.9946)), ('img003-043.png', '02', tensor(1.0000)), ('img003-046.png', 'small_x', tensor(0.5150)), ('img003-034.png', '02', tensor(0.9897)), ('img003-024.png', '02', tensor(0.9999)), ('img003-007.png', '02', tensor(0.9998))]
[('img004-010.png', '03', tensor(1.0000)), ('img004-032.png', '03', tensor(0.9968)), ('img004-015.png', '03', tensor(0.9982)), ('img004-005.png', '03', tensor(0.9952)), ('img004-053.png', '03', tensor(0.9999)), ('img004-052.png', '03', tensor(0.9986)), ('img004-004.png', '03', tensor(0.6506)), ('img004-051.png', '03', tensor(0.9994)), ('img004-054.png', '03', tensor(0.9998)), ('img004-017.png', '03', tensor(0.9999)), ('img004-019.png', '03', tensor(0.9994)), ('img004-043.png', '03', tensor(0.9991)), ('img004-037.png', '03', tensor(0.9999)), ('img004-046.png', '03', tensor(0.9961)), ('img004-045.png', '03', tensor(0.9996))]
for image 1
[('img001-005.png', 'small_o', tensor(0.7097)), ('img001-015.png', 'O', tensor(0.6159)), ('img001-041.png', 'O', tensor(0.5871)), ('img001-028.png', '00', tensor(0.5985)), ('img001-040.png', '00', tensor(0.8653)), ('img001-031.png', 'O', tensor(0.5443)), ('img001-006.png', 'small_o', tensor(0.4994)), ('img001-039.png', '00', tensor(0.5399)), ('img001-048.png', 'O', tensor(0.6689)), ('img001-035.png', 'small_o', tensor(0.6379)), ('img001-032.png', '00', tensor(0.6969)), ('img001-038.png', 'O', tensor(0.8594)), ('img001-020.png', '00', tensor(0.7054)), ('img001-023.png', 'O', tensor(0.7565)), ('img001-022.png', '00', tensor(0.6484))]
for image 2
[('img002-033.png', '01', tensor(0.9472)), ('img002-022.png', '01', tensor(0.9492)), ('img002-014.png', '01', tensor(0.9988)), ('img002-016.png', 'I', tensor(0.4381)), ('img002-015.png', '01', tensor(0.9963)), ('img002-027.png', 'I', tensor(0.3958)), ('img002-039.png', '01', tensor(0.9915)), ('img002-005.png', '01', tensor(0.5947)), ('img002-051.png', '01', tensor(0.4819)), ('img002-023.png', '01', tensor(0.9996)), ('img002-044.png', 'I', tensor(0.5023)), ('img002-054.png', '01', tensor(0.7846)), ('img002-036.png', 'I', tensor(0.5451)), ('img002-029.png', '01', tensor(0.9852)), ('img002-030.png', '01', tensor(0.8619))]
for image 3
[('img003-001.png', '02', tensor(1.0000)), ('img003-035.png', '02', tensor(0.9243)), ('img003-014.png', '02', tensor(0.8923)), ('img003-029.png', '02', tensor(0.9993)), ('img003-013.png', '02', tensor(0.9885)), ('img003-038.png', '02', tensor(1.0000)), ('img003-052.png', '02', tensor(0.9948)), ('img003-018.png', '02', tensor(0.9973)), ('img003-051.png', '02', tensor(1.0000)), ('img003-021.png', '02', tensor(0.9946)), ('img003-043.png', '02', tensor(1.0000)), ('img003-046.png', 'small_x', tensor(0.5150)), ('img003-034.png', '02', tensor(0.9897)), ('img003-024.png', '02', tensor(0.9999)), ('img003-007.png', '02', tensor(0.9998))]
for image 4
[('img004-010.png', '03', tensor(1.0000)), ('img004-032.png', '03', tensor(0.9968)), ('img004-015.png', '03', tensor(0.9982)), ('img004-005.png', '03', tensor(0.9952)), ('img004-053.png', '03', tensor(0.9999)), ('img004-052.png', '03', tensor(0.9986)), ('img004-004.png', '03', tensor(0.6506)), ('img004-051.png', '03', tensor(0.9994)), ('img004-054.png', '03', tensor(0.9998)), ('img004-017.png', '03', tensor(0.9999)), ('img004-019.png', '03', tensor(0.9994)), ('img004-043.png', '03', tensor(0.9991)), ('img004-037.png', '03', tensor(0.9999)), ('img004-046.png', '03', tensor(0.9961)), ('img004-045.png', '03', tensor(0.9996))]
for image 5
[('img005-015.png', '04', tensor(0.9999)), ('img005-026.png', '04', tensor(0.9996)), ('img005-030.png', '04', tensor(0.6328)), ('img005-053.png', '04', tensor(0.9999)), ('img005-041.png', '04', tensor(0.9996)), ('img005-035.png', '04', tensor(0.9999)), ('img005-010.png', '04', tensor(1.0000)), ('img005-003.png', '04', tensor(0.9999)), ('img005-006.png', '04', tensor(0.9991)), ('img005-028.png', '04', tensor(0.9990)), ('img005-018.png', '04', tensor(0.9997)), ('img005-040.png', '04', tensor(0.9998)), ('img005-019.png', '04', tensor(0.9998)), ('img005-043.png', '04', tensor(0.9999)), ('img005-039.png', '04', tensor(0.9998))]
for image 6
[('img006-040.png', '05', tensor(1.0000)), ('img006-013.png', '05', tensor(1.0000)), ('img006-031.png', '05', tensor(0.9999)), ('img006-037.png', '05', tensor(0.9999)), ('img006-046.png', '05', tensor(0.8876)), ('img006-054.png', '05', tensor(0.9553)), ('img006-019.png', '05', tensor(0.9987)), ('img006-044.png', '05', tensor(1.0000)), ('img006-033.png', '05', tensor(0.7419)), ('img006-047.png', '05', tensor(1.0000)), ('img006-016.png', 'S', tensor(0.8867)), ('img006-028.png', '05', tensor(1.0000)), ('img006-002.png', '05', tensor(1.0000)), ('img006-048.png', '05', tensor(0.9999)), ('img006-034.png', '05', tensor(0.9848))]
for image 7
[('img007-055.png', '06', tensor(0.9991)), ('img007-007.png', '06', tensor(0.9974)), ('img007-053.png', '06', tensor(0.9764)), ('img007-020.png', '06', tensor(1.0000)), ('img007-006.png', '06', tensor(0.5244)), ('img007-030.png', '06', tensor(0.5524)), ('img007-021.png', '06', tensor(0.9677)), ('img007-009.png', '06', tensor(0.9749)), ('img007-037.png', '06', tensor(0.9997)), ('img007-016.png', '06', tensor(0.9999)), ('img007-051.png', '06', tensor(0.9999)), ('img007-048.png', '06', tensor(0.9997)), ('img007-043.png', '06', tensor(0.9993)), ('img007-028.png', '06', tensor(0.9999)), ('img007-035.png', '06', tensor(0.9543))]
for image 8
[('img008-054.png', 'small_f', tensor(0.9589)), ('img008-048.png', '07', tensor(0.9984)), ('img008-025.png', '07', tensor(0.9981)), ('img008-001.png', '07', tensor(0.9275)), ('img008-036.png', '07', tensor(0.9996)), ('img008-022.png', '07', tensor(0.9995)), ('img008-037.png', '07', tensor(0.9999)), ('img008-030.png', '07', tensor(1.0000)), ('img008-043.png', '07', tensor(0.9994)), ('img008-006.png', '07', tensor(0.9894)), ('img008-020.png', '07', tensor(0.9997)), ('img008-004.png', '07', tensor(0.6930)), ('img008-050.png', '07', tensor(0.9996)), ('img008-051.png', '07', tensor(0.9989)), ('img008-045.png', '07', tensor(0.9917))]
for image 9
[('img009-027.png', '08', tensor(1.0000)), ('img009-050.png', '08', tensor(1.0000)), ('img009-014.png', '08', tensor(1.0000)), ('img009-043.png', '08', tensor(0.9999)), ('img009-055.png', '08', tensor(0.9999)), ('img009-053.png', '08', tensor(0.9994)), ('img009-025.png', '08', tensor(1.0000)), ('img009-033.png', '08', tensor(0.4942)), ('img009-019.png', '08', tensor(1.0000)), ('img009-004.png', '08', tensor(0.9977)), ('img009-044.png', '08', tensor(1.0000)), ('img009-048.png', '08', tensor(0.9999)), ('img009-031.png', '08', tensor(1.0000)), ('img009-021.png', '08', tensor(0.9936)), ('img009-002.png', '08', tensor(0.9999))]
image_path = '/content/drive/MyDrive/test/Sample004'
sp004 = os.listdir(image_path)
sp004
image_path = '/content/drive/MyDrive/test/Sample004'
res = []
for i in sp004:
image_path = os.path.join(image_path,i)
pred,pred_idx,probs = inference.predict(image_path)
image_path = '/content/drive/MyDrive/test/Sample004'
res.append((i,pred, probs[pred_idx]))
print(res)
for i in range(1,10):
image_path = '/content/drive/MyDrive/test/Sample/00'+'i'
def automate(path):
for i in range(62):
arr = os.listdir(path)
res = []
for j in arr:
image_path = os.path.join(path,j)
pred,pred_idx,probs = inference.predict(image_path)
image_path = path
res.append(j,pred,probs[pred_idx])
print('for image',i)
print(res)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 23:29:36 2020
@author: Saurabh Kumbhar
"""
import turtle
def drawHangman(chance,exitStatus):
if(chance == 7):
#Step 1
turtle.circle(50)
if(chance == 6):
#Step 2
turtle.right(90)
turtle.forward(100)
if(chance == 5):
#Step 3
turtle.left(60)
turtle.forward(70)
if(chance == 4):
#Step 4
turtle.backward(70)
turtle.right(120)
turtle.forward(70)
if(chance == 3):
#Step 5
turtle.backward(70)
turtle.right(120)
turtle.forward(50)
turtle.right(90)
turtle.fd(70)
if(chance == 2):
#Step 6
turtle.bk(140)
if(chance == 1):
#Step 7
turtle.fd(70)
turtle.left(90)
turtle.fd(50)
turtle.right(90)
turtle.circle(60)
if(chance == 0):
#Step 8
t = turtle.Pen()
for x in range(180):
t.forward(1)
t.left(1)
t.right(90)
t.fd(100)
if(exitStatus == 1):
turtle.done()
|
#OpenCV Resize image using cv2.resize()
#Resizing an image means changing the dimensions of it, be it width alone, height alone or both. Also, the aspect ratio of the original image could be preserved in the resized image. To resize an image, OpenCV provides cv2.resize() function.
#In this tutorial, we shall the syntax of cv2.resize and get hands-on with examples provided for most of the scenarios encountered in regular usage.
#OpenCV Python – Resize image
#Syntax of cv2.resize()
#Following is the syntax of resize function in OpenCV:
#cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
#The description about the parameters of resize function.
#Parameter Description
#src [required] source/input image
#dsize [required] desired size for the output image
#fx [optional] scale factor along the horizontal axis
#fy [optional] scale factor along the vertical axis
#interpolation [optional] flag that takes one of the following methods. INTER_NEAREST – a nearest-neighbor interpolation
#a Lanczos interpolation over 8×8 pixel neighborhood
#it is similar to the INTER_NEAREST method. INTER_CUBIC – a bicubic interpolation over 4×4 pixel neighborhood INTER_LANCZOS4 –
#INTER_LINEAR – a bilinear interpolation (used by default) INTER_AREA –
#It may be a preferred method for image decimat
# resampling using pixel area relation.ion, as it gives moire’-free results. But when the image is zoomed,
import cv2
img = cv2.imread('lena.png')
print('Original Dimensions : ',img.shape)
scale_percent = 220 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
print('Resized Dimensions : ',resized.shape)
cv2.imshow("Resized image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
#Original Dimensions : (512, 512, 3) (height,width,layer)
#Resized Dimensions : (1126, 1126, 3) (height,width,layer)
|
import cv2
import numpy as np
img =cv2.imread('lena.jpg')
height ,width =img.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((width/2,height/2),70,.5)
#getRotationMatrix2D is a function and rotate the img and (width,height ,angle,scaling factor)
#Means scaling factor will increase then img information destroy and scaling factor is decrease then img of information increase
#This rotation_matrix through image rotate
#Syntax of cv2: rotate image
# M(Matrix) = cv2.getRotationMatrix2D(center, angle, scale)
#rotated = cv2.warpAffine(img, M, (w, h))
rotated_img = cv2.warpAffine(img , rotation_matrix , (width,height))
cv2.imshow("Rotated Image", rotated_img)
cv2.imshow("Original Image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
def emptyMatrix(n):
result = []
for i in range(n):
result.append([])
for j in range(n):
result[i].append(0)
return result
def mul(X, Y):
result = emptyMatrix(len(X))
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result
def transpose(X):
result = emptyMatrix(len(X))
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
return result
a = [[1,2],[2,3]]
b = [[3,2],[2,1]]
c = mul(a,b)
print(c)
d = transpose(c)
print(d)
|
import winsound, time, os, platform
def sound():
for i in range(2): # Number of repeats
for j in range(9): # Number of beeps
winsound.MessageBeep(-1) # Sound played
time.sleep(2) # How long between beeps
def alarm(n):
print()
print("Wait time:", n, "seconds.")
time.sleep(n) # Waits 'n' seconds before playing sound
sound()
def input_destinations(user_input):
if user_input == '1':
user_input = int(input("Enter the desired hours: "))
wait_time = (user_input * 60) * 60
alarm(wait_time)
elif user_input == '2':
user_input = int(input("Enter the desired minutes: "))
wait_time = user_input * 60
alarm(wait_time)
elif user_input == '3':
user_input = int(input("Enter the desired seconds: "))
wait_time = user_input
alarm(wait_time)
elif user_input == '4':
hours = int(input("Hours: "))
minutes = int(input("Minutes: "))
seconds = int(input("Seconds: "))
wait_time = ((hours * 60) * 60) + (minutes * 60) + seconds
print(wait_time)
alarm(wait_time)
else:
try:
os.system('cls') # If OS is Windows
main()
except:
os.system('clear') # If OS is Linux or Mac
main()
def main():
print("What unit of time do you want to wait?\n (1) Hours\n (2) Minutes\n (3) Seconds\n (4) Combination")
main_input = input(": ")
input_destinations(main_input)
return;
main()
|
#student1, fireman, and doctor are all parts of the human class.
class Human:
def __init__(self,Name, Gender, Age):
self.gender = Gender
self.age = Age
self.name = Name
def run(self):
print('{name} is running.'.format(name=self.name))
class Student1(Human):
def study(self):
print('%s is studying.' % self.name)
class fireman(Human):
def fire(self):
print('%s is fighting fire.' %self.name)
class doctor(Human):
def docting(self):
self.name = 'Dr. '+self.name
print('%s is checking temperatures.' %self.name)
student = Student1('David','male',23)
a = fireman('Joe', 'male', 30)
b = doctor('Mary', 'female', 28)
print(student.gender, student.age, sep="\n")
student.run()
student.study()
a.fire()
b.docting()
|
'''
Created on Aug 21, 2017
@author: anhvu
'''
n = int(input());
edgeLen = 2;
for i in range(n):
edgeLen += edgeLen - 1;
print(pow(edgeLen, 2));
|
'''
Created on Jul 20, 2017
@author: anhvu
'''
from math import sqrt
triple = [int(i) for i in input().split(" ")];
n = triple[0];
w = triple[1];
h = triple[2];
diagonal = sqrt(w * w + h * h);
for j in range(n):
l = int(input());
# print(j, ":", n, ":", l);
if (l <= diagonal):
print("DA");
else:
print("NE");
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 13
@author: 陈佳榕
某个数字建筑领域公司的笔试题目
要求实现顺时针打印矩阵
比如对于矩阵
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
打印出1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
"""
def clockwisePrint(matrix):
"""
:param matrix:list[list],二维矩阵
:rtype :list,顺时针打印出来的矩阵元素
"""
left = top = 0;
bottom = len(matrix) - 1;
if bottom == -1:
return;
right = len(matrix[0]) - 1;
if right == -1:
return;
count = 0;
totalNum = (bottom + 1) * (right + 1);
i = j = 0;
result = [];
allowRight = True;
while count < totalNum:
result.append(matrix[i][j]);
count += 1;
if j > left and j < right: #1.如果不在左墙或右墙
if i == top: #且在上墙的话,直接右移
j += 1;
allowDown = True;
else: #在下墙的话,直接左移
j -= 1;
allowUp = True;
elif j == left: #2.如果在左墙的话
if i == top: #在上墙的话,右移
j += 1;
if top != 0 and allowRight: #除了刚开始不用移动左墙,其他情况左墙都需要右移
left += 1;
allowRight = False;
elif i == bottom: #在下墙的话,上移且下墙上移
i -= 1;
if allowUp:
bottom -= 1;
allowUp = False;
else: #不在上墙或下墙,直接上移
i -= 1;
allowRight = True;
else: #3.如果在右墙的话
if i == top: #在上墙,下移且上墙下移
i += 1;
if allowDown:
top += 1;
allowDown = False;
elif i == bottom: #在下墙,左移且右墙左移
j -= 1;
if allowLeft:
right -= 1;
allowLeft = False;
else: #不在上墙或下墙,直接下移
i += 1;
allowLeft = True;
return result;
if __name__ == '__main__':
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];
print(clockwisePrint(matrix));
|
def compare(a,b,c):
if (a > b > c):
return a
elif (a > c > b):
return a
elif (b > a > c):
return b
elif (b > c > a):
return b
elif (c > a > b):
return c
else:
return c
a = int(input())
b = int(input())
c = int(input())
print(compare(a, b, c))
|
list = []
length = int(input())
list = input().split()
place = 1
x = 0
lowest = int(0)
while x < len(list):
if int(list[x]) <= int(lowest):
lowest = list[x]
place = x
x += 1
else:
x+=1
if len(list) > length:
print('Sua lista é maior que o esperado, mas:')
print('Menor valor:', lowest)
print('Posicao:', place)
elif len(list) < length:
print('Sua lista é menor que o esperado, mas:')
print('Menor valor:', lowest)
print('Posicao:', place)
else:
print('Menor valor:', lowest)
print('Posicao:', place)
|
def fatorial(n):
if n < 2:
return 1
if n % 2 == 1:
return n * fatorial(n-1)
else:
return fatorial(n-1)
n = int(input("Digite o valor que deseja saber o fatorial: "))
print(fatorial(n))
|
import queue #inbuilt stacks and queue
q = queue.Queue(maxsize = 10) #inbuilt queue
q.put(1)
q.put(2)
q.put(3)
q.put(4)
print(q.qsize())
while not q.empty():
print(q.get())
q = queue.LifoQueue() #inbuilt stack
q.put(1)
q.put(2)
q.put(3)
while not q.empty():
print(q.get())
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def midpoint_linkedlist(head):
slow = head
fast = head
while fast.next and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def merge(head1,head2):
final_head = None
final_tail = None
if head1.data < head2.data:
final_head = head1
final_tail = head1
head1 = head1.next
while head1 != None and head2 != None:
if head1.data > head2.data:
final_tail.next = head2
final_tail = final_tail.next
head2 = head2.next
else:
final_tail.next = head1
final_tail = final_tail.next
head1 = head1.next
else:
final_head = head2
final_tail = head2
head2 = head2.next
while head1 != None and head2 != None:
if head1.data > head2.data:
final_tail.next = head2
final_tail = final_tail.next
head2 = head2.next
else:
final_tail.next = head1
final_tail = final_tail.next
head1 = head1.next
if(head1 is not None):
final_tail.next=head1
if(head2 is not None):
final_tail.next=head2
return final_head
def length(head):
count = 0
while head is not None:
count = count + 1
head = head.next
return count
def mergeSort(head):
if length(head) == 0 or length(head) == 1:
return head
mid = midpoint_linkedlist(head)
head2 = mid.next
mid.next = None
left=mergeSort(head)
right=mergeSort(head2)
shead=merge(left,right)
return shead
def ll(arr):
if len(arr)==0:
return None
head = Node(arr[0])
last = head
for data in arr[1:]:
last.next = Node(data)
last = last.next
return head
def printll(head):
while head:
print(head.data, end=' ')
head = head.next
print()
arr=list(int(i) for i in input().strip().split(' '))
l = ll(arr[:-1])
l = mergeSort(l)
printll(l)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
def midpoint_linkedlist(head):
slow = head
fast = head
while fast.next and fast.next.next is not None:
slow = slow.next
fast = fast.next.next
return slow
def ll(arr):
if len(arr)==0:
return None
head = Node(arr[0])
last = head
for data in arr[1:]:
last.next = Node(data)
last = last.next
return head
arr=list(int(i) for i in input().strip().split(' '))
l = ll(arr[:-1])
node = midpoint_linkedlist(l)
if node:
print(node.data)
|
import queue
class Graph:
def __init__(self, nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)] for j in range(nVertices)]
def addEdge(self, v1, v2):
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
def __dfsHelper(self, sv, visited):
print(sv)
visited[sv] = True
for i in range(self.nVertices):
if self.adjMatrix[sv][i] > 0 and visited[i] is False:
self.__dfsHelper(i, visited)
def dfs(self):
visited = [False for i in range(self.nVertices)]
for i in range(self.nVertices):
if visited[i] is False:
self.__dfsHelper(i, visited)
def __bfsHelper(self, sv, visited):
q = queue.Queue()
q.put(sv)
visited[sv] = True
while q.empty() is False:
u = q.get()
print(u)
for i in range(self.nVertices):
if self.adjMatrix[u][i] > 0 and visited[i] is False:
q.put(i)
visited[i] = True
def bfs(self):
visited = [False for i in range(self.nVertices)]
for i in range(self.nVertices):
if visited[i] is False:
self.__bfsHelper(i, visited)
def removeEdge(self, v1, v2):
if self.containsEdge(v1, v2) is False:
return
self.adjMatrix[v1][v2] = 0
self.adjMatrix[v2][v1] = 0
def containsEdge(self, v1, v2):
if self.adjMatrix[v1][v2] > 0:
return True
else:
return False
def __str__(self):
return str(self.adjMatrix)
g = Graph(5)
g.addEdge(0, 1)
g.addEdge(1, 3)
g.addEdge(2, 4)
print(g)
g = Graph(5)
g.addEdge(0, 1)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 3)
g.addEdge(0, 2)
g.dfs()
g = Graph(5)
g.addEdge(0, 1)
g.addEdge(1, 3)
g.addEdge(2, 4)
g.addEdge(2, 3)
g.addEdge(0, 2)
g.bfs()
|
import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printAtK(root,k,lst):
t=k
if root is None:
return
if k==0 or t==0:
print(root.data)
return 0
else:
printAtK(root.left,k-1,lst)
printAtK(root.right, t -1, lst)
def printkDistanceNodeDown(root,k):
if root==None:
return
if k==0:
print(root.data)
return
printkDistanceNodeDown(root.left,k-1)
printkDistanceNodeDown(root.right,k-1)
def printkDistanceNode(root, target, k):
if root is None:
return -1
if root.data == target:
printkDistanceNodeDown(root, k)
return 0
dl = printkDistanceNode(root.left, target, k)
if dl != -1:
if dl + 1 == k :
print(root.data)
else:
printkDistanceNodeDown(root.right, k-dl-2)
return 1 + dl
dr = printkDistanceNode(root.right, target, k)
if dr != -1:
if (dr+1 == k):
print(root.data)
else:
printkDistanceNodeDown(root.left, k-dr-2)
return 1 + dr
return -1
def buildLevelTree(levelorder):
index = 0
length = len(levelorder)
if length<=0 or levelorder[0]==-1:
return None
root = BinaryTreeNode(levelorder[index])
index += 1
q = queue.Queue()
q.put(root)
while not q.empty():
currentNode = q.get()
leftChild = levelorder[index]
index += 1
if leftChild != -1:
leftNode = BinaryTreeNode(leftChild)
currentNode.left =leftNode
q.put(leftNode)
rightChild = levelorder[index]
index += 1
if rightChild != -1:
rightNode = BinaryTreeNode(rightChild)
currentNode.right =rightNode
q.put(rightNode)
return root
levelOrder = [int(i) for i in input().strip().split()]
root = buildLevelTree(levelOrder)
node = int(input())
k=int(input())
printkDistanceNode(root, node, k)
|
'''
输入一个整数和进制,转换成十进制输出
输入格式:
在一行输入整数和进制
输出格式:
在一行十进制输出结果
'''
source=input().split(",")
out=int(source[0],int(source[1]))
print(out)
|
'''
缩写词是由一个短语中每个单词的第一个字母组成,均为大写。例如,CPU是短语“central processing unit”的缩写。
函数接口定义:
acronym(phrase);
phrase是短语参数,返回短语的缩写词
裁判测试程序样例:
/* 请在这里填写答案 */
phrase=input()
print(acronym(phrase))
输入样例:
central processing unit
输出样例:
CPU
'''
def acronym(phrase):
output=''
for i in phrase.split():
first_str=i[0]
if first_str.isupper():
output+=first_str
else:
output+=first_str.upper()
return output
phrase=input()
print(acronym(phrase))
|
'''
本题要求将输入的任意3个整数从小到大输出。
输入格式:
输入在一行中给出3个整数,其间以空格分隔。
输出格式:
在一行中将3个整数从小到大输出,其间以“->”相连。
'''
list1=input().split(" ")
list3=[]
for i in list1:
list3.append(int(i))
list1=list3
list2=[]
while list1:
MIN=list1[0]
for i in list1:
if i < MIN:
MIN=i
list2.append(str(MIN))
list1.remove(MIN)
out="->".join(list2)
print(out)
|
# self hace referencia al propio objeto, y sirve para diferneciar entre el ambito de clase
#y el ambito del método
class Galleta:
chocolate=False
def __init__(self):
print('Acabas de crear una galleta')
def untar_chocolate(self):
# chocolate=True #esto hace referencia a una variable de la función untar_chocolate
self.chocolate = True
una_galleta = Galleta()
print(una_galleta.chocolate) # False
una_galleta.untar_chocolate()
print(una_galleta.chocolate) # True
|
#designed and coded by Jacqueline St Pierre
class NPC:
def __init__(self, mobType, level=1, attack=1, defense=1, startX=0, startY=0):
if(level<1 or attack<0 or defense<0):
print("Invalid Input")
self.valid = False
else:
self.valid = True
self.level = level
self.mobType = mobType
self.attack = attack
self.defense = defense
self.startX = startX
self.startY = startY
def displayStats(self):
# print("The mob's level is:\t\t" + str(self.level))
# print("The mob's type is:\t\t" + str(self.mobType))
# print("The mob's attack level is:\t" + str(self.attack))
# print("The mob's defense level is:\t" + str(self.defense))
# print("The mob's startX point is:\t" + str(self.startX))
# print("The mob's startY point is:\t" + str(self.startY))
if(self.valid==True):
print("Mob\tLevel\tX,Y\tAttack\tDefense")
print(str(self.mobType) + "\t" + str(self.level) + "\t" + str(self.startX)+", "+str(self.startY) + "\t" + str(self.attack) + "\t" + str(self.defense))
else:
print("This mob is invalid")
def generateMobs(rect, lvl):
randVal = random.randrange(3)
if randVal == 0:
xLen, yLen, bottomLeftXCord, bottomLeftYCord = rect
xLen = xLen-2
yLen = yLen-2
bottomLeftXCord = bottomLeftXCord + 1
bottomLeftYCord = bottomLeftYCord + 1
rectPoints = []
for i in range (yLen):
for j in range (xLen):
rectPoints.append((bottomLeftYCord+i,bottomLeftXCord+j,))
rectPoints = list(set(rectPoints))
newPoints = rectPoints[:]
val = len(newPoints)
randPoint = random.choice(newPoints)
return(Mob("Zombie", lvl, lvl*2, lvl*3, randPoint[1],randPoint[0]))
else:
return 0
def main(rectangles, lvl):
mobList = []
for i in rectangles:
thing = generateMobs(i, lvl)
if thing == 0:
continue
else:
mobList.append(thing)
return mobList
|
#https://pythonworld.ru/osnovy/tasks.html №5
def bank(deposit, years):
i = 0
while i < years:
deposit = deposit * 0.01 + deposit
i += 1
return round(deposit, 2)
if __name__ == "__main__":
deposit = int(input('Введите сумму депозита: '))
years = int(input('Введите количество лет: '))
print ('Расчет по ставке 10% годовых: ')
print(bank(deposit, years))
|
# Planner
# COMPLETED
# 1.0) Create chess board array, subclasses for colour and piece type, place in starting
# 1.1) Possible moves - Each piece is unique
# 2.0) Implement UI using pygame (drawing board, drawing pieces, alternating square colours)
# 1.2) Check mechanism - Valid moves (all of the other player's next possible moves attack your king in new position)
# 1.32) Moving a piece on the same square ?!!?!
# 2.1) Implement drag drop - moving pieces using cursor
# 1.4) Undo function, log system,
# 1.32) Moving a piece on the same square ?!!?!
# 2.0) Available moves function
# ONGOING
# 1.3) Special moves - Castling (both sides), pawn promotion, en pessant, pawn moves double ranks??
# 1.31) CHECKMATE, STALEMATE, in check (should you be able to click on other pieces that can't stop the check?)
# FUTURE
# 3.0) Basic chess AI
# - - - - - - - - - - - - - - - - - - - -
import copy
DIMENSION = 8
EMPTY = "--"
cur_turn = 'white'
## Functions
## Classes
class Piece():
def __init__(self, colour, row, col):
self.colour = colour
self.row = row
self.col = col
self.moved = False
self.available_moves = []
def __repr__(self): # TODO: Should be __str__
class_name = type(self).__name__
if class_name == 'Knight':
class_name = 'Night'
return "{}{}".format(self.colour[0], class_name[0]) # Returns 2 letter string showing colour and piece type respectively
# def __repr__(self):
# return "{}('{}', '{}', '{}')".format(type(self).__name__, self.colour, self.col, self.row)
# Moves piece at original square to the target square
def piece_move(self, target_row, target_col):
chess_board[target_row][target_col] = chess_board[self.row][self.col]
chess_board[self.row][self.col] = EMPTY
self.row = target_row
self.col = target_col
self.moved = True
# Function that can capture and/or move
def piece_move_capture(self, target_row, target_col):
# Ensure only capture a piece within our 8 x 8 array
# assert (0 <= target_row and target_row <= DIMENSION - 1)
# assert (0 <= target_col and target_row <= DIMENSION - 1)
# Piece capture : Target piece can only be captured if object exists at location (not a string)
# if not isinstance(chess_board[target_row][target_col], str):
if chess_board[target_row][target_col] == EMPTY or chess_board[target_row][target_col].colour != self.colour:
add_to_undo()
self.moved = True
self.piece_move(target_row, target_col)
return True
return False
# Loop through available moves list, if target square matches a tuple in available moves list, return move capture function
# TODO: Changge move_cap function name
def move_cap(self, target_row, target_col):
curr_available_moves = copy.deepcopy(self.available_moves)
self.available_moves.clear()
for i in curr_available_moves:
if (target_row, target_col) == i:
if (target_row == 7 or target_row == 0) and isinstance(self, Pawn): # checking for promotion
return self.promote(target_row, target_col)
if isinstance(self, King):
print("king moving")
if target_row == self.row and target_col == 2:
self.castle(target_row, target_col, chess_board[self.row][self.col-4], 3)
return True
if target_row == self.row and target_col == 6:
self.castle(target_row, target_col, chess_board[self.row][self.col+3], 5)
return True
#if self.piece_move_capture
# 1) Run is_in_check function (checks if your OWN king is in check)
# 2) For the piece in question (clicked) , loop through available moves and save the ones which 'stop' the check (using is_in_check), either by capturing or blockinig
# 2.1 Dont open your own king up to check (run is_in_check again, take out invalid moves)
# 3) Update the saved squares as the new available moves
return self.piece_move_capture(target_row, target_col)
return False
# For knights (one square)
def empty_or_enemy(self, possible_row, possible_col):
if chess_board[possible_row][possible_col] is EMPTY:
self.available_moves.append((possible_row, possible_col))
else:
if chess_board[possible_row][possible_col].colour != self.colour:
self.available_moves.append((possible_row, possible_col))
# For bishops and rooks (row, column or diagonals)
def loop_empty_or_enemy(self, possible_row, possible_col):
if chess_board[possible_row][possible_col] is EMPTY:
self.available_moves.append((possible_row, possible_col))
return True
else:
if chess_board[possible_row][possible_col].colour != self.colour:
self.available_moves.append((possible_row, possible_col))
return False
# Loops through EVERY enemy piece's available moves and if any matches your king's square, you are in check
def is_in_check():
pass
## Subclasses
class Pawn(Piece):
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_available_moves(self):
# Ability to move white up by one, or down by one for black pieces (if nothing blocking)
calc = -1 # Default white case
if self.colour == 'black':
calc = 1
# Pawn advance : Target square is one space forward, ensure it contains EMPTY
if 0 <= self.row + calc and self.row + calc <= DIMENSION - 1:
if chess_board[self.row + calc][self.col] == EMPTY:
self.available_moves.append((self.row + calc, self.col))
# Pawn double advance : Target square is two spaces forward, if on starting rank
if 0 <= self.row + 2*calc and self.row + 2*calc <= DIMENSION - 1:
if chess_board[self.row + 2*calc][self.col] == EMPTY and chess_board[self.row + calc][self.col] == EMPTY and self.row == 3.5 - 2.5 * calc:
self.available_moves.append((self.row + 2*calc, self.col))
# Pawn diagonal capture : If target square is the one square diagonally forward (left)
if 0 <= self.row + calc and self.row + calc <= DIMENSION - 1 and 0 <= self.col + calc and self.col + calc <= DIMENSION - 1:
if chess_board[self.row + calc][self.col + calc] != EMPTY:
if chess_board[self.row + calc][self.col + calc].colour != self.colour:
self.available_moves.append((self.row + calc, self.col + calc))
# Pawn diagonal capture : Forward right
if 0 <= self.row + calc and self.row + calc <= DIMENSION - 1 and 0 <= self.col - calc and self.col - calc <= DIMENSION - 1:
if chess_board[self.row + calc][self.col - calc] != EMPTY:
if chess_board[self.row + calc][self.col - calc].colour != self.colour:
self.available_moves.append((self.row + calc, self.col - calc))
def promote(self, target_row, target_col):
if chess_board[target_row][target_col] == EMPTY or chess_board[target_row][target_col].colour != self.colour:
add_to_undo()
chess_board[self.row][self.col] = EMPTY
chess_board[target_row][target_col] = Queen(self.colour, target_row, target_col)
return True
return False
class Queen(Piece):
# TODO: Put rook and bishop available moves into functiions (shorten code)
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_rook_available_moves(self):
# Looping vertically up and down the board from current position
for i in range(self.row - 1, -1, -1): # Range function doesn't include the end range number, so its -1 not 0
keep_looping = self.loop_empty_or_enemy(i, self.col)
if keep_looping == False:
break
# if chess_board[i][self.col] is EMPTY:
# self.available_moves.append((i, self.col))
# else:
# # If first non EMPTY square is opposite colour, add the potentially capture square to available moves
# if chess_board[i][self.col].colour != self.colour:
# self.available_moves.append((i, self.col))
# # Rook doesn't move through pieces
# break
for i in range(self.row + 1, DIMENSION, 1):
keep_looping = self.loop_empty_or_enemy(i, self.col)
if keep_looping == False:
break
# Horizontal
for i in range(self.col - 1, -1, -1):
keep_looping = self.loop_empty_or_enemy(self.row, i)
if keep_looping == False:
break
for i in range(self.col + 1, DIMENSION, 1):
keep_looping = self.loop_empty_or_enemy(self.row, i)
if keep_looping == False:
break
def get_bishop_available_moves(self):
# Upwards right
i = 1
while (self.row - i > -1 and self.col + i < DIMENSION):
keep_looping = self.loop_empty_or_enemy(self.row - i, self.col + i)
if keep_looping == False:
break
i += 1
# Upwards left
i = 1
while (self.row - i > -1 and self.col - i > -1):
keep_looping = self.loop_empty_or_enemy(self.row - i, self.col - i)
if keep_looping == False:
break
i += 1
# Downwards left
i = 1
while (self.row + i < DIMENSION and self.col - i > -1):
keep_looping = self.loop_empty_or_enemy(self.row + i, self.col - i)
if keep_looping == False:
break
i += 1
# Downwards right
i = 1
while (self.row + i < DIMENSION and self.col + i < DIMENSION):
keep_looping = self.loop_empty_or_enemy(self.row + i, self.col + i)
if keep_looping == False:
break
i += 1
def get_available_moves(self):
# Target square is a horizontal, vertical or diagonal
return self.get_rook_available_moves() or self.get_bishop_available_moves()
class Rook(Queen):
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_available_moves(self):
return self.get_rook_available_moves()
class Bishop(Queen):
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_available_moves(self):
return self.get_bishop_available_moves()
class Knight(Piece):
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_available_moves(self):
for n_possible_row in range(0, DIMENSION):
for n_possible_col in range(0, DIMENSION):
# L shape movement
if abs(n_possible_row - self.row) == 2 and abs(n_possible_col - self.col) == 1:
self.empty_or_enemy(n_possible_row, n_possible_col)
if abs(n_possible_row - self.row) == 1 and abs(n_possible_col - self.col) == 2:
self.empty_or_enemy(n_possible_row, n_possible_col)
class King(Piece):
def __init__(self, colour, row, col):
super().__init__(colour, row, col)
def get_available_moves(self):
for k_possible_row in range(0, DIMENSION):
for k_possible_col in range(0, DIMENSION):
# Left, right, up, down
if abs(k_possible_row - self.row) + abs(k_possible_col - self.col) == 1:
self.empty_or_enemy(k_possible_row, k_possible_col)
# Diagonally - up left, up right, down left, down right
if abs(k_possible_row - self.row) == abs(k_possible_col - self.col) == 1:
self.empty_or_enemy(k_possible_row, k_possible_col)
if self.moved == False:
if k_possible_row == self.row and k_possible_col == 6: #right side castle
rook = chess_board[self.row][self.col+3]
if chess_board[self.row][self.col + 1] == EMPTY and chess_board[self.row][self.col+2] == EMPTY and isinstance(rook, Rook) == True and rook.moved == False:
self.available_moves.append((self.row,6))
elif k_possible_row == self.row and k_possible_col == 2: #left side castle
rook = chess_board[self.row][self.col-4]
if chess_board[self.row][self.col - 1] == EMPTY and chess_board[self.row][self.col-2] == EMPTY and chess_board[self.row][self.col-3] == EMPTY and \
isinstance(rook, Rook) == True and rook.moved == False:
self.available_moves.append((self.row, 2))
def castle(self, target_row, target_col, rook, rook_col):
print("castled")
add_to_undo()
self.piece_move(target_row, target_col)
rook.piece_move(target_row, rook_col)
def add_to_undo():
copy_array = [[],[],[],[],[],[],[],[]]
for i in range(DIMENSION):
copy_array[i] = copy.deepcopy(chess_board[i])
last_board_state.append(copy_array)
cur_turn = 'white'
def flip_sides():
global cur_turn
if cur_turn == 'white':
cur_turn = 'black'
else:
cur_turn = 'white'
def undoMove():
global chess_board
global last_board_state
if (last_board_state == []): # if empty
return
print(chess_board)
print("\n")
print(last_board_state)
for i in range(DIMENSION):
chess_board[i] = copy.deepcopy(last_board_state[-1][i])
last_board_state.pop()
flip_sides()
# Creating all the pieces and placing them in their starting positions
bR1 = Rook('black', 0, 0)
bN1 = Knight('black', 0, 1)
bB1 = Bishop('black', 0, 2)
bQ = Queen('black', 0, 3)
bK = King('black', 0, 4)
bB2 = Bishop('black', 0, 5)
bN2 = Knight('black', 0, 6)
bR2 = Rook('black', 0, 7)
bP1 = Pawn('black', 1, 0)
bP2 = Pawn('black', 1, 1 )
bP3 = Pawn('black', 1, 2)
bP4 = Pawn('black', 1, 3)
bP5 = Pawn('black', 1, 4)
bP6 = Pawn('black', 1, 5)
bP7 = Pawn('black', 1, 6)
bP8 = Pawn('black', 1, 7)
wP1 = Pawn('white', 6, 0)
wP2 = Pawn('white', 6, 1)
wP3 = Pawn('white', 6, 2)
wP4 = Pawn('white', 6, 3)
wP5 = Pawn('white', 6, 4)
wP6 = Pawn('white', 6, 5)
wP7 = Pawn('white', 6, 6)
wP8 = Pawn('white', 6, 7)
wR1 = Rook('white', 7, 0)
wN1 = Knight('white', 7, 1)
wB1 = Bishop('white', 7, 2)
wQ = Queen('white', 7, 3)
wK = King('white', 7, 4)
wB2 = Bishop('white', 7, 5)
wN2 = Knight('white', 7, 6)
wR2 = Rook('white', 7, 7)
# 8 by 8 2D array
chess_board = [
[bR1, bN1, bB1, bQ, bK, bB2, bN2, bR2],
[bP1, bP2, bP3, bP4, bP5, bP6, bP7, bP8],
[EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY],
[wP1, wP2, wP3, wP4, wP5, wP6, wP7, wP8],
[wR1, wN1, wB1, wQ, wK, wB2, wN2, wR2]
]
last_board_state = []
|
#!/usr/bin/env python
# -*-coding:utf-8-*-
def func(a,b,c=0,*args,**kw):
print 'a:',a
print 'b:',b
print 'c:',c
print 'args=',args
print 'kw=',kw
print '------这是一条开心的分割线--------'
func(1,2)
func(1,2,c=3)
func(1,2,3,'a','b','c')
func(1,2,3,'a','b',x=99)
args=(1,2,3,4)
kw={'x':99}
func(*args,**kw)
|
import math
import numpy
if __name__=='__main__':
arr = list(map(float, input("Enter the numbers\n").split(",")))
n = len(arr)
squareplus = 0.00
mean =0.00
rms = 0.00
for i in range(0,n):
squareplus = squareplus + (arr[i]**2)
mean = (squareplus/float(n))
rms = math.sqrt(mean)
print("The Root mean Square value is :")
print("%.4f" % rms);
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv("Salary_Data.csv")
print(dataset)
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:,-1].values
print("<<<<<<<xxxxxxxxxxxxxxxx")
print(X)
print("<<<<<<<yyyyyyyyyyyyyyyy")
print(Y)
from sklearn.model_selection import train_test_split
X_train, X_test,Y_train,Y_test = train_test_split(X,Y , test_size = 1/3 , random_state = 1)
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
print(X_train)
print(Y_train)
regressor.fit(X_train, Y_train)
print(regressor.fit(X_train, Y_train))
y_pred = regressor.predict(X_test)
#print(y_pred)
plt.scatter(X_train, Y_train , color = 'red')
plt.plot(X_train, regressor.predict(X_train),color = 'blue')
plt.title('salary vs experience(Training set)')
plt.xlabel('years of experience')
plt.ylabel('salary')
plt.scatter(X_test, Y_test , color = 'red')
plt.plot(X_train, regressor.predict(X_train),color = 'blue')
plt.title('salary vs experience(Training set)')
plt.xlabel('years of experience')
plt.ylabel('salary')
plt.show()
|
if __name__ == "__main__":
vowels = ('a', 'e', 'i', 'o', 'u')
# i = 0
# while i < len(vowels):
# print(vowels[i])
# i += 1
# for letter in vowels:
# print(letter)
# for i in range(10, 21, 2):
# print(i)
for i in range(5):
print('pre nested loop')
for j in range(5, 8):
print(f'i = {i}; j = {j}')
print('post nested loop')
print('script complete')
|
import random
# roll = random.randint(1, 6)
# while True:
# print(roll)
# if roll == 4 or roll == 5:
# break
# roll = random.randint(1, 6)
# for i in range(1, 7):
# if i == 4 or i == 5:
# continue
# print(i)
# fruits = 'apples cherries blueberries blackberries'.split()
# for fruit in fruits:
# if 'peach' in fruit:
# break
# print(fruit)
# else:
# print("peach wasn't found in the fruits")
max_guesses = 3
num_guess = 0
val_check = 'kronos'
while num_guess < max_guesses:
val = input('Enter your guess: ')
if val == val_check:
print('You won!')
break
num_guess += 1
else:
print('You lose :(')
print('Game over')
|
"""
Tests for the Stack class.
"""
import unittest
from stack.stack import Stack, NumberOutOfRangeError
class StackTestCase(unittest.TestCase):
"""
This Case of tests checks the functionality of the implementation of Stack
"""
def test_new_stack_is_empty(self):
"""
Create an empty Stack.
Test that its size is 0.
"""
stack = Stack()
self.assertTrue(stack.empty())
self.assertEqual(stack.size(), 0)
def test_new_stack_from_list(self):
"""
Create a Stack from a list.
Check that the size of stack equals to the size of the list.
Check that the top element of stack equals to the latest element of the list.
"""
data_to_stack = [1, 3, 5, 7, 2, 4]
stack = Stack(data_to_stack)
self.assertFalse(stack.empty())
self.assertEqual(stack.size(), len(data_to_stack))
self.assertEqual(stack.top(), data_to_stack[-1])
def test_new_stack_from_generator(self):
"""
Create a Stack from a generator.
Test that its size equals to the number provided in the generator.
"""
stack = Stack(range(10))
self.assertFalse(stack.empty())
self.assertEqual(stack.size(), 10)
self.assertEqual(stack.top(), 9)
def test_push_element(self):
"""
Push an element in stack.
Test that its size is 1.
"""
stack = Stack()
stack.push(None)
self.assertFalse(stack.empty())
self.assertEqual(stack.size(), 1)
def test_push_sequence_of_elements(self):
"""
Push a sequence of elements in stack.
Test that its size equals to the length of the given sequence.
Pop all elements from stack and check reversed order.
"""
stack = Stack()
elements = (1, 2, "string", None, 0, Stack())
for element in elements:
stack.push(element)
self.assertEqual(stack.size(), len(elements))
for index, element in enumerate(reversed(elements)):
top = stack.top()
self.assertEqual(top, element)
stack.pop()
self.assertEqual(stack.size(), len(elements) - index - 1)
self.assertTrue(stack.empty())
def test_call_top_of_empty_stack_raised_error(self):
"""
Create an empty Stack.
Test that call of top function raises Value error
"""
stack = Stack()
self.assertRaises(ValueError, stack.top)
def test_call_pop_of_empty_stack_raised_error(self):
"""
Create an empty Stack.
Test that call of pop function raises Value error
"""
stack = Stack()
self.assertRaises(ValueError, stack.pop)
def test_call_pop_for_number_of_elements(self):
"""
Create a Stack.
Pop given number of elements
"""
data_to_stack = [1, 3, 5, 7, 2, 4, 10, 8]
stack = Stack(data_to_stack)
stack.pop_number_of_elements(5)
self.assertEqual(3, stack.size())
self.assertEqual([1, 3, 5], stack.data)
def test_call_pop_for_number_out_of_range(self):
"""
Create a Stack.
Test that call of pop_number_of_elements function raises custom error
"""
data_to_stack = [1, 3, 5, 7, 2]
stack = Stack(data_to_stack)
self.assertRaises(NumberOutOfRangeError, stack.pop_number_of_elements, 9)
def test_call_pop_with_incorrect_argument(self):
"""
Create a Stack.
Test that call of pop_number_of_elements function raises custom error
"""
data_to_stack = [1, 3, 5, 7]
stack = Stack(data_to_stack)
incorrect_arguments = ['string', None, 1.09, True, False, [1, 2], ('a', 'b')]
for argument in incorrect_arguments:
self.assertRaises(TypeError, stack.pop_number_of_elements, argument)
|
num = int(input("What's the number to check? "))
check = int(input("What's the number to divide by? "))
if num % 4 == 0:
print("It's a multiple of 4! :)")
elif num % check == 0:
print(str(num) + " is divisible by " + str(check))
else:
print(str(num) + " ain't divisible by " + str(check))
|
import Image
import argparse
def calc_pi(filename):
try:
img = Image.open(filename)
except:
print "Couldn't open image."
area = 0
rgb_img = img.convert('RGB')
rgb_values = rgb_img.load()
(width, height) = rgb_img.size
is_black = lambda (r,g,b): r==0 and g==0 and b==0
# Circles are symmetric so I can use the y-diameter from the min and max
# of the x-coords to calculate the radii.
min_point_x, max_point_x = (width, height), (0, 0)
# Scan down instances of black pixels to store max, mins, and area.
for x in range(width):
for y in range(height):
if is_black(rgb_values[x,y]):
if x < min_point_x[0]:
min_point_x = (x,y)
if x > max_point_x[0]:
max_point_x = (x,y)
area += 1
radius = (max_point_x[0] - min_point_x[0])/2
return float(area)/float(radius*radius)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
parser.add_argument('-f','--filename', help='Input file name', required=True)
args = parser.parse_args()
print calc_pi(args.filename)
|
import numpy as np
def compute_distances(features_instances, features_query):
"""
Compute euclidean distance.
computes the distances from a query house to all training houses.
The function takes two parameters:
(i) the matrix of training features and
(ii) the single feature vector associated with the query.
"""
# _________________________________________
# Euclidean distance: distance(xi,xq) = √(xj[1] − xq[1])² + ... + (xj[d] − xq[d])²
differences = features_instances - features_query # xj[1] − xq[1]
square_diff = differences ** 2 # (xj[1] − xq[1])²
# note: summing up only over features for every squared difference of each observation:
sum_square_diff = np.sum(square_diff, axis=1)
distances_matrix = np.sqrt(sum_square_diff)
return distances_matrix
def k_nearest_neighbors(k, feature_train, features_query):
"""
preform k-nearest neighbor regression.
Example:
-------
For instance, with 2-nearest neighbor,
a return value of [5, 10] would indicate that the 6th and 11th training houses are closest to the query house.
:param k: consider k neighbor
:param feature_train:
:param features_query:
:return: returns the indices vector of the k closest training houses
"""
distances_matrix = compute_distances(feature_train, features_query)
sorted_matrix = np.argsort(distances_matrix)
return sorted_matrix[:k] # return k neighbors
def predict_output_of_query(k, features_train, output_train, features_query):
"""
predict output using k nearest neighbors for given features query
predicts the value of a given query house. simply,
takes the average of the prices of the k nearest neighbors in the training set.
:param k:
:param features_train:
:param output_train:
:param features_query:
:return:
"""
knn_indices = k_nearest_neighbors(k, features_train, features_query)
avg_value = np.mean(output_train[knn_indices])
return avg_value # mean of k nearest neighbors is our prediction of given query
def predict_output(k, features_train, output_train, features_query):
"""
predict outputs using k nearest neighbors for given features query set
predict the value of each and every house in a query set.
(The query set can be any subset of the dataset, be it the test set or validation set.)
The idea is to have a loop where we take each house in the query set as the query house and make a prediction
for that specific house.
:param k:
:param features_train:
:param output_train:
:param features_query:
:return:
"""
n = len(features_query) # number of observation we want to predict
predictions = np.zeros(n)
for i in range(n):
# for each feature query that you want to predict its output, do:
predictions[i] = predict_output_of_query(k, features_train, output_train, features_query[i])
return predictions
|
# Inheritance helps with reusing instance variables and instance methods
class Parent():
def __init__(self, last_name,eye_color):
print("Parent Constructor Called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name: "+self.last_name)
print("Eye Color: "+self.eye_color)
#Inherits from class Parent
class Child(Parent):
def __init__(self, last_name,eye_color, number_of_toys):
print("Child Constructor Called")
Parent.__init__(self, last_name,eye_color)
self.number_of_toys = number_of_toys
#resultes in method overriding
def show_info(self):
print("Last Name: "+self.last_name)
print("Eye Color: "+self.eye_color)
print("Number of Toys: "+str(self.number_of_toys))
#Note: Keep class definition seperate from instance creation as much as possible, together here for demonstration of inheritance
tom_smith = Parent("Smith", "Green")
#tom_smith.show_info()
dick_smith = Child("Smith", "Green", 3)
#dick_smith.show_info()
|
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
np.random.seed(0)
x = np.random.rand(100,1)
x_train = np.c_[np.ones((x.shape[0], 1)), x]
y = 2 + 3 * x + np.random.rand(100,1)
model = LinearRegression()
model.fit(x,y)
y_pred = model.predict(x)
rmse = mean_squared_error(y, y_pred)
r_squared = r2_score(y, y_pred)
print(f'Slope is: {model.coef_}')
print(f'Intercept is: {model.intercept_}')
print(f'RMSE is: {rmse}')
print(f'R**2 is: {r_squared}')
# data points
plt.scatter(x, y, s=10)
plt.xlabel('x')
plt.ylabel('y')
# predicted values
plt.plot(x, y_pred, color='r')
plt.show()
|
l=int(input())
l1=[1,2,3,4,5,6,7,8,9,10]
if l in l1:
print("yes")
else:
print("no")
|
num = raw_input("if hillary clinton and donald trump go on a cruise togethor and the ship sinks who survives")
if num.lower()== "america":
print("You're correct")
else:
print("You're incorrect the correct answer was america")
|
#Implementing the linked list class
class Node:
def __init__(self, x): # x is the value of the node
self.value = x
self.next = None
def append(self, next_node): # next_node is a Node
if self.next == None:
self.next = Node(next_node) # next_node is a number
else:
# self.next points to another node - we wanna add the next_node after that node
self.next.append(next_node) # recursive
def __str__(self): # debugging
return str(self.value) + ' ' + str(self.next)
# test cases
# node1 = Node(3)
# node2 = Node(4)
## node1.append(node2)
## print node1
# node3 = Node(2)
# node3.append(node2)
# node1.append(node3)
# print node1
#Solution for removing duplicates from an unsorted linked list
def remove_duplicates(linked_list): # linked_list is a Node
hash_table = {}
new_linked_list = Node(linked_list.value)
linked_list = linked_list.next
# we cant use a for loop because it's not like an array (not iterable)
while linked_list is not None:
if linked_list.value not in hash_table:
hash_table[linked_list.value] = True
new_linked_list.append(linked_list.value)
# else:
# ....pass
linked_list = linked_list.next
return new_linked_list
def remove_duplicates2(linked_list): # linked_list is a Node
hash_table = {}
new_linked_list = Node(linked_list.value)
# we cant use a for loop because it's not like an array (not iterable)
while linked_list.next is not None:
if linked_list.next.value not in hash_table:
hash_table[linked_list.next.value] = True
new_linked_list.append(linked_list.next.value)
# else:
# ....pass
linked_list = linked_list.next
return new_linked_list
## In - place solution
def remove_duplicates_inplace(linked_list):
current_linked_list = Node(linked_list.value)
while linked_list != None:
pointer = linked_list.next # pointing to the first child
while pointer != None:
if pointer.value != linked_list.value:
current_linked_list.append(pointer.value)
pointer = pointer.next # advancing the pointer
linked_list = linked_list.next
return current_linked_list
# test cases
root = Node(1)
root.append(5)
root.append(5)
root.append(2)
root.append(3)
root.append(3)
# print remove_duplicates(root)
# print remove_duplicates2(root)
#print remove_duplicates_inplace(root)
## Implementing a stack
class Stack:
def __init__(self, inputs):
self.data = inputs
def push(self, item):
self.data.append(item)
def peek(self):
return self.data[-1]
def pop(self):
popped = self.peek()
self.data.remove(popped)
return popped
class Queue:
def __init__(self, inputs):
self.data = inputs
def push(self, item):
self.data.append(item)
def peek(self):
return self.data[0]
def pop(self):
popped = self.peek()
self.data.remove(popped)
return popped
class Graph:
def __init__(self, x): # x is the value of the node
self.value = x
self.neighbors = []
self.type = True # undirected
#Construction
def add_neighbor(self, next_node): # next_node is a Node
if self.type == False:
self.neighbors.append(next_node) # recursive
else:
if next_node not in self.neighbors:
self.neighbors.append(next_node) # self (graph object)
next_node.neighbors.append(self)
#Debug
def toStr(self, tabLevel, startSet=None):
#Initialize the set of printed values if not already done:
if not startSet:
_set = set([self])
else:
_set = startSet.union([self]) # already-printed nodes + current
ans = ""
for i in range(tabLevel):
ans+="\t"
ans+= self.value + ' Neighbors: '
#Print neighbors recursively
setToPrint = set(self.neighbors) - _set #neighbors that have not been printed
if len(setToPrint) == 0:
ans += "None!"
else:
ans+= "\n"
for neighbor in setToPrint:
a = neighbor.toStr(tabLevel+1, _set.union(setToPrint)) + "\n"
ans+= a
return ans
def __str__(self):
return self.toStr(0)
##### Testing Graph Class #####
a = Graph('A') # undirected by default
b = Graph('B')
c = Graph('C')
d = Graph('D')
e = Graph('E')
#Construct a Graph:
c.add_neighbor(d)
b.add_neighbor(c)
b.add_neighbor(d)
a.add_neighbor(b)
print "D: ", d
print "C: ", c
print "B: ", b
print "A: ", a
c.add_neighbor(e) #expect change to be reflected in A
print "A after adding E to C: ", a
from enum import Enum
class AdjacencyGraph:
def __init__(self, A):
self.A = A
def getNeighbors(nodeIndex):
neighbors = []
# add all neighbors from matrix for inputted node
return neighbors
def areConnected(node1, node2): #node1, node2 indexes into A
pass
def add_neighbor(node1, node2):
pass
|
box_w = int(raw_input('How wide is the box (an integer)? '))
box_h = int(raw_input('How high is the box (an integer)? '))
for i in range(0, box_h):
row = ''
for j in range(0, box_w):
if i != 0 and i != (box_h - 1):
if j == 0 or j == (box_w - 1):
row = row + '*'
else:
row = row + ' '
else:
row = row + '*'
print row
|
class Contact():
def __init__(self, first, last, phone):
self.first = first
self.last = last
self.phone = phone
kyle = Contact('Kyle', 'Booth', '212-442-1373')
print kyle.phone
print kyle.first
|
def sum(numbers):
total = 0
for number in numbers:
total += number
return total
print
print sum([10,3,34])
print
|
string = raw_input('A string for me to Leet, please: ')
string_length = len(string)
string_leet = ''
leet = []
leet_chars = [A,E,G,I,O,S,T]
leet_nums = [4,3,6,1,0,5,7]
for i in range(0, string_length-1):
for j in range(0, len(leet_chars)):
if string[i] == leet_char[j]:
string[i] = leet_num[j]
string_leet = string_leet + leet[i]
print string_leet[::-1] #reverse the string
|
def positives(numbers):
positive_nums = []
for number in numbers:
if number > 0:
positive_nums.append(number)
return positive_nums
print
print positives([10,-3,-34,2,57])
print
|
#Tam Hoang
# July 13 2018
#Having a secure password is a very important practice,when much of our information is stored online.
#Write a program that validates a new password, following these rules:
#• The password must be at least 8 characters long.
#• The password must have at least one upper case and one lowercase letter.
#• The password must have at least one digit.
#Write a program that asks for a password, then asks again to confirm it. If the passwords don’t match or the rules are not fulfilled,
#prompt again. Your program should include a function that checks whether a password is valid.
from math import*
def inputPassword():
print("Enter a password with the following rules:\n"
"The password must be at least 8 characters long.\n"
"The password must have at least one upper case and one lowercase letter.\n"
"The password must have at least one digit.")
password = input("Enter a password: ")
password1 = input("Confirm Password: ")
return (password, password1)
def checkForValidPassword(pass1, pass2):
uppercaseCounter = 0
lowercaseCounter = 0
digitCounter = 0
for i in range(len(pass1)):
if(pass1[i].isupper()):
uppercaseCounter += 1
elif(pass1[i].islower()):
lowercaseCounter += 1
elif(pass1[i].isdigit()):
digitCounter += 1
if(pass1 != pass2):
return 1
elif(len(pass1) < 8):
return 2
elif(uppercaseCounter < 1 or lowercaseCounter < 1):
return 3
elif(digitCounter < 1):
return 4
return 5
boolval = 1
while(boolval):
(password,confirmPassword) = inputPassword()
result = checkForValidPassword(password, confirmPassword)
if(result == 1):
print("The password doesn't match.\n")
elif(result == 2):
print("The password is not 8 character long.\n")
elif(result == 3):
print("The password need to be at least 1 uppercase and lower case.\n")
elif(result == 4):
print("The password need to have at least 1 digit.\n")
else:
print("The password is valid.")
boolval = 0
|
# -*- coding: utf-8 -*-
# Written by Sam Lööf <[email protected]>
from math import sqrt
# Returnerar medelvärdet för lista
def mean(lista):
return float(sum(lista)) / len(lista)
# Returnerar standardavvikelsen för lista
def standardDeviation(lista):
summa = 0.0
medel = mean(lista)
for i in lista:
summa += (i-medel)*(i-medel)
return sqrt(float(1)/(len(lista)-1)*summa)
theFile = open("resultat.txt", "r")
lista = []
for val in theFile.read().split():
lista.append(int(val))
theFile.close()
print 'Average: ', mean(lista)
print 'Standard deviation: ', standardDeviation(lista)
|
stevilka1 = int(input("Vnesi prvo številko: "))
operation = input("Izberi računsko operacijo, ki je lahko +, -, * ali /: ")
stevilka2 = int(input("Vnesi drugo številko: "))
if operation == "+":
print(stevilka1 + stevilka2)
elif operation == "-":
print(stevilka1 - stevilka2)
elif operation =="*":
print(stevilka1 * stevilka2)
elif operation == "/":
print(stevilka1 / stevilka2)
|
x,y,z=map(int,input().split())
if x>z and x>y:
print("x is greater")
elif y>z:
print("y is greater")
else:
print("z is greater")
|
a=int(input())
b=a**0.5
if(b%2==0):
print("yes")
elif(a==2):
print("yes")
elif(a==1):
print("yes")
else:
print("no")
|
'''
Read and filter CSV file using standard library
'''
#%%
# standard library
import csv
from pprint import pprint as pp
fn = 'data/CLEAN1A.csv'
#%% quick-and-dirty
data = list(csv.reader(open(fn, encoding="utf-8-sig")))
pp(data[:5])
#%% better
with open(fn, encoding="utf-8-sig") as csvfile:
data = list(csv.reader(csvfile))
pp(data[:5])
#%% each record is a dictionary
with open(fn, encoding="utf-8-sig") as csvfile:
data = list(csv.DictReader(csvfile))
pp(data[:5])
#%% why this is useful
# assume large data set,
# just need records (or first record)
# that matches condition
with open(fn, encoding="utf-8-sig") as csvfile:
for record in csv.reader(csvfile):
if record[0].startswith('143'):
print(record)
break
#%% explain why "utf-8-sig" is needed
print(open(fn, 'rb').read(27))
|
CACHE = {}
#return True after setting the data
def set(key, value):
CACHE[key] = value
return True
#return the value for key
def get(key):
return CACHE.get(key)
#delete key from the cache
def delete(key):
if key in CACHE:
del CACHE[key]
#clear the entire cache
def flush():
CACHE.clear()
# QUIZ - implement gets() and cas() below
#return a tuple of (value, h), where h is hash of the value. a simple hash
#we can use here is hash(repr(val))
def gets(key):
###Your gets code here.
value = CACHE[key]
if value :
return (CACHE[key], hash(repr(value)))
return None
# set key = value and return True if cas_unique matches the hash of the value
# already in the cache. if cas_unique does not match the hash of the value in
# the cache, don't set anything and return False.
def cas(key, value, cas_unique):
###Your cas code here.
if(cas_unique == hash(repr(CACHE[key]))) :
CACHE[key] = value
return True
return False
print set('x', 1)
#>>> True
#
print get('x')
#>>> 1
#
print get('y')
#>>> None
#
delete('x')
#print get('x')
#>>> None
#
set('x', 2)
print gets('x')
#>>> 2, HASH
#
print cas('x', 3, 0)
#>>> False
#
print cas('x', 4, 2105051955)
#>>> True
#
print get('x')
#>>> 4
|
def printStar(num):
for i in range(1, num + 1, 1):
print(" " * (num - i), end = "")
print("*" * i)
n = int(input(""))
printStar(n)
|
def mean(numbers):
return float(sum(numbers))/len(numbers)
print('введите числа:')
nums=map(int, input().split())
l=list(nums)
print(l, type(l))
print("среднее =" +str(mean(l)))
l = [1, 2, 3]
for e in l:
print(e)
m = np.random.randint(1, 20, (10, 10))
def minor(m, i, j):
return [row[:j] + row[j + 1:] for row in (m[:i] + m[i + 1:])]
def deternminant(m):
# base case for 2x2 matrix
if len(m) == 2:
return m[0][0] * m[1][1] - m[0][1] * m[1][0]
determinant = 0
for c in range(len(m)):
determinant += ((-1) ** c) * m[0][c] * deternminant(minor(m, 0, c))
return determinant
round(np.linalg.det(m)) == deternminant(m.tolist())
m.tolist()
|
#!usr/bin/env python
#-*-coding:utf-8 -*-
#导入SQLITE3模块
import sqlite3
#SQLite数据库名
DB_SQLITE_NAME="test.db"
def sqliteHandler():
#连接数据库
try:
sqlite_conn=sqlite3.connect(DB_SQLITE_NAME)
except sqlite3.Error,e:
print "连接sqlite3数据库失败", "\n", e.args[0]
return
#获取游标
sqlite_cursor=sqlite_conn.cursor()
#如果存在表先删除
sql_del="DROP TABLE IF EXISTS tbl_test;"
try:
sqlite_cursor.execute(sql_del)
except sqlite3.Error,e:
print "删除数据库表失败!", "\n", e.args[0]
return
sqlite_conn.commit()
#创建表
sql_add='''CREATE TABLE tbl_test(
i_index INTEGER PRIMARY KEY,
sc_name VARCHAR(32)
);'''
try:
sqlite_cursor.execute(sql_add)
except sqlite3.Error,e:
print "创建数据库表失败!", "\n", e.args[0]
return
sqlite_conn.commit()
#添加一条记录
sql_insert="INSERT INTO tbl_test(sc_name) values('mac');"
try:
sqlite_cursor.execute(sql_insert)
except sqlite3.Error,e:
print "添加数据失败!", "\n", e.args[0]
return
sqlite_conn.commit()
#查询记录
sql_select="SELECT * FROM tbl_test;"
sqlite_cursor.execute(sql_select)
for row in sqlite_cursor:
i=1;
print "数据表第%s" %i,"条记录是:", row,
if __name__=='__main__':
#调用数据库操作方法
sqliteHandler()
|
print "Welcome to the English to Pig Latin translator!"
original = raw_input("What word would you like to be translated?")
if len(original) > 0 and original.isalpha():
print original
else:
print "empty"
|
from tkinter import *
class Aplicacion:
def __init__(self):
self.win = Tk()
self.win.title("Mi primer App")
self.etq1 = Label(self.win,text="Nombre: ")
self.etq1.grid(column=0,row=0)
self.dato1 = StringVar()
self.nombre = Entry(self.win, textvariable=self.dato1)
self.nombre.grid(row=0, column=1)
self.etq2 = Label(text="Apellido: ")
self.etq2.grid(row=1,column=0)
self.dato2 = StringVar()
self.apellido = Entry(self.win, textvariable=self.dato2)
self.apellido.grid(row=1,column=1)
self.button = Button(self.win,text="Mostrar Datos", command=self.MostrarDatos)
self.button.grid(column=1,row=2)
self.etqres = Label(text="")
self.etqres.grid(column=1,row=3)
self.win.geometry("460x240")
self.win.mainloop()
def MostrarDatos(self):
nom = self.dato1.get()
ape = self.dato2.get()
data = nom+" "+ape
self.etqres.configure(text=data)
aplicacion1=Aplicacion()
|
# FizzBuzz Game #
# The Following code will run the FizzBuzz Game
# However, unlike the original I have included Bang when the number 4 appears
for i in range(1, 101):
output = ""
if i % 3 == 0:
output += 'Fizz'
if i % 5 == 0:
output += 'Buzz'
if i % 4 == 0:
output += 'Bang'
elif output == '':
output = str(i)
print(output)
|
import math
p=int(input(""))
b=int(input(""))
d=int(round((math.atan(p/b))*180/(math.pi)))
deg=str(d)+"°"
print(deg)
|
def print_rangoli(n):
string="abcdefghijklmnopqrstuvwxyz"
Lest=list(string)
k=n
c=2
L=[]
for i in range(k-1,-1,-1):
star=(2*n)-c
List=[]
if i==(k-1):
List.append(Lest[k-1])
for j in range (n-1,i,-1):
List.append(Lest[j])
List.append("-")
f="-"*star
if i!=k-1:
l=f+"".join(List)+string[i]+"".join(List[::-1])+f
else:
l=f+"".join(List)+f
print(l)
L.append(l)
c=c+2
for i in range(len(L)-2,-1,-1):
print(L[i])
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
def Insert_Node(root, data):
if(root == None):
root = Node(data)
return root
root.next = Insert_Node(root.next,data)
return root
def Remove_Node(root):
if(root.next == None)
head = None
head = Insert_Node(head,1)
head = Insert_Node(head,2)
head = Insert_Node(head,3)
head = Insert_Node(head,4)
temp = head
while(temp != None):
print(temp.data)
temp = temp.next
Remove_Node(head)
temp = head
while(temp != None):
print(temp.data)
temp = temp.next
|
def subsets(nums: List[int]) -> List[List[int]]:
def explore(chosen, remaining, res):
if not remaining:
res.append(chosen[:])
return
d = remaining.pop(0)
#choose
chosen.append(d)
#explore
explore(chosen, remaining, res)
chosen.pop()
explore(chosen, remaining, res)
#unchoose
remaining.insert(0, d)
res = []
chosen = []
explore(chosen, nums, res)
return res
|
#29211757 Kevin Yin and 72238150 Jenny Kim, Project 2
#This module contains the interface for a local Connect 4 game played on the console.
from connectfour import *
from collections import namedtuple
ConnectFour_Turn= namedtuple('ConnectFour_Turn', 'gamestate turntype column')
def playgame():
game_state= new_game_state()
print("You have started a new game of connect four.")
while True:
column = None
print('')
print_board(game_state)
#Determing whether a player has won
outcome= winning_player(game_state)
if outcome == RED:
print("Congratulations! RED player has won.")
break
elif outcome == YELLOW:
print("Congratulations! YELLOW player has won.")
break
#Basic move structure
if game_state.turn == RED:
print("It is RED turn.")
elif game_state.turn == YELLOW:
print("It is YELLOW turn.")
turn_type= input('DROP or POP? ').upper()
if turn_type != 'DROP' and turn_type != 'POP':
print('Please enter a valid command, either DROP or POP.')
else:
try:
column= int(input('Enter column number: ')) - 1
game_state= make_move(game_state, turn_type, column)
except:
print('Please enter a valid column number.')
def print_board(state: ConnectFourGameState):
'''Prints a visible representation of the game board given the state.
'''
string1 = ' '
for column in range(BOARD_COLUMNS):
column += 1
string1= string1 + str(column) + ' '
print(string1)
for row in range(BOARD_ROWS):
string2= ' '
for column in range(BOARD_COLUMNS):
if state.board[column][row] == NONE:
string2 += '.'
elif state.board[column][row] == RED:
string2 += 'R'
else:
string2 += 'Y'
string2 += ' '
print(string2)
def make_move(game_state: 'game state', turn_type: str, column: int) -> ConnectFourGameState:
'''Asks the user for a column number and turn type and returns a new ConnectFourGameState.
'''
if turn_type== 'DROP':
try:
game_state= drop_piece(game_state, column)
except ValueError:
print('Invalid column number, please try again.')
elif turn_type== 'POP':
try:
game_state= pop_piece(game_state, int(column))
except ValueError:
print('Invalid column number, please try again.')
except InvalidMoveError:
print('You cannot pop from that column.')
return game_state
if __name__ == '__main__':
playgame()
|
'''
Question Description :-
Consecutive Characters
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Output: 5
Explanation: The substring "eeeee" is of length 5 with the character 'e' only.
Example 3:
Input: s = "triplepillooooow"
Output: 5
Example 4:
Input: s = "hooraaaaaaaaaaay"
Output: 11
Example 5:
Input: s = "tourist"
Output: 1
Constraints:
1 <= s.length <= 500
s contains only lowercase English letters.
'''
def maxPower(s):
ans = 0
start = 0
end = 0
while end < len(s):
while end < len(s) and s[start] == s[end]:
end += 1
ans = max(ans,end-start)
start = end
ans = max(ans,end-start+1)
return ans
print(maxPower("leetcode"))
|
'''
Question Description :-
Convert Binary Number in a Linked List to Integer
Given head which is a reference node to a singly-linked list.
The value of each node in the linked list is either 0 or 1.
The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0]
Output: 0
Example 3:
Input: head = [1]
Output: 1
Example 4:
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880
Example 5:
Input: head = [0,0]
Output: 0
Constraints:
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
binary = []
while head:
binary.insert(0,head.val)
head = head.next
ans = 0
count = 0
for x in binary:
if x == 1:
ans += 2**count
count += 1
return ans
'''
Other Solution :-
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
ans = ''
while head:
ans += str(head.val)
head = head.next
return int(ans, 2)
'''
|
#!/usr/bin/env python
import sys
def select_list_by_value(select_list, value):
select_list.select_by_visible_text(value)
def select_list_by_index(select_list, index):
try:
select_list.select_by_visible_text(select_list.options[index].text)
except IndexError:
print("ERROR: Option #: {} does not exist!".format(index))
sys.exit(1)
from random import choice
from string import ascii_uppercase
def generate_str(size=4):
return ''.join(choice(ascii_uppercase) for i in list(range(size)))
def generate_name(name, unique_id=None, use_name_only=False):
if use_name_only:
return name
if unique_id is None:
unique_id = generate_str()
return "{}-AUTO-{}".format(name, unique_id)
def generate_email(address, host="test.com", unique_id=None, use_address_only=False):
if use_address_only:
return address
if unique_id is None:
unique_id = generate_str()
return "{}+auto-{}@{}".format(address, unique_id, host)
def generate_phone_number(area_code="555", prefix="111", number="2222"):
return "{}{}{}".format(area_code, prefix, number)
def generate_zip_code(zip_code="10018"):
return zip_code
def generate_birth_date(mm="06", dd="11", yyyy="2000"):
return "{}/{}/{}".format(mm, dd, yyyy)
def generate_address(address="1375 Broadway"):
return address
def generate_city(city="New York"):
return city
|
import argparse
import sys
class SubArgumentParser:
"""
Example usage:
parser = SubArgumentParser()
parser.add_subcommand('fetch', help='git fetch',
callable=git_func)
# parser.fetch is an argparse.ArgumentParser for everything after subcommand.
parser.fetch.add_argument('arg1', )
parser.fetch.add_argument('arg2', )
parser.add_subcommand('pull', help='git pull')
parser.pull.add_argument('arg', )
# Returns the subcommand (as text) and the parsed args for the rest of the args
subcommand, args = parser.parse_args()
# Can also directly call the callables passed with the parser.__dict__ as kwargs.
parser.call()
"""
def __init__(self):
self.subcommands = {}
def _build_subcommand_parser(self):
usage_str = "Sub-commands:\n\n"
for k in self.subcommands.keys():
usage_str += "{:20s}{}\n".format(k, self.subcommands[k]['help'])
usage_str += '\n'
self.subcommand = argparse.ArgumentParser(usage=usage_str)
self.subcommand.add_argument('subcommand')
def add_subcommand(self, subcommand, help=None, callable=None):
self.subcommands[subcommand] = {'parser': argparse.ArgumentParser(),
'help': help,
'callable': callable}
self._build_subcommand_parser()
def __getattr__(self, item):
return self.subcommands[item]['parser']
def parse_args(self):
subcmd = self.subcommand.parse_args(sys.argv[1:2])
return subcmd.subcommand, self.subcommands[subcmd.subcommand]['parser'].parse_args(sys.argv[2:])
def call(self):
subcmd, args = self.parse_args()
self.subcommands[subcmd]['callable'](**args.__dict__)
|
# futval-periods.py
# by Joshua Pedro. November 20th, 2018
# A program to compute the value of an investment
# carried 10 years into the future
def main():
print("This program calculates the future value")
print("of a x-year investment.")
principal = int(input("Enter the principal balance: "))
periods = int(input("how many times intrest is compounded anually?: "))
apr = float(input("Enter the annual interest rate: "))
balance = principal
for i in range (10 * periods) :
balance=balance * (1 + apr/periods)
print("The value in",periods * 10, "periods is:", balance)
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.