text stringlengths 37 1.41M |
|---|
#Rotation of an image
import cv2
import matplotlib.pyplot as plt
def main():
imgpath = "C:\\Users\\Purneswar Prasad\\Documents\\misc\\4.2.01.tiff"
img1 = cv2.imread(imgpath, 1)
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
rows, columns, channels = img1.shape
R = cv2.getRotationMatrix2D((rows/2, columns/2), 0, 0.5)
print(R)
output = cv2.warpAffine(img1, R, (rows, columns))
plt.imshow(output)
plt.title("Rotated Image")
plt.show()
if __name__ == "__main__":
main() |
if __name__ == "__main__":
from state import *
else:
from ..state import *
class GameState(State):
"""contains all info about a board state"""
number_of_players = 2
length = 4
stones = 2
squares = length * 2 + 2
def __init__(self, board=None, player=0, plys=0, handicap=-.5):
"""
:param board:
:param player:
:param plys:
:param handicap:
"""
super().__init__(board=board, player=player, plys=plys)
self.handicap = handicap
# draft variables
self._switch = None
self._still_playing = [True, True]
if len(self.board) != GameState.squares:
raise ValueError(f'Board must be of length {2 * (GameState.length + 1)}')
def __len__(self):
return self.length
def _rotate(self, n):
return self.player * (self.length + 1) + n
def do_switch(self):
return self._switch
def resign(self, player_id):
self._still_playing[player_id] = False
def show(self, switch_side=True, side=None, width=3):
"""
:param switch_side: the current player is always below
:param side: this player is always below
:param width:
:return:
"""
if switch_side:
side = self.player
your_side_is_playing = self.player == side
n1 = 0
n2 = len(self) + 1
if side == 0:
n1, n2 = n2, n1
l1 = 'O' if side else '#'
l2 = '#' if side else 'O'
l1 += ' ' if your_side_is_playing else ' >'
l2 += ' >' if your_side_is_playing else ' '
l1 += '\t\t' + ' '.join([f'{i:>{width}}' for i in reversed(self[n1:n1 + len(self)])])
l2 += '\t\t' + ' '.join([f'{i:>{width}}' for i in self[n2:n2 + len(self)]])
bins = '\t ' + f'{self[n1+len(self)]}' + ' '*(width*(self.length+2)+4) + f'{self[n2+len(self)]}'
out = f'\n\n{self.compute_score():+.1f}' + '\t' * (width*3) + ' ' * 2 + f'{self.plys}' + '\n' * 2
out += l1 + '\n'
out += bins + '\n'
out += l2 + '\n'
return out
def __iter__(self):
return (i for i in range(GameState.length))
def set_initial_state(self):
self.board = ([GameState.stones] * GameState.length + [0]) * 2
def compute_score(self):
"""at the end of the game the score is computed (score is NOT outcome)"""
return self[len(self)] - self[-1] + self.handicap
def plain_state(self) -> list:
"""
:returns list that describes state of the board from perspective of the current player
white_stones , black_stones , score
"""
score = self.compute_score()
score = round(score * 2)
left = self.board[:len(self)]
right = self.board[len(self)+1:-1]
if self.player == 0:
return left + right + [self.player] + [+score] # first player
else:
return right + left + [self.player] + [-score] # nero player
def legal_moves(self):
"""all legal moves"""
return self.action_distribution([1 if self[self._rotate(i)] > 0 else 0 for i in self])
def switch_player(self):
if self.do_switch():
self.player = 1 - self.player
def make_move(self, move_id):
self._switch = None
n0 = self._rotate(move_id)
stones = self[n0]
self[n0] = 0
last = None
for i in special_loop(start=n0, end=GameState.squares, length=stones):
last = i # optimize
self[i] += 1
self._switch = last != self._rotate(len(self))
def is_game_over(self):
if sum(self._still_playing) == 1: # todo check
return True
return self.count_legal_moves() == 0
def compute_outcome(self):
""":return final score for each player"""
if sum(self._still_playing) == 1:
return [1 if i else 0 for i in self._still_playing] # todo check
score = self.compute_score()
if score > 0:
outcome = [1., 0.]
elif score < 0:
outcome = [0., 1.]
else:
outcome = [.5, .5]
return outcome
def make_sure_move_is_legal(self, move_id):
if self.is_game_over():
raise ValueError('applying move on a finished game')
if not 0 <= move_id < len(self) + 1:
raise IndexError(f'Make sure 0 <= n < {len(self) + 1}')
stones = self[self._rotate(move_id)]
if not stones:
raise ValueError(f'Illegal move (square {move_id} has no stones)')
# ------------------------------------------
# ------------------------------------------
def special_loop(start, end, length):
out = start
count = length
while count:
out = (out + 1) % end
if out != start:
yield out
count -= 1
|
# Classes 1
print('####Classes_1#####')
## Clasess
class Employee_1:
#class variable
raise_amount = 1.10
num_of_employee = 0
# Constructor/ initialised
# self is an instance and others are arguments
def __init__(self, first, last, pay):
self.first = first # class variable
self.last = last # class variable
self.email = first + '.' + last + '@company.com'
self.pay = pay # class variable
# This way it will be same for all the instances
Employee_1.num_of_employee += 1
# regular methods
def full_name(self):
return '{} {}'.format(self.first, self.last)
# regular methods
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
# data and functions associated with a class are called attributes
#instances of a class
emp_1 = Employee_1('Check', 'Mate', 65000)
emp_2 = Employee_1('Test', 'User', 95000)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
print(Employee_1.raise_amount)
# Classes 2
print('####Classes_2#####')
## Clasess
class Employee_2:
#class variable
raise_amount = 1.10
num_of_employee = 0
# Constructor/ initialised
# self is an instance and others are arguments
def __init__(self, first, last, pay):
self.first = first # class variable
self.last = last # class variable
self.email = first + '.' + last + '@company.com'
self.pay = pay # class variable
# This way it will be same for all the instances
Employee_1.num_of_employee += 1
# regular methods
def full_name(self):
return '{} {}'.format(self.first, self.last)
# regular methods
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
# alternative constructors
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
# data and functions associated with a class are called attributes
#instances of a class
emp_1 = Employee_2('Check', 'Mate', 65000)
emp_2 = Employee_2('Test', 'User', 95000)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
print(Employee_2.raise_amount)
Employee_2.set_raise_amount(1.3)
#emp_1.set_raise_amount(1.3) # But doesn't make sense
print(emp_1.raise_amount)
print(emp_2.raise_amount)
print(Employee_2.raise_amount)
# Classes 3
print('####Classes_3#####')
## Clasess
class Employee_3:
#class variable
raise_amount = 1.10
num_of_employee = 0
# Constructor/ initialised
# self is an instance and others are arguments
def __init__(self, first, last, pay):
self.first = first # class variable
self.last = last # class variable
self.email = first + '.' + last + '@company.com'
self.pay = pay # class variable
# This way it will be same for all the instances
Employee_3.num_of_employee += 1
# regular methods
def full_name(self):
return '{} {}'.format(self.first, self.last)
# regular methods
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
# class method
# alternative constructors
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, string):
first, last, pay = string.split('-')
return cls(first, last, pay)
# data and functions associated with a class are called attributes
#instances of a class
emp_1 = Employee_3('Check', 'Mate', 65000)
emp_2 = Employee_3('Test', 'User', 95000)
emp_str_1 = 'Vipul-Sinha-75000'
emp_3 = Employee_3.from_string(emp_str_1)
print(emp_3.email)
print(emp_3.pay)
# Classes 4
print('####Classes_4#####')
import datetime
## Clasess
class Employee_4:
#class variable
raise_amount = 1.10
num_of_employee = 0
# Constructor/ initialised
# self is an instance and others are arguments
def __init__(self, first, last, pay):
self.first = first # class variable
self.last = last # class variable
self.email = first + '.' + last + '@company.com'
self.pay = pay # class variable
# This way it will be same for all the instances
Employee_4.num_of_employee += 1
# regular methods
def full_name(self):
return '{} {}'.format(self.first, self.last)
# regular methods
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
# class method
# alternative constructors
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, string):
first, last, pay = string.split('-')
return cls(first, last, pay)
# static method
@staticmethod
def is_workday(day):
if day.weekday()==5 or day.weekday()==6:
return False
return True
# data and functions associated with a class are called attributes
#instances of a class
emp_1 = Employee_4('Check', 'Mate', 65000)
emp_2 = Employee_4('Test', 'User', 95000)
emp_str_1 = 'Vipul-Sinha-75000'
emp_3 = Employee_4.from_string(emp_str_1)
print(emp_3.email)
print(emp_3.pay)
my_day = datetime.date(2017, 1, 31)
print(my_day)
print(emp_3.is_workday(my_day)) |
my_student = {'name': 'Vipul', 'age': '29', 'courses' : ['Math', 'CompSci']}
print(my_student)
print(my_student['name'])
my_student_new = {1: 'Vipul', 2: '29', 'courses' : ['Math', 'CompSci']}
print(my_student_new[2])
print(my_student.get('name'))
print(my_student.get('phone'))
print(my_student.get('phone', 'Not Found'))
my_student['phone'] = '123-5555'
print(my_student.get('phone', 'Not Found'))
my_student['name'] = 'Sinha'
print(my_student)
my_student.update({'name': 'Mr Sinha','age':'29.5', 'phone' : '5555-1234'})
print(my_student)
del my_student['age']
print(my_student)
courses = my_student.pop('courses')
print(my_student)
print(courses)
print(len(my_student))
print(my_student.keys())
print(my_student.values())
print(my_student.items())
for keys in my_student:
print(keys)
for keys,values in my_student.items():
print(keys, values) |
#Object programming
class parent:
#constructor
def __init__(self):
print("Our class is created")
#destructor
def __del__(self):
print("Our class is destructed")
#member function
#self is like void
def printParent(self):
print(self.value1)
#member variables
value1 = "Father"
value2 = "Mother"
class elderParent:
value3 = "GrandFather"
value4 = "GrandMother"
class child (parent,elderParent):
pass
#Object is creted
#calling instructor automatically
parent1 = parent()
child1 = child()
#calling member function
#parent1.setPersonName("Vipul","Sinha")
parent1.printParent()
print(child1.value2)
print(child1.value3)
print(child1.value4)
#calling destructor
parent1.__del__()
|
# Cauculadora de IMC
# Início do recebimento de dados
altura = float(input('Insira a sua altura em metro: '))
peso = float(input('Insira o seu peso, em kilograma: '))
# Fim do recebimento de dados
# Inicio do tratamento de dados
imc = peso/(altura**2)
# Fim do tratamento de dados
# Inicio das saídas para o usuário
if imc < 18.5:
print(f'Seu IMC é de {imc}, você está abaixo do peso.')
elif 24.9 > imc > 18.5:
print(f'Seu IMC é de {imc}, você está em seu peso ideal')
elif 30 > imc > 24.9:
print(f'Seu IMC é de {imc}, você está em sobrepeso')
else:
print(f'Seu IMC é de {imc}, você está em obesidade')
# Fim das saídas para o usuário
# Fim do programa |
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
# code reference: https://en.wikipedia.org/wiki/Maze_generation_algorithm
class robot_map(object):
def __init__(self, width=40, height=40, complexity=0.01, density=0.1):
self.width = width
self.height = height
self.complexity = complexity
self.density = density
# Only odd shapes
self.shape = ((self.height // 2) * 2 + 1, (self.width // 2) * 2 + 1)
self.bool_map = np.zeros(self.shape, dtype=bool)
def init(self):
self.width = 40
self.height = 40
self.complexity = 0.01
self.density = 0.1
# Only odd shapes
self.shape = ((self.height // 2) * 2 + 1, (self.width // 2) * 2 + 1)
self.bool_map = np.zeros(self.shape, dtype=bool)
def generate_map(self):
# Adjust complexity and density relative to maze size
complexity = int(self.complexity * (5 * (self.shape[0] + self.shape[1]))) # number of components
density = int(self.density * ((self.shape[0] // 2) * (self.shape[1] // 2))) # size of components
# Fill borders
self.bool_map[0, :] = self.bool_map[-1, :] = 1
self.bool_map[:, 0] = self.bool_map[:, -1] = 1
# Make aisles
for i in range(density):
# pick a random position
x = np.random.randint(0, self.shape[1] // 2) * 2
y = np.random.randint(0, self.shape[0] // 2) * 2
self.bool_map[y, x] = 1
for j in range(complexity):
neighbours = []
if x > 1:
neighbours.append((y, x - 2))
if x < self.shape[1] - 2:
neighbours.append((y, x + 2))
if y > 1:
neighbours.append((y - 2, x))
if y < self.shape[0] - 2:
neighbours.append((y + 2, x))
if len(neighbours):
y_,x_ = neighbours[np.random.randint(0, len(neighbours) - 1)]
if self.bool_map[y_, x_] == 0:
self.bool_map[y_, x_] = 1
self.bool_map[y_ + (y - y_) // 2, x_ + (x - x_) // 2] = 1
x, y = x_, y_
return self.bool_map
def get_image(self):
img = self.bool_map + np.ones(self.bool_map.shape) - np.ones(self.bool_map.shape)
img *= 255
return img
# start position is totally random
def get_start_position(self):
while True:
row = np.random.randint(1, self.bool_map.shape[0] - 1)
col = np.random.randint(1, self.bool_map.shape[0] - 1)
if self.bool_map[row, col] == False:
return row, col
# target position is closest to (maxx, maxy)
def get_target_position(self):
while True:
row = np.random.randint(1, self.bool_map.shape[0] - 1)
col = np.random.randint(1, self.bool_map.shape[0] - 1)
if self.bool_map[row, col] == False:
return row, col
# for row in range(self.bool_map.shape[0]):
# for col in range(self.bool_map.shape[1]):
# r = self.bool_map.shape[0] - 1 - row
# c = self.bool_map.shape[1] - 1 - col
# if self.bool_map[r, c] == False:
# return r, c
def get_result_path(unique_id, id_map, parent_map, target_row, target_col):
res_path = []
cur = unique_id[target_row, target_col]
while cur != None and parent_map[cur] != None:
res_path.append(id_map[cur])
cur = parent_map[cur]
res_path.append(id_map[cur])
return res_path |
def assym(a, g, p):
key = g ** a % p
return key
def valid(key_publ_s):
try:
i = False
file = open("allowed.txt", "r")
for line in file:
if line[0] == str(key_publ_s):
i = True
return i
except:
return False
def encode(st, key):
s = list(st)
for i in range(len(s)):
j = ord(s[i])
j += key
j = chr(j)
s[i] = j
return ''.join(s)
def decode(st, key):
s = list(st)
for i in range(len(s)):
j = ord(s[i])
j -= key
j = chr(j)
s[i] = j
return ''.join(s)
|
#find the target sum from an element from two lists
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sL = sorted(nums)
for _ in range(len(nums)-1):
# print('nums', nums)
a = sL.pop(0) #2, sL = [3,4]
aInd = nums.index(a) #1
b = target - a #4
# print(a,b)
if a == b:
if nums.count(a) < 2: continue
return [aInd, nums.index(b,aInd+1)]
if b in sL:
return [aInd, nums.index(b)]
def testtwoSum():
print('twoSum', end=": ")
assert(twoSum([3,3],6)==[0,1])
assert(twoSum([3,2,4],6)==[1,2])
print('passed')
def main():
testtwoSum()
if __name__ == '__main__':
main()
'''
solution page
(1) brute force
Time complexity : O(n^2)
For each element, we try to find its complement by looping through
the rest of array which takes O(n)O(n) time. Therefore, the time
complexity is O(n^2)
Space complexity : O(1)O(1).
(2) two-pass hash
- create hash in first iteration
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
Time complexity : O(n).
We traverse the list containing nn elements
exactly twice. Since the hash table reduces the look up time to O(1),
the time complexity is O(n)O(n).
Space complexity : O(n).
The extra space required depends on the number of items stored in
the hash table, which stores exactly n elements.
(3) one-pash hash
- one iteration:
- create hash and look back
Time complexity : O(n).
We traverse the list containing nn elements only once.
Each look up in the table costs only O(1)O(1) time.
Space complexity : O(n).
The extra space required depends on the number of items stored in
the hash table, which stores at most nn elements.
''' |
"""
Converter for Minutia
- to bitstring and vice-versa
- from bitstring to int and vice-versa
"""
from bitstring import BitArray
from Minutia import MinutiaNBIS, MinutiaNBIS_GH
class MinutiaConverter:
def __init__(self, x_bit_length=11, y_bit_length=11, theta_bit_length=10, total_bit_length=32):
self.X_BIT_LENGTH = x_bit_length
self.Y_BIT_LENGTH = y_bit_length
self.THETA_BIT_LENGTH = theta_bit_length
self.TOTAL_BIT_LENGTH = total_bit_length
def get_total_bitstring_from_minutia(self, minutia: MinutiaNBIS):
""" Converts minutia to bitstring
:returns BitArray """
x_bit = BitArray(uint=int(minutia.x), length=self.X_BIT_LENGTH)
y_bit = BitArray(uint=int(minutia.y), length=self.Y_BIT_LENGTH)
theta_bit = BitArray(uint=int(minutia.theta), length=self.THETA_BIT_LENGTH)
result_bit = x_bit.copy()
result_bit.append(y_bit)
result_bit.append(theta_bit)
assert len(result_bit) == self.TOTAL_BIT_LENGTH
return result_bit
def get_uint_from_minutia(self, minutia: MinutiaNBIS, non_negative=True):
""" Converts minutia to signed int
:param minutia: Minutia to be encoded to uint
:param non_negative: True if all coordinates in minutia are positive, else False (Minutia_NBIS_GH)
:returns unsigned int """
if not non_negative:
return self.get_total_bitstring_from_minutia(
MinutiaNBIS(minutia.x + minutia.X_MAX, minutia.y + minutia.Y_MAX, minutia.theta, limit=False)).uint
else:
return self.get_total_bitstring_from_minutia(minutia).uint
def get_minutia_from_bitstring(self, bitstring: BitArray, non_negative=True):
""" Recreates minutia from bitstring (BitArray)
:param bitstring: bitstring to decode to minutia
:param non_negative: True if all coordinates in minutia are positive, else False (Minutia_NBIS_GH, from storage)
:returns Minutia with unsigned integer values """
assert len(bitstring) == self.TOTAL_BIT_LENGTH
x = bitstring[0:self.X_BIT_LENGTH].uint
y = bitstring[self.X_BIT_LENGTH:self.X_BIT_LENGTH + self.Y_BIT_LENGTH].uint
theta = bitstring[
self.X_BIT_LENGTH + self.Y_BIT_LENGTH:self.X_BIT_LENGTH + self.Y_BIT_LENGTH + self.THETA_BIT_LENGTH].uint
if not non_negative:
x -= MinutiaNBIS_GH.X_MAX
y -= MinutiaNBIS_GH.Y_MAX
return MinutiaNBIS(x, y, theta)
def get_minutia_from_uint(self, unsigned_int, non_negative=True):
""" Recreates minutia from unsigned int that was created from bitstring
:param unsigned_int: representation of minutia
:param non_negative: True if all coordinates in minutia are positive, else False (Minutia_NBIS_GH, from storage)
:returns Minutia """
total_bit = BitArray(uint=unsigned_int, length=self.TOTAL_BIT_LENGTH)
return self.get_minutia_from_bitstring(total_bit, non_negative=non_negative)
|
def main():
arr = [6,4,7,8,10,12]
novelSort(arr,0,len(arr)-1)
print(arr)
def novelSort(arr,start,end):
if start >= end:
return arr
min_index = arr[start:end+1].index(min(arr[start:end+1])) + start
max_index = arr[start:end+1].index(max(arr[start:end+1])) + start
arr[start], arr[min_index] = arr[min_index], arr[start]
arr[end], arr[max_index] = arr[max_index], arr[end]
novelSort(arr, start + 1, end - 1)
main()
|
##https://www.geeksforgeeks.org/heap-sort/
import time
def main():
with open('input_10000.txt') as inputfile:
data = inputfile.read()
inputfile.close()
A = [int (i) for i in data.split()]
heapsize = 0
starttime = time.time()
heapsort(A)
endtime = time.time()
elapsedtime = endtime - starttime
print ("This test took", elapsedtime, "seconds")
def buildmaxheap(A):
global heapsize
heapsize = len(A)-1
for i in range((len(A)-1) // 2, -1,-1):
heapify(A,i)
def heapsort(A):
buildmaxheap(A)
for i in range((len(A)-1), 0,-1):
A[0],A[i] = A[i],A[0]
global heapsize
heapsize = heapsize - 1
heapify(A,0)
def heapify(A,i):
global heapsize
l = 2*i
r = (2*i) + 1
if l <= heapsize and A[l] > A[i]:
largest = l
else:
largest = i
if r <= heapsize and A[r] > A[largest]:
largest = r
if largest != i:
A[i],A[largest] = A[largest],A[i]
heapify(A,largest)
##test()
main()
|
import sys
import argparse
def setup_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--inputdata', type=str,
help='input a string for me to operate')
return parser
def expr(arr):
op = '+-*/'
stack =[]
while(len(arr)!=0):
for i in range(len(arr)):
if arr[i] not in op:
stack.append(int(arr.pop(i)))
break
elif arr[i] in op:
if (arr[i] =='+'):
temp2=stack.pop()
temp1=stack.pop()
arr.pop(i)
stack.append(temp1+temp2)
break
elif (arr[i] =='-'):
temp2=stack.pop()
temp1=stack.pop()
arr.pop(i)
stack.append(temp1-temp2)
break
elif (arr[i] =='*'):
temp2=stack.pop()
temp1=stack.pop()
arr.pop(i)
stack.append(temp1*temp2)
break
elif (arr[i] =='/'):
temp2=stack.pop()
temp1=stack.pop()
arr.pop(i)
stack.append(temp1/temp2)
break
else:
pass
else:
pass
#raise ValueError('This opeation I don't know')
print(stack[0])
if __name__ == '__main__':
args = setup_parser().parse_args()
print('My input is :', args.inputdata)
str_arr = args.inputdata;
print(str_arr)
arr =[]
for i in range(len(str_arr)):
arr.append(str_arr[i])
print(arr)
expr(arr)
|
from collections import namedtuple
# Orientations
UP, RIGHT, DOWN, LEFT = range(4)
# Turning
TURN_LEFT, GO_STRAIGH, TURN_RIGHT = range(3)
def next(turn):
return (turn + 1) % 3
Cart = namedtuple("Cart", "x, y, orientation, next_turn")
def out_of_lane(cart):
raise Exception("out of lane", cart)
def horizontal(cart):
if cart.orientation == RIGHT:
return cart._replace(x=cart.x+1)
elif cart.orientation == LEFT:
return cart._replace(x=cart.x-1)
else:
raise Exception("moving %s in horizontal lane", "UP" if cart.orientation == UP else "DOWN")
def vertical(cart):
if cart.orientation == DOWN:
return cart._replace(y=cart.y+1)
elif cart.orientation == UP:
return cart._replace(y=cart.y-1)
else:
raise Exception("moving %s in vertical lane", "LEFT" if cart.orientation == LEFT else "RIGHT")
def diagonal(cart):
if cart.orientation == UP:
return cart._replace(y=cart.y-1, orientation=LEFT)
elif cart.orientation == RIGHT:
return cart._replace(x=cart.x+1, orientation=DOWN)
elif cart.orientation == DOWN:
return cart._replace(y=cart.y+1, orientation=RIGHT)
else:
return cart._replace(x=cart.x-1, orientation=UP)
def contra_diagonal(cart):
if cart.orientation == UP:
return cart._replace(y=cart.y-1, orientation=RIGHT)
elif cart.orientation == RIGHT:
return cart._replace(x=cart.x+1, orientation=UP)
elif cart.orientation == DOWN:
return cart._replace(y=cart.y+1, orientation=LEFT)
else:
return cart._replace(x=cart.x-1, orientation=DOWN)
next_orientation = {
UP : {
TURN_LEFT : LEFT,
TURN_RIGHT : RIGHT },
RIGHT : {
TURN_LEFT : UP,
TURN_RIGHT : DOWN },
DOWN : {
TURN_LEFT : RIGHT,
TURN_RIGHT : LEFT },
LEFT : {
TURN_LEFT : DOWN,
TURN_RIGHT : UP },
}
def crossing(cart):
orientation = next_orientation[cart.orientation].get(cart.next_turn, cart.orientation)
next_turn = next(cart.next_turn)
if cart.orientation == UP:
return cart._replace(y=cart.y-1, orientation=orientation, next_turn=next_turn)
elif cart.orientation == RIGHT:
return cart._replace(x=cart.x+1, orientation=orientation, next_turn=next_turn)
elif cart.orientation == DOWN:
return cart._replace(y=cart.y+1, orientation=orientation, next_turn=next_turn)
else:
return cart._replace(x=cart.x-1, orientation=orientation, next_turn=next_turn)
translate_orientation = { "^" : UP, ">" : RIGHT, "v" : DOWN, "<" : LEFT }
translate_cell = { " " : out_of_lane,
"-" : horizontal, "<" : horizontal, ">" : horizontal,
"|" : vertical, "^" : vertical, "v" : vertical,
"/" : contra_diagonal,
"\\" : diagonal,
"+" : crossing }
def parse_lines(file):
return [line.rstrip("\n") for line in file if len(line) > 0]
def test_parse_lines_test1():
with open("test1.txt", "r") as test1:
expected = ['|', 'v', '|', '|', '|', '^', '|']
assert expected == parse_lines(test1)
def test_parse_lines_test2():
with open("test2.txt", "r") as test2:
expected = ['/->-\\ ',
'| | /----\\',
'| /-+--+-\\ |',
'| | | | v |',
'\\-+-/ \\-+--/',
' \\------/ ']
assert expected == parse_lines(test2)
def parse_carts(lines):
carts = []
for y, row in enumerate(lines):
for x, c in enumerate(row):
if c in { '>', '<', '^', 'v' }:
carts.append(Cart(x=x, y=y, orientation=translate_orientation[c], next_turn=0))
return carts
def test_parse_carts_test1():
with open("test1.txt", "r") as test1:
expected = [Cart(x=0, y=1, orientation=DOWN, next_turn=0),
Cart(x=0, y=5, orientation=UP, next_turn=0)]
assert expected == parse_carts(parse_lines(test1))
def test_parse_carts_test2():
with open("test2.txt", "r") as test2:
expected = [Cart(x=2, y=0, orientation=RIGHT, next_turn=0),
Cart(x=9, y=3, orientation=DOWN, next_turn=0)]
assert expected == parse_carts(parse_lines(test2))
def parse_grid(lines):
grid = []
for line in lines:
row = []
for c in line:
row.append(translate_cell[c])
grid.append(row)
return grid
def test_parse_grid_test1():
with open("test1.txt", "r") as test1:
expected = [[vertical]] * 7
assert expected == parse_grid(parse_lines(test1))
def parse(fname):
with open(fname, "r") as f:
lines = parse_lines(f)
carts = parse_carts(lines)
grid = parse_grid(lines)
return carts, grid
def move(cart, grid):
if cart.orientation == UP:
x, y = cart.x, cart.y-1
elif cart.orientation == RIGHT:
x, y = cart.x+1, cart.y
elif cart.orientation == DOWN:
x, y = cart.x, cart.y+1
else:
x, y = cart.x-1, cart.y
return grid[y][x](cart)
def calc_part1(carts, grid):
while True:
carts.sort(key=lambda cart: (cart.y, cart.x))
occupied_positions = { (cart.x, cart.y) for cart in carts }
next_carts = []
for cart in carts:
occupied_positions.remove((cart.x, cart.y))
new_cart = move(cart, grid)
if (new_cart.x, new_cart.y) in occupied_positions:
return (new_cart.x, new_cart.y)
occupied_positions.add((new_cart.x, new_cart.y))
next_carts.append(new_cart)
carts = next_carts
def part1(fname):
carts, grid = parse(fname)
return calc_part1(carts, grid)
def test_part1():
assert (0, 3) == part1("test1.txt")
assert (7, 3) == part1("test2.txt")
def calc_part2(carts, grid):
while True:
if len(carts) == 1:
return carts[0].x, carts[0].y
carts.sort(key=lambda cart: (cart.y, cart.x))
occupied_positions = { (cart.x, cart.y) for cart in carts }
next_carts = []
for cart in carts:
if (cart.x, cart.y) not in occupied_positions:
continue
occupied_positions.remove((cart.x, cart.y))
new_car = move(cart, grid)
if (new_car.x, new_car.y) in occupied_positions:
occupied_positions.remove((new_car.x, new_car.y))
else:
occupied_positions.add((new_car.x, new_car.y))
next_carts.append(new_car)
carts = [cart for cart in next_carts if (cart.x, cart.y) in occupied_positions]
def part2(fname):
carts, grid = parse(fname)
return calc_part2(carts, grid)
def test_part2():
assert (6, 4) == part2("test3.txt")
if __name__ == "__main__":
print("Part1", part1("input.txt"))
print("Part2", part2("input.txt"))
|
import string
import sys
from string import printable
from Crypto.Cipher import AES
def first_half():
pt = 'aaaaaaaaaaaaaaaa'
val = len(pt) % 16
if not val == 0:
pt += '0' * (16 - val)
res = {}
for a in printable:
for b in printable:
for c in printable:
key1 = '0' * 13 + a + b + c
cipher1 = AES.new(key=key1, mode=AES.MODE_ECB)
c1 = cipher1.encrypt(pt.encode('hex')).encode("hex")
res[c1] = key1
return res
def second_half(first_half):
ct = "ef92fab38516aa95fdc53c2eb7e8fe1d5e12288fdc9d026e30469f38ca87c305ef92fab38516aa95fdc53c2eb7e8fe1d5e12288fdc9d026e30469f38ca87c305".decode("hex")
for a in printable:
for b in printable:
for c in printable:
key2 = a + b + c + '0' * 13
cipher2 = AES.new(key=key2, mode=AES.MODE_ECB)
res = cipher2.decrypt(ct)
if res in first_half:
key1 = first_half[res]
return key1, key2
def main():
flag = 'fa364f11360cef2550bd9426948af22919f8bdf4903ee561ba3d9b9c7daba4e759268b5b5b4ea2589af3cf4abe6f9ae7e33c84e73a9c1630a25752ad2a984abfbbfaca24f7c0b4313e87e396f2bf5ae56ee99bb03c2ffdf67072e1dc98f9ef691db700d73f85f57ebd84f5c1711a28d1a50787d6e1b5e726bc50db5a3694f576'.decode(
"hex")
first = first_half()
print("first complete")
key1, key2 = second_half(first)
cipher1 = AES.new(key=key1, mode=AES.MODE_ECB)
cipher2 = AES.new(key=key2, mode=AES.MODE_ECB)
print(key1, key2)
print(cipher1.decrypt(cipher2.decrypt(flag).decode("hex")).decode("hex"))
main()
def unintended():
flag = 'fa364f11360cef2550bd9426948af22919f8bdf4903ee561ba3d9b9c7daba4e759268b5b5b4ea2589af3cf4abe6f9ae7e33c84e73a9c1630a25752ad2a984abfbbfaca24f7c0b4313e87e396f2bf5ae56ee99bb03c2ffdf67072e1dc98f9ef691db700d73f85f57ebd84f5c1711a28d1a50787d6e1b5e726bc50db5a3694f576'.decode(
"hex")
for a in printable:
for b in printable:
for c in printable:
key2 = a + b + c + '0' * 13
cipher2 = AES.new(key=key2, mode=AES.MODE_ECB)
x = cipher2.decrypt(flag)
if len(set(x).difference(string.hexdigits)) == 0:
print("Found second", key2)
for a in printable:
for b in printable:
for c in printable:
key1 = '0' * 13 + a + b + c
cipher1 = AES.new(key=key1, mode=AES.MODE_ECB)
y = cipher1.decrypt(x.decode("hex"))
if len(set(y).difference(string.hexdigits)) == 0:
print("Found first", key1)
print(y.decode("hex"))
sys.exit(0)
# unintended()
|
import math
def number_of_divisors(number):
divisors = 0
for x in range(1, int(math.sqrt(number)) + 1):
if number % x == 0:
divisors += 1
if math.sqrt(number).is_integer():
return divisors * 2 - 1
return divisors * 2
number = 0
n = 1
while True:
number += n
n += 1
# print(number)
if number_of_divisors(number) > 500:
print(number)
break;
|
def sieve_of_sundaram(limit):
new_limit = limit // 2 - 1
boolean_list = [True] * new_limit;
i = 1
j = i
while (i + j + 2 * i * j < new_limit):
while (i + j + 2 * i * j <= new_limit):
boolean_list[2 * i * j + i + j - 1] = False
j += 1
i += 1
j = i
primes = [2]
for i in range(0, new_limit):
if boolean_list[i]:
primes.append(i * 2 + 3)
return primes
def is_prime(number, prime_list):
if number in prime_list:
return 1
return 0
def is_trancutable_prime(number, prime_list):
number_string = str(number)
for i in range(1, len(number_string)):
if not is_prime(int(number_string[i:len(number_string)]), prime_list):
# print(number_string[i:4] + "is not a prime")
return 0
if not is_prime(int(number_string[0:i]), prime_list):
# print(number_string[0:i] + "is not a prime")
return 0
if not is_prime(number, prime_list):
return 0
return 1
prime_list = sieve_of_sundaram(1000000)
trancutable_primes_count = 0
trancutable_primes_sum = 0
i = 10
while trancutable_primes_count < 11:
while not is_prime(int(str(i)[0:len(str(i)) - 1]), prime_list):
while len(str(i)) > 2 and not is_prime(int(str(i)[0:len(str(i)) - 2]), prime_list):
while len(str(i)) > 3 and not is_prime(int(str(i)[0:len(str(i)) - 3]), prime_list):
while len(str(i)) > 4 and not is_prime(int(str(i)[0:len(str(i)) - 4]), prime_list):
i += 10000
i += 1000
i += 100
i += 10
if is_trancutable_prime(i, prime_list):
trancutable_primes_sum += i
trancutable_primes_count += 1
# print(i)
i += 1
print(trancutable_primes_sum) |
"""Assume that when calling count_down on a smaller range it would
print the numbers of that range in decreasing order. """
# start <= end
def count_down(start, end):
if start == end:
return start
else:
print(end)
count_down(start, end - 1)
# start <= end
def count_up_and_down(start, end):
if start == end:
return start
else:
print(start)
count_down(start + 1, end)
print(start)
"""Assume that when calling factorial with k(<n) it would return
k!. """
# n >= 1
def factorial(n): # T(n) = O(n)
if n == 1:
return 1
else:
return n * factorial(n - 1)
""" Assume that when calling count_appereances on a smaller list
it would return the number of times val appears in that list. """
# size of the input is the length of the list
def count_apperances(lst, val): # this implimentation is n^2 because the slicing is linear
if len(lst) == 0:
return 0
else:
if lst[0] == val:
return count_apperances(lst[1:], val) + 1
else:
return count_apperances(lst[1:], val)
print(count_apperances([1, 3, 2, 4, 2, 43], 2))
""" Assume that when calling count_apperances_2 on a smaller list
it would return the number of times val appears ont aht list. """
# interface
def count_apperances_2(lst, val):
return count_apperances_2_helper(lst, 0, len(lst), val)
# recursive algorithm
def count_apperances_2_helper(lst, low, high, val): # linear algorithm
if low == high:
if lst[low] == val:
return 1
else:
return 0
else:
if lst[low] == val:
return count_apperances_2_helper(lst, low + 1, high, val) + 1
else:
return count_apperances_2_helper(lst, low, high, val)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class SeqStorage(object):
def __init__(self, MAXSIZE):
"""
初始化线性表
:param MAXSIZE:
"""
self.MAXSIZE = MAXSIZE
self.data = [None] * self.MAXSIZE
self.length = 0
def show_list(self):
print(self.data)
def get_elem(self, i):
"""
获取对应位置的元素
:param i:
:return:
"""
if self.length == 0 or i < 1 or i > self.length:
raise Exception('请输入正确的index或检查线性表是否为空')
e = self.data[i - 1]
return e
def list_insert(self, i, e):
"""
在i位置插入元素e
:param i:
:param e:
:return:
"""
if self.length == self.MAXSIZE:
raise Exception('线性表长度已达到最大')
if i < 1 or i > self.length + 1:
raise Exception('请输入正确的index')
if i <= self.length:
for k in range(self.length - 1, i - 2, -1):
self.data[k + 1] = self.data[k]
self.data[i - 1] = e
self.length += 1
def list_delete(self, i):
"""
删除i位置元素并返回
:param i:
:return:
"""
e = self.data[i - 1]
if self.length == 0:
raise Exception('线性表为空')
if i < 1 or i > self.length:
raise Exception('请输入正确的index')
if i == self.length:
self.data[i - 1] = None
if i < self.length:
for k in range(i, self.length):
self.data[k - 1] = self.data[k]
self.data[self.length - 1] = None
self.length -= 1
return e
if __name__ == '__main__':
s = SeqStorage(20)
s.list_insert(1, 10)
s.list_insert(2, 11)
s.list_insert(2, 12)
s.list_insert(3, 14)
print(s.length)
s.show_list()
s.list_delete(3)
s.show_list()
s.list_delete(3)
s.show_list()
|
import turtle # importing our graphical library
turtle.speed(10) # Set speed of drawing
turtle.hideturtle() # Disable default turtle object
s = turtle.Screen() # Create a graphic window
s.bgcolor("black") # Set background color
turtle.pencolor("red") # Set drawing pen color
turtle.pensize(5) #Set drawing pen size to 5 (For better visualization)
s.title("Cantor Set Fractal By Smaranjit Ghose") # Set Title
def cantor_set(x, y, length):
if(length > 1):
turtle.up()
turtle.goto(x, y)
turtle.down()
turtle.forward(length)
turtle.up()
y = y-10
turtle.goto(x, y)
turtle.down()
cantor_set(x, y, length/3)
cantor_set(x+length*2/3, y, length/3)
cantor_set(-250, 0, 500)
|
def generarBaseDatos():
listaPalabras = []
continuar = "si"
while continuar == "si":
listaPalabras.append(input("Ingrese una palabra: "))
continuar=input("Desea agregar otra palabra? (si/no): ")
return listaPalabras
def buscarPalabraAleat(listaPalabras):
import random
palabraAleatoria = random.randint(0, len(listaPalabras) -1)
return listaPalabras[palabraAleatoria]
# MAIN ESTO ES EL PROGRAMA
print()
print("**********AQUI COMIENZA EL JUEGO********")
print()
miLista = generarBaseDatos()
miPalabra = buscarPalabraAleat(miLista)
print()
print("============================")
print("la palabra elegida es ......")
print("============================")
print()
palabra=list(miPalabra)
vidas=6
faltan=len(palabra)
mostrarPalabra=[]
print()
for i in range(len(palabra)):
mostrarPalabra.append('*')
while vidas > 0 and faltan > 0:
print(mostrarPalabra)
letra = input("Ingrese una letra: ")
if letra in palabra:
faltan = faltan - palabra.count(letra)
print("letras restantes: ", faltan)
for i in range(len(palabra)):
if palabra[i] == letra:
mostrarPalabra[i] = letra
else:
vidas= vidas-1
print("vidas: ", vidas)
if faltan ==0:
print("Ganaste el juego!!!!!!")
print("la palabra es ", palabra)
elif vidas ==0:
print("Perdiste,podes intentarlo nuevamente!!!")
|
def exponenciar (base,exponente):
resultado = base
for i in range(1, exponente):
resultado = resultado * base
return resultado
base = int(input("base: "))
exponente = int(input("exponente: "))
resultado = exponenciar(base,exponente)
print(resultado)
|
#!/usr/bin/python
def displayPathtoPrincess(n,grid):
p0 = grid[0][0] == 'p'
p1 = grid[0][n-1] == 'p'
p2 = grid[n-1][n-1] == 'p'
p3 = grid[n-1][0] == 'p'
up_down = True
left_right = True
if p1:
left_right = False
elif p2:
up_down = False
left_right = False
elif p3:
up_down = False
x = (n-1)//2
str1 = ''
if up_down:
str1+='UP\n'* x
else:
str1+='DOWN\n'* x
if left_right:
str1+='LEFT\n'* x
else:
str1+='RIGHT\n'* x
print(str1)
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
displayPathtoPrincess(m,grid) |
#Tipos de dados:
# string(str) "assim"
# inteiro(int) 0 10 20 30 -10 -20 -30
# real(float) 10.50 1.4 2.5
# boolean(bool) true/false
#funcao type retorna o tipo do valor
print('Gabriel ',type('Gabriel'),sep=' ### ')
print('10 ',type(10),sep=' ### ')
print('10.5 ',type(10.5),sep=' ### ')
print('10 = 10 ',type(10==10),sep=' ### ') |
# Condições IF, ELIF, ELSE
#como não usa chaves, ele se considera pela qtd de espaços
#se for verdadeiro entra na condição if
if True:
print("verdadeiro.")
else:
print('não é verdadeiro')
#se for falso, entra na condição else
if False:
print("verdadeiro.")
else:
print('não é verdadeiro')
if False:
print('verdadeiro')
elif True:
print('Agora é verdadeiro')
else:
print('não é verdadeiro') |
#exibir algo na tela
print('hello world')
print(123456)
#argumento nomeado sep='any' que da replace espaço entre argumento
#argumento nomeado end='any' que da replace na quebra de linha
#print('Gabriel', 'Miranda', 16, 'anos')
print('Gabriel', 'Miranda', sep='-',end='\n# # # # # # # # #\n')
print('Gabriel', 'Miranda', sep='-')
#python é case sensitive
#desafio criar cpf
print(824, 176, '070', sep='.',end='-')
print(18) |
# ===
# Program Name: harris-lab2-assign1.py
# Lab no: 2
# Description: Temperature Conversion App
# Student: Stacy Harris
# Date: 6/12/2020
# ===
import os.path
title = "Temperature Conversion Application"
print(title)
def main():
print("Would you like to convert from Fahrenheit to Centigrade or Centigrade to Fahrenheit?")
convert_input = input("For from Fahrenheit to Centigrade enter: F \n For Centigrade to Fahrenheit enter: C\n")
convert_input = convert_input.capitalize()
if convert_input == "F":
far_to_cent()
elif convert_input == "C":
cent_to_far()
else:
print("Please enter F or C")
main()
def far_to_cent():
fahrenheit_temp = float(input("Enter you temperature you would like to convert: "))
centigrade_temp = (5 / 9) * (fahrenheit_temp - 32)
centigrade_temp = float(round(centigrade_temp, 2))
print("{0} Fahrenheit is equal to {1} Centigrade.".format(fahrenheit_temp, centigrade_temp))
write_to_file(fahrenheit_temp, centigrade_temp)
end()
def cent_to_far():
centigrade_temp = float(input("Enter you temperature you would like to convert: "))
fahrenheit_temp = (((9 / 5) * centigrade_temp) + 32)
fahrenheit_temp = float(round(fahrenheit_temp, 2))
print("{0} Centigrade is equal to {1} Fahrenheit.".format(centigrade_temp, fahrenheit_temp))
write_to_file(fahrenheit_temp, centigrade_temp)
end()
def write_to_file(fahrenheit_temp, centigrade_temp):
if os.path.exists('temp_conversion.txt'):
with open("temp_conversion.txt", "a") as conversions:
conversions.write(" {0}\t\t\t\t\t {1}\n".format(centigrade_temp, fahrenheit_temp))
else:
with open("temp_conversion.txt", "a") as conversions:
conversions.write("Centigrade\t\t\t\tFahrenheit\n")
conversions.write("__________\t\t\t\t__________\n")
conversions.write(" {0}\t\t\t\t\t {1}\n".format(centigrade_temp, fahrenheit_temp))
def end():
end_result = input("Are you sure you wish to exit? Y or N ")
if end_result.lower() == "y":
exit()
else:
print()
print("*" * 80)
main()
main()
|
import pygame #importing pygame package
import sys #module helps to manipulate different parts (functions variables)
pygame.init() #initialize all imported pygame modules
#main interface
WINDOW_WIDTH = 1200
WINDOW_HEIGHT = 700
FPS = 20 # frames per second
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
ADD_NEW_FLAME_RATE = 25
cactus_img = pygame.image.load('mario/cactus_bricks.png') #load new image from a file
cactus_img_rect = cactus_img.get_rect() #rect->objects to store and manipulate rectangular areas
cactus_img_rect.left = 0
fire_img = pygame.image.load('mario/fire_bricks.png') ##load new image from a file
fire_img_rect = fire_img.get_rect() #rect->objects to store and manipulate rectangular areas
fire_img_rect.left = 0
CLOCK = pygame.time.Clock() #create an object to help track time
font = pygame.font.SysFont('forte', 20) #return a new font object that is loaded from the system fonts
canvas = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) #It actually creates an instance of the pygame
pygame.display.set_caption('Mini-Mario') #get the current window caption
# creating Topscore class
class TopScore:
def __init__(self):
self.h_score = 0 # initially high score=0
def top_score(self, score):
if score > self.h_score: #check the condition
self.h_score = score
return self.h_score
# class for hero Mario
class Mini_Mario:
velocity = 10 #library function
def __init__(self):
self.mario_img = pygame.image.load('mario/maryo.png') #load new image from a file of mario
self.mario_img_rect = self.mario_img.get_rect() #rect->objects to store and manipulate rectangular areas
self.mario_img_rect.left = 20
self.mario_img_rect.top = WINDOW_HEIGHT / 2 - 100 #set the window hight
self.down = True
self.up = False
#update fuction for checking mario
def update(self):
#set different conditions
canvas.blit(self.mario_img, self.mario_img_rect)
if self.mario_img_rect.top == cactus_img_rect.bottom: #check condition
game_over() #call game_over function
if SCORE > self.mario_score: #check condition
self.mario_score = SCORE
if self.mario_img_rect.bottom >= fire_img_rect.top: #check condition
game_over() #call game_over function
if SCORE > self.mario_score: #check condition
self.mario_score = SCORE
if self.up:
self.mario_img_rect.top -= 10
if self.down:
self.mario_img_rect.bottom += 10
class Dragon:
velocity_of_dragon = 10 # movement velocity
# variables for Dragon
def __init__(self):
self.img_of_dragon = pygame.image.load('mario/dragon.png') # insert dragon image
self.dragon_img_rect = self.img_of_dragon.get_rect()
self.dragon_img_rect.width -= 10
self.dragon_img_rect.height -= 10
self.dragon_img_rect.top = WINDOW_HEIGHT / 2
self.dragon_img_rect.right = WINDOW_WIDTH
self.up = True
self.down = False
# set the movement conditions of dragon
def update(self):
canvas.blit(self.img_of_dragon, self.dragon_img_rect)
if self.dragon_img_rect.top == cactus_img_rect.bottom:
self.up = False
self.down = True
elif self.dragon_img_rect.bottom >= fire_img_rect.top:
self.up = True
self.down = False
if self.up:
self.dragon_img_rect.top -= self. velocity_of_dragon
elif self.down:
self.dragon_img_rect.top += self. velocity_of_dragon
# class for the dragon flame
class Flames_Of_Dragon:
velocity_of_flames = 20 # flame velocity
# flame variable
def __init__(self):
self.dragon_flames = pygame.image.load('mario/fire2.png') # insert flame image
self.flames_img = pygame.transform.scale(self.dragon_flames, (20, 20))
self.flames_img_rect = self.flames_img.get_rect()
self.flames_img_rect.right = dragon.dragon_img_rect.left
self.flames_img_rect.top = dragon.dragon_img_rect.top + 30
def update(self):
canvas.blit(self.flames_img, self.flames_img_rect)
if self.flames_img_rect.left > 0:
self.flames_img_rect.left -= self.velocity_of_flames
|
import pygame
from Helpers import write
from Helpers import color
def playGame(game):
game.clear_screen()
game.display_stats()
# Bet
# Money input from user
if game.betting:
write(game.screen, "BET", 54, color("black"), (game.width/2 - 20, game.height/2 - 54))
write(game.screen, str(game.bet), 48, color("black"), (game.width/2 - 20, game.height/2+10))
write(game.screen, "Press a to increase and d to decrease, Press b to bet!", 32, color("black"), (game.width/8, game.height/2+64))
if game.pressedKeys[pygame.K_b]:
if game.bet > game.money or game.bet <= 0:
write(game.screen, "Not enough money", 32, color("black"), (game.width/3, game.height/2+90))
else:
game.betting = False
game.money -= game.bet
elif game.pressedKeys[pygame.K_a]:
game.bet += 10
elif game.pressedKeys[pygame.K_d]:
if game.bet > 0:
game.bet -= 10
else:
# Distribute cards
if game.distributing:
# display user cards
cardY = game.height * 3/4
cardX = game.width/2 - 100
for card in game.player.cards:
card.render(cardX, cardY)
cardX += 25
# Actions of user
# Determine who wins
|
"""
I answered incorrectly during a interview on 9/20/19 with Pokemon/Karat.
I said there would be an error with printing f.count()
But the correct answer is that 10.
Is Apple instantiated first and its count saved and not overwritten by
According to here
https://www.programiz.com/python-programming/multiple-inheritance
Method Resolution Order (MRO) says that the order of presidence goes from left to right.
So this case, Apple's count method takes presidence over Pear
"""
class Apple(object):
__color = 'red'
def __repr__(self):
return "instance of apple"
def count(self):
return 10
class Pear(object):
__color = "yellow"
def __repr__(self):
return "instance of pear"
def count(self):
return 15
class Fruit(Apple, Pear):
# See note above
pass
f = Fruit()
print(f.count())
class BaseSpace(object):
_type = "Default"
def get_type(self):
print(self.__type)
class TruckSpace(BaseSpace):
_type = "Truck"
def get_type(self):
print(self._type)
class CarSpace(BaseSpace):
def get_type(self):
print(self._type)
truck = TruckSpace()
truck.get_type()
car = CarSpace()
car.get_type()
|
# DOCS
# https://docs.python.org/3.7/library/stdtypes.html#set
a = set([1, 2, 3, 4, 5, 6])
b = a
c = set([1, 3, 5])
d = set([1, 10])
print(b.issubset(c)) # False
print(c.issubset(b)) # True
print(b.issuperset(c)) # True
print(b.union(c)) # set([1, 2, 3, 4, 5, 6])
print(c.union(b)) # set([1, 2, 3, 4, 5, 6]) what is in both c and b
print(c.difference(d)) # set([3, 5]) what is in c but not d
print(c.intersection(d)) # set([1]) venn-diagram intersection
print(c.symmetric_difference(d)) # set([3, 5, 10])
|
"""
Given an int array of holes where 1 means a mole and 0 is no mole.
Find out the max number of moles you can hit with a mallet of width w.
http://leetcode.com/discuss/interview-question/350139/Google-or-phone-screen-or-whac-a-mole
"""
# ans = 4
holes1 = [0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0]
w1 = 5
holes2 = []
w2 = 1
holes3 = [0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0]
w3 = 10
def findMaxDuplicateWork(holes, w):
"""
This version contains duplicate work inside the for loop with the use of sum().
"""
# check bounds
if w >= len(holes):
return sum(holes)
curr_max = 0
# the number of steps the sliding window will take
steps = len(holes) + 1 - w
for idx in range(steps):
curr_sum = sum(holes[idx: idx+w]) # duplicate work here
curr_max = max(curr_sum, curr_max)
return curr_max
assert findMaxDuplicateWork(holes1, w1) == 4
assert findMaxDuplicateWork(holes2, w2) == 0
assert findMaxDuplicateWork(holes3, w3) == 5
def findMax(holes, w):
# check bounds
if w >= len(holes):
return sum(holes)
# init vars
curr_sum = curr_max = 0
steps = len(holes)
for start in range(steps):
curr_sum += holes[start]
if (start >= w):
curr_sum -= holes[start-w]
curr_max = max(curr_sum, curr_max)
return curr_max
assert findMax(holes1, w1) == 4
assert findMax(holes2, w2) == 0
assert findMax(holes3, w3) == 5
|
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = ''
adjuster = 0
#go in reverse order through a string
for ss in range(len(s),0,-1):
substring = s[0:ss]
palindrome = self.findPalindrome(substring)
print("ss: %d longest %s palindrome %s" % (ss, longest, palindrome))
#if there hasn't been a longest before, than this is automatically the longest
if longest == '':
longest = palindrome
#if the longest is the same as the original string passed in, then no need to look further
if longest == s:
break
#otherwise check if the found palindrome is the longest
elif len(palindrome) >= len(longest):
longest = palindrome
return longest
def findPalindrome(self, s):
slen = len(s)
mid = slen / 2
longest = ''
print("Testing %s" % s)
#base case, nothing to check
if slen <= 1:
return s
#is front a palindrome
if self.checkPalindrome(s):
#check if its the longest
if len(s) > len(longest):
longest = s
#if top string is not a palindrome,
else:
#cut in half and see if that is the longest palindrome
print("finding in front half")
front = self.findPalindrome(s[:mid])
back = ''
#and test the back half as well
print("finding in back half")
if(slen % 2 == 0):
back = self.findPalindrome(s[mid:])
else:
back = self.findPalindrome(s[mid+1:])
#determine which is the longer palindrome
print("Front %s vs back %s" % (front, back))
if(len(front) > len(back)):
longest = front
else:
longest = back
print("longest is %s" % longest)
return longest
def checkPalindrome(self, s):
"""
check if the first part of a string is == to the back
"""
l = len(s)
mid = l / 2
front = ''
back = ''
ret = False
front = s[:mid]
#if even
if(l%2 == 0):
back = s[mid:]
else:
back = s[mid+1:]
#check if the strings are the same
if front == back[::-1]:
ret = True
return ret
sol = Solution()
"""
string = "ababa"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abaaba"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abgvba"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "abaqwerty"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
string = "babad"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest))
"""
string = "cbbd"
longest = sol.longestPalindrome(string)
print("Longest Palindrome of %s is %s" % (string,longest)) |
import pandas as pd
import matplotlib.pyplot as plt
# https://seaborn.pydata.org/tutorial.html
import seaborn as sns
table = pd.read_csv("soccerdata.csv")
print(table)
print(table.head())
print(table.head(10))
# print(table["Name"])
print(table.Name)
# sns.countplot(y=table.Nationality, palette="Set2")
# sns.countplot(x="Age", data=table)
# sns.countplot(x="Nationality", data=table)
# plt.show()
# Case Study : Find the GoalKeeper who is best to stop the kicks :)
# Let us create some weights
w1 = 1
w2 = 2
w3 = 3
w4 = 4
table["BEST_GK"] = (w1*table.GK_Kicking + w2*table.GK_Diving + w3*table.GK_Positioning + w4*table.GK_Reflexes)
print(table["BEST_GK"])
sortedData = table.sort_values("BEST_GK")
print(sortedData)
print(sortedData.tail(10)) |
print("Hello")
a=10
b=20
sum = a +b
print("sum is",sum);
#whatever we write in our program is by default part of main
print(__name__)#main |
"""
Unsupervised learning
We have data but no labels !!
Classification is numerically done by the model and we later name those classes
Output is not known for observations in DataSet
k-means clustering
k denotes no of classes we expect from our model
--------------------------------------------------------------------------------------
X Y P
--------
1 1 A
1 0 B
0 2 C
2 4 D
3 5 E
--------
we have above dataset as an example to work on 5 observations
each observation has 2 data points
But we dont know what class it belong to
Step 1
------
k -> represents number of classes
k -> 2
Asssume any 2 data points from the given dataset as CENTROIDS
eg: A(1,1) and C(0,2)
Step 2
-------
Calculate distance of each point from CENTROIDS
Eucilidean Distance Formula
suareroot [square(x2-x1) + (square(y2-y1)]
X Y P C1(1,1) C2(0,2)
-------------------------------
1 1 A 0 1.4
1 0 B 1 2.236
0 2 C 1.4 0
2 4 D 3.2 2.8
3 5 E 4.5 4.2
--------------------------------
Step-3
-------
Arrange Points as per distance from Centroids
P Nearest to
-----------------
A C1
B C1
C C2
D C2
E C2
-----------------
Looking the data above:
A and B who are nearest to C1, should be in one cluster
C, D and E who ae nearest to C2 are in another cluster
---------------------
X Y P NearestTo
---------------------
1 1 A C1
1 0 B C1
0 2 C C2
2 4 D C2
3 5 E C2
---------------------
C1 Mean = (1+1)/2, (1+0)/2
C2 Mean = (0+2+3)/3, (2+4+5)/3
C1Mean = (1, 0.5)
C2Mean = (1.7, 3.7)
--------------------------------------------
X Y P C1Mean(1, 0.5) C2Mean(1.7, 3.7)
distance distance
--------------------------------------------
1 1 A 0.5 2.7
1 0 B 0.5 3.7
0 2 C 1.8 2.4
2 4 D 3.6 0.5
3 5 E 4.9 1.9
--------------------------------------------
--------------------------------------------
X Y P NearestTo
---------------------
1 1 A C1
1 0 B C1
0 2 C C1
2 4 D C2
3 5 E C2
---------------------
We need to sure about our assumptions
We Re-Check Again with new centroids
New centroids shall be mean of previous cluster
---------------------
X Y P Nearest to
---------------------
1 1 A C1
1 0 B C1
0 2 C C2
2 4 D C2
3 5 E C2
--------------------
From above observation 1 of the data points i.e. C
has been shifted to C1 from C2
From our assumptions from where we started to hold it true,
if we get the same result twice we stop the consumption further
------------------
NC1 Mean = (1+1+0)/3, (1+0+2)/3
NC2 Mean = (2+3)/2, (4+5)/2
NC1Mean = (0.7, 1)
NC2Mean = (2.5, 4.5)
Now, Calculate distance from these above centroids
----------------------------------------------
X Y P NC1Mean(0.7, 1) NC2Mean(2.5, 4.5)
distance distance
----------------------------------------------
1 1 A 0.3 3.80
1 0 B 1.04 4.74
0 2 C 1.22 3.53
2 4 D 3.26 0
3 5 E 4.61 0.70
---------------------------------------------
---------------------
X Y P NearestTo
---------------------
1 1 A C1
1 0 B C1
0 2 C C1
2 4 D C2
3 5 E C2
---------------------
NOW, Algorithm Stops working
We will finalize Cluster Centroids as
(0.7, 1) Class 1
(2.5, 4.5) Class 2
Any UnObserved Data Point can now be computed
that it is nearer to which cluster and hence, it will have that class
"""
import matplotlib.pyplot as plt
X = [1, 1, 0, 2, 3]
Y = [1, 0, 2, 4, 5]
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.scatter(X, Y)
plt.title("k-means Clustering")
plt.show()
# Try writing above mathematical discussion as OOPS Program :)
class KMeans:
def __init__(self, clusters=2):
self.clusters = clusters
print(">> KMeans Model Created")
def fit(self, X, Y):
pass
def predict(self, X, Y):
pass
|
# class Input:
#
# def __init__(self, input, weight):
# self.input = input
# self.weight = weight
class Perceptron:
def __init__(self, inputs=None):
self.inputs = inputs
print(">> Perceptron Created with Inputs")
print(inputs)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def summationFunction(self):
self.sum = 0
for i in range(len(self.inputs)):
self.sum += self.inputs[i][0] * self.inputs[i][1]
print(">> Summation Function Output", self.sum)
def activationFunction(self):
threshold = 1
if self.sum >= threshold:
print(">> Output is 1")
print(">> Decision Taken")
else:
print(">> Output is 0")
print(">> Decision Not Taken")
def activationFunctionLinear(self):
pass
def activationFunctionBinary(self):
pass
def activationFunctionSigmoid(self):
pass
def activationFunctionTanh(self):
pass
def activationFunctionRelu(self):
pass
def activationFunctionSoftmax(self):
pass
def main():
# [input weight]
inputs = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
]
perceptron = Perceptron(inputs)
perceptron.summationFunction()
perceptron.activationFunction()
if __name__ == '__main__':
main()
"""
Assignment:
1. Linear
2. Binary
3. Sigmoid
4. tanh
5. Relu
6. Softmax
create all above functions
take certain input X and plot them on matplotlib as line graph
"""
"""
Natural Language Toolkit Installation
pip install nltk
Tensorflow Installation
https://www.tensorflow.org/install
Pytorch Installation
https://pytorch.org/get-started/locally/
""" |
#for i in range (1, 11):
#for i in range (1, 11,2):
for i in range (10, 0, -1):
print(">> i is:", i)
print("==========")
"""
show(num) => print num
"""
#creating or defining a function
#recursion -> executing same fnc again nd again from the same function
def show(num):
if num== 0:
return #return statement is an acknowledgement
print(">> num is:", num)
num -= 1 # num = num-1
show(num)
#executing a function
show(10)
#show(9)
#show(8)
#show(7)
#show(6)
#show(5)
#running time of loop nd recursive fnc is same or different
#if same or more thn whts the fun? why we need it or use it! |
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn import metrics
# DataSet Description
# 1. Number of times pregnant
# 2. Plasma glucose concentration a 2 hours in an oral glucose tolerance test
# 3. Diastolic blood pressure (mm Hg)
# 4. Triceps skin fold thickness (mm)
# 5. 2-Hour serum insulin (mu U/ml)
# 6. Body mass index (weight in kg/(height in m)^2)
# 7. Diabetes pedigree function
# 8. Age (years)
# 9. Class variable (0 or 1)
diabetesDataSet = pd.read_csv("pima-indians-diabetes.csv")
print(diabetesDataSet)
featureColumns = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age']
X = diabetesDataSet[featureColumns]
# Y = diabetesDataSet['label']
Y = diabetesDataSet.label
print("~~~~~~~~~FEATURES~~~~~~~~~~")
print(X)
print("~~~~~~~~~LABELS~~~~~~~~")
print(Y)
# DataSet Division -> Training and Testing
# As we have dataset, we will not train model with all of our dataset
# we will train the model with random dataset observations.
# 70% shall be used to train and 30% for the testing
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=1)
# Model Creation
model = DecisionTreeClassifier()
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
print(y_pred)
# Percentage Score :) How Accurate the Model IS ?
print(">> Accuracy Score:", metrics.accuracy_score(y_test, y_pred)) |
from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
# Initial Data
X = [1, 2, 3, 4, 5]
Y = [2, 4, 5, 4, 5]
# Lienar Regression : 1 Line of Code :)
data = stats.linregress(X, Y)
print(">> Slope is:", data[0])
print(">> Interceptor is:", data[1])
print(">> Equation of Line: y = {} + {} * x".format(data[1], data[0]))
maxX = np.max(X) + 10
minY = np.min(Y) - 10
print("maxX:", maxX)
print("minY:", minY)
# Data Points for Linear Regression. Instead of 5, we got 100
x = np.linspace(minY, maxX, 100)
y = data[1] + data[0] * x
print(x)
print("----------")
print(y)
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
plt.plot(x, y, color="red", label="Regression Line")
plt.scatter(X, Y, color="blue", label="Data Points")
plt.legend()
plt.show() |
students = ["John", "Jennie", "Jim", "Jack", "Joe", ["Jim","Jack"]]
print(students, hex(id(students)))
newStudents = students + ["Fionna", "George"]
print(students, hex(id(newStudents)))
# Operation -> Concatenation in the same List
students = students + ["Fionna", "George"]
print(students, hex(id(students)))
someStudents = ["Jim","Joe"]
print(someStudents in newStudents)
someStudents = ["Jim","Jack"] #to make it true we put list in list see line 1st
print(someStudents in newStudents)
|
import sqlite3
def create_connection(path):
""" This function connect to the path given
:param path: path to connect
:return: connection
:rtype: string
"""
try:
connection = sqlite3.connect(path)
print("Connection to DB successful!")
except sqlite3.Error as e:
print(f"Oops, The error {e} occurred!")
return connection
def execute_on_db(connection, query):
""" This function execute query on the connection
:param connection: connection parameter
:param query: content
"""
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully!")
except sqlite3.Error as e:
print(f"Oops, The error {e} occurred!")
def execute_read_query(connection, query):
""" This function return content from query
:param connection: connection parameter
:param query: content from query needed
:return: content
:rtype: list
"""
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except sqlite3.Error as e:
print(f"Oops, The error '{e} occurred!")
def close_connection(connection):
""" This function close the connection
:param connection: connection parameter
"""
try:
connection.close()
print("The connection DB closed")
except sqlite3.Error as e:
print(f"Oops, The error {e} occurred!")
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
cursor = head
num = []
while cursor!=None:
num.append(cursor.val)
cursor = cursor.next
return self.sortedArrayToBST(num)
# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
return self.convert(num,0,len(num)-1)
def convert(self, num, start, end):
if start > end:
return None
mid = (start + end)/2
node = TreeNode(num[mid])
node.left = self.convert(num, start, mid-1)
node.right = self.convert(num, mid+1, end)
return node
def printTree(self, root):
if root==None:
return
print str(root.val) + "->"
self.printTree(root.left)
self.printTree(root.right)
if __name__=='__main__':
s = Solution()
root = TreeNode(1)
cursor = root
for i in range(2,7):
cursor.next = ListNode(i)
cursor = cursor.next
node = s.sortedListToBST(root)
s.printTree(node) |
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param preorder, a list of integers
# @param inorder, a list of integers
# @return a tree node
def buildTree(self, preorder, inorder):
return self.build(preorder,inorder,0,0,len(preorder))
def build(self,preorder,inorder,preOffset,inOffset,length):
if length<=0:
return None
if length==1:
return TreeNode(preorder[preOffset])
rootValue=preorder[preOffset]
inIndex=inorder.index(rootValue,inOffset,inOffset+length)
leftLength=inIndex-inOffset
left=self.build(preorder,inorder,preOffset+1,inOffset,leftLength)
right=self.build(preorder,inorder,preOffset+1+leftLength,inIndex+1,length-1-leftLength)
root=TreeNode(rootValue)
root.left=left
root.right=right
return root |
#!/usr/bin/env python3
# coding: utf-8
"""
Maximize It!
https://www.hackerrank.com/challenges/maximize-it
"""
from itertools import product
if __name__ == '__main__':
line = input().split()
k, m = [int(x) for x in line[:2]]
l = []
for _ in range(k):
line = input().split()
l.append([int(x) for x in line[1:]])
def s(l):
return sum([x * x for x in l]) % m
print(max(map(s, product(*l))))
|
#!/usr/bin/env python3
# coding: utf-8
"""
Hex Color Code
https://www.hackerrank.com/challenges/hex-color-code
"""
import re
if __name__ == '__main__':
re_rgb = re.compile(r'[ ,:(](#(?:[a-f0-9]{3}|[a-f0-9]{6}))[ ,;)]', re.I)
n = int(input())
for _ in range(n):
s = input()
for m in re.finditer(re_rgb, s):
print(m.group(1))
|
#!/usr/bin/env python3
# coding: utf-8
"""
Detect HTML Tags, Attributes and Attribute Values
https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values
"""
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
print(tag)
for name, value in attrs:
print('-> {} > {}'.format(name, value))
def handle_startendtag(self, tag, attrs):
print(tag)
for name, value in attrs:
print('-> {} > {}'.format(name, value))
if __name__ == '__main__':
n = int(input())
s = ''
for _ in range(n):
s += input().rstrip() + '\n'
parser = MyHTMLParser()
parser.feed(s)
|
#!/usr/bin/env python3
# coding: utf-8
"""
itertools.product()
https://www.hackerrank.com/challenges/itertools-product
"""
from itertools import product
if __name__ == '__main__':
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
print(*product(a, b))
|
import turtle
area = turtle.Screen()
area.setup(width=650, height=650)
area.bgcolor("black")
tr = turtle.Turtle()
tr.speed(10)
tr.fillcolor('yellow')
tr.begin_fill()
tr.circle(100)
tr.end_fill()
tr.goto(7, -20)
tr.color('white')
tr.circle(200)
tr.color('black')
tr.penup()
tr.goto(7, -22)
tr.pendown()
tr.fillcolor('gray')
tr.begin_fill()
tr.circle(5)
tr.end_fill()
tr.goto(7, -40)
tr.color('white')
tr.circle(300)
tr.color('black')
tr.penup()
tr.goto(7, -42)
tr.pendown()
tr.fillcolor('orange')
tr.begin_fill()
tr.circle(7)
tr.end_fill()
tr.goto(7, -64)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(6, -72)
tr.pendown()
tr.fillcolor('blue')
tr.begin_fill()
tr.circle(10)
tr.end_fill()
tr.penup()
tr.goto(6, -66)
tr.pendown()
tr.fillcolor('lightgreen')
tr.begin_fill()
for i in range(4):
tr.forward(5)
tr.right(90)
tr.end_fill()
tr.goto(7, -94)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(7, -96)
tr.pendown()
tr.fillcolor('red')
tr.begin_fill()
tr.circle(7)
tr.end_fill()
tr.goto(7, -150)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(6, -182)
tr.pendown()
tr.fillcolor('#f7e8c3')
tr.begin_fill()
tr.circle(40)
tr.end_fill()
tr.penup()
tr.goto(26, -162)
tr.pendown()
tr.fillcolor('red')
tr.begin_fill()
tr.circle(10)
tr.end_fill()
tr.goto(7, -230)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(6, -262)
tr.pendown()
tr.fillcolor('#f7e8c3')
tr.begin_fill()
tr.circle(40)
tr.end_fill()
tr.penup()
tr.goto(-15, -252)
tr.pendown()
tr.width(10)
tr.fillcolor('brown')
tr.pencolor('brown')
tr.begin_fill()
def draw(rad):
for i in range(2):
# two arcs
tr.circle(rad,90)
tr.circle(rad//65,90)
draw(55)
tr.end_fill()
tr.width(1)
tr.goto(7, -278)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(6, -288)
tr.pendown()
tr.fillcolor('cyan')
tr.begin_fill()
tr.circle(10)
tr.end_fill()
tr.goto(7, -298)
tr.color('white')
tr.circle(400)
tr.color('black')
tr.penup()
tr.goto(6, -308)
tr.pendown()
tr.fillcolor('blue')
tr.begin_fill()
tr.circle(10)
tr.end_fill()
turtle.done()
|
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
def plot_character_words(character):
lines = pd.read_csv('scooby_doo_lines.csv')
lines = lines[lines['character'] == character] # Filter to character
lines = lines['line'] # Get the text data
lines = [l.split(' ') for l in lines] # Split each line into individual words
lines = sum(lines, []) # Turn into single list of words
lines = ' '.join(lines) # Convert into string for wordcloud
wordcloud = WordCloud().generate(lines) # Make word cloud
plt.imshow(wordcloud, interpolation='bilinear') # Plot
plt.axis('off')
plt.show()
plot_character_words('Scooby-Doo')
import pdb
pdb.set_trace()
|
'''
5. Convert 8 to a string
'''
result = str(8)
print(result) |
'''
X, Y, Z respresenting dimensins of cuboid along with integer N
print list of all possible
'''
x = int(input("Enter X"))
y = int(input("Enter Y"))
z = int(input("Enter Z"))
n = int(input("Enter N"))
coordinates = [] |
'''
4. Write a program which prompts the user for 10 floating-point numbers and calculates
their sum, product and average. Your program should only contain a single loop.
'''
print("Enter 10 floating-point numbers: ")
count = 0
float_list = []
sum = 0.0
product = 1.0
while count < 10:
number = float(input("Enter number: "))
float_list.append(number)
sum += number
product *= number
count += 1
average = sum/len(float_list)
# print("sum = %f \n product = %f \n average = %f"% sum, product, average)
print("sum = %f"% sum)
print("product = %f"% product)
print("average = %f"% average)
|
#defind a variable with a boolean value
it_is_tuesday = False
print("Which day is today")
#this is if statement starts a new block
if it_is_tuesday:
#this is inside the block
print("It's Tuesday")
#this is outside the block
print("Print this no matter what")
|
'''
1. Create a set whih contains the first four positive integers a and set b which contains
the first four odd positive integers
'''
a = {1, 2, 3, 4}
b = {5, 6, 7, 8}
print(a)
print(b)
'''
2. Create a new set c which combine the numbers which are in a or b (or both)
'''
c = a.union(b)
print(c)
'''
3. Create a set d which all the elements in a but not in b
'''
d = a.difference(b)
print(d)
'''
4. Create a set e which all the elements in b but not in a
'''
e = b.difference(a)
print(e)
'''
5. Create a set f which contains all the elements which are in a and b
'''
f = a.intersection(b)
print(f)
'''
6. Create a set f which contains all the elements which are in either a or in b but not both
'''
b = a.symmetric_difference(b)
print(f)
'''
7. Print the number of elements in c
'''
print(len(c))
|
class Solution:
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
ind = 0
while(ind != len(A)):
d = ind
ind = B[ind+1:].find(A[0])
if (ind == -1):
break
else:
ind += d + 1
if (B[ind:]+B[0:ind] == A) == True:
break
return B[ind:]+B[0:ind] == A |
#全局变量指向没有改箭头,则不用加global
import threading
import time
#定义一个全局变量
g_nums = [11,12]
g_num = 12
def test1(temp):
temp.append(33)
print("---in test1 temp=%s----" % str(temp) )
def test2(temp):
print("----in test2 temp=%s----" % str(temp))
def main():
#target指定将来新线程去哪个函数执行代码
#args是调用函数,传的数据
t1 = threading.Thread(target=test1,args=(g_nums,))
t2 = threading.Thread(target=test2,args=(g_num,))
t1.start()
time.sleep(1)
t2.start()
time.sleep(1)
print("----in main Thread g_num = %d----" % g_num)
if __name__ == '__main__':
main() |
arquivo = open("entradaSintatico.txt", "r")
tokens = arquivo.read()
tokens = tokens.split(" ")
posInicial = 0
posFinal = 0
tempAtual = 0
tabSimb = []
verificacoes = []
cod3End = []
linhaCod = 1
def Z(ch, pos):
if ch == "var":
ch, pos = I(ch, pos)
ch, pos = S(ch, pos)
print("Cadeia sintaticamente correta.")
else:
print("Erro, esperado var e encontrado %s no %dº token" %(ch, pos+1))
exit()
def I(ch, pos):
if ch == "var":
ch, pos = proxsimb(ch, pos)
ch, pos = D(ch, pos)
return (ch, pos)
else:
print("Erro, esperado var e encontrado %s no %dº token" %(ch, pos+1))
exit()
def D(ch, pos):
if isIdent(ch):
ch, pos = L(ch, pos)
if ch == ":":
ch, pos = proxsimb(ch, pos)
ch, pos = K(ch, pos)
ch, pos = O(ch, pos)
return (ch, pos)
else:
print("Erro, esperado : e encontrado %s no %dº token" %(ch, pos+1))
exit()
elif ch == "if":
return (ch, pos)
else:
print("Erro, esperado identificador ou if e encontrado %s no %dº token" % (ch, pos + 1))
exit()
def L(ch, pos):
if isIdent(ch):
addTabSimb(ch)
ch, pos = proxsimb(ch, pos)
ch, pos = X(ch, pos)
return(ch, pos)
else:
print("Erro, esperado identificador e encontrado %s no %dº token" %(ch, pos+1))
exit()
def X(ch, pos):
if ch == ",":
ch, pos = proxsimb(ch, pos)
ch, pos = L(ch, pos)
return(ch, pos)
elif ch == ":":
return (ch, pos)
else:
print("Erro, esperado , ou : e encontrado %s no %dº token" %(ch, pos+1))
exit()
def K(ch, pos):
if ch == "integer":
addTipo(ch, ch)
ch, pos = proxsimb(ch, pos)
return (ch, pos)
elif ch == "real":
addTipo(ch, ch)
ch, pos = proxsimb(ch, pos)
return (ch, pos)
else:
print("Erro, esperado integer ou real e econtrado %s no %dº token" %(ch, pos+1))
exit()
def O(ch, pos):
if ch == ";":
ch, pos = proxsimb(ch, pos)
ch, pos = D(ch, pos)
return (ch, pos)
elif isIdent(ch):
return (ch, pos)
elif ch == "if":
return (ch, pos)
else:
print("Erro, esperado ; ou identificador ou if e econtrado %s no %dº token" %(ch, pos+1))
exit()
def S(ch, pos):
global cod3End, linhaCod
if isIdent(ch):
if not existe(ch):
print("Identificador %s na posicao %sº nao declarado" %(ch, str(pos)))
exit()
addListaVerificacao(ch)
EEsq = ch
ch, pos = proxsimb(ch, pos)
if ch == ":=":
ch, pos = proxsimb(ch, pos)
ch, pos, EDir = E(ch, pos)
linha = "%d: [:= %s %s %s]" % (linhaCod, EEsq, EDir, "-")
cod3End.insert(linhaCod, linha)
linhaCod = linhaCod + 1
return (ch, pos)
else:
print("Erro, esperado := e econtrado %s no %dº token" %(ch, pos+1))
exit()
elif ch == "if":
ch, pos = proxsimb(ch, pos)
ch, pos, EDir = E(ch, pos)
if ch == "then":
S1Quad = linhaCod - 1
linhaCod = linhaCod + 1
ch, pos = proxsimb(ch, pos)
ch, pos = S(ch, pos)
linha = "%d: [JF %s %s %s]" % (S1Quad + 1, EDir, '<T>', "-")
cod3End.insert(S1Quad, linha)
linhaCod = linhaCod + 1
return (ch, pos)
else:
print("Erro, esperado then e econtrado %s no %dº token" %(ch, pos+1))
exit()
else:
print("Erro, esperado identificador ou if e econtrado %s no %dº token" %(ch, pos+1))
exit()
def E(ch, pos):
if isIdent(ch):
ch, pos, REsq = T(ch, pos)
ch, pos, EDir = R(ch, pos, REsq)
return (ch, pos, EDir)
else:
print("Erro, esperado identificador e econtrado %s no %dº token" %(ch, pos+1))
exit()
def R(ch, pos, REsq):
if ch == "+":
ch, pos = proxsimb(ch, pos)
ch, pos, R1Esq = T(ch, pos)
ch, pos, R1Dir = R(ch, pos, R1Esq)
RDir = geraTemp(REsq)
global cod3End, linhaCod
linha = "%d: [+ %s %s %s]" %(linhaCod, REsq, R1Dir, RDir)
cod3End.insert(linhaCod, linha)
linhaCod = linhaCod + 1
return (ch, pos, RDir)
elif ch == "then":
global verificacoes
if (not verificaTipo(verificacoes)):
exit()
verificacoes = []
return (ch, pos, REsq)
elif ch == "#":
if (not verificaTipo(verificacoes)):
exit()
verificacoes = []
return (ch, pos, REsq)
else:
print("Erro, esperado + ou then e econtrado %s no %dº token" %(ch, pos+1))
exit()
def T(ch, pos):
if isIdent(ch):
if not existe(ch):
print("Identificador %s na posicao %sº nao declarado" %(ch, str(pos)))
exit()
addListaVerificacao(ch)
TDir = ch
ch, pos = proxsimb(ch, pos)
return (ch, pos, TDir)
else:
print("Erro, esperado identificador e econtrado %s no %dº token" %(ch, pos+1))
exit()
def proxsimb(ch, pos):
if pos < len(tokens)-1:
return (tokens[pos + 1], pos + 1)
else:
return ("#", pos)
def isIdent(ch):
if ch == "var" or ch == "integer" or ch == "real" or ch == "if" or ch == "then":
resultado = False
elif (ch[0] >= "a" and ch[0] <= "z") or (ch[0] >= "A" and ch[0] <= "Z"):
resultado = True
else:
resultado = False
return resultado
def addTabSimb(ch):
global posFinal, tabSimb
for i in range(0, len(tabSimb)):
if tabSimb[i]['Cadeia'] == ch:
print('Cadeia ' + ch + " ja existe na tabela de simbolos.")
exit()
posFinal = posFinal + 1
conteudo = {'Cadeia': ch, 'Token': 'id', 'Categoria': 'var', 'Tipo': 'null'}
tabSimb.append(conteudo)
def addTipo(ch, tipo):
global posInicial, posFinal, tabSimb
for i in range(posInicial, posFinal):
tabSimb[i]['Tipo'] = tipo
posInicial = posFinal
def addListaVerificacao(ch):
global verificacoes, tabSimb
for i in range(len(tabSimb)):
if tabSimb[i]['Cadeia'] == ch:
verificacoes.append(tabSimb[i]['Tipo'])
def verificaTipo(verificacoes):
tipo = verificacoes[0]
for i in verificacoes:
if i != tipo:
print("Impossivel operar real com inteiro")
return False
verificacoes = []
return True
def existe(ch):
global tabSimb
for i in range(len(tabSimb)):
if tabSimb[i]['Cadeia'] == ch:
return True
return False
def geraTemp(ch):
global tabSimb, tempAtual
for i in range(len(tabSimb)):
if ch == tabSimb[i]['Cadeia']:
tipo = tabSimb[i]['Tipo']
tempAtual = tempAtual + 1
conteudo = {'Cadeia': 't' + str(tempAtual), 'Token': 'id', 'Categoria': 'var', 'Tipo': tipo}
tabSimb.append(conteudo)
return 't' + str(tempAtual)
#Main
Z(tokens[0], 0)
arquivo.close()
print("\n=-=-=-=-=-=-=-=-=-=-=-=-=TABELA DE SIMBOLOS=-=-=-=-=-=-=-=-=-=-=-=-=")
for i in range(len(tabSimb)):
print(tabSimb[i])
print("\n\n=-=CODIGO INTERMEDIARIO=-=")
cod3End = sorted(cod3End)
for i in range(len(cod3End)):
if cod3End[i][4] == 'J':
cod3End[i] = cod3End[i].replace('<T>', str(len(cod3End) + 1))
for i in cod3End:
print(f'{i}')
print(str(len(cod3End) + 1) + ": [...]")
|
import random
list1=["snake","water","gun"]
value=random.choice(list1)
print("******Snake Water Gun Game******")
name=input("Please Enter your name: ".upper())
cu=0
cp=0
c=5
while c>0:
a = input("You Choice 1. for Snake 2. for Water 3.for Gun\n")
if a == "snake":
if a == value:
print(f"Match is draw::{a} vs {value} ")
c=c-1
print("Chance left",c)
elif value == "water":
print(f"You won ::{a} vs {value}")
cu+=1
c=c-1
print("Chance left",c)
elif value == "gun":
print(f"You Lost ::{a} vs {value}")
cp+=1
c=c-1
print("Chance left",c)
elif a=="water":
if a == value:
print(f"Match is draw::{a} vs {value} ")
c=c-1
print("Chance left",c)
elif value == "gun":
print(f"You won ::{a} vs {value}")
cu+=1
c=c-1
print("Chance left",c)
elif value == "water":
print(f"You Lost ::{a} vs {value}")
cp+=1
c=c-1
print("Chance left",c)
elif a=="gun":
if a == value:
print(f"Match is draw::{a} vs {value} ")
c=c-1
print("Chance left",c)
elif value == "water":
print(f"You won ::{a} vs {value}")
cu+=1
c=c-1
print("Chance left",c)
elif value == "snake":
print(f"You Lost ::{a} vs {value}")
cp+=1
c=c-1
print("Chance left",c)
if(cu>cp):
print(f"\c{name} is the Winner Your score:\t".upper(),cu)
elif(cu==cp):
print("\nmatch is tie:\t".upper(),cp,cu)
elif:
print("\nSorry Computer is a winner Computer score:\t".upper(),cp)
|
import sys
import time
# import numpy as np
import pandas as pd
# import datetime as dt
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
months = ['all', 'january', 'february', 'march', 'april', 'may', 'june']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no
month filter
(str) day - name of the day of week to filter by, or "all" to apply no
day filter
"""
print('\nHello! Let\'s explore some US bikeshare data!\n')
# get user input for city (chicago, new york city, washington).
# HINT: Use a while loop to handle invalid inputs
city = ''
month = ''
day = ''
filter = ''
while city not in CITY_DATA.keys():
city = input("Would you like to see data for Chicago, "
"New York City, or Washington?\n")
city = city.lower()
while filter not in ['month', 'day', 'both', 'all']:
filter = input("\nWould you like to filter by 'month', 'day', "
"'both' or use 'all' the data?\n")
filter = filter.lower()
if (filter == 'month') or (filter == 'both'):
# get user input for month (all, january, february, ... , june)
while month not in months:
month = input("\nEnter a month to analyze "
"('all' or 'January' through 'June'):\n")
month = month.lower()
if (filter == 'day') or (filter == 'both'):
# get user input for day of week (all, monday, tuesday, ... sunday)
days_of_week = ['all', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday', 'sunday']
while day not in days_of_week:
day = input("\nEnter a day of the week to analyze "
"('all' or 'Monday', 'Tuesday', ... 'Sunday'):\n")
day = day.lower()
print()
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and applies filters as needed
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no
month filter
(str) day - name of the day of week to filter by, or "all" to apply no
day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
# Save unfiltered dataframe for possible use at the end of this routine.
df_raw = df
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# convert the End Time column to datetime
df['End Time'] = pd.to_datetime(df['End Time'])
# convert Trip Duration to a timedelta
df['Trip Duration'] = pd.to_timedelta(df['Trip Duration'], unit='s')
# extract month and weekday name from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day of week'] = df['Start Time'].dt.weekday_name
# filter by month if applicable
if (month != 'all') and (month != ''):
# use the index of the months list to get the corresponding int
# Note: months is defined as shown below.
# months = ['all', 'january', 'february', 'march',
# 'april', 'may', 'june']
month = months.index(month)
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if (day != 'all') and (day != ''):
# filter by day of week to create the new dataframe
df = df[df['day of week'] == day.title()]
# Create a new column in df named 'hour'
df['hour'] = df['Start Time'].dt.hour
# Create a new column in df named 'trip'
# Location where bikes were rented and then returned
df['trip'] = df['Start Station'].str.cat(df['End Station'], sep=' to ')
data_type = ''
if((len(df.index) - 1) > 0):
while data_type.lower() not in ['raw', 'filtered', 'no']:
print("Would you like to page through the 'raw' "
"or 'filtered' data?")
data_type = input("Enter 'no' to skip viewing the data.\n")
if data_type.lower() == 'raw':
print_data(df_raw, data_type, 'yes')
elif data_type.lower() == 'filtered':
print_data(df, data_type, 'yes')
elif data_type.lower() == 'no':
break
else:
print("Please enter 'raw', 'filtered', or 'no'.")
print('-'*40)
return df
def print_data(df, data_type, reply):
"""
Print the raw or filtered data to the screen, N rows at a time
Args:
(pdf) df - pandas DataFrame of 'raw' or 'filtered' data
(str) data_type - either 'raw' or 'filtered' data
(str) reply - initial value of reply (always 'yes')
"""
# Determine output type (json or columns)
while True:
output_style = input("\nWould you like to see the output in line "
"delimited json format?\n")
if output_style.lower()[0] == 'y':
json = True
break
elif output_style.lower()[0] == 'n':
json = False
break
else:
print("Please enter 'yes' or 'no'\n")
print()
# Determine start, stop and step values
start = 0
while True:
try:
step = (int(input("Enter number of rows to view at a time? "
"Default is 5 rows.\n")) or 5)
except ValueError:
print("Please enter an integer value.")
else:
print("Printing {} lines at a time.".format(step))
break
stop = len(df.index)
if step > stop:
step = stop
print("Step size lowered to {} rows.".format(stop))
# Print out 'raw' or 'filtered' data
while (reply.lower()[0] == 'y'):
end = min((start + step), stop)
if not json:
print(df.iloc[start:end])
else:
print(df.iloc[start:end].to_json(orient='records',
lines=True,
date_format='iso'))
print()
if end == stop:
break
reply = (input("Would you like to see more of the {} data? Enter "
"'yes' or 'no'. ".format(data_type.lower())) or 'yes')
start += step # Increment start by step count
print()
print("\nFinished\n")
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# Create a new column in df named 'hour'
# df['hour'] = df['Start Time'].dt.hour
# display the most common month
month = df['month'].mode()[0] # Get index of month
count = df.loc[df['month'] == month].count()[0]
month = months[month] # Get name of month from months list & index
print_travel('month', month.title(), count)
# display the most common day of week
weekday = df['day of week'].mode()[0]
count = df.loc[df['day of week'] == weekday].count()[0]
print_travel('day of week', weekday.title(), count)
# display the most common start hour
start_hour = df['hour'].mode()[0]
count = df.loc[df['hour'] == start_hour].count()[0]
if start_hour <= 12:
start_hour = str(start_hour) + ':00 AM'
else:
start_hour = str(start_hour - 12) + ':00 PM'
print_travel('start hour', start_hour, count)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def print_travel(travel_time, actual_dt, count):
"""
Print most common travel_time used with count riders
Args:
(str) travel_time - String of 'month', 'day of week', or 'start hour'
(str) actual_dt - actual month, day of week, or start hour
(int) count - number of users for given travel time
"""
print("Most common {} is {} with {} users."
.format(travel_time, actual_dt, count))
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
print_station(df, 'Start Station')
# display most commonly used end station
print_station(df, 'End Station')
# display most frequent combination of start station and end station
# df['trip'] = df['Start Station'].str.cat(df['End Station'], sep=' to ')
# Moved previous line into load_data module
trip = df['trip'].mode()[0]
count = df.loc[df['trip'] == trip].count()[0]
print("Most common trip is {} with {} users.".format(trip, count))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def print_station(df, station):
"""
Print most commonly used start and end stations
Args:
(df) df - pandas DataFrame
(str) station - String used to pick start or end location
"""
station_location = df[station].mode()[0]
count = df.loc[df[station] == station_location].count()[0]
print("Most commonly used {} is {} with {} users."
.format(station.lower(), station_location, count))
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time in the given city.
total_time = df['Trip Duration'].sum()
total_message = 'total time of all the trips was'
print_trips(total_time, total_message)
# display mean travel time
mean_time = df['Trip Duration'].mean()
print_trips(mean_time, 'mean trip took')
# display longest and shortest trips
longest_trip = df['Trip Duration'].max()
shortest_trip = df['Trip Duration'].min()
print_trips(longest_trip, 'longest trip took')
print_trips(shortest_trip, 'shortest trip took')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def print_trips(trip_duration, length_description):
"""
Determine trip_duration and print out results
Args:
(td) trip_duration - timedelta object - df['Trip Duration']
(str) length_description - String required to descripe trip duration
"""
days, hours, minutes, seconds, ms, us, ns = trip_duration.components
if days == 0:
print("The {} {:02}:{:02}:{:02}"
.format(length_description, hours, minutes, seconds))
else:
print("The {} {} days {:02}:{:02}:{:02}"
.format(length_description, days, hours, minutes, seconds))
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
customers = df.loc[df['User Type'] == 'Customer'].count()[0]
subscribers = df.loc[df['User Type'] == 'Subscriber'].count()[0]
dependents = df.loc[df['User Type'] == 'Dependent'].count()[0]
unknown = df.loc[df['User Type'].isnull()].count()[0]
print("There are {} customers.".format(customers))
print("There are {} subscribers.".format(subscribers))
print("There are {} dependents.".format(dependents))
print("There are {} unspecified type (NaN values).\n".format(unknown))
# Display counts of gender
if 'Gender' in df:
number_of_males = df.loc[df['Gender'] == 'Male'].count()[0]
number_of_females = df.loc[df['Gender'] == 'Female'].count()[0]
unknown = df.loc[df['Gender'].isnull()].count()[0]
print("Number of male riders is {}.".format(number_of_males))
print("Number of female riders is {}.".format(number_of_females))
print("Number of users of unspecified gender is {}.".format(unknown))
else:
print("Gender is not in dataset.")
print()
# Display earliest, most recent, and most common year of birth
if 'Birth Year' in df:
earliest = df['Birth Year'].min()
most_recent = df['Birth Year'].max()
most_common = df['Birth Year'].mode()[0]
print("Earliest year of birth is {}.".format(int(earliest)))
print("Most recent year of birth is {}.".format(int(most_recent)))
print("Most common year of birth is {}.".format(int(most_common)))
else:
print("Birth Year is not in dataset.")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
"""Usage: python bikeshare.py"""
if sys.version_info < (3, 5, 0):
sys.stderr.write("You need to use Python version 3.5.0 or higher "
+ "to run this script\n")
sys.exit(1)
start_time = time.time()
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
if(len(df) > 0):
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
else:
print("No data in the dataframe! How did we get here?")
restart = input("\nWould you like to restart? Enter 'yes' or 'no'.\n")
if restart.lower() != 'yes':
break
print("\nProgram took {} seconds".format(time.time() - start_time))
print('-'*40)
if __name__ == "__main__":
main()
|
import requests
S = requests.Session()
URL = "https://en.wikipedia.org/w/api.php"
#Function to serach for the most similar page title to the keyword
def page_title(target):
PARAMS = {
"action": "opensearch", #Which action to perform.(Search the wiki using the OpenSearch protocol.)
"search": target, #Search string.
"limit": "1", #Maximum number of results to return.
"format": "json" #The format of the output.
}
r = S.get(url=URL, params=PARAMS)
data = r.json()
keyword = data[1][0]
keyword = keyword.replace(" ","_")
return keyword
#Function to scrape for information using the page title provided by the page_title function
def scrape(target):
keyword = page_title(target)
PARAMS = {
"action": "query", #Which action to perform.(Fetch data from and about MediaWiki.)
"prop": "extracts", #Which properties to get for the queried pages.(Returns plain-text or limited HTML extracts of the given pages.)
"exsentences": "10", #How many sentences to return.
"exlimit": "1", #How many extracts to return.
"titles": keyword, #A list of titles to work on.
"formatversion": "2", #Output formatting(Modern format)
"format": "json", #The format of the output.
"explaintext": "1" #Return extracts as plain text instead of limited HTML.
}
r = S.get(url=URL, params=PARAMS)
data = r.json()
content = data['query']['pages'][0]['extract']
return content |
# -*- coding: utf-8 -*-
"""
remarks: commonly used functions related to intervals
NOTE
----
`Interval` refers to interval of the form [a,b]
`GeneralizedInterval` refers to some (finite) union of `Interval`s
TODO:
1. unify `Interval` and `GeneralizedInterval`, by letting `Interval` be of the form [[a,b]]
2. distinguish openness and closedness
"""
import time
from copy import deepcopy
from functools import reduce
from numbers import Real
from typing import Union, Optional, Any, List, Tuple, Sequence
import numpy as np
np.set_printoptions(precision=5, suppress=True)
from ..common import ArrayLike
__all__ = [
"get_optimal_covering",
"overlaps",
"validate_interval",
"in_interval",
"in_generalized_interval",
"get_confidence_interval",
"intervals_union",
"generalized_intervals_union",
"intervals_intersection",
"generalized_intervals_intersection",
"generalized_interval_complement",
"find_max_cont_len",
"interval_len",
"generalized_interval_len",
"diff_with_step",
"find_extrema",
"is_intersect",
"max_disjoint_covering",
"mask_to_intervals",
]
EMPTY_SET = []
Interval = Union[Sequence[Real], type(EMPTY_SET)]
GeneralizedInterval = Union[Sequence[Interval], type(EMPTY_SET)]
def overlaps(interval:Interval, another:Interval) -> int:
""" finished, checked,
Return the amount of overlap, in bp between interval and anohter.
If >0, the number of bp of overlap
If 0, they are book-ended
If <0, the distance in bp between them
Parameters
----------
interval, another: two `Interval`s
Returns
-------
int, overlap length of two intervals; if < 0, the distance of two intervals
"""
# in case a or b is not in ascending order
interval.sort()
another.sort()
return min(interval[-1], another[-1]) - max(interval[0], another[0])
def validate_interval(
interval:Union[Interval, GeneralizedInterval],
join_book_endeds:bool=True
) -> Tuple[bool,Union[Interval, GeneralizedInterval]]:
""" finished, not checked,
check whether `interval` is an `Interval` or a `GeneralizedInterval`,
if true, return True, and validated (of the form [a,b] with a<=b) interval,
return `False, []`, otherwise
Parameters
----------
interval: Interval, or unions of `Interval`s
join_book_endeds: bool, default True,
if True, two book-ended intervals will be joined into one
Returns
-------
tuple, consisting of
a bool, indicating whether `interval` is a valid interval
an interval (can be empty)
"""
if isinstance(interval[0], (list,tuple)):
info = [validate_interval(itv,join_book_endeds) for itv in interval]
if all([item[0] for item in info]):
return True, intervals_union(interval,join_book_endeds)
else:
return False, []
if len(interval) == 2:
return True, [min(interval), max(interval)]
else:
return False, []
def in_interval(val:Real, interval:Interval, left_closed:bool=True, right_closed:bool=False) -> bool:
""" finished, checked,
check whether val is inside interval or not
Parameters
----------
val: real number,
interval: Interval,
left_closed: bool, default True,
right_closed: bool, default False,
Returns
-------
is_in: bool,
"""
itv = sorted(interval)
if left_closed:
is_in = (itv[0] <= val)
else:
is_in = (itv[0] < val)
if right_closed:
is_in = is_in and (val <= itv[-1])
else:
is_in = is_in and (val < itv[-1])
return is_in
def in_generalized_interval(
val:Real,
generalized_interval:GeneralizedInterval,
left_closed:bool=True,
right_closed:bool=False
) -> bool:
""" finished, checked,
check whether val is inside generalized_interval or not
Parameters
----------
val: real number,
generalized_interval: union of `Interval`s,
left_closed: bool, default True,
right_closed: bool, default False,
Returns
-------
is_in: bool,
"""
is_in = False
for interval in generalized_interval:
if in_interval(val, interval, left_closed, right_closed):
is_in = True
break
return is_in
def get_confidence_interval(
data:Optional[ArrayLike]=None,
val:Optional[Real]=None,
rmse:Optional[float]=None,
confidence:float=0.95,
**kwargs:Any
) -> np.ndarray:
""" finished, checked,
Parameters
----------
data: array_like, optional,
val: real number, optional,
rmse: float, optional,
confidence: float, default 0.95,
kwargs: dict,
Returns
-------
conf_itv: ndarray,
"""
from scipy.stats import norm
assert data or (val and rmse), "insufficient data for computing"
correct_factor = kwargs.get("correct_factor", 1)
bias = norm.ppf(0.5 + confidence / 2)
if data is None:
lower_bound = (val - rmse * bias) * correct_factor
upper_bound = (val + rmse * bias) / correct_factor
else:
average = np.mean(np.array(data))
std = np.std(np.array(data), ddof=1)
lower_bound = (average - std * bias) * correct_factor
upper_bound = (average + std * bias) / correct_factor
conf_itv = np.array([lower_bound, upper_bound])
return conf_itv
def intervals_union(interval_list:GeneralizedInterval, join_book_endeds:bool=True) -> GeneralizedInterval:
""" finished, checked,
find the union (ordered and non-intersecting) of all the intervals in `interval_list`,
which is a list of intervals in the form [a,b], where a,b need not be ordered
Parameters
----------
interval_list: GeneralizedInterval,
the list of intervals to calculate their union
join_book_endeds: bool, default True,
join the book-ended intervals into one (e.g. [[1,2],[2,3]] into [1,3]) or not
Returns
-------
processed: GeneralizedInterval,
the union of the intervals in `interval_list`
"""
interval_sort_key = lambda i: i[0]
# list_add = lambda list1, list2: list1+list2
processed = [item for item in interval_list if len(item) > 0]
for item in processed:
item.sort()
processed.sort(key=interval_sort_key)
# end_points = reduce(list_add, processed)
merge_flag = True
while merge_flag:
merge_flag = False
new_intervals = []
if len(processed) == 1:
return processed
for idx, interval in enumerate(processed[:-1]):
this_start, this_end = interval
next_start, next_end = processed[idx + 1]
# it is certain that this_start <= next_start
if this_end < next_start:
# the case where two consecutive intervals are disjoint
new_intervals.append([this_start, this_end])
if idx == len(processed) - 2:
new_intervals.append([next_start, next_end])
elif this_end == next_start:
# the case where two consecutive intervals are book-ended
# concatenate if `join_book_endeds` is True,
# or one interval degenerates (to a single point)
if (this_start == this_end or next_start == next_end) or join_book_endeds:
new_intervals.append([this_start, max(this_end, next_end)])
new_intervals += processed[idx + 2:]
merge_flag = True
processed = new_intervals
break
else:
new_intervals.append([this_start, this_end])
if idx == len(processed) - 2:
new_intervals.append([next_start, next_end])
else:
new_intervals.append([this_start, max(this_end, next_end)])
new_intervals += processed[idx + 2:]
merge_flag = True
processed = new_intervals
break
processed = new_intervals
return processed
def generalized_intervals_union(
interval_list:Union[List[GeneralizedInterval],Tuple[GeneralizedInterval]],
join_book_endeds:bool=True
) -> GeneralizedInterval:
""" finished, checked,
calculate the union of a list (or tuple) of `GeneralizedInterval`s
Parameters
----------
interval_list: list or tuple,
a list (or tuple) of `GeneralizedInterval`s
join_book_endeds: bool, default True,
join the book-ended intervals into one (e.g. [[1,2],[2,3]] into [1,3]) or not
Returns
-------
iu: GeneralizedInterval,
the union of `interval_list`
"""
all_intervals = [itv for gnr_itv in interval_list for itv in gnr_itv]
iu = intervals_union(interval_list=all_intervals, join_book_endeds=join_book_endeds)
return iu
def intervals_intersection(interval_list:GeneralizedInterval, drop_degenerate:bool=True) -> Interval:
""" finished, checked,
calculate the intersection of all intervals in interval_list
Parameters
----------
interval_list: GeneralizedInterval,
the list of intervals to yield intersection
drop_degenerate: bool, default True,
whether or not drop the degenerate intervals, i.e. intervals with length 0
Returns
-------
its: Interval,
the intersection of all intervals in `interval_list`
"""
if [] in interval_list:
return []
for item in interval_list:
item.sort()
potential_start = max([item[0] for item in interval_list])
potential_end = min([item[-1] for item in interval_list])
if (potential_end > potential_start) or (potential_end == potential_start and not drop_degenerate):
its = [potential_start, potential_end]
else:
its = []
return its
def generalized_intervals_intersection(
generalized_interval:GeneralizedInterval,
another_generalized_interval:GeneralizedInterval,
drop_degenerate:bool=True
) -> GeneralizedInterval:
""" finished, checked,
calculate the intersection of generalized_interval and another_generalized_interval,
which are both generalized intervals
Parameters
----------
generalized_interval, another_generalized_interval: GeneralizedInterval,
the 2 `GeneralizedInterval`s to yield intersection
drop_degenerate: bool, default True,
whether or not drop the degenerate intervals, i.e. intervals with length 0
Returns
-------
its: GeneralizedInterval,
the intersection of `generalized_interval` and `another_generalized_interval`
"""
this = intervals_union(generalized_interval)
another = intervals_union(another_generalized_interval)
# NOTE: from now on, `this`, `another` are in ascending ordering
# and are disjoint unions of intervals
its = []
# TODO: optimize the following process
cut_idx = 0
for item in this:
another = another[cut_idx:]
intersected_indices = []
for idx, item_prime in enumerate(another):
tmp = intervals_intersection([item,item_prime], drop_degenerate=drop_degenerate)
if len(tmp) > 0:
its.append(tmp)
intersected_indices.append(idx)
if len(intersected_indices) > 0:
cut_idx = intersected_indices[-1]
return its
def generalized_interval_complement(
total_interval:Interval,
generalized_interval:GeneralizedInterval
) -> GeneralizedInterval:
""" finished, checked, to be improved,
TODO: the case `total_interval` is a `GeneralizedInterval`
Parameters
----------
total_interval, Interval,
generalized_interval: union of `Interval`s
Returns
-------
cpl: union of `Interval`s,
the complement of `generalized_interval` in `total_interval`
"""
rearranged_intervals = intervals_union(generalized_interval)
total_interval.sort()
tot_start, tot_end = total_interval[0], total_interval[-1]
rearranged_intervals = [
[max(tot_start, item[0]), min(tot_end, item[-1])] \
for item in rearranged_intervals if overlaps(item, total_interval) > 0
]
slice_points = [tot_start]
for item in rearranged_intervals:
slice_points += item
slice_points.append(tot_end)
cpl = []
for i in range(len(slice_points) // 2):
if slice_points[2 * i + 1] - slice_points[2 * i] > 0:
cpl.append([slice_points[2 * i], slice_points[2 * i + 1]])
return cpl
def get_optimal_covering(
total_interval:Interval,
to_cover:list,
min_len:Real,
split_threshold:Real,
traceback:bool=False,
**kwargs:Any
) -> Tuple[GeneralizedInterval,list]:
""" finished, checked,
compute an optimal covering (disjoint union of intervals) that covers `to_cover` such that
each interval in the covering is of length at least `min_len`,
and any two intervals in the covering have distance at least `split_threshold`
Parameters
----------
total_interval: Interval,
the total interval that the covering is picked from
to_cover: list,
a list of intervals to cover
min_len: real number,
minimun length of the intervals of the covering
split_threshold: real number,
minumun distance of intervals of the covering
traceback: bool, default False,
if True, a list containing the list of indices of the intervals in the original `to_cover`,
that each interval in the covering covers
Raises
------
if any of the intervals in `to_cover` exceeds the range of `total_interval`,
ValueError will be raised
Returns
-------
(ret, ret_traceback)
ret: GeneralizedInterval,
the covering that satisfies the given conditions
ret_traceback: list,
contains the list of indices of the intervals in the original `to_cover`,
that each interval in the covering covers
"""
start_time = time.time()
verbose = kwargs.get("verbose", 0)
tmp = sorted(total_interval)
tot_start, tot_end = tmp[0], tmp[-1]
if verbose >= 1:
print(f"total_interval = {total_interval}, with_length = {tot_end-tot_start}")
if tot_end - tot_start < min_len:
ret = [[tot_start, tot_end]]
ret_traceback = [list(range(len(to_cover)))] if traceback else []
return ret, ret_traceback
to_cover_intervals = []
for item in to_cover:
if isinstance(item, list):
to_cover_intervals.append(item)
else:
to_cover_intervals.append(
[max(tot_start, item-min_len//2), min(tot_end, item+min_len//2)]
)
if traceback:
replica_for_traceback = deepcopy(to_cover_intervals)
if verbose >= 2:
print(f"to_cover_intervals after all converted to intervals = {to_cover_intervals}")
# elif isinstance(item, int):
# to_cover_intervals.append([item, item+1])
# else:
# raise ValueError(f"{item} is not an integer or an interval")
# to_cover_intervals = interval_union(to_cover_intervals)
for interval in to_cover_intervals:
interval.sort()
interval_sort_key = lambda i: i[0]
to_cover_intervals.sort(key=interval_sort_key)
if verbose >= 2:
print(f"to_cover_intervals after sorted = {to_cover_intervals}")
# if to_cover_intervals[0][0] < tot_start or to_cover_intervals[-1][-1] > tot_end:
# raise IndexError("some item in to_cover list exceeds the range of total_interval")
# these cases now seen normal, and treated as follows:
for item in to_cover_intervals:
item[0] = max(item[0], tot_start)
item[-1] = min(item[-1], tot_end)
# to_cover_intervals = [item for item in to_cover_intervals if item[-1] > item[0]]
# ensure that the distance from the first interval to `tot_start` is at least `min_len`
to_cover_intervals[0][-1] = max(to_cover_intervals[0][-1], tot_start + min_len)
# ensure that the distance from the last interval to `tot_end` is at least `min_len`
to_cover_intervals[-1][0] = min(to_cover_intervals[-1][0], tot_end - min_len)
if verbose >= 2:
print(f"`to_cover_intervals` after two tails adjusted to {to_cover_intervals}")
# merge intervals whose distances (might be negative) are less than `split_threshold`
merge_flag = True
while merge_flag:
merge_flag = False
new_intervals = []
if len(to_cover_intervals) == 1:
break
for idx, item in enumerate(to_cover_intervals[:-1]):
this_start, this_end = item
next_start, next_end = to_cover_intervals[idx + 1]
if next_start - this_end >= split_threshold:
if split_threshold == (next_start - next_end) == 0 or split_threshold == (this_start - this_end) == 0:
# the case where split_threshold ==0 and the degenerate case should be dealth with separately
new_intervals.append([this_start, max(this_end, next_end)])
new_intervals += to_cover_intervals[idx + 2:]
merge_flag = True
to_cover_intervals = new_intervals
break
else:
new_intervals.append([this_start, this_end])
if idx == len(to_cover_intervals) - 2:
new_intervals.append([next_start, next_end])
else:
new_intervals.append([this_start, max(this_end, next_end)])
new_intervals += to_cover_intervals[idx + 2:]
merge_flag = True
to_cover_intervals = new_intervals
break
if verbose >= 2:
print(f"`to_cover_intervals` after merging intervals whose gaps < split_threshold are {to_cover_intervals}")
# currently, distance between any two intervals in `to_cover_intervals` are larger than `split_threshold`
# but any interval except the head and tail might has length less than `min_len`
ret = []
ret_traceback = []
if len(to_cover_intervals) == 1:
# NOTE: here, there's only one `to_cover_intervals`,
# whose length should be at least `min_len`
mid_pt = (to_cover_intervals[0][0]+to_cover_intervals[0][-1]) // 2
half_len = min_len // 2
if mid_pt - tot_start < half_len:
ret_start = tot_start
ret_end = min(tot_end, max(tot_start+min_len, to_cover_intervals[0][-1]))
ret = [[ret_start, ret_end]]
else:
ret_start = max(tot_start, min(to_cover_intervals[0][0], mid_pt-half_len))
ret_end = min(tot_end, max(mid_pt-half_len+min_len, to_cover_intervals[0][-1]))
ret = [[ret_start, ret_end]]
start = min(to_cover_intervals[0][0], to_cover_intervals[0][-1]-min_len)
for idx, item in enumerate(to_cover_intervals[:-1]):
# print("item", item)
this_start, this_end = item
next_start, next_end = to_cover_intervals[idx + 1]
potential_end = max(this_end, start + min_len)
# print(f"start = {start}")
# print("potential_end", potential_end)
# if distance from `potential_end` to `next_start` is not enough
# and has not reached the end of `to_cover_intervals`
# continue to the next loop
if next_start - potential_end < split_threshold:
if idx < len(to_cover_intervals) - 2:
continue
else:
# now, idx==len(to_cover_intervals)-2
# distance from `next_start` (hence `start`) to `tot_end` is at least `min_len`
ret.append([start, max(start + min_len, next_end)])
else:
ret.append([start, potential_end])
start = next_start
if idx == len(to_cover_intervals) - 2:
ret.append([next_start, max(next_start + min_len, next_end)])
# print(f"ret = {ret}")
if traceback:
for item in ret:
record = []
for idx, item_prime in enumerate(replica_for_traceback):
itc = intervals_intersection([item, item_prime])
len_itc = itc[-1] - itc[0] if len(itc) > 0 else -1
if len_itc > 0 or (len_itc == 0 and item_prime[-1] - item_prime[0] == 0):
record.append(idx)
ret_traceback.append(record)
if verbose >= 1:
print(f"the final result of get_optimal_covering is ret = {ret}, ret_traceback = {ret_traceback}, the whole process used {time.time()-start_time} second(s)")
return ret, ret_traceback
def find_max_cont_len(sublist:Interval, tot_rng:Real) -> dict:
""" finished, checked,
find the maximum length of continuous (consecutive) sublists of `sublist`,
whose element are integers within the range from 0 to `tot_rng`,
along with the position of this sublist and the sublist itself.
eg, tot_rng=10, sublist=[0,2,3,4,7,9],
then 3, 1, [2,3,4] will be returned
Parameters
----------
sublist: Interval,
a sublist
tot_rng: real number,
the total range
Returns
-------
ret: dict, with items
- "max_cont_len"
- "max_cont_sublist_start"
- "max_cont_sublist"
"""
complementary_sublist = [-1] + [i for i in range(tot_rng) if i not in sublist] + [tot_rng]
diff_list = np.diff(np.array(complementary_sublist))
max_cont_len = np.max(diff_list) - 1
max_cont_sublist_start = np.argmax(diff_list)
max_cont_sublist = sublist[max_cont_sublist_start: max_cont_sublist_start + max_cont_len]
ret = {
"max_cont_len": max_cont_len,
"max_cont_sublist_start": max_cont_sublist_start,
"max_cont_sublist": max_cont_sublist
}
return ret
def interval_len(interval:Interval) -> Real:
""" finished, checked,
compute the length of an interval. 0 for the empty interval []
Parameters
----------
interval: Interval
Returns
-------
itv_len: real number,
the `length` of `interval`
"""
interval.sort()
itv_len = interval[-1] - interval[0] if len(interval) > 0 else 0
return itv_len
def generalized_interval_len(generalized_interval:GeneralizedInterval) -> Real:
""" finished, checked,
compute the length of a generalized interval. 0 for the empty interval []
Parameters
----------
generalized_interval: GeneralizedInterval
Returns
-------
gi_len: real number,
the `length` of `generalized_interval`
"""
gi_len = sum([interval_len(item) for item in intervals_union(generalized_interval)])
return gi_len
def diff_with_step(a:ArrayLike, step:int=1, **kwargs) -> np.ndarray:
""" finished, checked,
compute a[n+step] - a[n] for all valid n
Parameters
----------
a: array_like,
the input data
step: int, default 1,
the step to compute the difference
kwargs: dict,
Returns
-------
d: ndarray:
the difference array
"""
_a = np.array(a)
if step >= len(_a):
raise ValueError(f"step ({step}) should be less than the length ({len(_a)}) of `a`")
d = _a[step:] - _a[:-step]
return d
def find_extrema(signal:Optional[ArrayLike]=None, mode:str="both") -> np.ndarray:
"""
Locate local extrema points in a signal. Based on Fermat's Theorem
Parameters
----------
signal: ndarray
input signal.
mode: str, optional
whether to find maxima ("max"), minima ("min"), or both ("both").
Returns
-------
extrema : ndarray
indices of the extrama points.
"""
# check inputs
if signal is None:
raise TypeError("Please specify an input signal.")
if mode not in ["max", "min", "both"]:
raise ValueError("Unknwon mode %r." % mode)
aux = np.diff(np.sign(np.diff(signal)))
if mode == "both":
aux = np.abs(aux)
extrema = np.nonzero(aux > 0)[0] + 1
elif mode == "max":
extrema = np.nonzero(aux < 0)[0] + 1
elif mode == "min":
extrema = np.nonzero(aux > 0)[0] + 1
return extrema
def is_intersect(
interval:Union[GeneralizedInterval,Interval],
another_interval:Union[GeneralizedInterval,Interval]
) -> bool:
"""
determines if two (generalized) intervals intersect or not
Parameters
----------
interval, another_interval: GeneralizedInterval or Interval
Returns
-------
bool, True if `interval` intersects with another_interval, False otherwise
"""
if interval is None or another_interval is None or len(interval)*len(another_interval)==0:
# the case of empty set
return False
# check if is GeneralizedInterval
is_generalized = isinstance(interval[0], (list,tuple))
is_another_generalized = isinstance(another_interval[0], (list,tuple))
if is_generalized and is_another_generalized:
return any([is_intersect(interval, itv) for itv in another_interval])
elif not is_generalized and is_another_generalized:
return is_intersect(another_interval, interval)
elif is_generalized: # and not is_another_generalized
return any([is_intersect(itv, another_interval) for itv in interval])
else: # not is_generalized and not is_another_generalized
return any([overlaps(interval, another_interval)>0])
def max_disjoint_covering(
intervals:GeneralizedInterval,
allow_book_endeds:bool=True,
with_traceback:bool=True,
verbose:int=0
) -> Tuple[GeneralizedInterval, List[int]]:
""" finished, checked,
find the largest (the largest interval length) covering of a sequence of intervals
NOTE
----
1. the problem seems slightly different from the problem discussed in refs
2. intervals with non-positive length will be ignored
Parameters
----------
intervals: GeneralizedInterval,
a sequence of intervals
allow_book_endeds: bool, default True,
if True, book-ended intervals will be considered valid (disjoint)
with_traceback: bool, default True,
if True, the indices of the intervals in the input `intervals` of the output covering
will also be returned
Returns
-------
covering: GeneralizedInterval,
the maximum non-overlapping (disjoint) subset of `intervals`
covering_inds: list of int,
indices in `intervals` of the intervals of `covering_inds`
References
----------
[1] https://en.wikipedia.org/wiki/Maximum_disjoint_set
[2] https://www.geeksforgeeks.org/maximal-disjoint-intervals/
"""
if len(intervals) <= 1:
covering = deepcopy(intervals)
return covering, list(range(len(covering)))
l_itv = [sorted(itv) for itv in intervals]
ordering = np.argsort([itv[-1] for itv in l_itv])
l_itv = [l_itv[idx] for idx in ordering]
# l_itv = sorted(l_itv, key=lambda itv: itv[-1])
if verbose >= 1:
print(f"the sorted intervals are {l_itv}, whose indices in the original input `intervals` are {ordering}")
if allow_book_endeds:
candidates_inds = [[idx] for idx,itv in enumerate(l_itv) if overlaps(itv, l_itv[0]) > 0]
else:
candidates_inds = [[idx] for idx,itv in enumerate(l_itv) if overlaps(itv, l_itv[0]) >= 0]
candidates = [[l_itv[inds[0]]] for inds in candidates_inds]
if verbose >= 1:
print(f"candidates heads = {candidates}, with corresponding indices in the sorted list of input intervals = {candidates_inds}")
for c_idx, (cl, ci) in enumerate(zip(candidates, candidates_inds)):
if interval_len(cl[0]) == 0:
continue
if allow_book_endeds:
tmp_inds = [
idx for idx,itv in enumerate(l_itv) if itv[0] >= cl[0][-1] and interval_len(itv) > 0
]
else:
tmp_inds = [
idx for idx,itv in enumerate(l_itv) if itv[0] > cl[0][-1] and interval_len(itv) > 0
]
if verbose >= 2:
print(f"for the {c_idx}-th candidate, tmp_inds = {tmp_inds}")
if len(tmp_inds) > 0:
tmp = [l_itv[idx] for idx in tmp_inds]
tmp_candidates, tmp_candidates_inds = \
max_disjoint_covering(
intervals=tmp,
allow_book_endeds=allow_book_endeds,
with_traceback=with_traceback,
# verbose=verbose,
)
candidates[c_idx] = cl + tmp_candidates
candidates_inds[c_idx] = ci + [tmp_inds[i] for i in tmp_candidates_inds]
if verbose >= 1:
print(f"the processed candidates are {candidates}, with corresponding indices in the sorted list of input intervals = {candidates_inds}")
# covering = max(candidates, key=generalized_interval_len)
max_idx = np.argmax([generalized_interval_len(c) for c in candidates])
covering = candidates[max_idx]
if with_traceback:
covering_inds = candidates_inds[max_idx]
covering_inds = [ordering[i] for i in covering_inds] # map to the original indices
else:
covering_inds = []
return covering, covering_inds
def mask_to_intervals(mask:np.ndarray, vals:Optional[Union[int,Sequence[int]]]=None) -> Union[list, dict]:
""" finished, checked,
Parameters
----------
mask: ndarray,
1d mask
vals: int or sequence of int, optional,
values in `mask` to obtain intervals
Returns
-------
intervals: dict or list,
the intervals corr. to each value in `vals` if `vals` is `None` or `Sequence`;
or the intervals corr. to `vals` if `vals` is int.
each interval is of the form `[a,b]`, left inclusive, right exclusive
"""
if vals is None:
_vals = list(set(mask))
elif isinstance(vals, int):
_vals = [vals]
else:
_vals = vals
# assert set(_vals) & set(mask) == set(_vals)
intervals = {v:[] for v in _vals}
for v in _vals:
valid_inds = np.where(np.array(mask)==v)[0]
if len(valid_inds) == 0:
continue
split_indices = np.where(np.diff(valid_inds)>1)[0]
split_indices = split_indices.tolist() + (split_indices+1).tolist()
split_indices = sorted([0] + split_indices + [len(valid_inds)-1])
for idx in range(len(split_indices)//2):
intervals[v].append(
[valid_inds[split_indices[2*idx]], valid_inds[split_indices[2*idx+1]]+1]
)
if isinstance(vals, int):
intervals = intervals[vals]
return intervals
|
# from __future__ import print_function
import collections #Deque. This is a higher performance version of a list. Faster when accessing first / last elements.
# ------------------------------------------------------------------------------------------------------------------------------------------------------
# Code was re-used from the util.py file
"""
Container with LIFO policy. First element that enters will be the last one that leaves.
"""
class Stack:
def __init__(self):
self.deque = collections.deque() #5,7 sec avg of 3 runs
#Add new item:
def push(self,item):
self.deque.append(item)
#Remove the item that was most recently pushed to the stack.
def pop(self):
return self.deque.pop()
#Is the queue empty?
def isEmpty(self):
return len(self.deque) == 0
# ------------------------------------------------------------------------------------------------------------------------------------------------------
# Code was re-used from the util.py file
"""
Container with FIFO policy. The first element in will also be the first element out.
"""
class Queue:
def __init__(self):
self.deque = collections.deque()
#Add new item:
def push(self,item):
self.deque.appendleft(item)
#Remove the oldest item in the Queue
def pop(self):
return self.deque.pop()
#Is the queue empty?
def isEmpty(self):
return len(self.deque) == 0
# ------------------------------------------------------------------------------------------------------------------------------------------------------
"""
Container for storing X,Y and cost
"""
class Location:
def __init__(self,x,y,param):
self.x=x
self.y=y
self.param=param
# self.deque = collections.deque()
def getx(self):
return self.x
def gety(self):
return self.y
def getParam(self):
return self.param
def setx(self,x):
self.x=x
def sety(self,y):
self.y=y
def setParam(self,param):
self.param=param
def printLoc(self):
print(self.getLocStr())
def getLocStr(self):
x = str(self.x)
y = str(self.y)
param = str(self.param)
fullStr = x +","+ y +","+ param
return fullStr
# ------------------------------------------------------------------------------------------------------------------------------------------------------
def main():
# aContainer = Queue() #123
aContainer = Stack() #321
for i in range(0,3):
xCoord = 10
yCoord = 10
aLoc = Location(xCoord,yCoord,i+1)
aContainer.push(aLoc)
while not aContainer.isEmpty():
item = aContainer.pop()
item.printLoc()
if __name__ == '__main__':
main() |
def manhattan_from_zero(point):
return abs(point[0]) + abs(point[1])
def load_path_points():
instructions = input().split(',')
x, y = 0, 0
dirs = {'L': (-1, 0), 'R': (1, 0), 'U': (0, 1), 'D': (0, -1)}
path_points = set()
for instruction in instructions:
direction = dirs[instruction[0]]
for step in range(int(instruction[1:])):
x, y = x + direction[0], y + direction[1]
path_points.add((x, y))
return path_points
cable1 = load_path_points()
cable2 = load_path_points()
print(sorted(list(map(manhattan_from_zero, cable1.intersection(cable2))))[0])
|
import random
import os
MENU = """ ++ P A S S W O R D G E N E R A T O R ++ by @djalocho
Choose a security level:
[1] - Low
[2] - Medium
[3] - High
Type a number [1-3] -> """
def num_input(message):
try:
number = int(input(message))
return number
except ValueError as ve:
print("Type a number, try again.")
# pass generator, number can be 1 for low and 3 for high security
def pass_gen(number):
def random_dic():
dic_words = { # dic that return a random number, letter or simbol
'number': str(random.randint(0,9)),
'letter': random.choice('qwertyuiopasdfghjklñzxcvbnm'),
'simbol': random.choice("!#$%&/()=?¡[];: ")
}
return dic_words
if number == 1:
password_list = [random_dic()[random.choice(['number', 'letter'])] for i in range(5)] # password of 5 digits of numbers and letters
elif number == 2:
password_list = [random_dic()[random.choice(['number', 'letter'])] for i in range(10)] # password of 10 digits of numbers and letters
elif number == 3:
password_list = [random_dic()[random.choice(['number', 'letter', 'simbol'])] for i in range(15)] # password of 10 digits of numbers, letters and simbols
else:
raise ValueError("Invalid number, choose a number from 1 to 3.")
#print(password_list)
password = "".join(password_list)
return password
def run():
os.system("clear")
security_level = num_input(MENU)
password = pass_gen(security_level)
print(" The password generated is:", password + '\n')
if __name__ == "__main__":
run() |
def FindNumber():
#Pick a number and the program will guess your number in the least
#amount of attemtps as possible. Only '<', '>' or '=' can be used.
lo = 0
hi = 2
print("Input '<' if my guess is smaller, Input '>' if my guess is greater")
print("or input '=' if guess is correct")
hinum = False
count = 0
while lo < hi:
mid = ( lo + hi )//2
print(mid)
response = str(input("Please enter < or > or = : "))
if response == '=' :
count += 1
break
elif response == '<' :
hinum = True
print('I will guess a smaller number')
count += 1
hi = mid - 1
elif response == '>' :
print('I will guess a bigger number')
count += 1
lo = mid + 1
if hinum == False:
hi = hi*2
else:
print('Please use < > or = ')
print('Number is: ',(lo + hi ) // 2)
print('Number of Guesses: %s' % count)
|
import numpy as np
import pandas as pd
df1=pd.DataFrame(np.arange(1,13).reshape(3,4),columns=list('abcd'))
df2=pd.DataFrame(np.arange(1,21).reshape(4,5),columns=list('abcde'))
df1.add(df2,fill_value=0) #两个表相加
frame=pd.DataFrame(np.arange(1,13).reshap(4,3),columns=list('bde'),index=['Shenzhen','Guangzhou','Shanghai','Beijing'])
print(df1.add(df2,fill_value=0))
|
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a+b
def subtract(a, b):
print "SUBSTRACTING %d - %d" % (a, b)
return a - b
def mulpiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a*b
def divide(a, b):
print "DIVIDING %d / %d" %(a, b)
return a/b
print "Let's do some math with just funcktions!"
age = add(30, 5)
height = subtract(78, 4)
weight = mulpiply(90, 2)
iq = divide(200, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age,height,weight,iq)
print "Gere is a puzzle."
what=add(age, subtract(height, mulpiply(weight, divide(iq, 2))))
print "Thah becomes: ", what, "Can youd do it by hand?"
|
s=raw_input("Enter the string ")
s=s.split(" ")
s.sort()
print " ".join(s)
|
# Python3 program to add two numbers
num1 = 15
num2 = 12
num3 = 10
# Adding two nos
sum = num1 + num2 + num3
# printing values
print("Sum of {0} {1} and {2} is {3}" .format(num1, num2, num3, sum))
|
with open("input.txt") as file:
passports = file.read().split("\n\n")
fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
count = 0
for passport in passports:
flag = False
for field in fields:
if f"{field}:" not in passport:
flag = True
break
if flag:
continue
count += 1
print(count)
|
"""
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder. What is the smallest positive number that is
evenly divisible by all of the numbers from 1 to 20?
LCM(x, y) = x * y / GCD(x, y) -> 1 * 20 / GCD(1, 20)
LCM(k1, k2, ..., kn) = LCM(...(LCM(LCM(k1, k2), k3)...), kn)
"""
import math
def smallest_multiple():
num = 1
for i in range(1, 21):
num *= i // math.gcd(i, num)
return num
print(smallest_multiple())
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 08:00:59 2018
@author: Papun Mohanty
"""
from faker import Faker
import sqlite3
import time
# Creating Faker Object
faker_factory = Faker()
try:
conn = sqlite3.connect('human.db')
cursor = conn.cursor()
print("Opened database successfully")
cursor.execute("""CREATE TABLE human (
NAME CHAR(250),
DOB CHAR(250),
ADDRESS CHAR(250),
EMAIL CHAR(250),
COMPANY_EMAIL CHAR(250),
CIGARATES_SMOKES INT,
NUMBER_OF_CHILDREN INT,
PHONE_NUMBER CHAR(250),
FAVOURITE_COLOR CHAR(250),
JOB CHAR(250)
)""")
conn.commit()
conn.close()
except:
print('There is some problem creating the Database')
number_of_human = int(input("Enter how many numbers of Human you want to insert in the Database: "))
number_of_db_entries = 0
list_humam = []
t1 = time.time()
# Iterating over the number of database entries.
for human in range(number_of_human):
# Creating fake Data.
name = faker_factory.name()
dob = str(faker_factory.date_of_birth())
address = faker_factory.address()
email = faker_factory.email()
company_email = faker_factory.company_email()
cigarates_smokes = faker_factory.random_digit()
number_of_childeren = faker_factory.random_digit()
phone_number = faker_factory.phone_number()
favourite_color = faker_factory.color_name()
job = faker_factory.job()
# Connecting to the Database.
conn = sqlite3.connect('human.db')
cursor = conn.cursor()
# Inserting Fake Data into the table.
list_humam.append((name, dob, address, email, company_email, cigarates_smokes, number_of_childeren, phone_number, favourite_color, job))
# cursor.execute("INSERT INTO human VALUES ('{}', '{}', '{}', '{}', '{}', {}, {}, '{}', '{}', '{}')".format(name, dob, address, email, company_email, cigarates_smokes, number_of_childeren, phone_number, favourite_color, job))
number_of_db_entries += 1
print("Running for {}th human".format(number_of_db_entries))
cursor.executemany("INSERT INTO human (NAME, DOB, ADDRESS, EMAIL, COMPANY_EMAIL, CIGARATES_SMOKES, NUMBER_OF_CHILDREN, PHONE_NUMBER, FAVOURITE_COLOR, JOB) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", list_humam)
print("Inserted database successfully")
# Commiting the data for the connection.
conn.commit()
# Closing the connection.
conn.close()
t2 = time.time() - t1
print("Total number of Database entries is: ", number_of_db_entries)
print("To insert {} number of Human entry, this machine took {} seconds.".format(number_of_human, t2)) |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def setDemo(self):
# NLR : A B D C E G H F I
# LNR : D B A G E H C F I
# LRN : D B G H E I F C A
n1l = TreeNode('B')
n1l.left = TreeNode('D')
n1rl = TreeNode('E')
n1rl.left = TreeNode('G')
n1rl.right = TreeNode('H')
n1rr = TreeNode('F')
n1rr.right = TreeNode('I')
n1r = TreeNode('C')
n1r.left = n1rl
n1r.right = n1rr
self.val = 'A' #= TreeNode('A')
self.left = n1l
self.right = n1r
def level_order(self):
re = []
if self!= None:
stack =[self]
while len(stack)!=0:
temp = stack[0]
re.append(temp.val)
stack = stack[1:]
if temp.left:
stack.append(temp.left)
if temp.right:
stack.append(temp.right)
return re
# demo = TreeNode(0)
# demo.setDemo()
# print demo.level_order() |
# PROBLEM DESCRIPTION
# A permutation is an ordered arrangement of objects.
# For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
# If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
# The lexicographic permutations of 0, 1 and 2 are:
# 012 021 102 120 201 210
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
# NOTES:
# The lexicographic permutations of 0, 1, 2, 3 are:
# 0123 0132 0213 0231 0312 0321
# 1023 1032 1203 1230 1302 1320
# 2013 2031 2103 2130 2301 2310
# 3012 3021 3102 3120 3201 3210
# number of permutations is len(numbers)! <-- factorial, not emphasis
# 10! == 3628800
# for one row of permutations, it has (len(numbers) - 1)! members
# 9! == 362880
# so the millionth permutation will be near the end of the 2 row
# remove 2 from the list, know how far to million
# and then do the function again
# write function that will take in a list of consecutive numbers and and int
# this function will take the factorial of the len(list)
# and then use this to find the iteration that is the largest and <= the int
# return that number
import math
# this will find which row in the permutation list that x is in
def find_permutation_row(list_numbers, x):
# find out the length of each permutation row
row_length = math.factorial(len(list_numbers) - 1)
# start off at row 1
row = row_length
which_row = 0
# while we still have not found the correct row yet
while(row < x):
# proceed to the next row
row += row_length
which_row += 1
return which_row
# this will build the correct permutation by calling find_permutation_row multiple times
def find_permutation(list_numbers, x):
permutation = ""
goal = x
# while we still have numbers in the list to iterate through
while(1 < len(list_numbers)):
# the permutation row is different from the number we need to add to the string
r = find_permutation_row(list_numbers, goal)
permutation_number = list_numbers[r]
# move the goal post over so we can feed find_permutation_row the correct maximum
# need to move the goal by the offset
row_offset = math.factorial(len(list_numbers) - 1)
goal -= r * row_offset
# next remove the found permutation so we don't find it again
list_numbers.remove(permutation_number)
permutation+=str(permutation_number)
# only one item left in the list
permutation+=str(list_numbers[0])
return permutation
print("our answer is: " + find_permutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1000000)) |
# PROBLEM DESCRIPTION
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-eight, rain or shine.
# And on leap years, twenty-nine.
# A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
# How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
# advance to the next first day of the month when given a day and a month, and if the year is a leap year
def first_of_next_month(day, month, leap):
# if the month has 31 days
if month in [1, 3, 5, 7, 8, 10, 12]:
return day + 3
# if the month has 30 days
elif month in [4, 6, 9, 11]:
return day + 2
# if the month is february on a leap year
elif (month == 2) and leap:
return day + 1
# if the month is february
else:
return day
# need to write a function that will count the sundays in a 100 year period
def count_sundays():
# Jan 1, 1900 was a monday, so we initialize day with 1
sundays = 0
day = 1
for i in range(101):
# calculate if we are in a leap year
b = True if (i % 4 == 0) else False
for j in range(12):
# we started on Jan 1 1900, but we only want to count sundays during and after 1901
if day == 0 and 0 < i:
sundays += 1
# find the first day of next month, if it is a sunday, we keep track of it
day = first_of_next_month(day, j+1, b)
day = day % 7
return sundays
print "our answer is: " + str(count_sundays()) |
from sys import stdin
"""
Nombre: Jhoan Sebastian Lozano
Código: 8931869
Código de honor del curso:
Como miembro de la comunidad académica de la
Pontificia Universidad Javeriana Cali me comprometo
a seguir los más altos estándares de integridad académica.
"""
def solve(M):
pascal = [ [1 for _ in range(M+1) ] for _ in range(M+1) ]
n,m = 1,1
ans = list()
while n!=M+1:
if m == M+1: n,m = n+1,1
else:
pascal[n][m] = pascal[n-1][m] + pascal[n][m-1]
if pascal[n][m] == M: ans.append((m+n,n))
m+=1
return ans
def main():
T = int(stdin.readline())
for _ in range(T):
m = int(stdin.readline())
ans = solve(m)
# for p in pascal: print(p)
ans.sort()
print(len(ans))
for a in ans: print("("+str(a[0])+","+str(a[1])+")",end=" ")
print()
return
main() |
#Calculate a power of a number rised to other
def power(a,b):
if b==0:
return 1
else:
return a*power(a,b-1)
a=int(input("base: "))
b=int(input("exponent: "))
print(power(a,b))
#Perfect numbers between 1 and 1000
import math
def divisors(n):
divs = [1]
for i in range(2,int(math.sqrt(n))+1):
if n%i == 0:
divs.extend([i,n/i])
return list(set(divs))
def is_perfect_number(n):
return n == sum(divisors(n))
res = []
for i in range(2,1001):
if is_perfect_number(i):
res.append(i)
print("Perfectnumbers between 1 and 1000: ",res)
#Recursuve function to calculate the sum of numbers from 0 to 10
def sum(n):
if n==1:
return 1
else:
return n+sum(n-1)
print("Sum of Numbers from 0 to 10: ",sum(10))
|
#!/usr/bin/env python
'''
For this exercise, draw a random number of randomly-sized sprites with a random color, random initial position, and random direction
'''
import sys, logging, pygame, random
assert sys.version_info >= (3, 4), 'This script requires at least Python 3.4'
logging.basicConfig(level=logging.CRITICAL)
logger = logging.getLogger(__name__)
screen_size = (800, 600)
FPS = 60
red = (255, 0, 0)
black = (0, 0, 0)
class Block(pygame.sprite.Sprite):
def __init__(self, color, size, position, direction):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface(size)
self.image.fill(color)
self.rect = self.image.get_rect()
(self.rect.x, self.rect.y) = position
self.direction = direction
def update(self):
(dx, dy) = self.direction
self.rect.x += dx
self.rect.y += dy
(WIDTH, HEIGHT) = screen_size
if self.rect.left > WIDTH:
self.rect.right = 0
if self.rect.right < 0:
self.rect.left = WIDTH
if self.rect.top > HEIGHT:
self.rect.bottom = 0
if self.rect.bottom < 0:
self.rect.top = HEIGHT
def main():
pygame.init()
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
amount = random.randint(1,11)
blocks = pygame.sprite.Group()
for x in range(0, amount):
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
pos = (random.randint(51, 750), random.randint(51, 550))
dir = (random.randint(-10, 10), random.randint(-10, 10))
block = Block(color, (50, 50), pos, dir)
blocks.add(block)
while True:
clock.tick(FPS)
screen.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
blocks.update()
blocks.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
|
'''
@ Ting-Yi Shih
#Usage Example
from factory import Factory
Factory(source=[1,2,3], filename="factory_out", func=lambda x:str(x), num_workers=1).run()
source: a list/an iterator/a generator of items
filename: output filename
func: function that returns a string as the result of the item
can take either 1 argument: item, or take 2 arguments: item and fparam
item: 1 out of source
fparam(optional): parameters
fparam: parameters to this function shared by all items (None by default)
if func takes exactly 1 argument, fparam must be None
if func takes exactly 2 arguments, fparam must not be None
num_worker: number of process to be executed
'''
from __future__ import division
class Factory:
def __init__(this, source=[], filename="factory_out", func=lambda x:str(x), fparam=None, num_workers=1):
this.source = source
this.fout_name = filename
this.func = func
this.num_workers = num_workers
this.fparam = fparam
@staticmethod
def worker(worker_id, in_queue, func, fparam, fout): # make args a tuple
while True:
item = in_queue.get()
result = func(item, fparam) if fparam else func(item) # input=item,args output=string
fout.write("%s\n"%result)
fout.flush()
in_queue.task_done()
@staticmethod
def progressor(in_queue,total_num):
if total_num==0: return
import time,sys
while True:
Factory.pg("%5.1f%%..."%(100-in_queue.qsize()/total_num*100))
time.sleep(1)
@staticmethod
def pg(msg, br=False):
import sys
sys.stderr.write("\rFactory: "+msg+"\033[K"+("\n" if br else ""))
sys.stderr.flush()
def test(this):
try:
this.source = iter(this.source)
except:
raise Exception("source should be a iterable")
import inspect
if this.fparam is None:
if len(inspect.getargspec(this.func).args)!=1:
raise Exception("function should take exactly 1 argument: item")
if this.fparam is not None:
if len(inspect.getargspec(this.func).args)!=2:
raise Exception("function should take exactly 2 arguments:item and parameters")
if this.fout_name=="":
raise Exception("filename cannot be an empty string")
if type(this.num_workers)!=type(1) or this.num_workers<=0:
raise Exception("invalid value of num_workers")
try:
item = next(this.source)
except:
raise Exception("source is empty")
result = this.func(item, this.fparam) if this.fparam else this.func(item)
if type(result)!=type(""):
raise Exception("function should return a string")
with open("%s_part"%this.fout_name, "w") as fout:
fout.write("%s\n"%result)
fout.flush()
def run(this):
Factory.pg("configuration test...")
this.test() # check configuration
source = this.source
fout_name = this.fout_name
func = this.func
fparam = this.fparam
num_workers = this.num_workers
worker = this.worker
progressor = this.progressor
# queue settings
Factory.pg("arranging source elements...")
from multiprocessing import JoinableQueue,Process
in_queue = JoinableQueue()
for item in source:
in_queue.put(item)
# worker progressing
progressor = Process(target=progressor, args=(in_queue, in_queue.qsize()))
import time
start_time = time.time()
progressor.start()
# worker settings
fouts, workers = [], []
for w_id in xrange(num_workers):
fouts.append(open("%s_part%d"%(fout_name,w_id),"w"))
workers.append(Process(target=worker, args=(w_id, in_queue, func, fparam, fouts[w_id])))
workers[w_id].start()
# post processing
in_queue.join()
for w_id in xrange(num_workers):
workers[w_id].terminate()
progressor.terminate()
end_time = time.time()
Factory.pg("working done (%.1fs lapsed)"%(end_time - start_time), br=True)
import os
os.system("cat %s_part* > %s"%(fout_name,fout_name))
os.system("rm -f %s_part*"%(fout_name))
# useful when the output is not str (not recommended)
def obj2line(obj):
return str(obj)
def line2obj(line):
import ast
return ast.literal_eval(line)
# useful when batch processing (1 result for all instead of for each) (not recommended)
def src2chunk(source, nChunks):
import math
source = list(source)
chunk_size = int(math.ceil(len(source)/nChunks))
return [source[i:i+chunk_size] for i in xrange(0,len(source),chunk_size)]
def mergeLines(filename, res, update):
with open(filename, "r") as fin:
for line in fin:
res_prt = line2obj(line)
res = update(res,res_prt)
with open(filename, "w") as fout:
fout.write(obj2line(res))
if __name__ == "__main__":
def simple(x,fparam):
import time
time.sleep(fparam)
return str(x)
Factory(source=range(10), filename="factory_out", func=simple, fparam=3, num_workers=5).run()
|
#Abhishek Khandelwal
def slope(q):
x0,y0 = lowest_point
x1,y1 = q
#print lowest_point,q
#print float(y0-y1)/(x0-x1)
return float(y0-y1)/(x0-x1)
n = int(raw_input("Enter number of Points"))
points = []
lowest_point = (100,100)
for i in xrange(n):
point = tuple(map(int,raw_input().split()))
points.append(point)
if point[1]<lowest_point[1]:
lowest_point = point
elif point[0]<lowest_point[0] and point[1]==lowest_point[1]:
lowest_point = point
points.remove(lowest_point)
points.sort(key = slope)
print points
|
# Mario recursion
from cs50 import get_int
def main():
height = get_int("Put the hight of the pyramid object: \n")
def mariostep(n):
if n == 0:
return
else:
mariostep(n - 1)
for i in range(n):
print("#", end = '')
print("", end = '\n')
mariostep(height)
main()
|
#code
def commonPrefix(s1, s2):
n1 = len(s1)
n2 = len(s2)
result = ""
i,j=0,0
while i<=n1-1 and j<=n2-1:
if s1[i]!=s2[j]:
break
result+=s1[i]
i+=1
j+=1
if result:
return result
else:
return -1
def prefix(s, l):
if l==1:
print(s)
else:
s.sort(reverse=False)
print(commonPrefix(s[0], s[l-1]))
t=int(input())
for cases in range(t):
length = int(input())
if length==1:
string=input()
else:
string=list(map(str, input().split(' ')))
prefix(string, length)
|
userInput = int(input("Please input side length of diamond: "))
if userInput > 0:
for i in range(userInput):
for s in range(userInput -3, -2, -1):
print(" ", end="")
for j in range(i * 2 -1):
print("*", end="")
print()
for i in range(userInput, -1, -1):
for j in range(i * 2 -1):
print("*", end="")
print()
|
def LeftView(root, level, maxlevel):
if root is None:
return 0
else:
if maxlevel[0]<level:
print(root.data, end=' ')
maxlevel[0] = level
LeftView(root.left, level+1, maxlevel)
LeftView(root.right, level+1, maxlevel)
def printLeft(root):
maxlevel = [0]
LeftView(root, 1, maxlevel)
def inorder(root):
if root is None:
return []
return inorder(root.left) + [root.val] + inorder(root.right)
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.data = val
def insert(self, data):
if self.data:
if data<self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def printTree(self):
if self.left:
self.left.printTree()
print(self.data)
if self.right:
self.right.printTree()
'''test_case = int(input())
for i in range(test_case):
elem_list = list(map(int, input().split()))
root = Node(elem_list[0])
for i in range(1,len(elem_list)):
root.insert(elem_list[i])
printLeft(root)'''
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(60)
#printLeft(root)
ans = inorder(root)
print(ans)
|
list1 = []
new_list = []
for _ in range(int(input())):
list2 = []
name = input()
score = float(input())
new_list.append(score)
list2.append(name)
list2.append(score)
list1.append(list2)
new_list.sort()
new_list = list(set(new_list))
new_list.sort()
print(new_list)
val = new_list[1]
result = []
for i in range(len(list1)):
if list1[i][1]==val:
result.append(list1[i][0])
result.sort()
for i in result:
print(i)
|
hashtable = [[], ] * 10
def checkPrime(n):
if n==1 or n==0:
return 0
for i in range(2, n//2):
if n%i==0:
return 0
return 1
def getPrime(n):
if n%2==0:
n+=2
while not checkPrime(n):
n+=1
return n
def hashFunction(key):
capacity = getPrime(10)
return key%capacity
def insertData(key, data):
index = hashFunction(key)
hashtable[index] =[key, data]
def removeData(key):
index = hashFunction(key)
hashtable[index] = 0
insertData(123, 'Aish')
insertData(234, 'Ish')
print(hashtable)
removeData(123)
print(hashtable)
|
def josephus(n, k):
ll = []
i=1
while i<=n:
ll.append(i)
i+=1
i=1
while len(ll)!=1:
index = (i+k)%n
ll.pop(index)
i+=1
return ll
def main():
T= int(input())
while(T>0):
nk = [int(x) for x in input().split()]
n = nk[0]
k = nk[1]
print(josephus(n,k))
if __name__=="__main__":
main()
|
# -*- coding: utf-8 -*-
import csv
class Contact:
def __init__(self,name, phone,email):
self.name=name
self.phone=phone
self.email=email
class ContactBook:
def __init__(self):
self._contacts=[]
def add(self, name,phone,email):
contact = Contact(name, phone, email)
self._contacts.append(contact)
self._save()
def show_all(self):
for contact in self._contacts:
self._print_contact(contact)
def delete(self,name):
for idx, contact in enumerate(self._contacts):
if contact.name.lower() == name.lower():
del self._contacts[idx]
self._save()
break
def search(self,name):
for contact in self._contacts:
if contact.name.lower() == name.lower():
print('--*--*--*--*--*--*--*--*')
print('Nombre: {}'.format(contact.name))
print('Telefono: {}'.format(contact.phone))
print('Email: {}'.format(contact.email))
print('--*--*--*--*--*--*--*--*')
break
else:
self.not_found()
def update(self, name):
for idx, contact in enumerate(self._contacts):
if contact.name.lower() == name.lower():
parameter= str(raw_input('''
¿Qué dato deseas actualizar?
[n]ombre
[t]elefono
[e]mail
[to]dos los datos: '''))
if parameter == 'n':
name_= str(raw_input('Escribe el nuevo nombre del contacto: '))
del self._contacts[idx].name
self._contacts[idx].name=name_
self._save()
break
if parameter == 't':
telefono_= str(raw_input('Escribe el nuevo telefono del contacto: '))
del self._contacts[idx].phone
self._contacts[idx].phone=telefono_
self._save()
break
if parameter == 'e':
email_= str(raw_input('Escribe el nuevo email del contacto: '))
del self._contacts[idx].email
self._contacts[idx].email=email_
self._save()
break
if parameter == 'to':
name_= str(raw_input('Escribe el nuevo nombre del contacto: '))
telefono_= str(raw_input('Escribe el nuevo telefono del contacto: '))
email_= str(raw_input('Escribe el nuevo email del contacto: '))
del self._contacts[idx].name
del self._contacts[idx].phone
del self._contacts[idx].email
self._contacts[idx].name=name_
self._contacts[idx].phone=telefono_
self._contacts[idx].email=email_
self._save()
print('Usuario actualizado exitosamente!')
break
else:
print('Comando no encontrado.')
break
else:
self.not_found()
def _print_contact(self,contact):
print('--*--*--*--*--*--*--*--*')
print('Nombre: {}'.format(contact.name))
print('Telefono: {}'.format(contact.phone))
print('Email: {}'.format(contact.email))
print('--*--*--*--*--*--*--*--*')
def not_found(self):
print('--*--*--*--*--*--*--*--*')
print('Contacto no encontrado !!')
print('--*--*--*--*--*--*--*--*')
def _save(self):
with open('contacts.csv','w') as f:
writer = csv.writer(f)
writer.writerow(('name','phone','email'))
for contact in self._contacts:
writer.writerow((contact.name, contact.phone, contact.email))
def run():
contact_book= ContactBook()
try:# intenta cargar archivo con usuarios previamente guardados
with open('contacts.csv','r') as f:
reader=csv.reader(f)
for idx, row in enumerate(reader):
if idx==0: #ignora el primer componente de la lista
continue
contact_book.add(row[0],row[1], row[2]) #agrega todos los demas componentes d ela lista
except: # si no encuentra el archivo crea uno vacio
with open('contacts.csv','w') as f:
f.write('')
while True:
command = str(raw_input('''
¿Qué deseas hacer?
[a]ñadir contacto
[ac]tualizar contacto
[b]uscar contacto
[e]liminar contacto
[l]istar contactos
[s]alir
'''))
if command == 'a':
name= str(raw_input('Escribe el nombre del contacto: '))
phone= str(raw_input('Escribe el telefono del contacto: '))
email= str(raw_input('Escribe el email del contacto: '))
contact_book.add(name,phone,email)
elif command == 'ac':
name= str(raw_input('Escribe el nombre del contacto: '))
contact_book.update(name)
elif command == 'b':
name= str(raw_input('Escribe el nombre del contacto: '))
contact_book.search(name)
elif command == 'e':
name= str(raw_input('Escribe el nombre del contacto: '))
contact_book.delete(name)
elif command == 'l':
contact_book.show_all()
elif command == 's':
break
else:
print('Comando no encontrado.')
if __name__ == '__main__':
run() |
import random
import matplotlib.pyplot as plt
# константы генетического алгоритма
POPULATION_SIZE = 100 # количество индивидуумов в популяции
MAX_GENERATIONS = 200 # максимальное количество поколений
P_CROSSOVER = 0.9 # вероятность скрещивания
P_MUTATION = 0.1 # вероятность мутации индивидуума
N_VECTOR = 2 # количество генов в хромосоме
LIMIT_VALUE_TOP = 100
LIMIT_VALUE_DOWN = -100
RANDOM_SEED = 1
random.seed(RANDOM_SEED)
class Individual(list):
def __init__(self, *args):
super().__init__(*args)
self.value = 0
def fitness_function(f):
return f[0] ** 2 + 1.5 * f[1] ** 2 - 2 * f[0] * f[1] + 4 * f[0] - 8 * f[1]
def individualCreator():
return Individual([random.randint(LIMIT_VALUE_DOWN, LIMIT_VALUE_TOP) for i in range(N_VECTOR)])
def populationCreator(n=0):
return list([individualCreator() for i in range(n)])
population = populationCreator(n=POPULATION_SIZE)
fitnessValues = list(map(fitness_function, population))
for individual, fitnessValue in zip(population, fitnessValues):
individual.value = fitnessValue
MinFitnessValues = []
meanFitnessValues = []
BadFitnessValues = []
population.sort(key=lambda ind: ind.value)
print([str(ind) + ", " + str(ind.value) for ind in population])
def clone(value):
ind = Individual(value[:])
ind.value = value.value
return ind
def selection(popula, n=POPULATION_SIZE):
offspring = []
for i in range(n):
i1 = i2 = i3 = i4 = 0
while i1 in [i2, i3, i4] or i2 in [i1, i3, i4] or i3 in [i1, i2, i4] or i4 in [i1, i2, i3]:
i1, i2, i3, i4 = random.randint(0, n - 1), random.randint(0, n - 1), random.randint(0,
n - 1), random.randint(
0, n - 1)
offspring.append(
min([popula[i1], popula[i2], popula[i3], popula[i4]], key=lambda ind: ind.value))
return offspring
def crossbreeding(object_1, object_2):
s = random.randint(1, len(object_1) - 1)
object_1[s:], object_2[s:] = object_2[s:], object_1[s:]
def mutation(mutant, indpb=0.04, percent=0.05):
for index in range(len(mutant)):
if random.random() < indpb:
mutant[index] += random.randint(-1, 1) * percent * mutant[index]
generationCounter = 0
while generationCounter < MAX_GENERATIONS:
generationCounter += 1
offspring = selection(population)
offspring = list(map(clone, offspring))
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < P_CROSSOVER:
crossbreeding(child1, child2)
for mutant in offspring:
if random.random() < P_MUTATION:
mutation(mutant, indpb=1.0 / N_VECTOR)
freshFitnessValues = list(map(fitness_function, offspring))
for individual, fitnessValue in zip(offspring, freshFitnessValues):
individual.value = fitnessValue
population[:] = offspring
fitnessValues = [ind.value for ind in population]
minFitness = min(fitnessValues)
meanFitness = sum(fitnessValues) / len(population)
maxFitness = max(fitnessValues)
MinFitnessValues.append(minFitness)
meanFitnessValues.append(meanFitness)
BadFitnessValues.append(maxFitness)
print(
f"Поколение {generationCounter}: Функция приспособленности. = {minFitness}, Средняя приспособ.= {meanFitness}")
best_index = fitnessValues.index(min(fitnessValues))
print("Лучший индивидуум = ", *population[best_index], "\n")
plt.plot(MinFitnessValues[int(MAX_GENERATIONS * 0.1):], color='red')
plt.plot(meanFitnessValues[int(MAX_GENERATIONS * 0.1):], color='green')
plt.plot(BadFitnessValues[int(MAX_GENERATIONS * 0.1):], color='blue')
plt.xlabel('Поколение')
plt.ylabel('Мин/средняя/max приспособленность')
plt.title('Зависимость min, mean, max приспособленности от поколения')
plt.show()
|
class things(object):
def __init__(self, name, function, surface):
self.name = name
self.function = function
self.surface = surface
def description(self):
print(f"名字:{self.name},功能:{self.function},外貌:{self.surface}")
things1 = things("桌子", "陈放东西", "有四条腿")
things2 = things("椅子", "可以坐人", "有四条腿")
things3 = things("柜子", "可以储物", "由储存空间")
things4 = things("笔记本", "可以携带", "屏幕与电脑本身为一体")
things5 = things("电视", "可以看电影", "屏幕很大")
|
"""
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
"""
"""
一个回合制游戏,每个角色都有hp 和power,hp代表血量,power代表攻击力,hp的初始值为1000,power的初始值为200。
定义一个fight方法:
my_final_hp = my_hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个hp进行对比,血量剩余多的人获胜
"""
def game():
my_hp = 1000
my_power = 200
enemy_hp = 999
enemy_power = 199
while True:
my_hp = my_hp - enemy_power # 通过循环我的血量每次扣减后,当前的血量值
enemy_hp = enemy_hp - my_power # 通过循环敌人的血量每次扣减后,当前的血量值
print(my_hp) # 打印我的血量
if my_hp <= 0: # 我的血量小于等于0就是我输了,然后跳出循环
print("我输了")
break
elif enemy_hp <= 0: # 滴人血量小于等于0就是我输了,然后跳出循环
print("你输了")
break
game() |
# 面向对象
class House:
# 静态属性 -> 变量, 类变量, 在类之中, 方法之外
door = "red"
floor = "white"
# 构造函数,是在类实例化的时候直接执行
def __init__(self):
# 实例变量,是在类实例化的时候直接执行,以“self.变量名的方式去定义”,实例变量的作用域为这个类中的所有方法
self.door
self.yangtai = "大"
# 动态属性 -> 方法(函数)
def sleep(self):
# 普通变量,再类之中、方法之中,并且不会以self.开头
print('房子是用来睡觉的')
def cook(self):
print("房子可以做饭吃")
# 实例化 -> 变量 = 类()
north_house = House()
china_house = House()
# 调用类变量
print(House.door)
House.door = "white"
north_house.door = "black"
print(north_house.door)
#图纸的door 是什么颜色
print(House.door)
# china_house.door 是什么颜色
print(china_house.door) |
#figure &subplot
"""
numpy를 이용한 다양한 그래프 그리기
"""
from matplotlib import pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
sp1 = fig.add_subplot(2,2,1)
sp2 = fig.add_subplot(2,2,2)
sp3 = fig.add_subplot(2,2,3)
sp4 = fig.add_subplot(2,2,4)
sp1.plot([2,3,4,5], [81,93,91,97])
sp2.plot(randn(50).cumsum(), 'k--')
sp3.hist(randn(100), bins=20, color = 'k', alpha = 0.3)
sp4.scatter(np.arrange(100), np.arange(100) + 3*randn(100))
plt.show() |
"""The unit test for runtime.ast"""
import unittest
from runtime import ast, env, lib
NULL_LITERAL = ast.Literal(env.Value(env.NULL))
INT_LITERAL = ast.Literal(env.Value(lib.INTEGER, 0))
TRUE_LITERAL = ast.Literal(env.Value(lib.BOOLEAN, True))
FALSE_LITERAL = ast.Literal(env.Value(lib.BOOLEAN, False))
STRING_LITERAL = ast.Literal(
env.Value(lib.STRING, "Hallo Welt!", "identifier"))
class SumNode(ast.Node):
"""A sum node."""
name = "sum"
def __init__(self):
super().__init__()
def eval(self, context):
"""Sums up the value of its children."""
value = 0
for child in self.children:
value += child.eval(context).data
return env.Value(lib.INTEGER, value)
class AccessNode(ast.Node):
"""A access node."""
def __init__(self):
super().__init__()
@classmethod
def eval(cls, context):
"""Stores a string in the current namespace."""
context.store(STRING_LITERAL.value)
return STRING_LITERAL.eval(context)
class TestAst(unittest.TestCase):
"""The abstract syntax tree test cases."""
def test_sequence_node(self):
"""Test the sequence node."""
context = env.empty_context()
return_node = ast.Return()
return_node.children = [TRUE_LITERAL]
# empty sequence
empty_seq = ast.Sequence()
self.assertEqual(empty_seq.eval(context), NULL_LITERAL.value)
# non-empty sequence
non_seq = ast.Sequence()
non_seq.children = [NULL_LITERAL, TRUE_LITERAL]
self.assertEqual(non_seq.eval(context), TRUE_LITERAL.value)
non_seq.children = [TRUE_LITERAL, NULL_LITERAL]
self.assertEqual(non_seq.eval(context), NULL_LITERAL.value)
# sequence with return
ret_seq = ast.Sequence()
ret_seq.children = [return_node, NULL_LITERAL]
self.assertEqual(ret_seq.eval(context), TRUE_LITERAL.value)
# self.assertEqual(ret_seq.__str__(), "<Node (sequence)>")
def test_conditional_node(self):
"""Test the conditional node."""
context = env.empty_context()
# Test bad conditional error
bad_conditional = ast.Conditional()
bad_conditional.add(NULL_LITERAL) # if None:
bad_conditional.add(NULL_LITERAL) # then None
self.assertRaises(Exception, bad_conditional.eval, context)
# Test correct result
good_conditional = ast.Conditional()
good_conditional.add(TRUE_LITERAL)
good_conditional.add(NULL_LITERAL)
self.assertEqual(good_conditional.eval(context), NULL_LITERAL.value)
# self.assertEqual(good_conditional.__str__(), "<Node (conditional)>")
def test_branch_node(self):
"""Test the branch node."""
context = env.empty_context()
# always evaluates
true_cond = ast.Conditional()
true_cond.children = [TRUE_LITERAL, STRING_LITERAL]
false_cond = ast.Conditional()
false_cond.children = [FALSE_LITERAL, NULL_LITERAL]
# Test if branch
if_branch = ast.Branch()
if_branch.children = [true_cond, NULL_LITERAL]
self.assertEqual(if_branch.eval(context), STRING_LITERAL.value)
# Test if-else branch
ifelse_branch = ast.Branch()
ifelse_branch.children = [false_cond, STRING_LITERAL]
self.assertEqual(ifelse_branch.eval(context), STRING_LITERAL.value)
# Test if-elif-else branch
ifelifelse_branch = ast.Branch()
ifelifelse_branch.children = [false_cond, true_cond, NULL_LITERAL]
self.assertEqual(ifelifelse_branch.eval(context), STRING_LITERAL.value)
# self.assertEqual(if_branch.__str__(), "<Node (branch)>")
def test_loop_node(self):
"""Test the loop node."""
break_node = ast.Break()
return_node = ast.Return()
return_node.children = [TRUE_LITERAL]
context = env.empty_context()
# check for exception
bad_loop = ast.Loop()
bad_loop.children = [NULL_LITERAL, TRUE_LITERAL]
self.assertRaises(Exception, bad_loop.eval, context)
# check for break
break_loop = ast.Loop()
break_loop.children = [TRUE_LITERAL, break_node]
self.assertEqual(break_loop.eval(context), NULL_LITERAL.value)
self.assertEqual(context.behaviour, ast.DEFAULT_BEHAVIOUR)
# check for return
return_loop = ast.Loop()
return_loop.children = [TRUE_LITERAL, return_node]
self.assertEqual(return_loop.eval(context), TRUE_LITERAL.value)
self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)
# self.assertEqual(return_loop.__str__(), "<Node (loop)>")
def test_return_node(self):
"""Test the return node."""
# test empty return node
context = env.empty_context()
empty_return = ast.Return()
self.assertEqual(empty_return.eval(context), NULL_LITERAL.value)
self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)
# test return with value
context = env.empty_context()
value_return = ast.Return()
value_return.add(TRUE_LITERAL)
self.assertEqual(value_return.eval(context), TRUE_LITERAL.value)
self.assertEqual(context.behaviour, ast.RETURN_BEHAVIOUR)
#self.assertEqual(value_return.__str__(), "<Node (return)>")
def test_break_node(self):
"""Test the break node."""
context = env.empty_context()
break_node = ast.Break()
self.assertEqual(break_node.eval(context), NULL_LITERAL.value)
self.assertEqual(context.behaviour, ast.BREAK_BEHAVIOUR)
#self.assertEqual(break_node.__str__(), "<Node (break)>")
def test_continue_node(self):
"""Test the continue node."""
context = env.empty_context()
continue_node = ast.Continue()
self.assertEqual(continue_node.eval(context), NULL_LITERAL.value)
self.assertEqual(context.behaviour, ast.CONTINUE_BEHAVIOUR)
#self.assertEqual(continue_node.__str__(), "<Node (continue)>")
def test_call_node(self):
"""Test the function node."""
# Create sample namespace
sum_function = SumNode()
sgn1 = env.Value(lib.INTEGER, None, "a")
sgn2 = env.Value(lib.INTEGER, None, "b")
sum_function.children = [
ast.Identifier("a"),
ast.Identifier("b"),
]
context = env.empty_context()
func = env.Function([
env.Signature([sgn1, sgn2], sum_function),
], "my_func")
context.store(func)
arg1 = SumNode()
arg1.children = [
ast.Literal(env.Value(lib.INTEGER, 1)),
ast.Literal(env.Value(lib.INTEGER, 2)),
]
arg2 = SumNode()
arg2.children = [
ast.Literal(env.Value(lib.INTEGER, 3)),
ast.Literal(env.Value(lib.INTEGER, 4)),
]
call_node = ast.Call("my_func")
call_node.children = [arg1, arg2]
self.assertEqual(call_node.eval(context), env.Value(lib.INTEGER, 10))
bad_node = ast.Call("missing")
self.assertRaises(Exception, bad_node.eval, context)
def test_operation_node(self):
"""Test the operation node."""
# Works completely like the call node
# Create sample namespace
sum_function = SumNode()
sgn1 = env.Value(lib.INTEGER, None, "a")
sgn2 = env.Value(lib.INTEGER, None, "b")
sum_function.children = [
ast.Identifier("a"),
ast.Identifier("b"),
]
context = env.empty_context()
func = env.Function([
env.Signature([sgn1, sgn2], sum_function),
])
operator = env.Operator(func, "+")
context.store(operator)
arg1 = SumNode()
arg1.children = [
ast.Literal(env.Value(lib.INTEGER, 1)),
ast.Literal(env.Value(lib.INTEGER, 2)),
]
arg2 = SumNode()
arg2.children = [
ast.Literal(env.Value(lib.INTEGER, 3)),
ast.Literal(env.Value(lib.INTEGER, 4)),
]
call_node = ast.Operation("+")
call_node.children = [arg1, arg2]
self.assertEqual(call_node.eval(context), env.Value(lib.INTEGER, 10))
bad_node = ast.Operation("?")
self.assertRaises(Exception, bad_node.eval, context)
def test_cast_node(self):
"""Test the cast node."""
context = env.empty_context()
context.store(lib.INTEGER)
cast_node = ast.Cast(lib.INTEGER.name)
cast_node.children = [NULL_LITERAL]
self.assertEqual(cast_node.eval(context), INT_LITERAL.value)
bad_node = ast.Cast("missing")
self.assertRaises(Exception, bad_node.eval, context)
def test_identifier_node(self):
"""Test the identifier node."""
context = env.empty_context()
# Search in local ns
context.store(STRING_LITERAL.value)
ident_node = ast.Identifier(STRING_LITERAL.value.name)
self.assertEqual(ident_node.eval(context), STRING_LITERAL.value)
# Search in parent ns
context.substitute()
self.assertEqual(ident_node.eval(context), STRING_LITERAL.value)
# Identifier does not exist
bad_node = ast.Identifier("missing")
self.assertRaises(Exception, bad_node.eval, context)
def test_literal_node(self):
"""Test the literal node."""
context = env.empty_context()
self.assertEqual(NULL_LITERAL.eval(context), NULL_LITERAL.value)
self.assertEqual(STRING_LITERAL.eval(context), STRING_LITERAL.value)
self.assertEqual(TRUE_LITERAL.eval(context), TRUE_LITERAL.value)
self.assertEqual(FALSE_LITERAL.eval(context), FALSE_LITERAL.value)
def test_declaration_node(self):
"""Test the declaration node."""
context = env.empty_context()
context.store(env.NULL)
decl_node = ast.Declaration("val", "null")
self.assertEqual(decl_node.eval(context), NULL_LITERAL.value)
self.assertEqual(context.find("id", "val"), NULL_LITERAL.value)
self.assertRaises(env.RuntimeException, decl_node.eval, context)
def test_assignment_node(self):
"""Test the assignment node."""
context = env.empty_context()
context.store(env.Value(lib.INTEGER, 1, "value"))
missing_asgn = ast.Assignment("missing")
self.assertRaises(env.NamespaceException, missing_asgn.eval, context)
bad_asgn = ast.Assignment("value")
bad_asgn.add(STRING_LITERAL)
self.assertRaises(env.AssignmentException, bad_asgn.eval, context)
asgn_node = ast.Assignment("value")
asgn_node.add(INT_LITERAL)
self.assertEqual(asgn_node.eval(context), INT_LITERAL.value)
self.assertEqual(context.find("id", "value"), INT_LITERAL.value)
def test_syntax_tree(self):
"""Test the syntax_tree method."""
syntax_tree = ast.syntax_tree()
self.assertTrue(syntax_tree is not None)
self.assertEqual(syntax_tree.name, ast.Sequence.name)
def test_run_in_substitution(self):
"""Test the run_in_substitution method."""
context = env.empty_context()
access_node = AccessNode()
result = ast.run_in_substitution(access_node, context)
self.assertEqual(result, STRING_LITERAL.value)
self.assertRaises(Exception, context.find, "id",
STRING_LITERAL.value.name)
|
import math
x1, y1 = input().split()
x2, y2 = input().split()
x1 = float(x1)
x2 = float(x2)
y1 = float(y1)
y2 = float(y2)
dist = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
print("%.4f" % dist)
|
n = int(input())
horas = n / 3600
resto = n % 3600
minutos = resto / 60
resto = resto % 60
segundos = resto
print("%d:%d:%d" % (horas, minutos, segundos))
|
# 2. 두 수를 입력 받아서 두 수의 차이를 출력하는 프로그램
a=int(input("input : "))
b=int(input("input : "))
if a>b:
print(a-b)
else:
print(b-a)
|
people = ['홍', '이', '김', '이', '이', '김']
def max_count(people):
counts = {}
for i in people:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
return counts
counts = max_count(people)
print(max(counts.values())) |
# 1. 두 수를 입력 받아서 큰 수를 출력하는 프로그램
a=int(input("input : "))
b=int(input("input : "))
if a>b:
print(a)
else:
print(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.