text
stringlengths 37
1.41M
|
---|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
outcome = [x**2 for x in range(1,11)]
#x**2 is the output expression
#x is the variable
#range(1,11) is the input sequence
outcome
# In[ ]:
|
filename = 'full_text_small.txt'
def file_write(filename):
with open(filename, 'r') as f:
n = 0
for line in f:
n += 1
if n <= 5:
print(line)
return(line)
file_write(filename)
|
from numpy import sqrt
def isPrime(n):
if (n<0):
return False
if (n%2==0):
return False
for i in range(3, int(sqrt(n))+1, 2):
if (n%i==0):
return False
return True
def formulaCount(a, b):
n = 0
while( isPrime(n*n+a*n+b) ):
n += 1
return n
solution = 0, 0
count = 0
for a in range(-999, 1000):
for b in range(-1000, 1001):
tmp = formulaCount(a, b)
if (tmp>count):
count = tmp
solution = a, b
print("a= {}, b= {}, c= {}: solution= {}".format(solution[0], solution[1], count, solution[0]*solution[1]))
|
from functions import isPalindrom, binary
solution = 0
for n in range(1, 10**6):
if isPalindrom(n) and isPalindrom(binary(n)):
solution += n
print(solution)
|
# 팩토리얼 구현
# 5! = 120
num = int(input("자연수 입력 : "))
fac = 1
for i in range(1, num + 1):
fac = fac * i
print(f'{num} 팩토리얼은 {fac}입니다.')
|
import random
arr = list()
print(arr)
for i in range(10):
arr.append(random.randint(1, 100))
print("*" * 40)
print(arr)
print("*" * 40)
# 이 리스트 안에서 가장 큰 값을 출력하시오
arr.sort()
print(arr[-1])
# 2번째 값도 출력하깅
print(arr[1])
li = []
# 가수 세 명을 입력 받기
for i in range(0, 3, 1):
li.append(input('가수 이름을 쓰세요 : '))
print('-' * 20)
print(li)
print(f'리스트 개수 {len(li)}개 입니다.')
|
def f_iter(n):
r = 1
for i in range(1, n + 1):
r *= i
return r
def f_rec(n):
if n <= 1:
return 1
else:
return n * f_rec(n-1)
print(f_iter(5))
print(f_rec(5))
# iter 1에서 올리며 팩토리얼
# rec 재귀적인 표현 팩토리얼
# 줄이고 줄이고
|
# for a in range(1,10):
# for b in range(1,10):
# if b == 9 :
# print('{} x {} = {:0>2}'.format(a,b,a*b))
# else :
# print ('{} x {} = {:0>2}'.format(a,b,a*b),end=', ')
# for _ in range(5) :
# for _ in range(5) :
# print('*',end=' ')
# print()
# for out in range(5) :
# for i in range(out+1) :
# print('*',end=' ')
# print()
# for out in range(5) :
# for i in range(out+1) :
# if i == out :
# print('*')
# else:
# print(' ',end=' ')
st = [5,5,5]
print(st)
tp = (6,6,6)
print(tp)
|
"""name='Mason'
age=20
food='라멘'
print('이름은:{},나이:{},음식:{}'.format(name,age,food))
price = 100
num = input('사탕 몇 개 줄까요? ') #str
print('총 {}원입니다.'.format(int(num)*price)) #총 가격 """
# p_score = int(input ('파이썬 점수 입력 : '))
# c_score = int(input ('C언어 점수 입력 : '))
# j_score = int(input ('자바 점수 입력 : '))
# print('평균 = {}'.format((p_score+c_score+j_score)/3))
green = '오늘 점심은 뭘 먹을까?'
print(green)
# print(green[0])
# print(green[12])
# print(green[0:2])
# print(green[3:5])
# print(green[3:2+1])
# print(green[len(green)-1])
# print(green[0:13:1])
# print(green[9:12])
# print(green[-1])
# print(green[-5:])
# print(green[5:7:1])
print(green[::-1])
import random
char=random.choice(green)
print(char)
print(green.count(" "))
|
# print(dir(list))
# print(help(list.reverse))
#list 추가하는 방법
st = [1,2,3,4,5]
st[5:] = [6,7]
print(st)
# st.insert(5,6)
# st.insert(6,7)
# print(st)
# del st[2]
# print(st)
st[2:4]=[4]
print(st)
# st.remove(3)
# print(st)
st[5:0]=[100]
print(st)
# st.insert(5,100)
# print(st)
|
# st4 = [d for d in range(1,7)]
# print(st4)
# st1 = [1,2,3,4,5]
# # st2 = []
# # for d in st1 :
# # st2.append(d*3)
# st2 = [d*3 for d in st1] #List comprehension
# print(st2)
# st = [1.2,3.4,5.6,7.8,9.9]
# # for i in range(len(st)) :
# # st[i] = int(st[i])
# st2 = [int(st[i]) for i in range(len(st))]
# print(st2)
# st1 = [100,80,92,75,85]
# # st2 = []
# # for d in st1 :
# # if d > 80 :
# # st2.append(d)
# st2 = [d for d in st1 if d>80 and d<90]
# print(st2)
# st1 = ['a','b','c']
# st2 = [1,2,3,4,5]
# # st3 = []
# # for f in st1 :
# # for s in st2 :
# # st3.append(f+str(s))
# st3 = [f+str(s) for f in st1 for s in st2]
# print(st3)
# print([3*i for i in range(1,10)])
# print(list(3*i for i in range(1,10)))
# print(tuple(3*i for i in range(1,10)))
# print([i*j for i in range(2,10) for j in range(1,10)])
# a = ['alpha','bravo','delta','charlie','echo','foxtrot','golf','hotel','india']
# # for i in range(len(a)) :
# # if len(a[i]) > 4 :
# # print(a[i])
# print([a[i] for i in range(len(a)) if len(a[i]) > 4])
# 2의 거듭제곱 리스트 만들기
a = int(input())
b = int(input())
# c = []
# for i in range(a,b+1):
# c.append(pow(2,i))
# print(c)
print([pow(2,i) for i in range(a,b+1) ])
# print(help(pow))
# print(help(range))
|
# -*- coding:utf-8 _*-
"""
@file: test.py
@time: 2021/03/01
@site:
@software: PyCharm
# code is far away from bugs with the god animal protecting
I love animals. They taste delicious.
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
# def fun(l=None):
# if l is None:
# l = []
# l.append(1)
# return l
#
#
# fun()
# fun()
# x = fun()
# print(x)
import inspect
def num():
return [lambda x:i*x for i in range(4)]
# num 函数 等价于 func()
def func():
fun_lambda_list = []
for i in range(4):
def lambda_(x):
return x * i
fun_lambda_list.append(lambda_)
return fun_lambda_list
for m in num():
print(inspect.getsource(m))
print(m(2))
print([m(2) for m in num()]) #[6,6,6,6]
# 一行打印 九九乘法表
print('\n'.join([' '.join(["%2s x%2s = %2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
|
def main ():
number = 533
h_code = hamming_code(number)
decoded_number = decode_from_hamming_code(h_code)
print(f'Hamming code of input number({number}): {h_code}')
print(f'Decodeding result: {decoded_number}')
print('\n\nTest:\n')
test_h_code = dec_to_bin(int(h_code, 2) ^ 1 << 4)
print(f'Hamming code with mistake: {test_h_code}')
test_decoded_number = decode_from_hamming_code(test_h_code)
print(f'Decoded number: {test_decoded_number}\n')
print('Checking...\n')
if decoded_number == test_decoded_number :
print('Result: Done')
else :
print('Result: Error')
def dec_to_bin(number):
return bin(number)[2:]
def count_bin_number(number):
return len(number.replace('0', ''))
def hamming_code(number):
bin_code = dec_to_bin(number)
m = len(bin_code)
redundant_bits = calcRedundantBits(m)
h_code = posRedundantBits(bin_code, redundant_bits)
h_code = calcParityBits(h_code, redundant_bits)
return h_code
def decode_from_hamming_code(h_code):
r = calcRedundantBits(len(h_code), full_code=True)
pos_r_bits = [2**i - 1 for i in range(r)]
h_code = h_code[::-1]
r_bits = ''
number = ''
for i in range(len(h_code)):
if i in pos_r_bits:
r_bits += h_code[i]
else :
number += h_code[i]
h_code_decoded_number = hamming_code(int(number[::-1], 2))[::-1]
if h_code_decoded_number != h_code:
r_bits_decoded_number = ''
for i in range(r):
r_bits_decoded_number += h_code_decoded_number[pos_r_bits[i]]
wrong_bit = 0
for i, j, k in zip(range(r), r_bits, r_bits_decoded_number):
if j != k:
wrong_bit += 2 ** i
if h_code[wrong_bit - 1] == '0':
h_code = h_code[:wrong_bit - 1] + '1' + h_code[wrong_bit:]
else:
h_code = h_code[:wrong_bit - 1] + '0' + h_code[wrong_bit:]
number = decode_from_hamming_code(h_code[::-1])
if isinstance(number, int):
return number
return int(number[::-1], 2)
def calcRedundantBits(m, full_code = False):
'''
Use the formula 2 ^ r >= m + r + 1
to calculate the no of redundant bits.
'''
if not full_code:
for i in range(m):
if 2 ** i >= m + i + 1:
return i
else :
for i in range(m):
if 2 ** i >= m + 1:
return i
def posRedundantBits(data, r):
'''
Redundancy bits are placed at the positions
which correspond to the power of 2.
'''
j = 0
k = 1
m = len(data)
res = ''
for i in range(1, m + r+1):
if(i == 2**j):
res = res + '0'
j += 1
else:
res = res + data[-1 * k]
k += 1
return res[::-1]
def calcParityBits(arr, r):
n = len(arr)
for i in range(r):
val = 0
for j in range(1, n + 1):
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])
arr = arr[:n-(2**i)] + str(val) + arr[n-(2**i)+1:]
return arr
def detectError(arr, r):
n = len(arr)
res = 0
for i in range(r):
val = 0
for j in range(1, n + 1):
if(j & (2**i) == (2**i)):
val = val ^ int(arr[-1 * j])
res = res + val*(10**i)
return int(str(res), 2)
if __name__ == '__main__':
main()
|
import numpy as np
from game.Constants import NB_COLUMNS, NB_ROWS, COMPUTER
from game.Game import Game
MAX_SCORE = 1
SCORE_DECREASE_RATE = 0.9
# Generate a lot of games, feeding the results to the given learning strategy.
# The playing strategy of the 2 players can be either the learning strategy, but also another strategy if required.
def generate(nb_games, nb_games_per_learning_iteration, learning_strategy, playing_strategy1, playing_strategy2):
game = Game(False, playing_strategy1, playing_strategy2)
boards_with_score = np.empty((0, NB_ROWS * NB_COLUMNS + 1))
for game_no in range(nb_games):
boards_from_game = np.empty((0, NB_ROWS * NB_COLUMNS))
game.start()
win = False
if game.nb_moves > 0:
# if a move has been made automatically, it was the computer that had to make the opening move
# hence, we don't need the factor that's 4 lines down.
adapted_board_state = game.board.state.copy().reshape((1, NB_ROWS * NB_COLUMNS))
boards_from_game = np.insert(boards_from_game, 0, adapted_board_state, axis=0)
while not game.board.finished:
factor = 1 if game.turn == COMPUTER else -1 # learn all boards from the computer's perspective
_, win = game.let_computer_play()
adapted_board_state = factor * game.board.state.copy().reshape((1, NB_ROWS * NB_COLUMNS))
boards_from_game = np.insert(boards_from_game, 0, adapted_board_state, axis=0)
score = MAX_SCORE
score_switch_factor = -1
if not win:
score = MAX_SCORE / 2
score_switch_factor = 1
for board in boards_from_game:
board_with_score = np.append(board, score)
boards_with_score = np.insert(boards_with_score, 0, board_with_score, axis=0)
if score > 0:
# the state that allowed the opponent to win should be scored as badly as the win itself
score = score_switch_factor * score
else:
score = score_switch_factor * score * SCORE_DECREASE_RATE
if (game_no > 0) & (game_no % nb_games_per_learning_iteration == 0):
learning_strategy.learn_from(boards_with_score)
boards_with_score = np.empty((0, NB_ROWS * NB_COLUMNS + 1))
if len(boards_with_score) != 0:
learning_strategy.learn_from(boards_with_score)
|
import math
rediusString = raw_input("Enter the radius of your circle: ")
radiusInteger = int(radiusString)
circumference = 2 * math.pi * radiusInteger
area = math.pi * (radiusInterger ** 2)
print "The circumference is: ", circumference, ", and the area is :", area
|
"""
AI agent that solves the n-sliding puzzle game through various search algorithms
Starting the script
-------------------
python driver.py <method> <board>
Parameters
----------
The method argument will be one of the following.
bfs (Breadth-First Search)
dfs (Depth-First Search)
ast (A-Star Search)
ida (IDA-Star Search)
The board argument will be a comma-separated list of integers containing no spaces that represents
that initial state of the puzzle board
Example Script Execution
-----------------
python driver.py bfs 0,8,7,6,5,4,3,2,1
Output
------
When executed, the program will write to a file called output.txt, containing the following statistics:
path_to_goal: the sequence of moves taken to reach the goal
cost_of_path: the number of moves taken to reach the goal
nodes_expanded: the number of nodes that have been expanded
fringe_size: the size of the frontier set when the goal node is found
max_fringe_size: the maximum size of the frontier set in the lifetime of the algorithm
search_depth: the depth within the search tree when the goal node is found
max_search_depth: the maximum depth of the search tree in the lifetime of the algorithm
running_time: the total running time of the search instance, reported in seconds
max_ram_usage: the maximum RAM usage in the lifetime of the process reported in megabytes
"""
import sys
import boardState
import Board
method = sys.argv[1]
board = sys.argv[2]
startState = boardState.BoardState(None, board, [])
puzzleBoard = Board.Board(startState)
print(puzzleBoard.board)
if method == "bfs":
print("")
elif method == "dfs":
print("")
elif method == "ast":
print("")
elif method == "ida":
print("")
|
#!/usr/bin/env python
#A python function that takes
#an ip_range ex: (192.168.1-254.0-255) or
#192.168.1.0-255) and appends every ip
#to a returned list for other uses.
#Use it if you would like or email me with
#a better one.
#d3hydr8[at]gmail[dot]com
import sys
def getips(ip_range):
lst = []
iplist = []
ip_range = ip_range.rsplit(".",2)
if len(ip_range[1].split("-",1)) ==2:
for i in range(int(ip_range[1].split("-",1)[0]),int(ip_range[1].split("-",1)[1])+1,1):
lst.append(ip_range[0]+"."+str(i)+".")
for ip in lst:
for i in range(int(ip_range[2].split("-",1)[0]),int(ip_range[2].split("-",1)[1])+1,1):
iplist.append(ip+str(i))
return iplist
if len(ip_range[1].split("-",1)) ==1:
for i in range(int(ip_range[2].split("-",1)[0]),int(ip_range[2].split("-",1)[1])+1,1):
iplist.append(ip_range[0]+"."+str(ip_range[1].split("-",1)[0])+"."+str(i))
return iplist
iplist = getips(sys.argv[1])
print "Length:",len(iplist)
|
class LinkedList:
class Node:
def __init__(self,value,next=None,previous=None):
self.value=value
self.next=next
self.previous=previous
def __init__(self):
self._first=None
self._last=None
self._count=0
def _old_add(self,value):
new_node=LinkedList.Node(value)
ptr=self._first
if ptr==None: #list is empty
self._first=new_node
else:
while ptr.next!=None:
ptr=ptr.next
new_node.previous=ptr
ptr.next=new_node
def add(self,value):
new_node=LinkedList.Node(value)
new_node.next=None
new_node.previous=self._last
if self._count==0: # list is empty
self._first=new_node
else:
self._last.next=new_node
self._last=new_node
self._count+=1
def size(self):
return self._count
def _locate(self,index=None):
if index==None:
index=self._count-1 #defaults to last node
if index>=self._count:
raise IndexError('invalid index {}'.format(index))
if index==self._count-1: return self._last
if index==0: return self._first
ptr=self._first
for i in range(0,index):
ptr=ptr.next
return ptr
def get(self,index):
return self._locate(index).value
def set(self,index,value):
self._locate(index).value=value
def remove(self,index=None):
del_node=self._locate(index)
# logic to remove the value from the list
if del_node is self._first:
self._first=del_node.next
else:
del_node.previous.next=del_node.next
if del_node is self._last:
self._last=del_node.previous
else:
del_node.next.previous=del_node.previous
value=del_node.value
del del_node
self._count-=1
return value
def info(self):
s='LinkedList(\t'
ptr=self._first
while ptr!=None:
s+='{}\t'.format(ptr.value)
ptr=ptr.next
s+=")"
return s
|
import threading as t
import sys
class CountDownTask:
def __init__(self, max,min=0,name=None):
self._min=min
self._max=max
self._name=name
self._thread=t.Thread(target=self.count_down,name=name)
self._thread.start()
def count_down(self):
name=self._name if self._name!=None else t.current_thread().name
print('{}:starts'.format(name))
count=self._max
while count>=self._min:
print('{}: counts {}'.format(name,count))
count-=1
print('{}: ends'.format(name))
def main(name,args):
c1=CountDownTask(50,name='marker')
c2=CountDownTask(50,30)
print('end of program')
if __name__=='__main__':
main(sys.argv[0],sys.argv[1:])
|
import threading as t
import sys
class CountDownThread(t.Thread):
def __init__(self,max,min=0,**kwargs):
name=kwargs.get('name')
super(CountDownThread,self).__init__(name=name,kwargs=kwargs)
self._max=max
self._min=min
def run(self):
name=t.current_thread().name
max=self._max
while max>=self._min:
print('{} counts {}'.format(name,max))
max-=1
print('{} ends'.format(name))
def main(name,args):
t1=CountDownThread(30,name='marker')
t2=CountDownThread(50,30)
t1.start()
t2.start()
print('end of program')
if __name__=='__main__':
main(sys.argv[0],sys.argv[1:])
|
n=input()
if n==n[::-1]:
print('是回文字符串')
else :
print('不是回文字符串')
|
"""
To test Double linkedlist and Tree
"""
class Dlist:
def __init__(self):
self.val = []
self.left = None
self.right = None
class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def build_tree():
root = Node(0)
root.left = Node(-1)
root.right = Node(1)
return root
if __name__ == '__main__':
root = build_tree()
print(root.left.val, " ", root.val, " ", root.right.val)
dl = Dlist()
dl.val.append(1)
dl.val.append(2)
dl.val.append(4)
for x in dl.val:
print(x, end=" - ")
|
#!/usr/bin/python3
from numpy import exp, arange, int32, array
# The pre-computed factorial numbers.
factorials = {
2 : array([1, 1, 2]),
3 : array([1, 1, 2, 6]),
4 : array([1, 1, 2, 6, 24]),
5 : array([1, 1, 2, 6, 24, 120]),
6 : array([1, 1, 2, 6, 24, 120, 720]),
7 : array([1, 1, 2, 6, 24, 120, 720, 5040]),
8 : array([1, 1, 2, 6, 24, 120, 720, 5040, 40320])
}
def tang_toennies(n, r, E):
""" The Tang-Toennies damping function. The equation is:
f_{n}(r) = 1.0 - \exp{(-Er)}\sum_{i=0}^{k}{\frac{(Er)^k}{k!}}
where n is the order, r is the damping target and E is the coefficient.
Parameters
----------
n : int
The order of the damping function.
r : float
The damping target.
E : float
The damping coefficient.
Returns
-------
v : float
The damping result.
"""
Er = E * r
k = arange(0, n+1, dtype=int32)
return 1.0 - exp(-Er) * ((Er**k / factorials[n]).sum())
if __name__ == '__main__':
print("Value of tang_toennis damping function: ", tang_toennies(8, 8.0, 1.2))
|
import inline
import numpy as np
import matplotlib.pyplot as plt
from numpy import number
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
seed =1 # seed for random number generation
numInstances = 200 # number of data instances
np.random.seed(seed)
X = np.random.rand(numInstances,1).reshape(-1,1)
y_true = -3*X+1
y = y_true + np.random.normal(size=numInstances).reshape(-1,1)
numTrain = 20 #number of training instances
numTest = numInstances - numTrain
X_train = X[:-numTest]
X_test = X[-numTest:]
y_train = y[:-numTest]
y_test = y[-numTest:]
#Create linear regression object
regr = linear_model.LinearRegression()
#Fit regression model to the training set
regr.fit(X_train,y_train)
print(regr)
|
from pandas import DataFrame
cars = {'make': ['Ford','Honda','Toyota','Tesla'],
'model':['Taurus','Accord','Camry','Model S'],
'MSRP' : [27595,23570,23495,68000]}
carData2 = DataFrame(cars,index = [1,2,3,4]) #change the row index
carData2['year'] = 2018 #ad column with same value
carData2['dealership'] = ['Courtesy Ford','Capital Honda','Spartan Toyota','N/A']
#accessing a specific element of the DataFrame
print(carData2)
print(carData2.iloc[1,2]) #retrieving second row. third column
print(carData2.loc[1,'model']) #retrieving second row. column named 'model'
#accessing a slice of the DataFrame
print('carData2.iloc[1:3,1:3] = ')
print(carData2.iloc[1:3,1:3])
|
import numpy as np
my2darr = np.arange(1,13,1).reshape(3,4)
print(my2darr)
divBy3 = my2darr[my2darr % 3 ==0]
print(divBy3,type(divBy3))
divBy3LastRow = my2darr[2:, my2darr[2,:] % 3==0]
print(divBy3LastRow)
|
def squared(x):
"""
Takes an int and returns it multiplied by 2.
:param x: int.
:return: x multiplied by 2.
"""
return x ** 2
print(squared(5))
|
class Horse:
def __init__(self, weight, name, rider):
self.weight = weight
self.name = name
self.rider = rider
class Rider:
def __init__(self, height, weight, name):
self.height = height
self.weight = weight
self.name = name
yutaka = Rider(170, 50, "Yutaka Take")
kitasanblack = Horse(543, "Kitasanblack", yutaka)
print("The name of Horse is {}".format(kitasanblack.name))
print("The name of Rider is {}".format(kitasanblack.rider.name))
|
def string_to_float(x):
"""
Converts passed in str to int.
:param x: str.
:return: string converted to int.
"""
try:
return float(x)
except ValueError:
print("It can not convert 'string' to 'float'.")
y = string_to_float("aaa")
print(y)
|
# -*- coding: utf-8 -*-
# @公众号 :Web图书馆 代码详解:http://t.cn/A6Ihdrxf
# @Software: PyCharm 安装教程:https://mp.weixin.qq.com/s/a0zoCo9DacvdpIoz1LEN3Q
# @Description:
# Python全套学习资源:https://mp.weixin.qq.com/s/G_5cY05Qoc_yCXGQs4vIeg
import pandas as pd
students = pd.read_excel('C:/Temp/Students_Duplicates.xlsx')
dupe = students.duplicated(subset='Name')
dupe = dupe[dupe == True] # dupe = dupe[dupe]
print(students.iloc[dupe.index])
print("=========")
students.drop_duplicates(subset='Name', inplace=True, keep='last')
print(students)
|
# -*- coding: utf-8 -*-
# @公众号 :Web图书馆 代码详解:http://t.cn/A6Ihdrxf
# @Software: PyCharm 安装教程:https://mp.weixin.qq.com/s/a0zoCo9DacvdpIoz1LEN3Q
# @Description:
# Python全套学习资源:https://mp.weixin.qq.com/s/G_5cY05Qoc_yCXGQs4vIeg
import pandas as pd
import matplotlib.pyplot as plt
students = pd.read_excel('C:/Temp/Students.xlsx')
students.sort_values('Number', inplace=True, ascending=False)
print(students)
students.plot.bar(x='Field', y='Number', color='blue', title='International Students by Field')
plt.tight_layout()
plt.show()
|
from bitarray import bitarray
import bitstring
def str_to_binary(s):
"""
Converts input string into binary.
:param s: (str) input
:return: (List[int]) list of bits
"""
bits = bitarray()
bits.frombytes(s.encode('utf-8'))
return bits.tolist(True)
def binary_to_str(bits):
"""
Converts a list of bits
:param bits: (List[int])
:return: (str)
"""
return bitarray(bits).tobytes().decode('utf-8')
def int_to_binary(z, nbits=8, signed=False):
"""
Converts an integer into its binary representation.
:param z: (int) integer
:param nbits: (int) number of bits needed
:param signed: (bool) whether to use signed binary
representation of integers
:return: (bitstring.BitArray)
"""
if signed:
return bitstring.BitArray(int=z, length=nbits)
else:
return bitstring.BitArray(uint=z, length=nbits)
def binary_to_int(b, signed=False):
"""
Converts a binary representation into an integer.
:param b: (bitstring.BitArray)
:param signed: (bool) whether binary
representation is signed
:return: (int)
"""
return b.int if signed else b.uint
def float_to_binary(f, nbits=64):
"""
Converts a float to its binary representation.
:param f: (float)
:param nbits: (int) number of bits used to represent
the input float
:return: (bitstring.BitArray)
"""
return bitstring.BitArray(float=f, length=nbits)
def binary_to_float(b):
"""
Converts a binary representation to its float.
:param b: (bitstring.BitArray)
:return: (float)
"""
return b.float
|
def chunk(L,x):
x = int(x)
chunked = [L[i:i+x] for i in range(0,int(len(L)),x)] #Divide the list of inputs into smaller lists equal in size to the time step x
return chunked
def consolidate(L,x):
x = int(x)
chunked_list = chunk(L,x) #Divide the list of inputs into smaller lists equal in size to the time step x
consolidated_list = [round(sum(chunked_list[i])/x) for i in range(len(chunked_list))] #Average each of the smaller lists and round the result
for i in consolidated_list:
if i == 1:
i = True
else:
i = False
return consolidated_list
|
# mode='a' (append): ファイルの最後尾に内容を追加
# with open("writing_file.txt", mode='a') as f:
# f.write("mode=a appends text")
# mode='r+': 読み書きどちらも可能
# with open("writing_file.txt", mode='r+') as f:
# f.write("You can write and read with r+ mode!!")
# print(f.read())
# f.write("This should be the last sentence.")
# mode='w+': 読み書きどちらも可能 Truncateされることに注意
# with open("writing_file.txt", mode='w+') as f:
# print(f.read())
# f.write("You can write and read with w+ mode!!")
# f.seek(0)
# print(f.read())
# mode='a+': 読み書きどちらも可能で、positionが最後尾から始まり、truncateされない
with open("writing_file.txt", mode="a+") as f:
print(f.read())
f.write("\nYou add sentences to the last of the file content with a+ mode.")
f.seek(0)
print(f.read())
|
import sys
input = sys.stdin.readline
def get_bin(N):
if N == 0 or N == 1:
return str(N)
return get_bin(N//2) + str(N%2)
if __name__ == '__main__':
N = int(input().strip())
print(get_bin(N))
|
def check_pixel(pixel, n):
check = pixel[0][0]
temp = -1
for i in range(n):
for j in range(n):
temp = pixel[i][j]
if temp != check:
return -1
return check
def slice_pixel(pixel, n, r, c):
sliced_num = int(n/2)
sliced_pixel = []
for i in range(r*sliced_num, r*sliced_num + sliced_num):
temp = ""
for j in range(c*sliced_num, c*sliced_num + sliced_num):
temp += pixel[i][j]
sliced_pixel.append(temp)
temp = ""
return sliced_pixel
ans = ""
def zip_pixel(pixel, n):
global ans
if check_pixel(pixel, n) == '0':
ans += "0"
elif check_pixel(pixel, n) == "1":
ans += "1"
elif check_pixel(pixel, n) == -1:
ans += "("
for i in range(2):
for j in range(2):
zip_pixel(slice_pixel(pixel, n, i, j), int(n/2))
ans += ")"
n = int(input())
pixel = []
for i in range(n):
sliced_pixel = input()
pixel.append(sliced_pixel)
zip_pixel(pixel, n)
print(ans)
|
'''
분해합
'''
def decomposite_num(num):
answer = num
while num > 0:
answer += num % 10
num //= 10
return answer
def find_creator():
n = int(input())
digit_n = int(len(str(n))) #n 자릿수 구하기
if n < 18:
for test_num in range(1, n):
if decomposite_num(test_num) == n:
return test_num
return 0
else:
for test_num in range(n - 9*digit_n, n):
if decomposite_num(test_num) == n:
return test_num
return 0
print(find_creator())
|
def cantor(n):
if n == 0 :
return '-'
elif n >= 1 :
return cantor(n-1) + ' '*(3**n-1) + cantor(n-1)
while True :
try :
n = int(input())
answer = cantor(n)
print(answer)
except :
break
|
def sugar_plz(sugar):
count = 0
while sugar >= 0:
if sugar % 5 == 0:
count += (sugar // 5)
print(count)
return
sugar -= 3
count += 1
print(-1)
return
if __name__ == "__main__":
sugar = int(input())
sugar_plz(sugar)
|
n = int(input())
arr = []
for _ in range(n):
arr.append(int(input()))
def merge_arr(a, b):
result = []
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
if i == len(a):
while j < len(b):
result.append(b[j])
j += 1
else:
while i < len(a):
result.append(a[i])
i += 1
return result
def merge_sort(arr):
if len(arr) <= 1:
return arr
left = merge_sort(arr[:len(arr) // 2])
right = merge_sort(arr[len(arr) // 2:])
result = merge_arr(left, right)
return result
arr = merge_sort(arr)
for element in arr:
print(element)
|
import math
n = int(input())
base_star = [" * ", " * * ", "*****"]
cnt = int(math.log(n/3, 2))
def make_triangle(base_star, n, cnt):
if cnt == 0:
return base_star
new_star = []
space = ' ' * (int(n/2))
for i in range(len(base_star)):
new_star.append(space + base_star[i] + space)
for i in range(len(base_star)):
new_star.append(base_star[i] + ' ' + base_star[i])
cnt -= 1
return make_triangle(new_star, n*2, cnt)
star = make_triangle(base_star, 6, cnt)
for i in range(len(star)):
print(star[i].replace('\0', ''), sep='')
|
def hanoi(num, _from, tmp, to):
if num == 1:
print(_from, to, end = ' ')
print()
else:
hanoi(num - 1, _from, to, tmp)
print(_from, to, end = ' ')
print()
hanoi(num - 1, tmp, _from, to)
hanoi_num = int(input())
print(pow(2,hanoi_num) - 1)
hanoi(hanoi_num, 1, 2, 3)
|
Q = int(input())
for _ in range(Q):
n, m = map(int,input().split())
importance = list(map(int,input().split()))
index = [0 for _ in range(n)]
index[m] = 'point'
cnt = 0
while True :
if importance[0] == max(importance):
cnt +=1
if index[0] == 'point':
print(cnt)
break
else :
importance.pop(0)
index.pop(0)
else:
importance.append(importance.pop(0))
index.append(index.pop(0))
|
# 0개 이상의 문자를 추가해서 팰린드롬 만들기
# 출력: 만들 수 있는 가장 짧은 팰린드롬의 길이
# 체크할 조건
# len(S) <= 1000
# 1. 각 문자의 양 옆을 살핀다.
# 양 옆 문자가 다르면 넘어간다.
# 같으면 다른 문자가 나오거나 끝이 나올 때까지 ++, --하며 살핀다.
# 서로 다른 문자가 나오면 넘어간다.
# 2. 문자열의 첫 부분이나 끝에 다다르면 남아있는 부분의 길이를 더해준다.
# 남은게 없으면 0을 더한다.
# 가장 짧은 팰린드롬의 길이로 갱신한다.
# def solution(string):
# min_length = float('inf')
# for i in range(len(string)):
# left, right, gap = i-1, i+1, 1
# while left >= 0 and right < len(string) and string[left] == string[right]:
# left -= 1
# right += 1
# gap += 1
# if left < 0 or right >= len(string):
# length = len(string) * 2 - (gap * 2 - 1)
# min_length = min(min_length, length)
# print(min_length)
# if __name__ == '__main__':
# solution(input())
# 반례: eeeffe
# 하나의 알파벳을 중심으로 양 옆을 비교하다보니 ff처럼 붙어있는 경우를 찾지 못한다.
# 문자열을 뒤집은 후 문자열 끝까지 일치하는 순간의 길이를 구한다.
def solution(string):
lst = list(string)
lst.reverse()
rev_string = ''.join(lst)
for i in range(len(string)):
for j in range(len(string)-i):
if string[j+i] != rev_string[j]:
break
else:
print(len(string) + i)
return
if __name__ == '__main__':
solution(input())
|
def how(n, guess):
n = str(n)
guess = str(guess)
strike = 0
ball = 0
for i in range(0, 3):
if n[i] == guess[i]:
strike += 1
else:
if n[i] in guess:
ball += 1
return (strike, ball)
N = int(input())
guesses = list()
for _ in range(N):
guesses.append(input())
res = [1 for _ in range(1000)]
for n in range(111, 1000): # 0이 들어간 것들이나 중복되는 것들 삭제...
str_n = str(n)
if '0' in str_n or str_n[0] == str_n[1] or str_n[1] == str_n[2] or str_n[0] == str_n[2]:
res[n] = 0
for n in range(111, 1000):
if res[n]:
for guess in guesses:
num = guess[:4]
strike = int(guess[4])
ball = int(guess[6])
if how(str(n), num) != (strike, ball):
res[n] = 0
break
cnt = 0
for n in range(111, 1000):
if res[n]:
# print(n)
cnt += 1
print(cnt)
|
#!/usr/bin/python3
import sys
def main():
if(len(sys.argv) == 2):
filename = sys.argv[1]
fo = open(filename,"r")
readF = fo.read()
readF = readF.lower()
readF = readF.split()
readF = [i.split('.',1)[0] for i in readF]
readF = list(set(readF))
readF = sorted(readF,reverse=True)
print("Hasil dari split dan sorting:")
print(readF)
else:
print("Format: ./tugas2.py [nama file text.txt]")
if __name__ == "__main__":
main()
|
Height=float(input("Enter your height in centimeters: "))
Weight=float(input("Enter your Weight in Kg: "))
Height = Height/100
BMI=Weight/(Height*Height)
print("Your Body Mass Index is: ",BMI)
if(BMI<=18.5):
print("Oops! You are underweight.")
elif(BMI<=24.9):
print("Awesome! You are healthy.")
elif(BMI<=29.9):
print("You are overweight.")
else:
print("You are Obese. Start Exercise.")
|
num =int(input("Number please:"))
def factorial(n):
x = 1
for i in range(n):
x = x * (n - i)
return x
print (factorial(num))
|
import random
board = ['''
>>>>>>>>>>Hangman<<<<<<<<<<
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
class Hangman:
# Método Construtor
def __init__(self, word):
self.word = word
# Método para adivinhar a letra
def guess(self, letter=''):
while True:
self.letter = input("guess a letter: ")
if len(self.letter) == 1 and self.letter.isalpha():
break
print("Enter a valid character")
def print_game_status(self, right_guesses=[], wrong_guesses=[]):
self.right_guesses = right_guesses
self.wrong_guesses = wrong_guesses
while True:
if all([self.letter in self.word, self.letter not in self.right_guesses,
self.letter not in self.wrong_guesses]):
self.right_guesses.append(self.letter)
break
elif all([self.letter not in self.word, self.letter not in self.right_guesses,
self.letter not in self.wrong_guesses]):
self.wrong_guesses.append(self.letter)
break
else:
print("Enter a different character!")
self.guess()
try:
print(board[len(self.wrong_guesses)])
except IndexError:
pass
print("Right guesses: %s \nWrong guesses: %s" % (self.right_guesses, self.wrong_guesses))
def hangman_won(self):
if all([letters in self.right_guesses for letters in self.word]):
return True
def rand_word():
with open("palavras.txt", "rt") as f:
bank = f.readlines()
print(bank[random.randint(0, len(bank))].strip())
return bank[random.randint(0, len(bank))].strip()
# Função Main - Execução do Programa
def main():
# Objeto
game = Hangman(rand_word())
while True:
# Enquanto o jogo não tiver terminado, print do status, solicita uma letra e faz a leitura do caracter
game.guess()
# Verifica o status do jogo
game.print_game_status()
# De acordo com o status, imprime mensagem na tela para o usuário
if game.hangman_won():
print('\nParabéns! Você venceu!!')
print('\nFoi bom jogar com você! Agora vá estudar!\n')
break
elif:
print('\nGame over! Você perdeu.')
print('A palavra era ' + game.word)
main()
|
from Homework6Regularization import getRawData, LinearRegression, nonLinearTransform, getTestError, getPredictions
import numpy as np
from random import randint
from LinearRegression import get_target_function
trainingPercent = 25 / 35
def splitTraining(trainingIndex=25, first=True):
"""helper function that takes the HW6 dta data set and then splits training group by TRAININGINDEX. if FIRST then
gets the first elements up to TRAININGINDEX. If LAST then gets all elements from TRAININGINDEX and to the end.
returns the same tuple as getRawData but then splits TRAININPUT and TRAINTARGET into train and validation sets"""
trainInput, trainTarget, testInput, testTarget = getRawData()
validationGroup = trainInput[trainingIndex:] if first else trainInput[:trainingIndex]
validationTarget = trainTarget[trainingIndex:] if first else trainTarget[:trainingIndex]
traingGroup = trainInput[:trainingIndex] if first else trainInput[trainingIndex:]
trainingTarget = trainTarget[:trainingIndex] if first else trainTarget[trainingIndex:]
return traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget
def shortenZVector(zData, kValue):
"""helper function that takes the array of z vectors returned by the NonLinear Transform method and shortens
each z vector to be only up to and including the kValue (ie if kValue = 3 then converts each z vector to be just
(1, z1, z2, z3)"""
newZData = []
for zPoint in zData:
newZData.append(zPoint[:kValue+1])
return np.array(newZData)
def validateModels(traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget,
kValues=[3,4,5,6,7]):
"""trains (using linear regression) models and then validates them. outputs the list of tuples. KVALUES is a list
of k values to denote up to what index of the nonLinear transform found in nonLinearTransform method we include
for the zData. Ie if it is 3 then transform input data to zVector of (1, z1, z2, z3)
(validation error, test error, transform Index) for problem 1"""
models = []
for k in kValues:
zData = shortenZVector(nonLinearTransform(traingGroup), k)
zValidation = shortenZVector(nonLinearTransform(validationGroup), k)
validationPredictions, e_inError, weights = LinearRegression(zData, trainingTarget, zValidation)
validationError = getTestError(validationPredictions, validationTarget)
zTestInput = shortenZVector(nonLinearTransform(testInput), k)
testPredictions = getPredictions(weights, zTestInput)
testError = getTestError(testPredictions, testTarget)
models.append((validationError, testError, k))
return models
traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget = splitTraining()
models = validateModels(traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget)
models.sort()
print(models)
# prints out the answer to question 1 and question 2 (first part of tuple is validation error. 2nd is test error 3rd is k value)
# had problems with this problem because my LinearRegression function in HW6 file was non linear transforming the inputs to
# to z space of k = 7 by default no matter the input so that was messing things up
print(models[0])
# sorting it by the 2nd element of the tuple
models.sort(key=lambda x: x[1])
problem1TestError = models[0][1]
# below prints out answers to problems 3 and 4. Basically, same as 1 and 2 but just trains on last 10 and validates on first 25
traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget = splitTraining(trainingIndex=25, first=False)
models = validateModels(traingGroup, trainingTarget, validationGroup, validationTarget, testInput, testTarget)
models.sort()
print(models)
# sorting it by the 2nd element of the tuple
models.sort(key=lambda x: x[1])
problem3TestError = models[0][1]
def problem5(pts, ptTwo):
""""""
distances = []
for pt in pts:
distance = np.sqrt((pt[0] - ptTwo[0])**2 + (pt[1] - ptTwo[1])**2)
distances.append((distance, pt))
return distances
# gets all the euclidean distances from the given points to the problem1 and 3 test errors. We basically make
# problem1 test error the x value and problem3 test error the y value. And then get euclidean distances between that
# point and the given (x, y) point
problem5pts = [(0.0, 0.1), (0.1, 0.2), (0.1, 0.3), (0.2, 0.2), (0.2, 0.3)]
distances = problem5(problem5pts, (problem1TestError, problem3TestError))
distances.sort()
print(distances)
def getAllbut(lst, index):
"""helper function that returns a new list that gets all elements except for the element at INDEX"""
newLst = []
for count, element in enumerate(lst):
if index != count:
newLst.append(element)
return newLst
def problem7():
"""problem 7. Which test cross validation"""
possibleX = [np.sqrt(np.sqrt(3) + 4), np.sqrt(np.sqrt(3) - 1), np.sqrt(9 + 4*np.sqrt(6)), np.sqrt(9 - np.sqrt(6))]
ro = -4
constantErrors = []
linearErrors = []
for roIndex, x in enumerate(possibleX):
ro = x
dataPoints = [(-1, 0), (ro, 1), (1, 0)]
constantRoError = []
linearRoError = []
for count, pt in enumerate(dataPoints):
trainingData = getAllbut(dataPoints, count)
validationData = dataPoints[count]
print(validationData)
# constant model is the the average 'y' value of the 2 training points
constantWeight = np.mean([value[1] for value in trainingData])
# basically just 'learn' the linear model by forming a line connecting the 2 training points
slope, intercept = get_target_function(trainingData[0], trainingData[1])
prediction = slope*validationData[0] + intercept
# inputMatrix = np.array([(1, dataPoint[0]) for dataPoint in trainingData])
# not sure why one step learning doesn't work here. gives me all the same cross validation error right now
# predictions, _, weights = LinearRegression(inputMatrix, [valueTarget[1] for valueTarget in trainingData], [validationData[1]])
constantError = (validationData[1] - constantWeight)**2
linearError = (validationData[1] - prediction)**2
constantRoError.append(constantError)
linearRoError.append(linearError)
constantErrors.append((np.mean(constantRoError), ro, roIndex))
linearErrors.append((np.mean(linearRoError), ro, roIndex))
return constantErrors, linearErrors
def extractPts(inputs):
"""extract input values for (x, y) points into 'input' (1, x) and a target (y)"""
x = []
y = []
for input in inputs:
x.append((1, inputs[0]))
y.append(inputs[2])
return x, y
def getPredictions(weights, inputs):
"""get list of predictions"""
predictions = []
for input in inputs:
predictions.append(np.sign(np.dot(weights, input)))
return predictions
def getRandomPt(points):
"""helper function that gets a random (x, y) point from the argument"""
randomIndex = randint(0, len(points) - 1)
return points[randomIndex]
def PLA(inputPts):
"""implmentation of the simple perception learning algorithm. Picks a randomly misclassified point and updates the
weights according to the equation found on pg 7 of the Learning From Data textbook (w(t+1) = w(t) + y(t)*x(t)"""
def findMisclassfied(weights, xy, inputPts, targets):
"""helper functions that takes in weights and uses the current weight vector to make predictions to compare
to the target values. Then outputs a list of points that are misclassified
xy - the actual (x, y) points
inputPts - the input points for the linear model ie (1, x) - 1 being the bias term
targets - the y values for the (x, y) points"""
predictions = getPredictions(weights, inputPts)
assert len(predictions) == len(targets)
misclassifiedPts = []
for index, predict in enumerate(predictions):
if predict != targets[index]:
misclassifiedPts.append(xy[index])
return misclassifiedPts
weights = np.array([0, 0])
inputX, inputY = extractPts(inputPts)
wrongPts = findMisclassfied(weights, inputPts, inputX, inputY)
while len(wrongPts) == 0:
randomWrongPt = getRandomPt(wrongPts)
weights += weights + randomWrongPt[1]*np.array([1, randomWrongPt[0]])
return weights
def createDataSet(N=10):
"""helper that returns points (x, y, target) for some random target functiont that is created"""
constant, linear = problem7()
print(constant)
print(linear)
|
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
self.output = list()
self._permuteUnique(list(), nums)
return self.output
def _permuteUnique(self, curr_arr, nums):
"""
Helper method to compute permutations recursively using a
local dict() to deal with duplicates
"""
mem = dict()
if not nums:
self.output.append(curr_arr)
return
for i, v in enumerate(nums):
if v in mem:
continue
else:
mem[v] = 1
new_arr = list(curr_arr)
new_arr.append(v)
self._permuteUnique(new_arr, nums[:i] + nums[i+1:])
|
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
grid = list()
# Initialize the 2D grid
for i in range(n):
temp = [0] * m
grid.append(temp)
# Topmost row are all 1's
for i in range(m):
grid[0][i] = 1
# Leftmost column are all 1's
for i in range(n):
grid[i][0] = 1
# All other spaces have a unique number of paths equal to
# the sum of the space above and to the left of it
for i in range(1, n):
for j in range(1, m):
grid[i][j] = grid[i][j-1] + grid[i-1][j]
return grid[n-1][m-1]
|
"""Grid class provides a template for data systems which implement grid
structures where the individual cells within the grid contain information
individual to the cell."""
class Grid:
#init Provides a default set of traits to each cell in the grid provided by
#the user. The grid is a two dimensional array and each cell is a dicionary
#where the key is the trait and the value is the state of the trait.
#x and y provide the dimensions of the grid and trait is a default
#dictionary which is assigned to each cell
def __init__(self,x,y,traits):
self.__width = x
self.__height = y
self.__grid = []
self.__traits = traits.keys()
for i in range(0,x):
self.__grid.append([])
for j in range(0,y):
self.__grid[i].append(traits.copy())
#Sets a value to a trait within a cell given the dimensions of the cell on
#the grid (x and y) and the trait and corresponding value to be assigned
#to the cell
def setValue(self,x,y,trait,value):
self.__grid[x][y][trait] = value
#The below function returns a value given a trait
def getValue(self,x,y,trait):
return self.__grid[x][y][trait]
#This function returns a two dimentional array which is the size of the grid
#and is populated with the states of a trait for each cell
def getTraitArray(self,trait):
traitArray = []
for i in range(0,self.__width):
traitArray.append([])
for j in range(0,self.__height):
traitArray[i].append(self.getValue(i,j,trait))
return traitArray
#This function takes in an array of traits and updates a each cell's
#trait according to the inputted array, similar to getTraitArray except it
#updates the traits given an array rather than getting an array
def updateTraitArray(self,trait,traitArray):
for i in range(0,self.__width):
for j in range(0,self.__height):
self.setValue(i,j,trait,traitArray[i][j])
#This function receives the coordinates of a cell, a trait and a value, and
#returns how many out of the eight adjacent cells have the trait at state
#value. The wrap parameter is used to distinguish how the cells at the edge
#of the grid handle adjacent cells. If wrap is True then the adjacent values
#which go off the grid wrap around and detect the cell on the opposite edge
#of the map. This creates continuous taurus shaped plane. If wrap is false
#then the cell at the edge of the map does not count the values that extend
#beyond the grid. If wrap is left as no value or False then it is considered
#as False. Otherwise wrap is True.
def getNumAdj(self,x,y,trait,value,*wrap):
#Local Constant
ADJ_VALS = [[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]
counter = 0
for i in range(0,len(ADJ_VALS)):
xVal = x+ADJ_VALS[i][0]
yVal = y+ADJ_VALS[i][1]
if wrap and wrap[0]:
if xVal == self.__width:
xVal = 0
if yVal == self.__height:
yVal = 0
if self.getValue(xVal,yVal,trait) == value:
counter += 1
else:
if not (xVal == self.__width or xVal < 0 or\
yVal == self.__height or yVal < 0) and \
self.getValue(xVal,yVal,trait) == value:
counter += 1
return counter
#This function returns the number of cells that hold a specific value for a
#given trait. The trait and values are the parameters for the funciton.
def getNumValue(self,trait,value):
counter = 0
for i in range(0,self.__width):
for j in range(0,self.height):
if self.getValue(i,j,trait) == value:
counter += 1
return counter
def __str__(self):
return "Grid size is: "+str(self.__width)+" by "+str(self.__height)+\
", traits are: "+", ".join(list(map(str,self.__traits)))
|
# 把以下程式放到 .py 上執行
# 執行後,伺服器會持續開著
# 到瀏覽器開啟 http://127.0.0.1:5000/ 就可以看到網頁
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return """
<html>
<head>
<title>網頁標題</title>
</head>
<body>
<div id="header">
<a class="logo" href="https://test.com.tw/logo-link">
PTT
</a>
</div>
<div class="images">
<img src="0.png" />
<img src="01.png" />
<img src="02.png" />
<img src="03.png" />
<img src="11.png" />
<img src="12.png" />
<img src="13.png" />
<img src="01111.png" />
</div>
<div id="container">
<h2 id="title">八卦版</h2>
<div class="article a1">
<h3 class="title t1">文章標題1</h3>
<div class="author">作者1</div>
<div class="date">11/01</div>
</div>
<div class="article a2">
<h3 class="title t2">文章標題2</h3>
<div class="author">作者2</div>
<div class="date">11/02</div>
</div>
<div class="article a3">
<h3 class="title t3">文章標題3</h3>
<div class="author">作者3</div>
<div class="date">11/03</div>
</div>
</div>
<div id="footer">
<p class="address">臺北市信義區</p>
<p class="copyright">© Copyright 2019</p>
</div>
</body>
</html>
"""
if __name__ == "__main__":
app.run()
|
# Reference File for Basic Plotting
# You'll see similarities here to Matlab plotting with this library
import numpy as np
import matplotlib.pyplot as plt
# generating 100 standard normally distributed random numbers as a NumPy ndarray
np.random.seed(1000)
y = np.random.standard_normal(100)
x = range(len(y))
plt.figure(1)
plt.plot(x,y)
#below is same as above b/c plot takes index values as the respective x values
plt.figure(2)
plt.plot(y)
#Don't forget that you can methods to this as such below on line 21
plt.figure(figsize=(7,4))
plt.plot(y.cumsum())
plt.title('Basic Plotting 101')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.grid(True)
plt.axis('tight')
plt.xlim(-1,20)
plt.ylim(-3,1)
#LaTeX is excellent for text rendering
plt.show()
|
import random
# initial values
# List = real value, suits, card
player_cards = []
dealer_cards = []
MINIMUM = 17
# poker card as a dictionary
poker_card = {
1: "Ace",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
10: "Ten",
11: "King",
12: "Queen",
13: "Jack"
}
suits_card = {
0: "Clubs",
1: "Diamonds",
2: "Hearts",
3: "Spades"
}
# assign cards at the start of the game
def start():
for i in range(2):
add_card(player_cards)
add_card(dealer_cards)
# adding another card to the card holder
def add_card(cards):
num = random.randint(1, 13)
s = random.randint(0, 3)
suit = suits_card[s]
if num >= 10:
card = [10, suit, poker_card[num]]
elif num == 1:
card = [11, suit, poker_card[num]]
else:
card = [num, suit, poker_card[num]]
cards.append(card)
def display_cards(cards):
for i in range(len(cards)):
print(cards[i][2] + " of " + cards[i][1])
print()
# get the total points from given set of cards
def evaluate_total_points(cards):
total_point = 0
for i in range(len(cards)):
total_point += cards[i][0]
return total_point
def check_blackjack(playerPoints, dealerPoints):
pPoint = playerPoints
dPoint = dealerPoints
if pPoint == 21 and dPoint == 21:
print("Both player and dealer got blackjack.\nIt's a Tie.")
return True
elif pPoint == 21:
print("Player got a BLACKJACK!!!\nPlayer wins!!")
return True
elif dPoint == 21:
print("Dealer got a BLACKJACK!!!\nDealer wins!!")
return True
return False
# check who got more points
def evaluate_winner(ppoint, dpoint):
if ppoint > 21 and dpoint > 21:
print("It's a draw.")
elif ppoint > dpoint:
if ppoint <= 21:
print("Player wins!!")
elif ppoint > 21 and dpoint <= 21:
print("Dealer wins!!")
elif ppoint < dpoint:
if dpoint <= 21:
print("Dealer wins!!")
elif dpoint > 21 and ppoint <= 21:
print("Player wins!!")
else:
print("It's a draw.")
# print the values
print("Player points:: " + str(playerPoints))
print("Dealer points:: " + str(dealerPoints))
# check if the cards has any ace in them
# return the index of the ace card
def check_ace(cards):
for i in range(len(cards)):
if cards[i][2] == "Ace":
return i
else:
return -1
# Dealers picking cards
# If the total is 17 or more, it must stand.
# If the total is 16 or under, they must take a card.
# The dealer must continue to take cards until the total is 17 or more, at which point the dealer must stand.
# return True if the dealer is picking, False if the dealer is not
def dealer_pick(totalPoint):
if totalPoint >= MINIMUM:
return False
else:
return True
# If the dealer has an ace, and counting it as 11 would bring the total to 17 or more
# (but not over 21), the dealer must count the ace
# as 11 and stand. The dealer's decisions, then, are automatic on all plays
# return 11 if the total is less or equal to 21, 1 if it is more than 21
def dealer_ace(totalpoint, indexoface, cards):
if (totalpoint - 1) + 11 <= 21:
cards[indexoface][0] = 11
else:
cards[indexoface][0] = 1
# program start
start()
print("Your cards::")
display_cards(player_cards)
# for testing purpose
# print("Dealer::")
# display_cards(dealer_cards)
playerPoints = evaluate_total_points(player_cards)
dealerPoints = evaluate_total_points(dealer_cards)
# for testing purpose
# print("Start player point: " + str(playerPoints))
# print("Start dealer point: " + str(dealerPoints))
if check_ace(dealer_cards) > -1:
placeOfAce = check_ace(dealer_cards)
dealer_ace(dealerPoints, placeOfAce, dealer_cards)
if not check_blackjack(playerPoints, dealerPoints):
while dealer_pick(dealerPoints):
add_card(dealer_cards)
dealerPoints = evaluate_total_points(dealer_cards)
# for testing purpose
# print("current dealer points: " + str(dealerPoints))
choice = input("Do you want to hit or stand? ")
while choice != 'hit' and choice != 'stand':
print("Enter a valid choice.")
choice = input("Do you want to hit or stand? ")
while choice == 'hit':
add_card(player_cards)
print("Player::")
display_cards(player_cards)
choice = input("Do you want to hit or stand? ")
while choice != 'hit' and choice != 'stand':
print("Enter a valid choice.")
choice = input("Do you want to hit or stand? ")
if check_ace(player_cards) > -1:
aceValue = int(input("Do you want to use your Ace as (1 or 11):: "))
# Change ace value to 1
if aceValue == 11:
player_cards[check_ace(player_cards)][0] = 1
playerPoints = evaluate_total_points(player_cards)
dealerPoints = evaluate_total_points(dealer_cards)
evaluate_winner(playerPoints, dealerPoints)
|
import numpy as np
import matplotlib.pyplot as plt
def compute_accel(desired_accel, desired_speed, duration, N):
accel = np.zeros(int(N))
N1 = int(desired_speed / desired_accel * N / duration)
N2 = int((duration - desired_speed / desired_accel) * N / duration)
if N1 <= N2:
accel[:N1] = desired_accel
accel[N2:] = -desired_accel
else:
N0 = int(2.0 * N / duration)
accel[:N0] = desired_accel
accel[N0:] = -desired_accel
return accel
def compute_vel(desired_accel, desired_speed, duration, N):
pass
if __name__=='__main__':
duration = 3.0
DT = 1/100.0
N = duration / DT
desired_accel = 1.0
desired_speed = 1.0
time = np.linspace(0.0, duration, N)
accel = compute_accel(desired_accel, desired_speed, duration, N)
plt.plot(time, accel)
plt.show()
|
'''
사회적 거리두기에 따른 영화관 좌석 예매 시스템 만들기
1~20번까지 총 20개의 좌석으로 구성
이 때 각 열에 대해 홀수(/짝수로 끝나는 좌석에 대해서만 출력
A, B, C, D열까지 있다고 가정하기
A, C열은 홀수만, B, D는 짝수만 있다고 가정
'''
def what_seat(alphabet):
seat_list = []
'''
# 평상시
for i in range(1, 21):
seat = alphabet + str(i)
seat_list.append(seat)
'''
# by COVID 19
odd = ["A", "C"]
if alphabet in odd:
for i in range(1, 11, 2):
seat = alphabet + str(i)
seat_list.append(seat)
else:
for i in range(2, 11, 2):
seat = alphabet + str(i)
seat_list.append(seat)
return seat_list
def display_seat(seats, alphabet):
# each row
odd = ["A", "C"]
if alphabet in odd:
for i in range(0, 10):
if i % 2 == 0:
k = i//2
print(seats[k], end="\t")
else:
print("\t", end=" ")
else:
for i in range(0, 10):
if i % 2 == 1:
k = i//2
print(seats[k], end="\t")
else:
print("\t", end=" ")
print("")
if __name__ == "__main__":
a = what_seat("A")
display_seat(a, "A")
b = what_seat("B")
display_seat(b, "B")
c = what_seat("C")
display_seat(c, "C")
d = what_seat("D")
display_seat(d, "D")
|
"""
Program: employee_class.py
Author: Ihsanullah Anwary
Last date modified: 12/11/2020
This is program is an example employee management system which allows the user to choose one for option from the list of
the selection.This program allows the user to save, find and delete the employee's id, first name, last name, deportment, job tiltle
salary and date hired to a file named employee_data.txt as dictionary.
"""
import os.path
import pickle
from tkinter.ttk import Label
try:
import Tkinter as tk
except:
import tkinter as tk
""" try exception GUI"""
class Employee:
""" class employee"""
def __init__(self, first_name, last_name, ID_number, dept, job_title, Salary, Hired_date): # constructor
self.root = tk.Tk()
self.quit = None
self.__first_name = first_name
self.__last_name = last_name
self.__ID_number = ID_number
self.__department = dept
self.__job_title = job_title
self.__salary = Salary
self.__date = Hired_date
# getters and setters
def set_first_name(self, first_name):
self.__first_name = first_name
def set_last_name(self, last_name):
self.__last_name = last_name
def set_ID_number(self, ID_number):
self.__ID_number = ID_number
def set_department(self, dept):
self.__department = dept
def set_job_title(self, job_title):
self.__job_title = job_title
def set_salary(self, Salary):
self.__salary = Salary
def set_date(self, Hired_date):
self.__date = Hired_date
def get_first_name(self):
return self.__first_name
def get_last_name(self):
return self.__last_name
def get_ID_number(self):
return self.__ID_number
def get_department(self):
return self.__department
def get_job_title(self):
return self.__job_title
def get_salary(self):
return self.__salary
def get_date(self):
return self.__date
class Welcome():
""" Class welcome"""
def __init__(self):
self.root = tk.Tk()
self.root.title('Welcome to employee management')
self.root.geometry('500x50')
self.label = tk.Label(self.root, text="Click OK to start the program")
self.label.pack()
button = tk.Button(self.root, text='OK', command=self.start)
button.pack()
self.root.mainloop()
def start(self):
self.root.destroy()
welcome = Welcome()
def add_employee():
"""Function add_employee"""
global id_number, choice
"""global Variables"""
if os.path.exists("employee_data.txt"): # file name
# If the file exist which contains a dictionary of employee records.
f = open('employee_data.txt', 'rb')
emp_dct = pickle.load(f)
f.close()
# if the file does not exist
else:
""" Creating employee and adding to dictionary"""
first_employee = Employee('Moke', 'John', 1, 'Accounting',
'Manager', '4000', '01-04-2019')
# initializing dictionary
emp_dct = {first_employee.get_ID_number(): first_employee.get_first_name() + ' '
+ first_employee.get_last_name() + ' ' +
first_employee.get_department() + ' ' + first_employee.get_job_title() + ' ' + first_employee.get_salary() + ' ' + first_employee.get_date()}
# using while loop to continue the program as per users' choice.
choice_qiut = 'y'
while choice_qiut.upper() == 'Y':
# This gives choices to the user
print('Enter any of the following choices: ')
print('Add a new employee to the dictionary: enter 1')
print('Find an employee in the dictionary by ID number: enter 2')
print('Change an existing employee\'s first name,last name,department or job title: enter 3')
print('Delete an employee from a dictionary: enter 4')
print('Quit the program: enter 5')
choice = input('Enter your choice: ')
if int(choice) == 2:
id_number = input('Enter the ID of the employee: ')
if int(id_number) in emp_dct.keys():
print(emp_dct[int(id_number)])
# If id_number entered by the use does not exist.
else:
print('Employee id not found!')
else:
if int(choice) == 1:
id_number = input('Enter ID of the employee: ')
# If id_number entered by the use exists
if int(id_number) in emp_dct.keys():
print('Employee already exist')
# If id_number entered by the use does not exist, then add
else:
first_name_ = input('Enter first name of the employee: ')
last_name_ = input('Enter last name of the employee: ')
dept = input('Enter department of the employee: ')
job = input('Enter job title of the employee: ')
salary_ = input(' enter salary of employee: ')
date_ = input(' enter date hired employee: ')
name_characters = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-")
salary__characters = set("1234567890-")
if not (name_characters.issuperset(first_name_ ) and name_characters.issuperset(last_name_)):
raise ValueError
if salary_ and not salary__characters.issuperset(salary_):
raise ValueError
new_employee = Employee(first_name_, last_name_, int(id_number),
dept, job, salary_, date_)
for id_number in range(100):
""" for loop allows user to add 100 employees"""
id_number = +1
emp_dct[
new_employee.get_ID_number()] = 'name:' + new_employee.get_first_name() + '' + new_employee.get_last_name() + ' ' + 'Departament:' + new_employee.get_department() + ' ' + 'Job:' + new_employee.get_job_title() + ' ' + 'Salary: $' + new_employee.get_salary() + ' ' + 'Date hired:' + new_employee.get_date()
print('Employee added to file')
else:
if int(choice) == 3:
""" User choice to modify the user information"""
id_number = input('Enter ID of the employee: ')
# If id_number entered by the use exists,then modify the record
if int(id_number) in emp_dct.keys():
first_name_ = input('Enter first name of the employee: ')
last_name_ = input('Enter last name of the employee: ')
dept = input('Enter department of the employee: ')
job = input('Enter job title of the employee: ')
salary_ = input(' enter salary of employee: ')
date_ = input(' enter date hired employee: ')
e4 = Employee(first_name_, last_name_, int(id_number),
dept, job, salary_, date_)
emp_dct[
e4.get_ID_number()] = e4.get_first_name() + ' ' + e4.get_last_name() + ' ' + e4.get_department() + e4.get_job_title() + ' ' + e4.get_salary() + ' ' + e4.get_date()
print('Employee data modified!')
# If id_number entered by the use does not exist, not modified
else:
print('Employee not found!')
else:
if int(choice) == 4:
id_number = input('Enter ID of the employee: ')
# Using pop() method to delete
# It returns default message, if the item not found
print('Deleted: ', emp_dct.pop(int(id_number), 'Employee not found!'))
# ends the program
if int(choice) != 5:
print('Invalid Choice!')
else:
print('OK Bye!')
break
choice_qiut = input('Continue? enter y for yes: ')
# Write the dictionary into the file
f = open('employee_data.txt', 'wb')
pickle.dump(emp_dct, f)
f.close()
add_employee()
""""Calling the function"""
|
import Snake as S
import os
import time
import random
#size of grid nxn
n = 16
grid = list()
#For now food is a tuple. Could make a spearate object for a separate sprite if there is time.
food = tuple()
def checkCollision(snakeObject,otherSnakeObject = None):
'''
Checks the collisions of the snake with the bounds, or itself
'''
if snakeObject.positionX < 0:
print("collision")
return True
if snakeObject.positionY < 0:
print("collision")
return True
if snakeObject.positionX >= n:
print("collision")
return True
if snakeObject.positionY >= n:
print("collision")
return True
if (snakeObject.positionX,snakeObject.positionY) in snakeObject.squaresoccupied:
print("collision with self")
return True
if otherSnakeObject != None:
if (snakeObject.positionX,snakeObject.positionY) in otherSnakeObject.squaresoccupied:
print(otherSnakeObject.playerName + " wins")
return True
elif snakeObject.squaresoccupied[0] in otherSnakeObject.squaresoccupied:
print(otherSnakeObject.playerName + " wins")
return True
else:
return False
def checkFood(snakeObject,otherSnakeObject=None):
'''
Checks if the head of a snake passes over food, and if it does, calls the
eat functino and creates a new random location for the food. Note, still need
to fix this so it doesn't make food over an occupied square.
'''
if snakeObject.positionX == food[0] and snakeObject.positionY == food[1]:
#return True
snakeObject.eat()
if otherSnakeObject != None:
makeFood(snakeObject,otherSnakeObject)
else:
makeFood(snakeObject)
return True
def makeFood(snakeObject,otherSnakeObject=None):
'''
Sets the coordinates of food.
'''
global food
temp = tuple((random.randint(0,n-1),random.randint(0,n-1)))
if otherSnakeObject != None:
while temp in snakeObject.squaresoccupied or temp in otherSnakeObject.squaresoccupied:
temp = tuple((random.randint(0,n-1),random.randint(0,n-1)))
else:
while temp in snakeObject.squaresoccupied:
temp = tuple((random.randint(0,n-1),random.randint(0,n-1)))
food = temp
def translatePositionX(x):
'''
Translates the x coordinate to match the coordinate system of Pyglet.
'''
return 340+(x*40)
def translatePositionY(y):
'''
Translates the y coordinate to match the coordinate system of Pyglet.
'''
return 60+(y*40)
|
FORWARD = 'forward'
DOWN = 'down'
UP = 'up'
def pretty_print_answer(part, answer):
print('Answer to part {num}: {ans}'.format(num=part, ans=answer))
def read_lines(file_name, is_strip=True):
file = open(file_name)
lines = [s for s in file.readlines()]
file.close()
if is_strip:
lines = [s.strip() for s in lines]
return lines
def travel(lines):
posx = posy = 0
for line in lines:
direction, magnitude = line.split()
magnitude = int(magnitude)
if direction == FORWARD:
posx += magnitude
elif direction == DOWN:
posy += magnitude
elif direction == UP:
posy -= magnitude
else:
assert(False, f'unsupported action {0}', direction)
return posx * posy
def aim_travel(lines):
posx = posy = aim = 0
for line in lines:
direction, magnitude = line.split()
magnitude = int(magnitude)
if direction == FORWARD:
posx += magnitude
posy += aim * magnitude
elif direction == DOWN:
aim += magnitude
elif direction == UP:
aim -= magnitude
else:
assert(False, f'unsupported action {0}', direction)
return posx * posy
def main():
lines = read_lines('input.txt')
pretty_print_answer(1, travel(lines))
pretty_print_answer(2, aim_travel(lines))
if __name__ == "__main__":
main()
|
def main():
file_input = open('input.txt', 'r')
lines = file_input.readlines()
file_input.close()
calories = []
current = 0
for line in lines:
line = line.strip()
if line.isdigit():
current += int(line)
else:
calories.append(current)
current = 0
max_calories = total = max(calories)
print(max_calories)
for _ in range(2):
calories.remove(max_calories)
max_calories = max(calories)
total += max_calories
print(total)
if __name__ == "__main__":
main()
|
import copy
import utils
class Recipes:
def __init__(self):
self.recipe = [3, 7]
self.current = 0
self.next = 1
self.processed = 0
def step(self):
score = self.recipe[self.current] + self.recipe[self.next]
score = [int(d) for d in str(score)]
self.recipe.extend(score)
self.current = (self.current + (self.recipe[self.current] + 1)) % len(self.recipe)
self.next = (self.next + (self.recipe[self.next] + 1)) % len(self.recipe)
return len(score)
def __repr__(self):
pretty = copy.deepcopy(self.recipe)
pretty[self.current] = '({num})'.format(num=pretty[self.current])
pretty[self.next] = '[{num}]'.format(num=pretty[self.next])
return ' '.join(map(str, pretty))
def next_ten(self, num):
while self.processed < num + 10:
self.processed += self.step()
return ''.join(map(str, self.recipe[num:num+10]))
def length_before(self, seq, step_size):
output = ''.join(map(str, self.recipe))
while seq not in output:
for _ in range(step_size):
self.processed += self.step()
output = ''.join(map(str, self.recipe))
return output.index(seq)
#sample
recipes = Recipes()
assert recipes.next_ten(9) == '5158916779'
assert recipes.length_before('51589', 1) == 9
empty = Recipes()
assert empty.length_before('51589', 1) == 9
assert recipes.next_ten(5) == '0124515891'
assert recipes.length_before('01245', 1) == 5
assert recipes.next_ten(18) == '9251071085'
assert recipes.length_before('92510', 1) == 18
assert recipes.next_ten(2018) == '5941429882'
assert recipes.length_before('59414', 1) == 2018
#input
ans = recipes.next_ten(409551)
assert ans == '1631191756'
utils.pretty_print_answer(1, ans)
utils.pretty_print_answer(2, recipes.length_before('409551', 100000))
|
import utils
TREE = '#'
class Map:
def __init__(self, file_name):
self.grid = []
lines = utils.read_lines(file_name)
for line in lines:
self.grid.append(list(line))
def traverse(self, col_mod, row_mod):
num_trees = 0
row = col = 0
while row < len(self.grid):
if self.grid[row][col] == TREE:
num_trees += 1
row += row_mod
col = (col + col_mod) % len(self.grid[0])
return num_trees
def main():
trees = Map('input.txt')
num_trees = trees.traverse(3, 1)
utils.pretty_print_answer(1, num_trees)
for col_mod, row_mod in [(1, 1), (5, 1), (7, 1), (1, 2)]:
num_trees *= trees.traverse(col_mod, row_mod)
utils.pretty_print_answer(2, num_trees)
if __name__ == "__main__":
main()
|
import utils
vowels = 'aeiou'
forbidden = ['ab', 'cd', 'pq', 'xy']
def is_nice(input_string):
return (has_three_vowels(input_string)
and has_duplicate_letter(input_string)
and not has_forbidden_pair(input_string))
def is_nice_pt2(input_string):
return (two_pairs(input_string)
and letter_sandwich(input_string))
def two_pairs(input_string):
for i in range(len(input_string) - 1):
pair = input_string[i: i + 2]
print(pair)
if pair in input_string[i + 2:]:
return True
return False
def letter_sandwich(input_string):
for i in range(len(input_string) - 2):
first, second, third = input_string[i: i + 3]
if first == third and first != second:
return True
return False
def has_three_vowels(input_string):
return len([c for c in input_string if c in vowels]) >= 3
def has_duplicate_letter(input_string):
for i in range(len(input_string) - 1):
pair = input_string[i: i + 2]
if pair[0] == pair[1]:
return True
return False
def has_forbidden_pair(input_string):
for i in range(len(input_string) - 1):
pair = input_string[i: i + 2]
if pair in forbidden:
return True
return False
def part1():
file = open('input.txt')
lines = file.readlines()
file.close()
total = 0
for line in lines:
if is_nice(line):
total += 1
return total
def part2():
file = open('input.txt')
lines = file.readlines()
file.close()
total = 0
for line in lines:
if is_nice_pt2(line):
total += 1
return total
def main():
utils.pretty_print_answer(1, part1())
utils.pretty_print_answer(2, part2())
if __name__ == '__main__':
main()
|
def snafu_to_decimal(value):
total = 0
power = 0
for digit in value[::-1]:
if digit.isdigit():
total += int(digit) * 5 ** power
elif digit == '-':
total += -1 * 5 ** power
elif digit == '=':
total += -2 * 5 ** power
else:
assert False, 'unsupported digit {digit}'.format(digit=digit)
power += 1
return total
def decimal_to_snafu(value):
result = []
while value:
quintuple = value % 5
if quintuple == 3:
result.append('=')
value += 2
elif quintuple == 4:
result.append('-')
value += 1
else:
result.append(str(quintuple))
value //= 5
result.reverse()
return ''.join(result)
def decimal_sum(file_name):
file_input = open(file_name, 'r')
lines = [line.strip() for line in file_input.readlines()]
file_input.close()
sum = 0
for line in lines:
sum += snafu_to_decimal(line)
return sum
def snafu_sum(file_name):
return decimal_to_snafu(decimal_sum(file_name))
def main():
assert snafu_to_decimal('1=-0-2') == 1747
assert snafu_to_decimal('12111') == 906
assert snafu_to_decimal('2=0=') == 198
assert snafu_to_decimal('21') == 11
assert snafu_to_decimal('2=01') == 201
assert snafu_to_decimal('111') == 31
assert snafu_to_decimal('20012') == 1257
assert snafu_to_decimal('112') == 32
assert snafu_to_decimal('1=-1=') == 353
assert snafu_to_decimal('1-12') == 107
assert snafu_to_decimal('12') == 7
assert snafu_to_decimal('1=') == 3
assert snafu_to_decimal('122') == 37
assert decimal_to_snafu(1) == '1'
assert decimal_to_snafu(2) == '2'
assert decimal_to_snafu(3) == '1='
assert decimal_to_snafu(4) == '1-'
assert decimal_to_snafu(5) == '10'
assert decimal_to_snafu(6) == '11'
assert decimal_to_snafu(7) == '12'
assert decimal_to_snafu(8) == '2='
assert decimal_to_snafu(9) == '2-'
assert decimal_to_snafu(10) == '20'
assert decimal_to_snafu(15) == '1=0'
assert decimal_to_snafu(20) == '1-0'
assert decimal_to_snafu(2022) == '1=11-2'
assert decimal_to_snafu(12345) == '1-0---0'
assert decimal_to_snafu(314159265) == '1121-1110-1=0'
assert decimal_sum('aoc2022/day25/sample.txt') == 4890
assert snafu_sum('aoc2022/day25/sample.txt') == '2=-1=0'
print('Part 1:', snafu_sum('aoc2022/day25/input.txt'))
if __name__ == '__main__':
main()
|
def coin_change(coins, m, n, mem):
if n == 0:
return 1
if n < 0:
return 0
if m < 0:
return 0
if (m, n) in mem:
return mem[m, n]
ans = 0
ans += coin_change(coins, m, n-coins[m], mem)
ans += coin_change(coins, m-1, n, mem)
mem[m, n] = ans
return ans
coins = [1,2,3]
mem = {}
print(coin_change(coins, len(coins)-1, 4, mem))
|
def smallestWindow(st):
n = len(st)
dic = {}
setChars = set()
count = 0
for c in st:
setChars.add(c)
count = len(setChars)
start = 0
end = n-1
curr = 0
found = set()
minl = n
start_ind = 0
for i in range(n):
c = st[i]
if c in setChars:
dic[c] = i
found.add(c)
if len(found) == count:
while dic[st[start]] > start:
start += 1
if i - start + 1 < minl:
minl = i - start + 1
end = i
start_ind = start
return st[start_ind:end+1]
st = "aaaabcdabchkdajebcda"
print(smallestWindow(st))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 29 16:17:42 2020
@author: Jill Wright
This program takes information from an API program called Financial Prep
and commits it to a SQL database. The information is from ticker symbol and includes
Industry,CEO, and company description. Another segment is populated with information
articles also pulled from the API that can be reviewed by the user.
"""
import sqlite3
try:
# Create the StockINFO database then the company table
conn = sqlite3.connect('STOCKINFORM')
cursor = conn.cursor()
print("Connected")
comtable_sql='''
CREATE TABLE IF NOT EXISTS
COMPANY(
pkid INTEGER,
symbol TEXT PRIMARY KEY,
Company INTEGER NOT NULL,
CEO TEXT NOT NULL,
DESC TEXT,
Industry INTEGER NOT NULL
)
'''
cursor.execute(comtable_sql)
conn.commit()
print("Created Company table")
except sqlite3.Error as error:
print("Error")
print(error)
# Close Resource
finally:
if cursor:
cursor.close()
if conn:
conn.close()
# In[ ]:
def close_DB_resources(dbconn, cursor):
try:
if dbconn:
dbconn.close()
if cursor:
cursor.close()
print("closed resources")
except sqlite3.Error as err:
("Error closing resources")
# In[ ]:
import sqlite3
# Utility for handling DB errors
def handle_DB_error(dbconn, cursor):
if dbconn:
try:
dbconn.rollback()
print("Rolled back transation")
except sqlite3.Error as error:
print("Error rolling back transaction")
close_DB_resources(dbconn, cursor)
dbconn = None
return dbconn
# In[ ]:
# utility DB connection and cursor function to return our access objects
def connect_SQLite():
try:
dbconn = sqlite3.connect('STOCKINFORM')
cursor = dbconn.cursor()
print("Connected to STOCK DATABASE")
except sqlite3.Error as error:
print("Error opening database")
dbconn = handle_DB_error(dbconn, cursor)
return dbconn, cursor
# In[ ]:
import csv
# SQL setup for insert of company information
pkid = 101
company_insert = '''INSERT INTO COMPANY (pkid, symbol, Company, CEO, Industry)
VALUES (?,?,?,?,?);
'''
# retrieve my connection and cursor for use in all my inserts
dbconn, cursor = connect_SQLite()
# Iterate over our CSV file of appointments, convert the missedappt to 0/1
with open('companyinfo.csv') as file:
print('reading comp csv')
compinfo = csv.DictReader(file)
print(compinfo)
for comp in compinfo:
# get rowid from generator
pkid += 1
record = (pkid,comp['symbol'],comp['Company'], comp['CEO'],comp['Industry'])
print("inserting records: ", end='')
print(record)
cursor.execute(company_insert, record)
dbconn.commit()
# In[ ]:
# Verify that we've got data
select_sql = '''
SELECT *
FROM COMPANY;
'''
dbconn, cursor = connect_SQLite()
cursor.execute(select_sql)
recs = cursor.fetchall()
for r in recs:
print(r)
#close_DB_resources(dbconn, cursor)
# In[22]:
#Create our table for student registration data
STK_table_sql= '''CREATE TABLE IF NOT EXISTS stock(
pkid INTEGER PRIMARY KEY,
symbol TEXT,
text TEXT,
urlinfo TEXT );
'''
dbconn, cursor = connect_SQLite()
cursor.execute(STK_table_sql)
dbconn.commit()
print('Create stock table')
# In[24]:
import csv
# Complete insert of news url info
pkid = 101
stock_insert = '''INSERT INTO stock (pkid,symbol, text, urlinfo)
VALUES (?,?,?,?);
'''
# retrieve my connection and cursor for use in all my inserts
dbconn, cursor = connect_SQLite()
# Iterate over our CSV file for the url for the recent news on the ticker symbol
with open('stockinfo.csv') as file:
stockinfo = csv.DictReader(file)
for stock in stockinfo:
# get rowid from generator
pkid += 1
record = (pkid, stock['symbol'], stock['text'], stock['urlinfo'])
print("inserting records: ", end='')
print(record)
cursor.execute(stock_insert, record)
dbconn.commit()
# close_DB_resources(dbconn, cursor)
select_sql = '''
SELECT *
FROM stock;
'''
dbconn, cursor = connect_SQLite()
cursor.execute(select_sql)
recs = cursor.fetchall()
for r in recs:
print(r)
close_DB_resources(dbconn, cursor)
class _TimesCalled:
def __init__(self):
self._called = 0
def __add__(self, other):
self._called = self._called + other
return self._called
def __str__(self):
return str(self._called)
times_called = _TimesCalled()
def increment():
return times_called + 1
|
print("Welcome to the BMI calculator\n")
height = float(input("Kindly Enter your height\n"))
weight = int(input("Kindly Enter your weight\n"))
bmi_data = int(weight) / float(height ** 2)
# bmi = float(bmi_data,2)
print(bmi_data)
if bmi_data < 18.5:
print(f"Your BMI is {bmi_data} You're underweight")
elif bmi_data < 25:
print("You have a normal weight dear")
elif bmi_data < 30:
print("You are overweight dear")
elif bmi_data < 35:
print("You are a obese dear")
else:
print("you are clinically obese")
|
is_even = 0
total_evens = 0
for numbers in range(1, 100+1):
is_even = numbers % 2
if is_even == 0:
total_evens += numbers
print(f"Total even numbers is {total_evens}")
|
from ListItem import ListItem
class List:
"""
A simple linked list implementation. The list object contains the head, tail, and
the length of the list. I keep track of the tail of the list
so that I can append items to the list in O(1) time.
"""
def __init__(self):
self._head = None
self._tail = None
self.length = 0
def get_head(self):
return self._head
def get_tail(self):
return self._tail
def set_head(self, n):
self._head = n
def set_tail(self, n):
self._tail = n
def append(self, li):
"""
Add an item to the linked list.
Args:
li (string|integer): a list item to add to the list
Returns:
boolean: whether or not the value is sucessfully appended to the list
"""
if self._head == None:
self._head = li
elif self._tail == None:
self._tail = li
self._head.set_next(li)
self._tail.set_previous(self._head)
else:
li.set_previous(self._tail)
self._tail.set_next(li)
self._tail = li
self.length += 1
return True
def insert_sorted(self, li):
node = self._head
if self._head == None:
self._head = li
elif self._tail == None:
if li.get_value() < self._head.get_value():
self._head.set_previous(li)
li.set_next(self._head)
self._tail = self._head
self._head = li
else:
self._tail = li
self._head.set_next(li)
self._tail.set_previous(self._head)
elif li.get_value() < self._head.get_value():
li.set_next(self._head)
self._head.set_previous(li)
self._head = li
elif li.get_value() >= self._tail.get_value():
li.set_previous(self._tail)
self._tail.set_next(li)
self._tail = li
else:
node = node.get_next()
while node != None:
if li.get_value() < node.get_value():
prev = node.get_previous()
newnxt = node
li.set_next(newnxt)
newnxt.set_previous(li)
li.set_previous(prev)
prev.set_next(li)
break
node = node.get_next()
self.length += 1
return True
def get_items(self):
"""
Builds an array of the values in the list.
Returns:
array: array representation of the values in the linked list
"""
if self.length == 0 or self._head == None:
return []
a = [self._head.get_value()]
i = self._head
while i.has_next():
i = i.get_next()
a.append(i.get_value())
return a
def get_string(self):
if self.length == 0 or self._head == None:
return ""
s = self._head.get_value()
i = self._head
while i.has_next():
i = i.get_next()
s += ", %s" % i.get_value()
return s
def __len__(self):
return self.length
def __str__(self):
return self.get_string()
|
import unittest
import random
import functools
from QuickSort import quick_sort
from List import List
from ListItem import ListItem
class TestList(unittest.TestCase):
def setUp(self):
self.int_list = List()
self.int_list.append(ListItem(0))
self.int_list.append(ListItem(15))
self.int_list.append(ListItem(3))
self.int_list.append(ListItem(212))
self.int_list.append(ListItem(2))
self.int_list.append(ListItem(9))
self.int_list.append(ListItem(8))
self.int_list.append(ListItem(60))
self.int_list.append(ListItem(300))
self.int_list.append(ListItem(0))
self.str_list = List()
self.str_list.append(ListItem("a"))
self.str_list.append(ListItem("c"))
self.str_list.append(ListItem("v"))
self.str_list.append(ListItem("b"))
self.str_list.append(ListItem("q"))
self.str_list.append(ListItem("a"))
self.str_list.append(ListItem("z"))
self.str_list.append(ListItem("e"))
self.str_list.append(ListItem("g"))
self.str_list.append(ListItem("p"))
def test_quick_sort_int(self):
self.assertEqual(
quick_sort(self.int_list.get_items(), 0, len(self.int_list) - 1),
[0, 0, 2, 3, 8, 9, 15, 60, 212, 300],
)
def test_quick_sort_str(self):
self.assertEqual(
quick_sort(self.str_list.get_items(), 0, len(self.str_list) - 1),
["a", "a", "b", "c", "e", "g", "p", "q", "v", "z"],
)
def test_quick_sort_list(self):
self.assertRaises(
Exception,
quick_sort,
List(),
0,
len(self.str_list) - 1,
)
|
# https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
# Jose Luiz Mattos Gomes
class Solution:
def solution(self, X, Y, D) -> int:
# calculate number of jumps
numJumps = (Y - X) // D
if (Y - X) % D > 0:
# add 1 jump if remainder is bigger than 0
numJumps +=1
# return number of jumps
return numJumps
s = Solution()
print(s.solution(10, 85, 30))
|
# https://leetcode.com/problems/fizz-buzz/
# Jose Luiz Mattos Gomes
from typing import List
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
# define return list
vReturn = []
# iteract from 1 to n
for i in range(1, n+1):
# test if is multiple of 3
if i%3==0:
# test if is also multiple of 5
if i%5==0:
vReturn.append('FizzBuzz')
else:
vReturn.append('Fizz')
# test if is multiple of 5
elif i%5==0:
vReturn.append('Buzz')
else:
vReturn.append(str(i))
# return final list
return vReturn
s = Solution()
print(s.fizzBuzz(15))
print(s.fizzBuzz(0))
print(s.fizzBuzz(75))
|
# https://leetcode.com/problems/rotate-array/
# Jose Luiz Mattos Gomes
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
# guarantee that k is between 0 and nums.length
k = k % len(nums)
# if k is zero than no rotation is needed
if(k==0):
return
# change items
nums[:] = nums[len(nums)-k:] + nums[: len(nums)-k]
s = Solution()
vNums01 = [1,2,3,4,5,6,7]
vTarget01 = 3
s.rotate(vNums01, vTarget01)
print(vNums01)
s.rotate(vNums01, vTarget01)
vNums01 = [1,2,3,4]
vTarget01 = 4
print(vNums01)
|
import random
wordlist = ["mouse", "banana", "grow", "king", "chalk",
"clever", "sharan", "mindset", "munnar", "eraser"]
choosen = random.choice(wordlist)
print(choosen)
chos_length = len(choosen)
empty = []
for i in range(chos_length):
empty.append("_")
def guess():
for i in range(0, chos_length):
if choosen[i] == guessed:
empty[i] = guessed
print(empty)
end_game = False
lives = 3
while "_" in empty and not end_game:
guessed = input("Guess a letter: ")
guessed.lower
if guessed not in choosen:
lives = lives-1
print("Thats not a correct letter\n Remaining lives= "+str(lives))
if lives == 0:
print("you lose-__-")
end_game = True
guess()
if "_" not in empty:
print("ya won")
|
#!/usr/bin/env python
#resp : 72 verbos 19 verbos em primeira pessoa
import sys
verb = 0
verb1 = 0
foo = ['r','x','w','j','m']
fp = open(sys.argv[1], "r")
line = fp.readline()
words = line.split(' ')
for wd in words:
if len(wd) >= 8 and wd[-1] not in foo:
verb = verb + 1
if wd[0] in foo:
verb1 = verb1 + 1
print verb, verb1
fp.close()
|
# coding:utf-8
# O(n^2)
# i 范围 0- (len-1)
# j 范围 0- (i-1) j永远比i小1
def insertSort(relist):
len_ = len(relist)
for i in range(1,len_):
for j in range(i):
if relist[i] < relist[j]:
relist.insert(j,relist[i]) # 首先碰到第一个比自己大的数字,赶紧刹车,停在那,所以选择insert
relist.pop(i+1) # 因为前面的insert操作,所以后面位数+1,这个位置的数已经insert到前面去了,所以pop弹出
break
return relist
print insertSort([1,5,2,6,9,3])
# 插入排序在最好情况下,需要比较n-1次,无需交换元素,时间复杂度为O(n);在最坏情况下,时间复杂度依然为O(n2)
|
# coding:utf-8
class BiNode(object): # 结点类
def __init__(self, element=None, left=None, right=None):
self.element = element
self.left = left
self.right = right
def get_element(self):
return self.element
def dict_form(self):
dict_set = {
"element": self.element,
"left": self.left,
"right": self.right,
}
return dict_set
def __str__(self):
return str(self.element)
class BiTree1(object): # 树 一颗完全二叉树(意思是一直从左到右添加,除了最后一层,之前的都是满的,可以不为满,但节点要集中在左边)
def __init__(self, tree_node=None):
self.root = tree_node
def add_node_in_order(self, item=None):
node = BiNode(item)
if not self.root:
self.root = node
else:
node_queue = []
node_queue.append(self.root)
while len(node_queue):
q_node = node_queue.pop(0)
if q_node.left is None:
q_node.left = node
break
elif q_node.right is None:
q_node.right = node
break
else:
node_queue.append(q_node.left)
node_queue.append(q_node.right)
def set_up_in_order(self,element_list): # 通过列表对树进行顺序构造
for elements in element_list:
self.add_node_in_order(elements)
def set_up_from_dict(self, dict_instance):
if not isinstance(dict_instance, dict):
return None
else:
dict_queue = list()
node_queue = list()
node = BiNode(dict_instance["element"])
self.root = node
node_queue.append(node)
dict_queue.append(dict_instance)
while len(dict_queue):
dict_in = dict_queue.pop(0)
node = node_queue.pop(0)
if isinstance(dict_in.get("left", None), (dict, int, float, str)):
if isinstance(dict_in.get("left", None), dict):
dict_queue.append(dict_in.get("left", None))
left_node = BiNode(dict_in.get("left", None)["element"])
node_queue.append(left_node)
else:
left_node = BiNode(dict_in.get("left", None))
node.left = left_node
if isinstance(dict_in.get("right", None), (dict, int, float, str)):
if isinstance(dict_in.get("right", None), dict):
dict_queue.append(dict_in.get("right", None))
right_node = BiNode(dict_in.get("right", None)["element"])
node_queue.append(right_node)
else:
right_node = BiNode(dict_in.get("right", None))
node.right = right_node
# 1. 如果树为空,返回0 。
# 2. 从根结点开始,将根结点拉入列。
# 3. 当列非空,记当前队列元素数(上一层节点数)。将上层节点依次出队,如果左右结点存在,依次入队。直至上层节点出队完成,
# 深度加一。继续第三步,直至队列完全为空
#
def get_depth(self):
if self.root is None:
return 0
else:
node_queue = list()
node_queue.append(self.root)
depth = 0
while len(node_queue):
q_len = len(node_queue)
while q_len:
q_node = node_queue.pop(0)
q_len = q_len - 1
if q_node.left is not None:
node_queue.append(q_node.left)
if q_node.right is not None:
node_queue.append(q_node.right)
depth = depth + 1
return depth
# 前序遍历
# 1. 如果树为空,返回None 。
# 2. 从根结点开始,如果当前结点左子树存在,则打印结点,并将该结点入栈。让当前结点指向左子树,继续步骤2直至当前结点左子树不存在。
# 3. 将当结点打印出来,如果当前结点的右子树存在,当前结点指向右子树,继续步骤2。否则进行步骤4.
# 4. 如果栈为空则遍历结束。若非空,从栈里面pop一个节点,从当前结点指向该结点的右子树。如果右子树存在继续步骤2,不存在继续步骤4直至结束。
def pre_traversal(self):
if self.root is None:
return None
else:
node_stack = list()
output_list = list()
node = self.root
while node is not None or len(node_stack):
if node is None:
node = node_stack.pop().right
continue
while node.left is not None:
node_stack.append(node)
output_list.append(node.get_element())
node = node.left
output_list.append(node.get_element())
node = node.right
return output_list
# 中序
def in_traversal(self):
if self.root is None:
return None
else:
node_stack = list()
output_list = list()
node = self.root
while node is not None or len(node_stack):
if node is None:
node = node_stack.pop()
output_list.append(node.get_element())
node = node.right
while node.left is not None:
node_stack.append(node)
node = node.left
output_list.append(node.get_element())
node = node.right
return output_list
# 后序
def post_traversal(self):
if self.root is None:
return None
else:
node_stack = list()
output_list = list()
node = self.root
while node is not None or len(node_stack):
if node is None:
node = node_stack.pop().left
while node.right is not None:
node_stack.append(node)
output_list.append(node.get_element())
node = node.right
output_list.append(node.get_element())
node = node.left
return output_list[::-1]
# 更简单的递归写法
# 依次为前中后遍历
def preOrder(self, BinaryTreeNode):
if BinaryTreeNode is None:
return
# 先打印根结点,再打印左结点,后打印右结点
print(BinaryTreeNode.data)
self.preOrder(BinaryTreeNode.left)
self.preOrder(BinaryTreeNode.right)
def inOrder(self, BinaryTreeNode):
if BinaryTreeNode is None:
return
# 先打印左结点,再打印根结点,后打印右结点
self.inOrder(BinaryTreeNode.left)
print(BinaryTreeNode.data)
self.inOrder(BinaryTreeNode.right)
def postOrder(self, BinaryTreeNode):
if BinaryTreeNode is None:
return
# 先打印左结点,再打印右结点,后打印根结点
self.postOrder(BinaryTreeNode.left)
self.postOrder(BinaryTreeNode.right)
print(BinaryTreeNode.data)
|
from re import findall
def is_isogram(string):
temp = findall(r'\w', string.upper())
return len(set(temp)) == len(temp)
|
# Import libraries
import os
import csv
smallval = 0
bigval = 0
bigdate = ''
smalldate = ''
maxchange = 0
minchange = 0
# open the file and EXCLUDE THE HEADER after printing it so I can see it
csvpath = os.path.join('resources', 'bank.csv')
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader) # Read and print the Header
mycount = 0 # Set a counter for the number of months/records not including the header
myvalue = 0
avgchange = 0
firstrow = next(csvreader)
begchange = int(firstrow[1])
minchange = int(firstrow[1])
for row in csvreader: # Read and print each row of data after the header
mycount = mycount + 1 # Set a counter for the number of months/records not including the header
myvalue += int(row[1]) # Add up the values across the entire data set
runchange = int(row[1]) - begchange # first time this should be 0
avgchange = avgchange + runchange
if runchange > maxchange:
maxchange = runchange
bigdate = str(row[0])
if runchange < minchange:
minchange = runchange
smalldate = str(row[0])
begchange = int(row[1]) #reset to the current value for the next loop
output_path = os.path.join('analysis', 'results.txt')
with open(output_path, 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(['Financial Analysis'])
csvwriter.writerow(['--------------------------------'])
csvwriter.writerow(['Total Months: ' + str(mycount)])
csvwriter.writerow(['Total: ' + str(myvalue)])
csvwriter.writerow(['Average Change: ' + str(avgchange)])
csvwriter.writerow(['Greatest Increase in Profits: ' + str(bigdate) + ' ('+ str(maxchange) + ')'])
csvwriter.writerow(['Greatest Decrease in Profits: ' + str(smalldate) + ' ('+ str(minchange) + ')'])
avgchange = (avgchange/85)
avgchange = round(avgchange, 2)
print('Financial Analysis')
print('--------------------------------')
print('Total Months: ' + str(mycount))
print('Total: ' + str(myvalue))
print('Average Change: ' + str(avgchange))
print('Greatest Increase in Profits: ' + str(bigdate) + ' ('+ str(maxchange) + ')')
print('Greatest Decrease in Profits: ' + str(smalldate) + ' ('+ str(minchange) + ')')
|
"""
Module for approximating square root
More details
"""
def sqrt2(x):
"""
Function definition
"""
s = 1.
kmax = 100
tol = 1.e-14
for k in range(kmax):
print "Before iteration %s, s = %20.15f" % (k+1,s)
s0 = s
s = 0.5 * (s + x / s)
delta_s = s - s0
if abs(delta_s / x) < tol:
break
print "After %s iterations, s = %20.15f" % (k+1,s)
|
"""Volume 1: The Drazin Inverse.
<Timothy Norris>
<MTH 420>
"""
import numpy as np
from scipy import linalg as la
# Helper function for problems 1 and 2.
def index(A, tol=1e-5):
"""Compute the index of the matrix A.
Parameters:
A ((n,n) ndarray): An nxn matrix.
Returns:
k (int): The index of A.
"""
# test for non-singularity
if not np.allclose(la.det(A),0):
return 0
n = len(A)
k = 1
Ak = A.copy()
while k<=n:
r1 = np.linalg.matrix_rank(Ak)
r2 = np.linalg.matrix_rank(np.dot(A,Ak))
if r1 == r2:
return k
Ak = np.dot(A,Ak)
k += 1
return
a = np.matrix('1 3 0 0; 0 1 3 0; 0 0 1 3; 0 0 0 0')
ad = np.matrix('1 -3 9 81; 0 1 -3 -18; 0 0 1 3; 0 0 0 0') #FALSE
b = np.matrix('1 1 3; 5 2 6; -2 -1 -3')
bd = np.matrix('0 0 0; 0 0 0; 0 0 0')
print("a: ",a,"\n")
print("ad: ",ad,"\n")
print("b: ",b,"\n")
print("bd: ",bd,"\n")
print(index(a))
print(index(ad))
print(index(b))
print(index(bd))
# Problem 1
def is_drazin(A, Ad, k):
"""Verify that a matrix Ad is the Drazin inverse of A.
Parameters:
A ((n,n) ndarray): An nxn matrix.
Ad ((n,n) ndarray): A candidate for the Drazin inverse of A.
k (int): The index of A.
Returns:
(bool) True of Ad is the Drazin inverse of A, False otherwise.
"""
print("\nAAd=AdA")
print(np.ma.allclose(np.dot(A,Ad),np.dot(Ad,A)))
print("A**(k+1)Ad = A**k")
print(np.ma.allclose(np.dot(A**(index(A)+1),Ad),A**(index(A))))
print("AdAAd=Ad")
print(np.ma.allclose(np.dot(np.dot(Ad,A),Ad),Ad))
is_drazin(a,ad,index(a))
is_drazin(b,bd,index(b))
# Problem 2
def drazin_inverse(A, tol = 1e-4):
"""Compute the Drazin inverse of A.
Parameters:
A ((n,n) ndarray): An nxn matrix.
Returns:
((n,n) ndarray) The Drazin inverse of A.
"""
n = A.shape[1]
f1 = lambda x:abs(x)>tol
V,S,k1=la.schur(A,sort=f1)
f2 = lambda x:abs(x)<=tol
Z,T,k2 = la.schur(A,sort=f2)
U=np.hstack((S[:,:(k1)],T[:,:(n-k1)]))
Uinv=la.inv(U)
V=np.dot(np.dot(Uinv,A),U)
Minv=np.zeros_like(A)
if k1 !=0:
Minv[:(k1),:(k1)]=la.inv(V[:(k1),:(k1)])
D=np.dot(np.dot(U,Minv),Uinv)
return D
is_drazin(a,drazin_inverse(a),index(a))
is_drazin(b,drazin_inverse(b),index(b))
# Problem 3
def effective_resistance(A):
"""Compute the effective resistance for each node in a graph.
Parameters:
A ((n,n) ndarray): The adjacency matrix of an undirected graph.
Returns:
((n,n) ndarray) The matrix where the ijth entry is the effective
resistance from node i to node j.
"""
from scipy.sparse import csgraph
g1 = np.matrix('0 1 0 0; 1 0 1 0; 0 1 0 1; 0 0 1 0')
g2 = np.matrix('0 1; 1 0')
l1 = csgraph.laplacian(g1, normed=False)
l2 = csgraph.laplacian(g2, normed=False)
d = []
for i in range(0,4):
R = l1
R[i]=np.eye(4)[i]
d.append(np.diagonal(drazin_inverse(R)))
i = i+1
print(np.vstack((d))[1,3],'\n', np.vstack((d)))
e = []
for i in range(0,2):
R = l2
R[i]=np.eye(2)[i]
e.append(np.diagonal(drazin_inverse(R)))
i=i+1
print(np.stack((e))[0,1],'\n', np.stack((e)))
|
class Board(object):
def __init__(self):
# Board spaces will be represented by a list. This list
# shows where the players have a mark or a space is empty.
# Indices relate to the board as follows:
#
# 0 | 1 | 2
# ---|---|---
# 3 | 4 | 5
# ---|---|---
# 6 | 7 | 8
self.__spaces = [False for index in xrange(9)]
self.numturn = 1
def draw(self):
self.__drawrow(0, 3)
print "\t ---|---|---"
self.__drawrow(3, 6)
print "\t ---|---|---"
self.__drawrow(6, 9)
def __drawrow(self, start, end):
print "\t ",
for index in xrange(start, end):
mark = [str(index + 1), self.__spaces[index]][self.__spaces[index] != False]
print "%s" % mark,
if index < (end - 1):
print "|",
print
def endgame(self):
"""We are at the end of the game if we have a winner or tie"""
# First check if we have a winner
if self.winner() == False:
# No winner, check for tie
return self.tie()
else:
return True
def is_empty(self, pos):
"""Return True if the position is empty, False if filled"""
return self.__spaces[pos] == False
def match_nummarks(self, mark, nummarks):
"""Return a list of empty positions given the number of marks to look for"""
empty_pos = []
numempties = 3 - nummarks
# Check rows
for start in xrange(0, 9, 3):
self._get_empty_pos(xrange(start, start + 3), mark, nummarks, numempties, empty_pos)
# Check columns
for index in xrange(3):
self._get_empty_pos(xrange(index, 9, 3), mark, nummarks, numempties, empty_pos)
# Check diagonals
self._get_empty_pos(xrange(0, 9, 4), mark, nummarks, numempties, empty_pos)
self._get_empty_pos(xrange(2, 8, 2), mark, nummarks, numempties, empty_pos)
return empty_pos
def _get_empty_pos(self, pos_range, mark, nummarks, numempties, empty_pos):
"""Return positions of empty spaces given # marks criteria"""
filled = []
empty = []
for pos in pos_range:
if self.__spaces[pos] == mark:
filled.append(pos)
elif self.__spaces[pos] == False:
empty.append(pos)
if len(filled) == nummarks and len(empty) == numempties:
empty_pos.extend(empty)
def setmark(self, pos, name, mark):
"""Set a player's mark in the given position. Return True if
successful, False otherwise"""
if self.__spaces[pos] == False:
print "\n%s places an '%c' in position %d." % (name, mark, pos + 1)
self.__spaces[pos] = mark
self.numturn += 1
return True
else:
return False
def tie(self):
"""Return True if there is a tie game, False if not"""
empty = filter(lambda value: value == False, self.__spaces)
# I realize winner() is called twice in rapid succession,
# once in endgame() and then again here since endgame()
# calles tie(). If this were a real product and winner()
# took any real time to run, we would have to optimize
# so that it wasn't called twice (cache the result from
# the first time perhaps and/or rearrange the IF statements).
#
# This being a simple game and winner() running fast enough
# not to notice, should I invest the time? I made the
# tradeoff (time to code vs speed of execution) to not worry
# about it.
#
# It is still useful to comment about potential problems,
# and so is documented here.
return len(empty) == 0 and not self.winner()
def winner(self):
"""Return the mark of the winner, False if no winner"""
spaces = self.__spaces
# Check rows
for index in xrange(0, 9, 3):
if spaces[index] != False and \
spaces[index] == spaces[index + 1] and \
spaces[index] == spaces[index + 2]:
return spaces[index]
# Check columns
for index in xrange(3):
if spaces[index] != False and \
spaces[index] == spaces[index + 3] and \
spaces[index] == spaces[index + 6]:
return spaces[index]
# Check diagonals
if spaces[0] != False and spaces[0] == spaces[4] and spaces[0] == spaces[8]:
return spaces[0]
if spaces[2] != False and spaces[2] == spaces[4] and spaces[2] == spaces[6]:
return spaces[2]
return False
|
dict1 = {}
dict1['one'] = '1'
dict1[2] = '2'
tinydict = {'name':'bloodymandoo','code':1,'site':'www.bloodymandoo.com'}
print(dict1['one'])
print(dict1[2])
print(tinydict)
print(tinydict.keys())
print(tinydict.values())
dict1 = dict([('Python',1),('Google',2),('Taobao',3)])
print(dict1)
dict2 = {x:x**2 for x in (2,4,6)}
print(dict2)
dict3 = dict(Python=1,Google=2,Taobao=3)
print(dict3)
|
'''
String to atoi
1. discards whitespace characters
2. optional intital plus and minus sign
3. string can contain additional characters
Input: "42"
Output: 42
Input: " -42"
Output: -42
Input: "4193 with words"
Output: 4193
Input: "words and 987"
Output: 0
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Therefore INT_MIN (−231) is returned.
'''
INT_MAX = 2147483647
INT_MIN = -2147483648
class solution:
def atoi(self, str):
pointer = 0
isNegative = False
#loop
while pointer<len(str) and str[pointer] == '':
pointer += 1
# null condition
if pointer == len(str):
return 0
# - or + sign set the flag
if str[pointer] == '-':
isNegative = True
pointer += 1
elif str[pointer] == '+':
isNegative = False
pointer += 1
solution = 0
for pointer in range(pointer, len(str)):
# check if its numeric
if not str[pointer].isdigit():
break
else:
solution *= 10
solution += int(str[pointer])
# if no valid conversion is found
if not isNegative and solution > INT_MAX:
return INT_MAX
elif isNegative and solution > INT_MAX:
return INT_MIN
if isNegative:
return -1 * solution
else:
return solution
|
'''
Given a linked list change it in sorted order
Merge sort
1. if head is null
one element in the linked list then return
2. else divide linked list in two halves
3. Sort the two halves
MergeSort(a)
MergeSort(b)
4. Merge the sorted a and b and
update the header pointer using
headRef
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
class MergeSort:
def __init__(self):
self.head = None
def get_mid(self, head, end):
# cursor is at head
current = head
size = 0
# loop through the linked list
for i in range(0, size/2):
current = current.next
return current
def sort(self, head, end=None):
if head is end: return head
if end is not None:
end.next = None
mid = self.get_mid(head, end)
head2 = sort(mid.next, end, level+1)
|
el = [10, 10, 53, 20, 30, 40, 59, 40]
k = 2
def kth_largest(input_list, k):
# initialize the top_k list to first k elements and sort descending
top_k = input_list[0:k]
top_k.sort(reverse = True)
for i in input_list[k:]:
if i > top_k[-1]:
top_k.pop() # remove the lowest of the top k elements
top_k.append(i) # add the new element
top_k.sort(reverse = True) # re-sort the list
return top_k[-1] # return the kth largest
if __name__ == "__main__":
print(kth_largest(el, k))
|
'''
This is the return book module for the user to return a book.
It imports booklist.py and datetime modules in order to access their main functions.
It imports the 2D list of books from booklist.py for the user to return a book and see if it is present in the library or not.
It then stores a record of the user in a text file 'returned_details.txt'.
The module datetime is imported from the python library to save the date of borrow of the user to save their record.
'''
import datetime
import booklist as b
booklst=b.listing2d() #saving the list of books in booklst from booklist.py
dash='-'*95 #declaring a variable to design the program whilst printing
today = datetime.date.today() #declaring a variable that stores today's date i.e. the day of borrow of book.
'''
This function takes the user's name as input from the user and checks if the name exists in the record of borrow in 'borrow_details.txt'.
If the name exists, it returns all of the borrowed books and prints a message else it returns the user back to the menu
This function returns nothing.
'''
def return_book():
norecord=True
global returned
returned = []
readborrowfile()
returner=input("Please enter your name again: ")
for i in range(len(lst2)):
if returner==lst2[i][0]:
returned.append(lst2[i])
#print(returned)
returneddetails()
norecord=False
lst.remove(lst2[i])
print("ThankYou for returning the book.")
if norecord==True:
print("Sorry, your name doesn't exist in our database.")
updatebooklist()
overwrite_txt()
#print(returned)
#print(ret)
print(dash)
print()
#print(lst2)
#print(returned)
#function reads the record of borrow in 'borrow_details.txt' and saves it in a 2D list. This function returns nothing.
def readborrowfile():
file=open("borrow_details.txt","r")
content=file.readlines()
file.close()
global lst
global lst2
lst=[]
lst2=[]
for i in range(len(content)):
lst.append(content[i].replace("\n","").split(","))
lst2.append(content[i].replace("\n","").split(","))
#function stores a record of the user to return a book in a 2D list'. This function returns nothing.
def returneddetails():
global ret
ret=[]
for i in range (len(returned)):
details=returned[i][0]+","+returned[i][1]+","+returned[i][2]+","+str(today)+"\n"
ret.append(details)
writereturnfile(ret)
#function writes the record of the user in a text file 'returns_details.txt'. This function returns nothing.
def writereturnfile(returnedlist):
file=open("returned_details.txt","a")
for each in returnedlist:
file.write(each)
file.close()
#function that updates the list of books in stock in 'books.txt' file that increases the quantity of the book that user returned. This function returns the new list with the updated quantity.
def updatebooklist():
global updatelist
updatelist=[]
for j in range (len(returned)):
for k in range (len(booklst)):
if returned[j][1]==booklst[k][1]:
newqty=int(booklst[k][3])+int(returned[j][2])
booklst[k][3]=str(newqty)
updatelist=booklst
return updatelist
#function that overwrites the list of books in 'books.txt' file with increases the quantity of the book that user had returned. This function returns nothing.
def overwrite_txt():
a=updatelist
file=open("books.txt","w")
for i in range(len(a)):
counter=1
for j in range(len(a[i])):
file.write(a[i][j])
if counter <=4:
file.write(",")
counter+=1
file.write("\n")
file.close()
|
import string
def get_word(file):
d = dict()
count = 0
#获取每一行
for f in file:
word_list = f.split(" ")
#取到单行的每个单词
for word in word_list:
table = str.maketrans(string.punctuation," " * len(string.punctuation))
word = word.translate(table).strip()
if word != "":
d[word] = d.get(word,0) + 1
count += 1
print(count)
print(d)
#降序排列
word_sort = sorted(d.items(), key=lambda d: d[1], reverse=True)
print(word_sort)
#取使用频率前10个
for i in range(10):
print(word_sort[i]) # ('the', 3850)
print(word_sort[i][0]) #the
file = open("THE_SUBSTITUTE_MOLLONAIRE.txt","r",encoding="utf-8")
get_word(file)
|
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "(%g, %g)" % (self.x, self.y)
def print_point(self):
print("(%g, %g)" % (self.x, self.y))
def __add__(self, other):
if isinstance(other, Point):
self.x += other.x
self.y += other.y
return self
elif isinstance(other, tuple):
self.x += other[0]
self.y += other[1]
return self
p = Point(3)
#p.print_point()
print(p)
p1 = Point(2,3)
print(p + p1)
p2 = (1,2)
print(p + p2)
vars(p)
|
# #01 - Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com essa formatação:
# [ 1 ][ 2 ][ 3 ]
# [ 4 ][ 5 ][ 6 ]
# [ 7 ][ 8 ][ 9 ]
# linha_1 = input("Linha 1: Escreva 3 números separados por espaço").split()
# linha_2 = input("Linha 2: Escreva 3 números separados por espaço").split()
# linha_3= input("Linha 3: Escreva 3 números separados por espaço").split()
# matriz = [list(map(int, linha_1)),list(map(int, linha_2)),list(map(int, linha_3))]
# # matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# for j in matriz:
# print(f'''
# [ {matriz[0][0]} ][ {matriz[0][1]} ][ {matriz[0][2]} ]
# [ {matriz[1][0]} ][ {matriz[1][1]} ][ {matriz[1][2]} ]
# [ {matriz[2][0]} ][ {matriz[2][1]} ][ {matriz[2][2]} ]
# ''')
matriz = []
somaPares= 0
terceira = 0
for i in range(3):
linha = []
for j in range(3):
valor = int(input(f'Escreva um número da linha {i+1} e coluna {j+1}:'))
linha.append(valor)
matriz.append(linha)
for i in matriz:
print()
for j in i:
print(f'[ {j} ]',end=' ')
if j % 2 == 0:
somaPares += j
print(f'A soma dos n pares {somaPares}')
# #02 - Aprimore o desafio anterior, mostrando no final:
# A) A soma de todos os valores pares digitados.
# B) A soma dos valores da terceira coluna.
# C) O maior valor da segunda linha.
#03 - Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista, depois do dado inserido, pergunte ao usuário se ele quer continuar, se ele não quiser pare o programa. No final mostre:
# Quantas pessoas foram cadastradas
# Mostre o maior peso
# Mostre o menor peso
# lista = []
# while True:
# nome = input('Escreva seu nome: ')
# peso = int(input('Escreva seu peso: '))
# lista.append([nome,peso])
# finalizar = input('Você quer finalizar? [S/N] ').strip().upper()[0]
# if finalizar == 'S':
# break
# else:
# continue
# print(lista)
# for i, c in enumerate(lista):
# if lista[i][1] > 18:
# print(f'{lista[i][0]} é maior de idade')
# else:
# print (f'{lista[i][0]} é menor de idade')
# print (f'{maior} pessoas são maiores de idade e {menor} pessoas menores de idade.')
|
# Utilizando os conceitos aprendidos até dicionários, crie um programa onde 4
# jogadores joguem um dado e tenham resultados aleatórios.
# O programa tem que:
# • Perguntar quantas rodadas você quer fazer;X
# • Guardar os resultados dos dados em um dicionário.
# • Ordenar esse dicionário, sabendo que o vencedor tirou o maior número
# no dado.
# • Mostrar no final qual jogador ganhou mais rodadas e foi o grande
# campeão.
# Obs: O projeto deve ser feito individualmente e entregue até o final da aula 16
import random
from operator import itemgetter
from time import sleep
from rich.progress import track
from rich import print
jogador1=jogador2=jogador3=jogador4=empate=0
times = int(input('Número de rodadas:'))
for c in range(times):
print(f'[green]Rodada {c+1}[/green]')
jogadas = {
'jogador 1':random.randint(1,6),
'jogador 2':random.randint(1,6),
'jogador 3':random.randint(1,6),
'jogador 4':random.randint(1,6)
}
sorteio = []
sorteio = sorted(jogadas.items(), key=itemgetter(1), reverse=True)
for i, d in enumerate(sorteio):
print(f'[bold blue]{i+1}º lugar[/bold blue]: [yellow]{d[0]}[/yellow] com {d[1]}')
sleep(1)
if jogadas['jogador 1']> jogadas['jogador 2'] and jogadas['jogador 4']<jogadas['jogador 1']>jogadas['jogador 3']:
jogador1 +=1
elif jogadas['jogador 2']> jogadas['jogador 1'] and jogadas['jogador 4']<jogadas['jogador 2']>jogadas['jogador 3']:
jogador2 +=1
elif jogadas['jogador 3']> jogadas['jogador 2'] and jogadas['jogador 4']<jogadas['jogador 3']>jogadas['jogador 1']:
jogador3 +=1
elif jogadas['jogador 4']> jogadas['jogador 2'] and jogadas['jogador 3']<jogadas['jogador 4']>jogadas['jogador 1']:
jogador4 +=1
for c in range(5):
sleep(0.3)
print('∎',end=' ')
sleep(0.3)
print('□',end=' ')
print()
for n in track(range(3), description="Carregando resultado..."):
sleep(1)
if jogador1 == jogador2 and jogador2 ==jogador3 and jogador1==jogador4 and jogador4==jogador2 and jogador3==jogador4 and jogador3==jogador1:
print('Ninguém ganhou')
elif jogador4<jogador1>jogador2 and jogador1>jogador3:
print('[bold red]O jogador 1 ganhou[/bold red]:1st_place_medal:')
elif jogador4<jogador2>jogador1 and jogador2>jogador3:
print('[bold red]O jogador 2 ganhou[/bold red]')
elif jogador4<jogador3>jogador2 and jogador3>jogador1:
print('[bold red]O jogador 3 ganhou[/bold red]')
elif jogador3<jogador4>jogador2 and jogador4>jogador1:
print('[bold red]O jogador 4 ganhou[/bold red]')
else:
print('A quantidade de vitórias foi igual. Não há vencedores.')
|
# Faça um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de nascimento de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL ou OBRIGATÓRIO nas eleições:
def voto(ano):
idade = 2021 - ano
if idade < 16:
return 'Voto negado'
elif 16<=idade<18 or idade >= 70:
return 'Voto opcional'
else:
return 'Voto obrigatório'
ano = int(input('Ano de nascimento:'))
print(voto(ano))
# Faça um programa, com uma função que necessite de um parametro. A função retorna o valor de caractere ‘P’, se seu argumento for positivo, e ‘N’, se seu argumento for zero ou negativo.
def vem(n):
if n>0:
return 'P'
else:
return 'N'
resultado = vem(int(input('Informe um número:')))
print(resultado)
# Faça um programa em Python com uma função que necessite de três parametros, e que forneça:
# A soma desses três parametros através de uma função.
# Seu script também deve fornecer a média dos três números, através de uma segunda função que chama a primeira.
def numeros(n1,n2,n3):
valor = n1 + n2 + n3
return valor
def media_func():
media = numeros(float(input('Nota 1: ')),int(input('Nota 2: ')),int(input('Nota 3: ')))/3
return media
print(f'A média é {media_func():.2f}')
|
#!/usr/bin/env python3
nums = [101,2,15,22,95,33,2,27,72,15,52]
evens = [num for num in nums if num%2==0]
print(evens)
|
#!/usr/bin/env python3
lines_num = 0
char_num = 0
with open("Python_05.fastq","r") as fastq_obj:
for line in fastq_obj:
print('This line length:', len(line))
line = line.rstrip()
lines_num += 1
char_num = char_num + len(line)
print('total lines:', lines_num)
print('total chars:', char_num)
print('Ave line length:', char_num/lines_num)
|
import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [ ['Nikhil', 'COE', '2', '9.0'],['Sanchit', 'COE', '2', '9.1'],['Aditya', 'IT', '2', '9.3'] ]
filename = 'record.csv'
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
print ('done !!')
|
# Getting Started Assignment 1:
# Given the below list of dictionaries, write code to:
# -- iterate through the list of dictionaries;
# -- for each dictionary, check whether the make is a Honda;
# -- if make is Honda, print the color year Honda model
# -- Precede the list with text intro
# Your output should look like:
# Hondas currently in stock include:
# Black 2010 Honda Accord
# Gray 1999 Honda Civic EX
# here's the list of dictionaries:
cars = [{'make': 'Toyota', 'year': 2013, 'color': 'Silver', 'model': 'Corolla'},
{'make': 'Honda', 'year': 2010, 'color': 'Black', 'model': 'Accord'},
{'make': 'Ford', 'year': 2001, 'color': 'Blue', 'model': 'Mustang'},
{'make': 'Honda', 'year': 1999, 'color': 'Gray', 'model': 'Civic EX'}]
|
# Array of unique, consecutive natural numbers such that allow all rows, all columns, and both of the main diagonals have the same sum
def verifysquare(square):
sums = []
rowsums = [sum(square[i]) for i in range(0,len(square))]
sums.append(rowsums)
colsums = [sum([row[i] for row in square]) for i in range(0,len(square))]
sums.append(colsums)
maindiag = sum([square[i][i] for i in range(0,len(square))])
sums.append([maindiag])
antidiag = sum([square[i][len(square) - 1 - i] for i in range(0,len(square))])
sums.append([antidiag])
flattened = [j for i in sums for j in i]
return(len(list(set(flattened))) == 1)
luoshu = [[4,9,2],[3,5,7],[8,1,6]]
"""
4 9 2
3 5 7
8 1 6
"""
print(verifysquare(luoshu))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.