blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
8ce392826544ef888ea49ea02a3e85364f6926f7 | grupyrp/dojos | /2016-03-24/batalha_naval.py | 10,652 | 3.640625 | 4 | #!/usr/bin/env python
import itertools
import unittest
import random
from copy import deepcopy
class BattleShipTest(unittest.TestCase):
def test_board_size(self):
game = BattleShip()
assert game.get_size() == 100
def test_ships_qt(self):
game = BattleShip()
assert len(game.get_all_ships()) == 10
def test_create_board(self):
board = Board(10, 10)
assert board.cols == 10
assert board.rows == 10
def test_create_board_small(self):
board = Board(3, 2)
matrix = [[0, 0],
[0, 0],
[0, 0]]
assert board.matrix == matrix
def test_create_matrix(self):
matrix = [[0 for i in range(10)] for j in range(10)]
board = Board(10, 10)
assert board.matrix == matrix
def test_ship_init_count(self):
board = Board(10, 10)
flat_board = list(itertools.chain(*board.matrix))
assert flat_board.count(0) == 100
def test_ship_count_with_ships(self):
board = Board(10, 10)
board.add_ships(_random=False)
flat_board = list(itertools.chain(*board.matrix))
for key, value in Board.ships.items():
self.assertEqual(value, flat_board.count(key))
def test_ship_random_count_with_ships(self):
board = Board(10, 10)
board.add_ships(_random=True)
flat_board = list(itertools.chain(*board.matrix))
for key, value in Board.ships.items():
self.assertEqual(value, flat_board.count(key))
def test_validatepos(self):
board = Board(10, 10)
self.assertTrue(board.validate_pos(0, 0))
board.matrix[2][3] = 1
self.assertFalse(board.validate_pos(2, 3))
def test_constants(self):
self.assertEqual(Board.CARRIER, 1)
self.assertEqual(Board.BATTLESHIP, 2)
self.assertEqual(Board.DESTROYER, 3)
self.assertEqual(Board.SUBMARINE, 4)
self.assertEqual(Board.PATROL_BOAT, 5)
def test_miss_attack(self):
board = Board(10, 10)
self.assertEqual(board.receive_attack(0, 0), False)
def test_hit_attack(self):
board = Board(10, 10)
board.add_ships()
self.assertEqual(board.receive_attack(0, 0), True)
def test_empty_attack_list(self):
board = Board(10, 10)
self.assertEqual(len(board.history), 0)
def test_insert_attack_list_empty_board(self):
board = Board(10, 10)
board.receive_attack(0, 0)
self.assertEqual(board.history[0], (0, 0, False))
def test_insert_attack_list_full_board(self):
board = Board(10, 10)
board.add_ships()
board.receive_attack(0, 0)
self.assertEqual(board.history[0], (0, 0, True))
def test_gameover_false(self):
board = Board(10, 10)
board.add_ships()
self.assertFalse(board.game_over())
def test_plot_empty_board(self):
board = Board(10, 10)
board_str = """------------
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
------------"""
self.assertEqual(board_str, board.plot())
def test_plot_full_board(self):
board = self._get_full_board()
board_str = """------------
|11111~~~~~|
|2222~~~~~~|
|333~~~~~~~|
|444~~~~~~~|
|55~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
------------"""
self.assertEqual(board_str, board.plot())
def test_plot_full_board_with_shots(self):
board = self._get_full_board()
board.receive_attack(1, 1)
board.receive_attack(2, 2)
board.receive_attack(8, 0)
board.receive_attack(9, 0)
board.receive_attack(4, 1)
board.receive_attack(1, 4)
board_str = """------------
|11111~~~~~|
|2x22o~~~~~|
|33x~~~~~~~|
|444~~~~~~~|
|5x~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|o~~~~~~~~~|
|o~~~~~~~~~|
------------"""
self.assertEqual(board_str, board.plot())
def test_plot_full_board_with_shots_without_ship(self):
board = self._get_full_board()
board.receive_attack(1, 1)
board.receive_attack(2, 2)
board.receive_attack(8, 0)
board.receive_attack(9, 0)
board.receive_attack(4, 1)
board.receive_attack(1, 4)
board_str = """------------
|~~~~~~~~~~|
|~x~~o~~~~~|
|~~x~~~~~~~|
|~~~~~~~~~~|
|~x~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|o~~~~~~~~~|
|o~~~~~~~~~|
------------"""
self.assertEqual(board_str, board.plot(show_ships=False))
def test_add_ships(self):
board = Board(10, 10)
self.assertTrue(board.add_ship(0, 0, board.HORIZONTAL, board.CARRIER))
self.assertTrue(board.add_ship(1, 0, board.VERTICAL, board.BATTLESHIP))
def test_add_ship_same_place_fail(self):
board = Board(10, 10)
self.assertTrue(board.add_ship(0, 0, board.HORIZONTAL, board.CARRIER))
self.assertFalse(board.add_ship(0, 0, board.HORIZONTAL, board.CARRIER))
def test_add_ship_out_of_board_matrix_restore(self):
board = Board(10, 10)
board.add_ship(9, 9, board.HORIZONTAL, board.CARRIER)
flat_board = list(itertools.chain(*board.matrix))
self.assertEquals(100, flat_board.count(0))
def test_add_ship_colliding_ships_matrix_restore(self):
board = Board(10, 10)
board.add_ship(0, 1, board.HORIZONTAL, board.CARRIER)
current_matrix = deepcopy(board.matrix)
board.add_ship(0, 0, board.HORIZONTAL, board.CARRIER)
self.assertEquals(current_matrix, board.matrix)
def test_fail_add_ships_out_of_boards(self):
board = Board(10, 10)
self.assertFalse(board.add_ship(10, 0, board.VERTICAL,
board.SUBMARINE))
self.assertFalse(board.add_ship(9, 0, board.VERTICAL, board.CARRIER))
def test_matrix_fail_add_ships(self):
board = Board(10, 10)
matrix = deepcopy(board.matrix)
board.add_ship(10, 0, board.VERTICAL, board.SUBMARINE)
self.assertEqual(matrix, board.matrix)
def _get_full_board(self):
board = Board(10, 10)
board.add_ship(0, 0, board.HORIZONTAL, board.CARRIER)
board.add_ship(1, 0, board.HORIZONTAL, board.BATTLESHIP)
board.add_ship(2, 0, board.HORIZONTAL, board.DESTROYER)
board.add_ship(3, 0, board.HORIZONTAL, board.SUBMARINE)
board.add_ship(4, 0, board.HORIZONTAL, board.PATROL_BOAT)
return board
class Board(object):
VERTICAL = 'vertical'
HORIZONTAL = 'horizontal'
CARRIER = 1
BATTLESHIP = 2
DESTROYER = 3
SUBMARINE = 4
PATROL_BOAT = 5
ships = {
CARRIER: 5, # porta-avioes
BATTLESHIP: 4, # encouracado
DESTROYER: 3, # destroier
SUBMARINE: 3, # submarino
PATROL_BOAT: 2 # barco de patrulha
}
def __init__(self, rows, cols):
self.cols = cols
self.rows = rows
self.create_matrix()
self.history = []
self.attacks = {}
def add_ship(self, row, col, orientation, ship):
matrix = deepcopy(self.matrix)
result = True
ship_size = self.ships[ship]
if (orientation == self.VERTICAL and row + ship_size > self.rows) or \
(orientation == self.HORIZONTAL and col + ship_size > self.cols):
return False
if orientation == self.HORIZONTAL:
for i in range(col, col + self.ships[ship]):
if self.matrix[row][i] == 0:
self.matrix[row][i] = ship
else:
result = False
break
else:
for i in range(row, row + self.ships[ship]):
if self.matrix[i][col] == 0:
self.matrix[i][col] = ship
else:
result = False
break
if not result:
self.matrix = matrix
return result
def add_ships(self, _random=False):
if _random:
for key, value in self.ships.items():
consegui = False
while not consegui:
x = random.randint(0, self.rows - 1)
y = random.randint(0, self.cols - 1)
orientation = random.choice([self.HORIZONTAL,
self.VERTICAL])
consegui = self.add_ship(x, y, orientation, key)
else:
i = 0
for key, value in self.ships.items():
self.add_ship(i, 0, self.HORIZONTAL, key)
i += 1
def validate_pos(self, x, y):
return self.matrix[x][y] == 0
def create_matrix(self):
self.matrix = [[0 for i in range(self.cols)] for j in range(self.rows)]
def receive_attack(self, row, col):
value = self.matrix[row][col]
self.history.append((row, col, bool(value)))
key = '{}-{}'.format(row, col)
self.attacks[key] = bool(value)
return bool(value)
def game_over(self):
shipcount = sum(self.ships.values())
hitcount = len(filter(lambda x: x[2], set(self.history)))
return hitcount == shipcount
def plot(self, show_ships=True):
if list(itertools.chain(*self.matrix)).count(0) == 100:
return """------------
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
|~~~~~~~~~~|
------------"""
else:
plot = []
start = '-' * 12 + '\n'
end = '-' * 12
for ridx, row in enumerate(self.matrix):
plot.append('|')
for cidx, col in enumerate(row):
key = '{}-{}'.format(ridx, cidx)
if key in self.attacks:
if self.attacks[key]:
v = 'x'
else:
v = 'o'
else:
if show_ships:
v = "~" if col == 0 else str(col)
else:
v = "~"
plot.append(v)
plot.append('|\n')
return start + "".join(plot) + end
class BattleShip(object):
size = [10, 10]
boards = ()
def get_size(self):
return self.size[0] * self.size[1]
def get_all_ships(self):
return range(10)
def create_board(self):
return [self.size[0], self.size[1]]
if __name__ == '__main__':
unittest.main()
|
804e72977310b47f5127ce844c7d7083a106577c | David-GaTre/Python-the-hard-way | /pythonPractice/ex25.py | 2,763 | 4.25 | 4 | #the split() divides whatever you have, between the () you put the separater
#by default is a ' ', we write it anyways
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
#sorts the sentence, but it always put capital letters at the beggining
#to avoid this you can change the key like
#sorted(var, key=lambda v: v.upper())
#obtained from https://stackoverflow.com/questions/13954841/sort-list-of-strings-ignoring-upper-lower-case
def sort_words(words):
"""Sorts the words."""
return sorted(words)
#pop() takes the value indicated and puts it into the stack, is erased from the
#original, let's call it "list", in this case 0 indicates the first value
def print_first_word(words):
"""Prints the first words after popping it off."""
word = words.pop(0)
print word
#same as the above with the difference of the -1, that takes the last value of the
#"list"
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and return the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
#this exercise is for working out in the console, it is by running python directly
#then write "import ex25", while in the same folder, to create a module for the
#functions, as we can see, this are only functions. Then, we can create variables
#within the console to work with, as MySentence = "Well, hello there.". There, we
#can execute every function that we want directly like this:
#ex25.sort_sentence(MySentence)
#and we can display what is on each variable by just writing the name of the variable
#
#VERY USEFUL: you can write help(nameOfYourModule) (or name of the function
#in the console (WYSS) for
#getting help of your own module, that's the usefulness of the sentences after the
#functions, they are useful as documentation. It is displayed like this:
#FILE
#ex25
#FUNCTIONS
#print_last_word
#Prints the last word after popping it off.
#
#That is an example, that's why it is important to document after each function.
#
#VERY USEFUL 2: to avoid writing "ex25." before each function we can also, from
#the import part write it like this "from /nameOfModule/ import *" and then all
#the functions will be there. Be careful when importing various as function names
#could not be overloaded correctly |
2a5ec1cf241e6417a8843c5181d8d6d8d0cbb6be | houdinis/python-study | /regression/work1/rhombus.py | 365 | 4.03125 | 4 | # 打印下面的菱形
# *
# ***
# *****
# *******
# *****
# ***
# *
#
number = 7
def rhom(number):
num = number // 2
for row in range(num, (-num-1), -1):
star = row if row >= 0 else -row
print(" " * star + "*" * (number - 2 * star) + " " * star)
rhom(number)
|
1e413d5450c139654a9f8fde42da8dee9fcd5435 | xiangliang-zhang/newcode_test | /中级班/第一章/class4.py | 1,520 | 3.703125 | 4 | class Heap:
def __init__(self):
self.value = []
def get_parent_index(self, index):
if index == 0 or index > len(self.value) - 1:
return None
else:
return (index - 1) >> 1 # >> 二进制右移运算符,相当于除以2
def swap(self, index1, index2):
self.value[index1], self.value[index2] = self.value[index2], self.value[index1]
def insert(self, data):
self.value.append(data)
index = len(self.value) - 1
parent_index = self.get_parent_index(index)
while parent_index is not None and self.value[parent_index] < data:
self.swap(parent_index, index)
index = parent_index
parent_index = self.get_parent_index()[parent_index]
def removeMax(self):
remove_data = self.value[0]
self.value[0] = self.value[-1]
del self.value[-1]
self.heapify(0)
return remove_data
def heapify(self, index):
total_index = len(self.value) - 1
while True:
maxvalue_index = index
if 2 * index + 1 <= total_index and self.value[2 * index + 1] > self.value[maxvalue_index]:
maxvalue_index = 2 * index + 1
if 2 * index + 2 <= total_index and self.value[2 * index + 2] > self.value[maxvalue_index]:
maxvalue_index = 2 * index + 1
if maxvalue_index == index:
break
self.swap(index, maxvalue_index)
index = maxvalue_index
|
67425a9288a28c466311ef747afb6085c47b88bf | meherchandan/python-exercise | /ListOverlap.py | 232 | 4.03125 | 4 | def listoverlap():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
result = set(item for item in a if item in b )
print(result)
if(__name__=="__main__"):
listoverlap() |
2d9e1b3e8905d0c87d9b60470483136759083152 | dvpcloud/py_entry_cert | /bio.py | 473 | 4.25 | 4 | name = input ("what is your name ? ")
colour = input("what is your favourite colour ?")
age = int(input("what is your age ? "))
print(f"{name} is {age} years old and favourite colout is {colour}")
#other way of printing things
print(name,end=" ")
print("is "+ str(age) + " years old", end = " ")
print("and likes colour " + colour + ".", end = " ")
#other way of printing things
print(name,"is ",str(age)," years old", " and likes colour " , colour + ".", sep = " - ")
|
0676fde8578e5d4fb97e4fe65309538e65083834 | yabeiwu/das | /das/dataset/box.py | 4,090 | 3.53125 | 4 | import numpy as np
class LatticeError(Exception):
"""
Exception class for Structure.
Raised when the structure has problems, e.g., atoms that are too close.
"""
pass
class Box:
def __init__(self, matrix):
try:
m = np.array(matrix, dtype=np.float64).reshape((3, 3))
except:
raise LatticeError("new_lattice must be length 9 sequence or 3x3 matrix!")
m.setflags(write=False)
self._matrix = m
@property
def matrix(self):
return self._matrix
@property
def volume(self):
return abs(np.linalg.det(self._matrix))
@property
def lengths(self):
return np.linalg.norm(self._matrix, axis=1)
@property
def angles(self):
"""
Returns the angles (alpha, beta, gamma) of the lattice.
https://en.wikipedia.org/wiki/Lattice_constant
"""
m = self._matrix
angles = np.zeros(3)
for i, ii in enumerate([[1, 2], [2, 0], [0, 1]]):
angles[i] = self.vector_angle(*self._matrix[ii])
angles = np.rad2deg(angles)
return angles
@property
def is_orthorhombic(self):
"""Check that lattice matrix is diagonal."""
return np.all(self._matrix == np.diag(np.diagonal(self._matrix)))
@property
def reciprocal_lattice(self):
"""
Return the reciprocal lattice with a factor of 2 * pi.
"""
v = np.linalg.inv(self._matrix).T
return Box(v * 2 * np.pi)
@property
def reciprocal_lattice_crystallographic(self):
"""
Returns the *crystallographic* reciprocal lattice, i.e., no factor of
2 * pi.
"""
return Box(self.reciprocal_lattice.matrix / (2 * np.pi))
def cart_to_frac(self, cart_coords):
return cart_coords @ np.linalg.inv(self._matrix)
def frac_to_cart(self, frac_coords):
return frac_coords @ self._matrix
def __repr__(self):
return (
f"{self.__class__.__name__}("
+ f'[[{",".join(map(repr, self._matrix[0]))}],'
+ f'[{",".join(map(repr, self._matrix[0]))}],'
+ f'[{",".join(map(repr, self._matrix[0]))}]]'
+ ")"
)
def __str__(self):
outs = [
"Lattice",
" abc : " + " ".join(f"{i:.6f}" for i in self.lengths),
" angles : " + " ".join(f"{i:.6f}" for i in self.angles),
f" volume : {self.volume:.6f}",
" A : " + " ".join(f"{i:.6f}" for i in self._matrix[0]),
" B : " + " ".join(f"{i:.6f}" for i in self._matrix[1]),
" C : " + " ".join(f"{i:.6f}" for i in self._matrix[2]),
]
return "\n".join(outs)
def __eq__(self, other):
return False if other is None else np.allclose(self._matrix, other.matrix)
def __ne__(self, other):
return not self.__eq__(other)
def copy(self):
return Box(self._matrix.copy())
@classmethod
def cubic(cls, a):
return cls(np.eye(3) * a)
@classmethod
def tetragonal(cls, a, c):
return cls(np.diag([a, a, c]))
@classmethod
def orthorhombic(cls, a, b, c):
return cls(np.diag([a, b, c]))
@staticmethod
def vector_angle(v1, v2):
return np.arccos(np.dot(v1, v2) / np.linalg.norm(v1) / np.linalg.norm(v2))
def get_lmp_box(self):
new_matrix = np.zeros((3, 3))
a, b, c = self.lengths
alpha, beta, gamma = np.deg2rad(self.angles)
a_x = a
b_x = b * np.cos(gamma)
b_y = b * np.sin(gamma)
c_x = c * np.cos(beta)
c_y = (np.dot(self.matrix[1, :], self.matrix[2, :]) - b_x * c_x) / b_y
c_z = np.sqrt(c ** 2 - c_x ** 2 - c_y ** 2)
new_matrix[0] = [a_x, 0, 0]
new_matrix[1] = [b_x, b_y, 0]
new_matrix[2] = [c_x, c_y, c_z]
return new_matrix
@classmethod
def from_lmp_box(cls, lx, ly, lz, xy, xz, yz):
matrix = np.array([[lx, 0, 0], [xy, ly, 0], [xz, yz, lz]])
return cls(matrix)
|
599a8c4825ea36f15d4952e9cff2426578e9a388 | uathena1991/Leetcode | /Interview coding problems/gray number_two numbers 2.py | 356 | 3.6875 | 4 | class Solution(object):
def isgray(self,x,y):
"""
judge if two values are gray numbers or not.
:param x: in binary format
:param y: in binary format
:return: True or False
"""
res1 = x ^ y
count = 0
while res1 > 0:
res1,remain = divmod(res1,2)
if remain == 1:
count += 1
return count == 1
a = Solution()
print a.isgray(-0,1) |
3edcb08cb587a525eded328e6216b34745800a3d | Linkaje/RandomPasswordGenerator | /main.py | 505 | 4.25 | 4 | # Imports the random library
import random
# Asks the user for the length of the password and transforms it to int type
passlen = int(input("Enter the length of the password: "))
# Stores the available characters for the random password
s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*()?"
# Creates the password joining random characters from the ones we stored before and the length of the password
p = "".join(random.sample(s, passlen))
# Prints the final password
print(p) |
81396a941f4e2a6727494b91d320f19dc877602f | StefanoCiotti/MyPython01 | /MyFirstFl40.py | 599 | 4.25 | 4 | # list comprehension form = [item for item in range()]
example = [item for item in range(1, 10, 2)]
# ex1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ex1 = [num1 + 1 for num1 in range(10)]
# ex2 = [3, 6, 9, 12]
ex2 = [num2 * 3 for num2 in range(1, 5)]
# ex3 = [2, 4, 6, 8, 10]
ex3 = [num3 for num3 in range(2, 12, 2)]
# ex1 = [0, 2, 4, 6, 8]
ex1 = [num1 for num1 in range(10) if num1 % 2 == 0]
# ex2 = [0, 15, 30, 45, 60, 75, 90]
ex2 = [num2 for num2 in range(0, 99, 3) if num2 % 3 == 0 and num2 % 5 == 0]
# ex3 = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
ex3 = [num3 for num3 in range(1, 21) if num3 > 10]
|
ae87652b95821654fe535ce515c1ca953e5f493d | swjmy/do-something-with-Python | /the_way_to_learn_algorithms/sorting.py | 5,429 | 4.09375 | 4 | #后面各种排序需要用到的,交换l数组中的x,y
def swap(x,y,l):
l[x], l[y] = l[y], l[x]
#可能你也发现了,python中swap操作很方便,不需要单独写一个函数
#但是既然写了,就留下来当做笔记吧
#冒泡排序
def bubble_sort(l):
for j in range(len(l),0,-1):
for i in range(j):
# 循环到最后一个
if i == len(l) - 1:
break
# 排序结果为递增
if l[i] > l[i + 1]:
l[i], l[i + 1] = l[i + 1], l[i]
return l
def select_sort(l):
#这个min可以不设,然后每次假设第一个unsorted元素为min
#为了方便理解,加了这个min变量,不影响复杂度
min = l[0]
for i in range(0,len(l)):
for j in range(i,len(l)):
if l[j] < l[i]:
l[j],l[i] = l[i],l[j]
return l
#插入排序
#这是《introduce to algorithms》书中的算法
def insert_sort(l):
#和前几个排序算法一下,第一层遍历是为了区分sorted和unsorted
#第一层的i指向桌子上的牌unsorted
for i in range(1,len(l)):
#从右往左遍历手里的牌,找到找到一个比extracted小的牌,插入
extra = l[i]
j = i-1
while j >= 0 and l[j] > extra:
l[j+1] = l[j]
j = j -1
else:
l[j+1] = extra
return l
#这是慕课网上一网友写的,稍有不一样。
def insert_sort2(lists):
count = len(lists)
for i in range(1, count):
key = lists[i]
j = i - 1
while j >= 0:
if lists[j] > key:
lists[j + 1] = lists[j]
lists[j] = key
j -= 1
return lists
#归并排序是典型的分治思想
#归并排序主要有两种实现方法:
#❤分解待排序的n个元素的序列成各具n/2个元素的两个字序列,
# 然后递归排序这两个序列,最终递归到每个序列的长度为1
#❤split each element into partitions of size 1。
# 将n个元素分成n个带归并的序列,最后归并成一个。
#你发现了,没错,这两种方法实际就是同一个,只是方法一用递归实现
#l[p:r]:待排序的数组
def merge_sort(l,p,r):
'《算法导论》p17'
if p<r:
q=int((r+p)/2)
merge_sort(l,p,q)
merge_sort(l,q+1,r)
#此时,l[p:q]和l[q+1:r]都已经排好序,即简单情况
#但是为了能够在递归里使用这个函数,需要改的小细节很多,最主要的是
#l是整个数组,遍历和写回原数组的时候,下标不能从0开始,而是p→r
MERGE(l,p,q,r)
#这是归并排序的简单情况,楼上的方法用递归把问题分解成简单情况
#l:待排序数组,pqr是数组下标,p<q<r,假设l[p..q]和l[p+1..r]都已排好序
def MERGE(l,p,q,r):
#两个数组的元素个数
n1 = q-p+1
n2 = r-q
#新建两个数组,将l中的元素拷贝到这两个数组中
A=list(l[p:q+1])
R=list(l[q+1:r+1])
#建立哨兵
A.append(float("inf"))
R.append(float("inf"))
i = j = 0
for k in range(p,r+1):
#谁小,谁放回原数组中,然后index+1
if A[i] < R[j]:
l[k] = A[i]
i += 1
else:
l[k] = R[j]
j += 1
return l
#快速排序
#这是《算法导论》里介绍的算法,取最后一个元素l[high]为 pivot element
def quick_sort(l,low,high):
if low < high:
q = PARTITION(l,low,high)
quick_sort(l,low,q-1)
quick_sort(l,q+1,high)
return l
def PARTITION(l,p,r):
key = l[r]
#两个游标i,j。i指向最后一个值小于key的位置;j为遍历游标
i = p-1
j = p
#开始找有多少个小于等于key的值,每找到一个i+1
#这里要注意的是,j的遍历不包括r,因为最后遍历结束时,要把r上的值交换到i+1上
while j < r:
#找到一个
if l[j] <= key:
i+=1
l[i],l[j] = l[j],l[i]
j+=1
#遍历结束
l[i+1],l[r] = l[r],l[i+1]
return i+1
#这是计算机408里的方法,但是《算法导论》里的方法不一样
#这里取第一个元素l[p]为 pivot element
#主要思想是,两个游标分别从两边向中间遍历,直至相等。
#参考快速排序百度百科
def quick_sort_408(l, p, q):
low = p
high = q
if low >= high:
return l
key = l[low]
while low < high:
while low < high and l[high] > key:
high -=1
l[low],l[high] = l[high],l[low]
while low < high and l[low] < key:
low +=1
l[low], l[high] = l[high], l[low]
quick_sort_408(l, p, low - 1)
quick_sort_408(l, high + 1, q)
return l
if __name__ == '__main__':
pass
l = [13, 3, 2, 9, 1, 2, 0, 13, 6]
list = [5,3,2,9,1,6,7,8]
'快速排序'
#计算机408的算法
#print(quick_sort_408(list, 0, len(list) - 1))
#《算法导论》的算法
#print(quick_sort(list,0,len(list)-1))
'归并排序'
#简单情况
#l1 = [2,4,5,7,1,2,3,6]
#print(MERGE(l1,0,3,7))
#一般情况
#merge_sort(l, 0, len(l) - 1)
#print(l)
#
'插入排序'
# print(insert_sort(l))
# print(insert_sort2(l))
'选择排序测试'
#print(select_sort(l))
'冒泡排序测试'
# print(bubble_sort(l))
|
127bbb6061ea37db6d1174d9a324d187785ec101 | felipsdmelo/Numerical-Calculus | /Numerical Solution for ODE/euler_method.py | 1,255 | 3.90625 | 4 | def euler_method(x0, y0, xf, h, f) :
'''
Approximates the value of an ODE using Euler's Method
Keyword arguments:
x0 - initial value of x
y0 - initial value of y
xf - final value of x
h - size of the intervals (step)
f - function of x and y (usually the right side of the equation)
Returns:
An estimate for the ODE
'''
n = int ((xf - x0) / h) # number of iterations
x = x0
y = y0
yf = 0 # avoids local variable reference error
for i in range(n) :
yf = y + h * f(x, y)
x += h
y = yf
return yf
def improved_euler_method(x0, y0, xf, h, f)
'''
Approximates the value of an ODE using Improved Euler's Method,
also known as Heun's Method
Keyword arguments:
x0 - initial value of x
y0 - initial value of y
xf - final value of x
h - size of the intervals (step)
f - function of x and y (usually the right side of the equation)
Returns:
An estimate for the ODE
'''
n = int ((xf - x0) / h) # number of iterations
x = x0
y = y0
yf = 0 # avoids local variable reference error
for i in range(n) :
yf = y + h/2 * (f(x, y) + f(x + h, y + h * f(x, y)))
x += h
y = yf
return yf
|
703a6ab4588cf0a467e81a1b218b8d2449ccbaaa | JohannesBuchner/pystrict3 | /tests/expect-fail23/recipe-113657.py | 670 | 3.765625 | 4 | def classmethod(method):
return lambda self, *args, **dict: method(self.__class__, *args, **dict)
class Singleton:
count = 0
def __init__(klass):
klass.count += 1
print(klass, klass.count)
__init__ = classmethod(__init__)
def __getattr__(klass, name):
return getattr(klass, name)
__getattr__ = classmethod(__getattr__)
def __setattr__(klass, name, value):
setattr(klass, name, value)
__setattr__ = classmethod(__setattr__)
c = Singleton()
d = Singleton()
c.test = 'In d?'
print('c.test', c.test)
print('d.test', d.test)
output = '''
junk.Singleton 1
junk.Singleton 2
c.test In d?
d.test In d?
'''
|
a508948bab2c16c730e79736d127ed06f30020ee | yglj/learngit | /PythonPractice/乱七八糟的基础练习/判断字符串是否为数字.py | 352 | 3.734375 | 4 | import unicodedata
def is_number():
s = input()
try:
if( unicodedata.numeric(s) or float(s) ):
return True
except (ValueError,TypeError):
print("不是数字")
return False
#is_number()
if ( True or 3/0):
print("逻辑短路")
try:
if (3/0 or True):
print(0)
except :
print("zero error") |
a074452428044d20cb799a705f4f652e193ba795 | xJuggl3r/PY4E | /Assignments/12_3.py | 719 | 4.03125 | 4 | # Exercise 3: Use urllib to replicate the previous exercise of
# (1) retrieving the document from a URL,
# (2) displaying up to 3000 characters, and
# (3) counting the overall number of characters in the document.
# Don't worry about the headers for this exercise, simply show the first 3000 characters of the document contents.
import urllib.request, urllib.parse, urllib.error
url = input("Type the full url you want to connect: ")
fhand = urllib.request.urlopen(url)
content = fhand.read()
# Since we only need to print the full file if it's <= 3000
# we can specify the length (in bytes) to be read and print.
print(content[:3001].decode().strip())
print("\nDocument length is {}".format(len(content))) |
47e0fb2b2d5e3a79ef6b5eb530225f7c6b8cec7f | rednikon/python-programming-book | /circles.py | 386 | 4.25 | 4 | # pg. 76, problem 1: Mathematical expressions
import math
def get_volume():
radius = int(input("Let's calculate the volume and area of a circle. Please enter a value for the radius: "))
volume = 4 / 3 * (math.pi * radius**3)
area = 4 * math.pi * radius**2
print("The circle's volume is: ", round(volume, 2), "and the circle's area is: ", round(area, 2))
get_volume()
|
2049176f7ae9e0dfcc29ebca6f574be21312041e | antonin-lfv/plot_picture-python | /Convertir image en niveau de gris.py | 1,803 | 3.75 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
from PIL.Image import *
""" import the picture """
file = 'picture_path.png'
picture = open(file)
""" plot the picture """
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.299, 0.587, 0.144])
def plot_gray(file):
img = mpimg.imread(file)
gray = rgb2gray(img)
plt.imshow(gray, cmap = plt.get_cmap('gray'))
plt.show()
def plot_color(file):
imgpil = mpimg.imread(file)
img = np.array(imgpil)
plt.imshow(img)
plt.show()
#picture size
def width_Height(picture):
return(picture.size)
#convert the x,y pixel in gray
def turn_pixel_to_gray(x,y,picture):
s = 0.21*picture.getpixel((x,y))[0]+0.71*picture.getpixel((x,y))[1]+0.07*picture.getpixel((x,y))[2]
return(s/3)
#pixel value
def array_gray_pixels(picture):
l=[]
(width,Height)=width_Height(picture)
for x in range(Height):
for y in range(width):
l.append((turn_pixel_to_gray(y,x,picture)))
return(l)
def array_coloured_pixels(picture):
l=[]
(width,Height)=width_Height(picture)
for x in range(Height):
for y in range(width):
l.append((picture.getpixel((y,x))))
return(l)
""" summary of all algorithms """
def pixels(x,y,file): #(x=0 gray) or (x=1 color); (y=0 plot) or (y=1 no plot)
picture=open(file)
if x==0:
print(array_gray_pixels(picture))
if y==0:
plot_gray(file)
elif y!=1 :
print('WARNING! y must be 0 or 1 ')
elif x==1:
print(array_coloured_pixels(picture))
if y==0:
plot_color(file)
elif y!=1 :
print('WARNING! y must be 0 or 1 ')
else:
print('WARNING! x and y must be 0 or 1 ')
|
8be4e1bd22a2158d11664bcf24e6869c353df3a3 | AJAY-AGARIAN/guvipgms | /17c.py | 136 | 3.703125 | 4 | u=int(input())
u1=u
d=0
while(u>1):
c=0
c=int(u%10)
d=d+(c**3)
u=u/10
if(d==u1):
print("yes")
else:
print("no")
|
e9031cc2fc141dabdb384c8ee26b7232a450e291 | robertjrodger/data-structures-and-algorithms | /src/data_structures/lru_cache.py | 2,712 | 3.671875 | 4 | from collections import OrderedDict
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.right: Optional[Node] = None
self.left: Optional[Node] = None
class LRUQueue:
def __init__(self):
self.left_end: Optional[Node] = None
self.right_end: Optional[Node] = None
def push_left(self, node: Node):
if self.left_end is None:
self.left_end = node
self.right_end = node
else:
node.right = self.left_end
self.left_end.left = node
self.left_end = node
def pop_right(self):
node = self.right_end
self.right_end = self.right_end.left
if self.right_end is None:
self.left_end = None
else:
self.right_end.right = None
return node
def move_to_left(self, node: Node):
left = node.left
right = node.right
if left is None:
return
left.right = right
if right is not None:
right.left = left
node.left = None
node.right = self.left_end
self.left_end.left = node
self.left_end = node
class LRUCache:
def __init__(self, max_size: int):
self.max_size: int = max_size
self.current_size: int = 0
self.data: dict = dict()
self.queue: LRUQueue = LRUQueue()
def put(self, key, value):
node = self.data.get(key)
if node:
node.value = value
self.queue.move_to_left(node)
else:
if self.current_size == self.max_size:
node = self.queue.pop_right()
self.data.pop(node.key)
self.current_size -= 1
node = Node(key, value)
self.data[key] = node
self.queue.push_left(node)
self.current_size += 1
def get(self, key):
node = self.data.get(key)
if node:
value = node.value
self.queue.move_to_left(node)
return value
else:
return None
class OrderedDictLRUCache:
def __init__(self, max_size: int):
self.max_size = max_size
self.cache: OrderedDict = OrderedDict()
def get(self, key):
if key in self.cache:
value = self.cache[key]
self.cache.move_to_end(key)
return value
else:
return None
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.max_size:
oldest = next(iter(self.cache))
del self.cache[oldest]
|
2e9b66ca43b45ca724d6de35750c7a853b776c3b | Warrlor/IlyaUdin | /4zad.py | 424 | 3.828125 | 4 | a=int(input("от "))
b=int(input("до "))
c=int(input("дают остаток "))
d=int(input("при делении на "))
if a<b:
print("в отрезок входят ")
for i in range(a, b):
if (i%d==c):
print(i)
elif a>b:
print("в отрезок входят ")
for i in range(b, a):
if (i%d==c):
print(i)
else:
print("нет чисел") |
87bb3854a948dfd7056fd1095c9f810f27727c98 | bingwin/python | /python/面向对象/函数/参数/global.py | 261 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# coding: utf-8
age = 18
def happy_birthday():
global age # 定义为global后,可以使用
print "age {}, happy birthday ~".format(age)
age += 1
happy_birthday()
print "your age is {}".format(age)
|
84e785c8419d398697612b2ea5567e3b6868e464 | adityaKoteCoder/codex | /as2_5.py | 91 | 3.53125 | 4 | x = [1,2,3,4]
y = [5,6,7,8]
z = []
for i in range(len(x)):
z.append(x[i]+y[i])
print(z) |
44658e1a3dfbafc489d3f0d15925280fc37efa71 | zexhan17/Problem-Solving | /python/a6.py | 3,151 | 4.28125 | 4 | """
There are two main tasks to complete.
(a) Write a function with the name calculate_sgpa . The semantics of this function are the same as in the previous grades assignment. However, this time, we will not be passing in three inputs. We will instead be passing in a single list which has the grades in its elements. This means that now, any number of subjects can be input to this function in this single list. Make sure your function can handle any number of subjects – from 0 to say 10. The function should also be able to handle the case where a single grade is passed to it instead of a list. If an invalid grade is passed to the function, it should return None. If a None is passed to the function, it should simply return None as the output.
(b) Of course, the SGPA is calculated based on the credit hours of the subject. So, we need to write another function with the name calculate_sgpa_weighted . This function takes in two lists – one for the grades and another for the credit hours. To calculate the total SGPA, the following formula is used:
SGPA = (g 1 ∗ w 1 ) + (g 2 ∗ w 2 ) + . . . + (g n ∗ w n ) / w 1 + w 2 + . . . + w n
where g i are the grades and w i are the weights – in this case the credit hours which are used as weights. Ideally, you should be able to use the function calculate_sgpa in this one to ease your task. If the number of items in the two lists is not the same, the function should return None. As before, if a single subject is passed instead of a list, the function should be able to use it. Also, as before, if the list contains an invalid grade, it should return None.
----------DYS----------------------
"""
dit = {
"A+": 4.00,
"A": 4.00,
"A-": 3.67,
"B+": 3.33,
"B": 3.00,
"B-": 2.67,
"C+": 2.33,
"C": 2.00,
"C-": 1.67,
"D+": 1.33,
"D": 1.00,
"F": 0.00
}
#---------------
def calculate_sgpa(l):
total_marks = 0
total_number_of_subjects = 0
# checking if None was send
if l == None:
return None
for grade in l:
# checking if invalid grade is send
if grade not in dit:
return None
# checking nothing was not sent
if grade != 'nothing':
total_number_of_subjects += 1
total_marks += round( dit[ grade ] )
if total_number_of_subjects == 0:
return 0
SGPA = total_marks / total_number_of_subjects
return SGPA
#---------------
def calculate_sgpa_weight(grade_l, credit_hours_l):
# checking unequal lists
if len( grade_l ) != len( credit_hours_l ):
return None
low = 0
up = 0
for w in credit_hours_l:
for g in grade_l:
if g == 'nothing' or g not in dit:
return None
g = round( dit[ g ] )
up += g * w
low += w
# calculating SGPA
SGPA = up / low
return SGPA
if __name__ == '__main__':
grades = ['C', 'A', 'A', 'A', 'B', 'B']
# credit hours
c_hours = [2, 3, 3, 3, 3, 4]
print( calculate_sgpa( grades ) )
print( calculate_sgpa_weight( grades, c_hours ) )
|
8a7ac855a3f974e54a77dcba27e226d9e49e62fd | GustavoSousaPassos/Estudos | /python/ex028.py | 153 | 3.9375 | 4 | from random import randint
num = int(input('Escreva um número de 0 a 5'))
v = randint(0,5)
print('Você venceu!' if num == v else'O computador venceu!') |
03e6b69e358d523aaab1c213e761dc8ee6062223 | iamieht/intro-scripting-in-python-specialization | /Python-Data-Representations/Week2/Ex7_W2_list_reference.py | 537 | 3.96875 | 4 | """
Analyze an example of a list reference situation
"""
# Initial list
list1 = [2, 3, 5, 7, 11, 13]
# Another reference to list1
list2 = list1
# Print out both lists
print(list1)
print(list2)
# Update the first item in second list to zero
list2[0] = 0
# Print out both lists
print(list1)
print(list2)
# Explain what happens to list1 in a comment
#Both lists point to the same memory address, as they are the same referenced object
# Output
#[2, 3, 5, 7, 11, 13]
#[2, 3, 5, 7, 11, 13]
#[0, 3, 5, 7, 11, 13]
#[0, 3, 5, 7, 11, 13] |
da536ffbfe555249dee98d8a7724ad2c8fb309a2 | deepikaGit/SelfLearn | /Assignment.py | 281 | 4.03125 | 4 | from numpy import array
# Adding two array using for loop
a = array([2,1,4,5,3])
b = array([8,4,0,2,3])
for i in range(5):
temp = a[i] + b[i]
print(temp,end=" ")
# Max value from an array
max = a[0]
for i in range(1,5):
if max < a [i]:
max = a[i]
print(max)
|
6aff3901c408e4b79a8b585d203878bd0637e053 | sss6391/iot_python2019 | /01_Jump_to_python/5_APP/5_native_function/244_sorted.py | 126 | 3.5625 | 4 | my_list = [3,1,2]
print(sorted(my_list))
print(my_list)
my_list.sort()
print(my_list)
my_str = 'acb'
print(sorted(my_str))
|
eceaf0a48c48d643a5153d52b502272498e4cc80 | zarkle/code_challenges | /dsa/trees/tree_level_order.py | 454 | 4.0625 | 4 | """Given a binary tree of integers, print it in level order. The output will contain space between the numbers in the same level, and new line between different levels."""
class Node:
"""Node class for binary tree."""
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
def levelOrderPrint(tree):
"""Print nodes in level order. Print each level on one line."""
# Code here
pass |
34d42c0a3f014798dc1fbc5f7c494edc859c55d5 | amshapriyaramadass/learnings | /Hackerrank/itertools/itertools._combinations.py | 663 | 3.5 | 4 | from itertools import combinations
from itertools import combinations_with_replacement
# if __name__ == "__main__":
# string,number= input().split()
# # c = combinations(sorted(string),int(number))
# for i in range(1,int(number)+1):
# for c in combinations(sorted(string),i):
# print(''.join(c))
# from itertools import combinations
if __name__ == "__main__":
string,number= input().split()
c = combinations_with_replacement(sorted(string),int(number))
print(*[''.join(i) for i in c],sep='\n')
# for i in range(1,int(number)+1):
# for c in combinations(sorted(string),i):
# print(''.join(c)) |
56463992a6e05743ae11c931de6cc32320edca17 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/90965d16552f49a495a2be2d3fa358bd.py | 963 | 3.71875 | 4 | from calendar import day_name, Calendar
from datetime import date
class Meetup:
def __init__(self, year, month):
self.year = year
self.month = month
self.cal = Calendar()
@property
def monthly(self):
return self.cal.monthdatescalendar(self.year, self.month)
def weeks(self, ord_day):
daily = (
[day for day in week
if day.weekday() == ord_day and day.month == self.month]
for week in self.monthly
)
return [ordinal[0] for ordinal in filter(lambda d: d != [], daily)]
def meetup_day(year, month, day_of_week, meet):
day_n = list(day_name).index(day_of_week)
meetup = Meetup(year, month)
weeks = meetup.weeks(day_n)
if meet[0].isdigit():
day = weeks[(int(meet[0])-1)]
if meet == 'teenth':
day = weeks[1].day > 10 and weeks[1] or weeks[2]
if meet == 'last':
day = weeks[-1]
return day
|
476122f8a8454eb6a2f51e89aa1ba3a0a33fe76a | alantort10/CS161 | /project-2c-alantort10/change.py | 721 | 4 | 4 | # Author: Alan Tort
# Date: 6/22/2021
# Description: Project 2c
# A program that asks for an integer number of cents from 0 to 99 and outputs
# how many of each type of coin would represent that amount with the fewest
# total coins
print("Please enter an amount in cents less than a dollar.")
cents = int(input())
# check to see if number of cents is within 0 to 99
if cents < 0 or cents > 99:
print("Please start the program again and enter"
" an integer between 0 and 99 inclusive.")
else:
print("Your change will be:")
print("Q:", cents // 25)
cents %= 25
print("D:", cents // 10)
cents %= 10
print("N:", cents // 5)
cents %= 5
print("P:", cents // 1)
|
9c173b42e1bc9a1c35021f7130724b219194b952 | ruslaan7/Sort | /bubble.py | 229 | 4.125 | 4 | def bubble_sort(array):
length = len(array) - 1
for i in range(length):
for j in range(length-i):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
|
753008821036643f543605f3b0fb17c6a73cf9cf | lyggnsj/pessimism-recsys-2021 | /src/agents/abstract.py | 8,968 | 3.8125 | 4 | import numpy as np
import pandas as pd
import math
from datetime import datetime # FIXME
class Agent:
"""
This is an abstract Agent class.
The class defines an interface with methods those should be overwritten for a new Agent.
"""
def __init__(self, config):
self.config = config
def act(self, observation, reward, done):
"""An act method takes in an observation, which could either be
`None` or an Organic_Session (see reco_gym/session.py) and returns
a integer between 0 and num_products indicating which product the
agent recommends"""
return {
't': observation.context().time(),
'u': observation.context().user(),
}
def train(self, observation, action, reward, done = False):
"""Use this function to update your model based on observation, action,
reward tuples"""
pass
def reset(self):
pass
class ModelBuilder:
"""
Model Builder
The class that collects data obtained during a set of sessions
(the data are collected via set of calls `train' method)
and when it is decided that there is enough data to create a Model,
the Model Builder generates BOTH the Feature Provider and the Model.
Next time when the Model is to be used,
the Feature Provider generates a Feature Set
that is suitable for the Model.
"""
def __init__(self, config):
self.config = config
self.data = None
self.reset()
def train(self, observation, action, reward, done):
"""
Train a Model
The method should be called every time when a new training data should be added.
These data are used to train a Model.
:param observation: Organic Sessions
:param action: an Agent action for the Observation
:param reward: reward (click/no click)
:param done:
:return: nothing
"""
assert (observation is not None)
assert (observation.sessions() is not None)
for session in observation.sessions():
self.data['t'].append(session['t'])
self.data['u'].append(session['u'])
self.data['z'].append('organic')
self.data['v'].append(session['v'])
self.data['a'].append(None)
self.data['c'].append(None)
self.data['ps'].append(None)
self.data['ps-a'].append(None)
if action:
self.data['t'].append(action['t'])
self.data['u'].append(action['u'])
self.data['z'].append('bandit')
self.data['v'].append(None)
self.data['a'].append(action['a'])
self.data['c'].append(reward)
self.data['ps'].append(action['ps'])
self.data['ps-a'].append(action['ps-a'] if 'ps-a' in action else None)
def build(self):
"""
Build a Model
The function generates a tuple: (FeatureProvider, Model)
"""
raise NotImplemented
def reset(self):
"""
Reset Data
The method clears all previously collected training data.
"""
self.data = {
't': [],
'u': [],
'z': [],
'v': [],
'a': [],
'c': [],
'ps': [],
'ps-a': [],
}
class Model:
"""
Model
"""
def __init__(self, config):
self.config = config
def act(self, observation, features):
return {
't': observation.context().time(),
'u': observation.context().user(),
}
def reset(self):
pass
class FeatureProvider:
"""
Feature Provider
The interface defines a set of methods used to:
* collect data from which should be generated a Feature Set
* generate a Feature Set suitable for a particular Model from previously collected data
"""
def __init__(self, config):
self.config = config
def observe(self, observation):
"""
Collect Observations
The data are collected for a certain user
:param observation:
:return:
"""
raise NotImplemented
def features(self, observation):
"""
Generate a Feature Set
:return: a Feature Set suitable for a certain Model
"""
raise NotImplemented
def reset(self):
"""
Reset
Clear all previously collected data.
:return: nothing
"""
raise NotImplemented
class AbstractFeatureProvider(ModelBuilder):
"""
Abstract Feature Provider
The Feature Provider that contains the common logic in
creation of a Feature Set that consists of:
* Views (count of Organic Events: Products views)
* Actions (Actions provided by an Agent)
* Propensity Scores: probability of selecting an Action by an Agent
* Delta (rewards: 1 -- there was a Click; 0 -- there was no)
"""
def __init__(self, config):
super(AbstractFeatureProvider, self).__init__(config)
def train_data(self):
data = pd.DataFrame().from_dict(self.data)
features = []
actions = []
pss = []
deltas = []
prev_user = -1
for row in data.itertuples():
# If new user, clear history
if row.u != prev_user:
views = np.zeros(self.config.num_products)
# If organic interaction, update views
if row.z == 'organic':
view = int(row.v)
views[view] += 1
elif row.z == 'bandit':
features.append(views)
actions.append(int(row.a))
deltas.append(int(row.c))
pss.append(row.ps)
prev_user = row.u
return (
np.array(features),
np.array(actions),
np.array(deltas),
np.array(pss)
)
class ModelBasedAgent(Agent):
"""
Model Based Agent
This is a common implementation of the Agent that uses a certain Model when it acts.
The Agent implements all routines needed to interact with the Model, namely:
* training
* acting
"""
def __init__(self, config, model_builder):
super(ModelBasedAgent, self).__init__(config)
self.model_builder = model_builder
self.feature_provider = None
self.model = None
def train(self, observation, action, reward, done = False):
self.model_builder.train(observation, action, reward, done)
def act(self, observation, reward, done):
if self.model is None:
assert (self.feature_provider is None)
self.feature_provider, self.model = self.model_builder.build()
self.feature_provider.observe(observation)
return {
**super().act(observation, reward, done),
**self.model.act(observation, self.feature_provider.features(observation)),
}
def reset(self):
if self.model is not None:
assert (self.feature_provider is not None)
self.feature_provider.reset()
self.model.reset()
class ViewsFeaturesProvider(FeatureProvider):
"""
Views Feature Provider
This class provides Views of Products i.e. for all Products viewed by a users so far,
the class returns a vector where at the index that corresponds to the Product you shall find
amount of Views of that product.
E.G.:
Amount of Products is 5.
Then, the class returns the vector [0, 3, 7, 0, 2].
That means that Products with IDs were viewed the following amount of times:
* 0 --> 0
* 1 --> 3
* 2 --> 7
* 3 --> 0
* 4 --> 2
"""
def __init__(self, config):
super(ViewsFeaturesProvider, self).__init__(config)
self.history = None
self.views = None
self.reset()
def observe(self, observation):
assert (observation is not None)
assert (observation.sessions() is not None)
for session in observation.sessions():
view = np.zeros((1, self.config.num_products))
view[:, session['v']] = 1
self.views = np.append(view, self.views, axis = 0)
self.history = np.append(np.array([session['t']])[np.newaxis, :], self.history, axis = 0)
def features(self, observation):
if (
hasattr(self.config, 'weight_history_function')
and self.config.weight_history_function is not None
):
time = observation.context().time()
weights = self.config.weight_history_function(time - self.history)
return np.sum(self.views * weights, axis = 0)
else:
return np.sum(self.views, axis = 0)
def reset(self):
self.views = np.zeros((0, self.config.num_products))
self.history = np.zeros((0, 1))
|
3d89292611fe4effa147db3e540aab3488c5f66a | NinaS0220/coursera | /provierka-chisla-na-prostotu.py | 272 | 3.84375 | 4 | # -coding:utf-8
# сложность алгоритма O(корень из n):
def IsPrime(n):
d = 2
while d * d <= n and n % d != 0:
print(d, d*d, n%d)
d += 1
return d * d > n
if IsPrime(int(input())):
print("YES")
else:
print("NO")
|
09e602455590f646f63020719e6b0ae2abb5c935 | JohnKepplers/a3200-2015-algs | /lab14/Kravchenko/t_sort.py | 1,676 | 3.5 | 4 | from sys import stdin, stdout
class Graph:
def __init__(self):
self.a = [[42],[0]]
self.k = 14 / 88
self.list = []
self.d = {42:1}
def size_of_matrix(self):
return len(self.a)
def print_matrix(self):
return self.a
def size_of_list(self):
return len(self.list)
def add_vertex(self, v):
self.a[0] += [v]
self.d.update({v: 1})
for i in range(1, self.size_of_matrix()):
self.a[i] += [0]
self.a += [[0] * self.size_of_matrix()]
def add_directed_link(self, v1, v2):
if self.a[self.a[0].index(v1) + 1][self.a[0].index(v2)] != 1:
self.a[self.a[0].index(v1) + 1][self.a[0].index(v2)] = 1
else:
print('Error: these vertex already have rib.')
''' 1 — WHITE
2 — GREEN
3 — BLUE'''
def DFS(self):
for key, value in self.d.items():
if value == 1:
self.DFS_visit(key)
def DFS_visit(self, u):
self.d[u] = 2
for key in self.d.keys():
if self.d[key] == 2 and self.a[self.a[0].index(u) + 1][self.a[0].index(key)] == 1:
self.k = None
break
if self.d[key] == 1 and self.a[self.a[0].index(u) + 1][self.a[0].index(key)] == 1:
self.DFS_visit(key)
self.d[u] = 3
self.list.insert(0, u)
def topological_sort(self, a):
self.DFS()
if self.k == None or self.size_of_list() == 0:
return None
else:
return self.list
if __name__ == '__main__':
my_graph = Graph()
print(my_graph.topological_sort(my_graph.a))
|
ec9d7e59a4c3fd3c5cde09b62b82f5a410758a33 | wildbill2/python_projects | /favorite_number.py | 711 | 3.8125 | 4 | # Module imports
import json
def check_for_number():
"""Checks if a favorite number is already stored."""
filename = 'favorite_number.json'
try:
with open(filename) as f_obj:
number = json.load(f_obj)
except FileNotFoundError:
return None
else:
return number
def get_number():
"""Get favorite number if it does not exist."""
number = check_for_number()
if number:
print("I know your favorite number! It's " + number + ".")
else:
number = input("What is your favorite number? ")
filename = 'favorite_number.json'
with open(filename, 'w') as f_obj:
json.dump(number, f_obj)
get_number()
|
3f59f6ee2af656e9fd9a0ad114169bcbbb8c47d6 | ne7ermore/playground | /python/linkedlist/reverse.py | 678 | 3.578125 | 4 | class Node():
def __init__(self, val=None):
self.val = val
self.next = None
def arr2linked(arr):
res = cur = Node(arr[0])
for a in arr[1:]:
cur.next = Node(a)
cur = cur.next
return res
def link2arr(link):
list = []
while link:
list.append(link.val)
link = link.next
return list
def reverse(head):
prev = None
while head:
cur = head
head = head.next
cur.next = prev
prev = cur
return prev
if __name__ == "__main__":
list = [1, 2, 3, 4, 5, 6]
head = arr2linked(list)
head = reverse(head)
assert link2arr(head) == [6, 5, 4, 3, 2, 1]
|
9df6e0af5d39023673d3f6119b51a57c0aeba170 | Fares84/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 506 | 4.1875 | 4 | #!/usr/bin/python3
"""
a square printing function: print_square():
>>> def print_square(1):
#
"""
def print_square(size):
"""
Argument:
size {[int]} -- [size of square]
Raises:
TypeError: [if size is not int]
ValueError: [if size < 0]
"""
if not isinstance(size, int):
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
else:
for row in range(size):
print("#" * size)
|
73daf20cf998a47a6ef0c1787983695e64bee1e8 | phu-n-tran/LeetCode | /monthlyChallenge/2020-09(septemberchallenge)/9_30_FirstMissingPositive.py | 4,136 | 4.03125 | 4 | # --------------------------------------------------------------------------
# Name: First Missing Positive
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Follow up:
Your algorithm should run in O(n) time and uses constant extra space.
Hints:
1. Think about how you would solve the problem in non-constant space.
Can you apply that logic to the existing space?
2. We don't care about duplicates or non-positive integers
3. Remember that O(2n) = O(n)
"""
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# if not nums:
# return 1
# for i in range(1, len(nums)+2):
# if i not in nums:
# return i
######## OR
nums.sort()
result = 1
for i in nums:
if i == result:
result += 1
if result < i:
break
return result
'''other faster methods (from other submissions)
##################################################
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
n = len(nums)
for i in range(len(nums)): #delete those useless elements
if nums[i]<0 or nums[i]>=n:
nums[i]=0
for i in range(len(nums)): #use the index as the hash to record the frequency of each number
nums[nums[i]%n]+=n
for i in range(1,len(nums)):
if nums[i]/n==0:
return i
return n
##################################################
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==[]:
return 1
else:
hashm=dict.fromkeys(nums)
maxi=nums[-1]
for i in range(len(nums)):
if nums[i]>maxi:
maxi=nums[i]
if maxi<0:
return 1
k=0
while k < maxi:
if k not in hashm and k!=0:
return k
k=k+1
return maxi+1
##################################################
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 1
n = len(nums)
for i in range(n):
num = nums[i]
if num <= 0 or num > n:
continue
if num == n:
t = nums[0]
nums[0] = n
#nums[i] = t
self.putNum(nums, i, t)
continue
t = nums[num]
nums[num] = num
#nums[i] = t
#print "1 i %s t %s nums %s" %(i, t, nums)
self.putNum(nums, i, t)
#print "2 i %s nums %s" %(i, nums)
for i in range(1, n):
if nums[i] != i:
return i
if nums[0] != n:
return n
return n+1
def putNum(self, nums, i, n):
while True:
if n <= 0 or n > len(nums):
break
if n == len(nums):
t = nums[0]
nums[0] = n
else:
t = nums[n]
#print "Put num t %s n %s nums %s" %(t, n,nums)
nums[n] = n
if t == n:
break
n = t
##################################################
'''
|
4b585bc30981c7ba7b185562e24539cbde9ecab4 | benzoxyl/vector-product | /vectorproduct.py | 2,446 | 3.5625 | 4 | from tkinter import Tk, Label, Entry, Button, mainloop, messagebox
from PIL import Image, ImageTk
def formatFloat(num):
if num % 1 == 0:
return int(num)
else:
return num
def vectorProduct():
a = [None] * 3
b = [None] * 3
n = [None] * 3
# Abfrage der a1-3 und b1-3 Werte
for i in range(0,3):
t = eval("e" + str(i) + ".get()")
try:
a[i] = formatFloat(float(t))
except:
messagebox.showerror("Error", "Please enter a number for a" + str(i) + " .")
return
for i in range(3,6):
t = "e" + str(i) + ".get()"
try:
b[i-3] = formatFloat(float(eval(t)))
except:
messagebox.showerror("Error", "Please enter a number for b" + str(i-3) + " .")
return
# Berechnung des Kreuzproduktes
n[0] = a[1]*b[2] - a[2]*b[1]
n[1] = a[2]*b[0] - a[0]*b[2]
n[2] = a[0]*b[1] - a[1]*b[0]
# Ausgabe des Kreuzproduktes
for i in range(1,4):
exec("label" + str(i) + "['text']" + " = n[i-1]")
# Erstellen eines Tkinter Parent
root = Tk()
root.title("Kreuzprodukt")
# Definieren der Klammern
klauf = Image.open("/home/daniel/Downloads/klauf.png")
klauf = ImageTk.PhotoImage(klauf)
klzu = Image.open("/home/daniel/Downloads/klzu.png")
klzu = ImageTk.PhotoImage(klzu)
# Platzieren der Klammern
for i in range(0, 9, 4):
Label(root, image=klauf).grid(column=i, row=0, rowspan=3)
Label(root, image=klzu).grid(column=i+2, row=0, rowspan=3)
Label(root, text="x").grid(column=3, row=1)
Label(root, text="=").grid(column=7, row=1)
# Erstellung und Sortieren der Eingabefelder e0-2
for i in range(0,3):
exec("e" + str(i) + " = Entry(root, width=3)")
exec("e" + str(i) + ".grid(row=" + str(i) + ", column=1)")
# Erstellung und Sortieren der Eingabefelder e3-5
for i in range(3,6):
exec("e" + str(i) + " = Entry(root, width=3)")
exec("e" + str(i) + ".grid(row=" + str(i-3) + ", column=5)")
# Knopf für die Berechnung des Vektorproduktes
Button(root, text="Calculate!", command=vectorProduct).grid(row=1, column=11)
for i in range(1,4):
# Erstellung Labels für n1-3 ERGEBNISSE
exec("label" + str(i) + " = Label(root, width=3, borderwidth=2, relief='groove')")
exec("label" + str(i) + ".grid(row=i-1, column=9)")
# Loop der das Windows zeichnet
mainloop()
|
d11d40d029bce7831791a2b81c5eebf5ea1a58c4 | pbwis/training | /HackerRank/HR_ch10/test.py | 131 | 3.78125 | 4 | import collections
z = [1,2,3,2,1,5,6,5,5,5]
print(z)
print([item for item, count in collections.Counter(z).items() if count > 1]) |
b661dcdc1747ac4f839d31c998aca0c25b0c65e3 | dsbrown1331/Python1 | /Introduction/hello_world.py | 229 | 3.625 | 4 | print("Hello World!")
print('Python is fun!')
print('We can make the computer talk!')
print("You can print a single quote like this, 'hi'.")
print('You can also print double quotes, "hey there!", inside single quotes, "voila".')
|
c14de042f14c928588dee98b9515fbdcb65c1ffb | jishak13/PythonCourse | /printFormats.py | 488 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 09:14:54 2017
@author: JoeRemote
"""
from __future__ import print_function
print "This is a string"
s = "String"
"s stands for string"
print "Place my variable here: %s" %(s)
print 'Floating point number: %1.2f' %(13.1245)
print 'Convert to String %s' %(123)
print 'Convert to STring %r' %(123)
print 'First : %s, Second %s, Third %s' %('hi',"two",3)
print 'First: {x} Second: {y} Third: {x}'.format(x = "inserted",y="two")
|
7a524bd1c4c2e019c86aa2e02170ce546c095f6b | limdongjin/ProblemSolving | /python-lab/test_performance_named_tuple.py | 1,313 | 3.625 | 4 | import unittest
class MyTestCase(unittest.TestCase):
def test_something(self):
from datetime import datetime
N = 3000
# N*N 개의 tuple 을 리스트에 저장하고. 요소에 접근하는 시간을 측정한다.
start = datetime.now()
items = [(y, x) for x in range(N) for y in range(N)]
for item in items:
item[0]
item[1]
end = datetime.now()
tuple_time = (end - start).total_seconds()
print('tuples : ', tuple_time)
del items
# N*N 개의 namedtuple 을 리스트에 저장하고. 요소에 접근하는 시간을 측정한다.
start = datetime.now()
from collections import namedtuple
P = namedtuple('P', 'y x')
print(id((1,2)), id(P(1,2)), id((2,3)), id(P(2,4)), sep=', ')
items = [P(y, x) for x in range(N) for y in range(N)]
for item in items:
item.x
item.y
end = datetime.now()
namedtuple_time = (end - start).total_seconds()
print('namedtuple : ', namedtuple_time)
# 로컬 실행 결과
# tuples : 1.89178 sec
# namedtuple : 8.945932 sec
# namedtuple 의 생성, 접근 속도가 매우 느리다.
assert namedtuple_time > tuple_time * 2 |
783ca6462599afb01b7fead7841f40ddbe6c3569 | ngvinay/python-projects | /PythonBasics/src/functions.py | 1,648 | 4.3125 | 4 | def changeme( mylist ):
#"This changes a passed list into this function"
'''All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the calling function.'''
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return #A return statement with no arguments is the same as return None.
def iterate_list(mylist):
for num in mylist:
print "num : ", num
def printinfo(name, age):
#Keyword arguments
#Order of arguments does not matter
print "\nprintinfo(name, age)..."
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
def printinfo_def_arg( name, age = 35 ):
#Default arguments
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return
def printinfo_var_arg( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return
if __name__ == "__main__":
print "Main method...\n"
mylist = [10,20,30]
changeme( mylist )
print "Values outside the function: ", mylist
print "mylist[0] : ", mylist[0]
print "mylist[3][0] : ", mylist[3][0]
iterate_list(mylist)
# Now you can call printinfo function
printinfo( age=50, name="miki" )
# Now you can call printinfo function
printinfo_def_arg( age=50, name="miki" )
printinfo_def_arg( name="miki" )
printinfo_var_arg("Mike", "Mouse", 4) |
ca0d1171d218ed8c55c82c6df9ee9c4d6e90f679 | ahmettkara/class2-functions-week04 | /11.equal_reverse.py | 387 | 4.375 | 4 | def equal_reverse(*args):
"The function that controls the given inputs whether they are equal with their reverse writing or not."
result=""
for i in args:
if i == i[::-1]:
result += f"{i} ---> True\n"
else:
result += f"{i} ---> False\n"
return result
print(equal_reverse("madam", "tacocat", "utrecht", "ey edip adanada pide ye")) |
8b40b24762024f6453b2d1bd31e9a26e0a657ebf | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_87/44.py | 1,659 | 3.703125 | 4 | def int_input():
return int(raw_input())
def list_int_input():
return map(int, raw_input().split())
def list_char_input():
return list(raw_input())
def table_int_input(h):
return [list_int_input() for i in range(h)]
def table_char_input(h):
return [list_char_input() for i in range(h)]
def run_plain(x, s, r, t, ways):
ways.sort(key=lambda i: i[0])
len_plain = 0
last_end = 0
for way in ways:
len_plain += way[0] - last_end
last_end = way[1]
len_plain += x - last_end
run_time = min(t, float(len_plain) /r)
run_distance = run_time * r
walk_distance = len_plain - run_distance
walk_time = float(walk_distance) / s
time = run_time + walk_time
return (time, run_time)
def run_on_ways(x, s, r, t, ways):
ways.sort(key=lambda i: i[2])
time = 0
for way in ways:
way_distance = way[1] - way[0]
run_way_speed = r + way[2]
walk_way_speed = s + way[2]
run_time = min(t, float(way_distance) / run_way_speed)
run_distance = run_time * run_way_speed
walk_distance = way_distance - run_distance
walk_time = float(walk_distance) / walk_way_speed
t -= run_time
time += run_time + walk_time
return time
def solve(case):
x, s, r, t, n = list_int_input()
ways = [list_int_input() for i in range(n)]
time, run_time = run_plain(x, s, r, t, ways)
time += run_on_ways(x, s, r, t - run_time, ways)
print 'Case #%d: %.10f' % (case, time)
def main():
for i in range(int_input()):
solve(i+1)
main()
|
20a1ccf8df33f44540833686cd871acf029f1364 | haegray/Python-and-Java-Files | /sumStrings.py | 221 | 3.546875 | 4 | #sumStrings.py
def sumStrings(strList):
toNumbers=[]
sum = 0
for i in strList:
num = eval(i)
toNumbers.append(num)
for num in toNumbers:
sum = sum + num
print(sum)
sumStrings()
|
3efac7da878be7b0989d0d7ea20a4b067801042b | Guilherme-full/Python-jogo- | /JogodoParOuImpar.py | 866 | 3.765625 | 4 | from random import randint
v = 0
while True:
jogador = int(input('Diga um número: '))
computador = randint(1, 10)
total = jogador + computador
tipo = ' '
while tipo not in 'PI':
tipo = str(input('P/I: ')).strip().upper()[0]
print(f'Você disse o número {jogador}, e o computador pensou no número {computador}. O total é {total}', end=' ')
print('Deu par' if total % 2 == 0 else 'Deu ímpar')
if tipo == 'P':
if total % 2 == 0:
print('Você venceu!')
v += 1
else:
print('O computador venceu')
break
elif tipo =='I':
if total % 2 == 1:
print('Você venceu')
v += 1
else:
print('Você perdeu')
break
print('Vamos jogar novamente hehehe')
print(f'Gamer Over !, você venceu {v} vezes') |
647c6be4723f430cf80848df293488e526b52584 | prachichikshe/filehandling | /assign13.py | 982 | 3.96875 | 4 | #Write a Python program to combine each line from first file with the corresponding line in second file.
with open('abc.txt') as fh1, open('pc.txt') as fh2:
for line1, line2 in zip(fh1, fh2):
# line1 from abc.txt, line2 from pc.txtg
print(line1+line2)
'''Output
Paris is the capital and most populous city of France.
Paris is the capital and most populous city of France.
By the 17th century, Paris was one of Europe's major centres of finance, commerce, fashion, science, and the arts.
By the 17th century, Paris was one of Europe's major centres of finance, commerce, fashion, science, and the arts.
It is the second largest metropolitan area in the European Union.
It is the second largest metropolitan area in the European Union.
Paris is the fifth most expensive city in the world for luxury housing.
Paris is the fifth most expensive city in the world for luxury housing.
'''
|
03c87cd55c2fc53e4f4171fd803d314beb6ac05f | mkozel92/algos_py | /linked_lists/remove_duplicates.py | 943 | 4.15625 | 4 | from linked_lists.linked_list import LinkedList
def remove_duplicates(a_list: LinkedList):
"""
removes duplicates from a linked list by keeping track of seen elements
complexity O(N)
:param a_list: a linked list to process
"""
seen = set()
current = a_list.head
seen.add(current.data)
while current.next:
while current.next.data in seen:
current.next = current.next.next
seen.add(current.next.data)
current = current.next
def remove_duplicates_no_buffer(a_list: LinkedList):
"""
remove duplicates without using extra space
complexity O(N^2)
:param a_list: linked list to process
"""
current = a_list.head
while current:
runner = current
while runner.next:
while current.data == runner.next.data:
runner.next = runner.next.next
runner = runner.next
current = current.next
|
dbc51636535ab001530582f82156ef1363f01631 | Rodolfo-SFA/FirstCodes | /aula021b.py | 505 | 3.640625 | 4 | def funcao():
n1 = 4
print(f'N1 dentro vale {n1}')
n1 = 2
funcao()
print(f'N1 fora vale {n1}')
def teste(b):
# Escopo local
global a
a = 8
b += 4
c = 2
print(f'A dentro vale {a}.') # --> Receberá o "a" local
print(f'B dentro vale {b}.') # --> Receberá o "a" local
print(f'C dentro vale {c}.') # --> Receberá o "a" local
# Escopo Global
a = 5
teste(a)
print(f'A fora vale {a}') # --> Receberá o "a" local, porém, com o "global 'a'" ele receberá o 'a' global |
be90357ee0f1e513353be47f67952a6ef81473d6 | rovin/Python | /dict.py | 489 | 4.1875 | 4 | # Enter a line of text and find the most common word
counts = dict()
line = raw_input("Enter a line of text: ")
words = line.split()
print 'Words: ', words
bigcount = None
bigword = None
for word in words:
counts[word] = counts.get(word,0) + 1
print " Total count: ",counts
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print 'Common Word: ',bigword,' Count: ',bigcount
print counts.get('hello',-1) |
a970e08641de98a7a10948a5728d53c4a1fb7692 | AshishGoyal27/Face_detection | /face_detection/face_detect.py | 493 | 3.6875 | 4 | import cv2
#load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
#choose an image on which we want to test our code
img = cv2.imread('image2.jpg')
#detect faces in an image
faces = face_cascade.detectMultiScale(img, 1.1, 4)
#draw rectangles around the detected faces
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imwrite("face_detected2.png", img)
print('Successfully saved')
|
4897a9090d5f70b104877414f3c670cfb4eac48c | zakuro9715/aoj | /10018.py | 159 | 3.984375 | 4 | s = raw_input()
a = ""
for c in s:
if c >= 'A' and c <= 'Z':
a += c.lower()
elif c >= 'a' and c <= 'z':
a += c.upper()
else:
a += c
print a
|
9203898fff5a4d4d8397846dbe7bf5e4c9cd58b3 | IsseW/Python-Problem-Losning | /Uppgifter/1/1.33.py | 1,189 | 3.984375 | 4 | """
Övning 1.33 - Ränta på ränta
När man sätter in pengar på banken får man ränta på insatt kapital, dvs. kapitalet som är
insatt i banken ökar med ett viss en procent varje år. Om man till exempel sätter in 10 000 kronor
med 4% ränta har man 10000 · 1.04 = 10400 kronor efter första året. Andra året har man
10400 · 1.04 = 10816 kronor, tredje året 10000 · 1.04 · 1.04 · 1.04 = 11248.64 osv
Skriv ett program som låter användaren ange startbelopp, räntesats i procent och antal år som kapitalet förräntar sig. Därefter ska ditt program använda en loop för att beräkna hur mycket pengar användaren har på sitt konto efter dessa år. Låt slutligen programmet presentera slutsumman genom skriva ut den på skärmen.
Extrauppgift: Istället för att använda en loop kan man använda följande matematiska formel
för att beräkna totalbeloppet:
totalbelopp = startbelopp · räntefaktor^antalÅr
"""
inc = 1 + float(input("Ränta i procent: ")) / 100
years = int(input("Antal år: "))
start = float(input("Start kapital: "))
money = start
for i in range(years):
money *= inc
print(money)
# Extrauppgift
print("☆")
print(start * (inc ** years)) |
1a3052985193cb8c8fe387ef7dc1e64f2c179d42 | Hu-Wenchao/leetcode | /prob214_shortest_palindrome.py | 753 | 4.1875 | 4 | """
Given a string S, you are allowed to convert it to a
palindrome by adding characters in front of it. Find
and return the shortest palindrome you can find by
performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
class Solution(object):
def shortestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# using the KMP table
A = s + '*' + s[::-1]
table = [0]
for i in xrange(1, len(A)):
index = table[i-1]
while index > 0 and A[index] != A[i]:
index = table[index-1]
table.append(index + (1 if A[index] == A[i] else 0))
return s[table[-1]:][::-1] + s
|
163ea54ac945fe2ba7cacccd3e258ab1fe190a93 | umoqnier/programas_IA | /vectores.py | 6,243 | 3.953125 | 4 | # Programa que realiza operaciones con vectores
# !/usr/bin/python
# -*- coding: utf-8 -*-
# Universidad Nacional Autonoma de Mexico / Facultad de Ingenieria
# inteligenica Artificial
# Alumnos:
# Almazán García Giovanni
# Barriga Martínez Diego Alberto
# Bustamante Carrera Manuel Alejandro
# Juárez Pascual Karla Vanessa
# Hecho en Python 3.3
import os
import math
def cls(): # Funcion para limpiar pantalla en cualquier S.O.
if os.name == 'ce' or 'nt' or 'dos':
os.system("cls")
else:
os.system("clear")
def creaVector(): # Función que crea un vector de n dimensiones
while True:
v = input("\nIngrese las componentes del vector separadas por una coma\n-->\t")
v = v.split(",")
try:
vector = list(map(lambda n: float(n), v))
return vector
except ValueError:
print("\n\t*Error* Ingrese solo valores numericos")
def suma():
# La suma se puede realizar entre n vectores y se van sumando una a una
# las componentes de cada uno de los vectores, dando como resultado un
# vector de las mismas dimensiones que los originales
print("\n========= SUMA =========\n")
num = int(input("Ingrese cuantos vectores desea sumar -->\t"))
vectores = []
for i in range(0, num):
vectores.append(creaVector())
total = vectores[0]
temp = list(filter(lambda n: len(n) == len(total), vectores))
if len(temp) != len(vectores):
print("\n\t*Error* Ambos vectores deben tener la misma dimension")
return 0
jump = True
for i in vectores:
if not jump:
m = 0
for j in i:
total[m] += j
m += 1
jump = False
print("\n\tEl resultado de la suma es: " + str(total))
def resta():
# La resta de vectores se puede realizar entre n vectores, se van restando
# una a una las componentes de cada uno de los vectores, dando como resultado
# un vector de las mismas dimensiones que los originales
print("\n========= RESTA =========\n")
num = int(input("Ingrese cuantos vectores desea restar -->\t"))
vectores = []
total = []
for i in range(0, num):
vectores.append(creaVector())
total = vectores[0]
temp = list(filter(lambda n: len(n) == len(total), vectores))
if len(temp) != len(vectores):
print("\n\t*Error* Ambos vectores deben tener la misma dimension")
return 0
jump = True
for i in vectores:
if not jump:
m = 0
for j in i:
total[m] -= j
m += 1
jump = False
print("\n\tEl resultado de la resta es: " + str(total))
def producto():
# El producto escalar se calcula multiplicando el escalar por cada uno de los
# elementos del vector, el resultado es otro vector
print("\n========= PRODUCTO =========")
vector = creaVector()
while True:
try:
escalar = float(input("Ingrese el escalar que multiplicara al vector -->\t"))
print("\n\tEl producto es: " + str(list(map(lambda n: escalar * n, vector))))
return 0
except ValueError:
print("\n\t*Error* Ingrese solo valores numericos")
def norma(vect):
# La norma de un vector se calcula de la siguiente forma:
# norma = ((v1^2) + (v2^2) + (v3^2) + (v4^2) + ...)^(1/2)
# y da como resultado un escalar, la magnitud del vector
try:
temp = list(map(lambda n: n ** 2, vect))
temp1 = 0
for i in temp:
temp1 += i
modulo = math.sqrt(temp1)
return modulo
except TypeError:
pass
def angulo():
# El ángulo entre vectores se calcula de la siguiente forma:
# angulo = ang_cos ((u * v) / (||u|| * ||v||))
print("\n========= ANGULO ENTRE VECTORES =========")
v1 = creaVector()
v2 = creaVector()
if len(v1) != len(v2):
print("\n\t*Error* Ambos vectores deben tener la misma dimension")
return 0
mod1 = norma(v1)
mod2 = norma(v2)
j = 0
temp = 0.0
temp1 = 0.0
for i in v1:
temp += (i * v2[j])
j += 1
temp1 = round(mod1 * mod2, 2)
temp = temp / temp1
print("\n\tEl angulo entre los vectores es " + str(math.degrees(math.acos(temp))) + " grados")
# Tanto el programa principal como algunas funciones utilizan excepciones para
# responder adecuadamente en caso de que el usuario no ingrese valores numericos
# o quiera operar vectores de distintas dimensiones.
while True:
try:
print("\n========= Programa encargado de hacer operaciones con vectores n-dimensionales =========\n"
" \t1. Suma\n"
" \t2. Resta\n"
" \t3. Producto por escalar\n"
" \t4. Norma\n"
" \t5. Angulo entre dos vectores\n"
" \t0. Salir")
opcion = int(input("-->\t"))
if opcion:
cls()
if opcion == 1: # Suma
suma()
elif opcion == 2: # Resta
resta()
elif opcion == 3: # Producto
producto()
elif opcion == 4: # Norma
print("\n========= NORMA =========")
vect = creaVector()
mod = norma(vect)
if mod:
print("\n\t La norma es: " + str(mod))
elif opcion == 5: # Angulo
angulo()
elif opcion == 0: # Salir del programa
print("""\t\t\t\t____________________________________
Developed by
-Almazán García Giovanni
-Barriga Martínez Diego Alberto
-Bustamante Carrera Manuel Alejandro
-Juárez Pascual Karla VanessaTeam
-------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/
||----w |
|| ||""")
break
else:
print("\n\t\tOpcion invalida, intente de nuevo")
except ValueError:
print("\n\tValor erroneo")
|
a30c9e168f60d3635e846803a4e7a5ce5e00ecda | DavidS48/Flavour-Graph | /graphs.py | 9,786 | 3.546875 | 4 |
test_nodes = [1,2,3,4,5,6]
test_links = { 1 : [2,3],
2 : [1,3,5],
3 : [1,2],
5 : [2]
}
def is_complete(graph):
pass
def makes_complete(graph, new_node, links):
for node in graph:
if node not in links or new_node not in links[node]:
return False
return True
def find_complete_subgraphs(nodes, links, seed = None):
complete_subgraphs = {}
if seed == None:
complete_subgraphs[1] = [set([node]) for node in nodes]
else:
complete_subgraphs[1] = [set([node]) for node in seed]
k=2
while True:
complete_subgraphs[k] = []
for graph in complete_subgraphs[k-1]:
for node in nodes: # make this right
if node not in graph:
if makes_complete(graph, node, links) and graph.union(set([node])) not in complete_subgraphs[k]:
complete_subgraphs[k].append(graph.union(set([node])))
if len(complete_subgraphs[k]) == 0:
break
k += 1
return complete_subgraphs
def check_well_defined(nodes, links):
for node in nodes:
if not node in links:
print "%s is isolated" % str(node)
for node, linked_nodes in links.iteritems():
if node not in nodes:
print "Unrecognised node: %s" % node
for linked_node in linked_nodes:
if linked_node not in nodes:
print "Unrecognised relative: %s" % linked_node
if node not in links[linked_node]:
print "asymmetric relation: %s and %s" %(node, linked_node)
def calc_similarity(node1, node2, links):
same = len(set(links[node1]).intersection(set(links[node2])))
diff = len(set(links[node1])) + len(set(links[node2]))
return 1.0 * same / diff
def most_similar(nodes, links):
best_similarity = 0
best_nodes = None
for ii in range(len(nodes)):
for jj in range(ii):
new_similarity = calc_similarity(nodes[ii], nodes[jj], links)
if new_similarity > 0.3:
print new_similarity
print (nodes[ii], nodes[jj])
if new_similarity > best_similarity:
best_similarity = new_similarity
best_nodes = (nodes[ii], nodes[jj])
print best_similarity
return best_nodes
flavours = ["alm",
"anc",
"ani",
"app",
"apr",
"asp",
"aub",
"avo",
"bac",
"ban",
"bas",
"bef",
"bet",
"bel",
"bbe",#blackberry
"bcu",#blackcurrant
"bpu",#black pudding
"blb",#blueberry
"blc",#blue cheese
"bro",
"but",
"cab",
"cap",
"car",
"crt",
"cau",
"cav",
"cel",
"chr",
"chs",
"chi",
"chk",
"cho",
"cin",
"clo",
"coc",
"cof",
"cle",
"cse",
"cuc",
"cum",
"dil",
"egg",
"fig",
"gar",
"gin",
"glo",
"goa",
"gra",
"gfr",
"har",
"haz",
"hor",
"jun"]
pairings = {"alm" : ["ani", "app", "apr", "asp", "ban", "bbe", "bcu", "blb",
"but", "car", "cau", "chr", "chk", "chi", "cho", "cin",
"coc", "cof", "fig", "gar", "gin", "gra", "har", "haz"],
"anc" : ["bef", "bet", "bro", "cap", "cau", "chi", "coc", "egg",
"gar", "har"],
"ani" : ["alm", "app", "asp", "bac", "ban", "bas", "bef", "bcu",
"crt", "chk", "chi", "cho", "cin", "coc", "cuc", "egg",
"fig", "goa", "gra", "har"],
"app" : ["alm", "ani", "bac", "bet", "bbe", "bpu", "blb", "but",
"cab", "crt", "cel", "cin", "clo", "cse", "har", "haz",
"hor"],
"apr" : ["alm", "car", "cho", "cin", "cum", "gin", "goa", "har"],
"asp" : ["alm", "ani", "egg", "har"],
"aub" : ["bel", "chi", "gar", "gin"],
"avo" : ["bac", "blc", "chk", "chi", "cho", "cof", "cle", "cuc",
"dil", "gra", "gfr", "haz"],
"bac" : ["ani", "app", "avo", "ban", "bef", "bel", "bpu", "blc",
"bro", "but", "cab", "car", "chk", "chi", "cho", "clo",
"egg", "glo", "har", "hor"],
"ban" : ["alm", "ani", "bac", "car", "cav", "chr", "chk", "cho",
"cin", "coc", "cof", "egg", "har", "haz"],
"bas" : ["ani", "chk", "clo", "coc", "egg", "gar", "goa", "har"],
"bef" : ["anc", "ani", "bac", "bet", "bel", "bbe", "blc", "bro",
"cab", "cap", "crt", "cel", "chi", "cin", "clo", "coc",
"cof", "dil", "egg", "gar", "gin", "har", "hor", "jun"],
"bet" : ["anc", "app", "bef", "cap", "cho", "coc", "cum", "dil",
"egg", "goa", "hor"],
"bel" : ["aub", "bac", "bef", "chk", "chi", "egg"],
"bbe" : ["alm", "app", "bef", "goa"],
"bcu" : ["alm", "ani", "cho", "cof", "jun"],
"bpu" : ["app", "bac", "cho", "egg"],
"blb" : ["alm", "app", "blc", "cin", "cse"],
"blc" : ["avo", "bac", "bef", "blb", "bro", "but", "cab", "cel",
"chk", "fig", "gra", "gfr"],
"bro" : ["anc", "bac", "bef", "blc", "cau", "chi", "gar", "har"],
"but" : ["alm", "app", "bac", "blc", "chs", "chi", "cin", "gin",
"goa"],
"cab" : ["app", "bac", "bef", "blc", "crt", "chs", "chk", "chi",
"egg", "gar", "gin", "jun"],
"cap" : ["anc", "bef", "bet", "cau", "cuc", "goa"],
"car" : ["alm", "apr", "bac", "ban", "crt", "cho", "cin", "coc",
"cof", "cse", "gin"],
"crt" : ["ani", "app", "bef", "cab", "car", "cel", "cin", "coc",
"cuc", "cum", "haz"],
"cau" : ["alm", "anc", "bro", "cap", "cav", "chi", "cho", "cum",
"gar", "har"],
"cav" : ["ban", "cau", "chk", "egg", "haz"],
"cel" : ["app", "bef", "blc", "crt", "chs", "chk", "egg", "hor"],
"chr" : ["alm", "ban", "cho", "cin", "coc", "cof", "goa", "haz"],
"chs" : ["but", "cab", "cel", "chk", "cho"],
"chk" : ["alm", "ani", "avo", "bac", "ban", "bas", "bel", "blc",
"cab", "cav", "cel", "chs", "chi", "coc", "cle", "egg",
"gar", "gra", "har", "haz"],
"chi" : ["alm", "anc", "ani", "aub", "avo", "bac", "bef", "bel",
"bro", "but", "cab", "cau", "chk", "cho", "coc", "cle",
"egg", "gar", "gin", "goa", "har"],
"cho" : ["alm", "ani", "apr", "avo", "bac", "ban", "bet", "bcu",
"bpu", "car", "cau", "chr", "chs", "chi", "cin", "coc",
"cof", "fig", "gin", "goa", "haz"],
"cin" : ["alm", "ani", "app", "apr", "ban", "bef", "blb", "but",
"car", "crt", "chr", "cho", "clo", "coc", "cof", "fig",
"gin", "gfr"],
"clo" : ["app", "bac", "bas", "bef", "cin", "cof", "gin", "har"],
"coc" : ["alm", "anc", "ani", "ban", "bas", "bef", "bet", "car",
"crt", "chr", "chk", "chi", "cho", "cin", "cle", "dil",
"egg"],
"cof" : ["alm", "avo", "ban", "bef", "bcu", "car", "chr", "cho",
"cin", "clo", "cse", "gin", "goa", "haz"],
"cle" : ["avo", "chk", "chi", "coc", "cse", "cum", "gar", "goa"],
"cse" : ["app", "blb", "car", "cof", "cle", "cum", "gar", "goa"],
"cuc" : ["ani", "avo", "cap", "crt", "cum", "dil", "gar", "goa"],
"cum" : ["apr", "bet", "crt", "cau", "cle", "cse", "cuc", "egg"],
"dil" : ["avo", "bef", "bet", "coc", "cuc", "egg"],
"egg" : ["anc", "ani", "asp", "bac", "ban", "bas", "bef", "bet",
"bel", "bpu", "cab", "cav", "cel", "chk", "chi", "coc",
"cum", "dil", "gin"],
"fig" : ["alm", "ani", "blc", "cho", "cin", "goa", "har", "haz"],
"gar" : ["alm", "anc", "aub", "bas", "bef", "bro", "cab", "cau",
"chk", "chi", "cle", "cse", "cuc", "gin", "goa", "haz"],
"gin" : ["alm", "apr", "aub", "bef", "but", "cab", "car", "chi",
"cho", "cin", "clo", "cof", "egg", "gar"],
"glo" : ["bac", "har"],
"goa" : ["ani", "apr", "bas", "bet", "bbe", "but", "cap", "chr",
"chi", "cho", "cof", "cle", "cse", "cuc", "fig", "gar"],
"gra" : ["alm", "ani", "avo", "blc", "chk", "har"],
"gfr" : ["avo", "blc", "cin", "jun"],
"har" : ["alm", "anc", "ani", "app", "apr", "asp", "bac", "ban",
"bas", "bef", "bro", "cau", "chk", "chi", "clo", "fig",
"glo", "gra", "jun"],
"haz" : ["alm", "app", "avo", "ban", "crt", "cav", "chr", "chk",
"cho", "cof", "fig", "gar"],
"hor" : ["app", "bac", "bef", "bet", "cel"],
"jun" : ["bef", "bcu", "cab", "gfr", "har"],
}
print len(flavours)
check_well_defined(flavours, pairings)
comp_subs = find_complete_subgraphs(flavours, pairings, ["hor"])
print comp_subs
print most_similar(flavours, pairings)
|
4fd8c924a6140ff2394ef5a317e8d23d8d1dfe39 | anaypaul/Codeforces | /Contest Questions/DIV2/CFR_85_DIV2_A.py | 269 | 3.78125 | 4 | def main():
first = input()
second = input()
first = first.lower()
second = second.lower()
if(first == second):
print("0")
elif( first < second):
print("-1")
else:
print("1")
if __name__ == '__main__':
main() |
970b282851f1610fc766758cad8273e64cdb547c | solaimanhridoy/penguin-swe-intern | /task_3/services/Routine.py | 484 | 3.5625 | 4 | class Routine():
def __init__(self, dayIndex:list, hourIndex:list, courseIndex:list):
# super().__init__(course_name, teacher_name)
self.day = dayIndex
self.hour = hourIndex
self.course = courseIndex
def show_routine(self):
courses = ["English Grammar", "Mathematics", "Physics", "Chemistry", "Biology"]
for (i, j, k) in zip(self.day, self.hour, self.course):
print(i + " " + j + " " + courses[int(k)]) |
7c6f1a254c796a55a8b2b74de1ef4cbe1bb11ee3 | saml/x | /py/bible_ko_niv_json.py | 878 | 3.515625 | 4 | import sqlite3
if __name__ == '__main__':
conn = sqlite3.connect('bible_ko_niv.sqlite')
c = conn.cursor()
book_names = {rowid: (ko_name, en_name) for rowid,ko_name,en_name in c.execute('SELECT rowid,ko,en FROM books')}
tree = []
bible = {
'ko': {ko:book_id-1 for book_id,(ko,_) in book_names.items()},
'en': {en:book_id-1 for book_id,(_,en) in book_names.items()},
'data': tree,
}
for book_id, chapter, verse, ko, en in c.execute('SELECT book_id, chapter, verse, ko, en FROM verses'):
if len(tree) < book_id: # book_id is not in the tree. insert it
tree.append([])
chapters = tree[book_id-1]
if len(chapters) < chapter:
chapters.append([])
verses = chapters[chapter-1]
verses.append([ko, en])
import json
import sys
json.dump(bible, sys.stdout) |
74f7e9159655212aa05dc35626a378b8f43119fb | reemnasserr/AImancala | /heuristic1.py | 2,533 | 3.5625 | 4 |
# scoring ratio
from typing import Tuple
stealing_score = 1.2
farther_score = 1
repeating_score = 0.8
prevent_stealing = 0.5 # * number of balls prevented from stealing
def score_evaluation(board, turn, stealing=True):
heu_score = [0,0,0, 0,0,0, 0 ,0,0,0, 0,0,0, 0]
# heuristic 2 prefere again as long as total of balls in my pockets greater than or equla l 3ndo
sum_human_player = sum(board[0:6])
sum_ai_player = sum(board[7:])
start = 7 if turn == 1 else 0
if turn == 1 and sum_ai_player >= sum_human_player:
# check if there is amove allows another move
indices_again = [idx for idx in range(start, start+6) if (board[idx] == (13-idx)) or ((board[idx]-(13-idx)) % 12 == 0)]
# print (indices_again)
elif turn == 0 and sum_ai_player <= sum_human_player:
indices_again = [idx for idx in range(start, start+6) if (board[idx] == (6-idx)) or ((board[idx]-(6-idx)) % 12 == 0)]
# print (indices_again)
for i in indices_again:
heu_score[i]=1
# heuristic 3 prefer pockets farther from the mancala (for both mode)
far_score = farther_score
for i in board[(start,start+6)]:
heu_score [i] += far_score
far_score -= 0.15
if stealing:
# heuristic 1 give high weight for move causes stealing
zero_idx = [idx for idx in range(start,start+6) if board[idx]==0] #figure out if there is an empty pocket
print (zero_idx)
if len (zero_idx)>0: # it may be empty
for idx in zero_idx:
for i in range (start,idx):
if idx-i == board[i]:
if board[12-idx]!=0: #the opposite pocket has balls that can be stealed
heu_score[12-idx] = board[12-idx]*stealing_score
# heuristic 4 prevent stealilng
#check if the opposite user can steal from me
opp_start = 0 if start == 7 else 7
print (opp_start)
zero_idx_opp = [idx for idx in range(opp_start,opp_start+6) if board[idx]==0]
print (zero_idx_opp)
if len (zero_idx_opp)>0:
for idx in zero_idx_opp:
for i in range (opp_start,idx):
if idx-i == board[i]:
if board[12-idx]!=0: #the opposite pocket has balls that can be stealed
heu_score[12-idx] = board[12-idx]*prevent_stealing
return heu_score
print (score_evaluation([4,4,4, 4,4,4, 0, 4,3,10,2,0,5,0], 0, True)) |
11c508d884685726f9df64e3b0da87dacf9506c5 | Boissadax/school-projects | /school-projects/Maths/euler.py | 449 | 3.78125 | 4 | def euler1(a,h):
x=1
y=0
while x<a:
x = x + h
y = y + h / x
print("f(",a,") = ",y,"avec h =",h)
return
"""
euler1(2,1)
euler1(3,1)
euler1(7,1)
euler1(2,10)
euler1(3,10)
euler1(7,10)
"""
def euler2(a,h):
x=1
y=0
if a>1:
while x<a:
x=x+h
y+=h/x
else:
while x>a:
x-=h
y-=h/x
print("f(",a,") = ",y,"avec h =",h)
euler2(2,0.000001) |
1713abb88185b2087dd469706a371d15c979ca56 | y43560681/y43560681-270201054 | /lab12/example3.py | 1,013 | 3.78125 | 4 | class DNA:
def __init__(self, dna):
self.dna = dna
def count_nucleotides(self):
nucleotides = {}
a, c, g, t = 0, 0, 0, 0
for i in self.dna:
if i == "A":
a += 1
elif i == "C":
c += 1
elif i == "G":
g += 1
elif i == "T":
t += 1
nucleotides["A"] = a
nucleotides["C"] = c
nucleotides["G"] = g
nucleotides["T"] = t
return nucleotides
def calculate_complement(self):
self.dna = self.dna[::-1]
new_dna = ''
for i in self.dna:
if i == "A":
new_dna += "T"
elif i == "C":
new_dna += "G"
elif i == "G":
new_dna += "C"
elif i == "T":
new_dna += "A"
return new_dna
dna1 = DNA("AGCGTACGTAGTCGATCGATCGATGCATCG")
print(dna1.count_nucleotides())
print(dna1.calculate_complement()) |
0b03ba48ff915e6ecb5ab7af7fa96b1096f42070 | ananiastnj/PythonLearnings | /LearningPrograms/Fibo.py | 136 | 3.625 | 4 | def fib(n):
result=[0]
a,b=0,1
while b<n:
a,b = b,a+b
result.append(a)
#print(result)
return result
|
bcea72ba2947e64e6a2457f3e31d84aafff5c896 | frankkarsten/MTG-Math | /DwarvenMine.py | 9,045 | 3.828125 | 4 | '''
MULLIGAN RULE: Consider a red-blue deck.
• A 7-card hand is kept if it has 2, 3, 4, or 5 lands.
• For a mulligan to 6, we first choose what to put on the bottom and decide keep or mull afterwards.
To get a good mix, we bottom a spell if we drew 4+ spells and we bottom a land if we drew 4+ lands.
Afterwards, we keep if we hold 2, 3, or 4 lands. Otherwise, we mulligan.
• When bottoming lands, we might choose between Mines, Mountains, duals, and Islands.
We always keep a potential Mine, and then favor as many duals as possible.
We keep one Island if we didn't add a dual yet but bottom additional Islands as much as possible.
Finally we put Mountains on the bottom if needed.
• For a mulligan to 5, we try to get close to 3 lands and 2 spells.
So we bottom two spells if we drew 4+ spells, we bottom a spell and a land if we drew 3 spells, and we bottom two lands if we drew 2 spells.
Afterwards, we keep if we have 2, 3, or 4 lands; otherwise, we mulligan.
• For a mulligan to 4, we try to get close to 3 lands and 1 spell. Then we always keep.
'''
import random
from collections import Counter
num_simulations = 1000000
def put_lands_on_bottom(hand, lands_remaining_to_bottom):
"""
Parameters:
hand - A dictionary, with the same cardnames as in decklist, with number drawn
lands_remaining_to_bottom - The number of lands to bottom (<= number of lands in hand)
Returns - nothing, it just adjusts the hand value
"""
if hand['Dual'] == 0:
#Keep one Island if possible but bottom additional Island as much as possible
island_to_bottom = min( max(hand['Island'] -1, 0), lands_remaining_to_bottom )
else:
#Bottom Islands as much as possible
island_to_bottom = min( hand['Island'], lands_remaining_to_bottom )
hand['Island'] -= island_to_bottom
lands_remaining_to_bottom -= island_to_bottom
#If we still need to bottom some lands, then bottom Mountains as much as needed
mountain_to_bottom = min( hand['Mountain'], lands_remaining_to_bottom )
hand['Mountain'] -= mountain_to_bottom
lands_remaining_to_bottom -= mountain_to_bottom
#If we still need to bottom some lands, then bottom duals as much as needed
dual_to_bottom = min( hand['Dual'], lands_remaining_to_bottom )
hand['Dual'] -= dual_to_bottom
lands_remaining_to_bottom -= dual_to_bottom
#If we still need to bottom some lands, then bottom Mines as much as needed
mine_to_bottom = min( hand['Dwarven Mine'], lands_remaining_to_bottom )
hand['Dwarven Mine'] -= mine_to_bottom
def put_spells_on_bottom(hand, spells_remaining_to_bottom):
"""
Parameters:
hand - A dictionary, with the same cardnames as in decklist, with number drawn
spells_remaining_to_bottom - The number of spells to bottom (<= number of spells in hand)
Returns - nothing, it just adjusts the hand value
"""
other_spell_to_bottom = min( hand['Spell'], spells_remaining_to_bottom )
hand['Spell'] -= other_spell_to_bottom
spells_remaining_to_bottom -= other_spell_to_bottom
#If we still need to bottom some lands, then bottom Brainstorms as much as needed
brainstorm_to_bottom = min( hand['Brainstorm'], spells_remaining_to_bottom )
hand['Brainstorm'] -= brainstorm_to_bottom
def nr_lands(hand):
return hand['Mountain'] + hand['Island'] + hand['Dual'] + hand['Dwarven Mine']
def run_one_sim(decklist, sim_type = 'Mine'):
keephand = False
for handsize in [7, 6, 5, 4]:
#We may mull 7, 6, or 5 cards and keep every 4-card hand
#Once we actually keep, the variable keephand will be set to True
if not keephand:
#Construct library as a list
library = []
for card in decklist.keys():
library += [card] * decklist[card]
random.shuffle(library)
#Construct a random opening hand
hand = {
'Mountain': 0,
'Island': 0,
'Dual': 0,
'Dwarven Mine': 0,
'Brainstorm': 0,
'Spell': 0
}
for _ in range(7):
card_drawn = library.pop(0)
hand[card_drawn] += 1
if handsize == 7:
#Do we keep?
if (nr_lands(hand) >= 2 and nr_lands(hand) <= 5):
keephand = True
if handsize == 6:
#We have to bottom. Ideal would be 3 land, 3 spells
if nr_lands(hand) > 3:
put_lands_on_bottom(hand, 1)
else:
#The hand has 0, 1, 2, or 3 lands so we put a spell on the bottom
put_spells_on_bottom(hand, 1)
#Do we keep?
if (nr_lands(hand) >= 2 and nr_lands(hand) <= 4):
keephand = True
if handsize == 5:
#We have to bottom. Ideal would be 3 land, 2 spells
if nr_lands(hand) <= 3:
#Two spells on the bottom
put_spells_on_bottom(hand, 2)
elif nr_lands(hand) == 4:
#One land, one spell on the bottom
put_spells_on_bottom(hand, 1)
put_lands_on_bottom(hand, 1)
else:
#The hand has 0, 1, or 2 spells so we put two land on the bottom
put_lands_on_bottom(hand, 2)
#Do we keep?
if (nr_lands(hand) >= 2 and nr_lands(hand) <= 4):
keephand = True
if handsize == 4:
#We have to bottom. Ideal would be 3 land, 1 spell
if nr_lands(hand) <= 3:
put_spells_on_bottom(hand, 3)
elif nr_lands(hand) == 4:
put_spells_on_bottom(hand, 2)
put_lands_on_bottom(hand, 1)
elif nr_lands(hand) == 5:
put_spells_on_bottom(hand, 1)
put_lands_on_bottom(hand, 2)
else:
put_lands_on_bottom(hand, 3)
#Do we keep?
keephand = True
if sim_type == 'Opening hand':
blue_sources_in_opener = hand['Island'] + hand['Dual']
return 'Blue' if blue_sources_in_opener > 0 else 'No'
battlefield = {
'Mountain': 0,
'Dwarven Mine': 0,
'Dual': 0
}
for turn in [1, 2, 3, 4]:
draw_a_card = True if (turn == 1 and random.random() < 0.5) or (turn > 1) else False
if (draw_a_card):
card_drawn = library.pop(0)
hand[card_drawn] += 1
#Play a Brainstorm (on turn 2 or 3, cause Triomes make this tough on turn 1)
if (turn == 2 or turn == 3) and hand['Brainstorm'] > 0 and battlefield['Dual'] > 0:
hand['Brainstorm'] -= 1
card_drawn = library.pop(0)
hand[card_drawn] += 1
card_drawn = library.pop(0)
hand[card_drawn] += 1
#Play a land. No point in playing an Island for the purpose of this calculation
if turn < 4:
if hand['Dual'] > 0:
hand['Dual'] -= 1
battlefield['Dual'] += 1
elif hand['Mountain'] > 0:
hand['Mountain'] -= 1
battlefield['Mountain'] += 1
elif hand['Dwarven Mine'] > 0:
hand['Dwarven Mine'] -= 1
battlefield['Dwarven Mine'] += 1
#Now we're in turn 4, ready to play a land
if (hand['Dwarven Mine'] + battlefield['Dwarven Mine'] == 0):
Outcome = 'No Mine'
if hand['Dwarven Mine'] + battlefield['Dwarven Mine']> 0 and battlefield['Mountain'] + battlefield['Dual'] + battlefield['Dwarven Mine'] >= 3 and hand['Dwarven Mine'] > 0:
Outcome = 'Three Mountains'
if hand['Dwarven Mine'] + battlefield['Dwarven Mine'] > 0 and (battlefield['Mountain'] + battlefield['Dual'] + battlefield['Dwarven Mine'] < 3 or hand['Dwarven Mine'] == 0):
Outcome = 'Not enough Mountains'
return Outcome
def determine_prob(decklist):
print("-----------------")
print(decklist)
print("We now consider the probability to draw 3 Mountain by turn 4, conditional on drawing a Dwarven Mine")
#For Dwarven Mine purposes, treat Fabled Passage as a Mountain
passages = decklist['Fabled Passage']
decklist['Mountain'] += passages
decklist['Fabled Passage'] = 0
total_relevant_games = 0.0
total_favorable_games = 0.0
for _ in range(num_simulations):
Outcome = run_one_sim(decklist)
if (Outcome == "Not enough Mountains"):
total_relevant_games += 1
if (Outcome == "Three Mountains"):
total_relevant_games += 1
total_favorable_games += 1
print("Probability:" +str(round(total_favorable_games / total_relevant_games * 100.0 ,1))+"%.")
print("We now consider the probability that a keepable opening hand contains a blue source")
#For opening hand purposes, treat Fabled Passage as a Island
decklist['Mountain'] -= passages
decklist['Island'] += passages
total_relevant_games = 0.0
total_favorable_games = 0.0
for _ in range(num_simulations):
Outcome = run_one_sim(decklist, sim_type = 'Opening hand')
if (Outcome == "No"):
total_relevant_games += 1
if (Outcome == "Blue"):
total_relevant_games += 1
total_favorable_games += 1
print("Probability:" +str(round(total_favorable_games / total_relevant_games * 100.0 ,1))+"%.")
SamPardee_decklist = {
'Mountain': 6,
'Island': 4,
'Fabled Passage': 4,
'Dual': 8,
'Dwarven Mine': 4,
'Brainstorm': 4,
'Spell': 30
}
determine_prob(SamPardee_decklist)
JohnGirardot_decklist = {
'Mountain': 4,
'Island': 4,
'Dual': 8,
'Fabled Passage': 4,
'Dwarven Mine': 4,
'Brainstorm': 4,
'Spell': 32
}
determine_prob(JohnGirardot_decklist)
SperlingNettles_decklist = {
'Mountain': 6,
'Island': 2,
'Dual': 10,
'Fabled Passage': 3,
'Dwarven Mine': 4,
'Brainstorm': 4,
'Spell': 31
}
determine_prob(SperlingNettles_decklist)
RaphLevy_decklist = {
'Mountain': 6,
'Island': 3,
'Dual': 9,
'Fabled Passage': 3,
'Dwarven Mine': 4,
'Brainstorm': 4,
'Spell': 31
}
determine_prob(RaphLevy_decklist) |
dea957cc7bed1973b12cfa34be33a77c203b47b6 | Rodagui/Cryptography | /Gammal.py | 2,146 | 3.84375 | 4 | from exponenciacion import*
from generadorPrimos import*
from inversoModular import*
from primalidad import*
from random import *
# Python Program to find the factors of a number
def obtenerFactoresPrimos(n):
factores = set({})
if n % 2 == 0:
factores.add(2)
while n % 2 == 0:
n = n // 2
raiz = int(n ** 0.5)
for i in range(3, raiz + 1, 2):
# while i divides n , print i ad divide n
while n % i== 0:
factores.add(i)
n = n // i
if n > 2:
factores.add(n)
return list(factores)
# change this value for a different result.
num = 320
# uncomment the following line to take input from the user
#num = int(input("Enter a number: "))
#para calcular el elemento generador o primitivo: #
p = generarPrimo(5)
q = generarPrimo(5)
#p = 53
#q = 71
numPrimo = False
i = 1
while not numPrimo:
i +=1
if( esPrimo(i*p*q + 1)):
numPrimo = True
pAsterisco = i*p*q + 1
factoresPrimos = obtenerFactoresPrimos(pAsterisco - 1)
print("{}, {}".format(i, pAsterisco))
print("Factores primos de p*-1: {}".format(factoresPrimos))
alfa = 1
esGenerador = False
while not esGenerador:
alfa += 1
esGenerador = True
for i in range(len(factoresPrimos)):
primo = factoresPrimos[i]
if exponenciacionModulo(alfa, (pAsterisco - 1) // primo, pAsterisco) == 1:
esGenerador = False
break
print("alfa (generador): {}".format(alfa))
k = randint(1, pAsterisco - 1)
#k= 1203
#a llave privada
a = generarPrimo(3)
# x es el mensaje
# = 1399
x = int(input("Mensaje: "))
beta = exponenciacionModulo(alfa, a , pAsterisco)
#se manda y1 y y2
y1 = exponenciacionModulo(alfa, k, pAsterisco)
y2 = multiplicacionExponenteModulo(x, 1, beta, k, pAsterisco)
print("y1: {}\ny2: {}".format(y1, y2))
#desencriptar
inv = inversoModular(y1**a, pAsterisco)
#forma "lenta"
desncrypted = multiplicacionModulo( y2, inv, pAsterisco)
print("Resultado 1: {}".format(desncrypted))
#froma chida
descifrado = multiplicacionExponenteModulo(y1, pAsterisco - a - 1, y2, 1, pAsterisco)
print("Resultado 2: {}".format(descifrado)) |
070f9aecf4abaf13851962f2aa41ec963108cb35 | GeorgeTzan/python | /mathites.py | 282 | 4 | 4 | students = 8
grades = []
for i in range (students):
grade = input("Bathmos: ")
grades.append(grade)
total = int(sum(grades))
average = total / 8
print "xamhloteros bathmos: ", min(grades)
print "megistos mathmos: ",max (grades)
print "mesos oros: ", average
|
81f716596aecad70307dc869efa3f13063c35f61 | helloallentsai/leetcode-python | /268. Missing Number.py | 691 | 3.9375 | 4 | # 268. Missing Number
# Easy
# 1312
# 1726
# Add to List
# Share
# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
# Example 1:
# Input: [3,0,1]
# Output: 2
# Example 2:
# Input: [9,6,4,2,3,5,7,0,1]
# Output: 8
# Note:
# Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
sum_nums = 0
for i in range(0, len(nums)+1):
sum_nums += i
return sum_nums - sum(nums)
x = Solution()
print(x.missingNumber([3, 0, 1]))
|
655e9451619a546784a2fc03cff3dc6fdd986b07 | higashizono33/python_stack | /_python/python_fundamentals/functions_basicII/functions_basicII.py | 2,378 | 4.3125 | 4 | # Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one,
# from the number (as the 0th element) down to 0 (as the last element).
# # Example: countdown(5) should return [5,4,3,2,1,0]
# my function↓
# def countdown(num):
# new_list = []
# for i in range(num, -1, -1):
# new_list.append(i)
# return new_list
# print(countdown(5))
# Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
# my function↓
# def print_and_return(x):
# print(x[0])
# return x[1]
# print(print_and_return([5,9]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
# my function↓
# def first_plus_length(x):
# return len(x) + x[0]
# print(first_plus_length([1,2,3,4,5]))
# Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list
# that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements,
# have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
# my function↓
# def values_greater_than_second(x):
# new_list = []
# if len(x) < 3:
# return False
# else:
# for i in range(0, len(x)):
# if(x[i] > x[1]):
# new_list.append(x[i])
# return new_list
# print(values_greater_than_second([5,2,3,2,1,4]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and
# return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
# my function↓
# def length_and_value(x, y):
# new_list = []
# for i in range(0, x):
# new_list.append(y)
# return new_list
# print(length_and_value(4,7))
# print(length_and_value(6,2))
|
70b5f1d2e9c9743feb19604ab7546ef3772e8d7f | solenebutruille/MultiArmBanditProblem | /src/E-greedy_Reward.py | 3,273 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
@author: Butruille Solène
"""
import sys
import numpy as np
import matplotlib.pyplot as pyplot
import time
# Display percentage of advancement
def advance_statut(update):
sys.stdout.write("\r%d%%" % update)
# Epsilon_greedy algorithm
def epsilon_greedy(epsilon, number_of_arms, arm_mean):
# We take a random number between 0 and 1 and compare it to epsilon
if np.random.random_sample() >= epsilon:
# We take the one with the best average at this time
return np.argmax(arm_mean)
else:
# We choose a random arm
return np.random.randint(0, number_of_arms)
# Machine learning
def machine_learning(number_of_arms, number_of_bandit_pb, num_of_steps, epsilon):
# List with 2000 lists of the 1000 value that were earn
res = []
for problem_number in range(0, number_of_bandit_pb):
# List with reward earn each step (1000 values)
earned_reward = []
# Initialization of the arm arm_center_gaussian value for the center of the gaussian distribution
arm_center_gaussian = np.random.normal(size = number_of_arms)
# List with for each arm his current reward meaning
arm_mean = [0.0]*number_of_arms
# List to compt how many times each arm was chosen
occurence = [0]*number_of_arms
for step in range(0, num_of_steps):
# Selected arm with epsilon_greedy function
chosen_arm = epsilon_greedy(epsilon, number_of_arms, arm_mean)
# Reward is the random value following gaussian distribution with the center of the chosen_arm
reward = np.random.normal(arm_center_gaussian[chosen_arm])
occurence[chosen_arm] += 1
# Actualization of the reward mean for the chosen arm
arm_mean[chosen_arm] = ((arm_mean[chosen_arm] * occurence[chosen_arm] + reward) / (occurence[chosen_arm]+1))
earned_reward.append(reward)
# Add to returned list the reward for this bandit problem
res.append(earned_reward)
advance_statut(float(problem_number) / float(number_of_bandit_pb-1) * 100.0)
return res
# Graphic Display
def graphic_display(final_values_epsilon1, final_values_epsilon2, final_values_epsilon3, my_time):
pyplot.plot(range(0, len(final_values_epsilon1[0])), np.mean(final_values_epsilon1, axis=0), "b-", linewidth = 2, label = "Epsilon = 0.1")
pyplot.plot(range(0, len(final_values_epsilon2[0])), np.mean(final_values_epsilon2, axis=0), "r-", linewidth = 2, label = "Epsilon = 0.01")
pyplot.plot(range(0, len(final_values_epsilon3[0])), np.mean(final_values_epsilon3, axis=0), "g-", linewidth = 2, label = "Epsilon = 0")
pyplot.legend(loc = "upper left")
pyplot.xlabel("Steps")
pyplot.ylabel("Average reward")
pyplot.title("Learning with Epsilon-greedy")
print("Time = ", time.time() - my_time)
pyplot.show()
my_time = time.time()
final_values_epsilon1 = machine_learning(10, 2000, 1000, 0.1)
final_values_epsilon2 = machine_learning(10, 2000, 1000, 0.01)
final_values_epsilon3 = machine_learning(10, 2000, 1000, 0)
graphic_display(final_values_epsilon1, final_values_epsilon2, final_values_epsilon3, my_time)
|
c7976f29fa46ba976a059dd20ab977717483e87b | MarvickF/Coding-from-School-2020 | /randompatterns.py | 1,569 | 4.09375 | 4 | """
Marvick Felix
11/24/2020
File: randompatterns.py
Draws a radial pattern of squares in a random fill color
at each corner of the window.
"""
from turtle import Turtle
from polygons import *
import random
def drawPattern(t, x, y, count, length, shape):
"""Draws a radial pattern with a random
fill color at the given position."""
t.begin_fill()
t.up()
t.goto(x, y)
t.setheading(0)
t.down()
t.fillcolor('red')
"""I tried doing it the original way and troubleshooting my way through it but couldn't
just ended up doing what was sent via email"""
radialPattern(t, count, length, shape)
t.end_fill()
def main():
t = Turtle()
t.speed(0)
# Number of shapes in radial pattern
count = 10
# Relative distances to corners of window from center
width = t.screen.window_width() // 2
height = t.screen.window_height() // 2
# Length of the square
length = 30
# Inset distance from window boundary for squares
inset = length * 2
# Draw squares in upper-left corner
drawPattern(t, -width + inset, height - inset, count,
length, square)
# Draw squares in lower-left corner
drawPattern(t, -width + inset, inset - height, count,
length, square)
# Length of the hexagon
length = 20
# Inset distance from window boundary for hexagons
inset = length * 3
# Draw hexagons in upper-right corner
drawPattern(t, width - inset, height - inset, count,
length, hexagon)
# Draw hexagons in lower-right corner
drawPattern(t, width - inset, inset - height, count,
length, hexagon)
if __name__ == "__main__":
main()
|
7a1e572a360e1d065f6efbeb3a6b3e42790b5516 | horseTom/Test | /study-python/Day07.py | 2,881 | 4.09375 | 4 | def t_str():
str1 = "hello World!"
print(len(str1))
print(str1.capitalize())
print(str1.upper())
print(str1.find('shit')) #不存在的返回 -1
print(str1.index('or')) #不存在的报异常
print(str1.startswith('he')) #返回FALSE 或者 TRUE
print(str1.endswith('lo')) #返回FALSE 或者 TRUE
print(str1.center(50, '*'))# 将字符串以指定的宽度居中并在两侧填充指定的字符
print(str1.rjust(50, ' '))# 将字符串以指定的宽度靠右放置左侧填充指定的字符
print('********************华丽的分割线********************')
str2 = 'abc1234'
print(str2[2:5])
print(str2[2:])
print(str2[2::2]) #c24
print(str2[::2]) #ac24
print(str2[::-1]) #4321cba
print(str2[-3:-1]) #23
print(str2.isdigit())
print(str2.isalpha())# 检查字符串是否以字母构成
print(str2.isalnum())# 检查字符串是否以数字和字母构成
print('********************华丽的分割线********************')
str3 = ' [email protected] '
print(str3)
print(str3.strip())
def t_list():
list1 = [1, 3, 5, 7, 100]
print(list1)
list2 = ['hello'] * 5
print(list2)
print(len(list1))
print(list1[0])
print(list1[4])
print(list1[-1])
print(list1[-3])
list1[2] = 300
print(list1)
list1.append(200)
list1.insert(1, 400)
list1 += [1000, 2000]
print(list1)
print(len(list1))
list1.remove(3)
if 1234 in list1:
list1.remove(1234)
print(list1)
del list1[0]
print(list1)
list1.clear()
print(list1)
def strip_list():
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pear', 'lemon', 'mango']
for fruit in fruits:
print(fruit.title(), end='')
print()
fruits2 = fruits[1:4]
print(fruits2)
fruits3 = fruits[:]
print(fruits3)
fruits4 = fruits[-3:-1]
print(fruits4)
fruits5 = fruits[::-1]
print(fruits5)
import sys
def main():
# f = [x for x in range(1, 10)]
# print(f)
# f = [x + y for x in 'ABCDE' for y in'1234567']
# print(f)
# 用列表的生成表达式语法创建列表容器
# 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
f = [x ** 2 for x in range(1, 4)]
print(sys.getsizeof(f))
print(f)
# 请注意下面的代码创建的不是一个列表而是一个生成器对象
# 通过生成器可以获取到数据但它不占用额外的空间存储数据
# 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)
f = (x ** 2 for x in range(1, 3))
print(sys.getsizeof(f)) # 相比生成式生成器不占用存储数据的空间
print(f)
for val in f:
print(val)
if __name__ == "__main__":
# t_str()
# t_list()
# strip_list()
main() |
9c31d78c6a4d96781bac88859e7001b9502dc832 | ambergooch/urban-planner | /main.py | 843 | 3.84375 | 4 | from building import Building
from city import City
eight_hundred_eighth = Building("800 8th Street", 12)
eight_hundred_eighth.purchase("Fred Flintstone")
eight_hundred_eighth.construct()
# print(eight_hundred_eighth)
three_hundred = Building("300 Plus Park Blvd", 6)
three_hundred.purchase("Barney Rubble")
three_hundred.construct()
# print(three_hundred)
five_hundred = Building("500 Interstate Blvd", 3)
five_hundred.purchase("Wilma Flintstone")
five_hundred.construct()
# print(five_hundred)
two_hundred = Building("200 28th Street", 20)
two_hundred.purchase("Betty Rubble")
two_hundred.construct()
# print(two_hundred)
megalopolis = City()
megalopolis.add_building(eight_hundred_eighth)
megalopolis.add_building(three_hundred)
megalopolis.add_building(five_hundred)
megalopolis.add_building(two_hundred)
for building in megalopolis.buildings:
print(building)
|
fcc820614a6c175395ba72a0ca1fc7e1d72f58f6 | 1234567890boo/ywviktor | /MachineLearning/Boxplot.py | 322 | 3.890625 | 4 | import matplotlib.pyplot as plt
figure=plt.figure(1,figsize=(9,6)) #makes the boxplot
axes=figure.add_subplot(111, title="Boxplot Are cool") #adds name
axes.boxplot([[1, 2, 3, 4, 5], [6,7,8,9,10],[11,12,13,14,15]])#shows the axes each list in the list is 1 box plot
axes.set_xticklabels(["Dogs","Cats","Bats"])
plt.show() |
d3b34dddcee328b6ee47c70777a4eeff8b29f69f | enyel2/Script_python_Basic | /referencias_variable_lista.py | 560 | 3.65625 | 4 | #varibles
#spam = 42
#cheese = spam
#spam = 100
#print(spam)
#print(cheese)
#listas
#primero = [0, 1, 2, 3, 4, 5]
#segundo = primero
#segundo[1] = 'Hello'
#print(primero)
#print(segundo)
#las listas generan un solo id que puede se llamado por diferentes nombres
#def eggs(someParameter):
# someParameter.append('Hello')
#spam = [1, 2, 3]
#print(spam)
#eggs(spam)
#print(spam)
import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.copy(spam)
cheese[1] = 42
print(spam)
print(cheese)
#de esta manera se logra genera un id distinto para las listas
|
8608308b8bffff6e52ac5afebad0feaff672e07b | rustiri/Mission-to-Mars | /scraping.py | 6,338 | 3.53125 | 4 | # Import Splinter and BeautifulSoup
from splinter import Browser
from bs4 import BeautifulSoup as soup
#import pandas
import pandas as pd
import datetime as dt
import html5lib
#function to scrape all the data and create dictionary
def scrape_all():
#initiate headless driver
browser = Browser("chrome", executable_path="chromedriver", headless=True)
# set news title and paragrapp equal to mars_news() function
news_title, news_paragraph = mars_news(browser)
# Run all scraping functions and store results in dictionary
data = {
"news_title": news_title,
"news_paragraph": news_paragraph,
"featured_image": featured_image(browser),
"facts": mars_facts(),
"weather": mars_weather(browser),
"hemispheres": mars_hemisphere(browser),
"last_modified": dt.datetime.now()
}
# Stop webdriver and return data
browser.quit()
return data
# function to get mars update
def mars_news(browser):
# Visit the mars nasa news site
url = 'https://mars.nasa.gov/news/'
browser.visit(url)
# Optional delay for loading the page
browser.is_element_present_by_css("ul.item_list li.slide", wait_time=1)
# Convert the browser html to a soup object and then quit the browser
html = browser.html
news_soup = soup(html, 'html.parser')
# Add try/except for error handling
try:
slide_elem = news_soup.select_one('ul.item_list li.slide')
# Use the parent element to find the first `a` tag and save it as `news_title`
news_title = slide_elem.find("div", class_='content_title').get_text()
# Use the parent element to find the paragraph text
news_p = slide_elem.find('div', class_="article_teaser_body").get_text()
except AttributeError:
return None, None
return news_title, news_p
# ### JPL Space Images Featured Image
def featured_image(browser):
# Visit URL
url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
browser.visit(url)
# Find and click the full image button
full_image_elem = browser.find_by_id('full_image')[0]
full_image_elem.click()
# Find the more info button and click that
browser.is_element_present_by_text('more info', wait_time=1)
more_info_elem = browser.links.find_by_partial_text('more info')
more_info_elem.click()
# Parse the resulting html with soup
html = browser.html
img_soup = soup(html, 'html.parser')
try:
# Find the relative image url
img_url_rel = img_soup.select_one('figure.lede a img').get("src")
#img_url_rel
except AttributeError:
return None
# Use the base URL to create an absolute URL
# using an f-string for this print statement because it's a cleaner way
# to create print statements; they're also evaluated at run-time.
img_url = f"https://www.jpl.nasa.gov{img_url_rel}"
#img_url
return img_url
# ## Mars Facts
def mars_facts():
try:
# use Pandas '.read_html" to scrape the facts table into a dataframe
df = pd.read_html('http://space-facts.com/mars/')[0]
#df = pd.read_html('http://space-facts.com/mars/')
except Exception as e:
print(e)
#raise
return None
# Assign columns and set index of dataframe
df.columns = ['Description', 'Mars']
df.set_index('Description', inplace=True)
# use to_html method to convert DataFrame back into HTML format, add bootstrap.
#return df.to_html(classes="table table-striped")
return df.to_html(classes="table table-striped table-bordered")
# ## Mars Weather
def mars_weather(browser):
mars_weather=[]
# Visit the weather website
url = 'https://mars.nasa.gov/insight/weather/'
browser.visit(url)
# Parse the data
html = browser.html
weather_soup = soup(html, 'html.parser')
# Scrape the Daily Weather Report table
#weather_table = weather_soup.find('div', class_='textWhite')
weather_data = weather_soup.find('div', class_='vAlignTop textWhite')
weather_p = weather_data.find('p').get_text()
weather_temp = weather_data.find('div', class_="textLarger vCentered").get_text()
#print(weather_table.prettify())
return weather_p + weather_temp
#return df.to_html(classes="table table-striped table-bordered")
# ### Mars Hemispheres
def mars_hemisphere(browser):
# 1. Use browser to visit the URL
url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
browser.visit(url)
# Parse the resulting html with soup
html = browser.html
img_soup = soup(html, 'html.parser')
# Use the parent element to find where image url located
results = img_soup.findAll("a", class_='itemLink')
#create list to hold the result
new_result = []
#loop the result to get title in h3 tag
for result in range(0, len(results)):
if(result % 2 != 0):
new_result.append(results[result])
# 2. Create a list to hold the images and titles.
hemisphere_image_urls = []
# 3. Write code to retrieve the image urls and titles for each hemisphere.
#loop through collapsible_results to retrieve image urls and titles
for result in new_result:
#print(result)
#try:
#find image title
img_title_url = result.find('h3').text
img_title_click = browser.find_by_tag('h3').click()
#parse new page
html = browser.html
new_soup = soup(html, 'html.parser')
#find downloads class to get a href
img_url_rel = new_soup.find("div",class_="downloads").find("a")['href']
#print(img_url_rel)
#create empty dictionary to hold image and title
url_dict = {}
url_dict["title"] = img_title_url
url_dict["img_url"] = img_url_rel
#append the dictionary to the list
hemisphere_image_urls.append(url_dict)
#browser.back()
#except AttributeError:
# return None
#return hemisphere list
return hemisphere_image_urls
#test_output = mars_facts()
# tells Flask that our script is complete and ready for action.
if __name__ == "__main__":
# If running as script, print scraped data
print(scrape_all())
|
bfca9de088a0f1fd5578db938e934bd44d6ef09b | baibhab007/Database-operation | /connectDB_createTB.py | 756 | 3.53125 | 4 | import sqlite3
def register(NAME, AGE, SEX, INITIAL_AMOUNT):
con = sqlite3.connect('TEST.db')
cursor = con.cursor()
sql1 = 'DROP TABLE IF EXISTS CUSTOMER'
sql2 = '''
CREATE TABLE CUSTOMER (
NAME CHAR(20) NOT NULL,
AGE INT,
SEX CHAR(1),
INITIAL_AMOUNT FLOAT
)
'''
# cursor.execute(sql1)
# cursor.execute(sql2)
rec = (NAME, AGE, SEX, INITIAL_AMOUNT)
sql = '''
INSERT INTO CUSTOMER VALUES ( ?, ?, ?, ?)
'''
try:
cursor.execute(sql, rec)
con.commit()
print("Thanks for registering.")
except Exception as e:
print("Error Message :", str(e))
con.rollback()
con.close()
|
a891d9a214698836877778116d3ce391f0bbc148 | etherwar/MITxWordgame | /wordgame.py | 20,288 | 3.734375 | 4 | # The 6.00 Word Game
import random
from randomdict import RandomDict
import threading
import queue
import textwrap
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
WORDLIST_FILENAME = "words.txt"
def loadWords_thread(in_queue):
""" Worker queue processing function
"""
while True:
item = in_queue.get()
# wordList is a dict. str -> list
# keys are words, list[0] is the score list[1] is the word len
wordList[item] = [ getWordScore_init(item), len(item) ]
in_queue.task_done()
def loadWords(n):
"""
Returns a list of valid words based on maximum word size n.
Words are strings of lowercase letters. n assumed to be integer
n: int representing maximum word size
Depending on the size of the word list, this function may
take a while to finish.
"""
print("Loading word list from file...")
global wordList
wordList = {}
work = queue.Queue()
# Create 4 threads to process the words from the file into a dict
for i in range(4):
t = threading.Thread(target=loadWords_thread, args=(work,))
t.daemon = True
t.start()
# Use with open for guaranteed file closing
with open(WORDLIST_FILENAME, 'r') as inFile:
for line in inFile:
# First, check if the word has less or equal # of letters as n
if len(line.strip().lower()) <= n:
#If true, put the work in the worker queue
work.put(line.strip().lower())
# work.join() makes sure all processing is completed by threads before
# continuing with the program
work.join()
print(" ", len(wordList), "words loaded.")
return wordList
def getFrequencyDict(sequence):
"""
Returns a dictionary where the keys are elements of the sequence
and the values are integer counts, for the number of times that
an element is repeated in the sequence.
sequence: string or list
return: dictionary
"""
# freqs: dictionary (element_type -> int)
freq = {}
for x in sequence:
freq[x] = freq.get(x,0) + 1
return freq
# (end of helper code)
# -----------------------------------
#
# Problem #1: Scoring a word
#
def getWordScore_init(word):
"""
Returns the score for a word. Assumes the word is a valid word.
This is a helper function for initializing the dictionary that will
contain the word score for the remainder of the game.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
score = 0
for ltr in word:
score += SCRABBLE_LETTER_VALUES.get(ltr,0)
score *= len(word)
return score
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
Achieved by retrieving the score from the dictionary containing all
words and word scores
"""
score = wordList[word][0]
if len(word) == n:
score += 50
return score
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
if type(aList) != list:
return [aList]
else:
if len(aList) == 0:
return []
else:
return flatten(aList[0]) + flatten(aList[1:])
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
def shuffleHand(hand):
"""
Displays hand in randomized order
hand: dictionary (string -> int)
"""
randHand = [ [e]*hand[e] for e in hand ]
randHand = flatten(randHand)
random.shuffle(randHand)
for ltr in randHand:
print(ltr, end=" ")
print()
#
# Problem #2: Make sure you understand how this function works and what it does!
#
def dealHand(wordList, n):
"""
Generates a 'hand' from letters of a word in the wordlist with
letters = n
Takes wordList and filters it to only contain words of length n,
then randomly chooses one of these words using RandomDict
n: int >= 4
returns: dictionary (string -> int)
"""
# hand={}
# numVowels = n // 3
#
# First create a dictionary of words that match the word length selected
# at the beginning of the game
wordMatch = { x:y[0] for x, y in wordList.items() if y[1] == n }
wordMatchRand = RandomDict(wordMatch)
myRandHand = wordMatchRand.random_key()
hand = getFrequencyDict(myRandHand)
return hand
#
# Problem #2: Update a hand by removing letters
#
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
return { x: hand[x] - word.count(x) if x in word else hand[x]
for x in hand if (hand.get(x,0) - word.count(x)) > 0 }
#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word in wordList:
valWord = True
else:
return False
for ltr in word:
if hand.get(ltr,0) - word.count(ltr) >= 0:
valWord = True
else:
valWord = False
break
return valWord
#
# Problem #4: Playing a hand
#
def calculateHandlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string-> int)
returns: integer
"""
return sum(hand.values())
def playHand(hand, wordList, n):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word or a single period (the string ".")
to indicate they're done playing
* Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when there are no more unused letters or the user
inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
n: integer (HAND_SIZE; i.e., hand size required for additional points)
"""
# Keep track of the total score
score = 0
# As long as there are still letters left in the hand:
userSelect = 'n'
while calculateHandlen(hand) > 0:
# Display the hand
if userSelect != "r":
print()
print("Current hand: ", end=" ")
displayHand(hand)
# Ask user for input
userSelect = input("Enter word, a 'r' to shuffle the letters, or a '.' to indicate that you are finished: ")
print()
# If the input is a single period:
if userSelect == ".":
# End the game (break out of the loop)
break
# Otherwise (the input is not a single period):
elif userSelect == "r":
print("Current hand: ", end=" ")
shuffleHand(hand)
else:
# If the word is not valid:
if not isValidWord(userSelect, hand, wordList):
# Reject invalid word (print a message followed by a blank line)
print("Invalid word, please try again.")
# Otherwise (the word is valid):
else:
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
score += getWordScore(userSelect,calculateHandlen(hand))
print("Congratulations, your word '" + userSelect + "' has earned you " +
str(getWordScore(userSelect,calculateHandlen(hand))) + " points. Your new score is: " + str(score) + ".")
# Update the hand
hand = updateHand(hand, userSelect)
# Game is over (user entered a '.' or ran out of letters), so tell user the total score
print("Game over. You scored " + str(score) + " points.")
#
# Problem #5: Playing a game
#
def compChooseWord_thread(in_queue, hand, n):
global bestScore
global bestWord
global topScores
def addToTopScores(score, word):
for i in range(1,len(topScores)):
if score > topScores[i][0]:
topScores[i] = (score, word)
break
lock = threading.Lock()
while True:
word = in_queue.get()
if isValidWord(word, hand, wordList):
# find out how much making that word is worth
score = getWordScore(word, n)
# If the score for that word is higher than your best score
if (score > topScores[len(topScores)][0]):
# lock to prevent best words/scores being updated
# simultaneously (very small probability, I think it's needed
# since topScores is global)
lock.acquire()
# pass the score and word to the addToTopScores function to be
# sorted into the list of topScores (if applicable)
addToTopScores(score, word)
# release the lock
lock.release()
in_queue.task_done()
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: dictionary (string -> int)
wordList: list (string)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: string or None
"""
# Create a new variable to store the maximum score seen so far (initially 0)
global bestScore
bestScore = 0
# Create a new variable to store the best word seen so far (initially None)
global bestWord
bestWord = None
global topScores
topScores = {1:(0, None), 2:(0, None), 3:(0, None), 4:(0, None)}
work = queue.Queue()
# Create 4 threads for processing the data
for i in range(4):
t = threading.Thread(target=compChooseWord_thread, args=(work, hand, n))
t.daemon = True
t.start()
# For each word in the wordList
for word in wordList:
work.put(word)
# call join() to make sure all the work has been processed
work.join()
# return the best word you found.
defaultDiff = [1,2,2,2,3,3,3,3,4,4]
# Initially set the return result to None
result = None
# Loop the choice until a result is returned (in case top N choices didn't
# provide a usable word)
while result == None:
#if the top result is None, return None
if topScores[1][1] == None:
return None
# otherwise, set the result to a random choice of the topScores based
# on the defaultDiff distribution (work on math for this later)
else:
result = topScores[random.choice(defaultDiff)][1]
return result
#
# Computer plays a hand
#
def compPlayHand(hand, wordList, n):
"""
Allows the computer to play the given hand, following the same procedure
as playHand, except instead of the user choosing a word, the computer
chooses it.
1) The hand is displayed.
2) The computer chooses a word.
3) After every valid word: the word and the score for that word is
displayed, the remaining letters in the hand are displayed, and the
computer chooses another word.
4) The sum of the word scores is displayed when the hand finishes.
5) The hand finishes when the computer has exhausted its possible
choices (i.e. compChooseWord returns None).
hand: dictionary (string -> int)
wordList: list (string)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
"""
# Keep track of the total score
totalScore = 0
# As long as there are still letters left in the hand:
while (calculateHandlen(hand) > 0) :
# Display the hand
print("Current Hand: ", end=' ')
displayHand(hand)
print()
# computer's word
word = compChooseWord(hand, wordList, calculateHandlen(hand))
# If the input is a single period:
if word == None:
# End the game (break out of the loop)
break
# Otherwise (the input is not a single period):
else :
# If the word is not valid:
if (not isValidWord(word, hand, wordList)) :
print('This is a terrible error! I need to check my own code!')
break
# Otherwise (the word is valid):
else :
# Tell the user how many points the word earned, and the updated total score
score = getWordScore(word, calculateHandlen(hand))
totalScore += score
print('"' + word + '" earned ' + str(score) + ' points. Total: ' + str(totalScore) + ' points')
# Update hand and show the updated hand to the user
hand = updateHand(hand, word)
print()
# Game is over (user entered a '.' or ran out of letters), so tell user the total score
if calculateHandlen(hand) > 0:
print("I give up!")
else:
print("Game over!")
print('Total score: ' + str(totalScore) + ' points.')
#
# Problem #6: Playing a game
#
#
def playGame(wordList, HAND_SIZE):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'x'.
* If the user inputs 'x', immediately exit the game.
* If the user inputs anything that's not 'n', 'r', or 'x', keep asking them again.
2) Asks the user to input a 'u' or a 'c'.
* If the user inputs anything that's not 'c' or 'u', keep asking them again.
3) Switch functionality based on the above choices:
* If the user inputted 'n', play a new (random) hand.
* Else, if the user inputted 'r', play the last hand again.
* If the user inputted 'u', let the user play the game
with the selected hand, using playHand.
* If the user inputted 'c', let the computer play the
game with the selected hand, using compPlayHand.
4) After the computer or user has played the hand, repeat from step 1
wordList: list (string)
"""
while True:
print()
userInput = input("Enter 'n' to deal a new hand, 'r' to replay the last hand, or 'x' to end game: ")
if userInput == 'n':
hand = dealHand(wordList, HAND_SIZE)
while True:
print()
userInputSub = input("Enter 'u' to have yourself play, 'c' to have the computer play: ")
if userInputSub == 'u':
playHand(hand, wordList, HAND_SIZE)
break
elif userInputSub == 'c':
compPlayHand(hand, wordList, HAND_SIZE)
break
else: print("Invalid Command")
elif userInput == 'r':
if 'hand' in locals():
while True:
print()
userInputSub = input("Enter 'u' to have yourself play, 'c' to have the computer play: ")
if userInputSub == 'u':
playHand(hand, wordList, HAND_SIZE)
break
elif userInputSub == 'c':
compPlayHand(hand, wordList, HAND_SIZE)
break
else:
print()
print("Invalid Command")
else:
print()
print("You have not played a hand yet. Please play a new hand first!")
elif userInput == 'x':
break
else:
print()
print("Invalid Command.")
def welcome():
"""
Welcomes the player, brief intro to the game, and returns hand size as integer
ranging from 4 to 9
"""
version = '0.1'
m01 = "Welcome to the MIT 6.00.1x Wordgame (etherwar's mod)"
m02 = "Build " + version
m03 = "The Game: "
m04 = "First, you must select a word length. Word of 4 characters to 8 characters long are supported."
m05 = "A word of that length will then be scrambled and presented for you to guess. You may guess any " + \
"word that you can make with any number of the letters given to you. Words are scored using Scrabble(tm)" + \
"letter values. You get a bonus of 50 points for using all the letters remaining in your hand"
m06 = "We give you the option to play the game yourself, or to let the computer play the hand."
m07 = "We recommend that you play the game as yourself first, then enter 'r' to see how your " + \
"play stacks up against the computer!"
m08 = "Let's get started!"
nL = "\n\n"
defaultWidth = 70
wrapper = textwrap.TextWrapper(width=defaultWidth)
print("{:^80}".format(textwrap.fill(m01, defaultWidth)), end=nL)
print("{:>80}".format(textwrap.fill(m02, defaultWidth)), end=nL)
print(wrapper.fill(m03), end=nL)
print(wrapper.fill(m04), end=nL)
print(wrapper.fill(m05), end=nL)
print(wrapper.fill(m06), end=nL)
print(wrapper.fill(m07), end=nL)
print(wrapper.fill(m08), end=nL)
try:
userInput = 3
while int(userInput) < 4 or int(userInput) > 8:
print()
userInput = input("How many letters would you like to be dealt? (4-8): ")
if 4 <= int(userInput) <= 8:
HAND_SIZE = int(userInput)
else:
print("Invalid number. Please select a number from 4 to 8.")
except:
HAND_SIZE = 6
print("Invalid input. Default hand size selected (6).")
return HAND_SIZE
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
HAND_SIZE = welcome()
wordList = loadWords(HAND_SIZE)
playGame(wordList, HAND_SIZE)
|
638fa45799bb6c7ce2687b37c8df46d362f2fb70 | meighanv/05-Python-Programming | /LABS/Labs-3-1/lab3-1-8.py | 617 | 4.15625 | 4 | #Setting variable for tip and sales tax
salesTax = 0.07
tip = 0.15
#User input for amount of meal purchase
purchase = input("Input amount of meal purchase: \n")
#Input validation for numeric
#Using .replace to get rid of decimal to validate input is numeric
while purchase.replace('.','').isnumeric() == False:
purchase = input("Input was not valid. Input amount of purchase:\n")
print('Sales Tax: ${:.2f}'.format(float(purchase) * salesTax))
print('Tip at 15%: ${:.2f}'.format(float(purchase) * tip))
print('State Tax: ${:.2f}'.format((float(purchase) * salesTax) + (float(purchase) * tip) + float(purchase)))
|
820b496eb033c91342bd2bd281c36b6c093e63b8 | adam7395/bioinformatics_algorithms | /textbook_track/burrows_wheeler/BWMatching_1.py | 4,251 | 3.75 | 4 | '''
############################################################################
############################################################################
# Finds the number of occurences of finding a pattern in a text given only
# the first and last column, the pattern, and the lastToFirst
# http://rosalind.info/problems/ba9l/
#
# Given: A string and a collection of patterns
# Return: A list of integers showing the count for each pattern
#
#
############################################################################
'''
def parse( fname ):
with open( fname ) as f:
text = ''
patterns = []
for line in f:
if not text: text = line.strip()
else: patterns = line.strip().split()
return text, patterns
#maps each index of firstString to list of potential indices of lastString
def getIndices( c, string ):
indices = []
for i, s in enumerate(string):
if s == c:
indices.append(i)
return indices
#return the lastToFirst mapping
def last_to_first( transform ):
firstColumn = ''.join(sorted(transform))
#get indices for all characters in the string
indices = { c: getIndices(c, transform) for c in set( transform )}
#initialize map from first index to last index
sym_counts = { c: 0 for c in set(firstColumn) }
imap = []
for c in firstColumn:
imap.append( indices[c][sym_counts[c]] )
sym_counts[c] += 1
firstToLast = { imap[i]: i for i in imap }
return firstToLast
#return the firstColumn and lastColumn of Burrows Wheeler transform
def getFirstandLast( text ):
BWT = [ text ]
for i in range(1, len( text ) + 1):
BWT.append( BWT[i-1][-1] + ''.join(BWT[-1][0:-1]) )
return ''.join( [row[0] for row in sorted(BWT[1:])] ), ''.join( [row[-1] for row in sorted(BWT[1:])] )
def BWMatching( firstColumn, lastColumn, pattern, lastToFirst ):
print(pattern)
#initialize the indices
top = 0
bottom = len( lastColumn ) - 1
#terminate if no matches exist
while top <= bottom:
print( 'top: {}, bottom: {}'.format(top, bottom))
#while there are symbols in pattern to be matched
if pattern:
symbol = pattern[-1] #store the last symbol
pattern = pattern[0:-1] #remove last symbol
topIndex, bottomIndex = (0, 0)
if symbol in lastColumn[top: bottom + 1]:
topFound = False
for i in range( top, bottom + 1):
if symbol == lastColumn[i]:
if not topFound:
topFound = True
topIndex = i
else:
bottomIndex = i
print( " topIndex: {}, botIndex: {}".format(topIndex, bottomIndex ))
top = lastToFirst[topIndex]
if bottomIndex == 0:
bottom = top
else:
bottom = lastToFirst[bottomIndex]
else:
return 0
else:
#print('returning: bottom: {}, top: {}'.format(bottom, top))
return bottom - top + 1
print( 'return none' )
print('top: {}, bottom: {}'.format(top, bottom))
def main():
lastToFirst= last_to_first('T$GACCA')
firstColumn = ''.join( sorted('T$GACCA'))
print(firstColumn)
print('T$GACCA')
for i, v in enumerate( lastToFirst ):
print( 'i: {}, v: {}'.format(i, v))
exit()
text, patterns = parse('rosalind_ba9l.txt')
text = 'panamabananas$'
pattern = 'ana'
firstColumn, lastColumn = getFirstandLast( text )
lastToFirst = last_to_first( lastColumn )
for i, v in enumerate(lastToFirst):
print('i: {}, v: {}'.format(i, v))
print(firstColumn)
print(lastColumn)
count = BWMatching( firstColumn, lastColumn, patterns[1], lastToFirst )
# counts = [BWMatching( firstColumn, lastColumn, pattern, lastToFirst ) for pattern in patterns]
# print(counts)
if __name__ == '__main__':
main()
"""
$aaaaaabmnnnps
smnpbnnaaaaa$a
i: 0, v: 3
i: 1, v: 4
i: 2, v: 1
i: 3, v: 2
i: 4, v: 5
i: 5, v: 6
i: 6, v: 0
i: 7, v: 10
i: 8, v: 7
i: 9, v: 8
i: 10, v: 11
i: 11, v: 13
i: 12, v: 9
i: 13, v: 12
"""
|
7d78a8a72e0bb2ff4f79555fdba5ff28a6744324 | ryanA998/LeetCode-Problems | /LeetCode_1480_Sum_1D_Array.py | 798 | 3.9375 | 4 |
#LeetCode Problem 1480: Returing Sum of 1D Array
#Author: Ryan Arendt
#Verified: 11/15/2020
#Description:
# Goal: Return the Sum of a 1D array.
# Given an array nums. We define a running sum of an array as
# runningSum[i] = sum(nums[0]…nums[i]).
# Return the running sum of nums.
# Example:
# Input: nums = [1,2,3,4]
# Output: [1,3,6,10]
# Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
class Solution:
def runningSum(self,nums):
""" Computes the running sum of a list of integers. Returns a list
that contains the running sum at each index.
"""
run_sum = []
cur_sum = 0
for n in nums:
cur_sum += n
run_sum.append(cur_sum)
return run_sum
|
b1314e61d4a75b2a7981ce598b496fb705bc6254 | maleks93/Python_Problems | /algos/merge_sort.py | 1,095 | 3.859375 | 4 |
# Merge Sort
# Avg Time complexity: O( NlogN )
# Worst/Best case Time complexity: O( NlogN )
# Space complexity: O(N)
class Solution(object):
def sortArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Merge sort
if len(nums) < 2:
return nums
mid = len(nums) // 2
left_sort = self.sortArray(nums[0:mid])
right_sort = self.sortArray(nums[mid:])
result = []
left_ind = 0
right_ind = 0
while(left_ind < len(left_sort) and right_ind <len(right_sort)):
if left_sort[left_ind] < right_sort[right_ind]:
result.append(left_sort[left_ind])
left_ind += 1
else:
result.append(right_sort[right_ind])
right_ind += 1
if left_ind < len(left_sort):
result += left_sort[left_ind:]
if right_ind <len(right_sort):
result += right_sort[right_ind:]
return result
|
6544c7f0fcb16fec60daa8b2abc1768f470660d7 | Mapashi/Ejercicios-Python | /Actividad 1.1.py | 324 | 3.71875 | 4 | #1.1 Introduciendo la hora del día en horas, minutos y segundos, calcular cuántos segundos han transcurrido desde el comienzo del día
horas = int(input("Introduce la hora: "))
minutos = int(input("Introduce los minutos: "))
segundos = int(input("Introduce los segundos: "))
total = segundos + minutos * 60 + horas * 3600
|
c11bdad489a95b521c00c1d473432109a5c313fd | KwantomSolace/joint-project | /game.py | 21,715 | 4.0625 | 4 | #!/usr/bin/python3
from introendings import *
from map import rooms
from player import *
from items import *
from gameparser import *
from debate import *
import os
global game_over
game_over = False
global debate_over
debate_over = False
def list_of_items(items):
"""This function takes a list of items (see items.py for the definition) and
returns a comma-separated list of item names (as a string).
"""
items_list = []
for key in items:
items_list.append(key["name"])
return ", ".join(items_list)
def print_room_items(room):
"""This function takes a room as an input and nicely displays a list of items
found in this room (followed by a blank line). If there are no items in
the room, nothing is printed.
"""
if room["items"]:
print("There is " + list_of_items(room["items"]) + " here.")
def print_inventory_items(items):
"""This function takes a list of inventory items and displays it nicely, in a
manner similar to print_room_items(). The only difference is in formatting:
print "You have ..." instead of "There is ... here.".
"""
if (len(items) != 0):
print()
print("You have " + list_of_items(items) + ".")
print()
def print_room(room):
print(room["image"])
print()
print(room["name"].upper())
print()
print(room["description"])
print()
print_room_items(room)
def exit_leads_to(exits, direction):
"""This function takes a dictionary of exits and a direction (a particular
exit taken from this dictionary). It returns the name of the room into which
this exit leads. For example:
>>> exit_leads_to(rooms["Reception"]["exits"], "south")
"MJ and Simon's room"
>>> exit_leads_to(rooms["Reception"]["exits"], "east")
"your personal tutor's office"
>>> exit_leads_to(rooms["Tutor"]["exits"], "west")
'Reception'
"""
return rooms[exits[direction]]["name"]
def print_exit(direction, leads_to):
"""This function prints a line of a menu of exits. It takes a direction (the
name of an exit) and the name of the room into which it leads (leads_to).
"""
global current_room
if not current_room == rooms['Car']:
print("GO " + direction.upper() + " to go to " + leads_to + ".")
else:
print("GO TO " + direction.upper() + " to go to " + leads_to + ".")
def print_menu(exits, room_items, inv_items):
"""This function displays the menu of available actions to the player. The
argument exits is a dictionary of exits as exemplified in map.py. The
arguments room_items and inv_items are the items lying around in the room
and carried by the player respectively. The menu should, for each exit,
call the function print_exit() to print the information about each exit in
the appropriate format. The room into which an exit leads is obtained
using the function exit_leads_to(). Then, it should print a list of commands
related to items: for each item in the room print
"TAKE <ITEM ID> to take <item name>."
and for each item in the inventory print
"DROP <ITEM ID> to drop <item name>."
For example, the menu of actions available at the Reception may look like this:
You can:
GO EAST to your personal tutor's office.
GO WEST to the parking lot.
GO SOUTH to MJ and Simon's room.
TAKE BISCUITS to take a pack of biscuits.
TAKE HANDBOOK to take a student handbook.
DROP ID to drop your id card.
DROP LAPTOP to drop your laptop.
DROP MONEY to drop your money.
What do you want to do?
"""
print("You can:")
for direction in exits:
print_exit(direction, exit_leads_to(exits, direction))
global current_room
if not current_room == rooms['Car']:
for key in room_items:
print("TAKE " + key["id"].upper() + " to take " + key["name"] + ".")
for key in inv_items:
print("DROP " + key["id"].upper() + " to drop " + key["name"] + ".")
for key in inv_items:
print("LOOK AT " + key["id"].upper() + " to look at " + key["name"] + ".")
print()
print("What do you want to do?")
def is_valid_exit(exits, chosen_exit):
"""This function checks, given a dictionary "exits" (see map.py) and
a players's choice "chosen_exit" whether the player has chosen a valid exit.
It returns True if the exit is valid, and False otherwise. Assume that
the name of the exit has been normalised by the function normalise_input().
For example:
>>> is_valid_exit(rooms["Reception"]["exits"], "south")
True
>>> is_valid_exit(rooms["Reception"]["exits"], "up")
False
>>> is_valid_exit(rooms["Parking"]["exits"], "west")
False
>>> is_valid_exit(rooms["Parking"]["exits"], "east")
True
"""
return chosen_exit in exits
def execute_go(direction):
"""This function, given the direction (e.g. "south") updates the current room
to reflect the movement of the player if the direction is a valid exit
(and prints the name of the room into which the player is
moving). Otherwise, it prints "You cannot go there."
"""
global current_room
global debate_over
try:
if not debate_over and move(current_room["exits"], direction) == rooms['Debate'] and not (item_satans_number in inventory or item_eagle in inventory or item_money in inventory or item_photo in inventory):
print('You are not prepared for the debate, so you cannot yet enter.')
print()
return
elif not debate_over and move(current_room["exits"], direction) == rooms['Debate'] and (item_satans_number in inventory or item_eagle in inventory or item_money in inventory or item_photo in inventory):
print('You are prepared for the debate, but you only have one chance to reach 75 million votes. Proceed?')
player_input = None
while player_input == None:
player_input = input('> ')
if len(normalise_input(player_input))>0 and (normalise_input(player_input)[0] == 'yes' or normalise_input(player_input)[0] == 'y' or normalise_input(player_input)[0] == 'yeah' or normalise_input(player_input)[0] == 'yep' or normalise_input(player_input)[0] == 'yup' or normalise_input(player_input)[0] == 'aye'):
current_room = move(current_room["exits"], direction)
print_room(current_room)
debate()
return
if len(normalise_input(player_input))>0 and (normalise_input(player_input)[0] == 'no' or normalise_input(player_input)[0] == 'n' or normalise_input(player_input)[0] == 'nope'):
print()
return
else:
print('I didn\'t quite get that. Are you willing to debate?')
player_input = None
return
elif move(current_room["exits"], direction) == rooms['House'] and not item_key in inventory:
print('The doors to the White House are covered in chains and are padlocked. As presumed, it is a big house that is white!')
print()
return
elif move(current_room["exits"], direction) == rooms['House'] and item_key in inventory:
print('There\'s no going back once you enter the White House. Proceed?')
player_input = None
while player_input == None:
player_input = input('> ')
if len(normalise_input(player_input))>0 and (normalise_input(player_input)[0] == 'yes' or normalise_input(player_input)[0] == 'y' or normalise_input(player_input)[0] == 'yeah' or normalise_input(player_input)[0] == 'yep' or normalise_input(player_input)[0] == 'yup' or normalise_input(player_input)[0] == 'aye'):
print()
current_room = move(current_room["exits"], direction)
return
if len(normalise_input(player_input))>0 and (normalise_input(player_input)[0] == 'no' or normalise_input(player_input)[0] == 'n' or normalise_input(player_input)[0] == 'nope'):
print()
return
else:
print('I didn\'t quite get that. Are you willing to enter the White House?')
player_input = None
return
elif move(current_room["exits"], direction) == rooms['Booths'] and not item_photo in inventory:
current_room = move(current_room["exits"], direction)
inventory.append(item_photo)
return
if is_valid_exit(current_room["exits"], direction):
current_room = move(current_room["exits"], direction)
else:
print("You cannot go there.")
except:
print("You cannot go there.")
def execute_take(item_id):
"""This function takes an item_id as an argument and moves this item from the
list of items in the current room to the player's inventory. However, if
there is no such item in the room, this function prints
"You cannot take that."
"""
found = False
for key in current_room["items"]:
if item_id == key["id"]:
inventory.append(key)
current_room["items"].remove(key)
found = True
break
if not found:
print("You cannot take that.")
def execute_drop(item_id):
"""This function takes an item_id as an argument and moves this item from the
player's inventory to list of items in the current room. However, if there is
no such item in the inventory, this function prints "You cannot drop that."
"""
dropped = False
for key in inventory:
if item_id == key["id"]:
inventory.remove(key)
current_room["items"].append(key)
dropped = True
break
if not dropped:
print("You cannot drop that.")
def execute_look(item_id):
look_successful = False
for item in inventory:
if item_id == item['id']:
print(item['description'])
look_successful = True
if not look_successful:
print("There is no such item.")
def execute_command(command):
"""This function takes a command (a list of words as returned by
normalise_input) and, depending on the type of action (the first word of
the command: "go", "take", or "drop"), executes either execute_go,
execute_take, or execute_drop, supplying the second word as the argument.
"""
if 0 == len(command):
return
if command[0] == "go":
if len(command) > 1:
execute_go(command[1])
else:
print("Go where?")
elif command[0] == "take":
if len(command) > 1:
execute_take(command[1])
else:
print("Take what?")
elif command[0] == "drop":
if len(command) > 1:
execute_drop(command[1])
else:
print("Drop what?")
elif command[0] == "look":
if len(command) > 1:
execute_look(command[1])
else:
print("Look at what?")
else:
print("This makes no sense.")
def menu(exits, room_items, inv_items):
"""This function, given a dictionary of possible exits from a room, and a list
of items found in the room and carried by the player, prints the menu of
actions using print_menu() function. It then prompts the player to type an
action. The players's input is normalised using the normalise_input()
function before being returned.
"""
# Display menu
print_menu(exits, room_items, inv_items)
# Read player's input
user_input = input("> ")
# Normalise the input
normalised_user_input = normalise_input(user_input)
return normalised_user_input
def move(exits, direction):
"""This function returns the room into which the player will move if, from a
dictionary "exits" of avaiable exits, they choose to move towards the exit
with the name given by "direction". For example:
>>> move(rooms["Reception"]["exits"], "south") == rooms["Admins"]
True
>>> move(rooms["Reception"]["exits"], "east") == rooms["Tutor"]
True
>>> move(rooms["Reception"]["exits"], "west") == rooms["Office"]
False
"""
# Next room to go to
return rooms[exits[direction]]
def debate():
'''
This function deals with the mechanics for the debate:
The moderator asks six questions.
After the question is asked, Hillary responds.
Trump responds.
After the questions are asked, Trump can do one or two special attacks, depending on if he has the corres if he has the corresponding item in his inventory
The player is judged for how many votes they accumulated.
'''
global votes
global game_over
global debate_over
print('''In the debate, the moderator will ask a question, Hillary will respond, then you\'ll make your response.
Six questions will be asked.
You earn more votes for better-fitting answers, but you cannot make the same response twice.''')#Insctructions for the debate
print()
print('Press enter to continue.')
wait = input('> ')
print('The moderator asks his first question.''')
shuffle(responses)
your_special_attacks = []
for attack in spatks:
if attack['item'] in inventory:
your_special_attacks.append(attack)
#Questions are asked
print()
for debate_round in range(1, 7):#Moderator asks six questions, as this for loop suggests
moderator_question = questions[random.randint(0, len(questions)-1)]
print('QUESTION: ' + moderator_question['moderator'])
print('HILLARY RESPONDS: ' + moderator_question['hillary'])
print()
player_response = None
response_made = False
print('You have ' + votes_to_string() + ' votes.')
while not response_made:
print('You can say one of the following:')
menu_number = 1
for response in responses:#this loop goes through the available responses and prints them out to create a menu
print(str(menu_number) + ') ' + response['full response'])
menu_number += 1
print('Which option would you like to choose? Please enter a number.')
player_input = input('> ')
try:#this try and except prevents crashes from happening if user inputs wacky responses
if int(player_input)>0 and int(player_input)<=len(responses):#if the player's input is between 1 and the amount of responses there are, it is valid input
player_response = responses[int(player_input)-1]
response_made = True
else:
print('That didn\'t make sense.')
print('THE QUESTION WAS: ' + moderator_question['moderator'])
print('HILLARY RESPONDED: ' + moderator_question['hillary'])
print()
except:
print('That didn\'t make sense.')
print('THE QUESTION WAS: ' + moderator_question['moderator'])
print('HILLARY RESPONDED: ' + moderator_question['hillary'])
print()
fitting_response = False#we need to check if the response fits the question
for question in player_response['fitting questions']:
if question == moderator_question:
fitting_response = True
if fitting_response:
print(player_response['fit result'])
votes += player_response['fit votes']
else:
print(player_response['regular result'])
votes += player_response['regular votes']
responses.remove(player_response)
if moderator_question in questions:
questions.remove(moderator_question)
print()
#Special attack opportunity follows
print('The questions are over.')
if len(your_special_attacks)>1:
print('You can perform two special attacks!')
print()
for special_attack_round in range(1, 3):
print('You have ' + votes_to_string() + ' votes.')
response_made = False
while not response_made:
menu_number = 1
for spatk in your_special_attacks:
print(str(menu_number) + ') ' + spatk['option'][0].upper() + spatk['option'][1:] +'.')
menu_number += 1
print('Which option would you like to choose?')
player_input = input('> ')
try:
if int(player_input)>0 and int(player_input)<menu_number:
if your_special_attacks[int(player_input)-1] == spatk_satan:
os.system("Hillarylaugh.wav")
print(your_special_attacks[int(player_input)-1]['result'])
print()
votes += your_special_attacks[int(player_input)-1]['votes']
your_special_attacks.remove(your_special_attacks[int(player_input)-1])
response_made = True
else:
print('That didn\'t make sense.')
except:
print('That didn\'t make sense.')
else:
print('You have ' + votes_to_string() + ' votes.')
print('You ' + your_special_attacks[0]['option'] + '.')
print()
print(your_special_attacks[0]['result'])
votes += your_special_attacks[int(player_input)-1]['votes']
print()
#votes = 78000000#meant for testing game. if this is uncommented, comment from shuffle to line above
debate_over = True
print('The debate is over.')
print('You ended with ' + votes_to_string() + ' votes.')
print()
if votes >= 75000000:
print('Congratulations! You won the debate and became president. You obtained the key to the White House.')
inventory.append(item_key)
else:
print('You lost the debate, as you needed at least 75,000,000 votes. Hillary became president. Welp.')
game_over = True
room_debate["description"] = '''The debate hall is now void of life. You spot a few tattered American flags on the floor.'''
room_debate["image"] = ""
print()
print('Press enter to continue.')
wait = input('> ')
def votes_to_string():#puts commas in the right places
global votes
votes_as_string = ''
character_number = 1
for ch in str(votes)[::-1]:
votes_as_string += ch
if character_number%3==0:
votes_as_string += ','
character_number += 1
return votes_as_string[::-1]
def main():
os.system("Anthem.wav")
game_title()
game_intro()
print()
global game_over
global previous_room
previous_room = ''
while not game_over:
if previous_room != current_room["name"]:#this if statement and the code within prevents the room ASCII art from reappearing if the player
print_room(current_room)#is only picking up, dropping, or looking at an item in the room
previous_room = current_room["name"]#ie. the ASCII art only appears if the player changes rooms
if current_room == rooms['Bar'] and not item_satans_number in inventory and item_money in inventory:#this executes after you first enter the bar with money in your inventory, and after the room details are displayed
print('Press enter to continue.')
wait = input('> ')
print('''You go over to the bar and slap down $20 for the finest drink on the menu. Satan
recognises you and says it's on the house. The two of you chat until you finish drinking,
then he gives you his number, telling you to call him whenever you need his help.''')
inventory.append(item_satans_number)
print()
if not current_room == rooms['Car']:#the inventory is not displayed if Trump is in his limousine
print_inventory_items(inventory)
command = menu(current_room["exits"], current_room["items"], inventory)
execute_command(command)
if current_room == rooms['House']:#The game ends once Trump goes to the white house with the key in his inventory, or if Hillary wins the debate
print_room(current_room)
game_over = True
'''inventory.append(item_money)#meant for testing game. if this is uncommented, comment block above
inventory.append(item_eagle)
while not game_over:
print_room(current_room)#is only picking up, dropping, or looking at an item in the room
command = menu(current_room["exits"], current_room["items"], inventory)
execute_command(command)
if current_room == rooms['House']:#The game ends once Trump goes to the white house with the key in his inventory, or if Hillary wins the debate
print_room(current_room)
game_over = True'''
if current_room == rooms['House']:
if votes>=75000000 and votes<76300000:
execute_trump_wins()
if votes>=76300000:
execute_trump_wins_too_much()
else:
execute_hillary_wins()
print('Press any key to quit.')
wait = input('> ')
# Are we being run as a script? If so, run main().
# '__main__' is the name of the scope in which top-level code executes.
# See https://docs.python.org/3.4/library/__main__.html for explanation
if __name__ == "__main__":
main()
|
884a20f648777191b43b56d3476d75c4ca12c6e3 | rosepcaldas/Cursoemvideo | /ex086.py | 508 | 4.28125 | 4 | '''
EXERCÍCIO 86 - MATRIZ EM PYTHON
Crie um programa que crie uma atriz de dimensão 3 x 3 e preencha
com valores lidos pelo teclado.
No final mostre a matriz com a formataçã correta
'''
matriz = [[0,0,0], [0,0,0], [0,0,0]]
for lin in range(0, 3):
for col in range(0, 3):
matriz[lin][col] = int(input(f'Digite um valor para [{lin},{col}]:'))
print('-='*30)
for lin in range(0, 3):
for col in range(0, 3):
print(f'[ {matriz[lin][col]:^5} ]', end='')
print()
|
695ba511215b1d0c3e68845a665b5fc246b40bda | apan64/basic-data-structures | /Programming Assignment 4.py | 1,637 | 3.578125 | 4 | import math
import sys
class AdjMatrixGraph:
def __init__ (self):
self.n = 0
self.array = []
self.arraynames = []
def display (self):
for x in range (self.n):
for y in range (self.n):
print ("{0:2}".format(self.array[x][y]), end=" ")
print( )
print( )
def insert (self, x, y, w):
self.array[x][y] = int(w)
def update(self):
if len(self.array) < self.n:
x = self.n - len(self.array)
for q in range(0, x):
for row in self.array:
row.append(int(0))
for q in range(0,x):
new = []
for y in range(self.n):
new.append(int(0))
self.array.append(new)
def read(self, file):
reader = open(file, "r")
for line in reader:
q = str(line).split()
try:
x = self.arraynames.index(q[0])
except:
x = self.n
self.n += 1
self.arraynames.append(q[0])
try:
y = self.arraynames.index(q[2])
except:
y = self.n
self.n += 1
self.arraynames.append(q[2])
self.update()
self.array[x][y] = (int(q[1]) - int(q[3]))
self.array[y][x] = (int(q[3]) - int(q[1]))
def main():
graph = AdjMatrixGraph()
graph.read(input("Filename? "))
graph.display()
|
11c23a8be509cee389ad06657ea5e8ec9b6618b4 | tanshen/py_leetcode | /test.py | 239 | 3.6875 | 4 | from collections import OrderedDict
a = dict()
a['e'] = 1
a['a'] = 2
a.update({'banana': 3, 'apple':4, 'pear': 1, 'orange': 2})
a = OrderedDict(sorted(a.items(), key=lambda x:x[1]))
print(a)
d = a.popitem(0)
print(d[1])
print("a" < "aa") |
77e7403094acb65850c8db5b29a503128394e86c | neelup84/Python | /requests.py | 273 | 3.984375 | 4 | import random
import string
def password_generator(size=8, chars=string.ascii_letters + string.digits + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
print(password_generator(int(input('How many characters in your password?')))) |
e6136cfcd1d8477b5065eb795c1932ba0af5b37d | ChenYingLong2016/basis | /src/basis/magic_methods_rewrite.py | 1,228 | 4.125 | 4 | # coding = utf-8
'''
Created on 2016年11月17日
@author: 陈应龙
'''
'''魔法方法,总是被双下划线包围,如学过的__init__,
__init__这个方法返回值必须为None。这个方法的作用
终于想到了,就是函数必须被调用才会执行,可是这个方法
不需要调用也一样执行了。也就是说类里面不需要调用,
最先执行的就是__init__方法。'''
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def getPeri(self):
return (self.x + self.y) * 2
def getArea(self):
return self.x * self.y
rect = Rectangle(3,4)
print('长方形周长是:',rect.getPeri())
print('长方形面积是:',rect.getArea())
'''对象实例化调用的第一个方法是__new__,返回值是一个实例对象,
一般情况不需要重写__new__,需要重写的情况是继承一个不可改变对象,
如下面例子中str是程序默认字符串类,不可改变就需要这个方法重写,
这个可以说是新的构造一个方法'''
class Capstr(str):
def __new__(cls,string):
string = string.upper() #.upper()字符串方法把所有字符串变为大写
return str.__new__(cls,string)
a = Capstr("I love nothing,do you understand!")
print(a)
|
13b66388f73e9a3898c656684ef163c0a01ab9e6 | ahmedlela/learnpython | /sum.py | 521 | 3.8125 | 4 | # recursive/recursion
def recSum(arr):
if len(arr) == 0: # Base case
return 0
return arr[0] + recSum(arr[1:])
# [20,5,30] = 55
# 20 + sum([5,30]) = 20 + 35
# 5 + sum([30]) = 35
# 30 + sum([]) = 30
# print(recSum([20, 5, 30]))
# Find max
def recMax(arr):
if len(arr) == 0: # Base case
return 0
return max(arr[0], recMax(arr[1:]))
# subMax = recMax(arr[1:])
# if arr[0]> subMax:
# return arr[0]
# return subMax
print(recMax([20, 5, 30, 50, 300, 1350, 20, 10]))
|
39b921acb839f4df33a603c64dbd4843c40c86ff | tylerharter/caraza-harter-com | /cs220_tools/anonymize_whoAreYouSurvey.py | 986 | 3.75 | 4 | import hashlib
import csv
################################################################################
# This program requires the response to "Who are you" survey as a csv file named
# "Who_are_you_responses.csv"
#
# Run simply as python3 anonymize_whoAreYouSurvey.py
################################################################################
def process_csv(filename):
exampleFile = open(filename)
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
return exampleData
rows = process_csv("Who_are_you_responses.csv")
header = rows[0]
email_index = header.index("Email Address")
#Hash the email field
for index, row in enumerate(rows[1:]):
email = rows[index][email_index].lower()
hash_object = hashlib.md5(email.encode())
rows[index][email_index] = hash_object.hexdigest()
#Write updated csv file
with open("Who_are_you_responses_anonymized.csv", "w+") as wFH:
writer = csv.writer(wFH)
writer.writerows(rows)
|
100f70885fa3b806f2231ecc1e0e5bbdb2de4161 | LauDAW/dam2020 | /ejercicio5.py | 343 | 3.96875 | 4 | print("== Convertir números binarios en enteros ==")
binario = int(input("Introduce un número binario para transformar: "))
def binario_a_entero(binario):
decimal = 0
binario = str(binario)
decimal = int(binario, 2)
return decimal
print("El número binario", binario, "equivale a", binario_a_entero(binario))
|
bcc2b8848661e371ea6bc57bfb4d93c3254113ed | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module I/EX023 - Separando números.py | 397 | 4 | 4 | #Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
print('-=-'*9)
print('EX023 - Separando números')
print('-=-'*9)
print('\n')
num = int(input('Digite um número: '))
print('Milhar: {}' .format(num//1000%10))
print('Centena: {}' .format(num//100%10))
print('Dezena: {}' .format(num//10%10))
print('Unidade: {}' .format(num//1%10)) |
c910bfd37005593afb9d0d13506e6bf90f5efc9c | Ardhra123/Python-Programming | /decimals.py | 523 | 3.828125 | 4 | a = 3.1415926
b = -12.9999
c = 314.987
d = 11.09875
e = 20.987656
print("\nOriginal Number: ", a)
print("Formatted Number with sign: "+"{:+.5f}".format(a));
print("Original Number: ", b)
print("Formatted Number with sign: "+"{:+.5f}".format(b));
print("\nOriginal Number: ", c)
print("Formatted Number with sign: "+"{:+.5f}".format(c));
print("Original Number: ", d)
print("Formatted Number with sign: "+"{:+.5f}".format(d));
print("Original Number: ", e)
print("Formatted Number with sign: "+"{:+.5f}".format(e));
print()
|
37c350c2c306011d0f85712d0baa9403ae5df265 | BlakeMcMurray/Coding-Problem-Solutions | /Arrays/sumToValue.py | 345 | 3.78125 | 4 | #finds indexes of values that sum to val
#O(n) sol
def sum_to_value(val,arr):
hash_t = {}
pairs = []
for i in arr:
if i not in hash_t:
hash_t[val - i] = i
else:
if (i,val-i) not in pairs:
pairs.append((i,val-i))
return(pairs)
print(sum_to_value(5,[2,-8,3,-2,4,-10,1,4]))
|
6d5c3a40f25d54dc204aebba0b52b12e6615a880 | ethan786/hacktoberfest2021-1 | /Python/Blinding Auction/blindAuction.py | 1,229 | 4.21875 | 4 | # This program is designed so that we can organize blind auction at a small platform
import os
logo = '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| | | | | | ''-.
| |_| |_ _| |_..-'
|_______| '-' `'---------'` '-'
)"""""""(
/_________\\
.-------------.
/_______________\\
'''
bid_details = {}
bid_continue = True
max_bid = 0
winner = ""
print(logo)
print("Welcome to the secret auction program.")
while bid_continue:
name = input("What is your name?: ")
bid_price = float(input("What's your bid?: $"))
bid_details[name] = bid_price
if bid_price > max_bid:
max_bid = bid_price
winner = name
continue_bid = input("Are there any other bidders? Type 'yes' or 'no'.\n").lower()
if continue_bid == 'yes':
os.system('clear')
else:
bid_continue = False
print(f"Hence, the highest bid is ${max_bid} made by {winner}.")
|
efa1a59598a735e445c3b804b6a8f1c0e31eada3 | sliwkam/Beginning | /a18_Cows_And_Bulls.py | 1,098 | 3.734375 | 4 | import random
def cows_and_bulls(number, rand_number):
# counts number of 'cows'
count = 0
for i in range(0, 4):
if number[i] == rand_number[i]:
count += 1
return count
if __name__ == "__main__":
rand_num = str(random.randint(1000, 9999))
su = 1
attempts = 0
# explanation
print("Let's play a game of Cowbull!")
print("I will generate a number, and you have to guess the numbers one digit at a time.")
print("For every number in the wrong place, you get a cow. For every one in the right place, you get a bull.")
print("The game ends when you get 4 bulls!")
print("Type exit at any prompt to exit.")
while su != 0:
num = input("Enter your guess: ")
if num == "exit":
break
cou = cows_and_bulls(num, rand_num)
su = 4 - cou
print('You have: ' + str(su)+' cows '+str(cou) + ' bulls.')
# counts movements
attempts += 1
if num == 'exit':
print('Game was terminated.')
else:
print('You win in ' + str(attempts) + ' moves.')
|
499538bd5b71be56e68f31e12e720c2e8f5a5c68 | AruN227/python | /tikinter.py | 582 | 3.65625 | 4 | from tkinter import *
window = Tk()
window.wm_title("India X1")
l1 = Label(window, text="Virat Kohli(C)")
l1.grid(row=0, column=2)
l2 = Label(window, text="Rohit Sharma(Vc)")
l2.grid(row=0, column=3)
l3 = Label(window, text="MS Dhoni(WK)")
l3.grid(row=3, column=0)
l4 = Label(window, text="KL Ragul")
l4.grid(row=3, column=1)
l5 = Label(window, text="Rishap Pant")
l5.grid(row=3, column=2)
l6 = Label(window, text="D.Karthik")
l6.grid(row=3, column=3)
l7 = Label(window, text="Jadeja")
l7.grid(row=3, column=4)
l8 = Label(window, text="Hardik")
l8.grid(row=3, column=5)
window.mainloop() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.