blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
f21040812b1241328df75d665a7a1ecdf0b14834 | sananand007/LeetCodeProblems | /MajorityElement.py | 374 | 3.90625 | 4 | def MajorityElement(nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums==None: return None
nums.sort()
count=0
n = len(nums)
candidate = nums[n//2]
for num in nums:
if num==candidate:
count+=1
if count>=(n+1)//2:
return candidate
return -1
nums = [1,1,1,100]
print(MajorityElement(nums))
|
71c104628ae9f8830348e45736e33e8066156509 | shubham-beri/Point-Of-Sales-Software | /Customer1.py | 501 | 3.578125 | 4 | class Customer:
def __init__(self,cid,name,phoneNo,address,order):
self.cid = cid
self.name = name
self.phoneNo = phoneNo
self.address = address
self.order = order
def showCustomer(self):
return ("Customer ID: {}\nName: {}\nContact No: {}\nAddress: {}".format(self.cid, self.name, self.phoneNo, self.address.showAddress()))
def showOrder(self):
print("You ordered:\n")
return (self.order.show_Order())
3 |
43b6bcd65e382592e4e0b07d2e1a739b864594f6 | ahsan-rahim/Jumping-frog- | /FrogJump.py | 3,427 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:25:09 2020
@author: Ahsan Rahim
"""
#Graph to be AutoGenerated
graph={}
def validStates(node):
valid=[];
s=list(node);
for i in range(len(s)):
s=list(node);
if(i+1<len(s) and s[i]<='B' and s[i+1]=='-'):
s[i] , s[i+1] = s[i+1], s[i];
valid.append("".join(s))
elif (i+2<len(s) and s[i]<='B' and s[i+2]=='-'):
s[i] , s[i+2] = s[i+2], s[i];
valid.append("".join(s))
elif (i-1>=0 and s[i]>='Y' and s[i-1]=='-'):
s[i] , s[i-1] = s[i-1], s[i];
valid.append("".join(s))
elif (i-2>=0 and s[i]>='Y' and s[i-2]=='-'):
s[i] , s[i-2] = s[i-2], s[i];
valid.append("".join(s))
return valid
def addVertex( vertexName):
graph[vertexName]=[]
def addEdge( v1 , v2):
if v1 not in graph:
addVertex(v1);
if v2 not in graph:
addVertex(v2);
graph[v1].append(v2);
def GenerateGraph(node):
valid = validStates(node);
if valid!= []:
for v in valid:
addEdge(node, v);
GenerateGraph(v);
# Driver Code to generate Graph
GenerateGraph("AB-YZ");
print("Auto Generated Graph \n ")
print(graph);
print('\n')
visited = [] # Array to keep track of visited nodes.
found=False
def dfs(node , goal ):
global found
if node not in visited:
print(node)
visited.append(node)
if(node==goal):
found=True;
else:
for neighbour in graph[node]:
if(found!= True):
dfs( neighbour , goal)
print("DFS Traversal to goal \n ");
dfs("AB-YZ" , "YZ-AB")
print('\n')
visited = [] # Array to keep track of visited nodes.
#Shortest Path Using DFS
found = False
def dfs(node , goal , shortest ):
global found
if(node==goal):
shortest.extend([goal])
found=True
return shortest
if node not in visited:
visited.append(node)
shortest.extend([node])
for neighbour in graph[node]:
temp= dfs( neighbour , goal, [])
if(found== True):
shortest.extend(temp)
return shortest
print("Shortest Path Using DFS \n")
print(*dfs('AB-YZ' , 'YZ-AB' , [] ) , sep ='\n')
print('\n')
queue = [] #Initialize a queue
def bfs( node , goal):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s)
if( s== goal):
break;
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("BFS Traversal to goal \n")
bfs('AB-YZ' , 'YZ-AB')
#Hard Coded Graph, written but not used!
graph1= {
'AB-YZ': ['A-BYZ', '-BAYZ'],
'A-BYZ': ['-ABYZ' , 'AYB-Z'],
'-BAYZ' : [],
'-ABYZ' : [],
'AYB-Z' :['AY-BZ', 'AYBZ-'],
'AYBZ-' : ['AY-ZB'],
'AY-ZB' : ['AYZ-B' , '-YAZB'],
'AYZ-B' : [],
'-YAZB' : ['Y-AZB'],
'Y-AZB' : ['YZA-B'],
'YZA-B' : ['YZ-AB'],
'AY-BZ' : ['-YABZ' , 'AYZB-'],
'-YABZ' : ['Y-ABZ'],
'Y-ABZ' : [],
'AYZB-' : ['AYZ-B'],
'YZ-AB' : []
}
|
2961ec0fe3ae39a62d0822418b91674fcbc301db | lucasmbrute2/Blue_mod1 | /Aula13/Exercicio04_func.py | 623 | 4.03125 | 4 | # Faça um programa que calcule o salário de um colaborador na empresa XYZ.
# O salário é pago conforme a quantidade de horas trabalhadas.
# Quando um funcionário trabalha mais de 40 horas ele recebe um adicional de 1.5 nas horas extras trabalhadas.
def salario(n1,n2):
salario = n1 *n2
if n2 >= 40:
extra = ((n2 - 40) * salario_hora) * 1.50
salario += extra
return salario
salario_hora = float(input("Digite o seu salário por hora aqui: "))
horas = int(input("Digite quantas horas você trabalhou na semana: "))
print(f"O seu salário semanal é: {salario(salario_hora,horas)}")
|
698d2b093fd758c8b9f55e70a930ea09e6821717 | IamOmaR22/HackerRank-Problems-Solve-and-Programs-Practice-with-Python | /30 Days of Code/Day 25 - Running Time and Complexity.py | 878 | 4.125 | 4 | # Solution - 1
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(n):
if n <= 1:
return False
sqrt_n = math.sqrt(n)
if sqrt_n.is_integer():
return False
for i in range(2, int(sqrt_n)+1):
if n%i == 0:
return False
return True
num_test_cases = int(input())
for i in range(num_test_cases):
n = int(input())
if isPrime(n):
print('Prime')
else:
print('Not prime')
# Solution - 2
# Enter your code here. Read input from STDIN. Print output to STDOUT
from math import sqrt
T = int(input())
def isPrime(n):
for i in range(2, int(sqrt(n) + 1)):
if n % i is 0:
return False
return True
for _ in range(T):
n = int(input())
if n >= 2 and isPrime(n):
print("Prime")
else:
print("Not prime")
|
aecfed69bdeb9cfb937f3927fdf9232b18df33dd | qa-trainee/qa-trainee-learning-python | /python-practice/ATBS_S1_L7.py | 829 | 4.03125 | 4 | # ATBS_S1_L7.py is a proram that wrote to test my understanding of
# Automate the boring stuff Section 1, Lecture 7
# for loop
# for i in range(5)
# range (5) stops at 4
# you can give multiple arguement to range like range(5, 10)
# this will continue from 5 till 9
import datetime
print('This program prints a sum of all integers from ie 1+2+3 ...+number')
print('enter an integer number')
number = int(input())
start = str(datetime.datetime.now().time())
print('Code started at ' + start)
sum = 0
for i in range(1, number+1):
sum = sum + i
print('Total is ' + str(sum))
end = str(datetime.datetime.now().time())
print('Code ended at ' + end)
FMT = '%H:%M:%S.%f'
tdelta = datetime.datetime.strptime(end, FMT) - \
datetime.datetime.strptime(start, FMT)
print('Code took this much time to execute: ' + str(tdelta))
|
560f133094635d60fca4517fc8a68bc5a1ea3287 | mxl1994/Program_Python | /算法联系/插入排序.py | 309 | 3.609375 | 4 | A = [16,4,6,3,77,22,10,6]
def insert_sort(A):
for i in range(1, len(A)):
key = A[i]
j = i - 1
while j >= 0 and key < A[j]:
A[j + 1] = A[j]
j -= 1
A[j + 1] = key
return A
if __name__ == "__main__":
result = insert_sort(A)
print result
|
cacc60727d813b745399312d09ead10d4a63625d | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/luhn/25aae77f9280459cac2b3e7d34ad599d.py | 1,057 | 3.515625 | 4 | class Luhn(object):
def __init__(self, number):
self.number = number
def addends(self, offset=1):
number_string = str(self.number)
number_list = [int(digit) for digit in number_string]
reversed_list = number_list[::-1]
# Double every second number
reversed_list[offset::2] = [2 * x for x in reversed_list[offset::2]]
# Subtract 9 from numbers >= 10
parsed_reversed_list = []
for x in reversed_list:
if x >= 10:
parsed_reversed_list.append(x - 9)
else:
parsed_reversed_list.append(x)
# Return reverse of parsed list
return parsed_reversed_list[::-1]
def checksum(self):
return sum(self.addends()) % 10
def is_valid(self):
return (self.checksum() == 0)
def create(self):
number_string = str(self.number)
for i in range(10):
new_number = int(number_string + str(i))
if Luhn(new_number).is_valid():
return new_number
|
d8828809e4d7ee616b28b386c53efc1238248ba9 | jmetzz/ml-laboratory | /basic_ml/src/neural_networks/base/costs.py | 1,752 | 3.5625 | 4 | import numpy as np
from numpy import log, nan_to_num
class CrossEntropyCost:
@staticmethod
def evaluate(activation, true_label):
"""Return the cost associated with an output activation and desired output
``y``.
The cross-entropy is positive number.
Note that np.nan_to_num is used to ensure numerical
stability. In particular, if both ``a`` and ``y`` have a 1.0
in the same slot, then the expression (1-y)*np.log(1-a)
returns nan. The np.nan_to_num ensures that that is converted
to the correct value (0.0).
"""
return np.sum(nan_to_num(-true_label * log(activation) - (1 - true_label) * log(1 - activation)))
@staticmethod
def delta(z, activation, true_label):
"""Computes the error delta from the output layer.
Note that the parameter ``z`` is not used by the method.
It is included in the method's parameters in order to make the interface
consistent with the delta method for other cost classes.
"""
return activation - true_label
class QuadraticCost:
@staticmethod
def evaluate(activation, true_label):
"""Return the cost associated with an output activation and desired true label (``y``)."""
return 0.5 * np.linalg.norm(activation - true_label) ** 2
@staticmethod
def delta(z, activation, true_label):
"""Computes the error delta from the output layer."""
return (activation - true_label) * QuadraticCost.sigmoid_prime(z)
@staticmethod
def derivative(output_activations, y):
r"""Return the vector of partial derivatives
\partial C_x / \partial a for the output activations."""
return output_activations - y
|
d3e25805b601aff974c730abd85b4368724d09d4 | grimmi/learnpython | /reversebytes.py | 810 | 4.125 | 4 | '''
A stream of data is received and needs to be reversed.
Each segment is 8 bits meaning the order of these segments need to be reversed:
11111111 00000000 00001111 10101010
(byte1) (byte2) (byte3) (byte4)
10101010 00001111 00000000 11111111
(byte4) (byte3) (byte2) (byte1)
Total number of bits will always be a multiple of 8.
The data is given in an array as such:
[1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]
taken from: https://www.codewars.com/kata/569d488d61b812a0f7000015/train/python
'''
def data_reverse(data):
def chunk(ns, size):
for x in range(0, len(ns), size):
yield ns[x:x + size]
chunks = reversed(list(chunk(data, 8)))
return sum(chunks, [])
print(data_reverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]))
|
8767900d987e0fed3a5e6eff1afe2b6a80e12ab0 | mbgaspar/Cursos | /Descubra o Python/Cap. 04/leituraArquivo_start.py | 335 | 3.859375 | 4 | #
# Lendo arquivos com funções do Python
#
def leituraArquivo():
arquivo = open ("Novo Arquivo.txt", "r")
if (arquivo.mode == "r"):
conteudo = arquivo.read() #caso tenha um arquivo grande todo o arquivo irá para essa variavel, pode não ser boa ideia.
print (conteudo)
arquivo.close()
leituraArquivo() |
afbf05366c33bc9d395e7def0f88e1753ee69187 | takushi-m/atcoder-work | /work/abc121_d.py | 201 | 3.515625 | 4 | # -*- coding: utf-8 -*-
a,b = map(int, input().split())
def g(x):
if x%2==1:
return ((x+1)//2)%2
else:
return ((x//2)%2)^x
def f(a,b):
return g(b) ^ g(a-1)
print(f(a,b))
|
c6734f9980b6902a5230a0c61cbb2a0d99f520b7 | BohaoLiGithub/Leetcode | /Search a 2D Matrix/Search a 2D Matrix(Accepted).py | 535 | 3.53125 | 4 | class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
m = len(matrix)
if m > 0:
n = len(matrix[0])
if n > 0 :
for i in range(m):
if matrix[i][0] <= target <= matrix[i][n-1]:
for j in range(n):
if matrix[i][j] == target:
return True
return False |
f2c2668a934e8c7ee8f3737e4489d6bc5ef5d489 | swjtuer326/shiny-enigma | /基本数据处理.py | 658 | 3.625 | 4 | def getNum():
nums = []
iNumStr = input('请输入数字(回车退出):')
while iNumStr != '':
nums.append(eval(iNumStr))
iNumStr = input('请输入数字(回车退出):')
return nums
def mean(numbers):
s = 0.0
for i in numbers:
s += i
return s/len(numbers)
def dev(numbers, mean):
sdev = 0.0
for i in numbers:
sdev += (i-mean)**2
return pow(sdev/len(numbers), 0.5)
def median(numbers):
sorted(numbers)
size = len(numbers)
if size%2 ==0:
med = (numbers[size//2-1]+numbers[size//2])/2
else:
med = numbers[size//2]
return med
n = getNum()
m = mean(n)
print('平均值:{},方差:{:.2f},中位数:{}'.format(m, dev(n,m),median(n)))
|
39ef37e43c5fca55ea2daf9022e19ab74be75945 | happyjun190/machine-learning-py | /function.py | 134 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def area_of_circle(r):
return math.pi * r * r
print(area_of_circle(5)) |
5ab1cf1e2e1ab4618a0f5db70a49d1dc851574a6 | AshkenSC/Programming-Practice | /LeetCode/0136. Single Number.py | 515 | 3.53125 | 4 | # 0136. Single Number
'''
遍历数组,用字典存储元素出现过的次数。
'''
from typing import List
class Solution:
def singleNumber(self, nums: List[int]) -> int:
occurs = dict()
for num in nums:
if num not in occurs.keys():
occurs[num] = 1
else:
occurs[num] += 1
for num in occurs:
if occurs[num] == 1:
return num
# test
sol = Solution()
ans = sol.singleNumber([4,1,2,1,2])
print(ans) |
33136278a794ebfecc9ca852a525aea70e365014 | viktor-taraba/Dataquest | /Python Programming: Intermediate/Introduction to Functions-4.py | 2,092 | 3.953125 | 4 | ## 1. Overview ##
f = open("movie_metadata.csv", 'r')
file = f.read()
rows = file.split('\n')
movie_data = []
for row in rows:
split = row.split(',')
movie_data.append(split)
print(movie_data[0:2])
print(rows[0:2])
## 3. Writing Our Own Functions ##
def movie(movie_data):
alist = []
for item in movie_data:
alist.append(item[0])
return alist
movie_names = movie(movie_data)
print(movie_names[0:5])
## 4. Functions with Multiple Return Paths ##
wonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]
def is_usa(data):
for item in data:
if item == 'USA':
return True
wonder_woman_usa = is_usa(wonder_woman)
## 5. Functions with Multiple Arguments ##
wonder_woman = ['Wonder Woman','Patty Jenkins','Color',141,'Gal Gadot','English','USA',2017]
def index_equals_str(list, index, string):
if list[index] == string:
return True
else:
return False
wonder_woman_in_color = index_equals_str(string = 'Color', list = wonder_woman, index = 2)
print(wonder_woman_in_color)
## 6. Optional Arguments ##
def feature_counter(input_lst, index, input_str, header_row):
counter=0
if header_row==True:
input_lst=input_lst[1:len(input_lst)]
for element in input_lst:
if element[index]==input_str:
counter+=1
return counter
print(feature_counter(movie_data, 6, 'USA', True))
## 7. Calling a Function inside another Function ##
def feature_counter(input_lst,index, input_str):
num = 0
for each in input_lst:
if each[index-1] == input_str:
num = num + 1
return num
def summary_statistics(movie_data):
movie_data = movie_data[1:len(movie_data)]
num_japan_films=feature_counter(movie_data, 7, 'Japan')
num_color_films=feature_counter(movie_data, 3, 'Color')
num_films_in_english=feature_counter(movie_data, 6, 'English')
dictionary={'japan_films':num_japan_films, 'color_films':num_color_films, 'films_in_english':num_films_in_english}
return dictionary
summary = summary_statistics(movie_data) |
374b34df61c51aa98285edb3f57ab8a0c8a8cb91 | zkz917/program-practice | /Remove Duplicates from Sorted Array.py | 606 | 3.5 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
p1, p2 = 0,1
# use two pointers to solve the problem
while p2 < len(nums):
if p2 < len(nums) and nums[p1] != nums[p2]:
# move the pointer one step further
p1 +=1
# swap the numbers
nums[p1],nums[p2] = nums[p2],nums[p1]
p2 +=1
else:
p2+=1
return p1+1
|
6c914d0f3842230fe60198185e699f7060811ccd | vlcgreen/DigitalCrafts | /Python/Homework/W1D2/Day2HW_ExtraChallenge.py | 663 | 3.84375 | 4 | #Day 2 Homework Extra Challenge
# PROBLEM 1 - TRIANGLE NUMBERS
## Print the first 100 triangle numbers. formula
# num = 0
# for numbers in range(1,100):
# num += numbers
# print (num)
#I worked it this way first but it wasn't as pretty:
for stuff in range(1,100):
f = stuff * (stuff + 1) / 2
print(int(f))
#PROBLEM 2 - FACTOR A NUMBER
factor = input("What number would you like to factor?>> ")
while type(factor) != int:
print('Please enter whole numbers only')
factor = input("What number would you like to factor?>> ")
if type(factor) == int:
break
break
#I'm stuck from here, will look at how to factor it later |
d8c7df818b20a08de6a1fc50435d841db5f33c4e | AshFrankland/Conway-s-Game-of-Life | /life.py | 5,469 | 3.578125 | 4 | import pygame
WIDTH = 800
FPS = 10
WIN = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("Conway's Game of Life")
GREY = (128, 128, 128)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
class Cell:
def __init__(self, row, col, width, total_rows):
self.row = row
self.col = col
self.x = row * width
self.y = col * width
self.colour = WHITE
self.neighbors = []
self.living_neighbors = 0
self.width = width
self.total_rows = total_rows
def get_pos(self):
return self.row, self.col
def is_alive(self):
return self.colour == BLACK
def is_born(self):
return self.colour == GREEN
def is_dying(self):
return self.colour == RED
def is_dead(self):
return self.colour == WHITE
def make_dead(self):
self.colour = WHITE
def make_alive(self):
self.colour = BLACK
def make_born(self):
self.colour = GREEN
def make_dying(self):
self.colour = RED
def draw(self, win):
pygame.draw.rect(win, self.colour, (self.x, self.y, self.width, self.width))
def update_cell(self, grid):
self.neighbors = []
self.living_neighbors = 0
if self.row < self.total_rows - 1:
self.neighbors.append(grid[self.row + 1][self.col]) #DOWN
if self.col < self.total_rows - 1:
self.neighbors.append(grid[self.row + 1][self.col + 1]) #DOWN RIGHT
if self.col > 0:
self.neighbors.append(grid[self.row + 1][self.col - 1]) #DOWN LEFT
if self.row > 0:
self.neighbors.append(grid[self.row - 1][self.col]) #UP
if self.col < self.total_rows - 1:
self.neighbors.append(grid[self.row - 1][self.col + 1]) #UP RIGHT
if self.col > 0:
self.neighbors.append(grid[self.row - 1][self.col - 1]) #UP LEFT
if self.col < self.total_rows - 1:
self.neighbors.append(grid[self.row][self.col + 1]) #RIGHT
if self.col > 0:
self.neighbors.append(grid[self.row][self.col - 1]) #LEFT
for cell in self.neighbors:
if cell.is_alive() or cell.is_dying():
self.living_neighbors += 1
if self.is_dead() and self.living_neighbors == 3:
self.make_born()
if self.is_alive() and (self.living_neighbors < 2 or self.living_neighbors > 3):
self.make_dying()
def next_tick(self):
if self.is_dying():
self.make_dead()
if self.is_born():
self.make_alive()
def make_grid(rows, width):
grid = []
gap = width // rows
for i in range(rows):
grid.append([])
for j in range(rows):
cell = Cell(i, j, gap, rows)
grid[i].append(cell)
return grid
def draw_grid(win, rows, width):
gap = width // rows
for i in range(rows):
pygame.draw.line(win, GREY, (0, i * gap), (width, i * gap))
for j in range(rows):
pygame.draw.line(win, GREY, (j * gap, 0), (j * gap, width))
def draw(win, grid, rows, width):
win.fill(WHITE)
for row in grid:
for cell in row:
cell.draw(win)
draw_grid(win, rows, width)
pygame.display.update()
def get_clicked_pos(pos, rows, width):
gap = width // rows
y, x = pos
row = y // gap
col = x // gap
return row, col
def main(win, width):
ROWS = 50
clock = pygame.time.Clock()
grid = make_grid(ROWS, width)
run = True
started = False
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if pygame.mouse.get_pressed()[0]: #LEFT
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, ROWS, width)
cell = grid[row][col]
cell.make_alive()
elif pygame.mouse.get_pressed()[2]: #RIGHT
pos = pygame.mouse.get_pos()
row, col = get_clicked_pos(pos, ROWS, width)
cell = grid[row][col]
cell.make_dead()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not started:
started = True
while started:
clock.tick(FPS)
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
started = False
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
started = False
for row in grid:
for cell in row:
cell.update_cell(grid)
#draw(win, grid, ROWS, width) # uncommenting this line will draw the dying and born steps for each cell
for row in grid:
for cell in row:
cell.next_tick()
pygame.quit()
main(WIN, WIDTH) |
13d6125e2dfdcf63be5ad2bd9e4703af1b325399 | amj18/test-driven-development | /Checkout.py | 1,779 | 3.546875 | 4 | from typing import Dict
class Checkout:
class Discount:
def __init__(self, nbrItems, price):
self.nbrItems = nbrItems
self.price = price
def __init__(self):
self.prices = {}
self.discounts = {}
self.items = {}
def addDiscount(self, item: str, numberOfItems: int, price: float) -> None:
discount = self.Discount(numberOfItems, price)
self.discounts[item] = discount
def addItemPrice(self, item: str, price: int) -> None:
self.prices[item] = price
def addItem(self, item: str) -> None:
if item not in self.prices:
raise Exception("Item has no price")
if item in self.items:
self.items[item] +=1
else:
self.items[item] = 1
def calculateTotal(self) -> int:
total = 0
for item, cnt in self.items.items():
total += self.canCalculateItemTotal(item, cnt)
return total
def canCalculateItemTotal(self, item: str, cnt: int) -> int:
total = 0
if item in self.discounts:
discount = self.discounts[item]
if cnt >= discount.nbrItems:
total += self.canCalculateItemDiscountedTotal(item, cnt, discount)
else:
total += self.prices[item] * cnt
else:
total += self.prices[item] * cnt
return total
def canCalculateItemDiscountedTotal(self, item: str, cnt: int, discount: Dict) -> int:
total = 0
numberOfDiscounts = cnt / discount.nbrItems
total += numberOfDiscounts * discount.price
remaining = cnt % discount.nbrItems
total += remaining * self.prices[item]
return total |
5672d4a5b80291362a9e31d7aa5647d762b438d3 | FelipeMirandaM/Albion_bot | /Conexion/conection_lite.py | 2,424 | 3.59375 | 4 | import sqlite3
class conection:
def __init__(self):
self.con = None
def open_con(self):
self.con = sqlite3.connect("member_list.db")
def close_con(self):
self.con.close()
def load_data(self, members):
self.delete_data()
self.open_con()
query = "INSERT INTO members(name, total_fame, pve_fame, pvp_fame, crafting_fame, ID, gather_fame,guild) VALUES (?,?,?,?,?,?,?,?)"
cur = self.con.cursor()
cur.executemany(query, members)
self.con.commit()
cur.close()
self.close_con()
def delete_data(self):
self.open_con()
cur = self.con.cursor()
cur.execute('DELETE FROM members;')
self.con.commit()
cur.close()
self.close_con()
def search_name(self, name):
self.open_con()
name = (name,)
cur = self.con.cursor()
member = None
try:
cur.execute('select * FROM members WHERE name = ?',name)
member = cur.fetchone()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
self.con.commit()
cur.close()
self.close_con()
return member
def get_member_list(self):
self.open_con()
cur = self.con.cursor()
cur.execute('select * FROM members')
members = cur.fetchall()
cur.close()
self.close_con()
return members
def get_white_list(self):
self.open_con()
cur = self.con.cursor()
white_list = None
try:
cur.execute('select * FROM white_list')
white_list = cur.fetchall()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
cur.close()
self.close_con()
return white_list
def is_white_list(self, discord_id):
self.open_con()
cur = self.con.cursor()
white_list = None
try:
cur.execute('select * FROM white_list where discord_id = ?',(discord_id,))
white_list = cur.fetchone()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
cur.close()
self.close_con()
return white_list
|
c39aecac652ba3860500c5ff37d7fa3f05d8e3bd | psideleau/shu-book-rental-owners | /book_rental_class.py | 1,833 | 3.859375 | 4 | class BookRental:
# Creating Book Rental class
def __init__(self, isbn, book_title, author, rental_id, owner_id, rental_value, start_date, end_date,):
self.isbn = isbn
self.book_title = book_title
self.author = author
self.rental_id = rental_id
self.owner_id = owner_id # Owner will be passed in value from the login group. Hard coding for now
self.rental_value = rental_value
self.start_date = start_date
self.end_date = end_date
# Function to pass in values from the ISBN search and set variables needed for posting book rental
def get_rental_info(self):
self.isbn = input("ISBN: ") # pass ISBN from search and set in this variable
self.author = input("author: ") # pass Author from search and set in this variable
self.book_title = input("Title: ") # pass title from search and set in this variable
self.owner_id = "owner id: " # no variable to be passed yet. This would come from login group
self.rental_id = input("Enter rental ID: ") # Owner assigns rental value to book
self.rental_value = input("Enter a rental value: ") # Owner sets the start and end period for book rental
self.start_date = input(" Enter your rental period start date: ")
self.end_date = input(" Enter your rental period end date: ")
# Creating an instance of the class 'BookRental' and setting the variables. This will essentially create a
# Python dict.
rental_info = BookRental(self.isbn, self.author, self.book_title, self.rental_id, self.owner_id,
self.rental_value, self.start_date, self.end_date)
# Returning value to be used for posting the book to the group of student renters
return rental_info
|
d6fc0b18c210d5c6883c48fbe7c716805edd58df | thecodesanctuary/python-study-group | /assessment/assessment_1/DimejII/assignment5.py | 186 | 4.09375 | 4 | #this prog asks for your weight in kg
kilo_grams = float(input('Enter weight in Kg to Convert into pounds:'))
pounds = kilo_grams * 2.2
print(kilo_grams,' Kilograms =', pounds,' Pounds') |
bfb87251e8500338aa182edcdf96940323f10770 | DevinTyler26/learningPython | /mvaIntroToPython/if-else.py | 315 | 4.125 | 4 | g = 9
h = 8
if g < h:
print('g < h')
else:
if g == h:
print('g == h')
else:
print('g > h')
name = 'Devin'
height = 2
weight = 110
bmi = weight / (height ** 2)
print('bmi: ')
print(bmi)
if bmi < 25:
print(name)
print('is not overweight')
else:
print(name)
print('is overweight') |
666d881694b2d704cee38dabd05cc9c651b43136 | kelvin-jose/computer_vision_opencv | /erosion.py | 430 | 3.578125 | 4 | import cv2
import numpy as np
image = cv2.imread('image.jpg', 0)
"""
a kernel slides over the binary image like convolution and
changes the current pixel value to 0 if all the pixels under
the kernel are not 1s i.e erode the pixels. So the pixels of
the edges of white region might change from 1 to 0.
"""
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(image, kernel, iterations=1)
cv2.imwrite('erosion.jpg', erosion)
|
fdbe94b9f0a67e74945563e17d56aa0e05236365 | Pysche666/coffee_machine_coding | /coffee_machine/core/beverage.py | 1,527 | 3.515625 | 4 | from coffee_machine.core.ingredient import Ingredient
class Beverage:
"""
A class for Beverage.
It has the information about ingredients, time required to prepare a beverage and dispense it.
"""
_preparation_time: int
def __init__(self, name, ingredients, preparation_time=10, dispensing_time=3):
self._name = name
for beverage_ingredient in ingredients:
if type(beverage_ingredient) is not Ingredient:
raise TypeError(
"Expected beverage ingredient type to be Ingredient but got {0}".format(
type(beverage_ingredient)))
# set the beverage ingredients
self._ingredients = ingredients
# preparation time is in ms(milliseconds)
self._preparation_time = preparation_time
self._dispensing_time = dispensing_time
@property
def __repr__(self):
ingredients_repr = ''
for idx, beverage_ingredient in enumerate(self._ingredients):
ingredients_repr += idx + '.' + beverage_ingredient + '\n'
return "Name of the beverage is: {n}\nIngredients are:\n" + ingredients_repr
@property
def name(self):
return self._name
@name.setter
def name(self, s):
self._name = s
@property
def ingredients(self):
return self._ingredients
@property
def preparation_time(self):
return self._preparation_time
@property
def dispensing_time(self):
return self._dispensing_time
|
97b88634e78f4ac8c0bfd3919da75ed9976c82dc | websvey1/TIL | /algorithm/home/every's_algorithm/하노이탑.py | 250 | 3.9375 | 4 | def hanoi(n, S, E, M):
if n == 1:
print(S, "->", E)
return
hanoi(n-1, S, M, E)
# print(S, "->", E)
hanoi(n-1, M, E, S)
# print("n=1")
hanoi(1, 1, 3, 2)
# print("n=2")
hanoi(2,1,3,2)
# print("n=3")
hanoi(3,1,3,2)
|
7dade6f6a5a3ec14cb6d745dad2b797ccf91c4c0 | pradeepkumar1017/guvitask | /hangman.py | 386 | 3.78125 | 4 |
import random
strs = ['A','B','C','D','E','F']
count = 0
string = random.choice(strs)
for i in range(5):
c = input('Enter a character: ')
if c in string and c!='':
print('Good')
counts = count + 1
if count == 3:
break
else:
print('You entered a wrong character')
if count == 3:
print('Won')
else:
print('Lost')
|
53852d5166b4763891674d06b05ffe12376f67d3 | dicao425/algorithmExercise | /LeetCode/countingBits.py | 402 | 3.546875 | 4 | #!/usr/bin/python
import sys
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
result = [0]*(num+1)
for i in range(num+1):
result[i] = result[i>>1] + i&1
return result
def main():
aa = Solution()
print aa.countBits()
return 0
if __name__ == "__main__":
sys.exit(main())
|
43048d3b0847066a2e0ed27b1a65722ba5213c0f | psbarros/Variaveis3 | /2019-1/230/users/4023/codes/1877_1653.py | 196 | 3.515625 | 4 | from numpy import *
##############Entrada#################:
vet = input("Digite as iniciais do pais: ")
v1 = vet.split(',')
###############For####################:
for i in range(:
cont = cont |
f4f1b9f384bf64b302ce03d0be3a255a237f8498 | Satar07/whatpython | /code/pass7.py | 186 | 3.8125 | 4 | a = 0
while a < 100:
a += 1
if a % 7 == 0:
continue
elif (a + 3) % 10 == 0:
continue
elif (a + 30) % 100 <10:
continue
else:
print (a) |
e7f9b17221058f912c7eec6a21af0f325a79cd45 | tusvhar01/practice-set | /Practice set 38.py | 362 | 4.1875 | 4 | def fibonacci(n):
if n < 1:
return None
if n < 3:
return 1
elem1 = elem2 = 1
sum = 0 ## Fabonacci no.(it is addition of last two no.)
for i in range(3,n+1):
sum = elem1 + elem2
elem1, elem2 = elem2, sum
return sum
for n in range(1,51):
print(f"fibonacci of {n} is",fibonacci(n)) |
3add99ca8bf8ed1aad0cf30d66f190f5eaeb3f76 | Yuvv/LeetCode | /2001-2100/2042-check-if-numbers-are-ascending-in-a-sentence.py | 802 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : 2042-check-if-numbers-are-ascending-in-a-sentence.py
# @Author : Yuvv ([email protected])
# @Date : 2021-10-25
class Solution:
def areNumbersAscending(self, s: str) -> bool:
v = -1
for e in map(int, filter(lambda s : s and s.isdigit(), s.split(' '))):
if e <= v:
return False
v = e
return True
if __name__ == '__main__':
s = Solution()
# true
print(s.areNumbersAscending('1 box has 3 blue 4 red 6 green and 12 yellow marbles'))
# false
print(s.areNumbersAscending('hello world 5 x 5'))
# false
print(s.areNumbersAscending('sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s'))
# true
print(s.areNumbersAscending('4 5 11 26'))
|
8bf2136907255571402b7e11afc440f4c98f0282 | DianaBonilla/deber_Harry | /harry_potter.py | 1,421 | 3.703125 | 4 | ##ESCUELA POLITECNICA NACIONAL
##ESCUELA DE FORMACION DE TECNOLOGOS
##PROGRAMACION AVANZADA
##AUTOR:DIANA BONILLA-VALERIA OCHOA
##TITULO: OCURRENCIAS DE UNA PALABRA
print("\t\t\t Escuela Politécnica Nacional")
print("\t\t\t Escuela de Formación de Tecnólogos")
print("\t\t\t\t Programación Avanzada")
print("\t\t\t\tDiana Bonilla - Valeria Ochoa")
print("Cuenta el numero de ocurrencias de palabras en un archivo")
##p= "Quirrell"
##def creartxt():
## archivo = open('HarryPotter.txt','a')
## archivo.close()
def contarPalabras():
palabra = str(input("Ingrese la palabra: "))
archivo=open('HarryPotter.txt','r')
## data=archivo.readlines()
## archivo.close()
contador=0
## cont=0
#### for renglon in data:
#### for palabra in renglon.split(' '):
#### if palabra == "Hagrid":
#### contador +=1
#### print(str(contador),palabra)
## if palabra == "Harry":
## cont+=1
## print("Hay: ", str(cont),"con la palabra Harry")
lines = archivo.readlines()
for line in lines:
palabras = line.split(" ")
for p in palabras:
if p == palabra:
contador = contador + 1
print(contador,palabra)
##def grabartxt():
## archivo = open('NumPalaHarry.txt','a')
## archivo.write("hola")
## archivo.close()
##creartxt()
contarPalabras()
##grabartxt()
|
bb63cb4638dc346fd9dcb37d374302756d9d29d5 | miguelabreuss/scripts_python | /CursoEmVideoPython/desafio89.py | 944 | 3.71875 | 4 | grade = []
aluno = []
notas = []
medias = float()
while True:
aluno.append(str(input('Nome: ')))
notas.append(float(input('Digite primeira nota: ')))
notas.append(float(input('Digite segunda nota: ')))
aluno.append(notas[:])
medias = (notas[0] + notas[1]) / 2
aluno.append(medias)
grade.append(aluno[:])
if str(input('Deseja continuar [S/N]? ')).lower() == 'n':
break
notas.clear()
aluno.clear()
print('-='*14)
print('{:^28}'.format('RESULTADO FINAL'))
print('-='*14)
print('No. NOME MÉDIA')
print('-'*28)
for i in range(0, len(grade)):
print('{:<6}{:<15}{:.2f}'.format(i, grade[i][0], grade[i][2]))
print('-'*28)
while True:
qual = int(input('Mostrar notas de qual aluno? (Invalide para sair) '))
if qual < 0:
break
elif qual > (len(grade) - 1):
break
else:
print(f'As notas de {grade[qual][0]} são {grade[qual][1]}.')
print('')
|
e29744b1b7710351d415e16ef198aacf9d1cf78a | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /matrizes/thiagoD/13.py | 644 | 3.53125 | 4 | matriz1 = []
for i in range(4):
matriz1.append(list(map(int, input(
f"Digite os 5 elementos da linha {i + 1} divididos por espaço: ").split())))
matriz2 = []
for i in range(5):
matriz2.append(list(map(int, input(
f"Digite os 2 elementos da linha {i + 1} divididos por espaço: ").split())))
result = []
for i in range(len(matriz1)):
soma1, soma2 = 0, 0
for j in range(len(matriz2)):
soma1 += matriz1[i][j] * matriz2[j][0]
soma2 += matriz1[i][j] * matriz2[j][1]
result.append([soma1, soma2])
for i in result:
for j in i:
print(j, end=" ")
print()
|
6e4ab2110958b633deec1f6550cd28f5ca2293cb | ShourjaMukherjee/Dummy | /11thcodes/Lists/ASSIGN 111 - LIST - Rotate List (1).py | 646 | 3.734375 | 4 | def RollUp(L):
l=len(L)
t=L[0]
for i in range(l-1):
L[i]=L[i+1]
L[-1]=t
#print "Rolled Up List:-", L
return L
def RollDown(L):
l=len(L)
t=L[-1]
for i in range(l-2,-1,-1):
L[i+1]=L[i]
L[0]=t
#print "Rolled Down List:-", L
return L
L=[1,2,3,4,5]
#N=[1,2,3,4,5]
print "Orginal List:- ", L
#RollUp(L)
#RollDown(N)
n=int(raw_input("Enter Rotation Factor:- "))
if n>0:
for i in range(n):
N=RollDown(L)
else:
a=-n
for i in range(a):
N=RollUp(L)
print "The List after being rotated with a factor of",n,"is:-"
print N
|
a44998ee0751e39ddc092b944f68f3615e30c37f | RuachKim/Algorithm_Practice | /CodeWithPython/codetest/etc/codetest04.py | 2,054 | 3.703125 | 4 | """
Greedy method: find all the ways to achieve goal.
count the number of condition, includes '3' in time
"""
# n = int(input())
# cnt = 0
# for i in range(n+1):
# for j in range(60):
# for k in range(60):
# num = str(i)+str(j)+str(k)
# if '3' in num:
# cnt += 1
# print(cnt)
"""
Chess Board
Find all the available location knight can move
"""
# dat = input()
# #row, col -> cur
# row = int(dat[1])
# col = int(ord(dat[0])) - ord('a') + 1
# nite_steps = [ (-1,-2), (1,-2), (-1,2), (1,2), (2,1), (2,-1), (-2,-1), (-2,1) ]
# cnt = 0
# for step in nite_steps:
# next_row = row + step[0]
# next_col = col + step[1]
# if next_row >= 1 and next_row <= 8 and next_col >= 1 and next_col <= 8:
# cnt += 1
# print(cnt)
"""
Game Development
move character with each direction
"""
# n, m = map(int, input().split())
# x, y, to = map(int, input().split())
# array =[]
# for i in range(n):
# array.append(list(map(int, input().split())))
# #print(array)
# #visited map - init with zero
# v = [[0]*m for _ in range(n)]
# v[x][y] = 1 # cur location
# dx = [-1, 0, 1, 0]
# dy = [ 0, 1, 0, -1]
# def turn_left():
# global direction
# direction = direction -1
# if direction == -1:
# direction = 3
# cnt = 1 #already taken by cur_character
# turn_time = 0 #turning time by 4
# direction = 0
# while True:
# turn_left()
# nx = x + dx[direction]
# ny = y + dy[direction]
# if array[nx][ny] == 0 and v[nx][ny] == 0:
# x = nx
# y = ny
# cnt += 1
# turn_time = 0
# v[nx][ny] = 1
# continue
# else:
# turn_time += 1
# if turn_time == 4:
# nx = x - dx[direction]
# ny = y - dy[direction]
# if array[nx][ny] == 0:
# cnt += 1
# v[nx][ny] = 1
# else:
# break
# print(cnt)
|
a0884cc494db0dff69a64054bdcc3f381202ebd7 | dhhyey-desai/python-crash-course-code | /for-loops.py | 115 | 3.859375 | 4 | fruits = ["apple", "banana", "orange"]
for x in fruits:
print(x)
else:
print("I'm done!")
|
a807c48bd3a26182853c9dc91b821104c4dcf676 | BrunoVittor/pythonexercicios | /pythonexercicios/pythonexercicios/ex015.py | 893 | 3.9375 | 4 | # km percorridos e dias pelos quais foi alugado, preço a pagar , carro custa 60 reais o dia , e 0,15 o km rodado
'''dia = int(input('Por quantos dias foi alugado: '))
km = float(input('Quando km foram rodados: '))
res = (dia * 60) + (km * 0.15)
print('Se passaram {} dias \n foram percorridos {} km \n O valor total a pagar é de R${}'.format(dia, km, res))'''
'''dia = int(input('Quantidad de dias: '))
km = float(input('kilometros percorridos: '))
res = (dia * 60) + (km * 0.15)
print(f'O aluguel foi de {dia} e foram rodads {km}km, o valor foi de {res}')'''
print('-='*10)
print("Bruno's rent a car")
print('-='*10)
print('''TABELA DE PREÇOS
R$ 60,00 por dia
R$ 0,15 por kilometro rodado ''')
dia = int(input('Dias utilizados: '))
km = float(input('Kilometros utilizados: '))
res = (dia * 60) + (km * 0.15)
print(f'O valor final foi de R${res}') |
e53a3021a6d9f9f779bb1e24fe4d105792c2d298 | LegendaryKim/Hackerrank_30_Days_of_Code | /8-DictionariesAndMaps/Solution.py | 407 | 3.796875 | 4 | num = int(input())
phone_book = {}
for i in range(num):
entry = str(input()).split(" ")
name = entry[0]
phone = int(entry[1])
phone_book[name] = phone
while True:
try:
name = input()
if name in phone_book:
phone = phone_book[name]
print(name + "=" + str(phone))
else:
print("Not found")
except:
break
|
f077be2430de2207d9301b5469f473337e671d77 | XiaoqingWang/python_code | /python语法基础/02.if、while、for/08-判断星期几.py | 381 | 3.796875 | 4 | #1.获取用户的输入
num = int(input("请输入一个数字(1~7):"))
#2.判断用户的数据,并且显示对应的信息
if num == 1:
print("星期一")
elif num == 2:
print("星期二")
elif num == 3:
print("星期三")
elif num == 4:
print("星期四")
elif num == 5:
print("星期五")
elif num == 6:
print("星级六")
else:
print("你输入的数据有误...") |
a1551921c6f4b23662ff71fbbaa8359235fbd987 | VitaliiStorozh/Python_marathon_git | /2_sprint/Tasks/s2.1.py | 423 | 4.09375 | 4 | # As input data, you have a list of strings.
#
# Write a method double_string() for counting the number of strings from the list,
# represented in the form of the concatenation of two strings from this list
def double_string(s):
return len([i for i in s if i + i in s])
data = ['aa', 'aaaa', 'abc', 'abcabc', 'qwer', 'qwerqwer']
print(double_string(data))
data = ['aa', 'abc', 'qwerqwer']
print(double_string(data)) |
3363948902d8d0c138b0593c345243bcb8c6f45a | DCC-Lab/RayTracing | /raytracing/ray.py | 8,026 | 3.59375 | 4 | import warnings
from .utils import deprecated
class Ray:
"""A vector and a light ray as transformed by ABCD matrices.
The Ray() has a height (y) and an angle with the optical axis (theta).
It also has a position (z) initially at z=0, the diameter of the aperture at that point
when it propagated through, and a marker if it has been blocked by the
aperture.
Simple static functions are defined to obtain a group of rays: fans
originate from the same height but sweep a range of angles; fan groups
are fans originating from different heights.
Parameters
----------
y : float
Initial height of the ray. (Default=0)
theta : float
Initial angle of the ray. (Default=0)
Attributes
----------
z : float
Position of the ray along the optical axis. Initialized at 0.
apertureDiameter : float
The diameter of any blocking aperture at the present position z. Initialized at +Inf.
isBlocked : bool
Whether or not the ray was blocked by an aperture. Initialized to False.
See Also
--------
raytracing.rays
"""
def __init__(self, y: float = 0, theta: float = 0, z: float = 0, isBlocked:bool = False, wavelength: float = None):
self.y = y
self.theta = theta
self.z = z
self.isBlocked = isBlocked
self.apertureDiameter = float("+Inf")
self.wavelength = wavelength
@property
def isNotBlocked(self) -> bool:
"""Opposite of isBlocked. Convenience function for readability.
Examples
--------
>>> from raytracing import *
>>> # define an input ray
>>> ray1=Ray(y=1,theta=0.1)
>>> # define a lens to propagate the ray through
>>> mat=Matrix(A=1,B=0,C=-1/5,D=1,physicalLength=2,apertureDiameter=2,label='Lens')
>>> ray1Output=mat.mul_ray(ray1)
>>> print('the ray is not blocked? :', ray1Output.isNotBlocked)
the ray is not blocked? : True
"""
return not self.isBlocked
@staticmethod
@deprecated("The creation of a group of rays with this method is deprecated. Usage of the class Rays and its "
"subclasses is recommended.")
def fan(y: float, radianMin: float, radianMax: float, N: int):
"""This function generates a list of rays spanning from radianMin to radianMax.
This is usually used with Matrix.trace() or Matrix.traceMany() to trace the rays
through an element or group of elements.
Parameters
----------
y : float
Height of the ray
radianMin : float
Minimum angle in radians of the fan.
radianMax : float
Maximum angle in radians of the fan.
N : int
The number of rays to create inside the fan.
Returns
-------
rays : list of ray
The created list of rays that define this fan.
Notes
-----
This method is deprecated. The class Rays and its subclasses should be used to generate multiple Ray objects.
See Also
--------
raytracing.Matrix.trace()
raytracing.Matrix.traceMany().
"""
if N >= 2:
deltaRadian = float(radianMax - radianMin) / (N - 1)
elif N == 1:
deltaRadian = 0.0
else:
raise ValueError("N must be 1 or larger.")
rays = []
for i in range(N):
theta = radianMin + float(i) * deltaRadian
rays.append(Ray(y, theta))
return rays
@staticmethod
@deprecated("The creation of a group of rays with this method is deprecated. Usage of the class Rays and its "
"subclasses is recommended.")
def fanGroup(yMin: float, yMax: float, M: int, radianMin: float, radianMax: float, N: int):
"""This function creates a list of rays spanning from yMin to yMax and radianMin to radianMax.
This is usually used with Matrix.trace() or Matrix.traceMany() to trace the rays
through an element or group of elements.
Parameters
----------
yMin : float
Minimum height of the fans.
yMax : float
Maximum height of the fans.
M : int
The number of fans to create inside yMin and yMax.
radianMin : float
Minimum angle in radians of each fan.
radianMax : float
Maximum angle in radians of each fan.
N : int
The number of rays to create inside each fan.
Returns
-------
rays : list of ray
The created list of rays that define these fan groups.
Notes
-----
This method is deprecated. The class Rays and its subclasses should be used to generate multiple Ray objects.
See Also
--------
raytracing.Matrix.trace()
raytracing.Matrix.traceMany().
"""
if N >= 2:
deltaRadian = float(radianMax - radianMin) / (N - 1)
elif N == 1:
deltaRadian = 0.0
else:
raise ValueError("N must be 1 or larger.")
if M >= 2:
deltaHeight = float(yMax - yMin) / (M - 1)
elif M == 1:
deltaHeight = 0.0
else:
raise ValueError("M must be 1 or larger.")
rays = []
for j in range(M):
for i in range(N):
theta = radianMin + float(i) * deltaRadian
y = yMin + float(j) * deltaHeight
rays.append(Ray(y, theta))
return rays
def at(self, z):
"""This function returns a ray at position z parallel to the current ray.
Z is not the distance, it is the position. The distance is (z-self.z)
Parameters
----------
z : float
Position in z where we want the output ray
Returns
-------
ray : an interpolated Ray
A Ray at position z, with y interpolated and theta unchanged
Notes
-----
If ray is blocked, then the output Ray will be blocked too
See Also
--------
raytracing.Ray.along()
"""
outputRay = Ray(y=self.y + (z-self.z) * self.theta, theta=self.theta, z=z)
if self.isBlocked:
outputRay.isBlocked = True
return outputRay
@staticmethod
def along(rayTrace, z):
"""This function returns a ray at position z along the ray trace.
y and theta are linearly interpolated in between the two closest rays.
Parameters
----------
rayTrace : list of Ray
The rayTrace
z : float
Position in z where we want the output ray
Returns
-------
ray : an interpolated Ray
A Ray at position z, with y and theta interpolated from the ray trace
Notes
-----
If the ray at an earlier z is blocked, then the Ray will be blocked too
See Also
--------
raytracing.Ray.at()
"""
closestRay = rayTrace[0]
for ray in rayTrace:
if ray.z == z:
return ray
if ray.z > z:
return closestRay.at(z=z)
closestRay = ray
return rayTrace[-1]
def __str__(self):
"""String description that allows the use of print(Ray())."""
description = "y = {0:6.3f}\n".format(self.y)
description += "theta = {0:6.3f}\n".format(self.theta)
description += "z = {0:4.3f}".format(self.z)
if self.isBlocked:
description += " (blocked)"
return description
def __eq__(self, other):
"""Define rays to be equal if they have the same height and angle."""
if not isinstance(other, Ray):
return False
elif self.y != other.y:
return False
elif self.theta != other.theta:
return False
return True
|
beff77c181bf91a2d1b6fbb37660257e34afcf4d | slavkoBV/solved-tasks-SoftGroup-course | /Sockets/Chat/model.py | 3,281 | 3.609375 | 4 | import sqlite3
import hmac
# Secret key for hash generate password
SECRET_KEY = 'secret'
def hash_generate(user_pass):
"""Generate hash of user password
:param user_pass: string
:return: hash.digest()
"""
user_hash = hmac.new(SECRET_KEY.encode(), user_pass.encode())
return user_hash.digest()
def check_password(user_pass_input, user_pass_db):
"""Check if user is authorised or not
:param user_pass_input: user input password
:param user_pass_db: user password from database
:return: True or False
"""
user_input_hash = hash_generate(user_pass_input)
if hmac.compare_digest(user_input_hash, user_pass_db):
return True
else:
return False
def create_user_db(db_file):
"""Create table users in database DB_FiLE
:param db_file: name of database file (as global variable)
:return: None
"""
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password BLOB)")
curs.close()
conn.close()
def create_post_db(db_file):
"""Create table users in database DB_FiLE
:param db_file: name of database file (as global variable)
:return: None
"""
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, post TEXT)")
curs.close()
conn.close()
def save_msg_db(user, message, db_file):
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("INSERT INTO posts (username, post) VALUES (?, ?)", [user, message])
conn.commit()
curs.close()
conn.close()
class User:
def __init__(self):
self._username = None
self._password = None
@property
def username(self):
return self._username
@username.setter
def username(self, username):
if len(username) >= 3:
self._username = username
else:
raise ValueError('Username must be not less than 3 symbols')
@property
def password(self):
return self._password
@password.setter
def password(self, password):
if len(password) > 6:
self._password = hash_generate(password)
else:
raise ValueError('Password too short, must be 6 or more symbols')
def save(self, db_file):
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("INSERT INTO users (username, password) VALUES (?, ?)", [self.username, self.password])
conn.commit()
curs.close()
conn.close()
@staticmethod
def delete(db_file, username):
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("DELETE FROM users WHERE username='{}'".format(username))
conn.commit()
curs.close()
conn.close()
@staticmethod
def get_user_by_username(username, db_file):
conn = sqlite3.connect(db_file)
curs = conn.cursor()
curs.execute("SELECT * FROM users WHERE username='{}'".format(username))
user = curs.fetchone()
curs.close()
conn.close()
if user:
return user
else:
return None
|
7a6f1ea8e0d8b3000e224ebe322015bd973ac702 | Junewang0614/pypypy | /chap07/p7-3.py | 119 | 3.53125 | 4 | n = input()
if int(n) % 10 == 0:
print(n + '是10的整数倍。')
else:
print(n + '不是10的整数倍。')
|
33922a0e31894e848897eef47323449828e5c90c | Jiaweihu08/EPI | /6 - Strings/6.12 - substring_matching.py | 1,055 | 3.96875 | 4 | """
Given two strings s and t, find the starting position of s in t if
s is a substring of t, otherwise return -1.
The naive approach is to go through t and at each position i compare
the substring starting at i to s. This leads to a O(n^2) algorithm.
A simple and more efficient algorithm for string matching is the
Rabin-Karp algorithm. This algorithm relies on the concept of fingeprint
which is a rolling hash of the strings. Using this hash function, the
hashes of sliding windows of t can be computed very efficiently.
"""
import functools
def rabin_karp(s, t):
if len(s) > len(t):
return -1
base = 26
t_hash = functools.reduce(lambda h, c: h * base + ord(c), t[:len(s)], 0)
s_hash = functools.reduce(lambda h, c: h * base + ord(c), s, 0)
power_s = base ** max(len(s) - 1, 0)
for i in range(len(s), len(t)):
if t_hash == s_hash and t[i - len(s):i] == s:
return i - len(s)
t_hash -= ord(t[i - len(s)]) * power_s
t_hash = t_hash * base + ord(t[i])
if t_hash == s_hash and t[-len(s):] == s:
return len(t) - len(s)
return -1 |
371791950f055bef08336f12740275146d3e1bcf | tkj5008/Luminar_Python_Programs | /Object_Oriented_Programming/polymorphism/demo2.py | 367 | 4.03125 | 4 | #overriding
# same method name and same num of parameters
# Child class method overide parent class method
class Person:
def printval(self,name):
self.name=name
print("Inside Parent",self.name)
class Child(Person):
def printval(self,class1):
self.class1=class1
print("Inside Child",self.class1)
ch=Child()
ch.printval("abc")
|
0708e51e1db878e97be5fab7fd0f87df2b21b872 | sibodiamond/kaggle-lshtc-1 | /tf-idf.py | 3,190 | 3.53125 | 4 | # Extract the most important terms from each document
# This script generates tf-idf.csv,
# where each document from {INPUT_FILE}
# is represented with {TERMS_NEEDED} most important terms.
# Structure of tf-idf.csv:
# - each line is a document,
# for example "335416,416827 57:3.5 70:3.0 71:2.5 72:1.5 81:1.5"
# - in this case:
# "335416,416827" is the target class of the document
# (copied from INPUT_FILE)
# "57:3.5" means that
# term 57 has TF-IDF equal to 3.5
from __future__ import division
import csv
from math import log
# (Max) number of the most important terms
TERMS_NEEDED = 5
INPUT_FILE = 'train-sklearn.csv'
OUTPUT_FILE = 'tf-idf.csv'
def compute_ifidf(terms, num_documents, raw_idf, max_raw_frequency):
""" Computes TF-IDF
http://en.wikipedia.org/wiki/Tf%E2%80%93idf
"""
tf_idf = dict()
for term, frequency in terms:
tf = 0.5 + (0.5 * frequency) / max_raw_frequency
idf = log(num_documents/raw_idf[term])
tf_idf[term] = tf * idf
return tf_idf
def max_raw_frequency(terms):
""" terms = [['a', 5], ['b', 7], ['c', 3]]
maximum_raw_frequency(terms) => returns 7
"""
max = 0
for term, frequency in terms:
if frequency > max:
max = frequency
return max
def extract_terms(document):
""" document = "545,32 8:1 18:2"
extract_terms(document) => returns [[8, 1], [18, 2]]
"""
terms = [item.split(':') for item in document.split() if item.find(':') >= 0]
terms = [[int(term), int(frequency)] for term, frequency in terms]
return terms
def extract_classes(document):
""" document = "545,32 8:1 18:2"
extract_classes(document) => returns "545,32"
"""
return document.split()[0]
def extract_most_important(tf_idf, terms_needed):
""" tf_idf = {'a': 2, 'b': 0.5, 'c': 3, 'd': 1}
extract_most_important(tf_idf, 2) => returns "c:3 a:2"
extract_most_important(tf_idf, 3) => returns "c:3 a:2 d:1"
"""
sort_by_value = sorted(tf_idf, key=tf_idf.get, reverse=True)
most_important = sort_by_value[:terms_needed]
return ' '.join([str(item) + ":" + str(tf_idf[item]) for item in most_important])
# Read IDF data
raw_idf = dict()
with open('idf.csv', 'r') as idf_data:
reader = csv.reader(idf_data)
for row in reader:
raw_idf[int(row[0])] = int(row[1])
# Count number of documents in the input file
num_documents = 0
with open(INPUT_FILE) as f:
for line in f:
num_documents += 1
# For each document:
# 1) Compute TF-IDF
# 2) Write down T most important terms
# into a separate file (tf-idf.csv)
with open(INPUT_FILE, 'r') as input_file:
with open(OUTPUT_FILE, 'w') as output_file:
for document in input_file:
terms = extract_terms(document)
tf_idf = compute_ifidf(terms, num_documents, raw_idf, max_raw_frequency(terms))
most_important_terms = extract_most_important(tf_idf, TERMS_NEEDED)
classes = extract_classes(document)
output_file.write(classes + " " + most_important_terms + "\n")
|
ca541d793567078594fba910524598004e920ba8 | Chener-Zhang/HighSchoolProject | /python/hw3pr1/csgrid.py | 2,135 | 3.9375 | 4 | from turtle import *
#TheScreen = Screen()
#TheScreen.onclick( mouseHandler )
currentL = None
COL = -1
ROW = -1
currentXs = []
currentYs = []
def getCol(mouse_x, mouse_y):
global currentXs;
global currentYs;
global COL
global ROW
COL = 0
ROW = 0
for i in range(len(currentXs)-1):
if currentXs[i] <= mouse_x < currentXs[i+1]:
COL = i
for i in range(len(currentYs)-1):
if currentYs[i] <= mouse_y < currentYs[i+1]:
ROW = i
return COL
# start-up turtle stuff
reset()
tracer(False)
delay(0)
clrD = { 0:"white", 1:"red", 2:"blue", 3:"green", 4:"gold" }
def setColor( key, color ):
global clrD
clrD[key] = color
return
def colorLookup( clr ):
global clrD
if clr in clrD:
return clrD[clr]
else:
return clr
def drawsq(ulx,uly,side,clr):
delay(0)
tracer(False)
up()
# try setting the color
pencolor( "black" )
# look up the color
clr = colorLookup( clr )
# go!
try:
fillcolor( clr )
except:
print "Color", clr, "was not recognized."
print "Using blue instead."
fillcolor( "blue" )
goto(ulx, uly)
down()
seth( 0 ) # east in normal mode
begin_fill()
for s in range(4):
forward(side)
right(90)
end_fill()
up()
def show1d( L ):
""" new - with turtle!! """
# remember this!
global currentL
currentL = L
W = window_width()
H = window_height()
if len(L) == 0:
print "You can't show(L) when L is empty."
return
n = len(L) + 2 # 2 more for a margin on each side
sq_side = min( W/float(n), H/float(3), 100.0 )
uly = 0 + sq_side/2.0
ulx = -sq_side*len(L)/2.0
global currentYs
currentYs = [-uly,uly]
global currentXs
currentXs = [ulx]
clear()
for clr in L:
#print "clr is", clr
drawsq(ulx, uly, sq_side, clr)
ulx += sq_side
currentXs.append( ulx )
return
def show(L):
show1d(L)
return
# start with something
show1d( [1,1,0,1] )
|
f4326995781d824ab481c03159b45581e7a328c6 | gautambatra100/Health-Management-System-in-Python | /Gym(Trainer-Client) Management System.py | 4,006 | 3.71875 | 4 | import datetime
def gettime():
return datetime.datetime.now()
try:
client_list={1:"Harry",2:"Gautam",3:"Sara"}
log_list={1:"add",2:"retreive"}
work_list={1:"diet",2:"exercise"}
while True:
for key,value in client_list.items():
print("press",key,"for",value,"\n",end="")
client_number=int(input())
print()
print("selected client is",client_list[client_number])
print()
for key,value in log_list.items():
print("press",key,"to",value,"\n",end="")
log_number=int(input())
print()
for key,value in work_list.items():
print("press",key,"for",value,"\n",end="")
work_number=int(input())
print()
if log_number==1:
if client_number==1:
if work_number==1:
while True:
diet1=input("enter what did you just eat?")
f=open("Harrydiet.txt","a")
f.write(str([str(gettime())]) + ": " + diet1 + "\n")
print("succesfully updated")
print()
f.close()
print("Do you want to add mmore y/n")
a=input()
if a=="y":
continue
elif a=="n":
break
else:
print("enter a valid number")
break
elif work_number==2:
exercise1=input("enter what you did")
f=open("Harryexercise.txt","a")
f.write(str([str(gettime())]) + ": " + exercise1 + "\n")
print("succesfully updated")
f.close()
else:
print("please enter valid operation")
elif client_number==2:
if work_number==1:
diet2=input("enter what did you just eat?")
f=open("Gautamdiet.txt","a")
f.write(str([str(gettime())]) + ": " + diet2 + "\n")
print("succesfully updated")
f.close()
elif work_number==2:
exercise2=input("enter what you did")
f=open("Gautamexercise.txt","a")
f.write(str([str(gettime())]) + ": " + exercise1 + "\n")
print("succesfully updated")
f.close()
else:
print("please enter valid operation")
elif client_number==3:
if work_number==1:
diet3=input("enter what did you just eat?")
f=open("Saradiet.txt","a")
f.write(str([str(gettime())]) + ": " + diet3 + "\n")
print("succesfully updated")
f.close()
elif work_number==2:
exercise3=input("enter what you did")
f=open("Saraexercise.txt","a")
f.write(str([str(gettime())]) + ": " + exercise1 + "\n")
print("succesfully updated")
f.close()
else:
print("please enter valid operation")
else:
print("please enter valid client_number and try again")
elif log_number==2:
if client_number==1:
if work_number==1:
f=open("Harrydiet.txt","rt")
print("Harry's diet :")
content=f.read()
print(content)
f.close()
elif work_number==2:
f=open("Harryexercise.txt","rt")
print("Harry's exercise :")
content=f.read()
print(content)
f.close()
else:
print("please enter valid operation")
if client_number==2:
if work_number==1:
f=open("Gautamdiet.txt","rt")
print("Gautam's diet :")
content=f.read()
print(content)
f.close()
elif work_number==2:
f=open("Gautamexercise.txt","rt")
print("Gautam's exercise :")
content=f.read()
print(content)
f.close()
else:
print("please enter valid operation")
if client_number==3:
if work_number==1:
f=open("Saradiet.txt","rt")
print("Sara's diet :")
content=f.read()
print(content)
f.close()
elif work_number==2:
f=open("Saraexercise.txt","rt")
print("Sara's exercise :")
content=f.read()
print(content)
f.close()
else:
print("please enter valid operation")
else:
print("please enter valid operation")
print("Do you want to repeat y/n")
a=input()
if a=="y":
continue
elif a=="n":
break
else:
break
except :
print("try again")
|
6f58ffc4fe45e530e846f7442fa3ede493bb68b2 | Niroshan-Selvaraj/100daysofpython | /day-19/main.py | 1,311 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
tim = Turtle()
screen = Screen()
screen.setup(width=500, height=400)
all_turtles = []
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red","green","yellow","blue","orange","purple"]
is_game_on = False
def place_all_turtle(turtle_count, start_x_position, start_y_position):
for n in range(turtle_count):
new_turtle = Turtle()
new_turtle.penup()
new_turtle.shape("turtle")
new_turtle.color(colors[n])
new_turtle.goto(start_x_position, start_y_position)
all_turtles.append(new_turtle)
start_y_position += 50
print(all_turtles)
return all_turtles
turtles = place_all_turtle(6,-230,-130)
if user_bet:
is_game_on = True
while is_game_on:
for a_turtle in turtles:
if a_turtle.xcor() > 230:
is_game_on = False
winning_color = a_turtle.pencolor()
if winning_color == user_bet:
print(f"You've won! The {winning_color} turtle is the winner!")
else:
print(f"You've lost! The {winning_color} turtle is the winner!" )
rand_distance = random.randint(0,10)
a_turtle.forward(rand_distance)
screen.exitonclick()
|
832bc6064a6e56e501dbe950822d714d0fc237cf | Android4567/Python | /integer.py | 126 | 4.09375 | 4 | a = int(input("Enter any Integer "))
if (a > 0):
print("Integer is positive")
else:
print("Integer is Negative")
|
77ec36dece8eb5e225eec561d2c904b45c5ac3e1 | jrcox/dsp | /python/q8_parsing.py | 734 | 4.25 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’
# contain the total number of
# goals scored for and against each team in that season
# (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them).
# Write a program to read the file,
# then print the name of the team with the
# smallest difference in ‘for’ and ‘against’ goals.
import pandas as pd
football = pd.read_csv("/Users/Jessica/ds/metis/prework/dsp/python/football.csv")
football['difference'] = abs(football['Goals'] - football['Goals Allowed'])
min_difference = football['difference'].idxmin()
team = football['Team'][min_difference]
team
|
3c2f528708277c04773a910e90b372b6dea7374f | syurskyi/Python_Topics | /115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Check_Multiple_Calls.py | 2,151 | 3.671875 | 4 | # Python Test Mock
# unittest.mock � mock object library
# unittest.mock is a library for testing in Python.
# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
# unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.
# After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with.
# You can also specify return values and set needed attributes in the normal way.
#
# Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel
# for creating unique objects.
#
# Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by
# many mocking frameworks.
#
#
# Checking multiple calls with mock:
# mock has a nice API for making assertions about how your mock objects are used.
#
mock _ Mock()
mock.foo_bar.return_value _ N..
mock.foo_bar('baz', spam_'eggs')
mock.foo_bar.a_c_w..('baz', spam_'eggs')
#
# If your mock is only being called once you can use the assert_called_once_with() method that also asserts that the call_count is one.
#
mock.foo_bar.a_c_o_w..('baz', spam_'eggs')
mock.foo_bar()
mock.foo_bar.a_c_o_w..('baz', spam_'eggs')
#
# Both assert_called_with and assert_called_once_with make assertions about the most recent call.
# If your mock is going to be called several times, and you want to make assertions about all those calls you can use call_args_list:
#
mock _ Mock(return_value_None)
mock(1, 2, 3)
mock(4, 5, 6)
mock()
mock.call_args_list
# OUTPUT: '[call(1, 2, 3), call(4, 5, 6), call()]'
#
# The call helper makes it easy to make assertions about these calls.
# You can build up a list of expected calls and compare it to call_args_list.
# This looks remarkably similar to the repr of the call_args_list:
#
expected _ [call(1, 2, 3), call(4, 5, 6), call()]
mock.call_args_list __ expected
# OUTPUT: 'True'
|
f3b468bfae4c95364df663edf7431d671c987899 | Cheryl-Tsui/D002-2019 | /L1/Q2.py | 225 | 3.921875 | 4 | from math import*
print(8*3.57)
print(5+30*20)
print((5+30)*20)
print(1+(2+20*3)/(4*2))
print(1+2**10)
print(ceil(29/4))
radius=input("What is the radius?")
int(radius)
radius=sqrt(100/pi)
print((2*radius+1)**2)
|
68cb62e5d516e60f3fe43db4066fb9bf5eaacf52 | gitter-badger/python_me | /hackrankoj/itertool/permutations.py | 551 | 3.578125 | 4 | #!/usr/bin/env python
# coding=utf-8
from itertools import permutations
print '\n'.join([''.join(_) for _ in sorted(list(permutations(*map(lambda s:int(s) if s.isdigit() else s,raw_input().split()))))])
#上面语句的list可以不用写,单纯返回一个迭代器,反正前面有for
'''
permutations(iterable[,k])函数会根据中的iterable的顺序排列,'213'就会先2开头,然后1开头,再3开头,
'''
print '\n'.join([''.join(_) for _ in permutations(*map(lambda s:int(s) if s.isdigit() else sorted(s),raw_input().split()))])
|
17186a0b0140bf6713855347e1c33f1b64d2b837 | peterneyens/pygame-tetris | /tetris.py | 9,909 | 4 | 4 | #!/usr/bin/python
# Filename: tetris.py
#
# A game of Tetris
#
# Author; Peter Neyens
# Version: 31-01-2012
import random
class Position:
'''A postition'''
def __init__(self, x=0, y=0):
self.x = int(x)
self.y = int(y)
def rotate90(self):
'''Return the positions when this position is rotated 90 degrees
clockwise round the origin'''
comp = complex(self.x, self.y)
comp *= -1j #rotate 90 degrees
return Position(comp.real, comp.imag)
def __repr__(self):
'''Return a textual representation of this position'''
return 'P({x},{y})'.format(x=self.x, y=self.y)
def __eq__(self, other):
'''Return if this position is equal to the other position'''
return self.x == other.x and self.y == other.y
def __hash__(self):
'''Return the hash of this position'''
return (self.x * 97) + self.y
class Tetronimo:
'''A tetronimo that can move left, right and down and rotate and
has 4 positions'''
def __init__(self, grid, color):
if not isinstance(grid, Grid):
raise ValueError("Parameter grid should be a Grid object")
self._relPositions = []
self.position = None
self.grid = grid
self.color = color
def rotate90(self):
'''Rotate this tetronimo 90 degrees clockwise if possible'''
rotatedRelPos = []
for position in self._relPositions:
relPos = position.rotate90()
absPos = Position(self.position.x + relPos.x, \
self.position.y + relPos.y)
if self.grid.isOpenPosition(absPos):
rotatedRelPos.append(relPos)
if len(rotatedRelPos) == len(self._relPositions):
self._relPositions = rotatedRelPos
def positions(self):
'''Return the position of this tetronimo'''
positions = []
for rel in self._relPositions:
x = self.position.x + rel.x
y = self.position.y + rel.y
positions.append(Position(x, y))
return positions
def visiblePositions(self):
'''Return the visible positions of this tetronimo'''
return [p for p in self.positions() if p <= self.grid.height]
def moveLeft(self):
'''Move this tetronimo one position to the left if possible'''
self._moveDelta(-1, 0)
def moveRight(self):
'''Move this tetronimo one position to the right if possible'''
self._moveDelta(1, 0)
def moveDown(self):
'''Move this tetronimo one position down if possible'''
self._moveDelta(0, -1)
def canMoveDown(self):
'''Can this tetronimo move down ?'''
return self._canMoveDelta(0, -1)
def canMoveHorizontally(self):
'''Can this tetronimo move to left or right ?'''
return self._canMoveDelta(-1, 0) or self._canMoveDelta(1, 0)
def _moveDelta(self, x, y):
if self._canMoveDelta(x, y):
self.position.x += x
self.position.y += y
def _canMoveDelta(self, x, y):
for pos in self.positions():
if not self.grid.isOpenPosition(Position(pos.x + x, pos.y + y)):
return False
return True
class TetronimoL(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.ORANGE)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(1, 0));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(0, 2));
class TetronimoJ(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.BLUE)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(-1, 0));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(0, 2));
class TetronimoZ(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.GREEN)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(-1, 1));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(1, 0));
class TetronimoS(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.RED)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(-1, 0));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(1, 1));
class TetronimoT(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.PURPLE)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(-1, 0));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(1, 0));
class TetronimoI(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.CYAN)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(0, -1));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(0, 2));
self._vertical = True
def rotate90(self):
# if vertical rotate 90 degrees
Tetronimo.rotate90(self)
# if horizontal rotate another 180 degrees (270 or -90 degrees in total)
if not self._vertical:
Tetronimo.rotate90(self)
Tetronimo.rotate90(self)
#switch vertical/horizontal
self._vertical = not self._vertical
class TetronimoO(Tetronimo):
def __init__(self, grid):
Tetronimo.__init__(self, grid, Color.YELLOW)
self._relPositions.append(Position(0, 0));
self._relPositions.append(Position(1, 0));
self._relPositions.append(Position(0, 1));
self._relPositions.append(Position(1, 1));
def rotate90(self):
pass #no rotation
class Grid:
'''The playing grid'''
def __init__(self):
self.width = 10
self.height = 20
self._heightWithMargin = self.height + 4;
self._positions = []
for x in xrange(self.width):
self._positions.append([])
for y in xrange(self._heightWithMargin):
self._positions[x].append(Color.DEFAULT)
def getColorAt(self, pos):
'''Return the color of the given position'''
if not isinstance(pos, Position):
raise ValueError("Parameter pos should be a Position object")
if not self.isValidPosition(pos):
raise ValueError("The given position is not on the grid")
return self._positions[pos.x][pos.y]
def isValidPosition(self, pos):
'''Lies the given position within the boundries of the grid?'''
if not isinstance(pos, Position):
raise ValueError("Parameter pos should be a Position object")
return (pos.x >= 0 and pos.x < self.width) and \
(pos.y >= 0 and pos.y < self._heightWithMargin)
def isOpenPosition(self, pos):
'''Is the given position valid and open?'''
if not isinstance(pos, Position):
raise ValueError("Parameter pos should be a Position object")
if not self.isValidPosition(pos):
return False
return self.getColorAt(pos) == Color.DEFAULT
def colorPosition(self, pos, color):
'''Color the given position with the given color'''
if not isinstance(pos, Position):
raise ValueError("Parameter pos should be a Position object")
if self.isValidPosition(pos):
self._positions[pos.x][pos.y] = color
def colorTetronimo(self, tetronimo):
'''Color the tetronimo's positions on this grid'''
if not isinstance(tetronimo, Tetronimo):
raise ValueError("Parameter tetronimo should be a Tetronimo object")
for pos in tetronimo.positions():
self.colorPosition(pos, tetronimo.color)
def isLineFull(self, line):
'''Is the given line full?'''
for x in xrange(0, self.width):
if self.isOpenPosition(Position(x, line)):
return False
return True
def hasBlockAtTop(self):
'''Has a block at the top ? Grid full?'''
for x in xrange(0, self.width):
if not self.isOpenPosition(Position(x, self.height-1)):
return True
return False
def removeLine(self, line):
'''Remove the given line from the grid'''
if self.isLineFull(line):
for y in xrange(line, self.height):
for x in xrange(self.width):
if y == self.height-1:
self.colorPosition(Position(x,y), Color.DEFAULT)
else:
color = self.getColorAt(Position(x,y+1))
self.colorPosition(Position(x,y), color)
class Color:
'''Color of tetronimos - enumeration'''
DEFAULT, CYAN, BLUE, ORANGE, YELLOW, GREEN, PURPLE, RED = range(8)
class Game:
'''Game object'''
def __init__(self):
self.grid = Grid()
self.droppingTetronimo = self._randomTetronimo()
self.nextTetronimo = self._randomTetronimo()
def isEnded(self):
'''Is this game ended ??'''
return self.grid.hasBlockAtTop()
def dropNextTetronimo(self):
# drop a new tetronimo
self.droppingTetronimo = self.nextTetronimo
self.nextTetronimo = self._randomTetronimo()
def _randomTetronimo(self):
tetronimos = [TetronimoS(self.grid), TetronimoZ(self.grid),
TetronimoL(self.grid), TetronimoO(self.grid),
TetronimoI(self.grid), TetronimoJ(self.grid),
TetronimoT(self.grid)]
tetronimo = random.choice(tetronimos)
tetronimo.position = Position(self.grid.width/2, self.grid.height+1)
return tetronimo
|
2f171ba7822aa3b5e3de7b13b3574bb94fc37612 | manelmmh/Arrays-practice | /pos_neg_index.py | 608 | 3.515625 | 4 | #another approach to solving the negative, positive numbers sorting
# is by using 2 index pointers, one is incremented and the other is decremented
def partition(lo,hi):
up_ptr=lo
dwn_ptr=hi
while(up_ptr<dwn_ptr):
while(A[up_ptr]<0):
up_ptr+=1
while(A[dwn_ptr]>0):
dwn_ptr-=1
if(up_ptr<dwn_ptr):
A[up_ptr], A[dwn_ptr]=A[dwn_ptr], A[up_ptr]
A=[]
n=int(input())
for i in range (0,n):
nbr=int(input())
A.append(nbr)
print('the array before sorting: ', A)
partition(0,n-1)
print('after sorting: ', A) |
ba22c0a53a402f2ae7174548e3e240f099e6bc83 | DanzTheDeadly/algorithms_and_data_structures | /python/algorithms/sort.py | 1,941 | 3.59375 | 4 | from math import floor, ceil, inf
def insertion_sort (m, inplace=False):
if not inplace:
m = m[:]
for j in range(1, len(m)): # m
k = m[j] # m-1
i = j-1 # m-1
while i >= 0 and m[i] > k: # m(m+1)/2
m[i+1] = m[i] # m(m+1)/2-1
i -= 1 # m(m+1)/2-1
m[i+1] = k # m-1
return m
def selection_sort (m):
n = [] # 1
while m: # m
k = m[0] # m
for i in m[1:]: # m(m+1)/2
if i < k: # m(m+1)/2-1
k = i # m(m+1)/2-1
n.append(m[m.index(k)]) # m
return n
def mergesort (m, start=0, end=0, inplace=False):
if not end:
end = len(m)
if not inplace:
m = m[:]
if end-start > 1:
div = floor((end+start)/2)
print(start, div, end)
mergesort(m, start, div)
mergesort(m, div, end)
merge(m, start, div, end)
if not inplace:
return m
def merge (m, start, div, end):
A = m[start:div]
A.append(999999)
B = m[div:end]
B.append(999999)
i, j = 0, 0
for n in range(start, end):
if A[i] < B[j]:
m[n] = A[i]
i += 1
else:
m[n] = B[j]
j += 1
print(m)
def quicksort (m, a=0, b=10, inplace=False):
if not inplace:
m = m[:]
if len(m[a:b]) <= 1:
return m
div = a
for i in range(a, b-1):
if m[i] <= m[b-1]:
m[div], m[i] = m[i], m[div]
div += 1
m[div], m[b-1] = m[b-1], m[div]
quicksort(m, a, div)
quicksort( m, div+1, b)
return m
def counting_sort (m, r):
less = [0 for i in range(r)]
esum = 0
for n in range(r):
for k in m:
if k < n:
esum += 1
less[n] = esum
esum = 0
res = [0 for i in range(len(m))]
print(less)
for j in range(len(m)):
res[less[m[j]]] = m[j]
less[m[j]] += 1
return res
|
3840b515569ee1b25ebd663822b20d9e33b75ad4 | violenttestpen/DataStructureAlgorithms | /Sort/SelectionSort.py | 352 | 3.734375 | 4 | # selection sort [O(n**2)]
def ssort(array):
a = array[:]
# start from the second element
for i in range(len(a) - 1):
min_index = i
for j in range(i + 1, len(a)):
if a[min_index] > a[j]:
min_index = j
if min_index != i:
a[min_index], a[i] = a[i], a[min_index]
return a
|
d25b39f60a7cd0b3123655a705bf046610e81db3 | marionseignovert/tp-proba | /dossier_code/monty_hall.py | 2,735 | 3.734375 | 4 | from random import *
class Game:
def __init__(self):
porte_win = randint(0, 2)
self.porte_gagnante = porte_win
self.porte_ouverte = -1
self.porte_designe = -1
#print("Porte gagnante :", self.porte_gagnante)
def init_game(self):
pass
def choix_porte(self):
self.porte_designe = randint(0, 2)
#print("Porte Choisie : ",self.porte_designe)
def reveal(self):
if self.porte_designe == self.porte_gagnante:
porte_a_ouvrir = randint(0,2)
while porte_a_ouvrir == self.porte_gagnante:
porte_a_ouvrir = randint(0,2)
self.porte_ouverte = porte_a_ouvrir
else:
porte_a_ouvrir = randint(0, 2)
while porte_a_ouvrir == self.porte_designe or porte_a_ouvrir == self.porte_gagnante:
porte_a_ouvrir = randint(0, 2)
#print("Porte ouverte :", porte_a_ouvrir)
self.porte_ouverte = porte_a_ouvrir
def open(self, changement):
if changement == 1:
if self.porte_designe == self.porte_gagnante:
#print("Vous avez perdu")
return "Loose"
else:
#print("Vous avez gagné")
return "Win"
elif changement == 0:
if self.porte_designe == self.porte_gagnante:
#print("Vous avez gagné")
return "Win"
else:
#print("Vous avez perdu")
return "Loose"
else:
print("Vous avez rentré un paramètre faux")
conteur_win = 0
conteur_loose = 0
nombre_passage = 0
n = 100
print("Pour ", n, " parties en changeant de porte")
for i in range(0,n):
nombre_passage = nombre_passage + 1
game = Game()
game.choix_porte()
game.reveal()
#game.open(1)
if game.open(1) == "Win":
conteur_win = conteur_win + 1
else:
conteur_loose = conteur_loose + 1
print("Nombre de Passage : ", nombre_passage, " ")
print("Nombre de Victoire : ", conteur_win, " ")
print("Nombre de Défaite : ", conteur_loose, " ")
conteur_win = 0
conteur_loose = 0
nombre_passage = 0
print("Pour ", n, " parties sans changer de porte")
for i in range(0,n):
nombre_passage = nombre_passage + 1
game = Game()
game.choix_porte()
game.reveal()
#game.open(1)
if game.open(0) == "Win":
conteur_win = conteur_win + 1
else:
conteur_loose = conteur_loose + 1
print("Nombre de Passage : ", nombre_passage, " ")
print("Nombre de Victoire : ", conteur_win, " ")
print("Nombre de Défaite : ", conteur_loose, " ")
print("Conclusion: Le joueur a plus de chances de gagner lorsqu'il change de choix de porte. ")
|
32f22d35eccf4f3d90785c49d20f669bb1ecd408 | El-fish/Sirius_python | /4 Условия/ThirdStar.py | 552 | 3.8125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
# 1
if x1 + 1 == x2 and y1 + 2 == y2:
print("YES")
# 2
elif x1 + 2 == x2 and y1 + 1 == y2:
print("YES")
# 3
elif x1 + 2 == x2 and y1 - 1 == y2:
print ("YES")
# 4
elif x1 + 1 == x2 and y1 - 2 == y2:
print ("YES")
# 5
elif x1 - 1 == x2 and y1 - 2 == y2:
print ("YES")
# 6
elif x1 - 2 == x2 and y1 - 1 == y2:
print("YES")
# 7
elif x1 - 2 == x2 and y1 + 1 == y2:
print("YES")
# 8
elif x1 - 1 == x2 and y1 + 2 == y2:
print ("YES")
else:
print("NO")
|
b9c5b548e99abdbe246b9e97b0777a0969c80776 | fiona-tina/Duke-ECE-568 | /Scalability&Performance/erss-hwk4-kx30-wz125/analysis/main.py | 756 | 3.75 | 4 | import matplotlib.pyplot as plt
import sys
# Read a file line by line and return list of lines.
def read_file(filename):
f = open(filename, "r")
lines = f.readlines()
f.close()
return lines
# Parse the log file line by line.(strictly follow our print format)
def parse_log(filename):
lines = read_file(filename)
data = []
for l in lines:
data.append(int(l.split(":")[1]))
return data
# Use data as y value to draw the image.
def draw(data):
plt.ylim(min(data) - 5, max(data) + 5)
plt.plot(data, marker="o")
plt.show()
if __name__ == '__main__':
if len(sys.argv) > 1:
for index in range(1, len(sys.argv)):
draw(parse_log(sys.argv[index]))
draw(parse_log("./data.log"))
|
c2298f59deb8d79100c23150513d8bbc292148fd | Pizzabakerz/codingsuperstar | /python-codes/codes/file_operations/file_writting.py | 505 | 3.765625 | 4 | # if you are writting a file it dont mean the file should exist
st = """
Java
A suite of computer software products and specifications from Sun Microsystems
for developing apps that can run on many different types of computers.
"""
# write
f = open('/Users/jacksonjegatheesan/PycharmProjects/meena/file_operations/write/test.txt','w')
f.write(st)
f.close()
# append
f = open('/Users/jacksonjegatheesan/PycharmProjects/meena/file_operations/write/test_two.txt','a')
f.write(st)
f.close() |
68da4f7f9003cc013a229ad141839bfcb801a75f | sendurr/spring-grading | /submission - lab5/set2/KAITLYN CALLAHAN SHEREYK_9399_assignsubmission_file_Lab5/lab5/Q2.py | 289 | 3.703125 | 4 | def printstar(n):
print '*'*n
def printstarx(n, row=1):
default=1
for i in range(row):
printstar(n) # call printstar function row number of times
printstarx(10)# print star of lenth n and in 4 row
printstarx(10,5)# print stars of length 18 and in one row (default value of row = 1) |
ebe83d3d4e9e3ffb5ba6110cb4878e2eab888abf | suhas456/suvvi | /vtweetp.py | 656 | 3.703125 | 4 | #tweeting using python
import tweepy
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
def main():
# Fill in the values from ur tweeter a/c
cfg = {
"consumer_key" : "yznfje72iVFnCKdQRS7JlQT10",
"consumer_secret" : "KNsnNZmpIrzqJ8A90yu3U13UzA2jaxOwQ8ag5DBSexCgeS4ZxT",
"access_token" : "919291897146884097-5DGqfMHFuUbUplu3Ozoe5mE6TKoLwA9",
"access_token_secret" : "xk1hNFF4mt9EoZIeNa3covFAlEeJ7wBNkD3aowyOJpBr3"
}
api = get_api(cfg)
tweet = "hi"
status = api.update_status(status=tweet)
# Yes, tweet is called 'status' rather confusing
if __name__ == "__main__":
main()
print('DONE')
|
daf0db3d3c8ff11e5a76ad7bc2528a281a73fccb | localsnet/Python-Learn | /PCC/ch9/95login_attempts.py | 1,340 | 4.09375 | 4 | #!/usr/bin/python3
class User():
def __init__(self, first_name, last_name):
"""Initialize name and age attributes."""
self.first_name = first_name
self.last_name = last_name
self.age = 0
self.gender = ""
self.login_attempts = 0
##Increment method
def increment_login(self):
""" Method increments the value of login_attempts by 1"""
self.login_attempts += 1
##Reset method
def reset_login_attempts(self):
"""Method resets the value of login_attempts to 0"""
self.login_attempts = 0
#Describe user method
def describe_user(self):
"""Describe and summarize all attributes in one place"""
print("first name: " + self.first_name.title() + "\nlast name: " + self.last_name.title() + "\nage:" + str(self.age) + "\ngender: " + str(self.gender) + "Logged attempts: " + str(self.login_attempts) + "\n")
#Greet user method
def greet_user(self):
"""Personalized greeting to the user """
print("Your file here, dear user: "+ self.first_name)
#Specify opt params method:
def specify_opt(self, age, gender):
"""Optionals params"""
self.age = age
self.gender = gender
#Instance1
user1 = User('John', 'Doe')
user1.specify_opt(25,'male')
user1.greet_user()
user1.describe_user()
user1.increment_login()
user1.increment_login()
user1.describe_user()
user1.reset_login_attempts()
user1.describe_user()
|
8fcbf12038249929fc173fccc73b1a31b51e900d | Rokoshan/CP3-Komkrit-Visetkhumphai | /Assignment/Exercise8_Komkrit_V.py | 1,598 | 3.9375 | 4 | usernameInput = input("Username :")
passwordInput = input("Password :")
username = "Komkrit"
password = "12345"
if usernameInput == username and passwordInput == password:
print(" ยินดีต้อนรับเข้าสู่ร้านของเรา ")
print("------- Bank Shop -------")
print("กรุณาเลือกรายการสินค้าที่ท่านต้องการ")
print("1. Apple ราคาลูกละ 10 บาท")
print("2. Banana ราคาลูกละ 5 บาท")
print("3. Orange ราคาลูกละ 10 บาท")
userSelected = int(input(">>"))
qty = 0
if userSelected == 1:
qty = int(input("กรุณาระบุจำนวนที่ท่านต้องการซื้อ >>"))
print("Total = ", qty*10)
print("ขอบคุณที่ใช้บริการ")
elif userSelected == 2:
qty = int(input("กรุณาระบุจำนวนที่ท่านต้องการซื้อ >>"))
print("Total = ", qty * 5)
print("ขอบคุณที่ใช้บริการ")
elif userSelected == 3:
qty = int(input("กรุณาระบุจำนวนที่ท่านต้องการซื้อ >>"))
print("Total = ", qty * 10)
print("ขอบคุณที่ใช้บริการ")
else:
print("รหัสผ่าน หรือ Username ไม่ถูกต้อง") |
d512af493cb803cdf1258b184db67468d232faca | dkowsikpai/s1python | /Python/list_fibo.py | 131 | 3.578125 | 4 | listf=[0,1]
n=int(input("Enter the limit: "))
for i in range(2,n+1):
listf.append(listf[i-2]+listf[i-1])
print(listf)
input() |
49f4b36a143cbbfdb52cd59ebce569f984b985bc | ChrisMiller83/python-101 | /hello2.py | 201 | 4.15625 | 4 |
name = input('What is your name? '.upper())
print("HELLO, " + name.upper(),'!')
countLetters = len(name)
greeting = (f"Your name has {countLetters} letters in it! Awesome!")
print(greeting.upper()) |
03fc1dd1a2b0510ce6d206a45ce5ab487ee7a1ad | Crucialjun/HelloWorldPython | /practice+part+1.py | 674 | 4.25 | 4 | price_product_1=input("What is the price of product 1:")
quantity_product_1=input("What will be the quantity of product 1:")
price_product_2=input("What is the price of product 2:")
quantity_product_2=input("What will be the quantity of product 2:")
price_product_3=input("What is the price of product 3:")
quantity_product_3=input("What will be the quantity of product 3:")
result_product_1=float(price_product_1)*float(quantity_product_1)
result_product_2=float(price_product_2)*float(quantity_product_2)
result_product_3=float(price_product_3)*float(quantity_product_3)
result=result_product_1+result_product_2+result_product_3
print("Your final price is "+str(result)) |
3b98e20d5e25a6df2b95ebd259e55910a03dbcbb | pedantic79/Exercism | /python/darts/darts.py | 207 | 3.609375 | 4 | def score(x, y):
dist_squared = x*x + y*y
if dist_squared > 100:
return 0
elif dist_squared > 25:
return 1
elif dist_squared > 1:
return 5
else:
return 10
|
ec10fd43b4f7ac7da6b49222d25b57c19eaeb3a7 | sheepolata/GraphEngine | /main.py | 3,306 | 3.546875 | 4 | # import the pygame module, so you can use it
import pygame
from pygame.locals import *
import random
import numpy as np
import drawer
import ggraph
import graphdisplay as gd
import console
GlobalLog = console.Console(head="Head, ", tail=", tail")
InfoConsole = console.Console()
# define a main function
def main():
# define a variable to control the main loop
running = True
graph = ggraph.gGraph(node_type=ggraph.gNode)
display = gd.GraphDisplay(graph)
display.set_log(GlobalLog)
display.set_info(InfoConsole)
nb_node = 30
# sparseness = random.randint(nb_node-1, int(nb_node*(nb_node-1)/2.0))
sparseness = nb_node-1
collision_on = True
apply_forces_on = True
def update_info():
InfoConsole.clear()
InfoConsole.log("This is the GraphEngine example, hope you enjoy it!")
InfoConsole.log("Node number: {}".format(len(graph.nodes)))
InfoConsole.log("Edge number: {}".format(len(graph.edges)))
InfoConsole.log("Random number: {:.3f}".format(random.random()))
InfoConsole.log("Press SPACE to display one log line.")
def generate():
# graph.complete_graph(nb_node)
# graph.random_connected_graph(nb_node, random.randint(nb_node-1, nb_node*(nb_node-1)/2.0), True)
# graph.random_connected_graph(nb_node, sparseness, True)
graph.random_connected_graph(nb_node, sparseness, False)
# graph.random_tree_graph(nb_node)
for n in graph.nodes:
n.info["pos"] = [random.randint(0, display.graph_surface_size[0]), random.randint(0, display.graph_surface_size[1])]
n.info["radius"] = 12
# n.info["color"] = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
n.info["color"] = (0, 0, 0)
graph.setDelaunay()
# print(graph.serialise())
generate()
# print(graph.serialise())
selected = None
# main loop
while running:
t = pygame.time.get_ticks()
# deltaTime in seconds.
# deltaTime = (t - getTicksLastFrame) / 1000.0
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
elif event.type == pygame.KEYDOWN:
if event.key == K_r:
graph.reset()
generate()
if event.key == K_c:
collision_on = not collision_on
if event.key == K_SPACE:
# apply_forces_on = not apply_forces_on
GlobalLog.log("This is a logged line and a random number : {:.2f}".format(random.random()))
if event.key == K_s:
for n in graph.nodes:
n.info["pos"] = [random.randint(0, display.graph_surface_size[0]), random.randint(0, display.graph_surface_size[1])]
if event.key == K_p:
for n in graph.nodes:
n.info["pos"] = [display.graph_surface_size[0]/2, display.graph_surface_size[1]/2]
if event.key == K_d:
graph._draw_delaunay = not graph._draw_delaunay
graph.computeDelaunay()
if apply_forces_on:
for n in graph.nodes:
n.applyForces(collision=collision_on)
update_info()
InfoConsole.push_front("{:.1f} FPS".format(display.clock.get_fps()))
display.main_loop_end()
# run the main function only if this module is executed as the main script
# (if you import this as a module then nothing is executed)
if __name__=="__main__":
# call the main function
main() |
a6f73728a83ea22a17f3d36102977bfaea74138a | irfan-ansari-au28/Python-Pre | /Doubt/kanhu_ll_palindrome.py | 1,061 | 3.8125 | 4 | #Q-2 ) Palindrome Linked List
#Answer:-
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def isPalindrome(self, head):
if not head or not head.next:
return True
slow = fast = head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
prev = None
while slow:
temp = slow
slow = slow.next
temp.next = prev
prev = temp
while prev:
if prev.val != head.val:
return False
prev = prev.next
head = head.next
return True
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(2)
head.next.next.next = ListNode(1)
# print(head.next.next.val)
sol = Solution()
print(sol.isPalindrome(head)) |
364c0b9226188515f66ef63c77eee0aaf3026ffe | varlack1021/HarvardX-Data-Science | /Discrete Probaility/monty_hall_problem.py | 1,215 | 4.25 | 4 | '''
Say there are three doors and one door is the correct door.
Once a person chooses a door, one wrong door is then revealed.
The person then has two remaining doors to choose from and can either switch their choice
and choose the other door or stay with their original door.
Question---
Is the probablity higher is they switch their choice or if the stay with their original choice?
This program does not prove mathematical only using a Monte Carlo Simulation
'''
def monty_hall_problem():
no_change_total = 0
change_total = 0
limit = 10000
for i in range(limit):
doors = [0, 0, 0]
correct = random.randrange(3)
choice = random.randrange(3)
doors[correct] = 1
if doors[choice] == 1:
no_change_total += 1
print("Not changing choices results in a proability of {} ".format(no_change_total/limit))
for i in range(limit):
doors = [0, 0, 0]
correct = random.randrange(3)
choice = random.randrange(3)
if choice == correct: #If the person picked right then when they switch it will be incorrect
continue
else:
change_total +=1 #If person picked wrong then when they switch it will be correct
print("Changing results in a proability of {}".format(change_total/limit)) |
b6381838ea6c9d0915aaa451e9c46fd32858f2a2 | kvharini/Harni | /FindFileCount.py | 1,089 | 3.671875 | 4 | import os
import math
def findDirectories(root_dir, keyword):
outputArray={}
for root, Dirs, files in os.walk(root_dir):
for Directory in Dirs:
if(Directory is not None):
fileCount =FindFilecount(Directory)
if(fileCount is not None):
print("Filecount=%d"%fileCount)
outstr =os.path.abspath(Directory)
outputArray={outstr, fileCount}
print ("outputArray%s"%outputArray)
print("Directory= %s\n"%Directory)
findDirectories(Directory, keyword)
def FindFilecount(root_dir):
fileCount =0
print(" inside findfile Root_dir=%s"%root_dir)
for root, Dirs, files in os.walk(root_dir):
files= next(os.walk(root_dir))[2]
if(files is not None):
#print("Filename= %s\n"%files)
fileCount=len(files)
print("FileCOUNT= %s\n"%fileCount)
#for file1 in files:
return fileCount
findDirectories("C:\Python27","txt")
|
924c3db6848f1d81c4195d6bf6f2f8def4812fe2 | projeto-de-algoritmos/Divide_Hanoi_tower | /hanoi.py | 368 | 3.921875 | 4 | def TowerOfHanoi(n , fromT, toT, aux):
if n == 1:
print("Move disk 1 from tower",fromT,"to tower",toT )
return
TowerOfHanoi(n-1, fromT, aux, toT)
print("Move disk",n,"from tower",fromT,"to tower",toT)
TowerOfHanoi(n-1, aux, toT, fromT)
n = input("Number of disks in your hanoi tower: ")
TowerOfHanoi(int(n), 'A', 'C', 'B')
|
bb5c403f43b460b3398149f6e334a6e01198a40f | phanithi/PythonSamples | /PythonSamples/src/com/python/samples/strings/RepeatedCharacterFinder.py | 365 | 3.640625 | 4 | '''
Created on Apr 13, 2017
@author: Phanithi
'''
# Find 1st repeated character. duplicate comment
def findRepeatedChar(s):
print('Inside function : findRepeatedChar()')
if(len(s) == 1) : return s
st = set()
for ch in s:
if (ch in st):
return ch
else:
st.add(ch)
print(findRepeatedChar("Hellooo")) |
8aa61193db7a6dc88fa247fd76fc144c071934df | spirit0908/pyTimer | /timer.py | 2,276 | 3.578125 | 4 | #!/usr/bin/python
#import Tkinter
from tkinter import *
from tkinter import ttk
from tkinter import font
import time
import datetime
#import wiringPi2 as wiringpi
import RPi.GPIO as GPIO
global endTime
global timer_M
global timer_S
global Timer_val
def quit(*args):
root.destroy()
def show_time():
# Get the time remaining until the event
# remainder = endTime - datetime.datetime.now()
# remove the microseconds part
# remainder = remainder - datetime.timedelta(microseconds=remainder.microseconds)
# Show the time left
# txt.set(remainder)
# timer_M = 1
global timer_M
global timer_S
global timer_val
#Read GPIO input pin 40-BCM21-wiringpi29
myinput = GPIO.input(21)
# print(myinput)
if myinput == 1:
if timer_S >= 59:
timer_S = 0
timer_M = timer_M + 1
else:
timer_S = timer_S + 1
#End if myinput == 1
#txt.set(timer_H)
#txt.set(timerm)
if timer_M<timer_val:
var_M = timer_val - timer_M - 1
var_S = 60-timer_S-1
txt.set("{:02d}:{:02d}".format(var_M, var_S))
elif timer_M==timer_val and timer_S==0:
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="red", background="black")
lbl.place(relx=0.5, rely=0.5, anchor=CENTER)
txt.set("Total time \n {:02d}:{:02d}". format(timer_M, timer_S))
else:
txt.set("Total time \n {:02d}:{:02d}". format(timer_M, timer_S))
# Trigger the countdown after 1000ms
root.after(1000, show_time)
# Use tkinter lib for showing the clock
root = Tk()
root.attributes("-fullscreen", True)
root.configure(background='black')
root.bind("x", quit)
root.after(1000, show_time)
# Set the end date and time for the countdown
endTime = datetime.datetime(2017, 9, 19, 9, 0, 0)
#endTime = datetime.datetime.now() + datetime.datetime(0, 0, 0, 0, 45, 0)
timer_val = 40
timer_M = 00
timer_S = -1
GPIO.setmode(GPIO.BCM)
#Setup the port 29 as inout (0)
GPIO.setup(21, GPIO.IN)
fnt = font.Font(family='Helvetica', size=60, weight='bold')
txt = StringVar()
lbl = ttk.Label(root, textvariable=txt, font=fnt, foreground="green", background="black")
lbl.place(relx=0.5, rely=0.5, anchor=CENTER)
root.mainloop()
|
750d5d783685fac09cdae6991017d5febecddb44 | renanaquinno/python3 | /#ATIVIDADES_URI/#AtividadeURI_3_Iterações/AtividadeURI_3_Intereacoes_1143_quadrado_ao_cubo.py | 247 | 3.9375 | 4 | #entrada
n = int(input())
contador = 1
# processamento
def quadrado_cubo (n, contador):
while contador <= n:
print(contador, contador*contador, contador**3)
contador += 1
#saida
quadrado_cubo(n, contador) |
ad03024b2e54ca4368dd0eb01d01db89e75eafea | capslockd/test | /test_code_python/randomizer.py | 233 | 3.71875 | 4 | import random
print(random.randrange(10, 20))
x = ['a', 'b', 'c', 'd', 'e']
# Get random choice
print(random.choice(x))
# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)
# Print random element
print(random.random()) |
6ae70a82e4e9534eb5ecbeb11f977d5a4a7bde80 | njoki2017/Age-calculator | /age calculator.py | 426 | 4.15625 | 4 | from datetime import date
import calendar
AGE = int(input('enter your age: '))
YEAR = int(input('enter the current year: '))
DOB= int(input('date of birth(1-31): '))
month = int(input('month(1-12): '))
current_date = 18,5
if DOB >18 and month > 5:
b = YEAR - AGE - 1
else:
b = YEAR - AGE
birthday = date(b,month,DOB)
print(birthday.strftime('you were born on %d %A %b %Y'))
input('end of the program')
|
c807d115d66bd83c1628c9312c24fac282af5259 | guilhermeagostinho22/exercicios-e-exemplos | /Pyton/exercicio8.py | 113 | 3.90625 | 4 | kelvin = float(input("Digite a temperatura em kelvin: "))
print("temperatura em celcius é: ", (kelvin - 273.15)) |
a06e68bb473d20d26fdf2f25fc01678e2d9933c8 | DziadoszWiktor/pp1 | /02-ControlStructures/Mandat.py | 265 | 3.546875 | 4 | a = int(input("Podaj limit predkosci (km/h): "))
b = int(input("Podaj predkosc pojazdu (km/h): "))
if b<=60:
m=(b-a)*5
print("Mandat (zl): ",m)
if b<=50:
print("Mandat (zl): 0 ")
if b>60:
n=(b-a)*5*1.5
print("Mandat (zl): ",n)
|
215967a30e5f451c6ca35442f42756175bbc4e74 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/TOM-Lambda/CSEU4_Intro_Python_GP/rps.py | 2,459 | 4.15625 | 4 | import random
# Create a rock/paper/scissors REPL loop
# Have a computer AI to play against us
# Keep track of the score
# Rules: r beats s, s beats p, p beats r
wins = 0
losses = 0
ties = 0
<<<<<<< HEAD
choices = ['r', 'p', 's']
=======
choices = ["r", "p", "s"]
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
while True:
print(f"Score: {wins} - {losses} - {ties}")
cmd = input("\nChoose r/p/s: ")
# AI picks a random choice from r/p/s
ai_choice = choices[random.randrange(3)]
<<<<<<< HEAD
print (f"Computer chose {ai_choice}")
if cmd == "r":
if ai_choice == 'p':
losses += 1
print("You lose")
elif ai_choice == 's':
wins += 1
print("You win!")
elif ai_choice == 'r':
ties += 1
print("You tie.")
elif cmd == "p":
if ai_choice == 's':
losses += 1
print("You lose")
elif ai_choice == 'r':
wins += 1
print("You win!")
elif ai_choice == 'p':
ties += 1
print("You tie.")
elif cmd == "s":
if ai_choice == 'r':
losses += 1
print("You lose")
elif ai_choice == 'p':
wins += 1
print("You win!")
elif ai_choice == 's':
=======
print(f"Computer chose {ai_choice}")
if cmd == "r":
if ai_choice == "p":
losses += 1
print("You lose")
elif ai_choice == "s":
wins += 1
print("You win!")
elif ai_choice == "r":
ties += 1
print("You tie.")
elif cmd == "p":
if ai_choice == "s":
losses += 1
print("You lose")
elif ai_choice == "r":
wins += 1
print("You win!")
elif ai_choice == "p":
ties += 1
print("You tie.")
elif cmd == "s":
if ai_choice == "r":
losses += 1
print("You lose")
elif ai_choice == "p":
wins += 1
print("You win!")
elif ai_choice == "s":
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
ties += 1
print("You tie.")
elif cmd == "q":
print("Goodbye!")
break
else:
<<<<<<< HEAD
print("I do not understand that command.")
=======
print("I do not understand that command.")
>>>>>>> 23fb4d348bb9c7b7b370cb2afcd785793e3816ea
|
953b340846d1a0f6d21e42bea8bd5340f454bbbe | RodolfoDelgadoDev/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/12-roman_to_int.py | 797 | 3.65625 | 4 | #!/usr/bin/python3
def roman_to_int(roman_string):
if type(roman_string) is not str or roman_string is None:
return 0
ro = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
con = 0
rev = False
lon = len(roman_string)
for n in range(lon):
if rev is True:
rev = False
if n < lon:
continue
else:
break
if n < lon - 1:
if ro.get(roman_string[n+1]) > ro.get(roman_string[n]):
var = ro.get(roman_string[n])
con = con + ro.get(roman_string[n + 1]) - var
rev = True
else:
con = con + ro.get(roman_string[n])
else:
con = con + ro.get(roman_string[n])
return con
|
0438667447eb04ee2e25877290625d86adf4946b | 7Aishwarya/HakerRank-Solutions | /Data_Structures/queues/truck_tour.py | 1,985 | 4.28125 | 4 | '''Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to N-1 (both inclusive).
You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular
petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.
Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps.
Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop
at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.
Input Format
The first line will contain the value of N.
The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump.
Output Format
An integer which will be the smallest index of the petrol pump from which we can start the tour.
Sample Input
3
1 5
10 3
3 4
Sample Output
1
'''
#!/bin/python3
import os
import sys
#
# Complete the truckTour function below.
#
def truckTour(petrolpumps):
#
# Write your code here.
#
p = 0
n = 0
temp = 0
i = 0
while(i != (len(petrolpumps)-1)):
if i == 0:
p = p + petrolpumps[i][0]
n = n + petrolpumps[i][1]
i+=1
if p > n:
p = p + petrolpumps[i][0]
n = n + petrolpumps[i][1]
i+=1
else:
temp+=1
i = temp
p = petrolpumps[temp][0]
n = petrolpumps[temp][1]
return temp
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
petrolpumps = []
for _ in range(n):
petrolpumps.append(list(map(int, input().rstrip().split())))
result = truckTour(petrolpumps)
fptr.write(str(result) + '\n')
fptr.close()
|
1d0c573ffb1053bd49ee3a8e6b58e9abd9a3fe3d | srungarapugopikrishna/problems | /bit_wise_and.py | 951 | 3.578125 | 4 |
# def bit_wise():
# n = int(raw_input())
# for _ in range(n):
# ip = raw_input()
# A = int(ip.split(' ')[0])
# B = int(ip.split(' ')[1])
# sol = A
# for i in range(A, B+1):
# sol = sol & i
# if sol == 0:
# break
# print sol
# print bit_wise()
def significant_bit_position(n):
sb_position = -1
while n > 0:
n = n >> 1
sb_position += 1
return sb_position
def bit_wise_and(A, B):
res = 0
while A > 0 and B > 0:
sb_position1 = significant_bit_position(A)
sb_position2 = significant_bit_position(B)
if (sb_position1 != sb_position2):
break
sb_value = (1 << sb_position1)
res = res + sb_value
A = A - sb_value
B = B - sb_value
return res
n = int(raw_input())
for _ in range(n):
ip = raw_input()
A = int(ip.split(' ')[0])
B = int(ip.split(' ')[1])
print(bit_wise_and(A, B))
|
573a596f0811fd5063018db6dd11204d053572c5 | Cooleyy/AdventCode2020 | /day2/day2solution.py | 782 | 3.625 | 4 | #!/usr/bin/env python3
import sys
passwordsFile = open (sys.argv[1], 'r')
passwordAndRules = passwordsFile.read().splitlines()
counter = 0
for item in passwordAndRules:
passAndRule = item.split()
passAndRule[0] = list(map(int, passAndRule[0].split("-")))
passAndRule[1] = passAndRule[1][0]
passwordAndRules[counter] = passAndRule
counter += 1
numValid = 0
for password in passwordAndRules:
##numOfLetter = password[2].count(password[1])
##if numOfLetter < password[0][0] or numOfLetter > password[0][1]:
if (password[2][password[0][0]-1] == password[1] or password[2][password[0][1]-1] == password[1]) and not (password[2][password[0][0]-1] == password[1] and password[2][password[0][1]-1] == password[1]):
numValid += 1
print(numValid)
|
abeee882a38315b1e33d00bc2e98f88ec1358034 | yorch-el-profe/TECP0006FSPYOL2101 | /sesion06/inventario_tienda.py | 1,412 | 3.96875 | 4 | class Producto:
def __init__(self, nombre, precio):
self.nombre = nombre
self.precio = precio
def __str__(self):
return "{} - ${}".format(self.nombre, self.precio)
inventario = []
def agregar_producto():
print("Ingresa el nombre:")
nombre = input()
print("Ingresa el precio:")
precio = input()
inventario.append(Producto(nombre, precio))
almacenar_producto(nombre, precio)
print("\nProducto agregado")
def ver_productos():
print("Inventario:\n")
for producto in inventario:
print(producto)
# 1. Cargar el inventario del archivo "inventario.txt"
def cargar_productos():
with open("archivos/inventario.txt") as archivo:
lineas = archivo.read().splitlines()
for linea in lineas:
linea_split = linea.split("|")
inventario.append(Producto(linea_split[0], linea_split[1]))
# 2. Almacenar el inventario en el mismo archivo
def almacenar_producto(nombre, precio):
with open("archivos/inventario.txt", "a") as archivo:
archivo.write("\n{}|{}".format(nombre, precio))
salir = False
cargar_productos()
while not salir:
print("\n")
print("1. Agregar productos")
print("2. Lista de productos")
print("3. Salir")
opcion = input()
print("\n")
if opcion == "2":
ver_productos()
elif opcion == "1":
agregar_producto()
elif opcion == "3":
salir = True
else:
print("Opción inválida")
print("Cerrrando sistema") |
585daa66a34fccafbb8efeee1a31177b3306d967 | ShivLakhanpal/CS-UY-1114 | /Lab Work/Lab 8.py | 2,048 | 3.953125 | 4 | #1a
print("Problem 1a: ")
n = 10
def fib(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return fib(n-1) + fib(n-2)
print(fib(n-10),fib(n-9),fib(n-8),fib(n-7),fib(n-6),fib(n-5),fib(n-4),fib(n-3),fib(n-2),fib(n-1))
#1b
print("Problem 1b: ")
number = int(input("Please enter a number: "))
def fib(n):
if n == 1:
return 1
elif n == 0:
return 0
else:
return fib(n-1) + fib(n-2)
print("The", str(number)+"th", "Fibonacci number is:",fib(number))
#1c
print("Problem 1c: ")
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
fib_seq = int(input("Please enter a number: "))
if fib_seq <= 0:
print("Plese enter a positive integer")
else:
print()
for num in range(fib_seq):
print(fib(num))
def find(some_string, substring, start, end):
length = len(substring)
index = end-length
if length == 1:
for curr in range(start,end):
if some_string[curr: curr+length]==substring:
return curr
else:
return 1
if length>1:
for i in range(0,index+1):
if substring==some_string[i:i+length]:
return i
#NUMERO 2B
def multi_find(some_string, substring, start, end):
first=find(some_string, substring, start, end)
if first==-1:
return first
if first>0:
length=len(substring)
index=end-length
res=''
for i in range(0,index+1):
if substring==some_string[i:i+length]:
res+=str(i)+','
return res
def main():
some_string = str(input("Enter string: "))
substring = str(input("Enter substring: "))
start = int(input("Enter a start: "))
end = int(input("Enter an end: "))
res = find(some_string, substring, start, end)
print(res)
res = multi_find(some_string, substring, start, end)
print(res)
main()
|
8eae022df50cf8cf7670664fbc030f4240a055a3 | becca6223/Tech_Prep | /recursion/pairParens.py | 935 | 4.125 | 4 | def getAllPairParens(n):
"""
n: n pairs of parentheses
"""
if n == 0:
return None
result = []
getAllPairParensVisit(n, 0, result, "")
return result
def getAllPairParensVisit(n, openLeft, result, string):
"""
n: remaining pairs
openLeft: number of left parentheses
result (list): contains all the possible valid n pairs of parentheses
string: current parentheses string
"""
if n == openLeft and n == 0:
#no more remaining pairs (n = 0) and it's balanced pairs (openLeft = 0)
result.append(string)
else:
if openLeft <= n:
#can still add ( cuz still have remaining pairs left
getAllPairParensVisit(n, openLeft + 1, result, string + "(")
if openLeft != 0:
#can add ) cuz there is at least one (
getAllPairParensVisit(n - 1, openLeft - 1, result, string + ")")
if __name__ == "__main__":
n = input("Enter number of pairs of parentheses: ")
result = getAllPairParens(int(n))
print(result)
|
ef3c1af06dad30e5a132fc26169ab89ba61f963c | J0e-Kozsuch/Monte-Carlo-Poker-Probabilities | /Poker Simulations.py | 19,916 | 3.65625 | 4 | import numpy as np
import pandas as pd
import math as m
import os
import random as r
def reformat_numbers(x):
'''
Allign one and two digit numbers to consistently have two as a string
'''
x=str(x).strip()
if len(x)<2:
return '0'+x
return x
class best_poker_hand:
def __init__(self,a_deck,a_hand,after_what=None):
self.flop=a_deck.flop
self.turn=a_deck.turn
self.river=a_deck.river
self.hand=a_hand.cards
self.best_hand=None
self.first=None
self.second=None
self.third=None
self.fourth=None
self.fifth=None
self.number=None
if self.hand==[]:
raise Exception("Trying to calculate best hand yet hand has no cards.")
# Assemble poker hand given after which deal the round has been played.
if after_what==None:
if self.flop==[]:
self.cards=self.hand
elif self.turn==None:
self.cards=self.hand+self.flop
elif self.river==None:
self.cards=self.hand+self.flop+[self.turn]
else:
self.cards=self.hand+self.flop+[self.turn]+[self.river]
elif str(after_what).lower()=="deal":
self.cards=self.hand
elif str(after_what).lower()=="flop":
self.cards=self.hand+self.flop
elif str(after_what).lower()=="turn":
self.cards=self.hand+self.flop+[self.turn]
elif str(after_what).lower()=="river":
self.cards=self.hand+self.flop+[self.turn]+[self.river]
else:
raise Exception("Calculating best hand variable after_what must be ['deal','flop','turn','river']")
def calculate_best_hand(self):
'''
Determine best hand (string) and the top cards that contribute to its scoring.
'''
# cards_df is rank and suit of cards in poker hand, sorted by rank
cards_df=pd.DataFrame(columns=['rank','suit'])
for a_card in self.cards:
cards_df=pd.concat((cards_df,pd.DataFrame(data=[[a_card.rank,a_card.suit]],columns=['rank','suit'])),axis=0)
cards_df.sort_values(['rank'],inplace=True,ascending=False)
cards_df.reset_index(inplace=True,drop=True)
# rank variables are used to determine pairings.
rank_count_series=cards_df['rank'].value_counts()
first_rank=rank_count_series.index[0]
first_count=rank_count_series.iloc[0]
self.first=first_rank
unique_ranks=rank_count_series.shape[0]
# If the highest number of recurrence of one rank is 1, start with high card.
if first_count==1:
self.best_hand='High Card'
rank_list=list(rank_count_series.index[1:])
self.second=rank_count_series.index[1]
if unique_ranks>2:
self.second=rank_list[0]
self.third=rank_list[1]
self.fourth=rank_list[2]
self.fifth=rank_list[3]
else:
return None
# If the highest number of recurrence of one rank is 2, start with pair and check for two pair.
elif first_count==2:
if rank_count_series.iloc[1]==1:
self.best_hand='Pair'
if unique_ranks>1:
rank_list=list(rank_count_series.index[1:])
rank_list.sort(reverse=True)
self.second=rank_list[0]
self.third=rank_list[1]
self.fourth=rank_list[2]
else:
return None
if rank_count_series.iloc[1]==2:
self.best_hand='Two Pair'
if rank_count_series.iloc[2]==2:
pair_list=list(rank_count_series.index[:3])
pair_list.sort(reverse=True)
self.first=pair_list.pop(0)
self.second=pair_list.pop(0)
non_pair_list=list(rank_count_series.index[3:])+pair_list
non_pair_list.sort(reverse=True)
self.third=non_pair_list[0]
return None
else:
rank_list=list(rank_count_series.index[:2])
rank_list.sort(reverse=True)
self.first=rank_list[0]
self.second=rank_list[1]
self.third=max(list(rank_count_series.index[2:]))
# If the highest number of recurrence of one rank is 3, start with three of a kind and check for three of a kind.
elif first_count==3:
if rank_count_series.iloc[1]==1:
self.best_hand='Three Kind'
rank_list=list(rank_count_series.index[1:])
rank_list.sort(reverse=True)
self.second=rank_list[0]
self.third=rank_list[1]
if rank_count_series.iloc[1]==2:
self.best_hand='Full House'
if rank_count_series.iloc[2]==2:
self.second=max(rank_count_series.index[1],rank_count_series.index[2])
return None
self.second=rank_count_series.index[1]
return None
if rank_count_series.iloc[1]==3:
self.best_hand='Full House'
self.first=max(list(rank_count_series.index[0:2]))
self.second=max(list(rank_count_series.index[0:2]))
return None
# If the highest number of recurrence of one rank is 4, four of a kind is the best hand possible.
elif first_count==4:
self.best_hand='Four Kind'
rank_list=list(rank_count_series.index[1:])
rank_list.sort(reverse=True)
self.second=rank_list[0]
return None
# If there are less than 5 unique ranks, flushes and straights are not possible.
if unique_ranks<5:
return None
#Check for flush by looking at suit value counts.
suit_count_df=cards_df['suit'].value_counts()
if suit_count_df.iloc[0]>4:
flush_suit=suit_count_df.index[0]
flush_cards_df=cards_df[cards_df['suit']==flush_suit]
flush_cards_list=flush_cards_df['rank'].tolist()
flush_cards_list.sort(reverse=True)
self.first=flush_cards_list[0]
self.second=flush_cards_list[1]
self.third=flush_cards_list[2]
self.fourth=flush_cards_list[3]
self.fifth=flush_cards_list[4]
self.best_hand='Flush'
# Before checking for straight, create duplicate Ace row with rank 1 rather than 14
for i in self.cards:
if i.rank==14:
cards_df=pd.concat((cards_df,pd.DataFrame(data=[[1,i.suit]],columns=['rank','suit'])),axis=0)
cards_df.reset_index(drop=True,inplace=True)
# If flush was found, check for straight flush
if self.best_hand=='Flush':
flush_cards_df=cards_df[cards_df['suit']==flush_suit]
flush_cards_list=flush_cards_df['rank'].tolist()
flush_cards_list.sort(reverse=True)
flush_cards_count=len(flush_cards_list)
streak=1
high_card=flush_cards_list[0]
for i in range(1,flush_cards_count):
if flush_cards_list[i-1]-flush_cards_list[i]>1:
if flush_cards_count-i<5:
return None
high_card=flush_cards_list[i]
streak=1
else:
streak+=1
if streak==5:
self.best_hand='Straight Flush'
self.first=high_card
return None
#Cheack for straight
cards_list=cards_df['rank'].unique().tolist()
cards_list.sort(reverse=True)
cards_count=len(cards_list)
streak=1
high_card=cards_list[0]
for i in range(1,cards_count):
if cards_list[i-1]-cards_list[i]>1:
if cards_count-i<5:
return None
high_card=cards_list[i]
streak=1
else:
streak+=1
if streak==5:
self.best_hand='Straight'
self.first=high_card
self.second=None
self.third=None
self.fourth=None
self.fifth=None
return None
def calculate_hand_number(self):
'''
Calculate a number reflecting hand strength for comparison.
The better the best poker hand, the higher the exponent in 10^b.
The tie-breaking cards are added as digits below the highest value.
'''
if self.number!=None:
return None
num_str=''
if self.best_hand==None:
self.calculate_best_hand()
if self.best_hand=='High Card':
for i in [self.first,self.second,self.third,self.fourth,self.fifth]:
if i==None:
num_str+='00'
else:
num_str+=reformat_numbers(i)
elif self.best_hand=='Pair':
for i in [self.first,self.second,self.third,self.fourth]:
if i==None:
num_str+='00'
else:
num_str+=reformat_numbers(i)
num_str+='000'
elif self.best_hand=='Two Pair':
for i in [self.first,self.second,self.third]:
if i==None:
num_str+='00'
else:
num_str+=reformat_numbers(i)
num_str+='000000'
elif self.best_hand=='Three Kind':
for i in [self.first,self.second,self.third]:
if i==None:
num_str+='00'
else:
num_str+=reformat_numbers(i)
num_str+='0000000'
elif self.best_hand=='Straight':
for i in [self.first]:
num_str+=reformat_numbers(i)
num_str+='000000000000'
elif self.best_hand=='Flush':
for i in [self.first,self.second,self.third,self.fourth,self.fifth]:
num_str+=reformat_numbers(i)
num_str+='00000'
elif self.best_hand=='Full House':
for i in [self.first,self.second]:
num_str+=reformat_numbers(i)
num_str+='000000000000'
elif self.best_hand=='Four Kind':
for i in [self.first,self.second]:
num_str+=reformat_numbers(i)
num_str+='0000000000000'
elif self.best_hand=='Straight Flush':
for i in [self.first]:
num_str+=reformat_numbers(i)
num_str+='0000000000000000'
self.number=int(num_str)
class card:
def __init__(self,suit,rank):
if suit not in ['H','S','C','D']:
raise Exception( "Card has incorrect suit "+str(suit)+", must be within ['H','D','C','S'].")
if rank not in list(range(2,15)):
raise Exception("Card has incorrect rank "+str(rank)+", must be integer 2-14")
self.suit=suit
self.rank=rank
class hand:
def __init__(self):
self.cards=[]
self.best_hand=None
self.hand_number=None
self.first=None
self.second=None
self.third=None
self.fourth=None
self.fifth=None
def receive_cards(self,deck):
''' Deal oneself cards given deck object.'''
if len(self.cards)>0:
raise Exception("Hand already has cards.")
self.cards.append(deck.deal_card())
self.cards.append(deck.deal_card())
def assign_best_poker_hand(self,deck):
'''
Create best poker hand object and assign best hand and hand num.
'''
var=best_poker_hand(deck,self)
var.calculate_hand_number()
self.best_hand=var.best_hand
self.first=var.first
self.second=var.second
self.third=var.third
self.fourth=var.fourth
self.fifth=var.fifth
self.hand_number=var.number
class deck:
def __init__(self):
self.cards=[]
for suit in ['H','S','C','D']:
for rank in range(2,15):
self.cards.append(card(suit,rank))
self.flop=[]
self.turn=None
self.river=None
def deal_flop(self):
'''
Deal the flop.
'''
if self.flop!=[]:
raise Exception("Flop has already been dealt")
self.flop.append(self.deal_card())
self.flop.append(self.deal_card())
self.flop.append(self.deal_card())
def deal_turn(self):
'''
Deal the turn.
'''
if self.turn!=None:
raise Exception("Turn has already been dealt")
if self.flop==[]:
raise Exception("Can't deal turn if flop has not been dealt.")
self.turn = self.deal_card()
def deal_river(self):
'''
Deal the river.
'''
if self.river!=None:
raise Exception("River has already been dealt")
if self.turn==None:
raise Exception("Can't deal river if turn has not been dealt.")
self.river = self.deal_card()
def retrieve_cards(self):
'''
Pickup all dealt cards and reset community cards.
Hands must be reset as well.
'''
self.cards=[]
for suit in ['H','S','C','D']:
for rank in range(2,15):
self.cards.append(card(suit,rank))
self.flop=[]
self.turn=None
self.river=None
def shuffle(self):
'''
Shuffle the cards currently in the deck.
'''
r.shuffle(self.cards)
deck_after_second_shuffle=[]
while len(self.cards)>0:
deck_after_second_shuffle.append(self.cards.pop(np.random.randint(0,len(self.cards))))
self.cards=deck_after_second_shuffle
def deal_card(self):
'''
Deal a card from deck.
'''
try:
return self.cards.pop(0)
except Exception as e:
print("Deal card error: "+e)
def round_simulations():
deck1=deck()
hand_dict={i:0 for i in ['Straight','High Card','Flush','Straight Flush','Four Kind','Three Kind','Pair','Two Pair','Full House']}
for players in range(MIN_PLAYERS_SIMULATED, MAX_PLAYERS_SIMULATED+1):
print("Number of Players: ____________________________ "+str(players))
hands_df=pd.DataFrame(columns=['Num Hands','Best Hand','Hand Number','First','Second',
'Card 1 Rank','Card 1 Suit','Card 2 Rank','Card 2 Suit','Won Hand',
'flop_1_rank','flop_1_suit','flop_2_rank','flop_2_suit',
'flop_3_rank','flop_3_suit','turn_rank','turn_suit',
'river_rank','river_suit'])
for i in range(SIMULATED_ROUNDS):
deck1.shuffle()
deck1.deal_flop()
deck1.deal_turn()
deck1.deal_river()
hands=[]
highest_num=0
best_hand_index=0
card1=None
card2=None
for j in range(players):
hands.append(hand())
hands[j].receive_cards(deck1)
hands[j].assign_best_poker_hand(deck1)
if hands[j].hand_number>highest_num:
best_hand_index=j
highest_num=hands[j].hand_number
tie=False
elif hands[j].hand_number==highest_num:
tie=True
best_hand=hands[best_hand_index]
if tie:
winner_val=0.5
else:
winner_val=1
new_row=pd.DataFrame(data=[[players,best_hand.best_hand,best_hand.hand_number,best_hand.first,best_hand.second,
best_hand.cards[0].rank,best_hand.cards[0].suit,
best_hand.cards[1].rank,best_hand.cards[1].suit,winner_val,
deck1.flop[0].rank,deck1.flop[0].suit,deck1.flop[1].rank,
deck1.flop[1].suit,deck1.flop[2].rank,deck1.flop[2].suit,
deck1.turn.rank,deck1.turn.suit,deck1.river.rank,deck1.river.suit]],
columns=['Num Hands','Best Hand','Hand Number','First','Second',
'Card 1 Rank','Card 1 Suit','Card 2 Rank','Card 2 Suit','Won Hand',
'flop_1_rank','flop_1_suit','flop_2_rank','flop_2_suit',
'flop_3_rank','flop_3_suit','turn_rank','turn_suit',
'river_rank','river_suit'])
hands_df=pd.concat((hands_df,new_row),axis=0)
hands.remove(best_hand)
for hand_var in hands:
if hand_var.hand_number==highest_num:
hand_outcome=0.5
else:
hand_outcome=0
new_row=pd.DataFrame(data=[[players,hand_var.best_hand,hand_var.hand_number,hand_var.first,hand_var.second,
hand_var.cards[0].rank,hand_var.cards[0].suit,
hand_var.cards[1].rank,hand_var.cards[1].suit,hand_outcome,
deck1.flop[0].rank,deck1.flop[0].suit,deck1.flop[1].rank,
deck1.flop[1].suit,deck1.flop[2].rank,deck1.flop[2].suit,
deck1.turn.rank,deck1.turn.suit,deck1.river.rank,deck1.river.suit]],
columns=['Num Hands','Best Hand','Hand Number','First','Second',
'Card 1 Rank','Card 1 Suit','Card 2 Rank','Card 2 Suit','Won Hand',
'flop_1_rank','flop_1_suit','flop_2_rank','flop_2_suit',
'flop_3_rank','flop_3_suit','turn_rank','turn_suit',
'river_rank','river_suit'])
hands_df=pd.concat((hands_df,new_row),axis=0)
deck1.retrieve_cards()
if i%5000==0:
print("Rounds Completed: "+str(i)+' / '+str(SIMULATED_ROUNDS))
hands_df.to_csv(str(players)+"_players_best_hands_with_table.csv",index=False)
SIMULATED_ROUNDS = 10000
MIN_PLAYERS_SIMULATED = 2
MAX_PLAYERS_SIMULATED = 5
round_simulations()
|
adf1bda5febdb6e0a967d53fcd48660eca99e671 | BPBO/Project1 | /build/lib/Calculadora_pkg/__main__.py | 5,907 | 3.75 | 4 | '''--------------------------------------------------------------------
Tittle: Interfaz grafica de la calculadora
Developed by: Alex Montano Rojas
Date: January of 2021
-----------------------------------------------------------------------
'''
import tkinter # Libreria que maneja el entorno grafico en python
from tkinter import *
from tkinter import messagebox
from .ArbolDeExpre import ArbolExp
class main(Frame):
"""Definicion de la clase frame para la
creacion del entorno visual"""
def __init__(self,master=None):
super().__init__(master, width=400, height=300, bg="#404040")
self.master.resizable(0,0)
self.master = master
self.master.title("Calculator")
self.pack()
self.crearWidgets()
def crearWidgets(self):
"""Crea los elementos dentro del Frame"""
#self.lbl1 = Label(self, text="f:", font=(25),
# bg="#404040", fg="white")
self.lbl2 = Label(self, text="R:", font=(25), bg="#404040",
fg="white")
self.entrada = StringVar()
self.txt1 = Entry(self, textvariable=self.entrada, font=(35),
bg="#404040", fg="white")
self.txt1.config(bd=5)
#self.txt1.config(highlightbackground="#000000")
self.salida = StringVar()
self.btn1 = Button(self, text="=",font=(25),
command=self.calcular, bg="#9999FF")
self.btn2 = Button(self, text="C",font=(20), command=self.limpiar,
bg="#FF6666")
self.btn01 = Button(self, text="1",font=(25), command=self.boton01)
self.btn01.config(bg="#A0A0A0")
self.btn02 = Button(self, text="2",font=(25), command=self.boton02)
self.btn02.config(bg="#A0A0A0")
self.btn03 = Button(self, text="3",font=(25), command=self.boton03)
self.btn03.config(bg="#A0A0A0")
self.btn04 = Button(self, text="4",font=(25), command=self.boton04)
self.btn04.config(bg="#A0A0A0")
self.btn05 = Button(self, text="5",font=(25), command=self.boton05)
self.btn05.config(bg="#A0A0A0")
self.btn06 = Button(self, text="6",font=(25), command=self.boton06)
self.btn06.config(bg="#A0A0A0")
self.btn07 = Button(self, text="7",font=(25), command=self.boton07)
self.btn07.config(bg="#A0A0A0")
self.btn08 = Button(self, text="8",font=(25), command=self.boton08)
self.btn08.config(bg="#A0A0A0")
self.btn09 = Button(self, text="9",font=(25), command=self.boton09)
self.btn09.config(bg="#A0A0A0")
self.btn00 = Button(self, text="0",font=(25), command=self.boton00)
self.btn00.config(bg="#A0A0A0")
self.btnS = Button(self, text="+",font=(25), command=self.botonS)
self.btnS.config(bg="#FF9933")
self.btnR = Button(self, text="-",font=(25), command=self.botonR)
self.btnR.config(bg="#FF9933")
self.btnM = Button(self, text="*",font=(25), command=self.botonM)
self.btnM.config(bg="#FF9933")
self.btnD = Button(self, text="/",font=(25), command=self.botonD)
self.btnD.config(bg="#FF9933")
self.btnPA = Button(self, text="(",font=(20), command=self.botonPA)
self.btnPA.config(bg="#FF9933")
self.btnPC = Button(self, text=")",font=(20), command=self.botonPC)
self.btnPC.config(bg="#FF9933")
#COORDENADAS
self.txt1.place(x=5, y=5, height=70, width=390)
#self.txt2.place(x=25, y=65, width=100)
self.btn1.place(x=280, y=245, height=50, width=115)
self.btn2.place(x=360, y=80, height=50, width=35)
self.btnM.place(x=280, y=190, height=50, width=115)
self.btnD.place(x=280, y=135, height=50, width=115)
self.btn01.place(x=5, y=80, height=50, width=86)
self.btn02.place(x=96, y=80, height=50, width=86)
self.btn03.place(x=187, y=80, height=50, width=86)
self.btn04.place(x=5, y=135, height=50, width=86)
self.btn05.place(x=96, y=135, height=50, width=86)
self.btn06.place(x=187, y=135, height=50, width=86)
self.btn07.place(x=5, y=190, height=50, width=86)
self.btn08.place(x=96, y=190, height=50, width=86)
self.btn09.place(x=187, y=190, height=50, width=86)
self.btn00.place(x=96, y=245, height=50, width=86)
self.btnS.place(x=5, y=245, height=50, width=86)
self.btnR.place(x=187, y=245, height=50, width=86)
self.btnPA.place(x=280, y=80, height=50, width=35)
self.btnPC.place(x=320, y=80, height=50, width=35)
def calcular(self):
"""Calcula el resultado de la expresion"""
A = ArbolExp()
cadena = self.entrada.get()
A.generar(cadena)
if A.raiz is not None:
resp = A.calcular(A.raiz)
self.salida.set(str(resp))
else:
self.salida.set("Error, expresion no valida!")
#messagebox.showinfo("Error","expresion no valida!")
self.entrada.set(self.salida.get())
self.txt1.config(state=DISABLED)
def limpiar(self):
"""Vacia los cuadros de textos"""
self.txt1.config(state=NORMAL)
self.entrada.set("")
self.salida.set("")
def boton00(self):
self.entrada.set(self.entrada.get() + "0")
def boton01(self):
self.entrada.set(self.entrada.get() + "1")
def boton02(self):
self.entrada.set(self.entrada.get() + "2")
def boton03(self):
self.entrada.set(self.entrada.get() + "3")
def boton04(self):
self.entrada.set(self.entrada.get() + "4")
def boton05(self):
self.entrada.set(self.entrada.get() + "5")
def boton06(self):
self.entrada.set(self.entrada.get() + "6")
def boton07(self):
self.entrada.set(self.entrada.get() + "7")
def boton08(self):
self.entrada.set(self.entrada.get() + "8")
def boton09(self):
self.entrada.set(self.entrada.get() + "9")
def botonS(self):
self.entrada.set(self.entrada.get() + "+")
def botonR(self):
self.entrada.set(self.entrada.get() + "-")
def botonM(self):
self.entrada.set(self.entrada.get() + "*")
def botonD(self):
self.entrada.set(self.entrada.get() + "/")
def botonPA(self):
self.entrada.set(self.entrada.get() + "(")
def botonPC(self):
self.entrada.set(self.entrada.get() + ")")
if __name__ == "__main__":
Lienzo = Tk() # instancia del objeto frame para la visualizacion de
#la ventana en python
ventana = main(Lienzo) # Creacion de la ventana segun parametizacion
Lienzo.mainloop() |
15d91d49699e305ed7e35be6f3cab36df170469b | louisuss/Algorithms-Code-Upload | /Python/AlgorithmsBookStudy/Nonlinear/Tree/tree_travelsals.py | 379 | 3.5 | 4 | def preorder(node):
if node is None:
return
print(node.val)
preorder(node.left)
preorder(node.right)
def inorder(node):
if node is None:
return
inorder(node.left)
print(node.val)
inorder(node.right)
def postorder(node):
if node is None:
return
postorder(node.left)
postorder(node.right)
print(node.val)
|
b77d412b49a07e6bde4c21d8e6af61c25fe84a6b | rafaelvictor88/python3exercises | /ex034.py | 257 | 3.71875 | 4 | salário = float(input('Qual o valor do salário do funcionário? R$'))
if salário > 1250:
novo = salário + (salário * 10 / 100)
else:
novo = salário + (salário * 15 / 100)
print('O seu salário passará a ser de R${:.2f}.'.format(novo))
|
bdeec68890498468a2bdb9f2add8bfc7a203082c | RobertG247/classDAY | /tomorrow/tempo.py | 303 | 4.15625 | 4 | def Temperature():
entry="yes"
while (entry=="yes" or entry=="Yes" ):
x = float(input("what temperature is it outside in grades fahrenheit??"))
y=(x-32)/ 1.8
print ("the temperature in celsius is", y)
entry=input("continue yes or no?")
Temperature()
|
2daaea5c2e96d8f0385f2a9ccd1be1dc887bf7d0 | wjasonhuang/python_utils | /standard_library/concurrent_execution/lib_queue.py | 1,499 | 4.28125 | 4 | '''
https://docs.python.org/3/library/queue.html
class queue.Queue(maxsize=0) constructor for a FIFO queue
class queue.LifoQueue(maxsize=0) constructor for a LIFO queue
class queue.PriorityQueue(maxsize=0) data format: (priority_number, data)
Queue.qsize()
Queue.empty()
Queue.full()
Queue.put(item, block=True, timeout=None)
Queue.put_nowait(item)
Queue.get(block=True, timeout=None) remove and return an item from the queue
Queue.task_done() indicate that a formerly enqueued task is complete
Queue.join()
- The count of unfinished tasks goes up whenever an item is added to the queue.
- The count goes down whenever a consumer thread calls task_done().
- When the count of unfinished tasks drops to zero, join() unblocks.
'''
from queue import Queue
from threading import Thread, Lock
import time, random
def worker(t_id, lock):
while True:
item = q.get()
if item is None: break
time.sleep(item)
with lock:
print(f'Thread {t_id}: sleep {round(item, 2)} second(s)')
q.task_done()
num_worker, n = 3, 9
source = [random.randint(1, n - 1) / n for i in reversed(range(n))]
q = Queue()
lock = Lock()
threads = []
for i in range(num_worker):
t = Thread(target=worker, args=(i, lock))
t.start()
threads.append(t)
for item in source: q.put(item)
# block until all tasks are done
q.join()
# stop workers
for i in range(num_worker): q.put(None)
for t in threads: t.join()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.