blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b4620995cae0bef2e3d9a84dc0fe3be317b063c3 | StatusNeo/StatusNeo-101 | /Machine-Learning/7_Reinforcement_Learning/Upper_confidence_Bound/random_selection.py | 616 | 3.84375 | 4 | # Random Selection
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
# Implementing Random Selection
import random
N = 10000
d = 10
ads_selected = []
total_reward = 0
for n in range(0, N):
ad = random.randrange(d)
ads_selected.append(ad)
reward = dataset.values[n, ad]
total_reward = total_reward + reward
# Visualising the results
plt.hist(ads_selected)
plt.title('Histogram of ads selections')
plt.xlabel('Ads')
plt.ylabel('Number of times each ad was selected')
plt.show() |
8b48bd30d62767cc699ade62016fc80f2de00deb | pratyushagarwal22/coding-practice | /python/thinkpython/conditionsexercise1.py | 470 | 4.125 | 4 | '''
Write a function named check_fermat that takes four parameters—a, b, c and n—and that checks to see if Fermat’s theorem holds.
Fermats Theorem: a^n + b^n = c^n
'''
import math
def check_fermat():
a = int(input())
b = int(input())
c = int(input())
n = int(input())
finval = math.pow(a,2) + math.pow(b,2)
if finval == math.pow(c,2) and n>2:
print('Holy Smokes, Fermat was Wrong!')
else:
print('No, that doesn\'t work')
check_fermat()
|
dfcb468583bedc46679f33a6fe4891931b731dd6 | Benedict0819/ECNU-computer-test | /3.数学问题/2018.0224.math/1007.N!的最高位.py | 648 | 3.671875 | 4 | """
@Time:2018/2/24 15:36
@Author:xuzhongyou
"""
# 1007. N!的最高位
# Time limit per test: 2.0 seconds
#
# Memory limit: 256 megabytes
#
# 求 N 的阶乘的最高位数。
#
# 例如:
#
# 5!=120, 所以最高位为 1
#
# 10!=3628800,所以最高位为 3
#
# Input
# 每个数据包含一行,每行有一个整数 N(0<=N<=10000000)
#
# Output
# 对于每个测试数据,输出 N! 的最高位数字
#
# Examples
# input
# 5
# 10
# output
# 1
# 3
def cal(n):
res =1
for i in range(2,n+1):
temp = str(i)[:3]
res= str(res*int(temp))[:3]
print('res',res)
res = int(res)
print(res)
cal(10000000) |
2f089d961ae1edad6803c40977a7ea4fe609b184 | sniemi/SamPy | /astronomy/randomizers.py | 1,042 | 3.9375 | 4 | """
This module can be used to randomize for example galaxy positions.
:depends: NumPy
:author: Sami-Matias Niemi
:date: 21 May, 2011
:version: 0.1
"""
import numpy as np
__author__ = 'Sami-Matias Niemi'
def randomUnitSphere(points=1):
"""
This function returns random positions on a unit sphere. The number of random
points returned can be controlled with the optional points keyword argument.
:param points: the number of random points drawn
:type points: int
:return: random theta and phi angles
:rtype: dictionary
"""
#get random values u and v
u = np.random.rand(points)
v = np.random.rand(points)
#Convert to spherical coordinates
#Note that one cannot randomize theta and phi
#directly because the values would
#be packed on the poles due to the fact that
#the area element has sin(phi)!
theta = 2. * np.pi * u
phi = np.arccos(2. * v - 1)
#pack all the results to a dictionary
out = {'theta': theta,
'phi': phi,
'points': points}
return out |
63f5acc7f26d9530553e2e7aa0fed432828963c9 | plee-lmco/python-algorithm-and-data-structure | /pramp/array_index_element_equality.py | 1,125 | 3.921875 | 4 | '''
Array Index & Element Equality
Given a sorted array arr of distinct integers, write a function indexEqualsValueSearch that returns the lowest index i for which arr[i] == i. Return -1 if there is no such index. Analyze the time and space complexities of your solution and explain its correctness.
Examples:
input: arr = [-8,0,2,5]
output: 2 # since arr[2] == 2
input: arr = [-1,0,3,6]
output: -1 # since no index in arr satisfies arr[i] == i.
Constraints:
[time limit] 5000ms
[input] array.integer arr
1 ≤ arr.length ≤ 100
[output] integer
'''
def index_equals_value_search(arr):
# [-8,1,2,5,6,8]
# 0 1 2 3 4 5
# [-8,0,1,2,4,8]
# 0 1 2 3 4 5
left = 0
right = len(arr)-1
min_index = float('inf')
while(left <= right):
#mid = left + ((right - left)/2)
mid = (left + right) / 2
if (arr[mid] == mid):
min_index = min(mid,min_index)
right = mid-1
elif arr[mid] > mid:
right = mid - 1
elif arr[mid] < mid:
left = mid + 1
if min_index != float('inf'):
return min_index
return -1
arr = [0,0,2,5,6,8]
print(index_equals_value_search(arr))
|
0895c1d083714d59ee651d55f5d4334afc02c9d2 | Cheng0639/CodeFights_Python | /Intro/53_validTime.py | 228 | 3.734375 | 4 | def validTime(time):
h, s = map(int, time.split(':'))
return h < 24 and s < 60
print(validTime("13:58") == True)
print(validTime("25:51") == False)
print(validTime("02:76") == False)
print(validTime("24:00") == False)
|
0cee4e2f6c6e261c00f1a4b5a2786e332c2c04b5 | dankovan444/python | /math.py | 1,086 | 3.890625 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide (x, y):
return x / y
def average (x, y):
return (x + y) / 2
def max (x , y):
if x > y:
return x
if y > x:
return y
def min (x , y):
if x < y:
return x
if y < x:
return y
while True:
choice = input("enter(1/2/3/4/5/6)/7: ")
if choice in ('1', '2', '3', '4','5','6','7'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
if choice == '2':
print(num1,'-',num2,"=", subtract(num1,num2))
if choice == '3':
print(num1,'*',num2,"=", multiply(num1,num2))
if choice == '4':
print(num1 ,',', num2,"=", divide(num1,num2))
if choice == '5':
print (average(num1,num2))
if choice == '6':
print (max(num1,num2))
if choice == '7':
print (min(num1,num2))
|
4cad4758fa7d81045662277f93e94f168e7e64a0 | AatreshKulkarni/Learning-Python | /basic_programs/pgm28_dectobin.py | 349 | 4.375 | 4 | # Converting Decimal to Binary using recursion
# Defining a function that converts Decimal number to Binary number
def dectobin(num):
if num > 1:
# Recursive function call
dectobin(num // 2)
# Printing binary equivalent of decimal
print(num % 2,end = '')
# Taking user input
decnum = int(input("Enter a decimal number:"))
dectobin(decnum) |
691e856e6a8135679398d3e14834bf69befd2402 | LONG990122/PYTHON | /第一阶段/5. OOP/day04/code/10_contains.py | 754 | 3.828125 | 4 | # 10_contains.py
# 此示例示意in / not in 运算符的重载
class MyList:
def __init__(self, iterable):
print("__init__被调用")
self.data = list(iterable)
def __repr__(self):
return 'MyList(%r)' % self.data
def __contains__(self, e):
'''此方法用来实现 in / not in 运算符的重载'''
print("__contains__被调用")
for x in self.data:
if x == e:
return True
return False
L1 = MyList([1, -2, 3, -4])
if -2 in L1:
print('-2 在 L1 中')
else:
print('-2 不在 L1中')
# 当MyList的类内重载了__contains__方法,则not in也同时可用
if -3 not in L1:
print("-3 不在 L1中")
else:
print('-3 在 L2中')
|
6f50981f15718f804935173c79a323d7ecb6f228 | minjujung/python_algorithm_class | /week_2/00_study_class.py | 500 | 4.125 | 4 | # 5번 라인은 클래스를 생성했을 때, 즉 Person()이 호출되는 순간에
# class Person내부의 함수가 불리게 되면서 실행됨
class Person:
def __init__(self,param_name):
print("I am created! ", self)
self.name = param_name
def talk(self):
print("안녕하세요, 제 이름은", self.name, "입니다!")
person_1 = Person("한지민")
print(person_1.name)
person_1.talk()
person_2 = Person("이나영")
print(person_2.name)
person_2.talk() |
780f26b0a4ba4903be2173cdd60489371065dcaa | clashroyaleisgood/midi-data-preprocessing | /support/do_log.py | 1,079 | 3.65625 | 4 | from os.path import isfile
class Log:
def __init__(self, dirpath, log_file_name):
mode = 'w'
if isfile(dirpath + log_file_name):
mode = input("exist file {}, cover or append? (w/a)...>".format(log_file_name))
while mode != 'a' and mode != 'w':
print("invalid way:", mode)
mode = input("exist file {}, cover or append? (w/a)...>".format(log_file_name))
else:
print("create file", dirpath + log_file_name)
print("log at", dirpath + log_file_name)
self.dirpath = dirpath
self.log_name= log_file_name
self.file = open(dirpath + log_file_name, mode)
def log(self, msg, end='\n'):
self.file.write(msg + end)
def __del__(self):
print("file {} closed".format(self.log_name))
self.file.close()
if __name__ == "__main__":
import os
dir_path = os.path.dirname(os.path.realpath(__file__)) + '\\'
error = Log(dir_path, "error_log.txt")
error.log("happy", end=" ")
error.log("birth")
print() |
c7a9d642c588b29649796706a8af301d703d5da1 | GraceRonnie/my-isc-work | /python/dictionaries.py | 429 | 3.921875 | 4 | if {}: print "hi"
d = {"maggie": "uk", "ronnie": "usa"}
d.items() #items returns [('maggie', 'uk'), ('ronnie', 'usa')] i.e. the contents of the dictionary in their paired tuples
d.keys() #keys returns ['maggie', 'ronnie']
d.values() #values returns ['uk', 'usa']
d.get("maggie", "nowhere") #returns uk
d.get("ringo", "nowhere") #returns nowhere
res = d.setdefault("mikhail", "ussr")
print res, d["mikhail"] #returns ussr ussr
|
d1c4d4987f67c40e6cebd5e114885d8469bcaf82 | kupad/tictactoe | /main.py | 5,922 | 3.828125 | 4 | # Phil Dreizen
# Tic Tac Toe
import random
DEV = False
# seed the RNG
seed = 42 if DEV else None
random.seed(a=seed)
EMPTY = 0
X = 1
O = 2
NROWS = 3
NCOLS = 3
START_POS = 0
MAX_ROW_POS = NROWS - 1
MAX_COL_POS = NCOLS - 1
class Board:
def __init__(self):
self.b = [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]]
@staticmethod
def val_to_str(val):
"""
str representation of a cell's value
"""
if val == X:
return "X"
elif val == O:
return "O"
else:
return " "
def __getitem__(self, key):
"""
return value of a cell via a tuple (row, col)
"""
return self.b[key[0]][key[1]]
def __setitem__(self, key, val):
"""
set value of a cell via a tuple (row, col)
"""
self.b[key[0]][key[1]] = val
def is_empty(self, key):
"""
is the cell at (row, col) empty?
"""
return self[key] == EMPTY
def get_empty_cells(self):
"""
:return: a list of cells that are empty (row,col)
"""
return [(row_pos, col_pos) for row_pos in range(NROWS) for col_pos in range(NCOLS)
if self.is_empty((row_pos, col_pos))]
def is_in_bounds(self, move):
row_pos, col_pos = move
return START_POS <= row_pos <= MAX_ROW_POS and START_POS <= col_pos <= MAX_COL_POS
def is_valid(self, move):
"""
is the move valid, given the current state of the board?
"""
if move is None:
return False
return self.is_in_bounds(move) and self.is_empty(move)
def is_full(self):
return all([all(row) for row in self.b])
def check_win(self):
"""
Are we in a win state?
"""
b = self.b
def is_row_win():
for row in b:
if row[0] and row[0] == row[1] and row[0] == row[2]:
return True
return False
def is_col_win():
for c in range(3):
if b[0][c] and b[0][c] == b[1][c] and b[0][c] == b[2][c]:
return True
return False
def is_diag1_win():
return b[0][0] and b[0][0] == b[1][1] and b[0][0] == b[2][2]
def is_diag2_win():
return b[0][2] and b[0][2] == b[1][1] and b[0][2] == b[2][0]
return is_row_win() or is_col_win() or is_diag1_win() or is_diag2_win()
def __repr__(self):
s = ''
for r in range(3):
for c in range(3):
s += f'{self.val_to_str(self.b[r][c])}'
s += '|' if c < 2 else '\n'
return s
class Player:
def __init__(self, val):
self.val = val # X or O
def choose_move(self):
raise Exception("Not implemented")
class HumanPlayer(Player):
def _from_console(self, board):
"""
Ask player to choose move.
Reads in cell as row and column like: 01, 22
TODO: maybe make each cell a single number: 1,2,3,...9
"""
rc = input(f'Player {board.val_to_str(self.val)} Select Move: ')
try:
return int(rc[0]), int(rc[1])
except ValueError:
return None
def choose_move(self, board):
move = self._from_console(board)
while not board.is_valid(move):
print("Invalid move.")
move = self._from_console(board)
return move
class CPUPlayer(Player):
pass
class RandomBot(CPUPlayer):
def choose_move(self, board):
"""
Make a random move
- Find all empty cells, and pick a random one
:return: (row_pos, col_pos)
"""
empty_cells = board.get_empty_cells()
return empty_cells[random.randint(0, len(empty_cells) - 1)]
class MiniMaxBot(CPUPlayer):
def _minimax(self, board, is_maximizing, val):
if board.check_win():
return -1 if is_maximizing else +1, None
elif board.is_full():
return 0, None
if is_maximizing:
best_score = -2
cmp = lambda a, b: a > b
else:
best_score = +2
cmp = lambda a, b: a < b
for row_pos in range(NROWS):
for col_pos in range(NCOLS):
cell = (row_pos, col_pos)
if not board.is_empty(cell):
continue
move = cell
board[cell] = val
score, _ = self._minimax(board, not is_maximizing, X if val == O else O)
board[move] = EMPTY
if cmp(score, best_score):
best_score = score
best_move = move
return best_score, best_move
def choose_move(self, board):
"""
Use the minimax alg to find the best move
:return: (row_pos, col_pos)
"""
_score, move = self._minimax(board, True, self.val)
return move
class Game:
def __init__(self):
self.board = Board()
self.playerX = HumanPlayer(X)
self.playerO = MiniMaxBot(O)
self.current_player = self.playerX
def start(self):
winner = None
while not winner and not self.board.is_full():
print(self.board)
move = self.current_player.choose_move(self.board)
self.board[move] = self.current_player.val
if self.board.check_win():
winner = self.current_player
else:
# swap current_player
self.current_player = self.playerX if self.current_player == self.playerO else self.playerO
print(self.board)
if winner:
print(f'The winner is Player {self.board.val_to_str(winner.val)}')
else:
print("The game is a draw")
if __name__ == '__main__':
game = Game()
game.start()
|
75747144a3735564364a1962ef1c25bd322f6760 | Manohar-Gunturu/AlgoPython | /MergeSort.py | 1,201 | 3.78125 | 4 | arr = [0, 3, 1, 5, 2, 4, 6, 1, 3, 0]
# arr = [5, 2, 4, 6, 1, 3]
def merge(array, begin, mid, end):
# size of first array [begin, mid]
n1 = mid - begin + 1 # +1 as index starts at 0
# size of first array [mid+1, end]
n2 = end - mid
# temp array to hold left and right
leftarr = [0] * n1
rightarr = [0] * n2
for i2 in range(0, n1):
leftarr[i2] = array[i2 + begin]
for i1 in range(0, n2):
rightarr[i1] = array[i1 + mid + 1]
# leftarr[n1] = -1
# rightarr[n2] = -1
i = 0
j = 0
k = begin
while i < n1 and j < n2:
if leftarr[i] <= rightarr[j]:
array[k] = leftarr[i]
i = i + 1
else:
array[k] = rightarr[j]
j = j + 1
k = k + 1
while i < n1:
array[k] = leftarr[i]
i = i + 1
k = k + 1
while j < n2:
array[k] = rightarr[j]
j = j + 1;
k = k + 1;
def mergesort(array, l, r):
if l < r:
mid = (l + r) >> 1
mergesort(array, l, mid)
mergesort(array, mid + 1, r)
merge(array, l, mid, r)
mergesort(arr, 0, len(arr) - 1)
for i in range(0, len(arr)):
print(arr[i])
|
96b48cba3841d3deba16a2a728613a5bb677722a | rituc/Programming | /geesks4geeks/array/merge_array.py | 812 | 3.953125 | 4 | def main():
print "Enter number of test cases"
T = int(input())
for t in range(T):
print "Enter array size of first array:"
n = int(input())
print "Enter number of elements in second array:"
m = int(input())
nplusm = []
a = []
for i in range(n+m):
nplusm.append(int(raw_input("array1 elem:")))
for i in range(int(m)):
a.append(int(raw_input("array2 elem:")))
print merge_array(nplusm, a, n, m)
def merge_array(nplusm, a, n, m):
b = shift_array_elem(nplusm, n, m)
j = 0
i = m+n-1
for k in range(n+m):
if (a[j] < b[i]):
b[k] = a[j]
j += 1
else:
b[k] = b[i]
i -= 1
return b
def shift_array_elem(a, n, m):
j = n+m-1
for i in range(n+m-1, 0, -1):
if(a[i] != -1):
a[j] = a[i]
j -= 1
print "shifted array", a
return a
if __name__ == "__main__":
main()
|
35964424e3c8111346cabbefaad2ecb18fb598f9 | sunrain0707/python_exercise_100 | /ex46.py | 210 | 3.71875 | 4 | #46.求输入数字的平方,如果平方运算后小于 50 则退出。
f = True
while f:
x = int(input('input a number:'))
cul = x*x
if cul<50:
f = False
print('exit')
|
56d996a5317d3a40149e8a42424d6a40d804796c | Akash1435/pythonprog | /holiday.py | 196 | 4.15625 | 4 | mystr = str(raw_input())
if(mystr == 'SATURDAY' or mystr == 'Saturday' or mystr == 'saturday' or mystr == 'SUNDAY' or mystr == 'Sunday' or mystr == 'sunday'):
print 'yes'
else:
print 'no'
|
a69e63e24620df64c1966bfe013afaf17ae89bb7 | valborgs/pythonStudy | /0807/dictionary/01_dictionary_merge.py | 615 | 4.21875 | 4 | dict1 = {'a':1,'b':2}
dict2 = {'c':3,'d':4}
# 2개의 딕셔너리 합치는 방법1
# update()
# **원본 데이터가 변경됨**
dict1.update(dict2)
print(dict1)
print(dict2)
print('---------------------------')
empty = dict()
print(empty)
# key=value : **kwarg라고 표현(가변길이인수)
# key=value 1개로 딕셔너리 생성
new1 = dict(x='a')
print(new1)
# key=value 2개로 딕셔너리 생성
new2 = dict(x='a', y=0)
print(new2)
# 딕셔너리 병합2:
new3 = dict(dict1,k=1,p=3,t='p')
print(new3)
# 2개의 딕셔너리 합치는 방법2: **kwarg사용
new4 = dict(dict1, **dict2)
print(new4) |
1a427c0a21524eaac184c57543764cfa4ff4eaa0 | ensamblador/este-politico-no-existe | /contextual-training/src/torch_loader/dataset_from_pandas.py | 1,440 | 3.515625 | 4 | from torch.utils.data import Dataset
from src.torch_loader.vectorize_input import TrainInput
import json
import pandas as pd
class DatasetFromPandas(Dataset):
"""
DatasetFromFile :
generate vectorize samples (coalicion, partido, entidades... ; tweet) from a dataframe
main idea :
1/ will generate (nb_paragraphes - 2) tupple (input, label)
2/ will apply a GPT_2 tokenization for each input, label
"""
def __init__(self, df, transform):
"""
:param df: Pandas Dataframe
:param transform: transform: function to transform paragraph into a vectorized form (GPT_2 tokenization
"""
self.data = df
self.transform = transform
self.length = len(df)
def __len__(self):
"""
:return: number of paragraphes in the novel
"""
return self.length
def __getitem__(self, idx):
"""
:return: vectorized (COALICION, PARTIDO, SENTIMIENTO, ENTIDADES, HASHTAGS, FRASES, TWEET)
"""
COALICION, PARTIDO, SENTIMIENTO, ENTIDADES, HASHTAGS, FRASES, TWEET = self.data.iloc[idx]
training_example = TrainInput(
COALICION=COALICION,
PARTIDO=PARTIDO,
SENTIMIENTO=SENTIMIENTO,
ENTIDADES=ENTIDADES,
HASHTAGS=HASHTAGS,
FRASES=FRASES,
TWEET=TWEET
)
return self.transform(training_example)
|
03c639e9143a958324a1ca30d42f5501bcce9cc1 | django-group/python-itvdn | /домашка/essential/lesson 8/Marukhniak Denys/L_8_2.py | 827 | 3.609375 | 4 | # Задание 2
# Модифицируйте решение предыдущего задания так, чтобы оно работало не с текстовыми, а бинарными
# файлами.
import random
import pickle
def numbs():
return str(random.randrange(99))
lines = ''
for i in range(20):
for j in range(25):
lines += (numbs() + ' ').zfill(3)
lines = (lines.rstrip() + '\n')
s = pickle.dumps(lines)
print(f'{type(s)=} {s=}')
with open('L_8_2_b_random.bin', 'wb') as f:
f.write(s)
with open('L_8_2_b_random.bin', 'rb') as f:
s = f.read()
s = pickle.loads(s)
print(f'{type(s)=} {s=}')
numbs = []
s = s.split('\n')
for i in s:
tmp = (i.split())
for j in tmp:
numbs.append(j)
result = [int(x) for x in numbs]
print(f'Sum = {sum(result)}')
|
16bcbf1ad21ea7e36239ad59c43d69dc2a7d55cd | CaiY77/python-exercise | /loops.py | 384 | 3.875 | 4 | for i in range (10):
print(i)
# prints every 2nd letter
mess = "This is a string"
for c in range(0, len(mess), 2):
print(mess[c])
# does cipher left shift
mess = "This is a random Message"
newmessage=""
for c in mess:
offset=ord(c)-ord("a")+25
wrap=offset%26
newchar=chr(ord("a")+wrap)
newmessage =newmessage+newchar
print("Your new Message: ", newmessage)
|
a8b6af04333629fa9ad34df65ca323de7fd8f330 | 8snayp8/Task | /№1.py | 263 | 3.765625 | 4 | #1
def Slov(key,val):
if len(key)>len(val):
while len(key)>len(val):
val.append(None)
else:
return {key:value for key,value in zip(key, val)}
key=[1,2,3,4,5]
val=["a","b",'c','d',]
print(Slov(key,val)) |
9cc823736e4777074b1498e38d56027457be5e9c | JoshCLWren/python_stuff | /multiple_inheritance.py | 736 | 4.03125 | 4 | class Aquatic:
def __init__(self, name):
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea"
class Ambulatory:
def __init__(self, name):
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land!"
# only the first one on the left will run but you still have access to all the inherited methods
class Penguin(Ambulatory, Aquatic):
def __init__(self, name):
super().__init__(name=name)
jaws = Aquatic("Jaws")
lassie = Ambulatory("Lassie")
captain_cook = Penguin("Captain Cook")
print(captain_cook.swim())
print(captain_cook.walk())
print(captain_cook.greet()) |
82be979ea634b390feb734450d8300fa4c385e06 | zafe312/tic-tac-toe-AI | /tictactoe.py | 7,870 | 3.625 | 4 | import random
from copy import deepcopy
X='X'
O='O'
EMPTY='EMPTY'
def initial_state():
return [[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY]]
def terminal(board):
status = 0
if board[0].count(EMPTY)+board[1].count(EMPTY)+board[2].count(EMPTY)==0:
status = 1
else:
if board[0][0]==board[1][1]==board[2][2]!=EMPTY or board[2][0]==board[1][1]==board[0][2]!=EMPTY:
status = 1
else:
for i in range(3):
if board[i][0]==board[i][1]==board[i][2]!=EMPTY or board[0][i]==board[1][i]==board[2][i]!=EMPTY:
status = 1
break
if status == 1:
return True
else:
return False
def winner(board):
winr=''
if board[0][0]==board[1][1]==board[2][2]==X or board[2][0]==board[1][1]==board[0][2]==X:
winr = 'X'
elif board[0][0]==board[1][1]==board[2][2]==O or board[2][0]==board[1][1]==board[0][2]==O:
winr = 'O'
else:
for i in range(3):
if board[i][0]==board[i][1]==board[i][2]==X or board[0][i]==board[1][i]==board[2][i]==X:
winr = 'X'
break
elif board[i][0]==board[i][1]==board[i][2]==O or board[0][i]==board[1][i]==board[2][i]==O:
winr = 'O'
break
if winr == '' and board[0].count(EMPTY)+board[1].count(EMPTY)+board[2].count(EMPTY)==0:
winr = None
return winr
# This function returns true if there are moves
# remaining on the board. It returns false if
# there are no moves left to play.
def isMovesLeft(board) :
for i in range(3) :
for j in range(3) :
if (board[i][j] == EMPTY) :
return True
return False
def evaluate(b, depth) :
# Checking for Rows for X or O victory.
for row in range(3) :
if (b[row][0] == b[row][1] and b[row][1] == b[row][2]) :
if (b[row][0] == 'X') :
return 10 - depth
elif (b[row][0] == 'O') :
return -10 + depth
# Checking for Columns for X or O victory.
for col in range(3) :
if (b[0][col] == b[1][col] and b[1][col] == b[2][col]) :
if (b[0][col] == 'X') :
return 10 - depth
elif (b[0][col] == 'O') :
return -10 + depth
# Checking for Diagonals for X or O victory.
if (b[0][0] == b[1][1] and b[1][1] == b[2][2]) :
if (b[0][0] == 'X') :
return 10 - depth
elif (b[0][0] == 'O') :
return -10 + depth
if (b[0][2] == b[1][1] and b[1][1] == b[2][0]) :
if (b[0][2] == 'X') :
return 10 - depth
elif (b[0][2] == 'O') :
return -10 + depth
# Else if none of them have won then return 0
return 0
def minimax_score(board, depth, isMax) :
board_copy = deepcopy(board)
score = evaluate(board, depth)
if winner(board) != '' :
return [score,(4,4)]
# If there are no more moves and no winner then
# it is a tie
if (isMovesLeft(board) == False) :
return [0,(4,4)]
depth += 1
score = []
moves = []
if isMax:
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
new_board = result(board_copy,(i,j))
board_copy = deepcopy(board)
score.append(minimax_score(new_board,depth,False)[0])
moves.append((i,j))
else:
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
new_board = result(board_copy,(i,j))
board_copy = deepcopy(board)
score.append(minimax_score(new_board,depth,True)[0])
moves.append((i,j))
if isMax:
return [max(score),moves[score.index(max(score))]]
else:
return [min(score),moves[score.index(min(score))]]
# This will return the best possible move for the player
def minimax(board):
# make copy of board
board_copy = deepcopy(board)
# before using minimax algorithm, check whether you can win in single move, otherwise check if opposition is about to win
# if board is empty: return a corner position
corner_pos = [(0,0),(0,2),(2,0),(2,2)]
if board == initial_state():
return corner_pos[random.randrange(4)]
# else if board is almost empty with an X at a corner: return (1,1)
elif board == [[X,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY]] or board == [[EMPTY,EMPTY,X],[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY]] or board == [[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY],[X,EMPTY,EMPTY]] or board == [[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,EMPTY],[EMPTY,EMPTY,X]]:
return (1,1)
else:
#loop through available positions of the board: nodes: check for winning move
for i in range(3):
for j in range(3):
if board[i][j]==EMPTY:
# if X is playing
if player(board) == 'X':
# evaluate node: first move
u = utility(result(board_copy,(i,j)))
board_copy = deepcopy(board)
# check if this move makes X win, i.e node score == 1: immediately return this position
if u == 1:
return (i,j)
# if O is playing
else:
# evaluate node
u = utility(result(board_copy,(i,j)))
board_copy = deepcopy(board)
# check if this move makes O win, i.e node score == -1: immediately return this position
if u == -1:
return (i,j)
#loop again if opposite is about to win
for i in range(3):
for j in range(3):
if board[i][j]==EMPTY:
# if X is playing
if player(board) == 'X':
# check if making this move makes O win in the next move, i.e. node score of next move == -1: immediately return this position
v = utility(result_opp(board_copy,(i,j)))
board_copy = deepcopy(board)
if v == -1:
return (i,j)
# if O is playing
else:
# check if making this move makes X win in the next move: immediately return this position
v = utility(result_opp(board_copy,(i,j)))
board_copy = deepcopy(board)
if v == 1:
return (i,j)
if player(board) == 'X':
return minimax_score(board, 0, True)[1]
else:
return minimax_score(board, 0, False)[1]
def result(board, move):
temp_board=board
temp_board[move[0]][move[1]]=player(board)
return temp_board
def result_opp(board, move):
temp_board=board
if player(board)=='X':
temp_board[move[0]][move[1]]='O'
else:
temp_board[move[0]][move[1]]='X'
return temp_board
# gives scores to terminal boards based on winner
def utility(board):
if terminal(board)==True:
if winner(board) == 'X':
return 1
elif winner(board) == 'O':
return -1
elif winner(board) == None:
return 0
else:
return 2 # board is not terminal
def player(board):
X=0
O=0
for i in range(3):
X+=board[i].count('X')
O+=board[i].count('O')
if X>O:
return 'O'
else:
return 'X' |
b182192cd0a682d2899ac983d9933f586f4ebee0 | mattgrogan/liberty_bell | /liberty_bell/slot_machines/components/symbol.py | 301 | 3.734375 | 4 | class Symbol(object):
""" Superclass for symbols on the slot machine """
def __init__(self, name, image=None):
""" Initialize the symbol """
self.name = name
self.image = image
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other.name
|
6fbe1a3d9bdecfeaa7a776ee16d28d2b0bcb88e9 | vicety/LeetCode | /python/interview/2023-fulltime/hulu/2.py | 2,467 | 4.1875 | 4 | # reverse signly linked list in recursive way
# 1 -> 2 -> 3 -> 4 -> 5
# 5 -> 4 -> 3 -> 2 -> 1
class ListNode:
def __init__(self):
self.val = None
self.next = None
def reverse(head: ListNode):
if head is None or head.next is None:
return head
ret = reverse(head.next)
head.next.next = head
head.next = None
return ret
def makeList(arr):
dummy = ListNode()
now = dummy
for num in arr:
now.next = ListNode()
now.next.val = num
now = now.next
return dummy.next
def printList(head):
s = ""
while head:
s += str(head.val) + " "
head = head.next
print(s)
lst = makeList([1, 2, 3, 4, 5])
# lst = makeList([])
printList(reverse(lst))
# Given the root of a binary tree, flatten the tree into a "linked list":
# The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
# The "linked list" should be in the same order as a pre-order traversal of the binary tree.
# 1
# 2. 3
# 4. 5. 6
# 1
# 2
# 4 5
# 3
# 6
# . 1
# 2
# 4
# 5
# 3
# 6
def solve(root):
if not root:
return None, None
flattenLHead, flattenLTail = solve(root.left)
flattenRHead, flattenRTail = solve(root.right)
if flattenLTail is not None:
root.right = flattenLHead
flattenLTail.right = flattenRHead
if flattenRTail:
return root, flattenRTail
else:
return root, flattenLTail
else:
root.right = flattenRHead
if flattenRTail:
return root, flattenRTail
else:
return root, root
# if root.left is not None:
# now = root.left
# while now.right is not None:
# now = now.right
# now.right = root.right
# root.right = root.left
# root.left = None
# solve(root.right)
class TreeNode:
def __init__(self, val):
self.left = None
self.right = None
self.val = val
nodes = [TreeNode(i) for i in range(0, 7)]
nodes[1].left = nodes[2]
nodes[1].right = nodes[3]
nodes[2].left = nodes[4]
nodes[2].right = nodes[5]
nodes[3].right = nodes[6]
solve(nodes[1])
now = nodes[1]
s = ""
while now:
s += str(now.val) + " "
now = now.right
print(s)
# def say_hello():
# print('Hello, World')
# for i in range(5):
# say_hello()
|
8f4cf29b137b4780521bbb85b1eb9f4c01b6010a | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/dbzphi002/question1.py | 270 | 4.0625 | 4 | #Thembekile Dubazana
#DBZPHI002
#10 March 2014
year= eval(input('Enter a year:\n'))
if ((year%400)/400)==0 :
print(year,'is a leap year.')
elif ((year%4/4)==0) and ((year%100/100)!=0):
print(year,'is a leap year.')
else:
print(year,'is not a leap year.') |
3d3aaec2c3f60f60cb07f868b641800c917394c0 | MaxBolD/UdemyTF | /Chapter2_Python/ForLoop.py | 426 | 4.125 | 4 | grades = [1, 2, 1, 4]
num_elements = len(grades)
for idx in range(num_elements): # range(num_elements) => [0, 1, ..., num_elements-1]
print(grades[idx])
print("\n")
for idx in range(1, 10, 1): # range(start, end, step) => [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(idx)
print("\n")
for idx in range(1, 10, 2): # range(start, end, step) => [1, 3, 5, 7, 9]
print(idx)
print("\n")
for grade in grades:
print(grade)
|
261c69339027e63e3a5806446d390eb7cf487ae1 | BlaiseMarvin/the-numpy-library | /transposingSwapping.py | 219 | 3.90625 | 4 | import numpy as np
arr=np.arange(15).reshape((3,5))
print(arr)
#Transposing
print(arr.T)
#The dot product
#np.dot(arr.T,arr) the dot product between the transpose of arr, and arr
arr=np.random.randn(6,3)
print(arr)
|
a940a0e2dacf3e894a4436f9f02e5df676710567 | mohammad20-meet/meetyl1201819 | /lab7.py | 1,446 | 3.828125 | 4 | from turtle import *
import random
import turtle
import math
turtle.colormode(255)
#edges
width = 350
height = 350
turtle.pu()
turtle.goto(350,0)
turtle.pd()
turtle.goto(350,350)
turtle.goto(-350,350)
turtle.goto(-350,-350)
turtle.goto(350,-350)
turtle.goto(350,0)
turtle.hideturtle()
class Ball(Turtle):
def __init__(self,x,y,dx,dy,radius,color):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.color(color)
#self.speed(speed)
self.goto(x,y)
self.dx = dx
self.dy = dy
def move(self):
oldx = self.xcor()
oldy = self.ycor()
newx = oldx + self.dx
newy = oldy + self.dy
self.goto(newx,newy)
if newy>height or newy<-height:
self.dy = -self.dy
if newx>width or newx<-width:
self.dx = -self.dx
def random_color(self):
r = random.randint(0,256)
g = random.randint(0,256)
b = random.randint(0,256)
self.color(r,g,b)
def check_colliision(ball_1,ball_2):
x1 = ball_1.xcor()
x2 = ball_2.xcor()
y1 = ball_1.ycor()
y2 = ball_2.xcor()
D = math.sqrt(math.pow((x2-x1),2) + math.pow((y2-y1),2))
if D<ball_1.radius+ball_2.radius:
return True
else:
return False
turtle.bgcolor("pink")
ball_1 = Ball(30,30,50,30,30,"blue")
ball_2 = Ball(50,14,20,40,30,"red")
balls = [ball_1,ball_2]
while True:
ball_1.move()
ball_2.move()
if(check_colliision(ball_1, ball_2) == True):
ball_1.random_color()
ball_2.random_color()
turtle.mainloop()
|
2d4e61723c86ed1a21ce6bb36a93bbe770abf079 | hamsini505/learning | /multiples.py | 202 | 3.515625 | 4 | #sum = 0
#sum1 = 0
#for i in range(1,1000):
# if(i % 3 == 0 or i % 5 == 0):
# sum = sum + i
#print(sum)
limit = 1000
li = (set(range(3,limit,3)) | set(range(5,limit,5)))
print(sum(li))
|
2833084d695e7066c7d7cb20ef902497938e770f | mubashramajid/Marksheet | /Marksheet.py | 3,711 | 3.875 | 4 | a=str(input("What is the student's name?"))
b=int(input("what is student's roll number?"))
c=str(input(" Enter 1st subject name"))
d=float(input("Enter 1st subject marks"))
e=str(input(" Enter 2nd subject name"))
f=float(input("Enter 2nd subject marks"))
g=str(input(" Enter 3rd subject name"))
h=float(input("Enter 3rd subject marks"))
i=str(input(" Enter 4rth subject name"))
j=float(input("Enter 4rth subject marks"))
k=str(input(" Enter 5th subject name"))
l=float(input("Enter 5th subject marks"))
X=500
print("*****************Marksheet**********************")
print("Student Name:", a)
print("Student ID:", b)
print("Subject"," Marks Obtained "," Grade")
if d>=91 and d<=100:
print(c," ",d," "," A+")
elif d>=81 and d<=90:
print(c," ",d," "," A")
elif d>=71 and d<=80:
print(c," ",d," "," B+")
elif d>=61 and d<=70:
print(c," ",d," "," B")
elif d>=56 and d<=60:
print(c," ",d," "," C+")
elif d>=51 and d<=55:
print(c," ",d," "," C")
else:
print(c," ",d," "," D")
if f>=91 and f<=100:
print(e," ",f," "," A+")
elif f>=81 and f<=90:
print(e," ",f," "," A")
elif f>=71 and f<=80:
print(e," ",f," "," B+")
elif f>=61 and f<=70:
print(e," ",f," "," B")
elif f>=56 and f<=60:
print(e," ",f," "," C+")
elif f>=51 and f<=55:
print(e," ",f," "," C")
else:
print(e," ",f," "," D")
if h>=91 and h<=100:
print(g," ",h," "," A+")
elif h>=81 and h<=90:
print(g," ",h," "," A")
elif h>=71 and h<=80:
print(g," ",h," "," B+")
elif h>=61 and h<=70:
print(g," ",h," "," B")
elif h>=56 and h<=60:
print(g," ",h," "," C+")
elif h>=51 and h<=55:
print(g," ",h," "," C")
else:
print(g," ",h," "," D")
if j>=91 and j<=100:
print(i," ",j," "," A+")
elif j>=81 and j<=90:
print(i," ",j," "," A")
elif j>=71 and j<=80:
print(i," ",j," "," B+")
elif j>=61 and j<=70:
print(i," ",j," "," B")
elif j>=56 and j<=60:
print(i," ",j," "," C+")
elif j>=51 and j<=55:
print(i," ",j," "," C")
else:
print(i," ",j," "," D")
if l>=91 and l<=100:
print(k," ",l," "," A+")
elif l>=81 and l<=90:
print(k," ",l," "," A")
elif l>=71 and l<=80:
print(k," ",l," "," B+")
elif l>=61 and l<=70:
print(k," ",l," "," B")
elif l>=56 and l<=60:
print(k," ",l," "," C+")
elif l>=51 and l<=55:
print(k," ",l," "," C")
else:
print(k," ",l," "," D")
sum=d+f+h+j+l
print("Total Marks: ",sum,"/",X)
per=sum/X*100
print("Percentage: ", per)
if per>=91 and per<=100:
print("-----The overall grade is A+-----")
elif per>=81 and per<=90:
print("-----The overall grade is A-----")
elif per>=71 and per<=80:
print("-----The overall grade is B+-----")
elif per>=61 and per<=70:
print("-----The overall grade is B-----")
elif per>=56 and per<=60:
print("-----The overall grade is C+-----")
elif per>=51 and per<=55:
print("-----The overall grade is C-----")
else:
print("-----The overall grade is D. FAILED-----") |
932d341f566702a727432c31adb52b469da08ef8 | edaley5177/PublicWork | /Python/CodeFights/MirrorBits.py | 563 | 4.15625 | 4 | # Reverse the order of the bits in a given integer.
# Example
# For a = 97, the output should be
# mirrorBits(a) = 67.
# 97 equals to 1100001 in binary, which is 1000011 after mirroring, and that is 67 in base 10.
# For a = 8, the output should be
# mirrorBits(a) = 1.
def mirrorBits(a):
import math
power=int(math.log10(a)/math.log10(2))
i=0
ret=0
while(power>=0):
ret += (a%2) * 2**power
print "power is :", power, " ret is : ", ret, " a mod 2**power is: ", a%(2**power)
a/=2
power-=1
return ret |
f7bc5abcde532dfb36422a959ee0d8646f628477 | chevEldrid/karn-sorter | /fixup_collection.py | 2,188 | 3.578125 | 4 | import sys
import csv
#Given two csv files, moves all cards above one threshold to the first file, and all below to the other...
#---------------------------
#intake output file
BULK_CEILING = 0.99
valued = []
bulk = []
valued_result = []
bulk_result = []
def read_file(file):
temp = []
with open(file) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
try:
temp.append((row[0], row[1], row[2]))
#print(row)
except:
print("Error on {0}. Will be dropped from Table".format(row[0]))
#create copy of cards list to iterate through and not mess up for loop
del temp[0]
return temp
def sort_list(card_list):
for i, val in enumerate(card_list):
name = val[0]
qty = val[1]
price = float(val[2])
#if the card hasn't already been found...
if price > BULK_CEILING:
valued_result.append((name, qty, price))
else:
bulk_result.append((name, qty, price))
def write_to_file(file, output_list):
with open(file, "w") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["card","qty","price"])
for card in output_list:
writer.writerow([card[0], card[1], card[2]])
try:
with open(sys.argv[1]) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
print(sys.argv[1] + " successfully read in, value will be stored here.")
with open(sys.argv[2]) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
print(sys.argv[2] + " successfully read in, bulk will be stored here.")
except:
print("ERROR: csv files could not be read. Please input names of csvs as first and second arg")
sys.exit()
valued_file = sys.argv[1]
bulk_file = sys.argv[2]
valued = read_file(valued_file)
bulk = read_file(bulk_file)
sort_list(valued)
sort_list(bulk)
#sort prices from high to low
valued_result = sorted(valued_result, key=lambda tup: float(tup[2]), reverse=True)
bulk_result = sorted(bulk_result, key=lambda tup: float(tup[2]), reverse=True)
#now print to csv
write_to_file(valued_file, valued_result)
write_to_file(bulk_file, bulk_result)
print("Bulk successfully sorted. Have a pleasant day")
|
5f938f72dc58c2cbb8c005cb3c4b15c4a645fa15 | southpawgeek/perlweeklychallenge-club | /challenge-080/roger-bell-west/python/ch-2.py | 567 | 3.5 | 4 | #! /usr/bin/python3
import unittest
def cc(list):
n=sorted(range(len(list)), key=lambda x: list[x])
k=[0] * len(list)
for i in n:
nr=[1]
if (i > 0 and list[i-1] < list[i]):
nr.append(k[i-1]+1)
if (i < len(list)-1 and list[i+1] < list[i]):
nr.append(k[i+1]+1)
k[i]=max(nr)
return sum(k)
class TestCc(unittest.TestCase):
def test_ex1(self):
self.assertEqual(cc((1,2,2)),4,'example 1')
def test_ex2(self):
self.assertEqual(cc((1,4,3,2)),7,'example 2')
unittest.main()
|
2754829119354f71fa4a181fb9b560da5223dfe7 | rafaxtd/URI-Judge | /AC02/donation.py | 208 | 3.578125 | 4 |
buy = True
vic = 0
while buy == True:
n = float(input())
if n == -1.0:
buy = False
else:
vic += n
real = vic * 2.50
print(f'VC$ {vic:.2f}')
print(f'R$ {real:.2f}')
|
4f2b9cbace08a6b062f42739c8c46a787fb85928 | usoofali/soofali | /Finding large number.py | 425 | 4.28125 | 4 | print("PROGRAM FOR FINDING THE LARGEST AMONG THREE NUMBERS")
print("Please enter the numbers")
a=int(input("First Number:"))
b=int(input("Second Number:"))
c=int(input("Third Number:"))
if a > b and a > c:
print("The largest number is",a)
elif c > a:
print("The largest number is",c)
elif b > a:
print("The largest number is",b)
else:
print("No answer")
input("\n\nPress enter key to exit")
|
c549b371e1c1a36905f24bd9e3344ff9ff64ab4a | pemedeiros/python-CeV | /pacote-download/CursoemVideo/ex088.py | 461 | 3.515625 | 4 | from random import randint
from time import sleep
jogo = []
lista = []
tot = 1
qtd = int(input('Quantos jogos você quer fazer? '))
while tot <= qtd:
cont = 0
while True:
n = randint(1, 60)
if n not in jogo:
jogo.append(n)
cont += 1
if cont >= 6:
break
lista.append(sorted(jogo[:]))
jogo.clear()
tot += 1
for i, l in enumerate(lista):
print(f'Jogo {i + 1}: {l}')
sleep(1)
|
a47c4e9e84ba75b84d7e692a9efda615034aece3 | bensonalec/CCBWIPFSR-C-Compiler | /src/frontend/semantics.py | 11,966 | 3.515625 | 4 | """
The module serves to perform semantic analysis on the AST to ensure the typing is correct
"""
from collections import namedtuple
import re
Node = namedtuple("Node", ["Node", "Scope"])
Node.__doc__ = """
A simple namedtuple to allow for better readability when performing the depth first search required for the semantic analysis.
"""
Node = namedtuple("Node", ["Node", "Scope"])
en_map = {
0 : "Variable",
1 : "Function",
2 : "Parameter",
3 : "Label",
}
class semantic():
"""
A class that stores any semantic errors that occur.
"""
def __init__(self,AST,symbols):
"""
Args:
AST: The head node of the abstract syntax tree.
symbols: The symbol table
"""
self.errors = []
self.AST = AST
self.symbols = symbols
def semanticAnalysis(self):
"""
Runs semantic analysis
"""
AST = self.AST
symbols = self.symbols
ntv = [Node(AST, "/")]
typ = None
b = False
#regexes to do type checks on the fly
isDigit = r"\-?([1-9]\d*|\d)"
isOp = r'\+|\-|\/|\*|\||\&|\^|\~'
isPrec = r"\-?(\d\.\d+|[1-9]\d*\.\d+)"
isChar = r"(\'[\w\;\\ \%\"\']\')"
isString = r"(\"[\w+\;\\ \%\"\']*\")"
precCheck = re.compile(isPrec)
digCheck = re.compile(isDigit)
opCheck = re.compile(isOp)
charCheck = re.compile(isChar)
stringCheck = re.compile(isString)
# Simple implementation of a DFS
funcname = ""
while ntv != []:
# Grabs the first element which will be the residual left most child
cur = ntv[0]
# checks whether the current node is an operation that will need to access the symbol table
try:
index = ["=","call","func","goto"].index(cur.Node.name)
#Catches edge case where var or func is used an self_defined name
if cur.Node.children == [] or cur.Node.parent.name == "call":
ntv = [Node(x, cur.Scope) for x in cur.Node.children if 'children' in x.__dict__] + ntv[1:]
continue
# Function Declaration
if index == 0:
children = cur.Node.children
expectedType = ""
topVar = ""
for x in children:
#get the expected type, or variable in assignment
if(x.name == "var"):
chil = ([z for z in x.children])
#this is the variable that is being assigned to
var = chil[-1]
#get the expected type from symbol table
tblEntry = [x for x in symbols if x.name == var.name and funcname in x.scope]
if(expectedType == ""):
if(len(tblEntry) == 1):
#it is in the table already (good)
topVar = tblEntry[0].name
expectedType = tblEntry[0].type
else:
if(expectedType != tblEntry[0].type):
self.errors.append("Type mismatch for variable" + " " + var.name)
#check function calls
elif(x.name == "call"):
chil = [z for z in x.children]
func = chil[-1]
tblEntry = [x for x in symbols if x.name == func.name and cur.Scope in x.scope and x.entry_type == {value: key for key, value in en_map.items()}["Function"]]
if(len(tblEntry) == 1):
funcType = tblEntry[0].type
if(funcType != expectedType):
self.errors.append("Type mismatch for " + topVar)
#one of the children is a precision
elif(precCheck.match(x.name)):
if(expectedType != "float" and expectedType != "double"):
self.errors.append("Type mismatch for " + topVar + ", unexpected precision " + x.name)
#one of the chidlren is an integer
elif(digCheck.match(x.name)):
if(expectedType != "" and expectedType != "int" and expectedType != "float" and expectedType != "double" and expectedType != "short" and expectedType != "long" and expectedType != "char"):
print(expectedType, x.name)
print("HERE")
self.errors.append("Type mismatch for " + topVar + ", unexpected integer " + x.name)
elif(charCheck.match(x.name)):
if(expectedType != "char"):
self.errors.append("Type mismatch for " + topVar + ", unexpected character " + x.name)
elif(stringCheck.match(x.name)):
if(expectedType != "string"):
self.errors.append("Type mismatch for " + topVar + ", unexpected string " + x.name)
#case that operators are in use
elif(opCheck.match(x.name)):
#need to desced through all possible branches of this, and ensure everything is use is an integer
#expect variables, function calls, and integers in operatiosn
#need to traverse all nodes inside of this branch
ntvTemp = [Node(x, "/")]
while ntvTemp != []:
# Grabs the first element which will be the residual left most child
curTemp = ntvTemp[0]
if(expectedType == "int"):
if(curTemp.Node.name == "var" or curTemp.Node.name == "call"):
pass
elif([x for x in symbols if x.name == curTemp.Node.name and curTemp.Scope in x.scope] != []):
var = [x for x in symbols if x.name == curTemp.Node.name and curTemp.Scope in x.scope][0]
if(var.type != "int"):
self.errors.append("Type mismatch for " + topVar)
elif((precCheck.match(curTemp.Node.name))):
self.errors.append("Type mismatch for " + topVar)
elif(not (digCheck.match(curTemp.Node.name) or opCheck.match(curTemp.Node.name))):
self.errors.append("Type mismatch for " + topVar)
ntvTemp = [Node(z, curTemp.Scope) for z in curTemp.Node.children if 'children' in z.__dict__] + ntvTemp[1:]
pass
#function call
elif index == 1:
#iterate through the children, get the name of the function, look up how many parameters it expects
func = cur.Node.children[0]
functionName = func.name
functionChildren = [x.name for x in func.children]
#get the number of params and types from the symbol table
params = [x for x in symbols if functionName in x.scope and x.entry_type == {value: key for key, value in en_map.items()}["Parameter"]]
types = [x.type for x in params]
if(len(params) != len(functionChildren)):
self.errors.append("Improper amount of arguments in call to function " + functionName)
else:
for it,par in enumerate(functionChildren):
#get type of par
expec = types[it]
#one of the children is a precision
if(precCheck.match(par)):
if(expec != "float" and expec != "double"):
self.errors.append("Type mismatch for " + functionName + ", unexpected precision " + par)
#one of the chidlren is an integer
elif(digCheck.match(par)):
if(expectedType != "int" and expectedType != "float" and expectedType != "double" and expectedType != "short" and expectedType != "long" and expectedType != "char"):
self.errors.append("Type mismatch for " + functionName + ", unexpected integer " + par)
elif(charCheck.match(par)):
if(expec != "char"):
self.errors.append("Type mismatch for " + functionName + ", unexpected character " + par)
elif(stringCheck.match(par)):
if(expec != "string"):
self.errors.append("Type mismatch for " + functionName + ", unexpected string " + par)
#check if type of par and types[it] are the same
pass
#then iterate through the children of this and check the types of the parameters
pass
#function definition
elif index == 2:
funcname = cur.Node.children[1].name
#get params of the node currently being visited
params = [x for x in cur.Node.children[2].children]
params = [(x.children[0].name) for x in params]
# print(params)
#get the expected params
expected = ([(x.type) for x in symbols if x.entry_type == {value: key for key, value in en_map.items()}["Parameter"] and f"/{funcname}/" == x.scope])
if expected != params:
self.errors.append("Parameters in function prototype do not match function definition in " + funcname)
#goto labels
elif index == 3:
label = cur.Node.children[0]
labelName = label.name
#look for labelName: in the symbol table
toLook = labelName
found = ([x.name for x in symbols if x.entry_type == {value: key for key, value in en_map.items()}["Label"] and x.name == toLook])
if(found == []):
self.errors.append("Label " + labelName + " not found")
elif(len(found) > 1):
self.errors.append("Multiple labels with name " + labelName + " found")
except ValueError:
# This means that the token is not in that list
pass
# fetches the relevant children of the current node and appends the already known children to the list of residual nodes
ntv = [Node(x, cur.Scope) for x in cur.Node.children if 'children' in x.__dict__] + ntv[1:]
def printSemanticErrors(self):
"""
Prints the semantic errors to stdout
"""
for i in self.errors:
print(i)
def lineSemanticErrors(self):
"""
Retrieves the semantic errors
Returns:
output: All the semantic errors as a string separated by new lines
"""
output = ""
for i in self.errors:
output += (i+"\n")
return output |
9777c22791a8fa7e60c9a21b4cbde97b0dde426e | kolyasalubov/Lv-585.2.PythonCore | /HW6/Viktor/6_2.py | 738 | 4.15625 | 4 | def rectangle_area(a, b):
return a * b
def triangle_area(a, h):
return (a*h)/2
def circle_area(r):
return 3.14*r**2
def area():
print("Choose the figure which you know to the area of")
x = int(input("Rectangle press: 1 \nTriangle press: 2 \nCircle press: 3\n"))
if x == 1:
a = float(input("Length a = "))
b = float(input("Length b = "))
print("Area of rectangle =", rectangle_area(a, b))
elif x == 2:
a = float(input("Length a = "))
h = float(input("Length h = "))
print("Area of triangle =", triangle_area(a, h))
elif x == 3:
r = float(input("Length r = "))
print("Area of circle =", circle_area(r))
return "Good job)"
print(area())
|
32786fe25aa0df1c32f8a23272b9169bf5bf7370 | romchie/MinecraftWheatSimulator | /mcWheatSim.py | 1,024 | 3.734375 | 4 | import time
import random
class Wheat:
def __init__(self):
self.stage = 0
def plant(self):
plant_input = str(input("Type [p] to plant the seeds: "))
if plant_input == "p":
print("The wheat has begun growing! (Now Stage 1)")
self.stage += 1
def plantedStatus(self):
if self.stage < 1:
planted = False
else:
planted = True
return planted
def grow(self):
if self.stage > 0 and self.stage < 5:
time.sleep(random.randrange(1, 5))
self.stage += 1
print("The wheat has grown! (Now stage " + str(self.stage) + ")")
def growthStatus(self):
if self.stage < 5:
growing = True
else:
growing = False
print("The wheat is fully grown and ready to be harvested!")
return growing
def main():
w = Wheat()
while not w.plantedStatus():
w.plant()
while w.growthStatus():
w.grow()
main()
|
91867ab88c767a302223ad54f8d7de2ec0dd668d | AaronTho/Python_Course | /inputs_and_integers.py | 95 | 3.953125 | 4 | num = input('Number: ')
print(int(num) - 5)
# print(float(num) - 5) will return a float (5.0)
|
390973660489ab575ff9f533f5f912d7b4e91e8f | dpetrovykh/Growing_Tree | /test_Node.py | 241 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 1 10:00:58 2020
@author: dpetrovykh
"""
from Node import Node
root = Node(1,1)
root.gen_child(1,2)
root.gen_child(2,1)
for node in root.depth_first():
print(node)
|
8dd6ed5951e04cf700596649381423089e71af7a | ansur304/PythonLearnings | /app.py | 763 | 4.03125 | 4 | # name = input("What is your name ? ")
# #favColor = input("What is your favourite color ? ")
# #print(name +" likes "+ favColor)
#
# #1 lb = 0.45359237 kg
# weight_kg = input("What is your weight in KG ? ")
# weight_lb = int(weight_kg) * 0.4535
# print(f" {name.upper()}! Your weight in LB is %d "%weight_lb)
# name = name.title()
# print(f"{name} name.find(a) ::")
#
# if name.__contains__("T"):
# print(f" {name}! Your name has 'T' ")
# elif int(weight_kg) > 100 or (name.find("a") != -1 and name.find("a") > 2) :
# print(f"{name}! Your name does not have 'T'")
# else:
# print(True)
print(max(range(1, 10, 2)))
list_x = []
for x in range(1,100,2):
list_x.append(x)
list_x.insert(len(list_x)+1, 2000)
print(list_x)
|
2ab4f44200f82a57ed0038f9f2813bdcbe45f0f3 | lintio/GuessTheWord | /GuessTheWord.py | 7,413 | 3.875 | 4 | import random, os, sys
from words import word_list as wordList
feedback = ''
winLose = ''
class settings:
wordlength = 10
level = 2
attempts = 5
hangman = ["""
/---\\
| |
| o
| /|\\ Hangman!
| / \\
|
/ \\____
""",
"""
/---\\
| |
| o
| /|\\ Hangman
| /
|
/ \\____
""",
"""
/---\\
| |
| o
| /|\\ Hangma
|
|
/ \\____
""",
"""
/---\\
| |
| o
| /| Hangm
|
|
/ \\____
""",
"""
/---\\
| |
| o
| | Hang
|
|
/ \\____
""",
"""
/---\\
| |
| o
| Han
|
|
/ \\____
""",
"""
/---\\
|
|
| Ha
|
|
/ \\____
""",
"""
/
|
|
| H
|
|
/ \\____
""",
"""
|
|
/ \\____
""",
"""
/ \\____
""",
"""
Let's Play Hangman!
Guess Letters and Words
Words to save the Hangman!
_______
"""]
def selectWord(lastWord):
#select a new word from word list and change to upper case
newWord = random.choice(wordList).upper()
if newWord == lastWord:
newWord = random.choice(wordList).upper()
else:
while len(newWord) > settings.wordlength:
newWord = random.choice(wordList).upper()
return(newWord)
def play(currentWord):
#init vers
global feedback
global winLose
activeWord = currentWord
guessedLetters = []
guessedWords = []
attempts = 10
wordCompletion = '_' * len(activeWord)
guessed = False
while guessed == False:
#check for lose
if attempts <= 0 and guessed == False:
winLose = 'lose'
feedback = 'sorry you lost the word was ' + activeWord
menu()
else:
os.system('cls' if os.name == 'nt' else 'clear')
# print(activeWord) #see word for testing
print('Guessed letters -', guessedLetters, 'Guessed Words -', guessedWords)
if attempts <= 0:
print(hangman[0])
else:
print(hangman[attempts])
print('\n')
print('-> ' + wordCompletion + ' <-')
print(feedback)
guess = input('->').upper()
#check input is a string
if guess.isalpha():
#check if input is a letter or word
#checks if letter
if len(guess) == 1:
if guess not in guessedLetters and guess not in activeWord:
guessedLetters.append(guess)
attempts -= settings.level
feedback = 'Sorry that letter is not in the word'
elif guess in guessedLetters:
feedback = 'you have already guessed ' + guess
else:
guessedLetters.append(guess)
#find index of letter in activeWord
for x, letter in enumerate(activeWord):
if guess == letter:
wordCompletion = list(wordCompletion)
wordCompletion[x] = letter
wordCompletion = ''.join(wordCompletion)
feedback = ''
if wordCompletion == activeWord:
feedback = 'Well done you guessed the word! ' + activeWord
winLose = 'win'
guessed = True
#checks if the guess is the length of activeWord
elif len(guess) == len(activeWord):
if guess not in guessedWords and guess != activeWord:
guessedWords.append(guess)
attempts -= settings.level
feedback = 'Sorry, ' + guess + ' is not the word'
elif guess in guessedWords:
feedback = 'You have already guessed ' + guess
else:
feedback = 'Well done you guessed the word! ' + activeWord
winLose = 'win'
guessed = True
else:
feedback = 'Sorry that is not a valid guess'
def menu():
global feedback
global winLose
menuSelect = 5
lastWord = ''
while menuSelect != 3:
os.system('cls' if os.name == 'nt' else 'clear')
if winLose == 'lose':
print("""
/---\\
| |
| o
| /|\\ Sorry, You Lost
| / \\
|
/ \\____
""")
elif winLose == 'win':
print("""
\\o/
| Congratulations!!
/ \\
""")
else:
print("""
/---\\
| |
| o
| /|\\ Hangman
| / \\
|
/ \\____
""")
print(feedback)
print('Current settings - Max Word length =', settings.wordlength, '& tries =', settings.attempts, '-')
print('1) Play')
print('2) Change Settings')
print('3) Quit')
menuSelect = input('->')
if menuSelect.isdigit:
menuSelect = int(menuSelect)
if menuSelect == 3:
exit()
elif menuSelect == 1: #Play
newWord = selectWord(lastWord)
lastWord = newWord
feedback = ''
play(newWord)
elif menuSelect == 2: #Settings
os.system('cls' if os.name == 'nt' else 'clear')
print('Current settings - Max Word length =', settings.wordlength, '& tries =', settings.attempts, '-')
print('1) Easy (max word length 4 & tries = 10)')
print('2) Normal (max word length 6 & tries = 5)')
print('3) Hard (max word length 10 tries = 3)')
print('4) Insane (max word length 100 tries = 2)')
print('5) Back')
diffSelect = input('->')
if diffSelect.isdigit():
diffSelect = int(diffSelect)
if diffSelect == 5:
continue
elif diffSelect == 1:
settings.wordlength = 4
settings.level = 1
settings.attempts = 10
elif diffSelect == 2:
settings.wordlength = 6
settings.level = 2
settings.attempts = 5
elif diffSelect == 3:
settings.wordlength = 10
settings.level = 4
settings.attempts = 3
elif diffSelect == 4:
settings.wordlength = 100
settings.level = 5
settings.attempts = 2
else:
print('Sorry, thats not a valid selection')
else:
print('Sorry, thats not a valid input')
else:
print('Sorry, thats not a valid input')
else:
print('Sorry, thats not a valid input')
menu() |
0071580506bfad973842e2b1cf93c2772ce07e70 | lienusrob/DeveloperbootcampDI | /Week_4/day2/Ex/code.py | 4,680 | 4.375 | 4 | # Create a set called my_fav_numbers with your favorites numbers.
# Add two new numbers to it.
# Remove the last one.
# Create a set called friend_fav_numbers with your friend’s favorites numbers.
# Concatenate my_fav_numbers and friend_fav_numbers to our_fav_numbers.
#task1
# my_fav_numbers = set([9, 3])
# my_fav_numbers.add("8")
# my_fav_numbers.add("4")
# my_fav_numbers.discard(3)
# friend_fav_numbers =set ([3, 1])
# our_fav_numbers = set(my_fav_numbers).union(set(friend_fav_numbers))
# print(our_fav_numbers)
#task2
#Given a tuple with integers is it possible to add more integers to the tuple?
#no becuase its immutable we could but we would creat a copy of it and it would not be saved anywhere
#task3
# fruits = ['apple', 'banana', 'kiwi', 'pear']
# for fruit in fruits:
# print(fruit)
# x = range(21)
# for n in x:
# print(n)
#another way easier
# for i in range(1, 21,):
# print(i)
#task4
# import decimal
# def float_range(start, stop, step):
# while start < stop:
# yield float(start)
# start += decimal.Decimal(step)
# print(list(float_range(0, 20.5, '0.5')))
#need to ask for help
#task5
# Consider this list basket = ["Banana", "Apples", "Oranges", "Blueberries"];
# Remove “Banana” from the list.
# Remove “Blueberries” from the list.
# Put “Kiwi” at the end of the list.
# Add “Apples” at the beginning of the list.
# Count how many apples are in the basket.
# Empty the basket.
# basket = ["Banana", "Apples", "Oranges", "Blueberries"];
# basket.remove("Banana")
# # print(basket)
# addbasket = ["Kiwi"]
# sumbaseket= basket + addbasket
# # print(sumbaseket)
# # print(len(sumbaseket))
# # print(sumbaseket.count("Apples"))
# # sumbaseket.clear
# # print(sumbaseket)
# print(sumbaseket)
# sumbaseket.clear()
# print(sumbaseket)
# task7
# Write a while loop that will keep asking the user for input until the input is the same as your name.
# Name = ''
# while Name != 'Rob':
# Name = input('Guess my name ? ')
# print('You guessed the right name!')
#task7
# Given a list, use a while loop to print out every element which has an even index.
# num=0
# basket = ["Banana", "Apples", "Oranges", "Blueberries"]
# while(num < len(basket)):
# # checking condition
# if num % 2 == 0:
# print(basket[num], end = " ")
# # increment num
# num += 1
# #task8Make a list of the multiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
# l = [i for i in range(3, 31) if i % 3 == 0]
# print(l)
# for i in range(3, 31,3):
# print(i)
#task9
#Use a for loop to find numbers between 1500 and 2700, which are divisible by 7 and multiples of 5.
# result=[]
# for x in range(1500, 2701):
# if (x%7==0) and (x%5==0):
# result.append(str(x))
# print (','.join(result))
#task10
# Ask the user to type in his/her favorite fruit(s) (one or several fruits).
# Hint : Use the input built in method. Ask the user to separate the fruits with a single space, eg. "apple mango cherry".
# Store the favorite fruit(s) in a list. (How can we ‘convert’ a string of words into a list of words?).
# # Now that we have a list of fruits, ask the user to type in the name of any fruit.
# # If the user’s input is a fruit name existing in the list above, print “You chose one of your favorite fruits! Enjoy!”.
# # If the user’s input is NOT a fruit name existing in the list above, print, “You chose a new fruit. I hope you enjoy it too!”.
# # Bonus: Display the list in a user friendly way : add the word “and” before the last fruit in the list – but only if there are more than 1 favorites!
# Fav = input('type your favorite fruits and separate with space?')
# def Convert(string):
# Fav = list(string.split(" "))
# return Fav
# favlist=(Fav.split(" "))
# print (type(favlist))
# # # Given string
# # print("Given string", Fav)
# # print(type(Fav))
# # # String to list
# # res = Fav.strip('][').split(', ')
# # # Result and its type
# # print("final list", res)
# # print(type(res))
# input1=""
# while input1 != favlist:
# favlist = input("type in any fruit")
# print("you guessed my fav fruit")
#code is broken grrrrr
# Exercise 11: Who Ordered A Pizza ?
# Write a loop that prompts the user to enter a series of pizza toppings until they enter a ‘quit’ value.
# As they enter each topping, print a message saying you’ll add that topping to their pizza.
# Upon exit print all the toppings on the pizza and what the total is (10 + 2.5 for each topping)
# pizza=[]
# pizzaone=[]
# while pizza != "quit":
# pizza=input("topping?")
# pizzaone.append(pizza)
# print( pizza )
# print(len(pizzaone)*2.5+10)
|
4845d16c061a4023c99bec6f1241b3273654de88 | Aditya7861/Self | /Rock-paper-scissors.py | 940 | 3.90625 | 4 | # Remember the rules:
# Rock beats scissors
# Scissors beats paper
# Paper beats rock
user1 = input("Enter Your Name:-")
user2 = input("Enter Your Name:-")
user1_input = input("Enter your choice:-");
user2_input = input("Enter your choice:-");
def game_controler():
if(user1_input == "Rock" and user2_input == "scissors"):
return "{} wins".format(user1)
elif(user1_input == "scissor" and user2_input == "paper"):
return "{} wins".format(user1)
elif (user1_input == "paper" and user2_input == "rock"):
return "{} wins".format(user1)
elif(user1_input == "scissors" and user2_input =="rock"):
return "{} loose".format(user1)
elif (user1_input == "paper" and user2_input == "scissors"):
return "{} loose".format(user1)
elif (user1_input == "rock" and user2_input == "paper"):
return "{} loose".format(user1)
else:
return "Try again"
print(game_controler())
|
0ce0049c12a2494d9c7c0bf42bfe65e65289ee90 | oomsebas/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/model_city.py | 573 | 3.671875 | 4 | #!/usr/bin/python3
""" Write a python file that contains the class definition of a State """
from sqlalchemy import Table, Column, Integer, ForeignKey, String
from model_state import Base, State
from sqlalchemy.orm import relationship
class City(Base):
""" Class for the State table """
__tablename__ = 'cities'
id = Column(Integer, primary_key=True, nullable=False,
autoincrement=True, unique=True)
name = Column(String(128), nullable=False)
state_id = Column(Integer, ForeignKey('states.id'), nullable=False)
|
7a82f4ed011b41860a919e7eddf71cd38b63f7db | Ashish138200/Hackerrank | /Scripts/CheapTravel4.py | 304 | 3.53125 | 4 | # two cases failed
x=input()
l=list(x.split(" "))
n=int(l[0])
m=int(l[1])
a=int(l[2])
b=int(l[3])
k=m/b #price per m ride
cost1=n*k
cost2=n*a
min_cost=int(min(cost1,cost2))
cost=0
for i in range(0,n):
for j in range(0,n):
if(i+j)==n :
cost=a*i + k*j
print(int(min(min_cost,cost))) |
c504c4fbfbde6657dbdbe57f10a1adb447153968 | esglhuguannan/snippet | /PythonNote/timeInPython.py | 427 | 3.703125 | 4 | import datetime
# ӿʼʱÿ50СʱӦʱڼ
def mymain():
datetimeStart=datetime.datetime.strptime('2012 03 04 15:15:33','%Y %m %d %H:%M:%S')
datetimeEnd=datetime.datetime.now()
while datetimeStart<datetimeEnd:
print datetimeStart.strftime('%Y-%m-%d %H:%M:%S'),'\t',datetimeStart.isoweekday()
datetimeStart+=datetime.timedelta(hours=50)
if __name__ == '__main__':
mymain() |
8d3ed5305a4379f5918eabe520ceb60447396d20 | 610yilingliu/leetcode | /Python3/653.two-sum-iv-input-is-a-bst.py | 673 | 3.515625 | 4 | #
# @lc app=leetcode id=653 lang=python3
#
# [653] Two Sum IV - Input is a BST
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findTarget(self, root, k):
if not root:
return False
visited = set()
def finder(root):
if not root:
return False
if k - root.val in visited:
return True
visited.add(root.val)
return finder(root.left) or finder(root.right)
return finder(root)
# @lc code=end
|
defa7a6905a1fe7995148a320fd0ef03226df28f | jorgeruiz11/GenomicaComputacional | /jruiz_p02/AreaTriangulo.py | 387 | 3.890625 | 4 | class AreaTriangulo(object):
def calcula_area(b, h):
area = (b * h)/2
return area
if __name__ == '__main__':
print("\nEscribe la longitud de la base: ")
b = float(input())
print("\nEscribe la longitud de la altura: ")
h = float(input())
area = calcula_area(b, h)
print("\nEl área es: " + str(round(area, 2)))
|
ab45f1df6d291386cdb9bd185fbad9a18b02aff9 | zahera-fatima/task_4 | /zip.py | 96 | 3.734375 | 4 | user = ["user1","user2","user3"]
name = ["zahera","faiza","aamna"]
print(list(zip(user,name))) |
b77188abd44b4b414caf2c79a296cb967fe64936 | Nadunnissanka/Day-14-higher-lower-python | /main.py | 1,842 | 3.734375 | 4 | import random
from replit import clear
from game_data import data
from art import vs, logo
# print(data[0]["name"])
def generate_random_number():
""" Generate Random Number """
count = 0
for celeb in data:
count += 1
random_number = random.randint(0,count-1)
return random_number
def select_celeb():
""" This Function Prevents Randomly Picking Same Celebrity """
person_a = generate_random_number()
person_b = generate_random_number()
if person_a == person_b:
select_celeb()
else:
return [person_a, person_b]
def compare(item_a, item_b):
compare_a = int(data[item_a]['follower_count'])
compare_b = int(data[item_b]['follower_count'])
if compare_a > compare_b:
return 1
elif compare_a < compare_b:
return 0
game_end = False
score = 0
celeb_a = select_celeb()[0]
while not game_end:
celeb_b = select_celeb()[1]
print(logo)
print(f"\n Current Score: {score}")
print(f"Compare A: {data[celeb_a]['name']}, a {data[celeb_a]['description']}, from {data[celeb_a]['country']}")
print(vs)
print(f"Compare B: {data[celeb_b]['name']}, a {data[celeb_b]['description']}, from {data[celeb_b]['country']}")
#print(compare(item_a = celeb_a, item_b = celeb_b))
answer = input("\n\nWho has more followers? Type 'a' and 'b': ").lower()
re_value = int(compare(item_a = celeb_a, item_b = celeb_b))
if answer == "a" and re_value == 1:
print(f"Answer is correct! {data[celeb_a]['name']} has more follower!")
celeb_a = celeb_b
score += 1
clear()
elif answer == "b" and re_value == 0:
print(f"Answer is correct! {data[celeb_b]['name']} has more follower!")
celeb_a = celeb_b
score += 1
clear()
else:
game_end = True
clear()
print(f"Game Over! your score is {score}")
|
fa19269be5495aa5caeaccea93e4660d20a5a360 | chrisdaly/Interactive-Python | /No 3/Stopwatch.py | 2,342 | 3.609375 | 4 | Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> #"Stopwatch: The Game"
import simplegui
# define global variables
timer_counter = 0
success_counter = 0
stop_counter = 0
is_whole_second = 0
timer_is_stopped = 0
# define helper function format that converts integer
def convert(number):
return str(number)
# in tenths of seconds into formatted string A:BC.D
def format(t):
global is_whole_second
A = t//600
B = (t-600*A)//100
C = (t-600*A - B*100)//10
D = (t-600*A)%10
formatted_time = str(A)+":"+str(B)+str(C)+"."+str(D)
if t !=0 and C==0:
is_whole_second = 1
else: is_whole_second = 0
return formatted_time
# define event handlers for buttons; "Start", "Stop", "Reset"
def start_handler():
global is_whole_second
global timer_is_stopped
timer_is_stopped = 0
is_whole_second = 0
timer.start()
return
def stop_handler():
global stop_counter
global success_counter
global timer_is_stopped
timer.stop()
if not timer_is_stopped:
stop_counter +=1
if is_whole_second:
success_counter+=1
print success_counter,stop_counter,format(timer_counter)
timer_is_stopped = 1
return
def reset_handler():
global timer_counter
global stop_counter
global success_counter
global timer_is_stopped
timer.stop()
timer_counter = 0
stop_counter = 0
success_counter = 0
timer_is_stopped = 1
return
# define event handler for timer with 0.1 sec interval
def timerhandler():
global timer_counter
timer_counter +=1
return
def draw_handler(canvas):
canvas.draw_text(format(timer_counter), (120, 150), 30, "Red")
score="Score: "+ convert(success_counter)+"/"+ convert(stop_counter)
canvas.draw_text(score, (8,20), 20, "White")
# create frame
frame = simplegui.create_frame("Stopwatch", 300, 300)
# register event handlers
timer = simplegui.create_timer(10, timerhandler)
frame.set_draw_handler(draw_handler)
start_button = frame.add_button("Start", start_handler, 100)
stop_button = frame.add_button("Stop", stop_handler, 100)
reset_button = frame.add_button("Reset", reset_handler, 100)
# start timer and frame
frame.start()
|
f024c03027dcb7ecb3d1120525b4c06e9b3f5768 | jtlai0921/MP31601 | /CH13/CH1341A.py | 1,102 | 3.625 | 4 | #使用Checkbutton - 多選鈕
from tkinter import *
wnd = Tk()
wnd.title('Checkbutton')
def varStates(): #回應核取方塊變數狀態
print('興趣,有:', var1.get(), var2.get(),
var3.get())
ft1 =('微軟正黑體', 14)
ft2 = ('Levenim MT', 16)
lbl = Label(wnd, text = '興趣:', font = ft1)
lbl.grid(row = 0, column = 0)
item1 = '音樂'
var1 = StringVar()
chk = Checkbutton(wnd, text = item1, font = ft1,
variable = var1, onvalue = item1, offvalue = '')
chk.grid(row = 0, column = 1)
item2 = '閱讀'
var2 = StringVar()
chk2 = Checkbutton(wnd, text = item2, font = ft1,
variable = var2, onvalue = item2, offvalue = '')
chk2.grid(row = 0, column = 2)
item3 = '爬山'
var3 = StringVar()
chk3 = Checkbutton(wnd, text = item3, font = ft1,
variable = var3, onvalue = item3, offvalue = '')
chk3.grid(row = 0, column = 3)
btnQuit = Button(wnd, text = 'Quit', font = ft2, command = wnd.destroy)
btnQuit.grid(row = 2, column = 1, pady = 4)
btnShow = Button(wnd, text = 'Show', font = ft2, command = varStates)
btnShow.grid(row = 2, column = 2, pady = 4)
mainloop()
|
84b4fe5d4e4349a2b542458d55f963111b51d814 | hosmanadam/quote-scraping-game | /ui.py | 1,168 | 3.703125 | 4 | import math
def justify_line(text, width):
# break string into lines not longer than width
words = text.split(' ')
lines = []
current_line = []
for i, word in enumerate(words):
current_line.append(word)
if (word is words[-1]) or (len(' '.join(current_line + [words[i+1]])) > width):
lines.append(current_line)
current_line = []
# pad lines to final width
for i, line in enumerate(lines):
if line is lines[-1]:
lines[i] = ' '.join(line)
else:
spaces_left = width - len(''.join(line))
for j, word in enumerate(line[:-1]):
voids_left = len(line[j:-1])
void_length = int(math.ceil(1.0 * spaces_left / voids_left))
line[j] += ' ' * void_length
spaces_left -= void_length
lines[i] = ''.join(line)
return '\n'.join(lines)
def format_text_block(text, cutoff=1000, width=60):
"""Return at most `cutoff` chars of `text`, justified to given width"""
text = text.replace('\t', '')
if len(text) > cutoff:
text = text[:cutoff] + '[...]'
formatted = []
for line in text.split('\n'):
formatted.append(justify_line(line, width))
return '\n\n'.join(formatted)
|
3047e45d20194b68a9666fbdf52d5fb88cbdea49 | Devrother/algorithm-exercises | /Programmers/연습문제/멀리뛰기/onsuk/solution.py | 734 | 3.640625 | 4 | import time
def solution2(n):
if (n == 1 or n == 2 or n == 3):
return n
a, b = 2, 3
for _ in range(3, n):
a, b = b, (a + b) % 1234567
return b
# 그냥 해본 제네레이터.
# 위 함수에 비해 약 2배 가량 느리다. 함수 호출 때문에 그런듯 하다.
def fib_gen(n):
a, b = 1, 2
for _ in range(n):
yield a
a, b = b % 1234567, a + b
def solution(n):
res = 0
for v in fib_gen(n):
res = v
return res
# 함수별 시간 측정
n = 10000000
start = time.time()
res = solution(n)
print('res of [n = ' + str(n) + '] -> ', res)
print('time :', time.time() - start)
start = time.time()
res2 = solution2(n)
print('res2 of [n = ' + str(n) + '] -> ', res2)
print('time :', time.time() - start) |
94f83e5b7ac74c83df1c12a7c174fb1065fd2c70 | XingyuHe/cracking-the-coding-interview | /Chapter8/He82.py | 694 | 3.6875 | 4 | class Solution(object):
def __init__(self):
self.path = []
def visit(self, maze, x, y):
if x == len(maze) or y == len(maze[0]):
return False
if maze[x][y]:
if x == len(maze) - 1 and y == len(maze[0]) - 1:
self.path.append([x, y])
return True
for i, j in zip([1,0],[0,1]):
new_x = x + i
new_y = y + j
result = self.visit(maze, new_x, new_y)
if result:
self.path.append([x, y])
return True
solution = Solution()
solution.visit([[True, False],[True,False]], 0, 0)
print(solution.path) |
a43c036aa2892f1bd8e2a2f370318fed7f7bb851 | wandershow/Python | /ex015.py | 438 | 3.78125 | 4 | #: Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias
# pelos quais ele foi alugado. Calcule o preço a pagar,
# sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
km = float(input('Quantos kilometros vc percorreu? '))
d = int(input('quantos dias voce ficou com o carro alugado?'))
t = (km * 0.15) + (d * 60)
print('Voce precisa pagar um total de R${:.2f}'.format(t))
|
7b001127adb4330d8ba44037507b80908d792f90 | elenamdo/Numerical_Analysis | /Root_Approximation.py | 5,050 | 3.828125 | 4 | #!/usr/bin/python
import math
#Calculates the roots of quadratic equation ax^2+ bx +y using nth digit approximation
#and formulas 1 and 2
#Computes the absolute error and relative error in approximations
#of answer obained as compared to input exact answer
#Function to make sure input is correct and convert to float or int
def IntegerOrNot (x):
try:
if "." in x:
val = float(x)
else:
val = int(x)
return val
except ValueError:
print("Please enter a valid number.")
#Digit approximation
def round_half_up(n, decimals=0):
n_sig_string = "{0:.4E}".format(n)
multiplier = 10 ** decimals
rounded_sig_fig = math.floor(float(n_sig_string[0:6])*multiplier + 0.5) / multiplier
if "-" in (n_sig_string[len(n_sig_string)-3:len(n_sig_string)]):
decimal = rounded_sig_fig*(math.pow(10,float(n_sig_string [len(n_sig_string)-3:len(n_sig_string)])))
else:
decimal = float(rounded_sig_fig*(math.pow(10,float(n_sig_string [len(n_sig_string)-2:len(n_sig_string)]))))
return decimal
def round_half_down(n, decimals=0):
n_sig_string = "{0:.4E}".format(n)
multiplier = 10 ** decimals
rounded_sig_fig = math.ceil(float(n_sig_string[0:7])*multiplier - 0.5) / multiplier
if "-" in (n_sig_string[len(n_sig_string)-3:len(n_sig_string)]):
decimal = rounded_sig_fig*(math.pow(10,float(n_sig_string [len(n_sig_string)-3:len(n_sig_string)])))
else:
decimal = float(rounded_sig_fig*(math.pow(10,float(n_sig_string [len(n_sig_string)-2:len(n_sig_string)]))))
return decimal
def rounder (m, approximation_digit):
if m < 0:
m = round_half_down(m, approximation_digit);
elif m > 0:
m = round_half_up(m, approximation_digit);
return m;
#ask for a, b and c and digit approximation
coefficient_a = None
while coefficient_a == None:
coefficient_a = input("Enter coefficient a: ");
coefficient_a = IntegerOrNot(coefficient_a);
coefficient_b = None
while coefficient_b == None:
coefficient_b = input("Enter coefficient b: ");
coefficient_b = IntegerOrNot(coefficient_b);
coefficient_c = None
while coefficient_c == None:
coefficient_c = input("Enter coefficient c: ");
coefficient_c = IntegerOrNot(coefficient_c);
while True:
try:
approximation_digit = int(input("Enter the digit to which you would like to approximate: "));
break
except ValueError:
print("Please enter a valid number.")
x_1 = None
while x_1 == None:
x_1 = input("Enter the exact value of x_1: ");
x_1 = IntegerOrNot(x_1);
x_2 = None
while x_2 == None:
x_2 = input("Enter the exact value of x_2: ");
x_2 = IntegerOrNot(x_2);
#Formula 1 step-by-step
rounded_b = rounder(coefficient_b, approximation_digit)
b_squared = math.pow(rounded_b, 2)
rounded_b_squared = rounder(b_squared, approximation_digit)
rounded_a = rounder(coefficient_a, approximation_digit)
rounded_c = rounder(coefficient_c, approximation_digit)
four_a_c = 4*rounded_a*rounded_c
rounded_four_a_c = rounder(four_a_c, approximation_digit)
b_2_minus_4ac = rounded_b_squared - rounded_four_a_c
rounded_b_2_minus_4ac = rounder(b_2_minus_4ac, approximation_digit)
square_root = math.sqrt(rounded_b_2_minus_4ac)
rounded_square_root = rounder(square_root, approximation_digit)
top = -rounded_b + rounded_square_root
rounded_top = rounder(top, approximation_digit)
bottom = 2* rounded_a
rounded_bottom = rounder(bottom, approximation_digit)
whole = rounded_top/rounded_bottom
rounded_whole = rounder(whole, approximation_digit)
x_1_1 = rounded_whole
rounded_b = rounder(coefficient_b, approximation_digit)
b_squared = math.pow(rounded_b, 2)
rounded_b_squared = rounder(b_squared, approximation_digit)
rounded_a = rounder(coefficient_a, approximation_digit)
rounded_c = rounder(coefficient_c, approximation_digit)
four_a_c = 4*rounded_a*rounded_c
rounded_four_a_c = rounder(four_a_c, approximation_digit)
b_2_minus_4ac = rounded_b_squared + rounded_four_a_c
rounded_b_2_minus_4ac = rounder(b_2_minus_4ac, approximation_digit)
square_root = math.sqrt(rounded_b_2_minus_4ac)
rounded_square_root = rounder(square_root, approximation_digit)
top = -rounded_b + rounded_square_root
rounded_top = rounder(top, approximation_digit)
bottom = 2* rounded_a
rounded_bottom = rounder(bottom, approximation_digit)
whole = rounded_top/rounded_bottom
rounded_whole = rounder(whole, approximation_digit)
x_1_2 = rounded_whole
#absolute error calculation
absolute_error= abs(x_1-x_1_1);
print("The absolute error is for x_1 using Formula 1 is: " + str(absolute_error));
#relative error calculation
relative_error = (abs(x_1-x_1_1))/abs(x_1);
print("The relative error is for x_1 using Formula 1 is: " + str(relative_error));
#absolute error calculation
absolute_error= abs(x_2-x_2_1);
print("The absolute error is for x_1 using Formula 1 is: " + str(absolute_error));
#relative error calculation
relative_error = (abs(x_2-x_2_1))/abs(x_2);
print("The relative error is for x_1 using Formula 1 is: " + str(relative_error));
|
b47085a5f6b7c026104b4d68e6c37c570d807eea | codewithpatch/data-science-from-scratch | /patch/regex.py | 442 | 4.1875 | 4 | import re
'''
1. re.match('a', 'cat') --> returns True if 2nd argument
starts with the regular expression, else
returns False
2. re.search(regex, string) --> returns generator of the match
3. re.split(regex, string) --> splits the strings by the regex match
returns a list
4. re.sub(regex, replacement, string) --> returns a text with a substituted
value using the regex
'''
print(re.sub("R(.)D(.)", r'\1-\2', "R2D2")) |
2e1f1f5adc91a141caffbdbf7d4a9a8dfa81b9de | shaunickmistry/intro-to-python | /application_support/workshop_2/range.py | 169 | 3.59375 | 4 | def main():
start = int(input("Start: "))
stop = int(input("Stop: "))
for x in range(start, stop):
print(x)
if __name__ == "__main__":
main()
|
f21a018c58cbc7312b271040577769df31592eab | jianing-sun/Python-Solutions | /Numbers/primefactorize.py | 629 | 4.3125 | 4 | # prime factorization for any integer
# for example: 30 = 2*3*5
# TODO: there would be an error with input ZERO
factors = lambda n: [x for x in range(1, n + 1) if not n % x]
is_prime = lambda n: len(factors(n)) == 2
prime_factors = lambda n: list(filter(is_prime, factors(n)))
def prime_factorize(num):
num = int(num)
f = prime_factors(num)
if is_prime(num):
return str(num)
else:
return str(f[0]) + "*" + str(prime_factorize(num / f[0]))
if __name__ == '__main__':
num = input('input the integer you want to be prime factorized: ')
print(prime_factorize(num))
|
392c15b983e660a4a0e1082b1b16972c2b2084f4 | DSXiangLi/Leetcode_python | /script/[230]二叉搜索树中第K小的元素.py | 1,388 | 3.59375 | 4 | # 给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
#
#
#
# 示例 1:
#
#
# 输入:root = [3,1,4,null,2], k = 1
# 输出:1
#
#
# 示例 2:
#
#
# 输入:root = [5,3,6,2,4,null,null,1], k = 3
# 输出:3
#
#
#
#
#
#
# 提示:
#
#
# 树中的节点数为 n 。
# 1 <= k <= n <= 10⁴
# 0 <= Node.val <= 10⁴
#
#
#
#
# 进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
# Related Topics 树 深度优先搜索 二叉搜索树 二叉树 👍 645 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack= []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k-=1
if k==0:
return root.val
root =root.right
# leetcode submit region end(Prohibit modification and deletion)
|
f2d08774fe52ea0f85aeb37c01a1228c8adae68c | redbeard28/api-redbeard28 | /ModuleIss.py | 734 | 3.578125 | 4 | #!/usr/bin/env python
import json
import requests, turtle
def get(self):
url = "http://api.open-notify.org/iss-now.json"
r = requests.get(url)
iss = r.json()
if iss['message'] != 'success':
message = "ERROR FROM ISS"
print(message)
iss_lat = float(iss['iss_position']['latitude'])
iss_lon = float(iss['iss_position']['longitude'])
# Display information on world map using Python Turtle
screen = turtle.Screen()
screen.setup(720, 360)
screen.setworldcoordinates(-180, -90, 180, 90)
# Load the world map picture
screen.bgpic("world-map.gif")
screen.register_shape("iss.gif")
iss = turtle.Turtle()
iss.shape("iss.gif")
iss.setheading(45)
iss.penup()
iss.goto(iss_lon, iss_lat)
if __name__ == '__main__':
getvigilance() |
b49afb6a6a2fafc548a0e61e854c138c95166d40 | Enahsedrof/QAC-python | /grades.py | 758 | 4.28125 | 4 | def determine_grade(scores):
if scores >= 70 and scores <= 100:
return 'A'
elif scores >= 60 and scores <= 69:
return 'B'
elif scores >= 50 and scores <= 59:
return 'C'
elif scores >= 40 and scores <= 49:
return 'D'
else:
return 'You failed!'
print("Welcome to Grade Calculator")
name = input("What is your name? ")
physics = int(input("Please enter your physics mark: "))
chemistry = int(input("Please enter your chemistry mark: "))
maths = int(input("Please enter your maths mark: "))
percentage = (physics + chemistry + maths)/3
print(name + ", your percentage score is: " + str(percentage) + "%")
grade = determine_grade(percentage)
print(name + ", your percentage score is " + grade) |
c89da0bb9b924755ba5efbd184c5c5fca3a21232 | chongin12/Problem_Solving | /acmicpc.net/5354.py | 176 | 3.9375 | 4 | for _ in range(int(input())):
n=int(input())
for i in range(n):
for j in range(n):
print(f"{'#' if i==0 or i==n-1 or j==0 or j==n-1 else 'J'}",end='')
print()
print() |
de4a2f5c3f69edb97420feaaa3e203712b459912 | caoxudong/code_practice | /hackerrank/012_sherlock_and_squares.py | 1,303 | 3.65625 | 4 | #!/bin/python3
"""
https://www.hackerrank.com/challenges/sherlock-and-squares?h_r=next-challenge&h_v=zen
Watson给了Sherlock两个整数A和_B_,现在Watson问Sherlock他是否可以计算A和_B_之间(包含A和 B)的完全平方数的个数。
完全平方数指的是任何整数的平方。例如,1, 4, 9, 16是完全平方数,因为它们分别是1, 2, 3,4的平方。
输入格式
第一行包含一个整数T, 测试数据的组数。 后面跟T组测试数据,每组占一行。
每组数据是两个整数A和_B_。
输出格式
对每组测试数据,输出一行结果。
约束条件
1 ≤ T ≤ 100
1 ≤ A ≤ B ≤ 1000000000
输入样例
2
3 9
17 24
输出样例
2
0
解释n
第一组测试数据中, 4和9是完全平方数。 第二组测试数据中, 17和24之间(包含17和24),没有完全平方数。
"""
import sys
import math
t = int(input().strip())
for a0 in range(t):
a_and_b = input().strip()
a_and_b_array = a_and_b.split(" ")
a = int(a_and_b_array[0])
b = int(a_and_b_array[1])
sqrt_a = math.sqrt(a)
sqrt_b = math.sqrt(b)
ceil_sqrt_a = math.ceil(sqrt_a)
floor_sqrt_b = math.floor(sqrt_b)
print(floor_sqrt_b - ceil_sqrt_a + 1)
|
135f15c538eeac99a50336fd1d8a1defa89aad6b | DarshanGowda0/LC-Grind | /Daily-Grind/122.py | 933 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# consider the root as lca
# at every recur call, if p <= node <= q, then thats one of ans
# else if node <= p, go right and if node >= q go left
self.low = root
def recur(node, p, q):
if not node:
return
# print(node.val)
self.low = node
# print(node.val , p.val, q.val)
if p.val < node.val and q.val < node.val:
recur(node.left, p, q)
elif p.val > node.val and q.val > node.val:
recur(node.right, p, q)
recur(root, p , q)
return self.low |
73b923136062a91e0330695679fe6bf6d366501d | VMatrixTeam/open-matrix | /src/judgesystem/src/worker/judgers/programmingJudger/checkers/baseChecker.py | 402 | 3.703125 | 4 | from abc import abstractmethod
class Checker(object):
"""
@param
tag is the name of the checkerStage
"""
def __init__(self, t_tag):
self.tag = t_tag
@abstractmethod
def check(t_submission):
"""
@detail
this is an abstract method
"""
print "this is the abstract method"
def getTag(self):
return self.tag
|
858579994ce459d11d6a3a28141214b8b92373d1 | phiratio/learn_python | /hyperskill_projects/hyperskill_coffee_machine/task/machine/coffee_machine.py | 4,583 | 3.515625 | 4 | class CoffeeMachine:
def __init__(self, water_amount, milk_amount, coffee_beans_amount, cups_amount, money):
self.water = water_amount
self.milk = milk_amount
self.coffee = coffee_beans_amount
self.cups = cups_amount
self.money = money
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, key, value):
return setattr(self, key, value)
def __str__(self):
return 'Machine bot v 0.1.7 alpha.'
COFFEE_RECIPES = { # water, milk, coffee, cost
'espresso': {"water": 250, "milk": 0, "coffee": 16, "money": 4, "cups": 1},
'latte': {"water": 350, "milk": 75, "coffee": 20, "money": 7, "cups": 1},
'cappuccino': {"water": 200, "milk": 100, "coffee": 12, "money": 6, "cups": 1},
}
def make_coffee(self, coffee_type):
"""
Makes coffee if possible, subtracts used resources from machine
:param coffee_type:string
"""
if self.check_resources(coffee_type):
for key, value in self.COFFEE_RECIPES[coffee_type].items():
if key == 'money':
self[key] += value
else:
self[key] -= value
# self.print_current_machine_resources()
# self.machine_start_state()
else:
print('Not enough resources to make this coffee type. Sorry')
# self.machine_start_state()
def machine_start_state(self):
self.print_current_machine_resources()
while True:
user_input = input('Write action (buy, fill, take):')
if user_input in ['buy', 'fill', 'take']:
self.execute_machine_command(user_input)
def execute_machine_command(self, command):
if command == 'buy':
self.do_buy_coffee()
elif command == 'fill':
self.do_fill_machine()
elif command == 'take':
self.do_take_money_from_machine()
else:
self.machine_start_state()
def print_current_machine_resources(self):
print('\n')
print('The coffee machine has:')
print(f'{self.water} of water')
print(f'{self.milk} of milk')
print(f'{self.coffee} of coffee beans')
print(f'{self.cups} of disposable cups')
print(f'{self.money} of money')
print('\n')
def check_resources(self, coffee_type):
resources_to_check = ['water', 'milk', 'coffee', 'cups']
for resource in resources_to_check:
if self[resource] <= self.COFFEE_RECIPES[coffee_type][resource]:
return False
return True
def do_buy_coffee(self):
coffee_codes = {
'1': 'espresso',
'2': 'latte',
'3': 'cappuccino'
}
# while True:
user_input = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ')
if user_input in coffee_codes.keys():
self.make_coffee(coffee_codes[user_input])
else:
pass
def do_fill_machine(self):
try:
self.water += int(input('Write how many ml of water do you want to add: '))
self.milk += int(input('Write how many ml of milk do you want to add: '))
self.coffee += int(input('Write how many grams of coffee beans do you want to add: '))
self.cups += int(input('Write how many disposable cups of coffee do you want to add: '))
# self.print_current_machine_resources()
# self.machine_start_state()
except Exception as e:
print('RETARD')
# self.machine_start_state()
def do_take_money_from_machine(self):
print('I gave you ${}'.format(self.money))
self.money = 0
# self.print_current_machine_resources()
# self.machine_start_state()
costa_ricca = CoffeeMachine(400, 540, 120, 9, 550)
# costa_ricca.machine_start_state()
def main():
while True:
action = input('Write action (buy, fill, take, remaining, exit):')
if action == 'buy':
costa_ricca.do_buy_coffee()
elif action == 'fill':
costa_ricca.do_fill_machine()
elif action == 'take':
costa_ricca.do_take_money_from_machine()
elif action == 'remaining':
costa_ricca.print_current_machine_resources()
elif action == 'exit':
break
else:
raise ValueError(f'Unknown command {action}')
if __name__ == '__main__':
main()
|
c0d7928d74b2feae7bea4be7496cc2e2f2455a5c | thomas302/OnlyX | /OnlyX.py | 6,979 | 3.828125 | 4 | import os
class Board:
def __init__(self, boardSideLength):
self.boardSideLength = boardSideLength
self.usedCoordinates = []
self.dead = False
def place(self, column, row):
coordinate = (column, row)
if self.dead:
print("That board is dead")
elif coordinate in self.usedCoordinates:
print("That square already has an X")
else:
self.usedCoordinates.append(coordinate)
print("Nice move!")
def checkIfDead(self):
if (not self.checkForDeadColumn()) and\
(not self.checkForDeadRow()) and\
(not self.checkForDeadDiagonal()):
return False
self.dead = True
return True
def checkForDeadColumn(self):
for column in range(self.boardSideLength):
if self.checkNextRowsForColumn(column):
return True
def checkNextRowsForColumn(self, column):
for row in range(self.boardSideLength):
if not self.hasX(column, row):
return False
return True
def checkForDeadRow(self):
for row in range(self.boardSideLength):
if self.checkNextColumnsForRow(row):
return True
def checkNextColumnsForRow(self, row):
for column in range(self.boardSideLength):
if not self.hasX(column, row):
return False
return True
def checkForDeadDiagonal(self):
isLeftDiagDead = True
isRightDiagDead = True
for number in range(self.boardSideLength):
if not self.hasX(number, number):
isLeftDiagDead = False
if not self.hasX(self.boardSideLength-number-1, number):
isRightDiagDead = False
if (not isLeftDiagDead) and (not isRightDiagDead):
return False
return True
def hasX(self, column, row):
return (column, row) in self.usedCoordinates
class Game:
def __init__(self):
self.playerOneWins = 0
self.playerTwoWins = 0
self.getBoardInfo()
self.turnNumber = 0
self.deadBoardsAmt = 0
self.createBoards()
self.play()
def getBoardInfo(self):
self.boardSideLength = self.getBoardSideLength()
self.totalBoardAmt = self.getTotalBoardAmt()
def getBoardSideLength(self):
try:
boardSideLength = int(input("Choose side length for the board: "))
if boardSideLength < 1:
raise Exception()
return boardSideLength
except Exception:
print("Invalid Board Side Length")
return self.getBoardSideLength()
def getTotalBoardAmt(self):
try:
totalBoardAmt = int(input("Choose number of rounds to play: "))
if totalBoardAmt < 1:
raise Exception()
return totalBoardAmt
except Exception:
print("Invalid Round Number")
return self.getTotalBoardAmt()
def createBoards(self):
self.boards = []
for i in range(self.totalBoardAmt):
self.boards.append(Board(self.boardSideLength))
def play(self):
self.displayBoard()
while self.deadBoardsAmt < self.totalBoardAmt:
self.turnNumber += 1
self.placeSquare(self.getUserSquare())
self.displayBoard()
self.checkForDeadBoard()
def getUserSquare(self):
if self.turnNumber % 2 == 0:
print("Player 2")
else:
print("Player 1")
return {'Column': self.getColumnNum(),
'Row': self.getRowNum()}
def getBoard(self):
try:
boardNum = int(input("Choose Board: "))
if boardNum < 1:
raise Exception()
boardIndex = boardNum - 1
return self.boards[boardIndex]
except Exception:
print("Invalid Board Number")
return self.getBoard()
def getColumnNum(self):
try:
columnNum = int(input("Choose Column: "))
if columnNum > self.boardSideLength or columnNum < 1:
raise Exception("")
return columnNum-1
except Exception:
print("Invalid Column Number")
return self.getColumnNum()
def getRowNum(self):
try:
rowNum = int(input("Choose Row: "))
if rowNum > self.boardSideLength or rowNum < 1:
raise Exception("")
return rowNum-1
except Exception:
print("Invalid Row Number")
return self.getRowNum()
def placeSquare(self, square):
self.boards[self.deadBoardsAmt].place(square["Column"], square["Row"])
def checkForDeadBoard(self):
if self.boards[self.deadBoardsAmt].checkIfDead():
self.deadBoardsAmt += 1
self.turnNumber = 0
self.congratulateRoundWinner()
def congratulateRoundWinner(self):
if self.turnNumber % 2 == 0:
print("Player 1 won that round!")
self.playerOneWins += 1
else:
print("Player 2 won that round!")
self.playerTwoWins += 1
if self.deadBoardsAmt == self.totalBoardAmt:
self.congratulateWinner()
else:
input("Enter anything to continue... ")
def congratulateWinner(self):
if self.playerTwoWins > self.playerOneWins:
print("Player 2 won by " + str(self.playerTwoWins-self.playerOneWins) + " round(s)!")
else:
print("Player 1 won by " + str(self.playerOneWins-self.playerTwoWins) + " round(s)!")
def displayBoard(self):
separator = "+---"
separatorEnd = "+"
side = "|"
board = self.boards[self.deadBoardsAmt]
os.system('cls' if os.name == 'nt' else 'clear')
for row in range(board.boardSideLength):
self.displaySeparator(separator, separatorEnd)
for column in range(board.boardSideLength):
self.displayRow(side, column, row)
print("")
self.displaySeparator(separator, separatorEnd)
def displaySeparator(self, separator, separatorEnd):
board = self.boards[self.deadBoardsAmt]
for column in range(board.boardSideLength):
print(separator, end='')
if column == board.boardSideLength-1:
print(separatorEnd, end='')
print("")
def displayRow(self, side, column, row):
board = self.boards[self.deadBoardsAmt]
print(side, end='')
if board.hasX(column, row):
print(' X ', end='')
else:
print(' ', end='')
if column == board.boardSideLength-1:
print(side, end='')
if __name__ == '__main__':
while True:
Game()
shouldReplay = input("Play Again? Y or N\n")
if shouldReplay == "N":
break
|
e6404f093e5ad3c4d8584e2f068e798a61759e36 | casper01/AdventOfCode2018 | /20/main.py | 3,410 | 3.515625 | 4 | """
Day 20: A Regular Map
"""
import queue
def findEnclosingParenthesisAndSplits(data, start):
i = start
lvl = 0
splits = []
splits.append(start)
while True:
if data[i] == '(':
lvl += 1
elif data[i] == ')':
lvl -= 1
elif data[i] == '|' and lvl == 1:
splits.append(i)
if lvl == 0:
splits.append(i)
return i, splits
i += 1
def addEdge(maze, fromE, toE):
if fromE not in maze:
maze[fromE] = []
if toE not in maze:
maze[toE] = []
maze[fromE].append(toE)
maze[toE].append(fromE)
return maze
def walk(data):
maze = {}
actPos = (0, 0)
active = set()
pending = []
sleeping = []
active.add(actPos)
for i in range(len(data)):
if data[i] == 'N':
newactive = set()
for pos in active:
newpos = pos[0], pos[1] - 1
maze = addEdge(maze, pos, newpos)
newactive.add(newpos)
active = newactive
elif data[i] == 'S':
newactive = set()
for pos in active:
newpos = pos[0], pos[1] + 1
maze = addEdge(maze, pos, newpos)
newactive.add(newpos)
active = newactive
elif data[i] == 'W':
newactive = set()
for pos in active:
newpos = pos[0] - 1, pos[1]
maze = addEdge(maze, pos, newpos)
newactive.add(newpos)
active = newactive
elif data[i] == 'E':
newactive = set()
for pos in active:
newpos = pos[0] + 1, pos[1]
maze = addEdge(maze, pos, newpos)
newactive.add(newpos)
active = newactive
elif data[i] == '(':
pending.append(active)
sleeping.append([])
elif data[i] == '|':
sleeping[-1].extend(active)
active = pending[-1]
elif data[i] == ')':
pending.pop()
active.update(set(sleeping.pop()))
return maze
def findLongestPath(maze):
visited = {}
unvisitedLeft = len(maze.keys())
q = queue.Queue()
q.put((0, 0))
visited[(0, 0)] = 0
maxdist = -1
while not q.empty():
pos = q.get()
d = visited[pos]
if maxdist < d:
maxdist = d
for neighs in maze[pos]:
if neighs in visited:
continue
visited[neighs] = visited[pos] + 1
unvisitedLeft -= 1
q.put(neighs)
return maxdist
def findLongerPath(maze, minDoors):
visited = {}
unvisitedLeft = len(maze.keys())
q = queue.Queue()
q.put((0, 0))
visited[(0, 0)] = 0
counter = 0
while not q.empty():
pos = q.get()
d = visited[pos]
if minDoors <= d:
counter += 1
for neighs in maze[pos]:
if neighs in visited:
continue
visited[neighs] = visited[pos] + 1
unvisitedLeft -= 1
q.put(neighs)
return counter
def main():
with open('input.txt', 'r') as f:
data = f.read()
data = data[1:-1]
maze = {}
maze = walk(data)
print('part1:', findLongestPath(maze))
print('part1:', findLongerPath(maze, 1000))
if __name__ == '__main__':
main()
|
653a3e4851449bc25efcf69a959cbd8535233433 | joez/letspy | /fun/point-24.py | 1,511 | 3.765625 | 4 | #!/usr/bin/env python3
import itertools
import math
def candidates(elements):
if len(elements) < 2:
yield elements[0]
return
skip = set() # to skip logically duplicated ones
for x, y, *rest in itertools.permutations(elements):
for op in '+-*/': # supported operations
pair = frozenset([x, y, op])
if pair in skip:
continue
expr = f'({x} {op} {y})' if rest else f'{x} {op} {y}'
yield from candidates([expr] + rest)
if op in '+*': # commutative property,e.g. x+y=y+x
skip.add(pair)
else:
if x == y: # special cases: x-x=0, x/x=1
skip.add(pair)
def isvalid(expression, target=24):
try: # we evaluate the expression in foat point math
if math.isclose(eval(expression), target):
return True
except ZeroDivisionError:
pass
return False
if __name__ == '__main__':
while True:
try:
cards = input("Input cards (CTRL+C to quit): ").split()
seen = set() # to skip duplicated ones
for e in candidates(cards):
if e not in seen and isvalid(e):
print('.', flush=True, end='') # we are working
seen.add(e)
print("\nSolutions:") if len(seen) else print('No solution')
for e in sorted(seen):
print(e)
except KeyboardInterrupt:
break
|
d468e74ec5588b7a2fbe6f4292e2d688fa9cd988 | kanemaru-git/python | /python1_test4.py | 419 | 3.9375 | 4 | # 借入金額
debt = 250000
# 年利/12(月利)
interest = 1 + 0.14 / 12
# 月々の返済金額
repay = 30000
# 返済期間(月ごと)
month = 0
while debt > 0:
debt = debt * interest
month += 1
if debt > repay:
debt -= repay
print(month,"ヶ月目:返済額=",repay,"円,","残り",debt)
else:
print(month,"ヶ月目:返済額=",debt,"円,","返済完了")
break |
1557c08d8cf95667f7781a1dbecf3f541b4cc3df | Hamza-Rashed/Python-data-structures-and-algorithms | /tests/test_array_shift.py | 521 | 3.765625 | 4 | from data_structures_and_algorithms.challenges.array_shift.array_shift import insertShiftArray
def test_insertShiftArray():
actual = insertShiftArray([1,2,3,5,6],4)
expected = [1,2,3,4,5,6]
assert expected == actual
def test_insertShiftArray2():
actual = insertShiftArray([35,48,50,90,300],150)
expected = [35,48,50,90,150,300]
assert expected == actual
def test_insertShiftArray3():
actual = insertShiftArray([-5,-4,-2,-1],-3)
expected = [-5,-4,-3,-2,-1]
assert expected == actual
|
6c39ddf2b426c81d00b4661f178bae45c0c12b1c | rafaelperazzo/programacao-web | /moodledata/vpl_data/25/usersdata/123/11819/submittedfiles/av1_3.py | 362 | 3.8125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
l= int(input('Insira um número:'))
f= int(input('Insira um número:'))
if (l>f):
maior=l
menor=f
elif (f>l):
maior=f
menor=l
cont=1
while True:
MDC=(maior%menor)
maior=menor
menor=MDC
cont=cont+1
if ((maior%menor)==0):
break
print (MDC)
print (cont) |
5328c4b78888c892e65524b80a9be943a0f1d92c | Eduard-z/stepic | /test_primes.py | 599 | 3.828125 | 4 | import itertools
def primes():
"""Реализуйте функцию-генератор primes, которая будет генерировать простые числа в порядке возрастания,
начиная с числа 2. """
d = 2
while 1:
isSimple = True
for i in range(2, d):
if d % i == 0 and d != 2:
isSimple = False
break
if isSimple:
yield d
d += 1
print(list(itertools.takewhile(lambda x : x <= 31, primes())))
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
|
d224e920d5ea54da62ffb3253758f1f1ea579a40 | nickpineda2008/uip--prog3 | /Laboratorio/sem5/quiz5.py | 636 | 3.75 | 4 | import os
print ("Supermercado ABC")
lista = []
opcion=0
contador = 0
while opcion != "4":
print("1. Agregar un objeto")
print("2. Eliminar un objeto")
print("3. Ver su lista")
print("4. Salir")
opcion = input("Selecione una opcion: ")
if opcion == "1":
objeto=input("Escriba el objeto a agregar: ")
contador = contador + 1
objeto = (str(contador)+"- "+ str (objeto))
lista.append(objeto)
if opcion == "2":
print(lista)
eliminar= int(input("Seleccione el objeto a eliminar: "))
print(lista[eliminar]+" Fue eliminado")
del lista [eliminar]
if opcion == "3":
print(lista)
input () |
c52105a0c52a8bdf9d64f1b963715fd1d4d34d69 | CAAC89/CODIGO-CAILIS | /PYTHON/PRACTICA TUTORIALES/1/Area y perimetro del cuadrado.py | 138 | 3.53125 | 4 | print"AREA Y PERIMETRO DEL CUADRADO"
l=float(raw_input("DIGITE EL LADO: "))
p=l*4
a=l**2
print"EL PERIMETRO ES: ",p
print"EL AREA ES: ",a |
d4c4cac154db64d80e83dc32fcc472033197c255 | dcbird92/CS4150 | /Assignment_2/Ceiling_Function.py | 2,992 | 3.796875 | 4 | import string
import sys
class Tree:
class Node(object):
def __init__(self, value, index):
self.left = None
self.right = None
self.value = value
self.index = index
def getValue(self):
return self.value
def getLeft(self):
return self.left
def getRight(self):
return self.right
def getIndex(self):
return self.index
def setValue(self, val):
self.value = val
def setLeft(self, xleft):
self.left = xleft
def setRight(self, xright):
self.right = xright
def setIndex(self, indx):
self.index = indx
def __init__(self):
self.root = None
#self.index_list = ''
def add(self, value):
self.root = Tree.addNode(self, self.root, value, 0)
def addNode(self, root, value, index):
if root is None:
#self.index_list += str(index)
return Tree.Node(value, index)
if value <= root.getValue():
index = (index * 2) + 1
root.setLeft(Tree.addNode(self, root.getLeft(), value, index))
else:
index = (index * 2) + 2
root.setRight(Tree.addNode(self, root.getRight(), value,index))
return root
def printOut(self):
Tree.printingOut(self.root)
def printingOut(root):
print("Root Value: ",root.getValue(), "with index: ", root.getIndex())
if root.getLeft() is not None:
print("Left child: ",root.getLeft().getValue())
Tree.printingOut(root.getLeft())
else: print("No left child")
if root.getRight() is not None:
print("Right child: ", root.getRight().getValue())
Tree.printingOut(root.getRight())
else: print("No Right child")
def indexOut(self):
if self.root is not None:
index_string = Tree.makeIndex(self.root)
return index_string
def makeIndex(root):
indexstr = str(root.getIndex())
if root.getLeft() is not None:
indexstr += Tree.makeIndex(root.getLeft())
if root.getRight() is not None:
indexstr += Tree.makeIndex(root.getRight())
return indexstr
if __name__ == '__main__':
x = 0
index_list = {}
numbers = input()
count, size = numbers.split(" ")
count = int(count)
size = int(size)
inputs = 0
_size = 0
for in_line in sys.stdin:
lst = in_line.split()
tree = Tree()
for n in lst:
tree.add(int(n))
_size += 1
if _size == size:
break
#tree.printOut()
index_string = tree.indexOut()
#print( index_string)
#print(hash(index_string))
index_list[index_string] = 0;
# print(indexstring)
inputs += 1
if inputs == count:
break
print(len(index_list)) |
e0bf25aaac8062e44fc3d4077fd9f10b797cf823 | jadetang/leetcode-in-python3 | /1482.py | 1,475 | 3.53125 | 4 | import sys
import unittest
from collections import defaultdict
from typing import List
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
totalFlowers = len(bloomDay)
def canMake(days, m, k):
flowers = [0] * totalFlowers
for (i, day) in days:
for d in day:
flowers[d] = 1
i = 0
while i < len(flowers):
if flowers[i] == 1:
j = i
while j < len(flowers) and flowers[j] == 1:
j += 1
length = j - i
if length == k:
m -= 1
break
i = j
else:
i += 1
return m <= 0
daysFlower = defaultdict(list)
for i, day in enumerate(bloomDay):
daysFlower[day].append(i)
daysFlowerList = list(daysFlower.items())
daysFlowerList.sort()
if not canMake(daysFlowerList, m, k):
return -1
left = 0
right = len(daysFlowerList)
while left < right:
mid = left + (right - left) // 2
if canMake(daysFlowerList[:mid + 1], m, k):
right = mid
else:
left = mid + 1
return daysFlowerList[left][0]
class MyTestCase(unittest.TestCase):
def test_something(self):
# print(minDays(self, [1, 10, 3, 10, 2], 3, 1))
print(minDays(self, [7,7,7,7,12,7,7], 2, 3))
if __name__ == '__main__':
unittest.main()
|
402d9c848d6d0a6abfae084d76944b9faad4785a | vinayakentc/BridgeLabz | /ObjectOrientedPrograms/StockReport.py | 1,376 | 3.9375 | 4 | class Stocks:
def __init__(self, name, price, number):
self.name = name
self.price = price
self.number = number
class Portfolio:
"""This class contains methods for creating a portfolio for stock account
"""
def __init__(self):
self.value = 0
self.portfolio = []
def enter_stock(self, name, price, number):
"""This method adds new account in the portfolio
Parameters:
name: name of the individual
price: price of the stocks
number: no. of shares purchased
"""
new_stock = Stocks(name, price, number)
self.portfolio.append(new_stock)
def portfolio_details(self):
"""This method calculates the total value of the stocks
"""
for obj in self.portfolio:
print(f"{obj.name}:\n\tPrice per share: {obj.price}\n\t"
f"Number of Shares: {obj.number}\n\tValue: {obj.price*obj.number}\n.")
def portfolio_total(self):
"""This method iterates through the portfolio and calculates the total stock value"""
for obj in self.portfolio:
self.value += obj.number * obj.price
port = Portfolio()
port.enter_stock("Infosys", 50000, 550)
port.enter_stock("TCS", 65000, 350)
port.portfolio_details()
port.portfolio_total()
print("Total portfolio value = ", port.value)
|
378b1655c48c369233c13c4ef174e10e724826b7 | Derek-lai-/matplotlib-attempt- | /KeywordSearchAlg.py | 629 | 3.515625 | 4 | import os
def rec_search(path):
for f in os.listdir(path):
if f.endswith(".py"):
r = open(path + "/"+f).read()
if keyword in r.lower():
print path + "/" + f
lines = r.split("\n")
lineNum = [str(i + 1) for i in range(len(lines)) if keyword in lines[i]]
print "\tLines: " + ", ".join(lineNum)+ "\n"
elif (os.path.isdir(path + "/" + f)):
rec_search(path + "/" + f)
keyword = "HAHA"
while keyword != "":
print
keyword = raw_input("Enter the keyword to search for: ").lower()
rec_search("matplotlib") |
bcbf4a59d2e550ee855b4b822acd14e4b79ae96e | rahulk207/betweenness_centrality | /SBC_2018254.py | 6,904 | 3.78125 | 4 | #!/usr/bin/env python3
import re
import itertools
ROLLNUM_REGEX = "201[0-9]{4}"
class Graph(object):
name = "Rahul Kukreja"
email = "rahul18254@iiitd.ac.in"
roll_num = "2018254"
def __init__ (self, vertices, edges):
"""
Initializes object for the class Graph
Args:
vertices: List of integers specifying vertices in graph
edges: List of 2-tuples specifying edges in graph
"""
self.vertices = vertices
ordered_edges = list(map(lambda x: (min(x), max(x)), edges))
self.edges = ordered_edges
self.validate()
def validate(self):
"""
Validates if Graph if valid or not
Raises:
Exception if:
- Name is empty or not a string
- Email is empty or not a string
- Roll Number is not in correct format
- vertices contains duplicates
- edges contain duplicates
- any endpoint of an edge is not in vertices
"""
if (not isinstance(self.name, str)) or self.name == "":
raise Exception("Name can't be empty")
if (not isinstance(self.email, str)) or self.email == "":
raise Exception("Email can't be empty")
if (not isinstance(self.roll_num, str)) or (not re.match(ROLLNUM_REGEX, self.roll_num)):
raise Exception("Invalid roll number, roll number must be a string of form 201XXXX. Provided roll number: {}".format(self.roll_num))
if not all([isinstance(node, int) for node in self.vertices]):
raise Exception("All vertices should be integers")
elif len(self.vertices) != len(set(self.vertices)):
duplicate_vertices = set([node for node in self.vertices if self.vertices.count(node) > 1])
raise Exception("Vertices contain duplicates.\nVertices: {}\nDuplicate vertices: {}".format(vertices, duplicate_vertices))
edge_vertices = list(set(itertools.chain(*self.edges)))
if not all([node in self.vertices for node in edge_vertices]):
raise Exception("All endpoints of edges must belong in vertices")
if len(self.edges) != len(set(self.edges)):
duplicate_edges = set([edge for edge in self.edges if self.edges.count(edge) > 1])
raise Exception("Edges contain duplicates.\nEdges: {}\nDuplicate vertices: {}".format(edges, duplicate_edges))
def min_dist(self, start_node, end_node):
"""
Finds minimum distance between start_node and end_node
Args:
start_node: Vertex to find distance from
end_node: Vertex to find distance to
Returns:
An integer denoting minimum distance between start_node
and end_node
"""
c=0
q=[start_node]
l=[]
for i in range(len(self.vertices)):
if self.vertices[i]!=start_node:
l.append([])
l[i].append(self.vertices[i])
l[i].append(None)
else:
l.append([])
l[i].append(self.vertices[i])
l[i].append(0)
source=start_node
while len(q)!=0:
for k in range(len(l)):
if l[k][0]==source:
temp=k
for i in range(len(self.edges)):
if source==self.edges[i][0]:
for j in range(len(l)):
if l[j][0]==self.edges[i][1] and l[j][1]==None:
l[j][1]=l[temp][1]+1
q.append(self.edges[i][1])
elif source==self.edges[i][1]:
for j in range(len(l)):
if l[j][0]==self.edges[i][0] and l[j][1]==None:
l[j][1]=l[temp][1]+1
q.append(self.edges[i][0])
q.pop(0)
if len(q)!=0:
source=q[0]
for i in range(len(l)):
if l[i][0]==end_node:
dist=l[i][1]
return dist
raise NotImplementedError
def all_paths(self, start_node, end_node, dist, path, path_final):
"""
Finds all paths from node to destination with length = dist
Args:
node: Node to find path from
destination: Node to reach
dist: Allowed distance of path
path: path already traversed
Returns:
List of path, where each path is list ending on destination
Returns None if there no paths
"""
path=path+[start_node]
if len(path)==dist+1:
if start_node==end_node:
return path
else:
return None
for i in range(len(self.edges)):
if start_node==self.edges[i][0] and self.edges[i][1] not in path:
path_final.append(self.all_paths(self.edges[i][1],end_node,dist,path,path_final))
elif start_node==self.edges[i][1] and self.edges[i][0] not in path:
path_final.append(self.all_paths(self.edges[i][0],end_node,dist,path,path_final))
return path_final
raise NotImplementedError
def all_shortest_paths(self, start_node, end_node, dist, path, path_final, shortest_paths):
"""
Finds all shortest paths between start_node and end_node
Args:
start_node: Starting node for paths
end_node: Destination node for paths
Returns:
A list of path, where each path is a list of integers.
"""
self.all_paths(start_node,end_node,dist,path,path_final)
for i in range(len(path_final)):
if path_final[i]!=None and isinstance(path_final[i][0],int):
shortest_paths.append(path_final[i])
return shortest_paths
raise NotImplementedError
def betweenness_centrality(self, node):
"""
Find betweenness centrality of the given node
Args:
node: Node to find betweenness centrality of.
Returns:
Single floating point number, denoting betweenness centrality
of the given node
"""
betweenness_centrality=0
for i in range(len(self.vertices)):
if self.vertices[i]!=node:
for j in range(i+1,len(self.vertices)):
if self.vertices[j]!=node:
dist=self.min_dist(self.vertices[i],self.vertices[j])
if dist!=None:
y=0
shortest_paths=[]
self.all_shortest_paths(self.vertices[i], self.vertices[j], dist, [], [], shortest_paths)
x=len(shortest_paths)
for k in range(len(shortest_paths)):
if node in shortest_paths[k]:
y=y+1
betweenness_centrality=betweenness_centrality+(y/x)
return betweenness_centrality
raise NotImplementedError
def standardized_betweenness_centrality(self,node):
'''Calculates the standardized betweenness centrality of any given node'''
n=len(self.vertices)
standardized_betweenness_centrality=(self.betweenness_centrality(node))/(((n-1)*(n-2))/2)
return standardized_betweenness_centrality
def top_k_betweenness_centrality(self):
"""
Find top k nodes based on highest equal betweenness centrality.
Returns:
List a integer, denoting top k nodes based on betweenness
centrality.
"""
top_k=[]
l=[]
c=0
for i in range(len(self.vertices)):
l.append([])
l[i].append(self.vertices[i])
l[i].append(self.standardized_betweenness_centrality(self.vertices[i]))
l.sort(key = lambda x: x[1], reverse=True)
k=l[0][1]
for i in range(len(l)):
if l[i][1]==k:
c=c+1
top_k=l[:c]
return top_k
raise NotImplementedError
if __name__ == "__main__":
vertices = [1, 2, 3, 4, 5, 6]
edges = [(1, 2), (1, 5), (2, 3), (2, 5), (3, 4), (4, 5), (4, 6), (3, 6)]
#vertices = [0, 1, 2, 3, 4, 5, 6, 7]
#edges=[(3,6),(3,2),(2,5),(2,4),(5,6),(5,1),(1,0),(4,1)]
graph = Graph(vertices, edges)
print(graph.top_k_betweenness_centrality())
|
4a9899878805cda610df3dbf57009a67cfc6919d | Fondamenti18/fondamenti-di-programmazione | /students/1743829/homework01/program01.py | 1,231 | 3.984375 | 4 | '''
Si definiscono divisori propri di un numero tutti i suoi divisori tranne l'uno
e il numero stesso.
Scrivere una funzione modi(ls,k) che, presa una lista ls di interi ed un intero
non negativo k:
1) cancella dalla lista ls gli interi che non hanno esattamente k divisori
propri
2) restituisce una seconda lista che contiene i soli numeri primi di ls.
NOTA: un numero maggiore di 1 e' primo se ha 0 divisori propri.
ad esempio per ls = [121,4,37,441,7,16]
modi(ls,3) restituisce la lista con i numeri primi [37,7] mentre al termine
della funzione si avra' che la lista ls=[441,16]
Per altri esempi vedere il file grade.txt
ATTENZIONE: NON USATE LETTERE ACCENTATE.
ATTENZIONE: Se il grader non termina entro 30 secondi il punteggio
dell'esercizio e' zero.
'''
def modi(ls,k):
"inserite qui il vostro codice"
l=[]
l1=[]
for i in ls:
if divisori(i,k)==0:
l+=[i]
if divisori(i,k)==k:
l1+=[i]
del ls[:]
ls+=l1
return l
def divisori (n,k):
cont=0
for x in range(2,int(n**0.5)):
if n%x==0:
cont+=2
if cont==k+2:
break
if n%int(n**0.5)==0:
cont+=1
return cont
|
f06c2c5c6c3c846abdfb43fad03468e87aa1926b | Rivarrl/leetcode_python | /leetcode/LCP173+/5377.py | 1,265 | 3.5 | 4 | # -*- coding: utf-8 -*-
# ======================================
# @File : 5377.py
# @Time : 2020/4/5 10:36
# @Author : Rivarrl
# ======================================
from algorithm_utils import *
class Solution:
"""
[5377. 将二进制表示减到 1 的步骤数](https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/)
"""
@timeit
def numSteps(self, s: str) -> int:
n = i = 0
for c in s[::-1]:
if c == '1':
n += (1 << i)
i += 1
res = 0
while n > 1:
if n & 1:
n += 1
else:
n //= 2
res += 1
return res
@timeit
def numSteps2(self, s: str) -> int:
i = len(s) - 1
s = [e for e in s]
res = 0
while i > 0:
if s[i] == '0':
res += 1
i -= 1
else:
res += 1
while i >= 0 and s[i] == '1':
res += 1
i -= 1
if i > 0: s[i] = '1'
return res
if __name__ == '__main__':
a = Solution()
a.numSteps(s = "1101")
a.numSteps(s = "10")
a.numSteps(s = "1") |
ea9c7ed19fe631eb96d96721eaf9f6a6f3a78109 | jude89654/cs-elec2a-python-exercises | /george.py | 503 | 3.765625 | 4 | number_of_rooms = int(input("PLEASE INPUT NO OF ROOMS: "))
rooms_available = 0
for x in range(1,number_of_rooms+1):
room_input = input("PLEASE INPUT THE NUMBER OF WHO ALREADY LIVE AND THE CAPACITY FOR ROOM NO. %i: " % x)
number_of_people_who_already_lived_in_the_room = int(room_input.split()[0])
room_capacity = int(room_input.split()[1])
if(room_capacity-number_of_people_who_already_lived_in_the_room)>=2:
rooms_available += 1
print("ROOMS AVAILABLE: %i" % rooms_available) |
e753509c73d1c376db02aa3fef4567f23e2b4ef3 | kunzhang1110/COMP9021-Principles-of-Programming | /Exams/Prac_1/Lab_11.py | 1,754 | 3.75 | 4 | from priority_queue import *
class MinPriorityQueue(PriorityQueue):
def __init__(self):
super().__init__(function = lambda x, y: x <y)
class MaxPriorityQueue(PriorityQueue):
def __init__(self):
super().__init__()
class Median():
def __init__(self):
self.max_pq = MaxPriorityQueue()
self.min_pq = MinPriorityQueue()
def median(self):
if self.max_pq._length == self.min_pq._length:
return (self.max_pq._data[1] + self.min_pq._data[1])/2
elif self.max_pq._length > self.min_pq._length:
return self.max_pq._data[1]
else:
return self.min_pq._data[1]
def insert(self, value):
if self.max_pq._length == 0:
self.min_pq.insert(value)
self.rebalance()
elif self.min_pq._length == 0:
self.max_pq.insert(value)
self.rebalance()
elif value< self.max_pq._data[1]:
self.max_pq.insert(value)
self.rebalance()
elif value> self.max_pq._data[1] :
self.min_pq.insert(value)
self.rebalance()
elif self.max_pq._length > self.min_pq._length:
self.min_pq.insert(value)
else:
self.max_pq.insert(value)
print(self.max_pq._data, self.min_pq._data)
def rebalance(self):
if self.max_pq._length > self.min_pq._length + 1:
self.min_pq.insert(self.max_pq.delete())
elif self.min_pq._length > self.max_pq._length + 1:
self.max_pq.insert(self.min_pq.delete())
if __name__ == '__main__':
L = [2, 1, 7, 5, 4, 8, 0, 6, 3, 9]
values = Median()
for e in L:
values.insert(e)
print(values.median(), end = ' ')
print() |
93c6cde648d38fd1483d1858159f6c23c1fc1522 | pavanpandya/Python | /Python Basic/49_Return.py | 369 | 3.875 | 4 | # Functions always returns, if return is absent in function definition then it will return none.
# Return automatically exits the function
def sum(num1, num2):
return num1 + num2
print(sum(4, 5))
# Nested Function
def sum2(num1, num2):
def another_func(n1, n2):
return n1 + n2
return another_func(num1, num2)
total = sum2(10, 5)
print(total)
|
88882adc2d5f9012330b7837aec45cf5a2b33aa7 | asarra/University-n-school-projects-experiences | /FHB-Py/Mathe/matrix.py | 1,656 | 3.75 | 4 | import numpy
a = [[-4,2,1],[2,-1,0],[1,-3,2]]
# a = [[3,0],[6,-1]]
b = [[3,0],[0,-1]]
def add(a,b):
a = numpy.matrix(a)
b = numpy.matrix(b)
c = a+b
def multiply(a,b):
a = numpy.matrix(a)
b = numpy.matrix(b)
d = a*b
print(d)
def freestyle(a,b):
a = numpy.matrix(a)
b = numpy.matrix(b)
# c = a + (3 * b)
# c = b + 3 * a
print(c)
def inverseMatrix(a):
y = numpy.linalg.inv(a)
print(f"Inverse:\t{y}")
def determinanteUNDBasisUNDrangUndinvertierbarkeitscheck(a): # von oben nach unten geht aber auch von links nach rechts
det = numpy.linalg.det(a)
print(f"Determinante der Matrix:\t{det}")
# Wenn die Determinante einer Matrix ungleich 0 ist, ist es immer eine Basis des Vektorraumes R^3.
# Die Vektoren in randomvektor sind linear unabhängig und somit eine Basis des ℝ3
# Compute the determinant of your matrix and use the fact that a matrix is invertible iff its determinant is nonzero.
# + nicht quadratische Matrizen sind automatisch nicht invertierbar, da man deren Determinante nicht berechnen kann
if det != 0:
print("Es ist eine Basis des Vektorraumes R^3! (Linear unabhängige Vektoren)\nEs ist außerdem invertierbar")
else:
print("Keine Basis!(Linear abhängige Vektoren)\nEs ist außerdem NICHT invertierbar")
print(f"Rang:\t{numpy.linalg.matrix_rank(a)}")
determinanteUNDBasisUNDrangUndinvertierbarkeitscheck(a)
# matrix bei der aufgabe von links nach rechts übernehmen für die unteren (Numpy ist iwie komisch und macht die vektoren von links nach rechts in matrix)
#inverseMatrix(a)
# freestyle(a,b)
# multiply(a,b)
|
04c0df596ff21f878f024661a49d7c98fff0c968 | mitchainslieg/listdir | /listdir.py | 3,762 | 4 | 4 | from argparse import RawTextHelpFormatter
import argparse
import os.path
import glob
def get_file_name(dir_path_glob):
"""Getting the file name from path
Arguments:
dir_path_glob -- Contains the path of the file
Returns:
File name from the path
"""
split_path = dir_path_glob.split("\\")
return '"' + split_path[len(split_path) - 1] + '"'
def get_dir_path(dir_path_glob):
"""From glob's path, it replaces all double back slash to one forward slash
Arguments:
dir_path_glob -- Contains the path of the file
Returns:
Returns the whole path of the file with double quote marks
"""
replace_symb = dir_path_glob.replace("\\", "/")
split_path = replace_symb.split("/")
split_path.pop()
return '"' + os.path.realpath("/".join(split_path)) + '"'
def get_file_size(dir_path_glob):
"""A function to get the file size
Arguments:
dir_path_glob -- Contains the path of the file
Returns
Returns the file size of the file using the getsize method from os.path
"""
file_realpath = os.path.realpath(dir_path_glob)
return os.path.getsize(file_realpath)
def export_csv(dir_path, csv_name):
"""Generates a CSV file containing path, name and size of files within the directory
Arguments:
dir_path -- Contains the path of the directory or folder
csv_name -- Contains the name the user want for his or her CSV file
Returns:
Returns e to print an exception, and if it executes successfully, returns True as default value for the function
"""
files = []
if dir_path[len(dir_path) - 1] != '/':
dir_path += '/'
for root, directories, file_names in os.walk(os.path.realpath(dir_path)):
files.extend(glob.glob(root + "/*.*", recursive=True))
try:
with open(csv_name, "w") as new_file:
file_list = []
for file_info in files:
file_list.append(f"{get_dir_path(file_info)},{get_file_name(file_info)},{get_file_size(file_info)}")
new_file.write("\n".join(file_list))
except Exception as e:
return e
return True
def check_valid_path(path):
"""Checks the path if it is a valid directory
Arguments:
path -- Contains the path of the directory or folder
Returns:
Returns as True if the path is a directory or the path exist else if the path is the path directs to a file, it returns false
"""
real_path = os.path.realpath(path)
if os.path.isfile(real_path):
return False
return True if os.path.isdir(real_path) or os.path.exists(real_path) else False
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Exports all file information in a CSV file of all files in a directory/folder.\n"
"Remove any succeeding back slash '\\' if it prints out any errors")
parser.add_argument("directory", type=str, help="Full path of a folder")
parser.add_argument("file_name", type=str, help="CSV file name\nexample: file_name.csv")
user_inp = parser.parse_args()
if check_valid_path(user_inp.directory):
destination_file = user_inp.file_name.split('.')
if len(destination_file) > 1:
if destination_file[len(destination_file) - 1] == 'csv':
export_csv(user_inp.directory, ".".join(destination_file))
print("Command Executed!")
else:
print("Invalid File name!")
else:
print("Command Executed!")
export_csv(user_inp.directory, destination_file[0] + '.csv')
else:
print("Invalid path!") |
64867605d515237ca144bb5a079f372d21aac717 | yglj/learngit | /PythonPractice/廖雪峰Python/2.6元类.py | 1,898 | 4.4375 | 4 | #动态语言和静态语言最大的不同,就是函数和类的定义,
#不是编译时定义的,而是运行时动态创建的
class H:
pass
h = H()
print(type(H)) #H是个class 类型是type
print(type(h)) #h是个实例 类型是class H(object)
#当Python解释器载入hello模块时,就会依次执行该模块的所有语句
#执行结果就是动态创建出一个Hello的class对象
#动态创建类
'''
一 type():
class的定义是运行时动态创建的,而创建class的方法就是使用type()函数
type()函数既可以返回一个对象的类型,又可以创建出新的类型
三个参数:
1.class的名称;
2.继承的父类集合,注意Python支持多重继承,
如果只有一个父类,别忘了tuple的单元素写法;
3。class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上
'''
def Hello(self): #定义函数
print("this is a function,name = Hello")
H2 = type("Hey",(object,),dict(fn=Hello)) #创建类
h2 = H2()
print(H2,h2)
h2.fn()
'''
二 metaclass(元类):
除了使用type()动态创建类以外,要控制类的创建行为,还可以使用metaclass
先定义metaclass,就可以创建类,最后创建实例。
所以,metaclass允许你创建类或者修改类。
可以把类看成是metaclass创建出来的“实例”
'''
#例:给自定义list类加个add方法
class ListMetaClass(type): #metaclass是类的模板,所以必须从“type”类型派生
def __new__(cls,name,bases,attr):
attr["add"] = lambda self,values:self.append(values)
return type.__new__(cls,name,bases,attr)
class MyList(list,metaclass=ListMetaClass):
pass
mylist = MyList()
mylist.add(2)
print(mylist)
'''
__new__()方法接收到的参数依次是:
当前准备创建的类的对象;
类的名字;
类继承的父类集合;
类的方法集合
'''
|
7c7c3e368b265e2b5497f242136bf960b334c17c | FlorCorrado/fundamentosInformatica | /trabajoPractico4/tp4ej7.py | 660 | 4.125 | 4 | valorIngresado = int(input("Ingrese un valor, para salir ingrese -1: "))
mayorNumero = 0
menorNumero = valorIngresado
while valorIngresado != -1:
if valorIngresado > mayorNumero:
mayorNumero = valorIngresado
valorIngresado = int(input("Ingrese un valor, para salir ingrese -1: "))
elif valorIngresado < menorNumero:
menorNumero = valorIngresado
valorIngresado = int(input("Ingrese un valor, para salir ingrese -1: "))
else:
valorIngresado = int(input("Ingrese un valor, para salir ingrese -1: "))
print("El mayor numero ingresado fue: ", mayorNumero)
print("El menor numero ingresado fue: ", menorNumero)
|
999b63ab4479a1ac2cfdadff07f883b928b77b9d | ShiyuCheng2018/ISTA350_Programming_for_Informatics_App | /lab/lab_9/lab9.py | 1,190 | 3.84375 | 4 | import requests
def get_page(url):
"""
This function takes a string that represents a url.
Your task is to send a request from the url given as a parameter.
From this request, return a string containing the content of the request.
"""
def how_bold(c):
"""
This function takes a string containing the content of a webpage.
Using the provided string, return a count of how many times
the string '<b>' (the bold tag) appears in the page.
"""
def get_title(c):
"""
This function takes a string containing the content of a webpage.
Using the provided string, return the title of the page.
The title is enclosed between the '<title>' and '</title>' tags.
"""
def upgrade_python(c):
"""
This function takes a string containing the content of a webpage.
Return a new copy of the content string, but with
all instances of "Python" replaced with "Anaconda".
Maintain the same capitalization in the replacement words as with the originals.
"""
def main():
get_page('http://www.pythonchallenge.com/')
if __name__ == '__main__':
main()
|
4b62f47388575d39199100fc39a9447c56db6a26 | yzheng21/Leetcode | /leetcode/data structure/priority queue vs heap/topk frequent words.py | 1,061 | 4.09375 | 4 | '''
Given a list of words and an integer k, return the top k frequent words in the list.
Notice
You should order the words by the frequency of them in the return list,
the most frequent one comes first. If two words has the same frequency,
the one with lower alphabetical order come first.
Example
Given
[
"yes", "lint", "code",
"yes", "code", "baby",
"you", "baby", "chrome",
"safari", "lint", "code",
"body", "lint", "code"
]
for k = 3, return ["code", "lint", "baby"].
for k = 4, return ["code", "lint", "baby", "yes"],
'''
from collections import defaultdict
from heapq import heappop, heappush
class solution:
def topkfrequentwords(self,words,k):
result = []
words_count = defaultdict(int)
for word in words:
words_count[word] += 1
max_heap = []
for word in words_count:
count = words_count[word]
heappush(max_heap,(-count,word))
for i in range(k):
count,word = heappop(max_heap)
result.append(word)
return result
|
a6b052bcaeb515bf5971600a2eb0eed84b8a38e6 | Sunghwan-DS/TIL | /Python/BOJ/BOJ_2233(2).py | 797 | 3.609375 | 4 | class Node:
def __init__(self, parent = None):
self.parent = parent
self.child = []
class Tree:
def __init__(self):
self.root = Node('root')
self.current = self.root
self.num_of_apple = 0
self.val = 0
def append(self):
self.current.child.append(Node(self.current))
self.current = self.current.child[-1]
self.num_of_apple += 1
self.val += 1
N = int(input())
data = input()
i, j = map(int,input().split())
apple_i = 0
apple_j = 0
tree = Tree()
for idx in range(len(data)):
if data[idx] == '0':
tree.append()
if tree.num_of_apple == i:
apple_i = tree.current
if tree.num_of_apple == j:
apple_j = tree.current
if tree.current =
else:
|
be140cb312ddf15b4fae08d7a7f1cae6da80555f | chesteraustin/CSIS-42 | /Week 02/circle.py | 695 | 4.59375 | 5 | # circle.py
# Chester Austin
# 02/06/2019
# Python 3.7.2
# Description: Program to calculate circumfrance and area of a circle
# Value of PI as constant
PI = 3.1415
# Ask user for radius of Circle
radius = float(input ("Please enter the radius of circle (in inches) ")) # radius
# Calculate area
circle_area = (PI) * (radius **2)
# Calculate circumfrance
circle_circumfrance = 2 * PI * radius
print("A circle with radius %.1f inches has" %radius)
print("circumfrance: %.1f inches" %circle_circumfrance)
print("area: %.1f square inches" %circle_area)
'''
Please enter the radius of circle (in inches) 12
A circle with radius 12.0 inches has
circumfrance: 75.4 inches
area: 452.4 square inches
''' |
6e428452c07b582667f9ea76240eea5090de3821 | jeremy886/crossword2019 | /main.py | 241 | 3.5 | 4 | import tex_printable
"""
Step 1:
- Create a new word list in words.txt
- Run crosswords.py to generate crosswords_out.txt
Step 2:
- Run this program to call text_printable.py to generate crossword_puzzle.text
"""
tex_printable.print_tex() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.