blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
28049ba6b25ffb88072b8a246276f5735290fa4e | Ultimategoal/helloPython | /HelloPython/day02/myhome02.py | 193 | 3.625 | 4 | from matplotlib.pyplot import plot
a = int(input("첫 번째 수를 입력하세요"))
b = int(input("두 번쨰 수를 입력하세요"))
sum = 0
for i in range(a,b+1):
sum += i
print(sum) |
887444a2f2650a17270aef91aa2ffe3f1ec72afb | LarsAstrom/Wilf-Zeilbergers-Method | /WZmethod/code/polynomial.py | 22,210 | 3.984375 | 4 | '''Constant class'''
class constant:
'''Methods only using self'''
def __init__(self,value,variable=None):
self.coefficients = [value]
self.degree = 0
self.is_zero = (value == 0)
self.variables = []
self.is_constant = True
self.is_one = (value == 1)
def convert_polynomial(self,variables):
return polynomial_parser(self.to_string(),variables)
def evaluate(self,variable,value):
return self.coefficients[0]
def get_constant(self,value):
return constant(value)
def get_prev_constant(self,value):
raise Exception('Not possible to get prev constant for a constant')
def power(self,n):
return constant(pow(self.coefficients[0],n))
def negate(self):
return constant(-self.coefficients[0])
def to_string(self):
return str(self.coefficients[0])
def PRINT(self):
print(self.to_string())
'''Methods using other'''
def get_common_variables(self,other):
return other.variables
def equals(self,other):
if self.variables == other.variables:
return self.equals_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).equals(other.convert_polynomial(vars))
def equals_simple(self,other):
assert self.variables == other.variables, 'Trying to check equality polynomials of different variables.'
return self.coefficients[0] == other.coefficients[0]
def add(self,other):
if self.variables == other.variables:
return self.add_simple(other)
return self.convert_polynomial(other.variables).add(other)
def add_simple(self,other):
assert self.variables == other.variables, 'Trying to add polynomials of different variables.'
return constant(self.coefficients[0]+other.coefficients[0])
def subtract(self,other):
return self.add(other.negate())
def multiply(self,other):
if self.variables == other.variables:
return self.multiply_simple(other)
return self.convert_polynomial(other.variables).multiply(other)
def multiply_simple(self,other):
assert self.variables == other.variables, 'Trying to multiply polynomials of different variables.'
return constant(self.coefficients[0]*other.coefficients[0])
def divide(self,other):
if self.variables == other.variables:
return self.divide_simple(other)
return self.convert_polynomial(other.variables).divide(other)
def divide_simple(self,other):
# Returns (q,r,f) such that f*self/other = q + r/other. (f is a constant)
assert self.variables == other.variables, 'Trying to divide polynomials of different variables.'
return (constant(self.coefficients[0]//other.coefficients[0]),
constant(self.coefficients[0]%other.coefficients[0]),
constant(1))
def modulo(self,other):
if self.variables == other.variables:
return self.modulo_simple(other)
return self.convert_polynomial(other.variables).modulo(other)
def modulo_simple(self,other):
assert self.variables == other.variables, 'Trying to modulo polynomials of different variables.'
q,r,f = self.divide(other)
return r
def gcd(self,other):
if self.variables == other.variables:
return self.gcd_simple(other)
return self.convert_polynomial(other.variables).gcd(other)
def gcd_simple(self,other):
assert self.variables == other.variables, 'Trying to gcd polynomials of different variables. {} {}'.format(self.variables,other.variables)
if other.is_zero: return self
return other.gcd(self.modulo(other))
'''Polynomial class'''
class polynomial:
'''Methods only using self'''
def __init__(self,coefficients,variable):
self.coefficients = coefficients
while len(self.coefficients) > 1 and self.coefficients[-1].is_zero:
self.coefficients.pop()
self.degree = len(self.coefficients) - 1
self.is_zero = (self.degree==0 and self.coefficients[0].is_zero)
assert variable not in self.coefficients[0].variables, 'Duplicate variable name.'
self.variables = [variable] + self.coefficients[0].variables
self.is_constant = (self.degree==0 and self.coefficients[0].is_constant)
self.is_one = (self.degree==0 and self.coefficients[0].is_one)
'''
Finds zeros of a polynomial with respect to a variable.
Tries to solve first and second degree order equations and further more tries
for a few small values.
'''
def get_zeros(self,variable):
assert variable in self.variables, 'Not possible to find zeros with variable {}, because the variables are {}'.format(variable,self.variables)
if variable != self.variables[-1]:
new_variable_list = list(self.variables)
new_variable_list.remove(variable)
new_variable_list.append(variable)
return self.convert_polynomial(new_variable_list).get_zeros(variable)
if len(self.variables) == 1:
if self.degree == 0:
return 'all_values' if self.is_zero else []
if self.degree == 1:
a, b = self.coefficients[1].coefficients[0],\
self.coefficients[0].coefficients[0]
return [b//a] if (b%a==0) else []
if self.degree == 2:
a,b,c = self.coefficients[2].coefficients[0],\
self.coefficients[1].coefficients[0],\
self.coefficients[0].coefficients[0]
out = []
if b**2 < 4*a*c: return out
if (-b+(b**2-4*a*c)**0.5)/(2*a) == int((-b+(b**2-4*a*c)**0.5)/(2*a)):
out.append(int((-b+(b**2-4*a*c)**0.5)/(2*a)))
if (-b-(b**2-4*a*c)**0.5)/(2*a) == int((-b-(b**2-4*a*c)**0.5)/(2*a)):
out.append(int((-b-(b**2-4*a*c)**0.5)/(2*a)))
return out
out = []
for value in range(-100,101):
if self.evaluate(variable,value).is_zero:
out.append(value)
return out if out else 'high_degree'
i = 0
while i < self.degree + 1:
if type(self.coefficients[i].get_zeros(variable)) == list:
break
else:
i += 1
if i == self.degree + 1:
L = []
for value in range(-100,101):
if self.evaluate(variable,value).is_zero:
L.append(value)
if not L: return 'high_degree'
else:
L = self.coefficients[i].get_zeros(variable)
out = []
for l in L:
if self.evaluate(variable,l).is_zero:
out.append(l)
return out
'''Evaluates the polynomial for variable=value'''
def evaluate(self,variable,value):
if variable == self.variables[0]:
out = self.coefficients[0]
for i in range(1,self.degree+1):
out = out.add(self.coefficients[i].multiply(constant(value).power(i)))
return out
return polynomial([c.evaluate(variable,value) for c in self.coefficients],
self.variables[0])
'''Converts the polynomial into the variable order variables'''
def convert_polynomial(self,variables):
for var in self.variables:
assert var in variables, 'Cannot convert {} to {}, because {} is missing.'\
.format(self.to_string(),variables,var)
return polynomial_parser(self.to_string(),variables)
def get_constant(self,value):
cur = constant(value)
for x in self.variables[::-1]:
cur = polynomial([cur],x)
return cur
def get_prev_constant(self,value):
cur = constant(value)
for x in self.variables[-1:0:-1]:
cur = polynomial([cur],x)
return cur
def power(self,n):
if n == 0:
return self.get_constant(1)
return self.power(n-1).multiply_simple(self)
def negate(self):
return polynomial([c.negate() for c in self.coefficients],self.variables[0])
def gcd_list(self):
if self.degree == 0: return self.coefficients[0]
out = self.coefficients[0].gcd(self.coefficients[1])
for x in self.coefficients[2:]:
out = out.gcd(x)
return out
def to_string(self):
out = []
for i,c in enumerate(reversed(self.coefficients)):
if c.is_zero and self.degree > 0: continue
coeff_string = c.to_string()
negative = coeff_string[0] == '-'
if negative: coeff_string = c.negate().to_string()
use_paran = len(self.variables) > 1 and ('+' in coeff_string or '-' in coeff_string)
use_coeff_string = (i==self.degree or coeff_string != '1')
#use_paran = use_coeff_string
if i or negative: out.append('-' if negative else '+')
out.append('{}{}{}{}{}{}'.format('(' if use_paran else '',
#coeff_string if (len(self.variables)>1 or coeff_string!='1' or i==self.degree) else '',
coeff_string if use_coeff_string else '',
')' if use_paran else '',
self.variables[0] if i<self.degree else '',
'^' if i<self.degree-1 else '',
self.degree-i if i<self.degree-1 else ''))
return ''.join(out)
def PRINT(self):
print(self.to_string())
'''Methods using other'''
def get_common_variables(self,other):
return sorted(list(set(self.variables)|set(other.variables)))[::-1]
def equals(self,other):
if self.variables == other.variables:
return self.equals_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).equals(other.convert_polynomial(vars))
def equals_simple(self,other):
assert self.variables == other.variables, 'Trying to check equality polynomials of different variables.'
if self.degree != other.degree: return False
for i in range(self.degree+1):
if not self.coefficients[i].equals(other.coefficients[i]):
return False
return True
def add(self,other):
if self.variables == other.variables:
return self.add_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).add(other.convert_polynomial(vars))
def add_simple(self,other):
assert self.variables == other.variables, 'Trying to add polynomials of different variables.'
c = [self.get_prev_constant(0) for _ in range(max(self.degree,other.degree)+1)]
for i in range(self.degree+1):
c[i] = c[i].add(self.coefficients[i])
for i in range(other.degree+1):
c[i] = c[i].add(other.coefficients[i])
return polynomial(c,self.variables[0])
def subtract(self,other):
return self.add(other.negate())
def multiply(self,other):
if self.variables == other.variables:
return self.multiply_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).multiply(other.convert_polynomial(vars))
def multiply_simple(self,other):
assert self.variables == other.variables, 'Trying to multiply polynomials of different variables.'
c = [self.get_prev_constant(0) for _ in range(self.degree+other.degree+1)]
for i in range(self.degree+1):
for j in range(other.degree+1):
c[i+j] = c[i+j].add(self.coefficients[i].multiply_simple(other.coefficients[j]))
return polynomial(c,self.variables[0])
'''Divides self by other and returns q,r,f such that f*self=q*other+r'''
def divide(self,other):
if self.variables == other.variables:
return self.divide_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).divide(other.convert_polynomial(vars))
def divide_simple(self,other):
# Returns (q,r,f) such that f*self/other = q + r/other. (f is of same type as coefficients)
assert self.variables == other.variables, 'Trying to divide polynomials of different variables.'
'''This if statement is not optimal'''
if other.degree == 0:
if other.coefficients[0].is_zero:
raise Exception('Polynomial divided by 0')
g = self.gcd_list().gcd(other.coefficients[0])
return (polynomial([c.divide(g)[0] for c in self.coefficients],self.variables[0]),
self.get_constant(0),
other.coefficients[0].divide(g)[0])
if self.degree < other.degree:
return (self.get_constant(0),self,self.get_prev_constant(1))
f0 = other.coefficients[-1]
deg = self.degree-other.degree
q0 = polynomial([self.get_prev_constant(0) for _ in range(deg)]+[self.coefficients[-1]],self.variables[0])
r0 = self.multiply(polynomial([f0],self.variables[0])).add(q0.multiply(other).negate())
q1,r1,f1 = r0.divide(other)
q,r,f = q0.multiply(polynomial([f1],self.variables[0])).add(q1),r1,f0.multiply(f1)
#return (q0.multiply(polynomial([f1],self.variables[0])).add(q1),r1,f0.multiply(f1))
g = q.gcd_list().gcd(f).gcd(r.gcd_list())
for i in range(q.degree+1):
q.coefficients[i] = q.coefficients[i].divide(g)[0]
for i in range(r.degree+1):
r.coefficients[i] = r.coefficients[i].divide(g)[0]
f = f.divide(g)[0]
return (q,r,f)
def modulo(self,other):
if self.variables == other.variables:
return self.modulo_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).modulo(other.convert_polynomial(vars))
def modulo_simple(self,other):
assert self.variables == other.variables, 'Trying to modulo polynomials of different variables.'
q,r,f = self.divide(other)
return r
def gcd(self,other):
if self.variables == other.variables:
return self.gcd_simple(other)
vars = self.get_common_variables(other)
return self.convert_polynomial(vars).gcd(other.convert_polynomial(vars))
def gcd_simple(self,other):
assert self.variables == other.variables, 'Trying to gcd polynomials of different variables.'
if other.is_zero: return self
g = other.gcd(self.modulo(other))
return g.multiply(self.gcd_list().gcd(other.gcd_list())).divide(g.gcd_list())[0]
def print_stack(stack):
print('---------PRINT STACK----------')
for a in stack:
if type(a) == polynomial:
print(a.variables,a.to_string())
else:
print(a)
print('------------------------------')
def polynomial_parser(s,variables = None):
if variables == None: variables = get_variables(s)
else:
for var in get_variables(s):
assert var in variables, 'Missing variable {} for parsing.'.format(var)
def simplify(stack):
if len(stack) == 1: return stack
if stack[-2] == '(': return stack
if stack[-1] == '(':
stack.append(constant_with_value(0))
return stack
#print_stack(stack)
b,op,a = stack.pop(),stack.pop(),stack.pop()
if a == '(':
stack.append(a)
assert op == '-', 'Something is weird.'
stack.append(b.negate())
return simplify(stack)
if op == '+':
stack.append(a.add(b))
elif op == '-':
stack.append(a.add(b.negate()))
elif op == '*':
stack.append(a.multiply(b))
elif op == '/':
raise Exception('polynomial_parser with divide not implemented')
#stack.append(a.divide())
return simplify(stack)
def constant_with_value(val):
cur = constant(val)
for var in variables[::-1]:
cur = polynomial([cur],var)
return cur
def poly_from_char(ch):
cur = constant(1)
for var in variables[::-1]:
if var == ch:
cur = polynomial([cur.get_constant(0), cur],var)
else:
cur = polynomial([cur],var)
return cur
stack = [constant_with_value(0)]
if s[0] != '-': stack.append('+')
i = 0
while i < len(s):
ch = s[i]
if ch == ' ':
i += 1
continue
elif ch == ')':
stack = simplify(stack)
stack = stack[:-2] + [stack[-1]]
elif ch == '+' or ch == '-':
stack = simplify(stack)
stack.append(ch)
elif ch == '*' or ch == '/':
stack.append(ch)
elif ch == '(':
if stack and type(stack[-1]) == polynomial:
stack.append('*')
stack.append(ch)
elif ch == '^':
stack.append(ch)
elif ch.isdigit():
st = i
while i+1 < len(s) and s[i+1].isdigit(): i += 1
n = int(s[st:i+1])
if stack and stack[-1] == '^':
stack[-2] = stack[-2].power(n)
stack.pop()
elif stack and type(stack[-1]) == polynomial:
stack.append('*')
stack.append(constant_with_value(n))
else:
stack.append(constant_with_value(n))
elif ch.isalpha():
if stack and type(stack[-1]) == polynomial:
stack.append('*')
stack.append(poly_from_char(ch))
else:
print(s)
raise Exception('polynomial_parser not implemented for character {}.'.format(ch))
i += 1
stack = simplify(stack)
return stack[0]
def get_variables(s):
return (sorted(list(set([ch for ch in s if ch.isalpha()])))[::-1])
'''TESTING'''
if __name__ == '__main__':
print('TESTING POLYNOMIALS')
p = polynomial_parser('xy + x^2')
p.PRINT()
s = '-7x + (x+1)(y^2+2y+4)(z-7) + 8xy'
print(s)
p = polynomial_parser(s,['z','y','x'])
p.PRINT()
s1 = 'x^2+2x+1'
s2 = '2xy'
p1 = polynomial_parser(s1)
p2 = polynomial_parser(s2)
p3 = p1.add(p2)
p4 = p1.multiply(p2)
p1.PRINT()
p2.PRINT()
p3.PRINT()
p4.PRINT()
print('============================')
p1 = polynomial_parser('(2k-n-1)(n+2-k)')
p2 = polynomial_parser('k(2k-n+2j-3)')
p1.PRINT()
p2.PRINT()
g = p1.gcd(p2)
g.PRINT()
print('TESTING EVALUATE')
g.evaluate('j',1).PRINT()
print(g.evaluate('j',1).is_zero)
print('============================')
p1 = polynomial_parser('(2k-n-1)(n+2-k)')
p2 = polynomial_parser('(k+j)(2k-n+2j-3)')
p1.PRINT()
p2.PRINT()
g = p1.gcd(p2)
g.PRINT()
g.evaluate('j',1).PRINT()
print(g.evaluate('j',1).is_zero)
print('============================')
p1 = polynomial_parser('0x+0*(x+y)')
p1.PRINT()
p1 = polynomial_parser('x^2y')
p1.multiply(constant(2)).PRINT()
p1.multiply(constant(2)).evaluate('x',1).PRINT()
p1.multiply(constant(2)).evaluate('x',2).PRINT()
p1.multiply(constant(2)).evaluate('y',2).PRINT()
print('==============================')
p1 = polynomial_parser('x+2')
p1.PRINT()
p1.evaluate('x',1).PRINT()
print(p1.evaluate('x',1).is_zero)
print('==============================')
p1 = polynomial_parser('x^2+2x+1')
print(p1.get_zeros('x'))
p2 = polynomial_parser('2x+6')
print(p2.get_zeros('x'))
p3 = polynomial_parser('3x+4')
print(p3.get_zeros('x'))
p4 = polynomial_parser('0',['x'])
print(p4.get_zeros('x'))
p5 = polynomial_parser('1',['x'])
print(p5.get_zeros('x'))
p6 = polynomial_parser('x^3+1')
print(p6.get_zeros('x'))
print('==============================')
p1 = polynomial_parser('(x-1)(x-2)(x-3)(y-3)(y-4)(z-5)(z-6)')
p1.PRINT()
print(p1.get_zeros('x'))
print(p1.get_zeros('y'))
print(p1.get_zeros('z'))
print('==============================')
p1 = polynomial_parser('x-3')
p2 = polynomial_parser('x-2')
p1.gcd(p2).PRINT()
print(type(p1.gcd(p2)))
print('==============================')
p1 = polynomial_parser('-x^2')
p1.PRINT()
print('==============================')
p1 = polynomial_parser('(k+1)(2k-n-1)')
p2 = polynomial_parser('(2k-n-1)(n+2-k)')
g1 = p1.gcd(p2)
g2 = p2.gcd(p1)
p1.PRINT()
p2.PRINT()
g1.PRINT()
g2.PRINT()
q,r,f = p2.divide(p1)
q.PRINT()
r.PRINT()
f.PRINT()
p1.gcd(f).PRINT()
p2.gcd(p1).multiply(p2.gcd(f)).divide(f.gcd(p1))[0].PRINT()
print('==============================')
p1 = polynomial_parser('(k+1)(n+1)(m+1)')
p2 = polynomial_parser('(k+1)(n+1)')
p1.gcd(p2).PRINT()
print('==============================')
p1 = polynomial_parser('(k+j)(2k+2j-3)')
p2 = polynomial_parser('(2k-1)(2-k)')
a,b,c = p1.divide(p2)
a.PRINT()
b.PRINT()
c.PRINT()
a,b,c = p2.divide(b)
a.PRINT()
b.PRINT()
c.PRINT()
#p1.gcd(p2).PRINT()
a,b,c = p1.divide(p2)
a.PRINT()
b.PRINT()
c.PRINT()
p3 = p1.multiply(c)
p3.PRINT()
p3.gcd(p2).PRINT()
p1.gcd(c).PRINT()
p2.gcd(c).PRINT()
p1.gcd(p2).PRINT()
p1 = polynomial_parser('10x^2+10x')
p2 = polynomial_parser('6x')
p1.PRINT()
p2.PRINT()
g = p1.gcd(p2)
g = g.multiply(p1.gcd_list().gcd(p2.gcd_list())).divide(g.gcd_list())[0]
g.PRINT()
p1 = polynomial_parser('(x+1)(y+1)(z+1)')
p2 = polynomial_parser('(z+1)(y+1)')
p1.PRINT()
p2.PRINT()
p1.gcd(p2).PRINT()
p1 = polynomial_parser('2x^2')
p2 = polynomial_parser('3x')
p1.PRINT()
p2.PRINT()
p1.gcd(p2).PRINT()
p1 = polynomial_parser('mn+m+1')
p1.PRINT()
print('TESTING DONE')
|
2452762ada4a066f617a37ff2e9399b39bcd55ee | alastairng/mis3640 | /session06/fibonacci.py | 146 | 3.90625 | 4 | def fibonacci(n):
if n = = 1 or n = = 2:
return 1
return fibonacci(n-2) + fibonacci(n-1)
print(facbonacci(6))
print(fabonacci(2)) |
db6a2392329bf5029a59aaf616f2883ad9c611d4 | MIR013/AlgorithmStudy | /10.ETC/PGM_재귀_타겟넘버.py | 847 | 3.546875 | 4 | total = 0
def calArr(numbers,types):
result = 0
for value, sign in zip(numbers,types):
if sign == 0:#+
result = result + value
else:#-
result = result - value
return result
def choicePM(idx,num,arr,length,numbers,target):
if(idx>=length):
#print(arr)
global total
if(calArr(numbers,arr) == target):
total = total + 1
return
arr[idx] = 0
choicePM(idx+1,0,arr,length,numbers,target)
arr[idx] = 1
choicePM(idx+1,1,arr,length,numbers,target)
return
def solution(numbers, target):
answer = 0
types = []
global total
for _ in range(len(numbers)):
types.append(-1)
choicePM(0,-1,types,len(types),numbers,target)
answer = total
return answer |
7e37234b2befc8b557873565436f10134f431318 | bingzhong-project/leetcode | /algorithms/minimum-absolute-difference-in-bst/src/Solution.py | 603 | 3.5625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getMinimumDifference(self, root: 'TreeNode') -> 'int':
def dfs(root, nodes):
if root.left:
dfs(root.left, nodes)
nodes.append(root.val)
if root.right:
dfs(root.right, nodes)
nodes = []
dfs(root, nodes)
res = 2**31
for i in range(1, len(nodes)):
res = min(res, nodes[i] - nodes[i - 1])
return res
|
59f99f795fc53fa1fc34fa3ba2e1449d125d2fc0 | gganjoo/Slap_Card_Game | /W200proj1.py | 23,499 | 3.9375 | 4 |
import random
import time
# I read up on the curses library from two main pages: https://www.devdungeon.com/content/curses-programming-python
# and https://docs.python.org/3/library/curses.html
import curses
class PlayingCard:
''' Takes a rank as a string.
Creates a playing card with said rank'''
def __init__(self, rank):
# Checks that the rank given is a possible card value.
if rank not in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]:
raise Exception ('Invalid rank!.')
# Assigns the PlayingCard attribute rank.
self.rank = rank
def __repr__(self):
# formats the PlayingCard
return '{self.rank}'.format(self=self)
class Deck:
'''Creates either a deck with 52 cards with four cards of each rank, or a deck with no cards.
Contains methods for drawing and adding cards, shuffling the deck, finding cards, and adding cards
during a mistaken 'slap' '''
def __init__(self, status= 'full'):
'''Creates a deck of cards. If no argument is entered, the deck will have 52 cards consisting
of four cards for each possible rank. If 'empty' is passed through as an argument, then the deck
will start with no cards, but still be able to have cards added later. '''
if status=='full':
deck = []
for i in range(4):
for rank in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]:
deck.append(PlayingCard(rank))
elif status== 'empty':
deck = []
#Saves the deck object and shuffles the deck after it is made.
self.deck = deck
self.shuffle_deck()
def __repr__(self):
return '{self.deck}'.format(self=self)
def shuffle_deck(self):
'''Randomly shuffles the cards in a deck.'''
random.shuffle(self.deck)
def draw_card(self):
'''Removes the top card from a deck.'''
if len(self.deck)>0:
return self.deck.pop(0)
def add_card(self,card):
#Adds a card to the bottom of a deck.
self.deck.append(card)
def lose_cards(player, discard):
'''Removes three cards from one deck(player) and adds them to the top of another deck(discard) '''
#Check if the deck passed is long enough to have three cards removed.
if len(player.deck)>=3:
discard.deck.insert(0,player.deck.pop(0))
discard.deck.insert(0,player.deck.pop(0))
discard.deck.insert(0,player.deck.pop(0))
def find_card(self,index):
'''Defines indexing for a Deck object'''
return self.deck[index]
class Board:
'''Creates a string to represent the game's board. The object needs three Deck objects and a
string object for controls'''
def __init__(self, discard_pile, comp, play, controls):
'''Creates a string object to represent the game board. The board's layout is the computer's deck and number of cards,
then a blank space for the discard pile, then the player's deck and number of cards, then keyboard control instructions.
The card emoji comes from https://emojipedia.org/joker/ '''
# Check if the discard pile has any cards in it to display yet. If yes, the board shows it. If not, the spot for
# the discard pile is left empty.
if len(discard_pile.deck)>0:
board = '🃏 computer ' + str(len(comp.deck)) +'\n' + str(Deck.find_card(discard_pile,-1)) \
+ '\n🃏 you ' + str(len(play.deck)) + '\n\n' +controls
else:
board = '🃏 computer ' + str(len(comp.deck)) +'\n\n🃏 you ' + str(len(play.deck)) + '\n\n' +controls
# Saves the board.
self.board = board
def __repr__(self):
return self.board
class Instructions:
'''Creates and displays the instructions for the game. Because the window object was having formatting issues displaying one string,
I decided to display them line by line through a loop.'''
def __init__(self, screen):
'''The Instructions are displayed via the object each time it is called. It takes as an argument the screen the instructions
will be displayed on.'''
instructions = ["Instructions:\n","There are two players, you and the computer.\n",
"Each player starts with 26 cards from a randomly shuffled 52 card deck.\n",
"You will see two cards representing each player and the number of remaining cards each player has left.\n",
"You will take turns drawing a card, by pressing d, from your decks and adding them to a discard pile,\n which you will see appear on the screen.\n"
"Keep track of the previous cards.\n",
"If two of the same card are placed in a row on the discard pile, a slap event is triggered.\n",
"When this happens, press s to 'slap' the discard pile.\n",
"If you 'slap' within two seconds, you get to add the discard pile to your deck.\n",
"If you 'slap' after two seconds, discard pile is added to the computer's deck.\n",
"The loser is whoever runs out of cards first.\n",
"Don't press s outside of a slap event, otherwise you will lose three cards from your deck.",
"Note: make sure you check the number of cards in each persons deck, because that tells you if another card was added,\n even if the top card does not change.\n",
"To quit early press q. To see the instructions again, press i.\n\n"]
self.instructions = instructions
self.screen = screen
def display_instructions(self):
# Displays the instructions.
for item in self.instructions:
self.screen.addstr(item)
class Slap:
'''This is the game object. It starts by creating two decks(player and computer) of 26 cards from a 52 card deck, as well as an
empty deck(discard pile). The game starts by using the curses library in python and opening a window in the terminal. The player will
press d to draw a card from their own deck and add it to the discard pile. The player and the computer will each add cards to the discard
pile one after another and the board will continually be updated to show the top card on the discard pile as well as the amount of cards
the computer and the player each have. Occasionally there will be a slap event where the player will press the s key as fast as they can
. If they press the s key within two seconds, the discard pile is added into the player's deck and the player's deck is reshuffled.
If not, then the discard pile is added to the computer's deck. The loser is the first person to run put of cards. A slap event is triggered
when the top two cards on the discard pile are the same (ex: 2 2, K K), called a Double event, or when the first and third cards on top of
the discard pile are the same (ex: 2 5 2, K 7 K ), called a Sandwhich event. After an event occurs, messages will appear on screen to
let the player know the result. If the player slaps when it is not a slap event, then the player loses 3 cards to the discard pile.
If the player presses i, the instructions will be displayed. If the the player presses q, they will quit the game early. If other keys are
pressed, messages will appear to help the player. When the game is finished or comleted, the window will close and print out a message
for the player.'''
def __init__(self):
'''Creates the player's deck, the computer's deck, and the discard pile.'''
#Initializes decks.
deck = Deck()
discard_pile = Deck('empty')
player = Deck('empty')
computer= Deck('empty')
#Fills the player deck and the computer's deck.
while len(deck.deck)>0:
player.add_card(deck.draw_card())
computer.add_card(deck.draw_card())
#Saves the decks.
self.deck = deck
self.discard_pile = discard_pile
self.player = player
self.computer = computer
self.screen = curses.initscr()
self.instructions = Instructions(self.screen)
def game_start(self):
'''Starts the game and the user interface'''
#To make the code less wordy, assigning the different deck's names here so I can write 'self' less.
discard_pile = self.discard_pile
player = self.player
computer = self.computer
screen = self.screen
instructions = self.instructions
# Turns off echo so that player's key presses aren't displayed.
curses.noecho()
# Turns on cbreak so that the player does not need to hit enter when playing.
curses.cbreak()
# Remembers the controls that will be displayed at the bottom of the Window object.
CONTROLS = "Press d to draw\nPress s to slap\nPress i for instructions\nPress q to quit"
# Remembers how much time a player has to press 's' in order to win a slap event
WAIT_TIME = 1
# Declares the variables for remembering whose turn it is and if the game is ongoing.
gameon = True
player_turn = True
# Asks player to press a key to start.
screen.addstr('Ready to start? Press any key to begin\n')
curses.napms(700)
c = screen.getch()
# Shows the instructions.
screen.clear()
instructions.display_instructions()
screen.addstr('Press any key to continue.')
screen.refresh()
screen.getch()
# Displays the initial game board on the screen.
screen.clear()
screen.addstr(Board(discard_pile,computer,player, CONTROLS).board)
screen.refresh()
# Saves the display message for the player if they exit the game early. If the game is completed, the message will be updated later on.
event = 'You exited early'
# Starts a loop that terminates when the game is over.
while gameon:
# This loop runs when it is the player's turn i.e. when player_turn == True
while player_turn:
# Checks if the player has any cards left in their deck. If not, then the player lost.
if len(player.deck)<1:
gameon = False # Changes flag to tell that the game is over
event = 'Sorry player, you lost' # Changes the final messge to the player
break
#Asks the player to press any key.
c = screen.getch()
#If the the player presses 'i', the window will be cleared and will pull up the instructions
if c == ord('i'):
# Clears the window and displays the instructions
screen.clear()
instructions.display_instructions()
# Instructions(screen)
screen.addstr('Press q to quit. Press any other key to continue game')
# If the player presses 'q', the game will quit.
q = screen.getch()
if q == ord('q'):
gameon = False
break
# Clears the window of the instructions and displays the updated board again.
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.refresh()
# If the player presses 'd', a card from the 'player' deck will be added to the discard pile.
# The board displayed will be updated to show the newly added card.
elif c == ord('d'):
# Adds a card from the 'player' deck to discard pile.
discard_pile.add_card(player.draw_card())
# Clears the window and displays the updated board with the newly added card.
screen.clear()
top_card = Deck.find_card(discard_pile,-1)
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.refresh()
# Checks if a Double event occurs.
if len(discard_pile.deck)>1:
if top_card.rank == discard_pile.deck[-2].rank:
# Times how long it takes for the player to press a key
start = time.time()
did_slap = screen.getch()
end = time.time()
# Checks if the player pressed 's' and if the player was quick enough
if (did_slap == ord('s')) and ((end-start)<WAIT_TIME):
# Adds cards to the player's deck and empties the discard pile
for item in discard_pile.deck:
player.deck.append(item)
player.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player, CONTROLS).board)
# Displays who won the event and which event it was
screen.addstr("\n\nYou slapped first on the Double.")
screen.refresh()
else:
# Adds cards to the computer's deck and empties the discard pile
for item in discard_pile.deck:
computer.deck.append(item)
computer.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player, CONTROLS).board)
# Displays who won the event and which event it was
screen.addstr("\n\nComputer slapped first on the Double.")
screen.refresh()
# Checks if a Sandwhich event occurs.
if len(discard_pile.deck)>2:
if top_card.rank == Deck.find_card(discard_pile,-3).rank:
# Times how long it takes for the player to press a key
start = time.time()
did_slap = screen.getch()
end = time.time()
# Checks if the player pressed 's' and if the player was quick enough
if (did_slap == ord('s')) and ((end-start)<WAIT_TIME):
# Adds cards to the player's deck and empties the discard pile
for item in discard_pile.deck:
player.deck.append(item)
player.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
# Displays who won the event and which event it was
screen.addstr('\n\nYou slapped first on the Sandwhich')
screen.refresh()
else:
# Adds cards to the computer's deck and empties the discard pile
for item in discard_pile.deck:
computer.deck.append(item)
computer.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
# Displays who won the event and which event it was
screen.addstr('\n\nComputer slapped first on the Sandwhich.')
screen.refresh()
curses.napms(100) # Pauses to make sure player sees the message. Not neccesary everywhere.
curses.napms(600) # Pauses to make sure player sees the message. Done by trial and error.
# Flags that the player's turn is done.
player_turn = False
# If playe presses 'q', the game will quit by changing the flags.
elif c == ord('q'):
player_turn = False
gameon = False
# If the player presses 's' and it is not a slap event, they lose three cards or lose.
elif c == ord('s'):
#Checks if the player has enough cards in their deck to continue.
if len(player.deck)>=3:
screen.clear()
# Removes three cards from the player's deck and adds them to the discard pile.
Deck.lose_cards(player,discard_pile)
screen.addstr(Board(discard_pile,computer,player, CONTROLS).board)
# Adds a game message underneath the board.
screen.addstr('\n\nOh no. You slapped at the wrong time. 3 of your cards have been added to the bottom of the discard pile')
screen.refresh()
else:
# If the player has less than three cards left, then they automatically lose the game.
screen.clear()
# Gives player a game message and waits for them to press any key.
screen.addstr("\n\nOh no. You slapped at the wrong time. You don't have enough cards to add to the discard pile.")
screen.addstr('\n\nPress any key to continue')
screen.refresh()
screen.getch()
# Empties player's deck so that when control loops to the top, the player will lose.
player = Deck('empty')
# Warning/error messages for player. The messages don't go away until 'd' or 's' is pressed.
# If player presses capitol 'D', the game tells the player the caps lock is on.
elif c == ord('D'):
screen.addstr('\n\nCaps lock is on.')
# If the player presses any key other that 'd','s','q','i', or 'D', the game tells the player that they pressed the worong key.
else:
screen.addstr('\n\nWrong key :)')
#Checks if game has ended after the player's turn.
if gameon==False:
break
# This loop runs for computer's turn i.e. if player_turn == False.
while not player_turn:
# Checks if the computer has no more cards and therefore the player has won.
if len(computer.deck)<1:
gameon = False # Changes game status flag.
event = 'Congrats player, you won' # Changes final messge to user.
break
# Adds a card from the 'computer' deck to the discard pile.
discard_pile.add_card(computer.draw_card())
# Clears the window and adds the updated board with newly added card.
screen.clear()
top_card = Deck.find_card(discard_pile,-1)
screen.addstr(Board(discard_pile,computer,player, CONTROLS).board)
screen.refresh()
# Checks for a Double event occurs
if len(discard_pile.deck)>1:
if top_card.rank == discard_pile.deck[-2].rank:
#
start = time.time()
did_slap = screen.getch()
end = time.time()
if (did_slap == ord('s')) and ((end-start)<1):
for item in discard_pile.deck:
player.deck.append(item)
player.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.addstr('\n\nYou slapped first on the Double')
screen.refresh()
else:
for item in discard_pile.deck:
computer.deck.append(item)
computer.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.addstr('\n\nComputer slapped first on the Double.')
screen.refresh()
if len(discard_pile.deck)>2:
if top_card.rank == Deck.find_card(discard_pile,-3).rank:
start = time.time()
did_slap = screen.getch()
end = time.time()
if (did_slap == ord('s')) and ((end-start)<1):
for item in discard_pile.deck:
player.deck.append(item)
player.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.addstr('\n\nYou slapped first on the Sandwhich')
screen.refresh()
else:
for item in discard_pile.deck:
computer.deck.append(item)
computer.shuffle_deck()
discard_pile = Deck('empty')
screen.clear()
screen.addstr(Board(discard_pile,computer,player,CONTROLS).board)
screen.addstr('\n\nComputer slapped first on the Sandwhich.')
screen.refresh()
curses.napms(500)
#Flags that the computer's turn is done.
player_turn = True
# Closes the window/game.
curses.endwin()
print(event)
game = Slap()
game.game_start() |
2d50e9fa33374b10c1feda69d2f8a787c1aab78f | sakurasakura1996/Leetcode | /堆/problem703_数据流中的第K大元素.py | 2,899 | 4.125 | 4 | """
703. 数据流中的第K大元素
设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,
返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
说明:
你可以假设 nums 的长度 ≥ k-1 且 k ≥ 1。
"""
from typing import List
import heapq
# 啊,我好笨啊,如果一直往堆中加入数据的话,那第k大的数又怎么能找到呢
# 所以这道题正确使用堆的方法就是,维持堆中只有k个数,如果加入的数据比堆顶的数还要小直接就忽略操作啊。
class KthLargest:
# 注意这里的方法超时了,原因是,我并未保持大顶堆的数量,只要add就往里面添加数据,然后再取出前k大的数,到后面肯定会很超时。
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = []
for num in nums:
heapq.heappush(self.heap, num)
def add(self, val: int) -> int:
# 运用heapq堆模块会对列表进行排序吗,那堆中第K大的元素是不是直接用索引来提取出来呢?然而并不是
# 那么如何取出第k大的数呢?解法见上方解析,或者 heapq.nlargest(n, heap)
heapq.heappush(self.heap, val)
num = heapq.nlargest(self.k, self.heap)[self.k-1]
return num
class Solution:
def __init__(self, k: int, nums: List[int]):
self.k = k
self.heap = []
# 使用小顶堆哦,然后维持堆中只有k个数,那么最小的数即为所求
for num in nums:
if len(self.heap) < self.k:
heapq.heappush(self.heap, num)
elif len(self.heap) == self.k and heapq.nsmallest(1, self.heap)[0] < num:
heapq.heappop(self.heap)
heapq.heappush(self.heap, num)
def add(self, val: int) -> int:
if len(self.heap) < self.k:
heapq.heappush(self.heap, val)
return heapq.nsmallest(1, self.heap)[0]
elif len(self.heap) == self.k and heapq.nsmallest(1, self.heap)[0] < val:
heapq.heappop(self.heap)
heapq.heappush(self.heap, val)
return heapq.nsmallest(1, self.heap)[0]
else:
return heapq.nsmallest(1, self.heap)[0]
k = 3
arr = [4, 5, 8, 2]
obj = Solution(k, arr)
# print(obj.heap)
ans = []
ans.append(obj.add(3))
ans.append(obj.add(5))
ans.append(obj.add(10))
ans.append(obj.add(9))
ans.append(obj.add(4))
print(ans)
|
71b19efc26bfd66a7db4cb3e033547510d64321a | PRITI1999/Mathest_Backend | /addition_category_classes/AdditionCategory1.py | 888 | 3.765625 | 4 | import random
class AdditionCategory1:
instance_no_list = []
answer_calculated = 1
def __init__(self, original_number_list):
self.instance_no_list = []
self.answer_calculated = 1
for i in range(0, len(original_number_list)):
self.instance_no_list.append(original_number_list[i])
def generate_answer(cls):
for i in range(0, len(cls.instance_no_list)):
cls.answer_calculated = cls.answer_calculated * cls.instance_no_list[i]
return cls.answer_calculated
def generate_question(cls, no_of_numbers):
question_generated = []
for i in range(0, no_of_numbers):
question_generated.append(random.randint(1, 9))
return question_generated
list1 = [1, 2, 3]
ac1 = AdditionCategory1(list1)
print(ac1.generate_answer())
print(ac1.generate_question(len(list1)))
|
d34b0f4fb74993f3d28a74406b433882ec0312a4 | ViktorRyabtcev/Geekbrains | /Test_2.py | 10,100 | 3.78125 | 4 | # 1)
# Создать список и заполнить его элементами различных типов данных. Реализовать скрипт
# проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list1 = [1, 'asd', False]
my_list = ['qwerty', 123, 1.2, my_list1, True]
print(f'Имеется список состоящий из элементов различных'
f'типов данных {my_list}')
for el in my_list:
print('Элемент- ' + str(el) + '- его тип -' + str(type(el)))
# 2)
# Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются
# элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний
# сохранить на своем месте. Для заполнения списка элементов необходимо использовать
# функцию input()
print(' ')
print(' Для списка реализовать обмен значений соседних элементов, т.е.\nЗначениями обмениваются '
'элементы с индексами 0 и 1, 2 и 3 и т.д.\nПри нечетном количестве элементов последний '
'сохранить на своем месте')
my_list = []
my_list_len = int(input('Введите длинну списка который хотите создать : '))
print('Вам нужно ввести ' + str(my_list_len) + ' значений, которые будут помещены в список.')
for el in range(0, my_list_len):
my_list.append(input('Введите ' + str(el) + ' значение списка: '))
print('Это, созданный вами список: ' + str(my_list))
print('Теперь мне нужно поменять местами значения в списке (обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.')
for i in range(0, my_list_len - 1, 2):
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
print('Это, список после обмена значений: ' + str(my_list))
# 3)
# Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict. Winter, spring, summer, autumn
print(' ')
print(' Первый вариант')
season = {12: 'Зима', 1: 'Зима', 2: 'Зима', 3: 'Весна', 4: 'Весна', 5: 'Весна', 6: 'Лето', 7: 'Лето', 8: 'Лето',
9: 'Осень', 10: 'Осень', 11: 'Осень'}
n_month = 0
while n_month < 1 or n_month > 12:
n_month = int(input('Введите номер месяца от 1 до 12? а я скажу к какому времени года относится месяц: '))
season_my = season.get(n_month)
print('это будет ' + str(season_my))
#Второй вариант
print(' Второй вариант')
seasons_list = ['Зима', 'Весна', 'Лето', 'Осень']
month = 0
while month < 1 or month > 12:
month = int(input("Введите число соответствующее месяцу: "))
if month == 1 or month == 12 or month == 2:
print(seasons_list[0])
elif month == 3 or month == 4 or month == 5:
print(seasons_list[1])
elif month == 6 or month == 7 or month == 8:
print(seasons_list[2])
elif month == 9 or month == 10 or month == 11:
print(seasons_list[3])
#Третий вариант
print(' Третий вариант')
seasons_dict = {1: 'Зима', 2: 'Весна', 3: 'Лето', 4: 'Осень'}
month = 0
while month < 1 or month > 12:
month = int(input("Введите число соответствующее месяцу: "))
if month == 1 or month == 12 or month == 2:
print(seasons_dict.get(1))
elif month == 3 or month == 4 or month == 5:
print(seasons_dict.get(2))
elif month == 6 or month == 7 or month == 8:
print(seasons_dict.get(3))
elif month == 9 or month == 10 or month == 11:
print(seasons_dict.get(4))
# 4)
# Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки.
# Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.
new_list = []
print(' ')
for words in input('Введите строку из нескольких слов разделенных пробелами,'
' я разделю его на отдельные слова: ').split():
new_list.append(words)
for it, el in enumerate(new_list, 1):
print(it, el[0:10])
# 5. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел.
# У пользователя необходимо запрашивать новый элемент рейтинга.
# Если в рейтинге существуют элементы с одинаковыми значениями,
# то новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, набор натуральных чисел: 7, 5, 3, 3, 2.
# Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2.
# Пользователь ввел число 8. Результат: 8, 7, 5, 3, 3, 2.
# Пользователь ввел число 1. Результат: 7, 5, 3, 3, 2, 1.
# Набор натуральных чисел можно задать непосредственно в коде, например, my_list = [7, 5, 3, 3, 2].
# Сделал так
print(' ')
print('Первый вариант программы "Рейтинг" ')
my_list = [8, 7, 7, 6, 5, 5, 3, ]
print('Имеющийся рейтинг: ' + str(my_list))
user_el = int(input('Введите число: '))
my_list.append(user_el)
my_list.sort(reverse=True)
print('Новый рейтинг: ' + str(my_list))
# Подумал, что не может быть настолько просто и сделал так. И f-строки опробовал заодно.
print(' ')
print('Второй вариант программы "Рейтинг" ')
my_list = [7, 5, 3, 3, 2]
print(f"Рейтинг - {my_list}")
us_digit = int(input("Введите число (666 - выход) : "))
while us_digit != 666:
for el in range(len(my_list)):
if my_list[el] == us_digit:
my_list.insert(el + 1, us_digit)
break
elif my_list[0] < us_digit:
my_list.insert(0, us_digit)
elif my_list[-1] > us_digit:
my_list.append(us_digit)
elif my_list[el] > us_digit and my_list[el + 1] < us_digit:
my_list.insert(el + 1, us_digit)
print(f"Измененный список - {my_list}")
us_digit = int(input("Введите число "))
# 6.
# * Реализовать структуру данных «Товары». Она должна представлять собой список кортежей.
# Каждый кортеж хранит информацию об отдельном товаре.
# В кортеже должно быть два элемента — номер товара и словарь с параметрами
# (характеристиками товара: название, цена, количество, единица измерения).
# нужно сформировать программно, т.е. запрашивать все данные у пользователя.
# Пример готовой структуры:
# [(1, {“название”: “компьютер”, “цена”: 20000, “количество”: 5, “eд”: “шт.”}),
# (2, {“название”: “принтер”, “цена”: 6000, “количество”: 2, “eд”: “шт.”}),
# (3, {“название”: “сканер”, “цена”: 2000, “количество”: 7, “eд”: “шт.”})]
# Необходимо собрать аналитику о товарах.
# Реализовать словарь,в котором каждый ключ — характеристика товара,
# например название, а значение — список значений-характеристик, например список названий товаров.
# Пример:
# {“название”: [“компьютер”, “принтер”, “сканер”],“цена”: [20000, 6000, 2000],“количество”: [5, 2, 7],“ед”: [“шт.”]}
print(' ')
it = int(input("Введите количество видов товара "))
y = 1
my_dict = []
my_list = []
analys = {}
while y <= it:
my_dict = dict({'название': input(f"Введите название {y} товара "), 'цена': input(f"Введите цену {y} товара "),
'количество': input(f'Введите количество {y} товара '),
'eд': input(f"Введите единицу измерения {y} товара ")})
my_list.append((y, my_dict))
y = y + 1
print(' Список ')
print(' ')
print(my_list)
print(' ')
print(' Дальше не понял ')
|
5a55242bef715ff025b17712382928ecf50e5615 | MariiaRev/Portfolio | /SomeOptimizationAlgorithms/SymbioticOrganismSearch/main_SOS.py | 1,389 | 3.578125 | 4 | from functions_SOS import *
a1 = -2
b1 = 2
a2 = -5
b2 = 5
a3 = -10
b3 = 10
a4 = [-1.5, -3]
b4 = 4
while True:
func_num = int(input("\nВведіть номер функції (1-4; 0 для виходу): "))
if func_num == 1:
#функція 1
print("-"*80)
print(" "*18, "@"*7, "ФУНКЦІЯ 1", "@"*7)
SymbioticOrganismsSearch(1, a1, b1)
print("Очікуваний результат: (-1; -4)")
print()
elif func_num == 2:
#функція 2
print("-"*80)
print(" "*18, "@"*7, "ФУНКЦІЯ 2", "@"*7)
print()
SymbioticOrganismsSearch(2, a2, b2)
print("Очікуваний результат: (-4.636; -10.774)")
print()
elif func_num == 3:
#функція 3
print("-"*80)
print(" "*18, "@"*7, "ФУНКЦІЯ 3", "@"*7)
print()
SymbioticOrganismsSearch(3, a3, b3)
print("Очікуваний результат: (0; 0; 0)")
print()
elif func_num == 4:
#функція 4
print("-"*80)
print(" "*18, "@"*7, "ФУНКЦІЯ 4", "@"*7)
print()
SymbioticOrganismsSearch(4, a4, b4)
print("Очікуваний результат: (-0.54719; -1.64719; -1.9133)")
print()
else:
break
|
eb7d0b690a61be93ec424247e93c00a98c587e30 | vandamonics101/my_projects | /pyramid.py | 339 | 3.703125 | 4 | def pyramid():
to_print = 1
going_down = False
for i in range (0, 7):
for j in range (0, to_print):
print ("*", end = " ")
print (" ")
if to_print == 4:
going_down = True
if going_down:
to_print -= 1
else:
to_print += 1
pyramid()
|
1be7aebb326021b485798b427848a16197acad76 | BaerSenac/Curso_em_Video_Modulo | /Conteudo/Condições/Exercicios/jogo.py | 517 | 3.890625 | 4 | from random import randint
from time import sleep
computador = randint(0, 10)
print("-=-" * 20)
print("Vou pensar em um numero entre 0 e 10, tente adivinhar...") # Computador está sorteando um numero#
print("-=-" * 20)
sleep(3)
jogador = int(input("Qual número eu escolhi? ")) # Jogador escolhe um valor#
print("Espera que o pai ta verificando...")
sleep(3)
if jogador == computador:
print("Omedetooo , você ganhou tigrão!!")
else:
print(f"Perdeu otário, eu escolhi {computador}")
|
a4479b5fe52136f3b240f59babf70be396560c9e | Ragav-Subramanian/My-LeetCode-Submissions | /1302. Deepest Leaves Sum Python Solution.py | 639 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
l=[root]
s=0
while l!=[]:
t=[]
s=0
for i in l:
if i is not None:
if i.left is not None:
t.append(i.left)
if i.right is not None:
t.append(i.right)
s+=i.val
l=t[:]
return s1 |
cb03681a092e079f5efff6b0386276c56a07475f | qianpeng-shen/Study_notes | /第二阶段笔记/pythonweb/正则表达式/regex3.py | 580 | 3.515625 | 4 | import re
# s="Hello World"
# l=re.findall('h\w+',s,re.I)
# print(l)
#M 对元字符 ^ $ 起作用,可以匹配每一行的开头结尾位置
# s='''hello world
# Hello kitty
# nihao China
# '''
# l=re.findall('China$',s,re.M)
# print(l)
#S 对元字符 . 起作用 让其可以匹配换行
# s='''hello world
# Hello kitty
# nihao China
# '''
# l=re.findall('.+',s,re.S)
# print(l)
s='''Hello world
Hello kitty
nihao China
'''
pattern ='''(?P<dog>hello)#dog组
\s+#空字符
(world)#第二组用来匹配'''
l=re.findall(pattern,s,re.X | re.I)
print(l)
|
138c5eeecadb78c2f6b601ef7bd0c09ea0b86287 | GabrielSuzuki/Daily-Interview-Question | /2020-12-18-Interview.py | 2,024 | 4.125 | 4 | #Hi, here's your problem today. This problem was recently asked by Microsoft:
#You are given an array of intervals - that is, an array of tuples (start, end). The array may not be sorted, and could contain overlapping intervals. Return another array where the overlapping intervals are merged.
#For example:
#[(1, 3), (5, 8), (4, 10), (20, 25)]
#This input should return [(1, 3), (4, 10), (20, 25)] since (5, 8) and (4, 10) can be merged into (4, 10).
#Here's a starting point:
def merge(intervals):
firstint = []
firstbool = True
secondint = []
listt = []
for i in intervals:
for j in i:
if(i == len(intervals) - 1):
listt.append(firstint[0],firstint[1])
elif(firstbool == True):
firstint[0] = j[0]
firstint[1] = j[1]
firstbool = False
elif(firstbool == False):
secondint.append(j[0])
secondint.append(j[1])
if(firstint[0] < secondint[0]):
if(firstint[1] < secondint[0]):
listt.append(firstint[0],firstint[1])
firstint[0] = firstint[0]
firstint[1] = firstint[1]
else:
listt.append(firstint[0],secondint[1])
firstint[0] = firstint[0]
firstint[1] = secondint[1]
else:
if(firstint[1],secondint[1]):
listt.append(secondint[0],secondint[1])
firstint[0] = secondint[0]
firstint[1] = secondint[1]
else:
listt.append(secondint[0],firstint[1])
firstint[0] = secondint[0]
firstint[1] = firstint[1]
return listt
#save 1 tuple
#use 2nd tuple to check the first
# if there is no 2nd tuple, just add the 1st tuple
#check if 1stnum1 < 2ndnum1
#if yes check if 1stnum2 < 2ndnum1
#if yes add 1st to list
#if no add (1stnum1,2ndnum2)
#if no check if 1stnum2 < 2ndnum2
#if yes add 2nd
#if no add (2ndnum1,1stnum2)
# Fill this in.
print(merge([(1, 3), (5, 8), (4, 10), (20, 25)]))
# [(1, 3), (4, 10), (20, 25)]
|
5dbe3d3c144da75225a481ed3293b0d7a7f019eb | jabbtoo/swampy | /myFactorialFunction.py | 402 | 3.515625 | 4 | import math
def factorial(k):
if k == 0:
return 1
else:
recurse = factorial(k-1)
result = k * recurse
return result
factor = 2 * math.sqrt(2) / 9801
total = 0
for n in range(2):
quotient = factorial(4*n) * (1103 + 26390*n)
divisor = factorial(n)**4 * 396**(4*n)
temp = factor * quotient / divisor
total += temp
print ' ', ' ', 1/total
|
6be43d5901897e156fccf13b0ce54737c5588ae3 | OliverSimonGH/PythonBasics | /sys_task.py | 414 | 3.921875 | 4 | import sys
if len(sys.argv) > 3:
print("I need you to enter a Movie and a rating")
sys.exit(1)
else:
movie_name, movie_rating = sys.argv[1], sys.argv[2]
if movie_rating.isdigit():
movie_rating = int(movie_rating)
movie_percent = movie_rating * 10
print("Movie: {}, Rating: {}".format(movie_name, movie_percent))
else:
print("I need a rating and a movie name")
|
7c07f1b2650415db028d64057016893b06f8245f | DanlanChen/cc_150_6.0 | /chapter_1/python/uniqueChars.py | 387 | 3.765625 | 4 | def isUniqueChars( s):
if len(s) > 128:
return False
char_set = [False]*128
for char in s:
char_ascii = ord(char)
if char_set[char_ascii]:
return False
char_set[char_ascii] = True
return True
if __name__ == '__main__':
s = 'abbbb'
print(s)
# unique = UniqueChars()
b = isUniqueChars(s)
print (b)
|
f891fdf677b75e4a84ddf5d713fb48f3ad22d119 | dougfraga/technical-interview-exercises | /list/max_min.py | 749 | 4.125 | 4 | from random import shuffle
def max_min(lst):
"""
Calculate the maximum and minimum of a list lst
:param lst: list
:return: tuple: (max, min)
"""
if len(lst) == 0:
raise ValueError('Empty List')
max_value = min_value = lst[0]
for value in lst:
if value > max_value:
max_value = value
if value < min_value:
min_value = value
return max_value, min_value # O(n)
if __name__ == '__main__':
print(max_min([1])) # (1, 1)
print(max_min([1, 2])) # (2, 1)
random_list = list(range(100))
shuffle(random_list)
print(random_list)
print(max_min(random_list)) # (99, 0)
print(max_min([])) # 'Empty List'
|
114b925629f4dcc228229be6eebb4576e57adef3 | vasyanch/edu | /Algo_club/inc.py | 539 | 3.609375 | 4 | # фун. inc() прибавляет 1 к числу в двоичном виде.
# это число храниться в массиве в виде [1, 0, 1, 0, 1]
# разобраться с тем что делает этот алгоритм
def inc(x): # x - число в виде массива
n = len(x)
for i, v in enumerate(x):
if v == 0:
break
if i == n - 1:
return False
for j in range(n - 1, i - 1, -1):
x[j] = abs(x[j] - 1)
return True
|
55b2abc3237b85f98149f993ae984d8de35b4853 | elrossco2/LearnPython | /CH6/HW/barry/12.py | 433 | 4.03125 | 4 | from math import *
def sumList(nums):
total = 0
for i in nums:
total = total + i
return total
def main():
print("Sum a list of numbers. ")
nums = input("Enter a list of numbers seperated by a space: ")
nums = nums.split()
entry = 0
for i in nums:
nums[entry] = int(i)
entry = entry + 1
sumTotal = sumList(nums)
print("The sum of your list is: ",sumTotal)
main()
|
4f186b7ca4636b0dc15b46a79bc61fffb9a6f58b | rafaelgama/Curso_Python | /Udemy/Secao2/aula30.py | 287 | 4.15625 | 4 | """
While em python - Aula 30
"""
x = 0
while x < 10:
if x == 3:
x += 1
continue # funciona como o loop em ADVPL, ele pula o laço que está sendo excutado.
if x == 8:
break # funciona como o exit emADVPL, ele finaliza o loop.
print(x)
x += 1
|
0146a1b3554007da3d06c315b5fefb3aa976f9e1 | sky3116391/selfteaching-python-camp | /exercises/1901090005/1001S02E05_stats_text.py | 1,111 | 3.6875 | 4 | text = '''
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambxiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
import re
a = re.sub('[^a-zA-Z ]',' ',text)
b = a.split()
c = {}
for word in b:
value = c.get(word,0)
value += 1
c[word] = value
d = sorted(c.items(), key=lambda x:x[1], reverse=True)
print(d) |
479557ce007852180509ea6de93727592574b742 | AdamZeh/program-arcade-games | /Lab 01 - Calculator/lab_01_part_a.py | 157 | 3.96875 | 4 | # The formula for F to C is F-32*5/9=C.
s = input("Enter temperature in Fahrenheit: ")
f = int(s)
c = (f - 32)*5/9
print("The temperature in Celsius:", c, )
|
ecc06234c11535bb517937d93ccfc7dd0ab38872 | lucasilvabc/CS241 | /CS241_check05a.py.py | 641 | 3.65625 | 4 |
class Ship:
def __init__(self):
self.x = 0
self.y = 0
self.dx = 0
self.dy = 0
def advance(self):
self.ship.x += self.ship.dx
self.ship.y += self.ship.dy
def draw(self):
print("Drawing ship at ({}, {})".format(self.ship.x, self.ship.y))
class Game:
def __init__(self, dx, dy):
self.ship = Ship()
self.ship.dx = dx
self.ship.dy = dy
def on_draw(self):
Ship.draw(self)
def update(self):
Ship.advance(self) |
48c30105a918d702721e736011bfa934d0739b7c | aaloksinghvi/technicaltest | /TEST3/saledata.py | 1,147 | 3.75 | 4 | #!/usr/local/opt/python/bin/python3.7
import pandas as pd
import numpy as np
import sys
def getProperties(file_name):
try:
df = pd.read_csv(file_name)
df['pricePerSqft'] = df['price'].divide(df['sq__ft'])
df = df.replace([np.inf, -np.inf], np.nan).dropna()
averagePricePerSqft = df['pricePerSqft'].mean()
print("Average Price / SQ.Foot" + str(averagePricePerSqft))
df = df[df['pricePerSqft']<averagePricePerSqft]
print("Creating a report for properties sold for less than the average price / sq.foot to sales-data-filtered.csv")
df.to_csv('sales-data-filtered.csv')
except:
print("Exception in getProperties def block")
if __name__ == "__main__":
print (" TEST3 : Generate a new CSV file that only includes properties sold for less than the average price / sq.foot.")
file_name = input("Enter filename with full path: ")
if len(file_name) == 0:
print("Next time please enter something")
sys.exit()
try:
getProperties(file_name)
except IOError:
print ("There was an error reading file")
sys.exit()
|
dd1eb4af7df0ebbcd821223bfb8323033a76435f | donRumata03/Neural_Network_Implementations | /NN_basic_functions.py | 5,183 | 3.65625 | 4 | import random
from matplotlib import pyplot as plt
import numpy as np
from typing import *
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return sigmoid(x) * (1 - sigmoid(x))
def known_sigmoid_derivative(s_val):
return s_val * (1 - s_val)
Scary_val = Union[np.array, float, np.float64, np.float32]
class Derivativable_function:
@staticmethod
def compute(value: Scary_val) -> Scary_val:
raise Exception
@staticmethod
def derivative(value: Scary_val, function_value: Scary_val) -> Scary_val:
raise Exception
"""
Here are some common Activation functions with their derivatives:
1) Sigmoid
2) Hyperbolic tangent
3) ReLU (with neuron death protection)
4) ...
"""
class Activation_function(Derivativable_function):
pass
class Sigmoid(Activation_function):
@staticmethod
def compute(value : Scary_val) -> Scary_val:
return 1 / (1 + np.exp(-value))
@staticmethod
def derivative(value : Scary_val, function_value : Scary_val) -> Scary_val:
return function_value * (1 - function_value)
class HyperTan(Activation_function):
@staticmethod
def compute(value : Scary_val) -> Scary_val:
exp2x = np.exp(2 * value)
return (exp2x - 1) / (exp2x + 1)
@staticmethod
def derivative(value : Scary_val, function_value : Scary_val) -> Union[np.array, float, np.float64, np.float32]:
return 1 - function_value ** 2
class ReLU(Activation_function):
@staticmethod
def compute_impl(value : Scary_val, alpha : float = 0.075) -> Union[None, float]:
"""
Not Really weird function :)
Though, it isn`t used ^)), so it doesn`t need to work
"""
if isinstance(value, np.ndarray):
if len(value.shape) == 1:
for i in range(len(value)):
value[i] = ReLU.compute_impl(value[i])
else:
for i in range(len(value)):
ReLU.compute_impl(value[i])
else:
return max(-alpha * value, value)
@staticmethod
def derivative_impl(value: Scary_val, indexes : Union[tuple, int] = None, alpha: float = 0.075) -> Union[None, float]:
"""
Really weird function :)
Also not used, but it works
"""
if isinstance(value, np.ndarray) and len(value.shape) > len(indexes):
if len(value.shape) == 1:
for i in range(value.shape[len(indexes)]):
ReLU.derivative_impl(value, indexes = tuple(list(indexes) + [i]))
else:
for i in range(value.shape[len(indexes)]):
ReLU.derivative_impl(value, indexes=tuple(list(indexes) + [i]))
else:
index_sequence = ""
for j in range(len(indexes)):
index_sequence += f"[{indexes[j]}]"
exec(f"value{index_sequence} = (-alpha if value{index_sequence} < 0 else 1)")
@staticmethod
def compute(value : Scary_val, alpha : float = 0.075) -> Scary_val:
return np.maximum(value * alpha, value)
@staticmethod
def derivative(value : Scary_val,
function_value : Scary_val, alpha : float = 0.075) -> Scary_val:
value[value==0] = 1
return function_value / value
# new_val = value.copy()
# ReLU.derivative_impl(new_val, (), alpha)
# return new_val
"""
Here are some loss functions with their derivatives defined
1) MSE
2) SoftMax
3) Cross Entropy
"""
class Loss_function(Derivativable_function):
@staticmethod
def compute(output: Scary_val, answer : Scary_val) -> Scary_val:
raise Exception
@staticmethod
def derivative(output: Scary_val, answer : Scary_val, function_value : Scary_val) -> Scary_val:
raise Exception
class MSE(Loss_function):
@staticmethod
def compute(output: Scary_val, answer : Scary_val) -> Scary_val:
return np.mean((output - answer)** 2)
@staticmethod
def derivative(output: Scary_val, answer : Scary_val, function_value : Scary_val) -> Scary_val:
return 2 * (output - answer) / len(output)
class SoftMax(Loss_function):
@staticmethod
def compute(output: Scary_val, answer : Scary_val) -> Scary_val:
exps = np.exp(output)
return exps / exps.sum()
@staticmethod
def derivative(output: Scary_val, answer : Scary_val, function_value : Scary_val) -> Scary_val:
s = function_value.reshape(-1, 1)
return np.diagflat(s) - np.dot(s, s.T)
if __name__ == '__main__':
example_output = np.array([1., 2, 3, 4, 0.1, 10])
example_answer = np.array([1., 3, 5, 7, 100])
print(ReLU.compute(example_output))
print()
function_out = SoftMax.compute(example_output, example_answer)
print(list(map(lambda x: round(x, 3), function_out, )))
print(MSE.derivative(example_output, example_answer, function_out))
# ms = np.array([[-2, 3, 2., 0, 100],
# [-2200, 34, 2., -1, 101]])
# val = ReLU.compute(ms.copy())
# der = (ReLU.compute(ms + 0.00000001) - val) / 0.00000001
# print(val)
# print(ReLU.derivative(ms.copy(), val))
|
c6645f78f98131e9b6ff96141d1dd571864ae994 | lakhanpaul/binary-search-algorithm | /main.py | 1,012 | 4.25 | 4 | # Binary Search
def binary_search(data, elem):
low = 0
high = len(data) - 1
while low <= high:
middle = (low + high) // 2
if data[middle] == elem:
print("Your desired element ", elem, "is at position ", middle)
return middle
elif data[middle] > elem:
print("This position's values is too high, still searching...")
high = middle - 1
elif data[middle] < elem:
print("This position's values is too low, still searching...")
low = middle + 1
else:
print("Your desired element does not exist in this list of data")
return -1
data_values = [1, 3, 4, 6, 7, 8, 10, 13, 14, 18, 19, 21, 24, 37, 40, 45, 71]
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
desired_element = int(input("Enter your desired element here: "))
binary_search(data_values, desired_element)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
49e6156d84ce93e7bc0f8a77fdb021c7e562e655 | antonyvam/python3 | /Python3/src/_Exercises/src/Basic/ex4-1.py | 452 | 3.9375 | 4 | """
Write a function that calculates the area of a rectangle.
Decide how many input parameters your function needs.
The area should be returned from the function. Write a
test program that calls your function with different sets
of test data.
"""
def Area(length, breadth):
return length * breadth
""" Tests """
print( Area(40, 20) )
print( Area(41, 19) )
print( Area(42, 18) )
print( Area(43, 17) )
print( Area(44, 16) )
|
375e2b8aab37da0b6d03a18a1bd9770161085db7 | ayeshabhutto/Moving-Ball | /BallMovement.py | 5,237 | 3.734375 | 4 | import pygame
import random
import math
init()
size = width, height = 800, 800
screen = display.set_mode(size)
#Setting up colour
BLACK = (0, 0, 0)
WHITE = (255,255,255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
FONT = font.SysFont("Times New Roman",30) # done once
FONT2 = font.SysFont("comicsansms",100) # done once
# setting up constants to help with the parts of the list
BALLX = 0
BALLY = 1
BALLSPEEDX = 2
BALLSPEEDY = 3
COLOUR = 4
radiusOFball = 10
# function to set up a ball with random attributes
def initBall():
ballx = random.randint(0, 800) # randomly setting the x position
bally = random.randint(0, 800) # randomly setting the y position
dirx = random.randint(-5,5) # randomly setting the x speed
diry = random.randint(-5,5) # randomly setting the y speed
COLOUR = random.choice([BLUE, GREEN, RED, WHITE])
info = [ballx, bally, dirx, diry, COLOUR] # returning a list with all the info the ball needs
return info # returning the list
def drawScreen(ClicksonBall):
draw.rect(screen, BLACK, (0, 0, 800, 800))
text = FONT.render(str(ClicksonBall), 1, (255,255, 255))
screen.blit(text, Rect(750,10,200,100))
def moveBall(info): # takes in the list of the ball
info[BALLX] += info[BALLSPEEDX] # increases the position of the ball
info[BALLY] += info[BALLSPEEDY]
# checks to see if the ball is hitting the walls in the x direction
if info[BALLX] > 800:
info[BALLX] = 800
info[BALLSPEEDX] *= -1
elif info[BALLX] < 0:
info[BALLX] = 0
info[BALLSPEEDX] *= -1
# checks to see if the ball is hitting the walls in the y direction
if info[BALLY] < 0:
info[BALLY] = 0
info[BALLSPEEDY] *= -1
elif info[BALLY] > 800:
info[BALLY] = 800
info[BALLSPEEDY] *= -1
return info # returning the updated list
def ballIsClicked(info, mx, my):
print(mx >= info[BALLX])
if mx >= info[BALLX] - radiusOFball and mx <= info[BALLX] + radiusOFball:
if my >= info[BALLY] - radiusOFball and my <= info[BALLY] + radiusOFball:
return True
return False
def BallCollision(info1, info2):
distance = ((info2[BALLX] - info1[BALLX])**2 + (info2[BALLY] - info1[BALLY])**2)
if distance < 0: #so we can still get the distance if the number is negative
distance *= -1
distance = sqrt(distance)
if distance <= radiusOFball:
return True
return False
def drawBall(info): # sends a ball to be displayed
draw.circle(screen, info[COLOUR], (info[BALLX], info[BALLY]), radiusOFball)
running = True # variable that controls the main loop
myClock = time.Clock() # for controlling the frames per second
balls = []
ClicksonBall = 0
win = False
redLeft = False
for i in range(0,10):
balls.append(initBall()) # initializing the ball
# Game Loop
while running == True: # do this loop as long as running is True
redLeft = False
# events all ready
for evnt in event.get(): # checks all events that happen
if evnt.type == QUIT:
running = False
if evnt.type == MOUSEBUTTONDOWN:
print('click')
mx, my = evnt.pos
button = evnt.button
for ball1 in balls:
if ballIsClicked(ball1, mx, my) and ball1[COLOUR] == RED:
balls[balls.index(ball1)] = initBall()
ClicksonBall += 1
break
#draw the black background
drawScreen(ClicksonBall)
# moving each ball and drawing it
for i in range(0,len(balls)):
# calling the draw ball function and sending the ball information
drawBall(balls[i])
balls[i] = moveBall(balls[i])
for ball2 in balls:
if ball2 is not balls[i] and BallCollision(balls[i], ball2):
c1 = balls[i][COLOUR]
c2 = ball2[COLOUR]
if c1 == GREEN or c2 == GREEN:
balls[i][COLOUR] = GREEN
ball2[COLOUR] = GREEN
elif (c1 == WHITE and c2 == BLUE) or (c1 == BLUE and c2 == WHITE):
balls[i][COLOUR] = WHITE
ball2[COLOUR] = WHITE
elif (c1 == RED and c2 is not GREEN) or (c2 == RED and c1 is not GREEN):
balls[i][COLOUR] = RED
ball2[COLOUR] = RED
if balls[i][COLOUR] == RED:
redLeft = True
display.flip()
myClock.tick(60) # waits long enough to have 60 frames per second
if not redLeft:
running = False
if ClicksonBall >= 5:
win = True
running = False
if win:
drawScreen('')
text = FONT2.render('You Win!', 1, (75,255, 241))
screen.blit(text, Rect(200,200,25,25))
display.flip()
time.wait(3000)
else:
drawScreen('')
text = FONT2.render('You lost.', 1, (75,255, 241))
screen.blit(text, Rect(200,200,25,25))
display.flip()
time.wait(3000)
quit()
|
620b6852bbe71426757630fe23229c32cd870d16 | iamGauravMehta/Hackerrank-Problem-Solving | /Algorithms/Implementation/day-of-the-programmer.py | 671 | 3.90625 | 4 | # Day of the Programmer
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/day-of-the-programmer/problem
# Time complexity: O(1)
import os
# Complete the solve function below.
def solve(year):
if year == 1918:
return "26.09.1918"
elif (year <= 1917 and year % 4 == 0) or (year > 1918 and (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0))):
return "12.09.{}".format(year)
else:
return "13.09.{}".format(year)
if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
year = int(input())
result = solve(year)
print (result + '\n')
# fptr.write(result + '\n')
# fptr.close() |
d53489c13dd78ae42d877aad36bfb98e84d2c04e | SeanFoley123/word_reader | /word_reader2.py | 4,208 | 3.828125 | 4 | class Node(object):
"""This will ONLY work for words that all start with the same letter. It starts checking at the children level, not the grandparent.
You also need to specify if the first letter begins a word.
Also credit goes to http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
"""
def __init__(self, value, children=None):
self.value = value
self.children = children
if self.children == None:
self.children = []
def check(self, string_in, index=0): #checks if the next index of the given string is the value of any of self's children. I think this one works.
i = 0 #index of which child you are at
letter_is_word = string_in[0] in ['a', 'i', 'o']
if len(string_in)==1 and letter_is_word: #Depends on the letter: a is a word, e is not.
return True
while True: #as long as you don't have a result, keep checking through the children
if i == len(self.children): #if we've exhausted all the children without returning a true
return False
child = self.children[i]
if child.value == string_in[index+1]: #if the child has the value of the next index of the string: so, if
if index+1 == len(string_in)-1:
return child.is_leaf()
else: #not the end of the string, so go another layer deep
return child.check(string_in, index+1)
i += 1
def display(self, level = 0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.display(level+1)
return ret
def is_leaf(self):
for child in self.children: #is it a standalone word? ex: cartoon is a word. Every word must end in ''
if child.value == '':
return True
return False
def return_children_values(self):
result = []
for child in self.children:
result.append(child.value)
return result
def create_node(word_list, start_letter):
whole_node = Node(start_letter)
added_node = False
for word in word_list:
current_node = whole_node
for i in range(1, len(word)):
for child in current_node.children:
if word[i] == child.value:
current_node = child
added_node = True
break
if not added_node:
new_node = Node(word[i], [])
current_node.children.append(new_node)
current_node = new_node
added_node = False
current_node.children.append(Node(''))
return whole_node
def list_words(word_in):
all_words_file = open('words.txt') #makes a list of words out of the file
all_words = []
for word in all_words_file:
all_words.append(word.strip())
all_words.sort()
end_index = 0 #makes a dictionary of lists of words starting with each letter
list_dict = {}
for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
temp = []
for i in range(end_index, len(all_words)):
if all_words[i][0] != letter:
end_index = i
break
temp.append(all_words[i])
list_dict[letter] = temp
node_dict = {}
for key in list_dict: #turns the dictionary of lists into a dictionary of trees
node_dict[key] = create_node(list_dict[key], key)
words_result = []
for i in range(len(word_in)):
for k in range(i+1, len(word_in)):
if word_in[i:k+1] not in words_result:
result = node_dict[word_in[i]].check(word_in[i:k+1])
if result:
words_result.append(word_in[i:k+1])
for i in range(len(words_result)):
words_result[i] = words_result[i].title()
words_result.sort() #make the list sorted a. by length and b. alphabetically
words_result.sort(key=len, reverse=True)
print
print words_result #prints results and restarts
print
word_input(False)
def word_input(first):
if first:
user_word = raw_input('Enter a word: ')
else:
user_word = raw_input('Enter another word! This is fun!: ')
user_word = user_word.lower()
adjusted_input = []
for letter in user_word:
if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
adjusted_input.append(letter)
adjusted_input = ''.join(adjusted_input)
list_words(adjusted_input)
if __name__ == '__main__':
word_input(True) |
807f9112aab0832b60e314546e11421913784685 | Bellroute/python_class | /someday/example0904.py | 250 | 3.78125 | 4 | def main():
x = int(input('type a starting number : '))
y = int(input('type an ending number : '))
sumx = 0
for i in range(x, y+1):
if i % 2 == 0:
sumx += 1
print(sumx)
if __name__ == '__main__':
main() |
492952451bd701600c61379ad1ab76ea197b9deb | DaveFres/Python_Projects | /coursera/week_4/magic_file.py | 1,112 | 3.78125 | 4 | #!/usr/bin/env python3
import os
import tempfile
class File:
def __init__(self, full_path):
self.full_path = full_path
def write(self, str_to_write):
with open(self.full_path, 'w') as f:
f.write(str_to_write)
def __add__(self, obj):
# Creating new file in /tmp
new_file_path = os.path.join(tempfile.gettempdir(), 'result.txt')
# Writing content of file1 in result file
with open(new_file_path, 'w') as result:
with open(self.full_path, 'r') as file1:
file1_content = file1.read()
result.write(file1_content)
# Adding content of file2 in result file
with open(new_file_path, 'a') as result:
with open(obj.full_path, 'r') as file2:
file2_content = file2.read()
result.write(file2_content)
return File(new_file_path)
def __str__(self):
return self.full_path
def __getitem__(self, index):
with open(self.full_path, 'r') as f:
f_cont = f.readlines()
return f_cont[index]
|
17930236a875638db0bac2567489522647c7ee5b | kylemitra/unit_testing_in_class_exercise | /unit_test_exercise.py | 341 | 3.5 | 4 | def line_maker(p1, p2, x):
slope = (p2[1] - p1[1]) / (p2[0] - p1[0])
b = p2[1] - (slope*p2[0])
y = (slope*x) + b
return y
def point_tester(p1, p2, p3):
slope = (p2[1] - p1[1]) / (p2[0] - p1[0])
b = p2[1] - (slope*p2[0])
y = (slope*p3[0]) + b
if y == p3[1]:
return True
else:
return False
|
aba0c71e39db6487306dabbd78b4207d6eef3820 | TomYablonski/pdsnd_github | /bikeshare.py | 10,617 | 4.28125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
CRED = '\033[91m'
CGREEN = '\033[92m'
CEND = '\033[0m'
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
try:
print(CGREEN + "\n To see the bikeshare data for a selected city")
print("Please enter one of these cities")
print("Chicago, New York, or Washington \n" +CEND)
city = input().lower()
if city == "new york":
city = "new york city"
if city != "chicago" and \
city != "new york city" and \
city != "washington":
print(CRED + "Invalid city name entered. Please try again." + CEND)
if city == "chicago" or \
city == "new york city" or \
city == "washington":
break
except:
print(CRED + "Unexpected Error occurred getting the City" +CEND)
# TO DO: get user input for month (all, january, february, ... , june)
while True:
try:
print("\n Which month would you like to see the data for ?")
print("January, February, March, April, May or June. To see all enter All \n")
month = input().lower()
if month != "january" and \
month != "february" and \
month != "march" and \
month != "april" and \
month != "may" and \
month != "june" and \
month != "all":
print(CRED + "Invalid month entered. Please try again." + CEND)
if month == "january" or \
month == "february" or \
month == "march" or \
month == "april" or \
month == "may" or \
month == "june" or \
month == "all":
break
except:
print(CRED + "Unexpected Error occurred getting the Month" + CEND)
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
while True:
try:
print("\n Which day would you like to see the data for ?")
print("Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday. To see all enter All \n")
day = input().lower()
if day != "monday" and \
day != "tuesday" and \
day != "wednesday" and \
day != "thursday" and \
day != "friday" and \
day != "saturday" and \
day != "sunday" and \
day != "all":
print(CRED + "Invalid day entered. Please try again." + CEND)
if day == "monday" or \
day == "tuesday" or \
day == "wednesday" or \
day == "thursday" or \
day == "friday" or \
day == "saturday" or \
day == "sunday" or \
day == "all":
break
except:
print(CRED + "Unexpected Error occurred getting the Day" + CEND)
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
if month != 'all':
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
df = df[df['month'] == month]
if day != 'all':
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
CEND = '\033[0m'
CBOLD = '\033[1m'
print(CBOLD + '\nCalculating The Most Frequent Times of Travel...\n' + CEND)
start_time = time.time()
# TO DO: display the most common month
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
popular_month = df['month'].mode()[0]
print('Most common Month:', popular_month)
# TO DO: display the most common day of week
df['day_of_week'] = df['Start Time'].dt.weekday_name
popular_day = df['day_of_week'].mode()[0]
print('Most common Start Hour:', popular_day)
# TO DO: display the most common start hour
df['hour'] = df['Start Time'].dt.hour
popular_hour = df['hour'].mode()[0]
print('Most common Start Hour:', popular_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
CEND = '\033[0m'
CBOLD = '\033[1m'
print(CBOLD + '\nCalculating The Most Popular Stations and Trip...\n' + CEND)
start_time = time.time()
# TO DO: display most commonly used start station
popular_start_station = df['Start Station'].mode()[0]
print('Most common Start Station is:', popular_start_station)
# TO DO: display most commonly used end station
popular_end_station = df['End Station'].mode()[0]
print('Most common End Station is:', popular_end_station)
# TO DO: display most frequent combination of start station and end station trip
start_stop_station = (df['Start Station'] + ' - ' + df['End Station']).mode()[0]
print('\nMost frequent combination of start station and end station is:')
print(start_stop_station)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
CEND = '\033[0m'
CBOLD = '\033[1m'
print(CBOLD + '\nCalculating Trip Duration...\n' + CEND)
start_time = time.time()
# TO DO: display total travel time
total_travel_time = df['Trip Duration'].sum()
holdtime = int(total_travel_time)
days = holdtime // (24 * 3600)
holdtime = holdtime % (24 * 3600)
hours = holdtime // 3600
holdtime %= 3600
minutes = holdtime // 60
holdtime %= 60
seconds = holdtime
print("Total travel time : {} days, {} hours, {} minutes, {} seconds"\
.format(days, hours, minutes, seconds))
# TO DO: display mean travel time
mean_travel_time = df['Trip Duration'].mean()
holdtime = int(mean_travel_time)
days = holdtime // (24 * 3600)
holdtime = holdtime % (24 * 3600)
hours = holdtime // 3600
holdtime %= 3600
minutes = holdtime // 60
holdtime %= 60
seconds = holdtime
print("The mean travel time : {} days, {} hours, {} minutes, {} seconds"\
.format(days, hours, minutes, seconds))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
CRED = '\033[91m'
CEND = '\033[0m'
CBOLD = '\033[1m'
print(CBOLD + '\nCalculating User Stats...\n' + CEND)
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
print("User Type Data :")
for index, user_type in enumerate(user_types):
print("{}: {}".format(user_types.index[index], user_type))
# TO DO: Display counts of gender
if 'Gender' in df.columns:
print("\nGender Data :")
genders = df['Gender'].value_counts()
for index, gender in enumerate(genders):
print("Gender \n {}: {}".format(genders.index[index], gender))
else:
print(CRED + "Gender data in not found in ths cities data" + CEND)
# TO DO: Display earliest, most recent, and most common year of birth
print("\n\n Birth Year Data")
if 'Birth Year' in df.columns:
early_birth_year = df['Birth Year'].min()
print("The earliest year of birth is : ", early_birth_year)
recent_birth_year = df['Birth Year'].max()
print("The most recent year of birth is : ", recent_birth_year)
common_birth_year = df['Birth Year'].value_counts().idxmax()
print("The most common year of birth is : ", common_birth_year)
else:
print(CRED + "Birth Year data in not found in ths selection of data" + CEND)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def raw_data(df):
"""Displays statistics on bikeshare users."""
CRED = '\033[91m'
CEND = '\033[0m'
rowcnt = 0
print('\nDisplay the data...\n')
print("\nWould you like to see the raw data ?")
print("Please entter 'yes' or 'no' \n")
displaydata = input().lower()
while True:
if displaydata != "yes" and displaydata != "no":
print(CRED + "Invalid answer entered. Please enter 'yes' or 'no'\n" + CEND)
displaydata = input("\nPlease enter either 'yes or 'no'\n")
if displaydata == "no":
return
if displaydata == "yes":
print(df[rowcnt: rowcnt + 5])
rowcnt = rowcnt + 5
displaydata = input("\nWould you like to see 5 more rows of data ? Enter 'yes' or 'no'\n")
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
raw_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
94b634ed12c5f4e3f3bc5f1255a45f76b013438c | poojashahuraj/CTCI | /practice/practice/matrix/multiply_two_matrices.py | 589 | 3.96875 | 4 | def multiply_two_matrices(mat_1, mat_2):
rows_1 = len(mat_1)
rows_2 = len(mat_2)
columns_1 = len(mat_1[0])
columns_2 = len(mat_2[0])
if columns_1 != rows_2:
return -1
op = [[0 for i in range(columns_2)] for j in range(rows_1)]
for i in range(rows_1):
for j in range(columns_2):
for k in range(rows_2):
op[i][j] += mat_1[i][k]*mat_2[k][j]
return op
mat_1 = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
mat_2 = [[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
print multiply_two_matrices(mat_1, mat_2)
|
8256f6dc57862c13166b250fb8701a31a195a570 | SharpBro/CodeWars | /codewars_svolti/the_observed_pin.py | 2,451 | 4.125 | 4 | """
Alright, detective, one of our colleagues successfully observed our target person, Robby the robber. We followed him to a secret warehouse, where we assume to find all the stolen stuff. The door to this warehouse is secured by an electronic combination lock. Unfortunately our spy isn't sure about the PIN he saw, when Robby entered it.
The keypad has the following layout:
┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┼───┼───┘
│ 0 │
└───┘
He noted the PIN 1357, but he also said, it is possible that each of the digits he saw could actually be another adjacent digit (horizontally or vertically, but not diagonally). E.g. instead of the 1 it could also be the 2 or 4. And instead of the 5 it could also be the 2, 4, 6 or 8.
He also mentioned, he knows this kind of locks. You can enter an unlimited amount of wrong PINs, they never finally lock the system or sound the alarm. That's why we can try out all possible (*) variations.
* possible in sense of: the observed PIN itself and all variations considering the adjacent digits
Can you help us to find all those variations? It would be nice to have a function, that returns an array (or a list in Java and C#) of all variations for an observed PIN with a length of 1 to 8 digits. We could name the function getPINs (get_pins in python, GetPINs in C#). But please note that all PINs, the observed one and also the results, must be strings, because of potentially leading '0's. We already prepared some test cases for you.
Detective, we count on you!
"""
import itertools
def get_pins(observed):
lista_crack = [['1','2','4'],['1','2','3','5'],['2','3','6'],['1','4','5','7'],['2','4','5','6','8'],['3','5','6','9'],['4','7','8'],['5','7','8','9','0'],['6','8','9'],['0','8']]
observ_crack = []
for carattere in observed:
carattere = int(carattere)
observ_crack.append(lista_crack[carattere - 1])#sottolista contenente esclusivamente le cifre di observed
lista_possibili_pass = list(itertools.product(*observ_crack))#lista di tuple contenente tutte le permutazioni della password
lista_mod = []
for elem in lista_possibili_pass:
lista_mod.append(''.join(elem))#conversione delle tuple in stringhe
return(lista_mod)
get_pins("369")
|
950f89dd217e1e319cc6d75e7bf414b7fbf62648 | Rotendahl/Gymnasie-tjeneste | /fagpakker/Machine Learning/uge2/pyIntro.py | 1,074 | 3.8125 | 4 |
# Dette er en kommentar som python ikke ser.
""" Dette er en kommentar, der kan strække sig over flere linjer
Hvor vildt! """
# hvis vi gerne vil se resultatet af en udregning sætter vi "print" foran
# I python kan man nemt lave udregninger.
print 2 + 2
print 10 / 2
print 1.1 * 9
# Hvis vi gerne vil gemme vores udregninger gøres det sålede
hilsen = "Hej med jer"
tal1 = 2 + 2
tal2 = 10 / 2
tal3 = 1.1 * 9
# Vi kan så bruge vores gemte tal.
print tal4 = tal1 * tal3 / tal2
# Hvis man vil styre hvad der skal ske kan det gøres med "if" udtryk
if(tal1 < tal2):
print "Tal 1 er mindre end tal 2"
else:
print "Tal 1 er større eller lig med tal 2"
# Hvis vi vil gentage noget et bestemt antal gange kan vi bruge en "for" løkke
# Erstat "n" med antal gange det skal køres.
for i in range(0, n):
# Her skal den kode som skal gentages skrives
# Her printes antal gange løkken har kørt.
print "Jeg har kørt: " + str(i) + " gange"
def prikProd(v1, v2, u1, u2):
return v1 * u1 + v2 * u2
fac = 1
for i in range(1, 10):
fac = fac * i
|
3616290900b74c8df13b24a36104a3c340dfb3b5 | Jinyiji/codingtest | /0821/26-1.py | 791 | 3.546875 | 4 | def solution(tile_length):
answer = ''
com = 'RRRGGB'
if tile_length%6 == 1 or tile_length%6 == 2 or tile_length%6 == 4:
answer = '-1'
else:
for i in range(tile_length):
answer += com[i % 6]
return answer
# 아래는 테스트케이스 출력을 해보기 위한 코드입니다.
tile_length1 = 11
ret1 = solution(tile_length1)
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은 ", ret1, " 입니다.")
tile_length2 = 16
ret2 = solution(tile_length2)
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은 ", ret2, " 입니다.")
# tile_lengthr가 다음과 같을때 return값을 구하시오
# 7
# 값 -1
|
d6f8e92083493751a2af705fd514f6faad53943b | Lei-Tin/OnlineCourses | /edX/MIT 6.00.1x Materials/pset1/bob.py | 387 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 20:21:33 2021
@author: ray-h
"""
s = 'obboboobdboobncubboobbobobobbobob'
lowerBound = 0
upperBound = 3
numOfBob = 0
for i in range(len(s) - 2):
if s[lowerBound:upperBound] == "bob":
numOfBob += 1
lowerBound += 1
upperBound += 1
print("Number of times bob occurs is: " + str(numOfBob)) |
0769338de09c00398d94f6a95c2938e60d8c0cc0 | kevinniechen/ctci-solutions | /chapter1/9-StringRotation.py | 971 | 4.0625 | 4 | '''
Problem 1.9 Determine if a string is a rotation of another string with only one call to isSubstring
August 25, 2017
Kevin Chen
'''
import unittest
def isStringRotation(str1, str2):
'''
time: o(n)
size: 0
where n is # of chars in string
'''
if (len(str1) != len(str2)):
return False
str1_rotations = str1[1:] + str1
if str2 in str1_rotations:
return True
return False
class Test(unittest.TestCase):
def test_different_words(self):
self.assertFalse(isStringRotation('word', 'dish'))
def test_different_lengths(self):
self.assertFalse(isStringRotation('word', 'wordw'))
def test_string_rotation(self):
self.assertTrue(isStringRotation('word', 'dwor'))
self.assertTrue(isStringRotation('word', 'rdwo'))
self.assertTrue(isStringRotation('word', 'ordw'))
self.assertTrue(isStringRotation('dwor', 'ordw'))
if __name__ == '__main__':
unittest.main()
|
9673b1e5a19491540467a37084bc0d89957f0707 | SajanDaheriya/print_all_positive_numbers_my_Captain | /Print_All_positive.py | 334 | 4.09375 | 4 | numbers = input('Enter all numbers(comma seperated): ') # taking input for list1
list1 = numbers.split(',') # Assigning input numbers to a list
list2 = [] # output list
for num in list1:
if int(num)>=0:
list2.append(int(num)) # checking condition and appending to output list
else:
continue
print(list2)
|
0c5600f641f47315609da6cfa4b8453474113946 | luyuan2002/PythonLearn | /series/09IO读写/04序列化.py | 5,901 | 4.03125 | 4 | """
序列化
在程序运行的过程中,所有的变量都是在内存中,比如,定义一个dict
d = dict(name="Andrew", age=20, score=100)
"""
d = dict(name="Andrew", age=20, score=100)
# 可以随时修改变量,比如把name改成'Bill',但是一旦程序结束,变量所占用的内存就被操作系统全部回收。
# 如果没有把修改后的'Bill'存储到磁盘上,下次重新运行程序,变量又被初始化为'Andrew'。
# 我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
# 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
# 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
# Python提供了pickle模块来实现序列化。
# 首先,我们尝试把一个对象序列化并写入文件:
import pickle
print(pickle.dumps(d))
# pickle.dumps()方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。
# 或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object:
f = open("D:\\hello.txt", "wb")
pickle.dump(d, f)
f.close()
# 看看写入的dump.txt文件,一堆乱七八糟的内容,这些都是Python保存的对象内部信息。
#
# 当我们要把对象从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:
fd = open("D:\\hello.txt", "rb")
d = pickle.load(fd)
fd.close()
print(d) # {'name': 'Andrew', 'age': 20, 'score': 100}
# 变量的内容又回来了!
#
# 当然,这个变量和原来的变量是完全不相干的对象,它们只是内容相同而已。
#
# Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python,并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的数据,不能成功地反序列化也没关系。
"""
JSON
如果我们要在不同的编程语言之间传输对象,就必须把对象序列化为标准规格,比如XML
但是更好的方法是JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地储存到磁盘或者铜鼓偶网络传输
JSON不仅是标准格式,而且比XML更快 而且可以直接在Web页面中读取,非常方便。
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:
JSON类型 Python类型
{} dict
[] list
"string" str
1234.56 int或float
true/false True/False
null None
"""
# Python内置的json模块提供了非常完善的Python对象到JSON格式的转换。我们先看看如何把Python对象变成一个JSON:
import json
print(json.dumps(d))
# dumps()方法返回一个str,内容就是标准的JSON。类似的,dump()方法可以直接把JSON写入一个file-like Object。
#
# 要把JSON反序列化为Python对象,用loads()或者对应的load()方法,前者把JSON的字符串反序列化,后者从file-like Object中读取字符串并反序列化:
json_str = '{"name": "Andrew", "age": 20, "score": 100}'
print(json.loads(json_str))
# 由于JSON标准规定JSON编码是UTF-8,所以我们总是能正确地在Python的str与JSON的字符串之间转换。
"""
JSON进阶
Python的dict对象可以直接序列化为JSON的{},不过,很多时候,我们更喜欢用class表示对象,比如定义Student类,然后序列化:
"""
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student("Andrew", 20, 99)
# print(json.dumps(s))
# 运行代码,毫不留情地得到一个TypeError:
# 错误的原因是Student对象不是一个可序列化为JSON的对象。
#
# 如果连class的实例对象都无法序列化为JSON,这肯定不合理!
# 别急,我们仔细看看dumps()方法的参数列表,可以发现,除了第一个必须的obj参数外,dumps()方法还提供了一大堆的可选参数:
# 这些可选参数就是让我们来定制JSON序列化。前面的代码之所以无法把Student类实例序列化为JSON,是因为默认情况下,dumps()方法不知道如何将Student实例变为一个JSON的{}对象。
# 可选参数default就是把任意一个对象变成一个可序列为JSON的对象,我们只需要为Student专门写一个转换函数,再把函数传进去即可:
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
# 这样,Student实例首先被student2dict()函数转换成dict,然后再被顺利序列化为JSON:
print(json.dumps(s, default=student2dict))
# 不过,下次如果遇到一个Teacher类的实例,照样无法序列化为JSON。我们可以偷个懒,把任意class的实例变为dict:
print(json.dumps(s, default=lambda obj: obj.__dict__))
# 因为通常class的实例都有一个__dict__属性,它就是一个dict,用来存储实例变量。也有少数例外,比如定义了__slots__的class。
# 同样的道理,如果我们要把JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象,然后,我们传入的object_hook函数负责把dict转换为Student实例:
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))
# 打印出的是反序列化的Student实例对象。
|
a2856c5fa6b53a1faf6a61e69318b2c8ce36a295 | CodeGolfWhatsapp/Respostas | /015-SQRT/sqrt-eduardo.py | 123 | 3.875 | 4 | def sqrt(a):
x=a
for i in range(20):
x-=(x*x-a)/(2.0*x)
return x
n=sqrt(float(input()))
print('%.2f'%n) |
3b2de7268e16fcca7dc541f08c93a7d1b08d49fb | JSMR-heuristics/JSMR | /test_scripts/test_area/hill_test/4th Time(ex-slowdown)/house.py | 491 | 3.796875 | 4 | class House(object):
def __init__(self, x, y, output):
# Coordinates of the house instance
self.x = int(x)
self.y = int(y)
# output of the house instance
self.output = float(output)
# to which battery is the house currently connected
self.link = []
# the differences in distance between the closest Battery
# and the other batteries
self.diffs = {}
# {0: 51, 1: 40, etc}
self.dists = {}
|
672bfbf22a39e2f94277d45ebe27aca9e3cbc784 | Deniece-long/alltemp | /connmysqldb/usesqlcreatetable.py | 913 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
#连接mysql数据库,删除存在的表,然后创建新表
#打开数据库链接
username ="root"
password ="070809"
databaseName="testdb"
db = MySQLdb.connect("localhost",username,password,databaseName)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句,如果数据库中已经存在表employee则删除
cursor.execute("DROP TABLE IF EXISTS employee2")
#穿件数据表的SQL语句
sql ="""CREATE TABLE EMPLOYEE2(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
)"""
cursor.execute(sql)
sql2 ="""INSERT INTO EMPLOYEE2(
FIRST_NAME,LASET_NAME,AGE,SEX,INCOME)VALUES('Mac','Jhone','20','1','5000'
)"""
try:
cursor.execute(sql2)
db.commit()
except:
db.rollback()
# 关闭数据库连接
db.close() |
3d0b51900ef7dd9db811641ec0e1cf2606b551b3 | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/marc_charbo/lesson02/grid_printer.py | 751 | 3.875 | 4 | #!/usr/bin/env python3
print ('print grid')
minus = "-"
plus = "+"
bar = "|"
space = " "
grid_size = 2
def grid():
for i in range(grid_size+1):
if(i%grid_size==0):
print ()
for j in range(grid_size+1):
if(j%grid_size==0):
print (plus,end=' ')
else:
print (minus,end=' ')
else:
print ()
for k in range(grid_size+1):
if(k%grid_size==0):
print (bar,end=' ')
else:
print (space,end=' ')
def test(n):
for i in range(n):
grid()
def main ():
test(2)
if __name__ == "__main__":
main()
|
760cdf4dc6ee5e842efb23b46895e16fe0110ec1 | AbilashC13/module1-practice-problems-infytq | /problem09.py | 362 | 4.03125 | 4 | #PF-Prac-9
'''
Write a Python function which generates and returns a dictionary where the keys are numbers between 1 and n (both inclusive)
and the values are square of keys.
'''
def generate_dict(number):
#start writing your code here
new_dict={}
for i in range(1,number+1):
new_dict[i]=i**2
return new_dict
number=10
print(generate_dict(number))
|
bf2c7e0b20222b5d9eb80ea2c856e236b0fe97f7 | rsally1/funcode | /pairs.py | 772 | 4.125 | 4 | import unittest
"""
How to find all pairs on integer array whose sum is equal to a given number
example [1,3,6,9] and 9
The answer is 3,6
"""
def find_pair(arr, target):
""" Complexity is O(N^2"""
x = 0
y = 0
for n in arr:
for j in arr:
if n + j == target:
x = n
y = j
break
return (x,y)
class TestPair(unittest.TestCase):
def test_pair_find(self):
arr = [2,7,4,1,15]
target = 5
res = find_pair(arr, target)
print(res)
self.assertEqual((1,4), res)
arr = [1,3,6,7]
target = 9
res = find_pair(arr, target)
print(res)
self.assertEqual((6,3), res)
if __name__ == '__main__':
unittest.main() |
5cc2e2c211c26a8a9095ab9b4916bbd10313d73e | syhwang125/python | /elice14-응용.py | 15,224 | 3.65625 | 4 | ### 14. 응용편
# 이름없는 한줄짜리 함수 만들기
# lambda 인자, 인자, .... : 실행코드
# func2 = lambda name, age: '이름: %s \n나이: %d' %(name, age)
print('-------- 이름없는 한줄짜리 함수 만들기 lambda --------- ')
# 1. x와 y를 인자로 받아 합을 출력하는 lambda 함수를 정의하고 add에 저장하세요.
add = lambda x, y : x+y
# 2. add를 이용해 1과 3의 합을 출력하세요.
print(add(1,3))
print('-------- 인자를 바꾸어 함수를 반복 호출하여 결과값 얻기 --------- ')
## map(f, A)와 같이 map()의 첫번째 인자로 함수를,
## 두번째 인자로 f에 대입할 집합을 입력하면,
## A의 모든 요소를 f에 대입한 결과를 얻을 수 있습니다.
# 실습에 사용할 변수를 선언합니다.
args = [1, 2, 3, 4, 5]
# 1. x를 인자로 받아 x의 제곱 x*x를 리턴하는 lambda 함수를 f에 저장하세요.
f = lambda x : x*x
### 2. args의 모든 요소를 f에 대입하여 결과를 얻은 후 ret1에 저장하세요.
ret1 = map(f, args)
# 3. ret1에 저장된 객체를 리스트 형태로 변환하세요.
ret2 = list(ret1)
# 아래는 출력을 위한 코드입니다. 수정하지 마세요.
print(ret2)
print('-------- 텍스트 파일을 읽고 출력하기 --------- ')
### 텍스트 읽기모드로 파일을 열기 open() -> r,w 모드 read() -> close()
# 1. open()을 이용해 stockcode.txt 텍스트 파일을 읽기 모드로 열고, 파일 객체를 f에 저장하세요.
f = open('stockcode.txt', 'r')
# 2. read()를 이용해 stockcode.txt 파일의 모든 내용을 읽고 data의 저장하세요.
data = f.read()
# 3. data에 저장된 stockcode.txt 파일의 모든 내용을 출력하세요.
print(data)
# 4. close()를 이용해 stockcode.txt 파일을 닫으세요.
f.close()
print('-------- 텍스트 파일을 한줄씩 읽고 출력하기 --------- ')
# 실습에 사용할 변수를 선언합니다.
line_num = 1
# 1. open()을 이용해 stockcode.txt 텍스트 파일을 읽기모드로 열고, 파일 객체를 f에 저장하세요.
f = open('stockcode.txt', 'r')
# 2. readline()을 이용해 stockcode.txt 파일 내용의 한 줄을 읽고 line에 저장하세요.
line = f.readline()
# 3. 실행 버튼을 누르고 주석과 함께 코드를 이해해보세요.
# line_num이 6보다 작을 동안 코드블럭을 실행합니다.
while line_num < 6:
# line_num과 stockcode.txt 파일 내용의 한 줄을 같이 출력합니다.
print('%d | %s' %(line_num, line), end='')
# stockcode.txt 파일 내용의 다음 줄을 읽고 line에 저장합니다.
line = f.readline()
# line_num에 1을 더합니다.
line_num += 1
# 파일을 닫습니다.
f.close()
print('-------- 텍스트 파일을 한줄씩 읽고 출력하기 --------- ')
# 1. open()을 이용해 stockcode.txt 텍스트 파일을 읽기모드로 열고, 파일 객체를 f에 저장하세요.
f = open('stockcode.txt','r')
# 2. readlines()을 이용해 stockcode.txt 파일의 내용을 원소로 갖고 있는 리스트를 lines에 저장하세요.
lines = f.readlines()
# 3. 실행 버튼을 누르고 주석과 함께 코드를 이해해보세요.
# lines의 인덱스와 요소를 각각 line_num과 line에 순서대로 저장합니다.
for line_num, line in enumerate(lines):
# 첫번째 반복문에서는 인덱스 0과 000020 동화약품 \n이 line에 저장됩니다.
print('%d %s' %(line_num+1, line), end='')
# 파일을 닫습니다.
f.close()
print('-------- 파일을 열고 자동으로 닫기 --------- ')
### 파일을 다룰떄는 open(), close()
## with open() as 를 사용하면 파일에 대한 처리가 끝나면 자동으로 파일을 닫을 수 있음
# 1. with open() as를 이용해 stockcode.txt 텍스트 파일을 읽기모드로 열고, 파일 객체를 f에 저장하세요.
with open('stockcode.txt', 'r') as f:
# 실습 결과를 출력하는 코드입니다. 수정하지 마세요.
for line_num, line in enumerate(f.readlines()):
print('%d %s' %(line_num+1, line), end='')
print('-------- 파일의 특정 부분만 읽기 --------- ')
### seek() 는 파일의 특정부분으로 파일을 읽는 위치를 이동시키고 해당 위치부터 일정크기만큼 읽을 수 있음
### read() 인자로 정수를 입력하면 읽을 크기를 지정할 수 있음
# 1. stockcode.txt를 읽기 모드로 열고 f에 저장합니다.
f = open('stockcode.txt', 'r')
# 2. stockcode.txt의 105 바이트 위치부터 파일을 읽기 시작하세요.
f.seek(105)
# 3. 500 바이트 만큼 파일을 읽고 그 내용을 data에 저장하세요.
data = f.read(500)
# 4. 파일을 닫으세요.
f.close()
# 아래는 출력을 위한 코드입니다. 수정하지 마세요.
print(data)
print('-------- 현재 시간 출력하기 --------- ')
### localtime()은 현재 서버 시간을 time.struct_time 형식의 데이터로 리턴함
### localtime()의 리턴값을 변수에 저장하고 인덱싱을 사용히먄 햔제 날짜, 시간등을 접근할 수 있음
# 인덱스0: tm_year (현재 년도)
# 인덱스1: tm_mon (현재 월)
# 인덱스2: tm_mday (현재 날짜)
# 인덱스3: tm_hour (현재 시간)
# 인덱스4: tm_min (현재 분)
# 인덱스5: tm_sec (현재 초)
# 인덱스6: tm_wday (현재 요일)
# 인덱스7: tm_yday (1월 1일부터 현재까지 날짜수)
# 인덱스8: tm_isdst (섬머타임 적용 여부)
# 1. time 모듈에서 localtime() 함수를 임포트하세요.
from time import localtime
# 2. localtime()을 이용해 time.struct_time 형식의 현재시간을 user_time에 저장하세요.
user_time = localtime()
# 3. user_time의 인덱스3 값을 hour에 저장하세요.
hour = user_time[3]
# 4. user_time의 인덱스4 값을 minute에 저장하세요.
minute = user_time[4]
# 5. user_time의 인덱스5 값을 sec에 저장하세요.
sec = user_time[5]
# 아래는 출력을 위한 코드입니다. 수정하지 마세요..
print('이 코드는 <%d시 %d분 %d초>에 실행되었습니다 (UTC+09:00).' %(hour+9, minute, sec))
print('-------- 프로그램 실행시간 계산하기 --------- ')
## datetime 객체의 now() 함수는 현재 시간의 1/10,000,000 초단위까지 처리
# 1. datetime 모듈에서 datetime 객체를 임포트하세요.
from datetime import datetime
# 2. 현재 시간을 측정하여 start에 저장하세요.
start = datetime.now()
# 아래는 실습에 사용되는 코드입니다. 수정하지 마세요.
ret = 0
for i in range(100000):
ret += i
# 3. 현재 시간을 다시 측정하여 end에 저장하세요.
end = datetime.now()
# 4. start와 end에 저장된 두 시간의 차이를 계산하고 elapsed에 저장하세요.
elapsed = end - start
# 아래는 출력을 위한 코드입니다. 수정하지 마세요.
print('1에서 100000까지 더한 결과: %d' %ret)
print('총 계산 시간:', elapsed)
print('-------- 주어진 숫자를 천단위로 구분하기 --------- ')
#input() - 사용자 입력받기
#if~else - if문 개념 배우기
#isdigit() - 문자열이 숫자인지 검사하기
#[::-1] - 리스트 요소 순서를 역순으로 만들기
#for - for문 개념 배우기
#enumerate() - 리스트의 모든 요소를 인덱스와 쌍으로 추출하기
#len() - 시퀀스 자료 크기 이해하기
# 사용자로부터 숫자를 입력받아 변수 num에 저장합니다.
num = input('아무 숫자를 입력하세요: ')
# 사용자가 입력한 문자열이 숫자로만 구성되어 있는지 확인합니다.
if num.isdigit():
# 숫자로만 구성된 문자열이면 사용자가 입력한 숫자를 거꾸로 배열하여 변수 num에 재지정 합니다.
num = num[::-1]
# 결과를 담을 변수 ret을 선언합니다.
ret = ''
# num에서 인덱스와 요소를 하나씩 추출합니다.
for i, c in enumerate(num):
# 인덱스i에 1을 더하여 추출한 숫자의 위치에 대응합니다.
i += 1
# 요소의 위치가 num의 마지막이 아니고 3의 배수이면 추출한 요소 뒤에 쉼표를 더한 값을 ret에 추가합니다.
if i != len(num) and i%3 == 0:
ret += (c + ',')
# 추출한 요소가 마지막에 위치하거나 3의 배수가 아니면 추출한 요소를 ret에 추가합니다.
else:
ret += c
# ret을 거꾸로 배열합니다.
ret = ret[::-1]
print(ret)
# 사용자가 입력한 문자열이 숫자로만 이루어져 있지 않으면 입력한 내용이 숫자가 아니라는 메시지를 출력합니다.
else:
print('입력한 [%s]은 숫자가 아닙니다.' %num)
print('-------- URL 에서 호스트 도메인 추출하기 --------- ')
# 실습에 사용할 변수를 선언합니다.
url = 'https://academy.elice.io/courses/112/lectures/1331/materials/9'
# 1. url에 저장된 문자열을 '/'로 구분한 결과를 tmp에 저장하세요.
tmp = url.split('/')
# 2. tmp에 저장된 리스트에서 인덱스2에 해당하는 요소를 domain에 저장하세요.
domain = tmp[2]
# 아래는 출력을 위한 코드입니다. 수정하지 마세요.
print('URL을 /로 구분한 결과: ', tmp)
print('호스트 도메인: ', domain)
print('-------- 스택 구현하기 --------- ')
# 1. 원소를 갖고 있지 않은 빈 리스트를 생성하여 mystack에 저장하세요.
mystack = []
# data를 mystack에 요소로 추가하는 putdata 함수를 정의합니다.
def putdata(data):
# 2. 전역변수 mystack에 접근하세요.
global mystack
# 3. mystack 리스트에 putdata 함수의 인자인 data를 맨 마지막 요소로 추가하세요.
mystack.append(data)
# 요소를 mystack으로부터 하나 추출하는 함수 popdata를 정의합니다.
def popdata():
# 전역변수 mystack에 접근합니다.
global mystack
# mystack의 크기가 0이면, 즉 추출할 데이터가 없으면 None을 리턴합니다.
if len(mystack) == 0:
return None
# mystack에 데이터가 있으면 mystack.pop()을 리턴합니다.
return mystack.pop()
# 위에서 정의한 putdata를 이용해 문자열, 리스트, 숫자를 mystack에 추가해봅니다.
putdata('데이터1')
putdata([3, 4, 5, 6])
putdata(12345)
# mystack에 저장된 원소를 확인하기 위해 출력해봅니다.
print('<스택상태>: ', end=''); print(mystack)
# popdata()를 호출하여 mystack에서 데이터를 하나 추출하여 ret에 저장합니다.
ret = popdata()
# ret이 None일 때까지 popdata()를 호출하여 mystack으로부터 원소를 하나씩 추출합니다.
while ret != None:
# mystack에서 추출된 원소를 출력합니다.
print('스택에서 데이터 추출된 원소: ', end=''); print(ret)
# mystack에서 원소가 추출된 후 mystack에 저장된 원소를 출력합니다.
print('<스택상태>: ', end=''); print(mystack)
ret = popdata()
print('-------- 문장에 나타나는 문자 빈도수 계산하기 --------- ')
## def - 함수 이해하기
# with~as - 파일을 열고 자동으로 닫기
# read - 텍스트 파일을 읽고 출력하기
# for - for문 개념 배우기
# if~else - if문 개념 배우기
# sorted - 사전 정렬하기
# lambda - 이름없는 한줄짜리 함수 만들기
# 1. filename을 인자로 받는 getTextFreq 함수를 정의하세요.
def getTextFreq(filename):
# 2. with open() as를 이용해 인자로 받은 filname을 읽기모드로 열고 파일 객체를 f에 저장하세요.
with open(filename,'r') as f:
# 3. read()를 이용해 인자로 받은 filename 파일의 모든 내용을 읽고 text에 저장하세요.
text = f.read()
# 4. 원소를 갖고 있지 않은 빈 사전을 생성하여 fa에 저장하세요.
fa = {}
# text의 모든 문자를 추출하고 그 문자가 fa의 키로 존재하면 해당 값을 1 증가합니다.
for c in text:
if c in fa:
fa[c] += 1
# text에서 추출한 문자가 fa의 키로 존재하지 않으면 fa에 새로운 요소로 추가합니다.
else:
fa[c] = 1
return fa
# python.txt를 인자로 하여 getTextFreq가 리턴한 사전을 ret에 저장합니다.
ret = getTextFreq('python.txt')
# ret을 내림차순으로 정렬하여 ret에 다시 저장합니다.
ret = sorted(ret.items(), key=lambda x:x[1], reverse=True)
# (문자, 빈도수)가 요소로 구성된 리스트 형식의 ret을 화면에 보기 좋게 출력합니다.
for c, freq in ret:
# 문자가 '\n'이면 줄바꿈 기호이므로 화면에 출력하지 않고 넘어갑니다.
if c == '\n':
continue
print('[%c] -> [%d]회' %(c, freq))
print('-------- 텍스트 파일에 있는 단어 개수 계산하기 --------- ')
# with~as - 파일을 열고 자동으로 닫기
# read - 텍스트 파일을 읽고 출력하기
# split() - 문자열을 특정 문자로 분리하기
# 1. with open() as를 이용해 python.txt를 읽기모드로 열고 파일 객체를 f에 저장하세요.
with open('python.txt','r') as f:
# 2. read()를 이용해 인자로 받은 python.txt의 모든 내용을 읽고 data에 저장하세요.
data = f.read()
# 3. data에 저장된 python.txt 내용을 split()하여 분리하고 tmp에 저장하세요.
tmp = data.split()
# tmp의 크기, 즉 요소 및 단어의 개수를 출력합니다.
print('단어수: [%d]' %len(tmp))
print('-------- 파일에서 특정 단어 개수 계산하기 --------- ')
# def - 함수 이해하기
#with~as - 파일을 열고 자동으로 닫기
##read - 텍스트 파일을 읽고 출력하기
#while - while문 개념 배우기
#lower() - 문자열 대소문자 변환하기
# 1. filename과 word를 인자로 받는 countWord 함수를 정의하세요.
def countWord(filename, word):
# 2. with open() as를 이용해 인자로 받은 filname을 읽기모드로 열고 파일 객체를 f에 저장하세요.
with open(filename, 'r') as f:
# 3. read()를 이용해 인자로 받은 filename 파일의 모든 내용을 읽고 text에 저장하세요.
text = f.read()
# 4. text에 저장된 모든 문자를 소문자로 변경한 후 text에 다시 저장하세요.
text = text.lower()
# text에서 word가 최초로 나타나는 위치를 구하여 pos에 저장합니다.
pos = text.find(word)
# 단어의 개수를 담을 변수 count를 선언합니다.
count = 0
# find()는 찾고자 하는 문자열이 없을 경우 -1을 리턴합니다. 해당 단어를 찾지 못할 때까지 반복합니다.
while pos != -1:
# 문자열이 존재할 경우 count를 1 증가합니다.
count += 1
# word의 위치 다음부터 다시 text에서 word를 찾습니다.
pos = text.find(word, pos+1)
return count
word = 'python'
# python.txt에서 'python'이 등장하는 빈도수를 ret에 저장합니다.
ret = countWord('python.txt', word)
# ret에 저장된 python의 빈도수를 출력합니다.
print('[%s]의 개수: %d' %(word, ret)) |
9e4a929c398f81cb81a7d2e0ca2f9925de3efcf0 | viktor-edward/AdventOfCode2019 | /src/day4.py | 1,632 | 3.859375 | 4 | def verifyNumber(number):
doubleCondition = False
increasingCondition = True
previous = str(number)[0]
for n in str(number)[1:]:
if int(n) < int(previous):
increasingCondition = False
break
if n == previous:
doubleCondition = True
previous = n
return doubleCondition and increasingCondition
def verifyNumberNewCondition(number):
doubleCondition = False
increasingCondition = True
previous = str(number)[0]
for n in str(number)[1:]:
if int(n) < int(previous):
increasingCondition = False
break
if n == previous and countCharactersInString(n, str(number)) == 2:
doubleCondition = True
previous = n
return doubleCondition and increasingCondition
def countCharactersInString(charToCount, stringInput):
numberOfChar = 0
for c in stringInput:
if c == charToCount:
numberOfChar += 1
return numberOfChar
def main():
lowerLimit = 172851
upperLimit = 675869
sumOfVerifiedNumbers = 0
for i in range(lowerLimit, upperLimit):
if verifyNumber(i):
sumOfVerifiedNumbers += 1
print("Part 1:")
print("Sum of numbers in the range that are ok:")
print(sumOfVerifiedNumbers)
sumOfVerifiedNumbers = 0
for i in range(lowerLimit, upperLimit):
if verifyNumberNewCondition(i):
sumOfVerifiedNumbers += 1
print()
print("Part 2:")
print("Sum of numbers in the range that are ok with new condition: ")
print(sumOfVerifiedNumbers)
if __name__ == '__main__':
main()
|
48ebdb0dfe1c404043e2a7225f516f24188eb020 | gmoran1016/Luthien | /Luthien.py | 4,756 | 3.59375 | 4 | import random
import time
import encounter
import combat
def d6():
return random.randint(1, 6)
def main():
skill = 6 + d6()
max_health = 12 + d6() + d6()
health = max_health
fuel = 6 + d6()
max_fuel = 20
money = 50
system = 1
repairToolAmount = 1
print("""\
__ __ __ ______ __ __ __ ______ __ __
/\ \ /\ \/\ \ /\__ _\ /\ \_\ \ /\ \ /\ ___\ /\ "-.\ \
\ \ \____ \ \ \_\ \ \/_/\ \/ \ \ __ \ \ \ \ \ \ __\ \ \ \-. \
\ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_____\ \ \_\\"\_ \
\/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_____/ \/_/ \/_/
""")
print("Welcome to Luthien a text based Space Adventure Game!")
print("By Brain Zschau & Griffin Moran")
print(
"\nYou find yourself the captain of the Starship Luthien. Congratulations on your promotion!\nAs i'm sure you "
"are aware you are on the run from the Eridu Empire, The most evil empire in the galaxy!")
print(
"\nYour goal is simple, navigate the various star systems of the universe and find and destroy the Eridu "
"Capital ship, simple stuff for a captain such as yourself.\nDuring your journey you will encounter many "
"things so don't be afraid to fail. Though i'm sure somebody with your skills will be fine. Good luck!")
input("\nPress enter to continue")
print("\nFirst we will create your character and ship:")
print("Skill: {} Health: {} Fuel: {}".format(skill, health, fuel))
test = input("\nWould you like to Start with 50 extra salvage (1) \nor \n2 Extra repair tools (2): ")
if test == '1':
money += 50
print('You now have {} Salvage'.format(money))
elif test == '2':
repairToolAmount += 2
print('You now have {} Repair Tools'.format(repairToolAmount))
else:
print('Fine have it your way')
input('\nPress enter to continue')
while system < 5:
area = 1
while area < 11:
print("-------------------------------------------\n"
"You are in system {} area {}, You have Skill: {}, Health: {}, Fuel: {}, and Salvage: {}".format(
system, area, skill, health, fuel, money))
rand = random.randint(1, 100)
# Enemy
if rand < 55:
health = combat.enemy(system, skill, health)
rewardMoney = random.randint(1, 5)
rewardFuel = random.randint(0, 2)
print("**********************\nYou have gained {} Salvage and {} Fuel".format(rewardMoney, rewardFuel))
money += rewardMoney
fuel += rewardFuel
if fuel > max_fuel:
fuel = max_fuel
# Store
elif rand < 70:
money, fuel, max_fuel, repairToolAmount, max_health, skill = encounter.store(money, fuel, max_fuel,
repairToolAmount,
max_health, skill)
# Station
elif rand < 75:
money, fuel, health, skill = encounter.station(money, fuel, max_fuel, health, skill)
if fuel > max_fuel:
fuel = max_fuel
# Nothing
else:
print(encounter.nothing[random.randint(0, len(encounter.nothing) - 1)])
if repairToolAmount > 0 and health < max_health:
selection = input(
"Would you like to use one of your repair tools (you have {} with a health of {} out of {}), "
"y or n?".format(repairToolAmount, health, max_health))
if selection == 'y':
health += d6() + d6()
repairToolAmount -= 1
if health > max_health:
health = max_health
input("Press enter to continue")
if fuel == 0:
selection = input("Sadly you have run out of and are stranded, you ended the game in system {} area {}"
"\n would you like to play again?(y/n)".format(system, area))
if selection == 'y':
main()
exit(0)
fuel -= 1
area += 1
system += 1
combat.finalboss(skill, health, max_health, repairToolAmount)
selection = input(
"{} has been destroyed!!!!!!!!!!!!!\n CONGRATULATION ON WINNING\nWould you like to play again?(y/n)".format(
"Eridu"))
if selection == 'y':
main()
exit(0)
if __name__ == "__main__":
main()
|
5632c2ae3f90b8dd5eae223ae682f6a27412f354 | koushikckm/PythonLearnings | /workspace/OOP/abstraction.py | 435 | 3.984375 | 4 | from abc import ABC,abstractmethod
class Restaurant(ABC):
@abstractmethod
def dininghall(self):
pass
class FiveStar(Restaurant):
def swimmingpool(self):
print("Yes there is a swimming pool")
class BeachSideResort(Restaurant):
def beachsidecafe(self):
print("Yes there is a beachside cafe")
fs=FiveStar()
fs.swimmingpool()
bc=BeachSideResort()
bc.beachsidecafe() |
76b85d853223f737c1ae555c31f61bc1e24b1c9d | gyurel/Python-Advanced-Course | /exercise_functions_advanced/negative_vs_positive.py | 496 | 4.28125 | 4 | def negative_vs_positive(nrs, neg, pos):
for x in nrs:
if x < 0:
neg += x
else:
pos += x
return neg, pos
negatives = 0
positives = 0
numbers = [int(x) for x in input().split()]
negatives, positives = negative_vs_positive(numbers, negatives, positives)
print(negatives)
print(positives)
if abs(negatives) > positives:
print("The negatives are stronger than the positives")
else:
print("The positives are stronger than the negatives")
|
f9a1d817a59d5bb1ddf37f60b3939a17c8977f24 | atjeprahmat/Code_Fundamental_Python | /nilai.py | 175 | 3.578125 | 4 | print("--contoh 3, Nilai A, B, C--")
n = 55
if n >= 80: #80-100
print("A")
elif n >=75: #75-79
print("B")
elif n >=70: #70-74
print("C")
else: #<=69
print("D") |
9e21151dbb635b132768b6a15bc5146875695259 | javascriptchen/python3basic | /twl/c9.py | 725 | 3.765625 | 4 | # -*- coding: utf-8 -*-
import time
def decorator(func):
# key word
def wrapper(*args,**kw): # args通用叫法
print(time.time())
func(*args,**kw)
return wrapper
@decorator # 装饰器的一个语法糖 @符号
def f1(func_name):
print('This is a function named ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is a function named ' + func_name1)
print('This is a function named ' + func_name2)
@decorator
def f3(func_name1,func_name2,**kw): # 关键字参数
print('This is a function named ' + func_name1)
print('This is a function named ' + func_name2)
print(kw)
f3('test func1','test func2',a=1,b=2)
f1('test func')
f2('test func1','hha')
|
6cb4ee9533974266cfafe13de92f437e02bff916 | shubhamkanade/Niyander-Python | /Object Orientation/Inhertance.py | 443 | 3.890625 | 4 | #in case of multiple which one we inherit first is gets called
class Base1:
def fun(self):
print("Base1 fun")
def gun(self):
print("Base1 gun")
class Base2:
def fun(self):
print("Base2 fun")
class Derived(Base2,Base1): #this is multilevel inheritance
def run(self):
print("Derived run")
def sun(self):
print("Derived sun")
def main():
dobj=Derived()
dobj.fun()
dobj.sun()
if __name__=="__main__":
main()
|
0b3c39ce967b8792ed6bc243c0addb1056879ef0 | kavyareddyp/Assignments | /pyassign/assign3.py | 145 | 4.25 | 4 | """
3.take a number from the user and check whether even or odd
"""
n=input("Enter a number:")
if n%2==0:
print "even"
else:
print "odd"
|
abd990d3f79fcf1f308c857b339770b73c06844c | southpawgeek/perlweeklychallenge-club | /challenge-018/paulo-custodio/python/ch-1.py | 1,288 | 4.40625 | 4 | #!/usr/bin/python3
# Challenge 018
#
# Task #1
# Write a script that takes 2 or more strings as command line parameters and
# print the longest common substring. For example, the longest common substring
# of the strings "ABABC", "BABCA" and "ABCBA" is string "ABC" of length 3.
# Other common substrings are "A", "AB", "B", "BA", "BC" and "C". Please check
# this wiki page for details.
import sys
import re
def longest_substr(strs):
def matches_all(substr, strs):
for s in strs:
if not re.search(substr, s):
return False
return True
longest_len = -1
longest = set()
for s in strs:
for start in range(0, len(s)):
for end in range(start+1, len(s)+1):
if end-start >= longest_len:
substr = s[start:end]
if substr not in longest:
if matches_all(substr, strs):
if end-start == longest_len:
longest.add(substr)
else:
longest = set([substr])
longest_len = end-start
return sorted(list(longest))
print("("+", ".join(['"'+x+'"' for x in longest_substr(sys.argv[1:])])+")")
|
d5c606b01e6a40bdcac38621a6e60fe69db22e1e | maxigarrett/cursoPYTHON | /1-ejercicios primera clase/5-ejercicio.py | 965 | 4.15625 | 4 | #Escribir un programa que pida ingresar un número entero mayor que cero por teclado.
#Verificar si el número ingresado es múltiplo de 2, 3, 4, 5, 6, 7,8 o 9.
#Armar una lista con los números encontrados (por ejemplo, si el número ingresado es múltiplo de 3,6 y 7, armamos una lista que
#contenga estos tres números).
#Mostrar la lista por pantalla, ordenada de mayor a menor.
#En caso de que el número ingresado no sea múltiplo de estos números, mostrar por pantalla el mensaje “No se encontraron
#divisores exactos”.
numero=int(input("ingrese un numero entero"))
lista=[]
if(numero<=0):
print("ingrese un numero mayor a 0")
for item in range(1,numero +1):#para q arranque de 1 y valla hasta el numero que digito el susuario
if(numero % item==0):#si el numero que escribio el usuario dividido por los numero q recorremos da 0 es divisor
lista.append(item)
print("ingresaste el numero ",numero," y los multiplos son: ", lista) |
f6dcecd5cd0b005f6820859aa2fbaa6e2fb022b3 | 1lch2/PythonExercise | /object_oriented/multi-inherit_customize.py | 2,137 | 3.53125 | 4 | # Submachine gun class.
class SMG(object):
def __init__(self, magsize, rpm):
self._magsize = magsize
self._mag = magsize
self._rpm = rpm
@property
def ammo(self):
return self._mag
@property
def rpm(self):
return self._rpm
@rpm.setter
def rpm(self, val: int):
if not isinstance(val, int):
raise TypeError("Input must be an integer.")
self._rpm = val
def fullauto(self, bullets):
if bullets <= 0 or bullets > self._magsize:
raise ValueError('Incorrect bullets count.')
else:
self._mag -= bullets
print('Bullets fired: ' + str(bullets))
def reload(self):
if self._mag == self._magsize:
print('No need for reload.')
else:
self._mag = self._magsize
print('Reload complete.')
# Pistol class.
class HG(object):
def __init__(self, magsize):
self._magsize = magsize
self._mag = magsize
def __str__(self):
return 'Pistol object (magsize: %d)' % self._magsize
def semiauto(self):
if self._mag == 0:
raise ValueError('No bullet in magzine !')
else:
self._mag -= 1
print('Bullets fired: 1.')
# Multi-inheritance test.
class SMG11(SMG, HG):
pass
# Class object iteration.
class EXP(object):
def __init__(self):
self._base = 1
def __iter__(self):
return self
def __next__(self):
self._base = self._base * 2
if self._base > 600:
raise StopIteration()
return self._base
def __getitem__(self, n):
return 2 ** n
def inheritance_test():
# Multi-inheritance.
g1 = SMG11(16, 1270)
g1.fullauto(13)
print(g1.ammo)
g1.reload()
print(g1.rpm)
g1.rpm = 1500
print(g1.rpm)
g1.semiauto()
print(g1.ammo)
def customize_test():
# Customized class with inner variables.
g2 = HG(15)
print(g2)
e = EXP()
for i in e:
print(i)
print(e[6])
if __name__ == '__main__':
inheritance_test()
|
9699d52835d10ecbba5c877519a96f15838b932f | tcider/shabalov-ds-school | /hw1/valid_parentheses.py | 655 | 3.96875 | 4 | from typing import List
class Solution:
def is_valid(self, string: str) -> bool:
stack: List = list()
for char in string:
if char in {"(", "{", "["}:
stack.append(char)
else:
if len(stack):
tmp = stack.pop()
else:
return False
if (
(char == ")" and tmp != "(")
or (char == "]" and tmp != "[")
or (char == "}" and tmp != "{")
):
return False
if len(stack):
return False
return True
|
b63e6dccc9766c5d70e698c88bfa2debd49722b8 | Jakoma02/pyGomoku | /pygomoku/models/observable.py | 672 | 3.515625 | 4 | class Observable:
"""
A simple class to facilitate the observable pattern.
"""
def __init__(self, parent, default=None):
self.parent = parent
self._value = default
self._callables = []
def add_callable(self, clb):
"""
Add a new change handler.
"""
self._callables.append(clb)
def _notify(self):
for c in self._callables:
c(self._value, self.parent)
def set(self, value):
"""
Set new value
"""
self._value = value
self._notify()
def get(self):
"""
Get current value
"""
return self._value
|
df9197a316b44625e66c4b455c3619a434f43e54 | lutfar9427/Exercises_Solution_of_INTRODUCTION_TO_PROGRAMMING_USING_Python | /chapter03/Exercise12_03.py | 751 | 4.625 | 5 | '''
**3.12 (Turtle: draw a star) Write a program that prompts the user to enter the length of
the star and draw a star. (Hint: The inner angle of each point in the star is 36 degrees.)
/**
* @author BASSAM FARAMAWI
* @email tiodaronzi3@yahoo.com
* @since 2018
*/
'''
import turtle # Import turtle module
# Prompt the user to enter the length of the star
lenght = eval(input("Enter the length of the the star:"))
# Draw the star
turtle.forward(lenght)
turtle.right(180 - 36)
turtle.forward(lenght)
turtle.right(180 - 36)
turtle.forward(lenght)
turtle.right(180 - 36)
turtle.forward(lenght)
turtle.right(180 - 36)
turtle.forward(lenght)
turtle.right(180 - 36)
turtle.hideturtle() # Hide the turtle
turtle.done() # Don't close the turtle graphics window
|
97cf37c876ded1b9a417a028d2735bc99414b828 | alexcatmu/CFGS_DAM | /PRIMERO/python/ejercicio76 funciondec.py | 1,337 | 4.21875 | 4 | '''
1.11) Ara que ja sabem fer un “llegirXifraSencera”, el repte és ara
escriure la funció “llegirXifraReal”. Considereu els següents aspectes:
El separador decimal ( punt o coma ) serà configurable, ens el passaran
com paràmetre char.
Haureu de controlar quantes vegades ens posen el separador decimal.
Només el podeu admetre una vegada.
'''
#funciones
def llegirXifraSencera():
dec = input("Indica el tipus de separador decimal: ")
num = input()
totalint = 0
totaldec = 0
numdec = 0
contdec = 0
total = 0.0
while ((ord(num)>= 48 and ord(num) <= 57) or \
(contdec <= 0 and num == dec )):
if (num == dec):
numdec = input()
while (ord(numdec) >= 48 and ord(numdec) <= 57):
numdec = int(numdec)
totaldec = (totaldec * 10) + numdec
numdec = input()
contdec = contdec + 1
else:
num = int(num)
totalint = (totalint * 10) + num
num = input()
for i in range (contdec):
totalint = totalint * 10
totalint = totalint + totaldec
for i in range(contdec):
totalint = totalint / 10
return totalint
#programa
total = llegirXifraSencera()
print(total)
|
47c2278d28a1b84fed3f9ffde1e771430b21c9c7 | gt-rail-internal/dcist-structure-from-noise | /netlogo/tools/adj_mat_from_list.py | 771 | 3.671875 | 4 | import numpy as np
num_nodes = 10
# change this string to the logged output graph from netlogo
# the code will output the adjacency matrix, which can be visualized using an online graph visualizer
input_str = "[[9 3 2 8] [5 4 6 8] [0 9 3 7] [0 9 2 7] [5 1 6 8] [1 4 6 7] [5 1 4 8] [5 9 3 2] [0 1 4 6] [0 3 2 7]]"
input_str = input_str[2:-2]
adj_list_char = input_str.split("] [")
adj_list = [chars.split(" ") for chars in adj_list_char]
adj_list = [[int(number) for number in adj_list[i]] for i in range(0, len(adj_list))]
adj =np.zeros((num_nodes, num_nodes))
for i in range(0, len(adj_list)):
for node in adj_list[i]:
adj[i][node] = 1
adj[node][i] = 1
for row in adj:
for j in range(0, len(row)-1):
print(str(int(row[j]))+', ', end='')
print(int(row[-1]))
|
b0218da3f48387875f000283c2de919bba10d215 | todorovventsi/Software-Engineering | /Programming-Fundamentals-with-Python/lists-advanced-lab/02.To-do-list.py | 305 | 3.953125 | 4 | note = input()
to_do_list = [0] * 10
while not note == "End":
note_importance, note_text = note.split("-")
note_importance = int(note_importance) - 1
to_do_list[note_importance] = note_text
note = input()
to_do_sorted = [task for task in to_do_list if not task == 0]
print(to_do_sorted)
|
70676ef3fdf8336ba4e19b64bf43e643abb79908 | Searge/mipt_oop | /week_1/invariant_internal.py | 643 | 4.09375 | 4 | x = int(input('Enter a number: '))
if x % 3 == 0:
print("Число делится на три.")
elif x % 3 == 1:
print("При делении на три остаток - один.")
else:
assert x % 4 == 2
# assert здесь является комментарием, гарантирующим истинность утверждения
print("Остаток при делении на три - два.")
x = int(input())
assert x > 0, "Positive"
def gcd(a, b):
assert type(a) == int and type(b) == int
assert a > 0 and b > 0
while b != 0:
r = a % b
b = a
a = r
return a
|
e32d49e741c8d8c299228392d62b7fa6c8b709f9 | Apizz789/DATA_STRUCTURES_AND_ALGORITHM | /LAB_01_Quick Python/1.4.py | 2,196 | 3.734375 | 4 | '''
Chapter : 1 - item : 4 - สนุกไปกับการวาดรูป(1)
เขียนภาษา Python เพื่อวาดรูปหัวใจ ซึ่งจะรับ
input เป็นขนาดของรูปหัวใจ โดย input จะมีค่าตั้งแต่ 2 ขึ้นไป
'''
def Top_Heart(inp) :
for i in range(inp-1): # บรรทัด
for j in range(inp-1-i): # จุด "." เซท 1
print(".", end="")
print("*", end="")
if i != 0: # เช็คว่า เช็คว่าเป็นบรรทัดที่ 1 หรือไหม ถ้าไม่ พิมพ์ บวก
for k in range((i*2)-1): # พิมพ์บวกตามจำนวน
print("+", end="")
print("*", end="") # Loop เช็คว่า พิมพ์บวกหรือไหม
# /////////////////////////////// #
for j in range(((inp*2)-3)-2*i):
print(".", end="") # จุด "." เซท 2
# /////////////////////////////// #
print("*", end="")
if i != 0: # เช็คว่า เช็คว่าเป็นบรรทัดที่ 1 หรือไหม ถ้าไม่ พิมพ์ บวก
for k in range((i*2)-1): # พิมพ์บวกตามจำนวน
print("+", end="")
print("*", end="")
for j in range(inp-1-i): # จุด "." เซท 3
print(".", end="")
print()
def Mid_Heart(inp) :
print("*", end="")
for j in range((inp*2)-3):
print("+", end="")
print("*", end="")
for j in range((inp*2)-3):
print("+", end="")
print("*")
def Bottom_Heart(inp) :
for Row in range((inp*2)-2):
print("."*(Row+1), end="")
print("*", end="")
print("+"*((4*inp-5)-((Row+1)*2)), end="")
if ((4*inp-5)-((Row+1)*2)) > 0 :
print("*", end="")
print("."*(Row+1))
if __name__ == "__main__":
print("*** Fun with Drawing ***")
inp = int(input("Enter input : "))
Top_Heart(inp)
Mid_Heart(inp)
Bottom_Heart(inp)
|
11476c8cd98f6d8b549b8cc7fefdc49bae90d048 | YBMu/MLExercice_RWTH_2020 | /exercise-01/q5_knn_python/knn.py | 978 | 3.546875 | 4 | import numpy as np
def knn_distance(element, samples, k):
distArray = np.abs(samples-element)
sort_distArray = np.sort(distArray)
distance = sort_distArray[k-1]
return distance
def knn(samples, k):
# compute density estimation from samples with KNN
# Input
# samples : DxN matrix of data points
# k : number of neighbors
# Output
# estDensity : estimated density in the range of [-5, 5]
#####Insert your code here for subtask 5b#####
# Compute the number of the samples created
answer = np.array([])
sort_samples = np.sort(samples)
N = np.size(samples)
print('Value of k is ', k)
for element in sort_samples:
radius = knn_distance(element, sort_samples, k)
volume = np.pi * (radius**2) # 2d circle as only area, no volume.
prob = (k/N)*(1/volume)
answer = np.append(answer, prob)
estDensity = np.stack((sort_samples, answer), axis=1)
return estDensity
|
0198e1b7364efea4a22eeaf2f239a4161f50991b | ericvui/movie-mining | /src/data/normalize_column.py | 624 | 3.984375 | 4 | import pandas as pd
from sklearn import preprocessing
import numpy as np
# this method removes the initial column and replaces it with the normalized column
def normalize_column_data(df, column_name):
x = df[column_name].astype(np.float64)
x = x.values.reshape(-1, 1)
# Create a minimum and maximum processor object
min_max_scaler = preprocessing.MinMaxScaler()
# Create an object to transform the data to fit minmax processor
x_scaled = min_max_scaler.fit_transform(x)
# Run the normalizer on the dataframe
df[column_name] = pd.DataFrame(x_scaled, index=df.index.values)
return df
|
e5b262b15b23a29f7fd486aa68f9b4c70f22c04d | chenyanqa/example_tests_one | /test_31.py | 2,107 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#题目:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
# Monday Tuesday Wednesday Thursday Friday Saturday Sunday
#方法1:方法一 没有实现主次输入
# s = input('请输入星期简称,首字母大写:')
#
# list1 = ['M','T','W','F','S']
# list2 = ['u','h','a']
#
# list = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
#
# if s not in list:
# print('您输入的星期有误,请重新输入:')
#
# else:
# print('您当前的输入为:%s'%s)
# if s[0] ==list1[0]:
# print('星期一')
# if s[0] ==list1[2]:
# print('星期三')
# if s[0] ==list1[3]:
# print('星期五')
#
# if s[0] ==list1[1] and s[1] ==list2[0]:
# print('星期二')
# if s[0] ==list1[1] and s[1] ==list2[1]:
# print('星期四')
# if s[0] ==list1[4] and s[1] ==list2[2]:
# print('星期六')
# if s[0] ==list1[4] and s[1] ==list2[0]:
# print('星期日')
#方法2:字典的思路::
# weeklist = {'M': 'Monday','T': {'u': 'Tuesday','h':'Thursday'}, 'W': 'Wednesday', 'F':'Friday','S':{'a':'Saturday','u':'Sunday'}}
#
# letter1 = input('请输入首字母:')
# letter1 = letter1.upper() #将用户输入的字母自动转化为大写
#
# if letter1 in ['T','S']:
# letter2 = input('请输入第二个字母:')
# print(weeklist[letter1][letter2])
# else:
# print(weeklist[letter1])
#方法3:先判断第一个字母,在判断第二个 if(if-else:)-elif-else:
letter = input("please input:")
if letter == 'S':
print('please input second letter:')
letter = input("please input:")
if letter == 'a':
print('Saturday')
elif letter == 'u':
print('Sunday')
else:
print('data error')
elif letter == 'F':
print('Friday')
elif letter == 'M':
print('Monday')
elif letter == 'T':
print('please input second letter')
letter = input("please input:")
if letter == 'u':
print('Tuesday')
elif letter == 'h':
print('Thursday')
else:
print('data error')
elif letter == 'W':
print('Wednesday')
else:
print('data error')
|
47db04dace450630932b698af746a82e8d532158 | EthanVV/p4p | /class_01/improved_file_demo.py | 243 | 3.515625 | 4 | with open('names.txt') as fin, open('names_upper.txt', 'w') as fout:
for line in fin:
name = line.strip()
#fout.write(name.upper() + ' ' + str(len(name)) + '\n')
fout.write('{} {}\n'.format(name.upper(), len(name))) |
0dbd47231e6523752aea23801d4057cc8b976d5f | AkshayKumarTripathi/Algorithms-And-Data-Structures | /Day 19 (Binary Search Tree)/populate next right pointers of a tree.py | 1,239 | 4.03125 | 4 |
# You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
# struct Node {
# int val;
# Node *left;
# Node *right;
# Node *next;
# }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
# Initially, all next pointers are set to NULL.
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root:
body=[root]
while body:
length=len(body)
body.append(None)
for x in range(1,length):
body[x-1].next=body[x]
body.pop()
temp=[]
for x in body:
if x.left==None:
break
temp.append(x.left)
temp.append(x.right)
body=temp
return root |
767c54df3024db5afb3e551d7e17220cf0320745 | 404232077/python-course | /ch03/3-3-3-dict3.py | 190 | 3.5 | 4 | lang1={'你好':'Hello'}
lang2={'學生':'Student'}
lang1.update(lang2)
print(lang1)
lang1={'早安':'Good Morning','你好':'Hello'}
lang2={'你好':'Hi'}
lang1.update(lang2)
print(lang1)
|
64e92349b69b061366e15aa0938253bc4112b79f | DeltaTemple/PySnippets | /Data/slice.py | 129 | 4 | 4 |
mytuple = (1, "Hello", 9000)
print(mytuple)
#Copy element from 'mytuple' into x during each loop
for x in mytuple:
print(x) |
2aad0906b447b4802d4e560bb49a471ab09f0792 | EduinJBL/Goodreads-Sequels-Analysis | /1. Books import and clean 10k.py | 3,480 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 15 09:20:31 2021
@author: eblat
"""
#First Script: Books Import and Clean
import pandas as pd
import numpy as np
import os
#Read in books data
books=pd.read_csv(r'https://raw.githubusercontent.com/EduinJBL/goodbooks-10k/master/books.csv')
#authors column lists multiple authors. For now only work with first author
auths=books.authors.str.split(',',expand=True)
books['auth1']=auths.iloc[:,0]
#drop books without isbn codes
books=books.dropna(subset=['isbn'])
#do some cleaning of high profile authors so we get the right books in the series
#drop book GRR Martin published before GoT
grr=books[books.auth1=='George R.R. Martin']
books=books[books.book_id!=7082]
#drop two boxsets of harry potter books which stop it matching
jkr=books[books.auth1=='J.K. Rowling']
books=books[(books.book_id!=422) & (books.book_id!=2101)]
#drop suzanne collins books before Hunger Games
sc=books[books.auth1=='Suzanne Collins']
scnohg=sc[sc.book_id>1000]
books=books[books.book_id.isin(scnohg.book_id)==False]
db=books[books.auth1=='Dan Brown']
dblesserbooks=db[db.book_id>26]
books=books[books.book_id.isin(dblesserbooks.book_id)==False]
#remove anonymous books
books=books[books.auth1!='Anonymous']
#just test how many times each author comes up
df=books[['auth1','book_id']].groupby('auth1').count()
df=df.sort_values('book_id',ascending=False)
#Check there are no duplicate works.
books=books.sort_values(['book_id','original_publication_year'])
books=books.drop_duplicates(subset='work_id')
#Find first book published by author
df=books[['auth1','original_publication_year']].groupby('auth1').min()
narrowbook=books[['book_id','auth1','original_publication_year','work_id',
'title','work_ratings_count']]
#some authors publish multiple books in the same year. drop these observations
df=df.merge(narrowbook,on=['auth1','original_publication_year'],how='left')
count=df[['auth1','book_id']].groupby('auth1').count()
count.rename(columns={'book_id':'count'},inplace=True)
df=df.merge(count,on=['auth1'],how='left')
df['count'].value_counts()
df=df[df['count']==1]
#keep only books written by authors where we have the 1st book
books=books[books['auth1'].isin(df['auth1'])]
#create new dataframe which doesn't have 1st books
books2=books[books['book_id'].isin(df['book_id'])==False]
#now find earliest book published other than the first books
df2=books2[['auth1','original_publication_year']].groupby('auth1').min()
df2=df2.merge(narrowbook,on=['auth1','original_publication_year'],how='left')
count=df2[['auth1','book_id']].groupby('auth1').count()
count.rename(columns={'book_id':'count'},inplace=True)
df2=df2.merge(count,on=['auth1'],how='left')
df2['count'].value_counts()
df2=df2[df2['count']==1]
#Merge 2 dfs to give 1st and second books
df=df.merge(df2,on='auth1',how='inner',suffixes=('1','2'))
df=df.drop(columns=['count1','count2'])
df['total_ratings']=df.work_ratings_count1+df.work_ratings_count2
df.sort_values('total_ratings',ascending=False,inplace=True)
df=df.drop('total_ratings',axis=1)
authlist=df.auth1
df=pd.wide_to_long(df,stubnames=['original_publication_year','book_id',
'work_id','title','work_ratings_count'],
i='auth1',j='booknum')
df=df.reset_index(level=['auth1','booknum'])
#Write csvs with just the books we want and just the authors we want
df.to_csv('cleanedbooks10k.csv',index=False)
authlist.to_csv('cleanedauthors10k.csv',index=False)
|
e60c3909f7438d9996b03af0ab0b93ec62409fe0 | tjwilli6/PHYS_4410 | /private/temp.py | 89 | 3.703125 | 4 | for i in range(5):
if i==2:
print( str(i) + "~" )
else:
print(i)
|
b537afca0b2c1aabc8f47aa40f16130bd1ae3859 | believeyinuo/PythonStudy | /API_AUTO_test/python_basic_package/class_truple.py | 1,004 | 3.703125 | 4 | # -*- coding:utf-8 -*-
#@Time : 2019-08-13
#@Author:lqc
#@Email:572948875@qq.com
#File : class_truple.py
#元祖 tuple 符号()
a = ()
print(type(a))
#1、可以存在空元组
#2、元组里面可以包含任何类型的数据
#3、元组里面的元素,根据逗号来进行分隔
#4、元组里面的元素,也是有索引,索引值从0开始
#5、获取元组里面的元素值:元组[索引值]
#6、元组的切片 元组名[索引头:索引尾:步长]
print(a[0:6:2])
#操作数据库看的时候 会放条件
#元组不支持任何修改(增删改) 'truple' object does not supprot item assignment
a = (1, 0.02, 'hello', [1,2,3], True, (4,5,6), "小小")
#a[3][-1] = "花花"
#a[3].pop()
#print(a[3][1])
b = [1, 0.02, 'hello', [1,2,3], True, (4,5,6), "小小"]
#元组是保护强的数据结构,元组内部元素不能动
#元组只有一个元素,要加一个逗号
c = (1)#int
e = (1,)#truple
d = ("hello")#str
f = ("hello",)#truple
g = ([1,2,3])#list
h = ([1,2,3],)#truple |
c3020e22d39b9d3752188dd343d26202812d40ec | gustavoreche/URI | /Python/1042.Sort Simples.py | 216 | 3.5 | 4 | ent = raw_input().split()
entrada = [int(elem) for elem in ent]
inicio = ent
entrada.sort()
print entrada[0]
print entrada[1]
print "%s\n" % entrada[2]
print inicio[0]
print inicio[1]
print inicio[2]
|
57c2f0d05563ad28fca9a0a0cad0c0767bd970ca | KRiteshchowdary/myfiles | /PAT2.py | 227 | 3.65625 | 4 | w = input('what is your word ')
l =[]
for i in w:
n = w.count(i)
l.append(n)
count = 0
for i in l:
if i>1:
count = count+1
if count > 0:
print('Bad word')
else:
print('Good word')
|
6af036165fd3b916d1ea4241bf46164ef8db2f60 | sampath1994/Research-Project | /speed/bb_distance.py | 1,468 | 3.671875 | 4 | import math
def get_distance(bb1, bb2):
if isInsideBB(bb1, bb2) or isInsideBB(bb2, bb1): # both centroids are in each other or one of them in the other
return 0
dis1 = calculate(bb1, bb2)
dis2 = calculate(bb2, bb1)
if dis1 < dis2:
return dis1
else:
return dis2
def dist(x1, y1, x2, y2):
dis = (x2-x1)**2 + (y2-y1)**2
return int(math.sqrt(dis))
def calculate(bb_previous, bb_current): # distance from bb_current centroid to bb_previous is measured
xp, yp, wp, hp = bb_previous
xc, yc, wc, hc = bb_current
x = int(xc + (wc/2))
y = int(yc + (hc/2))
x1 = xp + wp
y1 = yp + hp
if x < xp and y < yp:
return dist(xp, yp, x, y)
if x > x1 and y < yp:
return dist(x1, yp, x, y)
if x < xp and y1 < y:
return dist(xp, y1, x, y)
if x > x1 and y > y1:
return dist(x1, y1, x, y)
if yp <= y <= y1:
if x < xp:
return xp - x
else:
return x - x1
if xp <= x <= x1:
if y < yp:
return yp - y
else:
return y - y1
def isInsideBB(bb_previous, bb_current): # centroid of bb_current is inside bb_previous
xp, yp, wp, hp = bb_previous
xc, yc, wc, hc = bb_current
current_centroid_x = int(xc + (wc/2))
current_centroid_y = int(yc + (hc/2))
if (xp <= current_centroid_x <= (xp+wp)) and (yp <= current_centroid_y <= (yp+hp)):
return True
return False
|
d9c26571082744332a025988b1105532da027313 | miaha15/Programming-coursework | /Week 6 Question 1.py | 1,808 | 4.34375 | 4 | '''
while the size of the variable Store is greater than 0 then it checks
to see if the current node is not empty.
While the theres a node on the left hand side then it will add that node to the
list stored in the variable called Store and make the current node that node.
If there is no node on the left hand side then it will check the Stack if its
not empty, if it isnt then it will print values in the stack and add the node
on the right hand side.
'''
import sys
class BinTreeNode(object):
def __init__(self, value):
self.value=value
self.left=None
self.right=None
def tree_insert(tree, item):
if tree==None:
tree=BinTreeNode(item)
else:
if(item < tree.value):
if(tree.left==None):
tree.left=BinTreeNode(item)
else:
tree_insert(tree.left,item)
else:
if(tree.right==None):
tree.right=BinTreeNode(item)
else:
tree_insert(tree.right,item)
return tree
def postorder(tree):
if(tree.left!=None):
postorder(tree.left)
if(tree.right!=None):
postorder(tree.right)
print (tree.value)
def in_order(tree):
Store = [tree]
currentNode = tree
while len(Store) > 0:
if currentNode != None:
while currentNode.left != None:
Store.append(currentNode.left)
currentNode = currentNode.left
Stack = Store.pop()
if Stack != None:
print(Stack.value)
Store.append(Stack.right)
if __name__ == '__main__':
t=tree_insert(None,6);
tree_insert(t,10)
tree_insert(t,5)
tree_insert(t,2)
tree_insert(t,3)
tree_insert(t,4)
tree_insert(t,11)
in_order(t)
sys.exit()
|
5f46de7d6dc3b82705ed2917c33df2857f969ec1 | Phlank/ProjectEuler | /python/src/pje_0043.py | 813 | 3.703125 | 4 | import itertools
#returns the digits of l as an integer
def list_to_int(l):
return int("".join(str(x) for x in l))
#main
out = 0
pandigitals = list(itertools.permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
first_primes = [2, 3, 5, 7, 11, 13, 17]
for x in pandigitals:
has_property = 1
if list_to_int(x[1:4])%first_primes[0] != 0: has_property = 0
elif list_to_int(x[2:5])%first_primes[1] != 0: has_property = 0
elif list_to_int(x[3:6])%first_primes[2] != 0: has_property = 0
elif list_to_int(x[4:7])%first_primes[3] != 0: has_property = 0
elif list_to_int(x[5:8])%first_primes[4] != 0: has_property = 0
elif list_to_int(x[6:9])%first_primes[5] != 0: has_property = 0
elif list_to_int(x[7:10])%first_primes[6] != 0: has_property = 0
if has_property == 1: out += list_to_int(x)
print "%d" % (out)
|
d5ea8b4a0cb66799d201d7d0e6ec36f298997ead | roger2399/python-practice | /rotate_string.py | 708 | 4.15625 | 4 | ############################################################
# for conversion to ascii use functons ord and chr
# ex : ord("a")
# chr(99)
# ascii range for a-z(97-122)
#
#
#############################################################
word =(input("enter your string:"))
index = 0
#def rotate():
# while index < len(word):
#tmp = word[0]
# print (tmp)
#break
# ord(tmp) = tmp1
#tmp2 = tmp1 + 3
#chr(tmp2) = tmp3
#print(tmp3)
i = 0
for letter in word:
tmp = word[i]
#print (tmp)
tmp1 = ord(tmp)
#print (tmp1)
tmp2 = tmp1 + 3
#print (tmp2)
tmp3 = chr(tmp2)
print(tmp3)
i = i+1
|
32e3d5e51cd802bf4ea11b847389c95953c5c99f | JhamniYoungShinnick/CSP_GUIproject_102517_JYS | /Followtheleader.py | 2,488 | 3.71875 | 4 | ###
#Jhamni Young-Shinnick
#10.25.17
#RisingSun.py
#Interactive Animation w/rising Sun
###
import time
import Tkinter as tk #names TKinter to be used as tk
from Tkinter import *
root = tk.Tk() #Creates root window
canvas = tk.Canvas(root, width=1000, height=1000, borderwidth=0, highlightthickness=0, bg="white")
canvas.grid() #Fills background white and creates a larger Canvas
#format (x0, y0, x1, y1), all are poits for the circle's box
#canvas.create_oval(100,200,0,300, width=2, fill='red')
class Ball: # Class is object
def __init__(self,color,size,x,y):
self.color = color
self.size = size
self.x = x
self.y = y
self.xVel = 0
self.yVel = 0
self.xAccel = 0
self.yAccel = 0
global canvas
self.sprite = canvas.create_oval(self.x,self.y,self.x + self.size,self.y + self.size, width=2, fill=self.color)
def move(self):# moves ball
self.xVel = self.xVel + self.xAccel
self.yVel = self.yVel + self.yAccel
canvas.move(self.sprite,self.xVel,self.yVel)
self.x = self.x + self.xVel
self.y = self.y + self.yVel
if(self.y > 801): # if above 800 sets to 800 then flips velocity and lowers
self.setPos(self.x,800)
self.setVel(self.xVel,self.yVel * -0.9)
if(self.x > 1001): # if above 1000 set to 100 and flip velocity and lower
self.setPos(1000,self.y)
self.setVel(self.xVel * -0.9,self.yVel)
if(self.x < -1):
self.setPos(0,self.y)
self.setVel(self.xVel * -0.9,self.yVel)
def setAccel(self, x ,y):
self.xAccel = x
self.yAccel = y
def setVel(self, x ,y):
self.xVel = x
self.yVel = y
def setColor(self,color):
global canvas
canvas.itemconfig(self.sprite, fill=color)
def setPos(self,x,y):
canvas.move(self.sprite,x - self.x,y - self.y)
self.x = x
self.y = y
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple','pink','black']
balls = []
for point in range(0,50):
balls.append(Ball(colors[point%8],50,(point*15),800 - (point * 15)))#gives color
balls[point].setVel(4,-30)
balls[point].setAccel(0,1)
balls[point].setColor(colors[point%8])
def tick():#event loop
global ball
for ball in balls:
ball.move()
time.sleep(0.015)
canvas.after(1,tick)
tick()
root.mainloop()# Event loop |
60a602e751c6820605e03acb224e6158f8190925 | liseyko/CtCI | /Chapter 2 - Linked Lists/c0207.py | 1,862 | 3.859375 | 4 | """ is linked list a palindrome """
from linkedlist import LinkedList
def isLLaPalindrome_naive(ll):
"""reverse and compare 1/2"""
ll2 = LinkedList()
q = 0
for n in ll:
ll2.insert(n.data)
q += 1
q = q // 2
n1 = ll.head
n2 = ll2.head
while n1.data == n2.data:
if not n1.next or q == 1:
return True
n1 = n1.next
n2 = n2.next
q -= 1
return False
def isLLaPalindrome_rec(ll):
""" TODO: check only half of the list """
rw_n = ll.head
fw_n = rw_n
l = ll.len
def rec(rw_n,fw_n,l):
if rw_n.next:
fw_n = rec(rw_n.next,fw_n,l-2)
if not fw_n or not rw_n.data == fw_n.data:
return False
#print(rw_n.data,fw_n.data)
else:
if not rw_n.data == fw_n.data:
return False
#print(rw_n.data,fw_n.data)
if not fw_n.next:
return True
return fw_n.next
print(rec(rw_n,fw_n,l))
return False
def isLLaPalindrome(ll):
stack = LinkedList()
fast = ll.head
slow = fast
while fast and fast.next:
stack.insert(slow.data)
slow = slow.next
fast = fast.next.next
if fast is not None: # skip middle element if odd len
slow = slow.next
fast = stack.head
while slow:
if slow.data != fast.data:
return False
slow = slow.next
fast = fast.next
return True
test1 = LinkedList([c for c in "never odd or even".replace(" ", "")])
test2 = LinkedList([c for c in "mr owl ate my metal worm".replace(" ", "")])
print(isLLaPalindrome_naive(test1))
print(isLLaPalindrome_naive(test2))
print("recursive:")
isLLaPalindrome_rec(test1)
isLLaPalindrome_rec(test2)
print("iterative:")
print(isLLaPalindrome(test1))
print(isLLaPalindrome(test2))
|
e285d832a82ff4c00da87133419c3818a67ab3e0 | tanzilamohita/LiveGraph | /main.py | 853 | 3.546875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.animation as animation
from matplotlib import style
from pandas.plotting import register_matplotlib_converters
style.use('fivethirtyeight')
fig = plt.figure(figsize=(10, 6))
#ax1 = fig.add_subplot(1, 1, 1)
ax1 = fig.add_axes([0, 0, 1, 1])
ax2 = fig.add_axes([0.05, 0.65, 0.5, 0.3])
def animate(i):
stock_data = pd.read_csv('datasets/stocks.csv')
stock_data['Date'] = pd.to_datetime(stock_data['Date'])
fig.suptitle('AAPL vs IBM')
xs_ax1 = stock_data['Date']
ys_ax1 = stock_data['AAPL']
xs_ax2 = stock_data['Date']
ys_ax2 = stock_data['IBM']
ax1.clear()
ax1.plot(xs_ax1, ys_ax1, color='green')
ax1.plot()
ax2.clear()
ax2.plot(xs_ax2, ys_ax2, color='blue')
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
|
2b64dc02d0db332516025dd03c7901374771a277 | ManooshSamiei/dynamic-connect-4 | /AI-human.py | 16,034 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 12:44:18 2020
@author: ASUS
"""
import manual_init as mn
from math import inf
import timeit
from random import choice
board = [[' ',' ',' ',' ',' ',' ','X'],
['X',' ',' ',' ',' ',' ','O'],
['O',' ',' ',' ',' ',' ','X'],
['X',' ',' ',' ',' ',' ','O'],
['O',' ',' ',' ',' ',' ','X'],
['X',' ',' ',' ',' ',' ','O'],
['O',' ',' ',' ',' ',' ',' ']]
X_CENTER_INDEX= 4
Y_CENTER_INDEX = 4
COUNTER =0
def print_board(state):
"""
Printing the board
:param state: the current state of the board
"""
for i in range(7):
for j in range(7):
if j==6:
print(state[i][j].strip('\n'))
else:
print(state[i][j], end=',')
def initial_state(board):
"""
defining the initial state of the board
:param board: the initial state of the board
"""
print('The initial state is:')
print_board(board)
init=input('Do you like to enter a new initial state? y/n \n')
if init=='y':
ch=input('press "f" is you like to open a file \n press "m" to enter manually? f/m \n')
'''
build an arrangement like below in a txt file and import it here
you can change the sample file 'state.txt' provided in code folder.
, , , , , ,X
X, , , , , ,O
O, , , , , ,X
X, , , , , ,O
O, , , , , ,X
X, , , , , ,O
O, , , , , ,
'''
if ch=='f':
filename = input('enter the name of the file E.g: stateA.txt \n')
# change the below file for a new state!
with open(filename, 'r') as init_state:
a = init_state.read()
list_a= a.split('\n')
board_2=[item.split(',') for item in list_a]
print('The initial state is:')
print_board(board_2)
elif ch=='m':
board_2=mn.manual_init_state(board)
else:
board_2=board
return board_2
def evaluate (state, comp_p , human_p):
"""
Simple Evaluation of the score for the current sate
This function is now replaced by a more complex heuristic function below
:param state: the current state of the board
:param comp_p: the piece that AI agent plays with(='O' or 'X')
:param human_p: the piece that human plays with
:return: the score of the current state
"""
if win(state , comp_p):
score = +1
elif win(state , human_p):
score = -1
else:
score = 0
return score
def heuristic_count (state, comp_p , human_p):
"""
Evaluation of the value for the current sate, based on some heuristics that
specify how close each state is to a win state
:param state: the current state of the board
:param comp_p: the piece that AI agent plays with(='O' or 'X')
:param human_p the piece that human plays with
:return: the value of the current state
"""
def count_pieces (state, piece):
"""
This heuristic counts for each player how many pieces are placed in a
row as part of the winning states.
:param state: the current state of the board
:param piece: the piece of the player('X' or 'O')
:return: the number of pieces in a row
"""
count=0
win_states = []
for i in range(7):
for j in range(4):
#horizontal line up winning
win_states.append([state[i][j], state[i][j+1], state[i][j+2], state[i][j+3]])
#vertical line up winning
win_states.append([state[j][i], state[j+1][i], state[j+2][i], state[j+3][i]])
if(i < 4) :
#diagonal line up winning
win_states.append([state[j][i], state[j+1][i+1], state[j+2][i+2], state[j+3][i+3]])
win_states.append([state[j][6-i], state[j+1][5-i], state[j+2][4-i], state[j+3][3-i]])
row_two = [row[i:i+2] for row in win_states for i in range(3)]
row_three = [row[i:i+3] for row in win_states for i in range(2)]
row_four = [row[i:i+4] for row in win_states for i in range(1)]
if [piece,piece] in row_two:
for k in range(row_two.count([piece, piece])):
count+=1
if [piece, piece, piece] in row_three:
for k in range(row_three.count([piece, piece, piece])):
count+=5
if [piece, piece, piece, piece] in row_four:
count+=15
return count
def heuristic_center_dist (state, piece):
"""
This heuristic calculates the sum of the distance (in x direction) of
pieces from the center of the board (less distance is better) plus the
number if pieces that are more than 1 square away from the x center.
:param state: the current state of the board
:param piece: the piece of the player('X' or 'O')
:return: the number of pieces in a row
"""
dist =0
sum_dis =0
dist_c=0
for y, row in enumerate(state):
for x, cell in enumerate(row):
if cell==piece:
# if dist==0:
# x1=x
# y1=y
# dist=1
# dist=abs(x1-x)+abs(y1-y)
# sum_dis+=dist
dist_c= (2*abs(x-X_CENTER_INDEX))+(abs(y-Y_CENTER_INDEX))
sum_dis+=dist_c
return sum_dis
if COUNTER <= 4:
##
return 2*heuristic_center_dist(state,human_p) -2*heuristic_center_dist(state,comp_p)+ count_pieces (state,comp_p) - count_pieces (state,human_p)
#
elif COUNTER > 4:
##
return count_pieces (state,comp_p)**2 - 50*count_pieces (state,human_p)**2+ heuristic_center_dist(state,human_p) -heuristic_center_dist(state,comp_p)
def win(state, piece):
"""
Checks if the pieces are in winning states
:param state: the current state of the board
:param piece: the piece of the player('X' or 'O')
:return: True if the player won and False if it did not
"""
win_states = []
for i in range(7):
for j in range(4):
#horizontal line up winning
win_states.append([state[i][j], state[i][j+1], state[i][j+2], state[i][j+3]])
#vertical line up winning
win_states.append([state[j][i], state[j+1][i], state[j+2][i], state[j+3][i]])
if(i < 4) :
#diagonal line up winning
win_states.append([state[i][j], state[i+1][j+1], state[i+2][j+2], state[i+3][j+3]])
win_states.append([state[i][6-j], state[i+1][5-j], state[i+2][4-j], state[i+3][3-j]])
if [piece, piece, piece, piece] in win_states:
return True
else:
return False
def move_func(board_2, human_p, comp_p):
"""
recieves a move from a human player, interprets the command and
draws the new board.
:param human_p: the piece that human plays with
:param comp_p: the piece that ai agent plays with
"""
print('Human turn [%s]' %human_p)
print("Enter <x,y> of piece you'd like to move + direction (e.g. 72W)")
move=['','','']
move[:] = str(input())
x , y = int(move[0])-1, int(move[1])-1 #we subtract one to match 'board' array index numbers
direc = move[2]
while validate_move (board_2, direc, x, y,human_p):
print("movement isn't valid. Try again!\n")
print("Enter <x,y> of piece you'd like to move + direction (e.g. 72W)")
move=['','','']
move[:] = str(input())
x , y = int(move[0])-1, int(move[1])-1 #we subtract one to match 'board' array index numbers
direc = move[2]
interpret_move(direc, x, y , board_2)
def validate_move (board_2, direc, x, y , piece):
"""
validates if a move from a human player is eligible
:param direc: the direction of movement(West,East,...)
:param x: the position of the moving piece in x axis, column-wise
:param y: the position of the moving piece in y axis, row-wise
:param piece: the piece that player plays with
:return: True if the movements are not eligible, False when movements are fine
"""
valid_direc=['N','E','W','S']
if(
(x==6 and direc=='E') or
(x==0 and direc=='W') or
(y==0 and direc=='N') or
(y==6 and direc=='S') or
(y not in range(7)) or
(x not in range (7)) or
(direc not in valid_direc) or
(board_2[y][x]==' ') or
(board_2[y][x]!=piece)
):
return True
else:
return False
def interpret_move(direc, x, y, board):
"""
changes the state of the board based on the new movement
:param direc: the direction of movement(West,East,...)
:param x: the position of the moving piece in x axis, column-wise
:param y: the position of the moving piece in y axis, row-wise
:param board: the current state of the board
"""
if direc=='E':
board[y][x+1]= board[y][x]
board[y][x] = ' '
elif direc=='W':
board[y][x-1]= board[y][x]
board[y][x] = ' '
elif direc=='N':
board[y-1][x]= board[y][x]
board[y][x] = ' '
elif direc=='S':
board[y+1][x]= board[y][x]
board[y][x] = ' '
print_board(board)
def comp_turn(board_2, human_p, comp_p):
"""
Computes a move for AI agent through Minimax+alpha_beta pruning
sends the move command to the Telnet client and draws the new board
:param remote_p: the piece that remote agent plays with
:param comp_p: the piece that AI agent plays with
"""
print('Computer turn [%s]' %comp_p)
direction=['N', 'W', 'E','S']# with the order of m arrangement in minimax function
if (win(board_2, human_p) or win(board_2, comp_p)):
return
depth = 6
#depth = 10
start = timeit.default_timer()
move = [0 , 0 , 0 ,0]
count = 0
move , count = max_alpha_beta(board_2 ,-inf, +inf, human_p, comp_p, depth, start, count)
end = timeit.default_timer()
print('runtime:' , end - start)
y = move[0]
x= move[1]
direc = direction[move[2]]
interpret_move(direc, x, y ,board_2)
global COUNTER
COUNTER=1+COUNTER
def max_alpha_beta(state, alpha, beta, human_p, comp_p, depth, start, count):
"""
minimax algorithm with alpha-beta pruning, Max player
:param state: the current state of the board
:param alpha: the alpha parameter for pruning
:param beta: the beta parameter for pruning
:param human_p: the piece that human player plays with
:param comp_p: the piece that AI agent plays with
:param depth: the maximum depth search of the tree
:param start: the starting time of minimax search to cut the search after 10 sec
:param count: if true count the number of states explored
:return: the best movement with highest value for the max player
"""
count+=1
best = [None, None, None , -inf]
p = comp_p
#score=heuristic_count(state, comp_p , human_p)
stop = timeit.default_timer()
if depth<=0 or win(state , p) or stop-start>=8.5:
score = heuristic_count(state, comp_p , human_p)
return [-1, -1, -1 , score] , count
m =[(-1,0),(0,-1),(0,1),(1,0)]
for y, row in enumerate(state):
for x, cell in enumerate(row):
if cell==p:
for (i ,j) in m:
if (y+i)>(6) or (x+j)>(6) or (y+i)<0 or (x+j)<0:
continue
if state[y+i][x+j]==' ':
state[y+i][x+j]= p
state[y][x] = ' '
score , count = min_alpha_beta(state, alpha, beta, human_p, comp_p, depth-1, start,count)
state[y+i][x+j]= ' '
state[y][x] = p
score[0], score[1], score[2] = y, x, m.index((i ,j))
if score[3] > best[3]:
best = score
if best [3] >= beta:
return [y,x , m.index((i ,j)), best[3]], count
if best[3] > alpha:
alpha = best[3]
#print('number of explored states:', explored)
return best , count
def min_alpha_beta(state, alpha, beta, human_p, comp_p, depth, start , count):
"""
minimax algorithm with alpha-beta pruning, Min player
:param state: the current state of the board
:param alpha: the alpha parameter for pruning
:param beta: the beta parameter for pruning
:param human_p: the piece that human player plays with
:param comp_p: the piece that AI agent plays with
:param depth: the maximum depth search of the tree
:param start: the starting time of minimax search to cut the search after 10 sec
:param count: if true count the number of states explored
:return: the best movement with lowest value for the min player
"""
count+=1
best = [None, None, None , +inf]
p = human_p
#score=heuristic_count(state, comp_p , human_p)
stop = timeit.default_timer()
if depth<=0 or win(state , p) or stop-start>=8.5:
score=heuristic_count(state, comp_p , human_p)
return [-1, -1, -1 , score] , count
m =[(-1,0),(0,-1),(0,1),(1,0)]
for y, row in enumerate(state):
for x, cell in enumerate(row):
if cell==p:
for (i ,j) in m:
if (y+i)>(6) or (x+j)>(6) or (y+i)<0 or (x+j)<0:
continue
if state[y+i][x+j]==' ':
state[y+i][x+j]= p
state[y][x] = ' '
score , count = max_alpha_beta(state, alpha, beta, human_p, comp_p, depth-1, start,count)
state[y+i][x+j]= ' '
state[y][x] = p
score[0], score[1], score[2] = y, x, m.index((i ,j))
if score[3] < best[3]:
best = score
if best [3] <= alpha:
return [y,x , m.index((i ,j)), best[3]] , count
if best[3] < beta:
beta= best[3]
#print('number of explored states:', explored)
return best , count
def main():
"""
rules the game rounds between remote agent and AI agent
and prints the result of the game.
"""
board_2 = initial_state(board)
human_p = ''
comp_p = ''
while human_p != 'O' and human_p != 'X':
human_p = input('Choose black (X) or white (O) \n Chosen: ').upper()
#O (white piece) always start the game
if human_p=='O':
comp_p = 'X'
start = 0
else:
comp_p= 'O'
start = 1
while not(win(board_2 , human_p) or win(board_2, comp_p)):
if start==1:
#random choice by computer for the first node of game
(x , y , direction) =choice([(0, 2,'E'),(0, 4,'E'),
(0, 6,'E'),(6, 1,'W'),
(6, 3,'W'),(6, 5,'W')])
interpret_move(direction, x, y , board_2)
start = None
move_func(board_2 , human_p, comp_p)
comp_turn(board_2, human_p, comp_p)
if win(board_2 , human_p):
print_board(board_2)
print('YOU WIN!')
elif win (board_2, comp_p):
print_board(board_2)
print('YOU WIN!')
else:
print_board(board_2)
print('DRAW!')
exit()
if __name__ == '__main__':
main() |
c829fdc0d14abe40c97799f2b63ce06ceb64c28d | frank-u/python_snippets | /python_core/generators_coroutines.py | 576 | 3.65625 | 4 | def calc():
history = []
while True:
x, y = (yield)
if x == 'h':
print(history)
continue
result = x + y
print(result)
history.append(result)
c = calc()
print(type(c)) # <type 'generator'>
c.send(None) # Необходимая инициация. Можно написать c.send(None)
c.send((1, 2)) # Выведет 3
c.send((100, 30)) # Выведет 130
c.send((666, 0)) # Выведет 666
c.send(('h', 0)) # Выведет [3, 130, 666]
c.close() # Закрывем генератор |
38d279250a9cf73c2f605d0d74a5d689bea942f9 | QuantumXYZ/robot-owl-learns | /BookLabelPredictor_v3.py | 6,751 | 3.5 | 4 | ''' ======================================================================================================
BookLabelPredictor_v3.py
Author: Donnette Bowler
copyright: copyright © Donnette Bowler 2016. All rights reserved. No part of this document may be reproduced or distributed.
===================================================================================
The data that we are interested in is stored in a text file.
First we load the data into numpy array of form (n-samples,features),
where features are a 2D numpy array, and n-samples is the number of lines
in the file. The last column of the file represents the target labels of the data.
This predictor uses k-nearest neighbours to predict a label
on a new book.
=============================================================================================
'''
#standard scientific Python imports
import matplotlib.pyplot as plt
from numpy import *
import numpy as np
#import classifiers and performance metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn import linear_model,neighbors,svm
from sklearn.externals import joblib
import os
# a function that loads the data from a text file into arrays
def loadData():
input_dir="./testData"
filename="testData.txt"
full_name=os.path.join(input_dir,filename)
fr=open(full_name)
number_of_lines=len(fr.readlines()) #get the number of lines in text file for the number of observations
book_X=zeros((number_of_lines,2)) # initialize an 2D array and fill with zeros
book_Y=zeros((number_of_lines,)) #initialize a 1D array and fill with zeroes
index=0
fr=open(full_name)
for line in fr.readlines():
line=line.strip()
list_from_line=line.split('\t')
book_X[index,:]=list_from_line[0:2] #array of features
book_Y[index:,]=list_from_line[-1] #array of category or target values
index+=1
return book_X,book_Y
# a function to create an array of randomly ordered indices
def permutateData(input_list):
np.random.seed(0) #set the random seed
indices=np.random.permutation(len(input_list)) #randomly order the indices
return indices
#create a classifier: nearest-neighbor classifier
def classify0():
bookX,bookY=loadData()
book_indices=permutateData(bookX) #create a random list of indices
n_samples=len(bookX)
#take a subset of the data for training the classifier
book_X_train=bookX[:0.5*n_samples]
book_Y_train=bookY[:0.5*n_samples]
#take a subset of the data for testing the classifier
book_X_test=bookX[0.5*n_samples:]
book_Y_test=bookY[0.5*n_samples:]
#create a classifier
knn=KNeighborsClassifier(n_neighbors=5)
#train the classifier with training data
v=knn.fit(book_X_train,book_Y_train)
#use the trained classifier on the test data set to predict target values
prediction=knn.predict(book_X_test)
actual=book_Y_test
#compare the predicted target values with the actual target values of the data
print "predicted values: ", prediction
print "actual values: ", actual
print v
#score the performance of the KNN classifier
print ('KNN score: %f' %knn.fit(book_X_train,book_Y_train).score(book_X_test,book_Y_test))
#pickle the trained classifier
joblib.dump(v,'model_knn.plk')
def modelBook_Regression():
bookX,bookY=loadData() #load the data
book_indices=permutateData(bookX) #create a random list of indices
n_samples=len(bookX)
#take a subset of the data for training the classifier
book_X_train=bookX[:0.5*n_samples]
book_Y_train=bookY[:0.5*n_samples]
#take a subset of the data for testing the classifier
book_X_test=bookX[0.5*n_samples:]
book_Y_test=bookY[0.5*n_samples:]
#create a classifier
logistic=linear_model.LogisticRegression()
#fit the data to the regression line and score its performance.
print ('logisticsRegression score: %f' % logistic.fit(book_X_train,book_Y_train).score(book_X_test,book_Y_test))
#linear regression on data
regr=linear_model.LinearRegression()
#fit training data
regr.fit(book_X_train,book_Y_train)
#score the performance of classifier and print the result to the screen
print "regression score: (note a variance score of 1 is perfect prediction and 0 means no linear relationship): ", regr.score(book_X_test,book_Y_test)
#pickle the trained classifier
joblib.dump(regr,'model_regression.pkl')
def modelBook():
bookX,bookY=loadData()
book_indices=permutateData(bookX)
print book_indices,len(bookX),len(bookY)
n_samples=len(bookX)
#take 50% of data for training classifier
book_X_train=bookX[:0.5*n_samples]
book_Y_train=bookY[:0.5*n_samples]
#take 50% of data for testing classifier
book_X_test=bookX[0.5*n_samples:]
book_Y_test=bookY[0.5*n_samples:]
#create a classifier
clf=svm.SVC()
#train the classifier
clf.fit(book_X_train,book_Y_train)
#pickle the trained classifier
joblib.dump(clf,'model_svm.pkl')
# a function that outputs graphs for visual inspection of classified data based on support vector machines
def dataViz_SVM():
bookX,bookY=loadData()
book_indices=permutateData(bookX)
print book_indices,len(bookX),len(bookY)
n_samples=len(bookX)
#take 50% of data for training classifier
book_X_train=bookX[:0.5*n_samples]
book_Y_train=bookY[:0.5*n_samples]
#take 50% of data for testing classifier
book_X_test=bookX[0.5*n_samples:]
book_Y_test=bookY[0.5*n_samples:]
#fit the model
for fig_num,kernel in enumerate(('linear','rbf','poly')):
clf=svm.SVC(kernel=kernel,gamma=10)
clf.fit(book_X_train,book_Y_train)
plt.figure(fig_num)
plt.clf()
plt.scatter(bookX[:,0],bookX[:,1],c=bookY,zorder=10,cmap=plt.cm.Paired)
#circle out the test data
plt.scatter(book_X_test[:,0],book_X_test[:,1],s=80,facecolors='none',zorder=10)
plt.axis('tight')
x_min=bookX[:,0].min()
x_max=bookX[:,0].max()
y_min=bookX[:,1].min()
y_max=bookX[:,1].max()
XX,YY=np.mgrid[x_min:x_max:200j,y_min:y_max:200j]
Z =clf.decision_function(np.c_[XX.ravel(),YY.ravel()])
#put the result into a color plot
Z =Z .reshape(XX.shape)
plt.pcolormesh(XX,YY,Z >0,cmap=plt.cm.Paired)
plt.contour(XX,YY,Z,colors=['k','k','k'],linestyles=['--','-','--'],level=[-0.5,0,0.5])
plt.title(kernel)
plt.show()
|
db42110159e2b6db07faecc23e02bba41ceb6b78 | kpan0004/Rotate-matrix-90-degrees | /rotate_square_matrix_90_degrees.py | 2,149 | 4.0625 | 4 | """
New column index is current row index
New row index is dimension - 1 - (current column index)
"""
def rotate_square_matrix_90(a_matrix):
assert len(a_matrix) == len(a_matrix[0]), "Input must be a square matrix"
dim = len(a_matrix)
for i in range (dim // 2): #Number of 'loops'
for j in range(i, dim - i - 1): #Start and end indices of the loop
i_2,j_2 = get_point_90_away(i,j, dim)
i_3,j_3 = get_point_90_away(i_2,j_2, dim)
i_4,j_4 = get_point_90_away(i_3,j_3, dim)
swap_elements_pythonic(a_matrix, i, j, i_2, j_2, i_3, j_3, i_4, j_4)
return a_matrix
"""
Points 1,2,3,4 are defined in clockwise order. For the algo to worth they must
90 degrees apart in the same 'loop' in the matrix
"""
def swap_elements(a_matrix, i_1, j_1, i_2, j_2, i_3, j_3, i_4, j_4):
temp1 = a_matrix[i_1][j_1]
temp2 = a_matrix[i_2][j_2]
temp3 = a_matrix[i_3][j_3]
a_matrix[i_3][j_3] = a_matrix[i_4][j_4]
a_matrix[i_2][j_2] = temp3
a_matrix[i_1][j_1] = temp2
a_matrix[i_4][j_4] = temp1
def swap_elements_pythonic(a_matrix, i_1, j_1, i_2, j_2, i_3, j_3, i_4, j_4):
a_matrix[i_1][j_1], a_matrix[i_2][j_2], a_matrix[i_3][j_3], a_matrix[i_4][j_4] = \
a_matrix[i_2][j_2], a_matrix[i_3][j_3], a_matrix[i_4][j_4], a_matrix[i_1][j_1]
def get_point_90_away(i,j, dim):
new_j = dim - 1 - i
new_i = j
return new_i, new_j
def pretty_print(a_matrix):
for row in a_matrix:
for item in row:
item = str(item)
while len(item) < 2:
item += " "
print(item, end = " ")
print("")
if __name__ == "__main__":
my_matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
my_matrix2 = [[1,2,3],[4,5,6],[7,8,9]]
matrices = [my_matrix, my_matrix2]
for matrix in matrices:
print("----------")
print("Original matrix:")
pretty_print(matrix)
print("")
print("Matrix rotated 90 degrees:")
pretty_print(rotate_square_matrix_90(matrix))
print("----------")
|
bebae1468dba4b93bcdf0c0496c5d22868bf38b7 | fifi980326/2020-AE401-Jayden | /Hw9.py | 373 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 13 09:16:58 2020
@author: HARRY LIU
"""
a={}
while True:
key=input
if key==0:
print(d)
break
else:
if a not in d.pop:
value=input("請輸入翻譯")
d["a"]=180
else:
print("此字已經在字典中,請輸入其他的字")
|
7d5fcfaf3a8f7fe5923d22c0a5fef4c917e0f8a8 | Washirican/pcc_2e | /chapter_09/tiy_9_7_admin.py | 1,753 | 3.84375 | 4 | # --------------------------------------------------------------------------- #
# D. Rodriguez, 2020-05-11
# --------------------------------------------------------------------------- #
class User:
"""User class"""
def __init__(self, first_name, last_name, user_name, location):
"""Constructor for User"""
self.first_name = first_name.title()
self.last_name = last_name.title()
self.user_name = user_name
self.location = location.title()
self.login_attempts = 0
def describe_user(self):
"""Describe user."""
print(f'\n{self.first_name} {self.last_name} (username: '
f'{self.user_name}) lives in {self.location}.')
def greet_user(self):
"""Greets user."""
print(f'\nWelcome back, {self.first_name} {self.last_name}.')
def increment_login_attempts(self):
"""Increment login attempts by a given value."""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets login attempts."""
self.login_attempts = 0
class Admin(User):
"""Admin class"""
def __init__(self, first_name, last_name, user_name, location):
"""Constructor for Admin"""
super().__init__(first_name, last_name, user_name, location)
self.privileges = []
def show_privileges(self):
"""Show admin privileges."""
for privilege in self.privileges:
print(privilege)
user_1 = User('james', 'rodriguez', 'el_gago', 'madrid')
user_1.greet_user()
user_1.describe_user()
admin = Admin('daniel', 'rodriguez', 'washirican', 'kirkland')
admin.greet_user()
admin.describe_user()
admin.privileges = ['can add post', 'can delete post', 'can ban user']
admin.show_privileges()
|
4f4ace2dc65df7724e540d03e2a21670893359f1 | KayDeVC/Python-CeV | /MUNDO3/Ex102_Fatorial.py | 544 | 3.859375 | 4 | def fatorial(n, show = False):
"""
=> Calcula o valor do fatorial do número.
:param n: O número a ser calculado.
:param show: (opcional) Mostrar ou não a conta.
:return: O valor fatorial do número n.
"""
cont = n
fat = 1
while cont > 0:
if show:
print(f'{cont}', end = '')
print(' x ' if cont > 1 else ' = ', end = '')
fat *= cont
cont -= 1
return fat
num = int(input('Número para calcular o fatorial: '))
print(fatorial(num, True))
|
ddabaa2adc4b0568f9a25d74564150406d021298 | nileshgulve/directory-traversal | /traverse1.py | 319 | 3.734375 | 4 | #!/usr/bin/python3
import sys,os
def Traverse(dir):
for a,b,c in os.walk(dir):
print("Current location: ",a)
print("Folder Inside the current location(",a + "):",b)
print("Files inside the current location(",a + "):",c)
print('=' * 70)
def main():
Traverse(sys.argv[1])
if __name__ == '__main__':
main()
|
c131720c4c1b64ec3ff241abb84c38846d14c403 | pgmakwana/ProductModule | /task/Stock_Manage/TaxCalculation_task140996.py | 1,362 | 3.5625 | 4 | # Task 140996 date 11/12/2018
class TaxCalculation:
def get_tax(self,product_price,transactiona_type,product_type):
"""
func:- Calculate the GST from the get price and check it's purchase or sell
param:- product price is the amount to calculate the GST and it's datatype is float.
param:- transaction_type to check it's puchase or sell and it's datatype is string.
return:- total of CGST and SGST and it's datatype is float.
"""
#check the transaction type is purchase or not
if transactiona_type == "PURCHASE":
#CGST = 10% & SGST = 12%
CGST_tax=product_price*(10/100)
SGST_tax=product_price*(12/100)
return CGST_tax+SGST_tax
#check the transaction type is sell and stock type or not
elif transactiona_type == "SELL" and product_type=="STOCK":
#CGST = 18% & SGST = 12%
CGST_tax=product_price*(18/100)
SGST_tax=product_price*(12/100)
return CGST_tax+SGST_tax
#at the transaction type is sell and not stock type
else:
#CGST = 18% & SGST = 12%
CGST_tax=product_price*(13/100)
SGST_tax=product_price*(15/100)
return CGST_tax+SGST_tax |
44bfc1cf16c54de9f23e594f474c232e1bb0aa1d | jeffschaper/cs50 | /pset6/mario/less/mario.py | 781 | 3.84375 | 4 | # Import stuff
from sys import exit
from cs50 import get_int
def main():
ui = height()
row = 1
# AKA height
for row in range(ui):
# AKA width
for column in range(ui - (row + 1)):
# prints # and removes new line at the end
print(" ", end="")
for dot in range(row + 1):
print("#", end="")
# prints a new line
print()
# height function
def height():
# Need to loop until an appropriate answer is given
while True:
# casting default stirng input to int
user_input = get_int("Height: ")
if user_input > 0 and user_input < 9:
# break the loop if True otherwise ask again
break
return user_input
# success
exit(0)
main()
|
106a2614b1814779ab1b949335e59f9810a08670 | ddenizakpinar/Practices | /Breaking The Records.py | 573 | 3.515625 | 4 | # https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
# 28.07.2020
def breakingRecords(scores):
minCounter, maxCounter = 0,0
minimum,maximum = scores[0],scores[0]
for score in scores:
if minimum != min(minimum,score):
minCounter+=1
minimum = min(minimum,score)
if maximum != max(maximum,score):
maxCounter+=1
maximum = max(maximum,score)
return maxCounter,minCounter
n = int(input())
scores = list(map(int, input().rstrip().split()))
print(breakingRecords(scores)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.