blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
17643de886bee41c3c5173355e0aabb03ea22c78 | Puh00/toru-bot | /util/hacks.py | 1,223 | 3.546875 | 4 | """Hacky Methods
This script contains ehm... hacks that should normally not be used but
we use anyways because reasons.
"""
def stringify_residue_args(
_locals: dict, args_name: str = "args", kwargs_name: str = "kwargs"
) -> str:
"""Stringify and concatenate all *args and **kwargs arguments
Parameters
----------
_locals : dict
The dictionary obtained by calling locals() inside a function,
the * and ** args should be named as *args and **kwargs for it
to work properly.
Note that whatever objects in the *args and **kwargs must be
have implemented the __str__ methods.
args_name : str, OPTIONAL
Defaults to 'args', this needs to be assigned if your *args are
called something else
kwargs_name : str, OPTIONAL
Defaults to 'kwargs', this needs to be assigned if your **kwargs
are called something else
Returns
-------
str
A string containing all *args and **kwargs separared with a
space
"""
_args = list(_locals.get(args_name, ()))
_kwargs = list(_locals.get(kwargs_name, {}).values())
all_args = _args + _kwargs
return " ".join(map(lambda i: str(i), all_args))
|
ab66352bc17a441f7845aa5c2eb0d2b78b38abf8 | luicast/cursoPython | /for.py | 1,318 | 3.9375 | 4 | def tabla(numero):
print("la tabla del " + str(numero))
for i in range(1,11):
print(str(numero) + "x" + str(i) + "=" +str(i*numero))
def mensaje():
msj = input("desea realizar otra tabla de multiplicar [y/n]: ")
if msj == "y":
run()
else:
print("gracias por usar este servicio")
def run():
menu = """
LAS TABLAS DE MULTIPLICAR
selecciona la tabla que quieres ver:
- tabla del 1
- tabla del 2
- tabla del 3
- tabla del 4
- tabla del 5
- tabla del 6
- tabla del 7
- tabla del 8
- tabla del 9
elija una tabla: """
opcion = str(input(menu))
if opcion == "1":
tabla(1)
mensaje()
elif opcion == "2":
tabla(2)
mensaje()
elif opcion == "3":
tabla(3)
mensaje()
elif opcion == "4":
tabla(4)
mensaje()
elif opcion == "5":
tabla(5)
mensaje()
elif opcion == "6":
tabla(6)
mensaje()
elif opcion == "7":
tabla(7)
mensaje()
elif opcion == "8":
tabla(8)
mensaje()
elif opcion == "9":
tabla(9)
mensaje()
else:
print('esa no es una opcion correcta')
run()
if __name__ == "__main__":
run() |
904a3713c42199ae4b32ed515734f558dfcb99a9 | anakhap/ScribblerRobot | /TkinterPygame.py | 1,257 | 4.03125 | 4 | Tkinter
=======
# respond to a key without the need to press enter
import Tkinter as tk
def keypress(event):
if event.keysym == 'Escape':
root.destroy()
x = event.char
if x == "w":
print "blaw blaw blaw"
elif x == "a":
print "blaha blaha blaha"
elif x == "s":
print "blash blash blash"
elif x == "d":
print "blad blad blad"
else:
print x
root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', keypress)
# don't show the tk window
root.withdraw()
root.mainloop()
Pygame
=======
# The necessities to input pygame (MIGHT BE MORE/LESS NOT SURE)
import pygame, sys
from pygame.locals import *
pygame.init()
# Main part; Note 'events' can be keypresses or mouse clicks
while True:
for event in pygame.event.get() :
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_SPACE :
print "Space bar pressed down."
elif event.key == pygame.K_ESCAPE :
print "Escape key pressed down."
elif event.type == pygame.KEYUP :
if event.key == pygame.K_SPACE :
print "Space bar released."
elif event.key == pygame.K_ESCAPE :
pygame.quit()
sys.exit() |
90dee8c80d2e34e2f94369961d7d68a5a3d3a8b8 | HatemElhawi/student-Grads-Prediction | /grading.py | 1,939 | 3.546875 | 4 | import pandas as pd
from sklearn import linear_model
import numpy as np
import csv
import matplotlib.pyplot as plt
df = pd.read_csv('grade19.csv') #read exel sheet
reg = linear_model.LinearRegression()
reg.fit(df[['7th','12th','att']],df.final) #predect final grade
numOfStudents=int(input("enter number of student"))
print("7th 12th Attendance")
for i in range(numOfStudents):
mid1, mid2,att = map(int, input("").split())
output=reg.predict([[mid1, mid2,att]])
sum=mid1+mid2+att
if (sum <= 60 ) :
print("your grade before final exam is " , sum)
print("the final mark will be ", np.round(output,2) , "the garde will be " ,end="")
finalgrade = output
mark = output
fields=[mid1,mid2,att,np.round(output,2)]
with open(r'grade20.csv', 'a+') as f:
writer = csv.writer(f)
writer.writerow(fields)
if (95 <= mark <= 100):
print("A+")
elif (90 <= mark < 95):
print("A")
elif (85 <= mark < 90):
print("A-")
elif (80 <= mark < 85):
print("B+")
elif (75 <= mark < 80):
print("B")
elif (70 <= mark < 75):
print("B-")
elif (65 <= mark < 70):
print("C+")
elif (60 <= mark < 65):
print("C")
elif (60 <= mark < 50):
print("D")
elif ( mark > 101):
print("please enter valid input")
else:
print("F")
print("7th 12th Attendance")
else:
print("Error!!! ", end="\n")
x1 = np.array([0,25,50,75,100])
y1 = np.array([10,80,25,60,80])
x2 = np.array([0,20,40,60,80,100])
y2 = np.array([70,90,20,30,50,70])
plt.plot(x1,y1,c="g")
plt.plot(x2,y2,c="r")
#plt.show()
dff = pd.read_csv('grade20.csv')
print("2020",round(dff.describe(),1))
|
1064ec345d2d9b98cd6518ebf514032364f9d6fd | ishwarjindal/Think-Python | /Ex10_4_Chop.py | 354 | 3.65625 | 4 | #Author : Ishwar Jindal
#Created On : 07-Jul-2019 12:37 PM
#Purpose : Chop the list
def chop(lst):
#lst1 = lst[:]
lst.pop(0)
lst.pop(-1)
return None
print("main started")
myList = [10,20,30,40,50]
print(str.format("List before chopping is {0}", myList))
chop(myList)
print(str.format("List after chopping is {0}", myList))
print("main ended")
|
6f693cc325f07ef6ba7448126e67f7a695880636 | Aasthaengg/IBMdataset | /Python_codes/p03624/s314153396.py | 127 | 3.640625 | 4 | S=[x for x in input()]
A='abcdefghijklmnopqrstuvwxyz'
for a in A:
if a not in S:
print(a)
break
else:
print('None') |
3583e8d55ed4377dc0c89f1a69793af28af490d1 | cu-swe4s-fall-2019/test-driven-development-sahu0957 | /get_data.py | 1,246 | 3.546875 | 4 | import sys
import argparse
import select
def read_stdin_col(col_num):
# Only move forward with the script if stdin is empty
# otherwise, exit to avoid the program stalling
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
X = []
for l in sys.stdin:
try:
A = l.rstrip().split()
X.append(float(A[col_num]))
except IndexError:
# Indexes specified that are out of range
# will throw an error
raise IndexError('Column does not exist!')
sys.stderr.write('Column does not exist!')
sys.exit(1)
if len(X) == 0:
# Lists of length 0 will return None, to avoid
# errors in other scripts
return None
else:
return X
else:
sys.stderr.write('No input data')
sys.exit(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="returns specified column from stdin")
parser.add_argument("column_index",
help="column index of stdin",
type=int)
args = parser.parse_args()
a = read_stdin_col(args.column_index)
print(a)
|
98d69423c830e0ace5c4bb3024bac8db4042ff68 | ssx1235690/pythonfullstack | /16-day线程.py | 880 | 3.625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# __Author__ = songxy
# date : 2018/5/10
import threading
import time
print('start')
def song(bar):
time.sleep(1)
print('song',bar)
def xiang(bar):
time.sleep(2)
print('xiang',bar)
t1 = threading.Thread(target=song,args=('lele',))
t2 = threading.Thread(target=xiang,args=('baba',))
t1.start()
t2.start()
# t1.join()
#
# t2.join()
print(time.time())
##############################间接调用##########################
import threading
import time
class MyThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self): # 定义每个线程要运行的函数
print("running on number:%s" % self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
|
0216498747c0f7bc983719d6f8d59552f98ca194 | ArnoldoRicardo/gato | /main32.py | 849 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
map = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def si(preg):
resp = input(preg)
return (resp[0] == 's')
def tirar(player,pos):
ind = pos.split(",")
n = int(ind[0]) - 1
m = int(ind[1]) - 1
if player == 1:
map[m][n] = "x"
else:
map[m][n] = "o"
def check():
print("hola")
def printcrux():
print (map[0][0]+" | "+map[0][1]+" | "+map[0][2]+" ")
print ("----------")
print (map[1][0]+" | "+map[1][1]+" | "+map[1][2]+" ")
print ("----------")
print (map[2][0]+" | "+map[2][1]+" | "+map[2][2]+" ")
def main():
i=0
while True:
pass
np = i % 2 + 1
pos = str(input("jugador "+str(np)+" (ejemplo 2,3): "))
tirar(np,pos)
check()
printcrux()
i= i + 1
if __name__ == '__main__':
while True:
if si("Quieres iniciar la partida? "):
main()
else:
break |
94f6bc08eddc1e8594aee1f407406e2f3b3e9dfc | abx67/BasicDataScienceAlgorithm | /Goldman_Sachs/second_min.py | 472 | 3.609375 | 4 | def second_min(num):
n= len(num)
if n < 2:
return -1
if num[0] > num[1]:
min = num[1]
second = num[0]
else:
min = num[0]
second = num[1]
for i in range(2,n):
if num[i] < min:
second = min
min = num[i]
elif num[i] < second:
second = num[i]
return(second)
vec1=[5,6,2,6,9,2,65,65,95,6,2,1,26,-2.1,-6,62,-2,1]
print(second_min(vec1)) |
0828f989103a49a4c23cdab0f673519488c5412a | mrhut10/funky | /funky.py | 3,339 | 4.09375 | 4 | # generic fancy Function's
# trying to loosely follow principles of functional programming paradigm and Category theory within Math
# function -> function
def curry(fun:"function"):
"""
implementation of a curry/currying function
visit https://en.wikipedia.org/wiki/Currying for more information
"""
def curried(*args, **kwargs):
if len(args) + len(kwargs) >= fun.__code__.co_argcount:
return fun(*args, **kwargs)
return lambda *args2, **kwargs2: curried(*(args + args2), **dict(kwargs, **kwargs2))
return curried
# function function -> function
def compose (*functions):
"""
implementation of the compose / composition function for uniary functions (uni-ary as in 1 input variable)
visit https://en.wikipedia.org/wiki/Function_composition_(computer_science)
took me ages to get this to work for more than two functions
"""
def composed(arg=None): # function that will be returned
for f in reversed(functions):
arg = f(arg)
return arg
return composed
#function -> [iterable] -> [iterable]
# will run a function over all elements and return result
map = lambda f, a: [f(x) for x in a]
# idenity function visit https://en.wikipedia.org/wiki/Identity_function
# a -> a
idenity = lambda a : a
# a -> b -> bool
# will return true is a & b are equal
equal = curry(lambda a, b : a == b)
# fn1 -> fn2 -> a -> bool
equalfn = curry(lambda fn1,fn2,value: fn1(value)==fn2(value))
logicalNot = lambda a : (not a)
logicalOr = curry(lambda fn1, fn2, value: fn1(value) or fn2(value))
logicaland = curry(lambda fn1, fn2, value: all((fn1(value),fn2(value))))
str_lower = lambda value: value.lower()
gt = curry(lambda a,b: b > a)
lt = curry(lambda a,b: b < a)
et = curry(lambda a,b: a==b)
# String -> a
# will pull the property of an object
prop = curry(lambda prop, x: x[prop])
increment = lambda x: x+1
decrement = lambda x: x-1
Either = curry(lambda direction1, direction2, condition, value: direction1(value) if condition(value) else direction2(value))
class TestClass(object):
commonTestCases = ['hello',True,False,3,-1,3.3,-3.3,None,[1,2,3]]
def test_curry(self):
function = lambda a,b,c:a**3+b**2+c
assert curry(function)(3)(2)(1) == 32
def test_compose(self):
last = lambda x: x[-1]
flip = lambda a: [b for b in reversed(a)]
composed = compose(last,flip)
assert composed(['im','test','data']) == 'im'
def test_equal(self):
testcases = self.commonTestCases
for a in testcases:
for b in testcases:
assert equal(a,b) == (a==b)
def test_idenity(self):
testcases = self.commonTestCases
for t in testcases:
assert idenity(t) == t
def test_logicalNot(self):
testcases = [True,False]
for t in testcases:
assert logicalNot(t) == (not t)
def test_logicalOr(self):
testCase = logicalOr(lambda x:x>0,lambda x:x<0)
assert testCase(-1) == True
assert testCase(0) == False
assert testCase(1) == True
def test_str_lower(self):
assert str_lower('Y') == 'y'
assert str_lower('N') == 'n'
assert str_lower('y') == 'y'
assert str_lower('n') == 'n'
def test_Either(self):
testcase = Either(lambda x:x,lambda _:None,lambda x:x.isdigit())
assert testcase('abc') == None
assert testcase('') == None
assert testcase('8') == '8'
assert testcase('9') == '9'
|
065f0c9ad6a542087f75bc9373c67580854e6675 | dersonf/aulaemvideo | /exercicios/ex040.py | 435 | 3.71875 | 4 | #!/usr/bin/python36
n1 = float(input('Insira a PRIMEIRA nota: '))
n2 = float(input('Insira a SEGUNDA nota: '))
media = float((n1 + n2) /2)
if media >= 7:
print('Sua média foi {:.1f}, você foi \033[1;32;44mAPROVADO\033[m!'.format(media))
elif media >= 5:
print('Sua média foi {:.1f}, voce está de RECUPERAÇÃO!'.format(media))
else:
print('Sua média foi {:.1f}, você foi \033[1;31;44mREPROVADO\033[m!'.format(media))
|
4de19754f697ad1d368d9eed62b47b69235bd888 | northbridge-portfolio/PYTHON | /PythonPoker/Hand.py | 2,252 | 3.734375 | 4 | '''
Filename: Hand.py
Author: NorthBridge
Python Version: 2.7
Copyright 2017 - NorthBridge - All Rights Reserved
This class is responsible for encapsulating cards
into a list of Cards called called_list.
'''
from Suit import *
import Card
class Hand(object):
# Constructor terminates on error.
# Could consider throwing an exception and passing this back to the caller
# for corrected user input.
def __init__(self, hand_string_array):
card_list = []
for element in hand_string_array:
card_list.append(Card.Card(element))
self._hand = tuple(card_list)
def get_rank_histogram(self):
#temp_hist = []
rank_count = [0] * 13
for index in range(0, len(self._hand)):
rank_count[self._hand[index].get_rank() - 2] += 1
return rank_count
def get_suit_histogram(self):
suit_count = [0] * 4
for element in self._hand:
if element.get_suit() is Suit.CLUB:
suit_count[element.get_suit_rank()] += 1
elif element.get_suit() is Suit.DIAMOND:
suit_count[element.get_suit_rank()] += 1
elif element.get_suit() is Suit.HEART:
suit_count[element.get_suit_rank()] += 1
elif element.get_suit() is Suit.SPADE:
suit_count[element.get_suit_rank()] += 1
return suit_count
def __str__(self):
s = ""
for element in self._hand:
s += str(element) + " "
return s
def get_cards(self):
return list(self._hand)
def sort(self):
temp_list = list(self._hand)
temp_list.sort()
if(temp_list is not None):
self._hand = tuple(temp_list)
return self._hand
else:
print "SORTING ERROR"
def sort_reverse(self):
temp_list = list(self._hand)
temp_list.sort(reverse=True)
if(temp_list is not None):
self._hand = tuple(temp_list)
return self._hand
else:
print "REVERSE SORTING ERROR"
''' Copyright 2017 - NorthBridge - All Rights Reserved ''' |
3c56a4a55a43e0fc6abca9d2ca5dfad8efa74dc1 | AlexAbades/Python_courses | /3 - Python_Deep_Dive/Part 1_Functional Programming/3 - Numeric types/18 - Comparison Operators/Comparision.py | 1,315 | 4.09375 | 4 | # Categories of Comparision Operators
# Binary operators
# evaluate to a bool value
# Identity operators: is / is not --> compares memory address - any type
# Value comparision: == / != --> Compares values, different types OK, but must be compatible.
# Will work with all numeric types.
# Mixed types (except complex) supported
# 10.0 == Decimal('10.0') --> True
# 0.1 == Decimal('0.10') --> False. In binary we son't have an exact representation of 0.2
# Decimal('0.125') == Fraction(1,8) --> True
# True == 1 --> True
# True == Fraction(3 ,3) --> True
# a == b == c --> a == b and b == c
# Ordering comparision: < / <= / > / >= --> Doesn't work for all types.
# Mixed types (except complex) supported
# 1<3.14
# Fraction(22, 7) > math.pi
# Decimal('0.5') <= Fraction(2, 3)
# a < b < c --> a < b and b < c
# Membership Operations: in / not in --> used for iterable types
print(0.1 is (3 + 4j))
print(3 is 3)
print([1, 2] is [1, 2])
print('a' in 'this is a text')
print(3 not in [1, 2, 3])
print('key1' in {'key1': 1})
print(1 in {'key1': 1})
print(4 == 4 + 0j)
print(4.3 == 4.3 + 0j) # Remember complex are floats we'll have the same problem
3 < 2 < 2/0
import string
print('A'<'a'<'z'>'Z')
print('A'<'a'<'z'>'Z' in string.ascii_letters)
|
86ea7a1be46be6c3c68f4d6e348b25d5fe788b75 | testcomt/pythonlearning | /test_rhl.py | 2,198 | 4 | 4 | MAX_COUNT = 10000
# number shuold be a positive integer?
def cube_int(number):
"""input a positive integer
return 0 if not being able to find"""
if number == 0:
return 0
if number == 1:
return 1
min_number = 0
max_number = number
value = number // 2
count = 0
while True:
count += 1
real_number = value ** 3
if real_number > number:
max_number = value
elif real_number < number:
min_number = value
else:
break
value = (min_number + max_number)//2
# print "(min_number = ", min_number, " max_number = ", max_number, " value = ", value, " )"
# print count
if value <= min_number or count > MAX_COUNT:
value = 0
break
return value
ACCURACY = 0.0001
def cube_float(number):
min_number = 0
max_number = number
value = number/2
count = 0
while True:
count += 1
real_number = value ** 3
if real_number > number + ACCURACY:
max_number = value
elif real_number < number - ACCURACY:
min_number = value
else:
break
value = (min_number + max_number)/2
# print "(min_number = ", min_number, " max_number = ", max_number, " value = ", value, " )"
# print count
if value <= min_number or count > MAX_COUNT:
value = 0
break
return value
def cube():
try:
while True:
x = eval(raw_input("please input the value = "))
neg_flag = False
if x < 0:
neg_flag = True
x = abs(x)
if isinstance(x, int):
value = cube_int(x)
else:
value = cube_float(x)
if neg_flag:
value = -1 * value
if x == 0:
print("Value is 0")
elif value == 0:
print("cannot find the cube")
else:
print("value is ", str(value))
except:
print("input error, please input int or float")
cube()
|
8790cda34a4758e4d4224f562b38ba37e178ad89 | panmaroul/Numeric-Analysis | /ex5.py | 1,300 | 4.03125 | 4 | from matplotlib import pyplot as plt
import numpy as np
import math
'''
The deltaArray function returns a deltaarray matrix which contains all the Δ that is used for
computing the polynomial approximation
'''
def deltaArray():
deltaarray = np.zeros((len(arraysOfy),len(arraysOfy)))
for i in range(0, len(arraysOfy)-1):
deltaarray[i][0]=(arraysOfy[i+1]-arraysOfy[i])/(arraysOfx[i+1]-arraysOfx[i])
for i in range(1,len(arraysOfy)-1):
for j in range(0, len(arraysOfy)-i-1):
deltaarray[i][j]=(deltaarray[i-1][j+1]-deltaarray[i-1][j])/(arraysOfx[i+j+1]-arraysOfx[j])
return deltaarray
'''
The polynomial functions returns the approximate sum of sin function
'''
def polynomial(x):
sum1 = arraysOfy[0]
deltaarray = deltaArray()
for i in range (0,len(arraysOfy)-2):
a = float(deltaarray[i][0])
p = 1
for j in range(0,i+1):
p = p*(x-arraysOfx[j])
sum1 = sum1 + a*p
return sum1
begin = -3.14
end = 3.14
arraysOfy=[]
arraysOfx = np.random.uniform(begin,end,200 )
sort_arrayx = arraysOfx.sort()
for i in arraysOfx:
arraysOfy.append(math.sin(i))
print(polynomial(5))
X = np.linspace(begin, end, 200)
plt.plot(X,polynomial(arraysOfy))
plt.show()
|
25f9411fe628a5bed07b396a8b3b4572c7822130 | sebastianceloch/wd_io | /lab5/zadanie8.py | 740 | 3.625 | 4 | class Samogloski:
def __init__(self, napis):
if isinstance(napis, str):
self.napis = napis
self.index = 0
self.lista = ['a','ą','e','ę','i','o','ó','u','y','A','Ą','E','Ę','I','O','Ó','U','Y']
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.napis):
raise StopIteration
while self.index < len(self.napis):
if self.napis[self.index] in self.lista:
self.index+=1
return self.napis[self.index-1]
self.index+=1
gen = Samogloski("woyioraae")
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen)) |
18c0542251fb31e6c9cb90c9fdab8bdf5eeb544f | MartinMxn/NailTheLeetcode | /Python/Medium/Fine_572. Subtree of Another Tree.py | 1,202 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
"""
preorder
O(m*n)
"""
# def same_tree(self, s, t):
# if not s and not t:
# return True
# if not s or not t:
# return False
# if s.val == t.val:
# return self.same_tree(s.left, t.left) and self.same_tree(s.right, t.right)
# return False
# def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
# if not s and t:
# return False
# if self.same_tree(s, t): return True
# return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
"""
O(m + n)
by serialized two tree
and string serach
"""
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
def serialize(node):
if not node:
return '#'
l = serialize(node.left)
r = serialize(node.right)
node.se = '^' + str(node.val) + '$' + l + r
return node.se
return serialize(t) in serialize(s)
|
701cd161f0d0790c8b82e61dddd83bc9fa233248 | orenovadia/euler | /solved/euler2.py | 745 | 3.578125 | 4 | from math import sqrt
def isPandigital(s):
return set(s) == set('123456789')
rt5=sqrt(5)
def check_first_digits(n):
def mypow( x, n ):
res=1.0
for i in xrange(n):
res *= x
# truncation to avoid overflow:
if res>1E20: res*=1E-10
return res
# this is an approximation for large n:
F = mypow( (1+rt5)/2, n )/rt5
s = '%f' % F
if isPandigital(s[:9]):
print n
return True
a, b, n = 1, 1, 1
while True:
if isPandigital( str(a)[-9:] ):
# Only when last digits are
# pandigital check the first digits:
if check_first_digits(n):
break
a, b = b, a+b
b=b%1000000000
n += 1 |
43b32df6404181e5f4cd98894f3e6026d4630f54 | vgattani-ds/programming_websites | /leetcode/0128_removeCoveredIntervals.py | 778 | 3.59375 | 4 | from typing import List
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
result = len(intervals)
if result == 1:
return 1
intervals.sort(key= lambda x: (x[0],-x[1]))
prev_x, prev_y = intervals[0]
for index, interval in enumerate(intervals[1:], start=1):
curr_x, curr_y = interval
if prev_x <= curr_x and prev_y >= curr_y:
result -= 1
else:
prev_x, prev_y = curr_x, curr_y
return result
if __name__ == "__main__":
intervals=[[1,4],[3,6],[2,8]]
print(Solution().removeCoveredIntervals(intervals))
print(f"Correct Answer is: 2") |
ca2bf6465a6c687991f1c0d8db997a082374d9b9 | ZhenJie-Zhang/Python | /homework/m2_iteration/amstrong.py | 592 | 3.640625 | 4 | # 4. 迴圏的練習-amstrong
# Armstrong數是指一個三位數的整數,其各位數之立方和等於該數本身。
# 找出所有的Amstrong數。
# 說明:153=1^3+5^3+3^3,故153為Amstrong數。
num = 999
for test in range(100, num + 1):
digit100 = test // 100
digit10 = test % 100 // 10
digit1 = test % 10
# print(digit100, digit10, digit1)
Cube_Sum = digit100 ** 3 + digit10 ** 3 + digit1 ** 3
# print(Digit_cube_sum)
if test == Cube_Sum:
print('{} = {}^3 + {}^3 + {}^3,所以是Armstrong數'.format(Cube_Sum, digit100, digit10, digit1))
|
04e74052ee305001dc0c0fd8a9c8ceb6619dd3bb | ravenstudios/nQueens | /main.py | 1,810 | 3.828125 | 4 | # Robert Dodson RavenStudios 11/1/21
import math
# print("nQuees")
result = [];
n = 4;
def place_queen(row):
if row > n:
return
# loop through each col in a row and try to place a queen
# if backtracking start the loop at the next col that the previous result
for_start = row * n
for_stop = row * n + n
if len(result) > row:
for_start = result[row] + 1
result.pop()
for i in range(for_start, for_stop, 1):
if check_is_col_safe(i) and check_is_row_safe(i) and check_is_diag_safe(i):
# if we can place a queen the we place it and call place again with new row
result.append(i)
if len(result) == n:
print(result)
return
place_queen(row + 1)
return
place_queen(row - 1)
def check_is_row_safe(pos):# returns true if safe to place in row
row = math.floor(pos / n)
col = pos % n
if pos in result:
return False
return True
def check_is_col_safe(pos):
nums = []
row = math.floor(pos / n)
col = pos % n
for i in range(n):
nums.append(col + (i * n))
for num in nums:
if num in result:
return False
return True
def check_is_diag_safe(pos):
# check result list against pos
nums = []
row = math.floor(pos / n)
col = pos % n
for i in range(len(result)):
temp_pos = result[i]
temp_pos_row = math.floor(temp_pos / n)
temp_pos_col = temp_pos % n
delta_row = abs(row - temp_pos_row)
delta_col = abs(col - temp_pos_col)
# print("delta row: ", delta_row, " deltaCol: ", delta_col)
if delta_row == delta_col:
return False
return True;
place_queen(0)
|
be8ceb7acd1285f6d75f6e10a4598c9504dfb0ae | abelAbel/OS_Dean_Abel | /Gui_Practice/__init__.py | 3,060 | 3.546875 | 4 | __author__ = 'abelamadou'
from threading import Thread
from Tkinter import *
import tkinter.messagebox
import tkFont
root = Tk()
frame = Frame(root, bd=2,bg='blue', relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)
yscrollbar = Scrollbar(frame)
yscrollbar.grid(row=0, column=1, sticky=N+S)
# canvas = Canvas(frame, bd=0,
# xscrollcommand=xscrollbar.set,
# yscrollcommand=yscrollbar.set)
canvas = Canvas(frame, bd=0,background="yellow", scrollregion=(0, 0, 30000, 30000),width=1000, height=1000,
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
# canvas.pack(fill=BOTH,expand=True)
xscrollbar.config(command=canvas.xview)
yscrollbar.config(command=canvas.yview)
# label1 = Label(canvas, text="Hello", bd=10,relief="ridge", anchor=N)
# label1.grid(row=0, column=1)
# label2 = Label(canvas, text="Hello", bd=10,relief="ridge", anchor=N)
# label2.grid(row=1, column=1)
# label3= Label(canvas, text="Bread", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
# label3.grid(row=1, column=1)
# label4= Label(canvas, text="Bread", bg="red", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
# label4.grid(row=0, column=1)
# label5= Label(canvas, text="Cinammon", bg="green", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
# label5.grid(row=2,column=1)
# label6= Label(canvas, text="Cinammon", bg="green", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
# label6.grid(row=3,column=1)
# canvas.config(scrollregion=canvas.bbox("all"))
frame2 = Frame(canvas, borderwidth=5, bg='blue')
frame2.grid_rowconfigure(0, weight=1)
frame2.grid_columnconfigure(0, weight=1)
frame2.grid(row=0, column=1)
label1 = Label(frame2, text="Hello", bd=10,relief="ridge", anchor=N)
label1.grid(row=0, column=1)
label1 = Label(frame2, text="Hello", bd=10,relief="ridge", anchor=N)
label1.grid(row=1, column=1)
label1= Label(frame2, text="Bread", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
label1.grid(row=1, column=1)
label1= Label(frame2, text="Bread", bg="red", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
label1.grid(row=0, column=1)
label1= Label(frame2, text="Cinammon", bg="green", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
label1.grid(row=2,column=1)
label1= Label(frame2, text="Cinammon", bg="green", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
label1.grid(row=3,column=1)
label1= Label(frame2, text="Cinammon", bg="green", font=tkFont.Font(family="Helvetica", size =40),bd=10,relief="ridge", anchor=N)
label1.grid(row=4,column=1)
# canvas.create_window(400, 400, window=frame2)
canvas.create_oval(0,1,50,50,fill='red')
frame.pack()
root.mainloop() |
1499280e835d5c7f17f8b876c5caad28d4f53a32 | carevon/learning-python | /basics/print.py | 226 | 3.84375 | 4 | # PYTHON BASICS - PRINT FUNCTION
subst = "Python"
verb = "is"
adjective = "fantastic"
print(subst, verb, adjective, sep="_", end="!\n")
# IMPRIMINDO UMA DATA
dia = "07"
mes = "07"
ano = "1993"
print(dia, mes, ano, sep="/") |
f3bccf13bc8a8fa44786b621812ed63af1936db9 | Meaha7/dsa | /trees/binary/practice/insert-in-level-order.py | 587 | 3.75 | 4 | from collections import deque
from binarytree import build, Node
def main(root, val):
if not root:
return Node(val)
queue = deque([root])
while queue:
node = queue.popleft()
if node.left:
queue.append(node.left)
else:
node.left = Node(val)
return root
if node.right:
queue.append(node.right)
else:
node.right = Node(val)
return root
for root in [
build([1, 2, 3, 4, 5, 6, 7, None, None, 8, None, None, 9, None, None])
]:
print(main(root, 12))
|
55dff8a504ddc8afe40872cbcc16ece98f685097 | okumurakengo/til | /python/17_str.py | 303 | 3.53125 | 4 | name = "taguchi"
score = 52.3
print("name: %s, score: %f" % (name, score))
print("name: %-10s, score: %10.2f" % (name, score))
print("name: {0}, score: {1}".format(name, score))
print("name: {0:10s}, score: {1:10.2f}".format(name, score))
print("name: {0:>10s}, score: {1:<10.2f}".format(name, score))
|
89ad1cf0fbdfbc8254908c10ad93031f8a3871b9 | sandeepdas31/python | /simpleclassobj.py | 307 | 3.671875 | 4 | class person:
def __init__(self,x,y):
print("simple class object program")
self.x=x
self.y=y
self.x+=self.y
def fun(self,z):
self.z=z
print(z)
p1=person(30,20)
print(p1.x)
print(p1.y)
p1.fun(8745)
p1.fun("hello") |
3c6424b24f9fbf178360b5f0eb5322b0002174dd | swynnejr/bank_account | /bank_account.py | 1,211 | 3.875 | 4 | class BankAccount:
def __init__(self, int_rate, balance):
self.int_rate = int_rate
self.balance = balance
# self.name = User
def deposit(self, amount):
self.balance += amount
return self
def withdrawl(self, amount):
if self.balance < amount:
print("We took $5 that you don't even have.")
self.balance -= (amount + 5)
return self
else:
self.balance -= amount
return self
def display_account_info(self):
print(f'Your balance is: {self.balance}')
def yield_interest(self):
self.balance += self.int_rate * self.balance
return self
# class User:
# def __init__(self, name, email):
# self.name = name
# self.email = email
# self.balance = 0
account1 = BankAccount(.02, 100)
account2 = BankAccount(.02, 100)
account3 = BankAccount(.02, 100)
account1.deposit(350).deposit(475).deposit(225).withdrawl(14).yield_interest().display_account_info()
account2.withdrawl(400).display_account_info()
account3.deposit(125).deposit(900).withdrawl(19).withdrawl(42).withdrawl(7).withdrawl(19).yield_interest().display_account_info() |
13b64f19e499279ce9c80a291ace9f2b6a3d4373 | qeedquan/challenges | /leetcode/matrix-diagonal-sum.py | 1,089 | 4.34375 | 4 | #!/usr/bin/env python
"""
Given a square matrix mat, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
Example 1:
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
"""
def diagonal(m):
n = len(m)
r = 0
for i in range(n):
r += m[i][i]
r += m[i][n-i-1]
if n&1 != 0:
r -= m[n//2][n//2]
return r
def main():
assert(diagonal([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 25)
assert(diagonal([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) == 8)
assert(diagonal([[5]]) == 5)
main()
|
75e93c0987bc7ff9c21846dca746d96e726539ec | lalit97/DSA | /Tree/count_leaves.py | 594 | 3.71875 | 4 |
'''
one of the way
'''
count = 0
def countLeaves(root):
global count
count = 0
count_helper(root)
return count
def count_helper(root):
global count
if root is None:
return None
if root.left is None and root.right is None:
count += 1
count_helper(root.left)
count_helper(root.right)
############################################
'''
more smarter
'''
def countLeaves(root):
if root is None:
return 0
if root.left is None and root.right is None
return 1
return countLeaves(root.left) + countLeaves(root.right) |
d35f7a00aa9e553a3c8011d02bd8ccdab77e3129 | Fromero8706/AIA---GeoOpt | /A2/AIA_GEOOPT_SUNVEC_FR.py | 1,225 | 3.6875 | 4 | """
IAAC - Master of Computation for Architecture & Design (MaCAD)
Seminar: Digital tools for Algorithmic Geometrical Optimization
Faculty: David Andres Leon, Dai Kandil
Student: Felipe Romero
Assignment 02 - Part A Sun Vector Script
"""
import Rhino.Geometry as rg
#import Rhinoscriptsyntax as rs
import math
#create a sun vector
#1. create a Sphere at point (0,0,0) with radius 1 and output it to a
#output the sphere to a
#center = rg.Point3d(0,0,0)
center = rg.Point3d(0,0,0)
sphere = rg.Sphere(center, radius=1)
a = sphere
#2. evaluate a point in the sphere using rg.Sphere.PointAt() at coordintes x and y
#the point should only be on the upper half of the sphere (upper hemisphere)
#the angles are in radians, so you might want to use math.pi for this
#output the point to b -
lon = (x/math.pi)*360 # NOT WORKING PROPERLY
lat = y*math.pi
point = rg.Sphere.PointAt(a, lon, lat)
b = point
#create a vector from the origin and reverse the vector
#keep in mind that Reverse affects the original vector
#output the vector to c
vec1 = rg.Vector3d (b)
#vec2 = rg.Vector3d (center)
vecdir = rg.Line(center,b)
#vecneg = rg.Vector3d.Reverse(vec1)
vecneg = rg.Vector3d.Negate(vec1)
#vec2 = rg.Vector3d (vecneg)
c = vecneg
d = vecdir
|
af949b5b1e842b9b2e823a0446aad50902f4bdf6 | SimonFans/LeetCode | /OA/MS/Max Network Rank.py | 384 | 3.515625 | 4 | from collections import defaultdict
def max_network_rank(A,B,N):
res=float('-Inf')
mp=defaultdict(list)
for i in range(len(A)):
mp[A[i]].append(B[i])
mp[B[i]].append(A[i])
print(mp)
for i in range(len(A)):
res=max(res,len(mp[A[i]])+len(mp[B[i]])-1)
return res
A=[1,2,3,3]
B=[2,3,1,4]
N=4
print(max_network_rank(A,B,N))
|
bb8297d9bbde029a494cce6e3c3fc05cd58ef36d | dim-akim/python_lessons | /profile_10/lesson2_sort_new.py | 379 | 3.6875 | 4 | n = 6
a = [2, 8, 15, 6, -5, 3]
b = []
for i in range(n):
# ищем минимальное значение в массиве
minimum = a[0]
for j in range(n):
if a[j] < minimum:
minimum = a[j]
b.append(minimum)
a.remove(minimum)
n = n - 1 # решаем проблему с изменением длины списка
print(b)
|
5b588dcd4b79d0ee3c64eb505cb12f0fd5197a18 | blopah/python3-curso-em-video-gustavo-guanabara-exercicios | /Desafios/Desafio 106.py | 866 | 4.125 | 4 | print('''Faça um mini sistema que utilize o interactive Help do Python.
O usuário vai digitar o comando e o manual vai aparecer.
Quando o usuário digitar a palavra "FIM",
o programa se encerrará. OBS:Use cores''')
from time import sleep
def msgr(x):
l = len(x)+2
print('\033[1;30;41m~' * l)
print(f' {x}', end='')
txt = input('')
print('~' * l)
return txt
def msgy(x):
l = len(x)+2
print('\033[1;30;43m~' * l)
print(f' {x}')
print('~' * l)
print('\033[1;30;45m', end='')
def msgp(x):
l = len(x)+2
print('\033[1;30;45m~' * l)
print(f' {x}')
print('~' * l)
def ajuda():
while True:
txt = msgr('Função ou Biblioteca (FIM para sair)>')
if txt in 'FIMfim':
break
sleep(1)
msgy(f'Acessando a ajuda de {txt}.')
sleep(1)
help(txt)
ajuda() |
875d880a84d3e1c9f9cc258505b4e7a41bca2ee3 | yamarba/algorithmsngames | /nonRepeating1.py | 579 | 3.84375 | 4 | # This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def non_repeating(s):
s = s.replace(' ', '').lower()
char_count = ()
for c in s:
if c in char_count:
char_count[c] += 1
else:
char_count[c] = 1
for c in s:
if char_count == 1:
return c
return None
print(non_repeating(' I Apple Ape Peels '))
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
a917acab5912af5a9b7b13e20cffcc1bd5543151 | pkrishn6/problems | /api/singleton.py | 484 | 3.71875 | 4 | class SingleTone:
__instance = None
def get_instance(val):
if not SingleTone.__instance:
SingleTone.__instance = SingleTone(val)
return SingleTone.__instance
def __init__(self, val):
if SingleTone.__instance is not None:
raise KeyError
self.val = val
SingleTone.__instance = self
a = SingleTone(10)
print(a.val)
print(a)
assert isinstance(a, SingleTone) == True
b = SingleTone(20)
print(b.val)
print(b)
|
c3220cd1bf71ad4f97d6362b9a49dfeabf0f166c | shenlinli3/python_learn | /second_stage/day_11/demo_02_面向对象-私有属性.py | 1,032 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2021/5/22 11:41
@Author : zero
"""
# 面向对象的三大特性之一:封装
# 私有属性 private
class Person:
__sex_list = ["GG", "MM"]
def __init__(self, name, sex):
if type(name) != str or type(sex) != str:
raise TypeError("姓名和性别必须是字符串")
self.__name = name # 属性前面加上__代表这是一个私有属性
self.__sex = sex
def get_name(self):
return self.__name
def get_sex(self):
return self.__sex
def set_name(self, new_name):
self.__name = new_name
def set_sex(self, new_sex):
if type(new_sex) != str or new_sex not in self.__sex_list:
raise TypeError("性别必须是字符串")
self.__sex = new_sex
p1 = Person("zhangsan", "GG")
p2 = Person("lisi", "MM")
# p3 = Person("lisi", 1)
# print(p1.__sex) # 找不到
# p1.__sex = "MM" # 找不到
print(p1.get_sex())
print(p2.get_sex())
|
f395c7e7becad95088723f73e7a0e7bdd143992b | AntonioCenteno/Miscelanea_002_Python | /Ejercicios progra.usm.cl/Parte 1/3- Ciclos/tabla-de-multiplicar.py | 270 | 3.90625 | 4 | #Hacemos dos ciclos for, que vayan de 1 a 10
for y in range(1,11): #Eje y
for x in range(1,11): #Eje x
print str(x*y).rjust(4),
#rjust() justifica el texto a la derecha
#rellenando con espacios hasta llegar a
#un largo de 4.
print "" #Pasar a la linea de abajo |
9c6bc65fe9fda0e72a7fe0fb0b8d2207d16a1e54 | rivergt/python-learning | /1-10num_guess.py | 1,048 | 3.734375 | 4 | #猜数字游戏2.0版本【20191018AM11:25】
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
answer = random.randint(1,10)
print("我爱猜数字游戏2.0版本")
guess = int(input("来猜猜我心里想的是哪个数字,1-10随便选一个吧:"))
counter = 0
if (guess == answer) and (counter == 0) :
print("恭喜你,第一次就答对了")
else:
while (guess != answer) and (counter < 4) :
counter += 1
if guess > answer:
print("猜大了,您已经猜过",counter,"次了,最多5次哦")
guess = int(input("再猜小一点试试吧:"))
else:
print("猜小了,您已经猜过",counter,"次了,最多5次哦")
guess = int(input("再猜大一点试试吧:"))
if counter == 0 :
print("再见!")
else:
if guess != answer:
print("次数超过5次,您依然没有猜对,游戏结束。\n再见")
else:
print("恭喜你,答对了,游戏结束。\n再见!")
|
d189b0609e3d89225dd484cfbf454c617b6e28aa | marcelfeige/MashineLearningCode | /LinRegressionWohnung.py | 731 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
df = pd.read_csv(
"..\Kursmaterialien\Abschnitt 05 - Lineare Regression\wohnungspreise.csv")
plt.scatter(df["Quadratmeter"], df["Verkaufspreis"])
#plt.show()
model = LinearRegression()
model.fit(df[["Quadratmeter"]], df[["Verkaufspreis"]])
# Verkaufspreis = Intercept + Coef * x
print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))
# Vorhersagen durch das Model
min_x = min(df["Quadratmeter"])
max_x = max(df["Quadratmeter"])
predicted = model.predict([[min_x], [max_x]])
plt.plot([min_x, max_x], predicted, color = "red")
plt.xlabel("Quadratmeter")
plt.ylabel("Verkaufspreis")
plt.show()
|
e55775b42cc6bb4939b8d8ea6395f2ae98e70c58 | Introduction-to-Programming-OSOWSKI/3-14-find-doubles-IsaacYantes23 | /main.py | 179 | 3.671875 | 4 | def findDoubles(w):
for i in range(0, len(w)):
if w[i] == w[i-1]:
return True
else:
return False
print(findDoubles("madagascar"))
|
b88eac4ce3689abc81efe7efd1a72ddddd4add27 | uiandwe/TIL | /algorithm/programers/해시/42577.py | 402 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def solution(phoneBook):
phoneBook = sorted(phoneBook)
for p1, p2 in zip(phoneBook, phoneBook[1:]):
if p2.startswith(p1):
return False
return True
def test_solution():
assert solution(["119", "97674223", "1195524421"]) == False
assert solution(["123","456","789"]) == True
assert solution(["12","123","1235","567","88"]) == False
|
5c00fbfdf13eda7f84271f791b00ddb6132cdd8f | govilharsh/Hello-World | /problem1.py | 115 | 3.90625 | 4 | print("Enter a number")
num=int(input())
a=0
b=1
print(a)
print(b)
for i in range(num):
c=a+b
print(zz)
a=b
b=c |
54192e1f61736cb6e8db1e82dbd15f7ce9f870ba | johnistan/Interview_Problems | /palindrome.py | 1,013 | 3.828125 | 4 | '''
Retun true if a palindrome
'''
#Recursive solution
def pal(word):
if len(word) < 2:
return True
if word[0] == word [-1]:
return pal(word[1:-1])
if word[0] != word [-1]:
return False
#Simple reverse list solution
def pal2(word):
return word == word[::-1]
#Solve by skipping over spaces and punctuation
def pal3(word):
pass
'''
kept a cursor on the left (start from 0) and a cursor on the right (start from len(string)-1) (increment and decrease the left & right indices respectively if not valid), check if they are equal, and basically do it until the two cursors have crossed over (where right < left)>
'''
def pal4(word):
""" function to strip out space and uppercases """
stripped_word = word.replace(' ','').lower()
return stripped_word == stripped_word[::-1]
print pal2('rowme')
print pal2('Lion oil')
print pal2('a man a plan a canal Panama')
print pal4('rowme')
print pal4('Lion oil')
print pal4('a man a plan a canal Panama')
|
0f7c7c012866df06c99c359faa07cc258a5da91f | orlewilson/oficina-python-uninorte-2020 | /exemplo-03.py | 528 | 3.625 | 4 | '''
Oficina Profissionalizante - Uninorte/2020
Python e suas Aplicações
Facilitador: Orlewilson Bentes Maia
Data: 30/10/2020
Nome: Seu nome
Descrição: função
'''
# função para mostrar conteúdo de um variável informada por parâmetro
def mostrarConteudo(var=0):
print(f"Conteúdo da variável: {var}")
# chamando a função
a = 3 #número inteiro
b = 3.3 #número decial
c = 4 + 5j #número complexo
d = "Wilson" #caracter
mostrarConteudo(a)
mostrarConteudo(b)
mostrarConteudo(c)
mostrarConteudo(d)
|
94bbd43e6337b92292ce3c59b95d86c0b6ef4b80 | ivarus/Challenges | /CodeEval/src/Hard/RobotMovements.py | 504 | 3.53125 | 4 | '''
Created on Mar 14, 2015
@author: Ivan Varus
Thanks: Ferhat Elmas
'''
visited = [[False]*4 for _ in range(4)]
def step(i, j):
if i == 3 and j == 3:
return 1
if min(i, j) < 0 or max(i, j) > 3:
return 0
if visited[i][j]:
return 0
visited[i][j] = True
count = step(i, j-1) + step(i, j+1) + step(i-1, j) + step(i+1, j)
visited[i][j] = False
return count
def robotMovements():
return step(0, 0)
if __name__ == '__main__':
print(robotMovements())
|
8ee7096b17c1af7346041b7c6f5da4db3a67015a | genos/online_problems | /prog_praxis/two_factoring_games.py | 2,873 | 3.640625 | 4 | #!/usr/bin/env python
############################
# Behind the Scenes #
############################
from random import randrange
def split(n):
s = 0
while (n > 0) and (n % 2 == 0):
s += 1
n >>= 1
return (s, n)
def P(a, r, s, n):
if pow(a, r, n) == 1:
return True
elif (n - 1) in [pow(a, r * (2 ** j), n) for j in range(s)]:
return True
else:
return False
def miller_rabin(n, t):
(s, r) = split(n - 1)
for i in range(t):
a = randrange(2, n)
if not P(a, r, s, n):
return False
return True
def is_prime(n):
return miller_rabin(n, 50)
# from Python Cookbook
from itertools import count, islice
def erat2():
D = {}
yield 2
for q in islice(count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = q
yield q
else:
x = p + q
while x in D or not (x & 1):
x += p
D[x] = p
# leads to primes < n:
def primes(n):
e = erat2()
ps = []
x = next(e)
while x <= n:
ps.append(x)
x = next(e)
return ps
############################
# Start of Excercise #
############################
def times(x, n):
t = 0
while not n % x:
t += 1
n //= x
return t
from itertools import chain
def prime_factors(n):
pfs = ()
for p in primes(n):
if not n % p:
pfs = chain(pfs, [p for i in xrange(times(p, n))])
return pfs
def home_prime(n):
while not is_prime(n):
n = int(''.join(str(p) for p in prime_factors(n)))
return n
def lpf(n):
return next(prime_factors(n))
def euclid_mullin():
a = 2
p = 1
while True:
yield a
p *= a
a = lpf(1 + p)
r"""
My solution isn't very long, but the machinery behind the scenes is rather
extensive. In an effort to save memory, I've tried to make heavy use of
iterators---sort of like lazy evaluation of lists in Haskell. Below is what I
wrote for this exercise; I also used an implementation of the Sieve of
Eratosthenes for primes and a Miller-Rabin primality test.
The full code is available <a href="http://codepad.org/b5oGN9hi">here</a>.
[sourcecode lang="python"]
def times(x, n):
t = 0
while not n % x:
t += 1
n //= x
return t
from itertools import chain
def prime_factors(n):
pfs = ()
for p in primes(n):
if not n % p:
pfs = chain(pfs, [p for i in xrange(times(p, n))])
return pfs
def home_prime(n):
while not is_prime(n):
n = int(''.join(str(p) for p in prime_factors(n)))
return n
def lpf(n):
return next(prime_factors(n))
def euclid_mullin():
a = 2
p = 1
while True:
yield a
p *= a
a = lpf(1 + p)
[/sourcecode]
"""
|
cb8a2d005977b92f2f3be674fc467597a64cd6c1 | rafaelperazzo/programacao-web | /moodledata/vpl_data/3/usersdata/143/798/submittedfiles/ex1.py | 327 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a = input('Valor de a')
b = input('Valor de b')
c = input('Valor de c')
delta = (b)**2-4*a*c
x1 = (-b+delta**0.5)/2*a
x2 = (-b-delta**0.5)/2*a
if (delta<0):
print ('A equação não pussui raízes reais')
else:
print('%.2f'%x1)
print('%.2f'%x2)
|
4f5bcfff48f170260be1fedb7a169ded5b584f80 | pranavgurditta/data-structures-MCA-201 | /linked_list_pranav.py | 6,143 | 4.28125 | 4 | class Node:
'''
Objective: To represent a linked list node
'''
def __init__(self,value):
'''
Objective: To instantiate a class object
Input:
self: Implicit object of class Node
value: Value at the node
Return Value: None
'''
self.data = value
self.next = None
def __str__(self):
'''
Objective: To override the string function
Input:
self: Implicit object of class Node
Return Value: String
'''
return str(self.data)
class LinkedList:
'''
Objective: To represent a linked list
'''
def __init__(self):
'''
Objective: To instantiate a class object
Input:
self: Implicit object of class LinkedList
Return Value: None
'''
self.head = None
def insertAtBeg(self,value):
'''
Objective: To add a node at the begining of a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
Return Value: None
'''
temp = Node(value)
temp.next = self.head
self.head = temp
def insertAtEnd(self,temp,value):
'''
Objective: To add a node at the begining of a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
temp : Current node
Return Value: None
'''
#Approach: Recurssively
if temp == None:
self.head = Node(value)
elif temp.next == None:
temp.next = Node(value)
else:
return self.insertAtEnd(temp.next,value)
def insertSorted(self,temp,value):
'''
Objective: To add a node in a sorted linked list
Input:
self: Implicit object of class LinkedList
value: Value to be inserted
temp : Current node
Return Value: None
'''
#Approach: Recurssively
if temp == None:
self.head = Node(value)
elif temp == self.head and value < temp.data:
newNode = Node(value)
newNode.next = temp
self.head = newNode
elif temp.next == None:
if temp.data < value:
temp.next = Node(value)
else:
self.insertAtBeg(value)
elif temp.next.data > value:
node = Node(value)
node.next = temp.next
temp.next = node
else:
return self.insertSorted(temp.next,value)
def deleteFromBeg(self):
'''
Objective: To delete a node from the begining of a linked list
Input:
self: Implicit object of class LinkedList
Return Value: Value of node deleted
'''
if self.head == None:
print("List is already empty")
else:
temp = self.head
self.head = self.head.next
temp.next = None
return temp.data
def deleteValue(self,value):
'''
Objective: To delete a node from a linked list
Input:
self: Implicit object of class LinkedList
value: Value to be deleted
Return Value: None
'''
if self.head == None:
print("Value not found")
elif self.head.data == value:
print("Deleted successfully")
self.deleteFromBeg()
else:
parent = self.head
temp = parent.next
while temp != None:
if temp.data == value:
parent.next = temp.next
temp.next = None
print("Deleted successfully")
return
else:
parent = temp
temp = temp.next
print("Value not found")
def __str__(self):
'''
Objective: To override the string function
Input:
self: Implicit object of class LinkedList
Return Value: String
'''
if self.head == None:
return "List is empty"
else:
temp = self.head
msg = "List is: "
while temp != None:
msg += str(temp.data)+" "
temp = temp.next
return msg
if __name__ == "__main__":
lst=LinkedList()
while True:
print("Press 1 to insert at the beginning")
print("Press 2 to Insert at the end")
print("Press 3 to Insert in a sorted linked list")
print("Pres 4 to Delete from beginning")
print("Press 5 to Delete a value")
print("Press 6 to Print linked list")
print("Press 7 to Exit")
print("Enter your choice:",end="")
ch = input()
if ch.isdigit()== False:
print("Invalid input")
break
ch =int(ch)
if ch==1:
print("\nEnter the value to be inserted:",end="")
lst.insertAtBeg(int(input()))
elif ch==2:
print("\nEnter the value to be inserted:",end="")
lst.insertAtEnd(lst.head,int(input()))
elif ch==3:
print("\nEnter the value to be inserted:",end="")
lst.insertSorted(lst.head,int(input()))
elif ch==4:
elt = lst.deleteFromBeg()
if elt != None:
print("Element deleted:",elt)
elif ch==5:
print("\nEnter the value to be deleted:",end="")
lst.deleteValue(int(input()))
elif ch==6:
print(lst)
else:
if ch!=7:
print("Invalid input")
break
print("**********************************************************\n")
|
1d36a30b469e8d9e4f072d7b6f49c8361bdc5efc | matt-duell/euler | /challenge_3/prime_factors.py | 4,015 | 4.125 | 4 | import math
from sets import Set
def approach1(target):
currentNumber = 3;
#Cut the numbers we have to search through in half, there won't be any over half way that are prime factors.
cur_max_pos_factor= math.floor(target /2)
#start main processing
while currentNumber < cur_max_pos_factor:
#first check if it is a factor THEN check if it is prime
modulus = target % currentNumber
if modulus == 0: #is a factor
if DEBUG==True:
print str(currentNumber) + " is a factor. Checking primeness";
#check if it is prime
if isPrime(currentNumber):
#insert if it is
prime_factors.add(currentNumber);
#resize the cur_max_pos_factor, since the maximum possible is now lowered, I want to save time by not
# checking factors that I know won't match.
if DEBUG==True:
print"Factor found:" + str(currentNumber);
print"Resizing ceiling factor to check. Old value: " + str(cur_max_pos_factor);
cur_max_pos_factor = math.floor(target/currentNumber);
if DEBUG==True:
print"Resizing ceiling factor to check. New value: " + str(cur_max_pos_factor);
#increment by 2, to avoid unneccesary processessing of non-prime evens.
currentNumber +=2;
def approach2(target):
#Cut the numbers we have to search through in half, there won't be any over half way that are prime factors.
cur_max_pos_factor= math.floor(target /2)
foundGreatestPrimeFactor=False
currentNumber=cur_max_pos_factor
#ensure we are starting at an odd number
if cur_max_pos_factor %2 == 0:
currentNumber -=1
while foundGreatestPrimeFactor==False:
#first check if it is a factor
#THEN check if it is prime
modulus = target % currentNumber
if modulus == 0: #is a factor
if DEBUG==True:
print str(currentNumber) + " is a factor. Checking primeness";
#check if it is prime now
if isPrime(currentNumber):
#insert if it is
foundGreatestPrimeFactor=True
prime_factors.add(currentNumber);
#resize the cur_max_pos_factor, since the maximum possible is now lowered, I want to save time by not
# checking factors that I know won't match.
if DEBUG==True:
print"Resizing ceiling factor to check. Old value: " + str(cur_max_pos_factor);
cur_max_pos_factor = math.floor(target/currentNumber);
if DEBUG==True:
print"Resizing ceiling factor to check. New value: " + str(cur_max_pos_factor);
#decrement by 2, to avoid unneccesary processessing of non-prime evens.
#trying to go backwards now
currentNumber=cur_max_pos_factor
#ensure we are starting at an odd number
if cur_max_pos_factor %2 == 0:
currentNumber -=1
def isPrime(number):
return brute_force_isPrime(number);
#brute force method
def brute_force_isPrime(number):
if (number == 1):
return False;
if (number == 2):
return True;
if(number > 2):
#only consider the bottom half of the numbers to start.
#if it doesn't have a factor in the first half, it won't have one in the second half.
# readjust the upper limit as we find which numbers are not factors, and we get
# more assured that the number is a prime.
# i.e. if 3 is not a factor, then if there ARE factors then it will be in the first
# third section of the numbers. if there are factors it will be with numbers
# in that new segment.
# This repeats as we go up until we get smaller and smaller windows of opportunity
# to find a factor, until we don't find one anymore, at which point we have
# concluded it is a prime
#step by 2 (avoid evens)
print "Checking primeness of "+str(number)
limit = number/2
i = 3
while i < limit:
if number %i == 0:
return False
else:
limit = number/i
i+=2
return True;
#### Main below
target=600851475143
DEBUG=False
#cur_max_pos_factor= math.floor(target /2)
# our set of prime factors
prime_factors = Set();
print "Target=" + str(target)
approach1(target)
#approach2(target) # did not flesh out approach 2 enough, is too slow.
print "The prime factors of the number: " + str(target) + " is/are: " + str(prime_factors);
|
970d0b4f8c1b3678f43f249c2b4f6add791a35d4 | EvelynBortoli/Python | /02-Variables-y-tipos/tipos.py | 282 | 3.578125 | 4 | nada = None
cadena= "Evelyn Bortoli"
numero = 15
decimal = 1.5
#imprimimos una variable
print(nada)
#imprimimos el tipo de la variable
print(type(nada))
#imprimimos una variable
print(cadena)
print(type(cadena))
print(numero)
print(type(numero))
print(decimal)
print(type(decimal)) |
6f40eb77a1904c0d5b7571af30ac5b8a96dfd45c | fuzzy69/my | /my/extra/text.py | 254 | 3.578125 | 4 | from typing import AnyStr
from pycld2 import detect
def is_text_english(text: AnyStr) -> bool:
"""Returns True if given text is English otherwise False"""
is_reliable, _, details = detect(text)
return is_reliable and details[0][1] == "en"
|
fa2ec533b5e79f07a57ae208858c6be52ec9555b | ramonarr/Python-staff-signals | /rectangular_signal_generator_with_editable_frequency.py | 475 | 4 | 4 | # Generating a rectangular periodic signal with editable frequency in python
t = arange(0,2,0.001)
f = 5 # Frequency [Hz]
x = 0 # The initial value of x
k = 1 # Multiplication factor
N = 1001 # Harmonics number
while k <= N:
x = x + (4/pi)*(1/k)*sin(2*k*f*pi*t)
k = k+2
figure(figsize=(9,6))
plot(t,x)
title(r'Rectangular signal with editable frequency in Python: $x(t)$ ')
xlabel(r't')
ylabel(r'$x(t)$')
grid()
|
7cfc9d63fd7304af6abe9cd6a1bbc1bb78f009eb | kjh03160/data_structure | /lecture/Linked_List/Dlist.py | 2,449 | 3.828125 | 4 | class Node:
def __init__(self, key = None):
self.key = key
self.next = self
self.prev = self
def __str__(self):
return str(self.key)
class DList:
def __init__(self):
self.head = Node() # 더미 노드
self.size = 0
def splice(self, a, b, x):
a.prev.next = b.next
b.next.prev = a.prev
x.next.prev = b
b.next = x.next
x.next = a
a.prev = x
def moveafter(self, a, x):
self.splice(a, a, x)
def movebefore(self, a, x):
self.splice(a, a, x.prev)
def insertafter(self, x, key):
new = Node(key)
self.moveafter(new, x)
def insertbefore(self, x, key):
new = Node(key)
self.movebefore(new, x)
def pushfront(self, key):
self.insertafter(self.head, key)
self.size += 1
def pushback(self, key):
self.insertbefore(self.head, key)
self.size += 1
def remove(self, node):
if node == None or node == self.head:
return "Error"
node.prev.next = node.next
node.next.prev = node.prev
self.size -= 1
return node
# def pushback(self, key):
# new = Node(key)
# if self.size == 0:
# self.head.next = new
# new.prev = self.head
#
# else:
# self.tail.next = new
# new.prev = self.tail
#
# self.tail = new
# new.next = self.head
# self.head.prev = new
#
# self.size += 1
#
# def remove(self, key):
# refer = self.head
# while refer.next != None:
# if refer.key == key:
# return_key = refer.key
# refer.prev.next = refer.next
# refer.next.prev = refer.prev
# del refer
# self.size -= 1
# return return_key
# else:
# refer = refer.next
def print_list(self):
if self.size == 0:
print("비어있음")
else:
tail = self.head
while tail.next != self.head:
print(tail.key,"> ",end="")
tail = tail.next
print(tail.key)
# d = DList()
# d.pushback(1)
# d.pushback(2)
# d.pushback(3)
# d.remove(2)
# d.print_list()
|
0b8fa2bf419f6fbc895571873d387de9e396a765 | book155/pythonCorePractice | /chapter 11/11-4.py | 164 | 3.609375 | 4 |
def convert2(minute):
hour = minute // 60
minute = minute - 60* hour
return hour,minute
hour,minute = convert2(790)
print(hour)
print(minute) |
7f8719d38410ff2fe23b15180442e08781a696a6 | radeknavare/99Problems | /6_Find out whether a list is a palindrome.py | 231 | 4.15625 | 4 | newList = [1, 2, 3, 2, 1]
newTuple = (1, 2, 3, 2, 1)
if newTuple == newTuple[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
if newList == newList[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
|
8f1bdc466ca68c4076ec2927b6449e8e5c0ba8ce | gabriellaec/desoft-analise-exercicios | /backup/user_116/ch22_2020_03_04_12_59_24_369445.py | 158 | 3.5625 | 4 | def ft(t,n):
z=(n*(0.00694444))*(t*360)
return z
t=int(input('tempo em anos'))
n=int(input('cigarros por dia'))
print(int(ft(t,n)),('anos perdidos'))
|
ebf10197aa3f9f6e8b65f1352c388dc7a1a4ffa8 | Elaine-FullStackDeveloper/Bootcamp-Banco-Carrefour-Data-Engineer | /Soluções Aritmeticas em Python/Triangulo.py | 754 | 3.75 | 4 | '''
Leia 3 valores reais (A, B e C) e verifique se eles formam ou não um triângulo. Em caso positivo, calcule o perímetro do triângulo e apresente a mensagem:
Perimetro = XX.X
Em caso negativo, calcule a área do trapézio que tem A e B como base e C como altura, mostrando a mensagem
Area = XX.X
Entrada
A entrada contém três valores reais.
Saída
O resultado deve ser apresentado com uma casa decimal.
Exemplo de Entrada Exemplo de Saída
6.0 4.0 2.0 Area = 10.0
6.0 4.0 2.1 Perimetro = 12.1
'''
a = [float(x) for x in input().split()]
#complete o desafio
if a[0]<a[1]+a[2] and a[1]<a[0]+a[2] and a[2]<a[0]+a[1]:
print(f"Perimetro = {sum(a):.1f}")
else:
print(f"Area = {((a[2]) *(a[0]+a[1]) ) / 2:.1f}")
|
edf1b9bff1ac2cd4631cd14ce70429dfc3184057 | Ford-z/LeetCode | /714 买卖股票的最佳时机含手续费.py | 1,410 | 3.578125 | 4 | #给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。
#你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。
#返回获得利润的最大值。
#注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。
#来源:力扣(LeetCode)
#链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee
#著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
n=len(prices)
if n<2:
return 0
dp1=[0]*n#第i天手上有股票时的最大收益
dp2=[0]*n#第i天手上没有股票时的最大收益
dp1[0] = -prices[0]#买入价
for i in range(1,n):
dp1[i]=max(dp1[i-1], dp2[i-1] - prices[i])#若持有,看看前面有没有手握股票,若没有,则买入;若有,保持原买入价
dp2[i]=max(dp1[i-1]+prices[i]-fee,dp2[i-1])#若不持有,看看前面有没有手握股票,若没有,则保持收益;若有,获得卖出价
return max(dp1[-1],dp2[-1])
|
ba4554327eabf1eb61640b35d42125429215fa73 | alexpt2000/4Year_PythonFundamentals | /6_Largest and smallest in list.py | 317 | 4.15625 | 4 | def MaxMin(list):
minValue = min(list)
maxValue = max(list)
return minValue, maxValue
list = []
num = int(input('How many numbers int the list: '))
for n in range(num):
numbers = int(input('Enter number '))
list.append(numbers)
print("Min and Max element in the list is :", MaxMin(list))
|
9700dfd9bbb16b807573dfd20b805b1e37018464 | hooong/baekjoon | /Python/14425_1.py | 910 | 3.5 | 4 | # 14425번 문자열 집합 (트라이)
from sys import stdin
class Node:
def __init__(self, key):
self.key = key
self.child = {}
class Trie:
def __init__(self):
self.head = Node(None)
def insert(self, word):
cur = self.head
for ch in word:
if ch not in cur.child:
cur.child[ch] = Node(ch)
cur = cur.child[ch]
cur.child['*'] = True
def search(self, word):
cur = self.head
for ch in word:
if ch not in cur.child:
return False
cur = cur.child[ch]
if '*' in cur.child:
return True
n, m = map(int, stdin.readline().split())
trie = Trie()
cnt = 0
for _ in range(n):
s = stdin.readline()
trie.insert(s)
for _ in range(m):
candidate = stdin.readline()
if trie.search(candidate):
cnt += 1
print(cnt)
|
d4fdff5baa1355d1bf20f9d07a1b86c7a3599adb | addn2x/python3 | /ex04/ex04function04.py | 362 | 3.8125 | 4 | # Fuctions
# factoriel exmple
# 5! = 5 * 4 * 3 * 2 * 1
# sum of factoriel example
# sum = 5! + 4! + 3! + 2! + 1!
def my_fakt(n):
fakt = 1
for i in range(1, n + 1):
fakt *= i
return fakt
def fact_sum(n):
my_sum = 0
for i in range(1, n + 1):
my_sum += my_fakt(i)
return my_sum
print(my_fakt(5))
print(fact_sum(5)) |
7b1e913f7fc5e6423a57f2dd3bf3db25f6a3f798 | wawj901124/uiautomator2project | /util/compic.py | 879 | 3.71875 | 4 | from PIL import Image
#使用第三方库:Pillow
import math
import operator
from functools import reduce
image1=Image.open('D:\\Users\\Administrator\\PycharmProjects\\uiautomator2project\\screenshots\\S81102-151706.jpg')
image3=Image.open('D:\\Users\\Administrator\\PycharmProjects\\uiautomator2project\\screenshots\\S81102-151717.jpg')
#把图像对象转换为直方图数据,存在list h1、h2 中
h1=image1.histogram()
h2=image3.histogram()
result = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2, h1, h2)))/len(h1) )
'''
sqrt:计算平方根,reduce函数:前一次调用的结果和sequence的下一个元素传递给operator.add
operator.add(x,y)对应表达式:x+y
这个函数是方差的数学公式:S^2= ∑(X-Y) ^2 / (n-1)
'''
print(result)
#result的值越大,说明两者的差别越大;如果result=0,则说明两张图一模一样 |
a6f41c526ffcf94c556b3756be4465c8f7488688 | abhimaprasad/Python | /Python/Operators/ArthemeticOpeators.py | 197 | 4.21875 | 4 | #Arthemetic Operators(+,-,*,/,%,//)
a=int(input("enter a number"))
b=int(input("enter a number"))
c=a+b;
print(c)
c=a-b;
print(c)
c=a/b;
print(c)
c=a*b;
print(c)
c=a//b;
print(c)
c=a%b;
print(c)
|
df4a3db224f90099b3b68d9ff68371f4985fab6c | lr-carmichael/write-docker-actions | /.github/actions/cat-facts/src/main.py | 655 | 3.5625 | 4 | import requests
import random
import sys
# Make an HTTP GET request to the cat-fact API
cat_url = "https://cat-fact.herokuapp.com/facts"
r = requests.get(cat_url)
r_obj_list = r.json()["all"]
# Create an empty array, populate it with cats
fact_list = []
for fact in r_obj_list:
fact_list.append(fact["text"])
# create function to get a random fact
def select_random_fact(fact_arr):
return fact_arr[random.randint(0, len(fact_list) + 1)]
random_fact = select_random_fact(fact_list)
# Print the random cat fact
print(random_fact)
# Set the fact-output of the action as the value of random_fact
print(f"::set-output name=fact::{random_fact}")
|
8f3420c99ae3bda89cf090baab00bf22f53b66c1 | shesha4572/11 | /3_1.py | 253 | 3.703125 | 4 | def series1() :
for i in range (1 , 86 , 2):
print(i , end = " ,")
print()
def series2():
sum = 0
for a in range(1, 21 , 3):
sum += a
print("The sum of the series is 1 + 4 + 7+ ...20 is " ,sum)
series1()
series2() |
9abcd8ca83c4b662859c70b09b468b69d0cd1665 | adithyaGR/Ginormoust-oo-r-in | /T-u-ring.py | 11,796 | 4.34375 | 4 | from collections import defaultdict
....
# TuringMachine class represents our Turing machine;;;;;;;
class TuringMachine:
# Action class represents the action that can be taken in any step of
# the execution of Turing machine
class Action:
# Action consists of:
#
# - self.turing_machine is a reference to the Turing machine this action
# takes place on. Action can change the state of the machine,
# so it needs to be aware of the machine.
#
# - self.write is a character with which the character at the position
# to which head points to should be replaced (character to write as a
# result of this action)
#
# - self.direction is an integer (1, 0 or -1) that indicates
# the direction in which we should move the head after replacing
# the character that the head points to
#
# - self.new_state is an integer indicating the number of the state
# to which machine should transition to as a result of this action
def __init__(self, turing_machine, write, direction, new_state):
self.turing_machine = turing_machine
self.write = write
self.direction = direction
//self.new_state = new_state
# This method implements the procedure that takes place when the action
# is taken. As the definition of Turing machine describes, action
# consists of 3 steps:
# - Replace the character that the head points to
# - Move the head in the appropriate direction (or don't move it at all)
# - Change the current state of the Turing machine to a new appropriate
# state
def take_action(self):
# Replacing the character with self.write character
# *** HAPPENS ONLY IF self.write ISN'T * (* means DON'T WRITE) ***
if self.write != "*":
self.turing_machine.tape_contents[self.turing_machine.head] = self.write
# Moving the head - self.direction 1 will move it right, -1 left and
# 0 will keep it at the same position
self.turing_machine.head += self.direction
# Moving the head can result in head becoming -1 (if head was
# pointing to the first character of tape contents list
# (head was 0) and was moved to the left.
# If this is the case, we want to expand the content of the tape
# that we are keeping track of. Since the tape is infinite
# and blank symbols (-) are written all over the place we're not
# keeping track of yet, once we start to keep track of this spot,
# initially it's going to be filled with -. So our new content
# consists of -<old_content>, which means we just have to append -
# to the beginning of our tape_content list, and now we consider
# head 0 again (since it points to the first element of our
# content list
if self.turing_machine.head < 0:
self.turing_machine.tape_contents = ["-"] + self.turing_machine.tape_contents
self.turing_machine.head = 0
# Moving the head right can result in head pointing to the position
# that is to the right of the last character we are keeping track of
# We need to include this character in the tape content we are
# keeping track of as well, so we need to append it to our
# tape_contents list. Since we haven't kept track of it previously,
# it's filled with blank symbol ("-") so this is what we append
elif self.turing_machine.head >= len(self.turing_machine.tape_contents):
self.turing_machine.tape_contents.append("-")
# Lastly, we change the state of the Turing machine to the new
# state specified by this action
self.turing_machine.state = self.new_state
# Constructor of TuringMachine class.
# What we need to keep track of in a machine:
# - self.head - the position to which the head points to
# - self.state - the current state of the machine
# - self.halt_state - the halt state - state of the machine which indicates
# that the execution of the machine should stop (end state)
# - tape_contents - a list of characters representing the part of (infinite)
# machine tape that we keep track of. The rest of the tape (that we aren't
# keeping track of) consists of blank symbols (-)
# - self.action_table - The action table of this state machine.
# It is a dictionary (hash table) with possible machine states as keys
# and for every state we keep another dictionary (so this is dictionary
# of dictionaries). The second dictionary keeps track of actions that
# should be taken for each possible read character, so it has read
# characters as keys and corresponding actions as values
#
# defaultdict is used because it automatically adds a (key, value)
# pair when we access the key for the first time, so we don't have to
# care about creating an empty dictionary before adding the first element
# for each machine state. Otherwise, usage of defaultdict is the same
# as of dict.
def __init__(self):
self.head = 0
self.state = 0
self.halt_state = 0
self.tape_contents = []
self.action_table = defaultdict(dict)
# This method parses the machine definition from the file with name filename
# Returns a success flag:
# - True if the whole parsing was successful
# - False if there's been an error in any step of parsing (meaning file
# isn't correctly formatted)
def read_machine(self, filename):
# We read the whole file content into a list of lines
with open(filename, "r") as f:
lines = f.read().splitlines()
# Correct input file has at least first 4 lines:
# <Starting contents of tape>
# <Starting offset of machine head>
# <Start state index (integer)>
# <Halting state index (integer)>
# If this isn't a case, stop parsing and return error flag
if len(lines) < 4:
return False
try:
# First line is <Starting contents of tape>
self.tape_contents = list(lines[0])
# Second line is <Starting offset of machine head>
self.head = int(lines[1])
# Third line is <Start state index (integer)>
self.state = int(lines[2])
# Fourth line is <Halting state index (integer)>
self.halt_state = int(lines[3])
# All the other lines, beginning from fifth line (index 4)
# are <Action table>
for i in range(4, len(lines)):
# Each Action line is in this form:
# <State index> <Read> <Write> <Direction> <New state index>
# Let's make a list (called line) with these 5 values
# (we have to split our line using the space as a delimiter)
# So now,
# <State index> is in line[0]
# <Read> is in line[1]
# <Write> is in line[2]
# <Direction> is in line[3]
# <New state index> is in line[4]
# but they are all strings, so when we need integers
# (like for Direction or State index), we need to convert them
# to int with e.g. int(line[3]). If there's an error in file,
# and these strings cannot be converted to int, conversion
# methods throw ValueError exceptions (thus this is all done
# in try block)
line = lines[i].split(' ')
# If we didn't get all of our 5 needed values, return error flag
if len(line) < 5:
return False
# If we didn't get a SINGLE character for <Read> OR
# if we didn't get a SINGLE character for <Write> OR
# if we got a direction that's not -1, 0 or 1
# it's an error, so just stop parsing and return error flag
if len(line[1]) > 1 or len(line[2]) > 1 or abs(int(line[3])) > 1:
return False
# If all is right, add an entry to our action table
# In our action_table, using the key <State> (line[0])
# to access the dictionary of Actions, and using the key
# <Read> for that dictionary, add a new Action given <Write>
# character, <Direction> integer and <New state index> integer
self.action_table[int(line[0])][line[1]] =\
TuringMachine.Action(self, line[2], int(line[3]), int(line[4]))
except ValueError:
# If there was any conversion error, return error flag
return False
else:
# If everything was OK, return True
return True
# This method executes the Turing machine after the starting
# state, halt state, starting tape contents, starting head position have
# been set and action table filled with appropriate actions
#
# This method returns a list of strings, where each string
# represents characters on tape that we are currently keeping track of
# (which are in self.tape_contents list), so it returns a list
# of tape contents in each step of execution until the halt state is reached
# If an error is detected during execution, the method returns None instead
def execute(self):
# Add the starting tape contents to the resulting list of tape contents
all_tape_contents = ["".join(self.tape_contents)]
# Execute the machine - while the state doesn't become halt state
while self.state != self.halt_state:
# If the current state is not in our action table (we reached
# an "impossible state" for some reason, stop the execution and
# return None
if self.state not in self.action_table:
return None
# If the exact character that our head points to is in our action
# table for the current state, keep it in a read variable
if self.tape_contents[self.head] in self.action_table[self.state]:
read = self.tape_contents[self.head]
# If there isn't the exact read character, maybe there's a wild-card
# character (*). If so, keep it in read for later
elif "*" in self.action_table[self.state]:
read = "*"
# If there isn't an action for the character we read from head
# position, we don't know what to do at this point, so just
# stop the execution and return None
else:
return None
# If everything was OK, variable read keeps track of the place
# in dictionary where we should look for our action
# Access the action and take it!
self.action_table[self.state][read].take_action()
# Finally, since the action put us in a new state and (most likely)
# changed the tape content, we have to save it in our list
# of contents in all steps.
# Since we're keeping track of tape contents in a list of characters
# we want to convert it to string first. join method does that, and
# "".join(...) tells join not to add any character in between (thus
# empty string "")
all_tape_contents.append("".join(self.tape_contents))
return all_tape_contents
|
efc3526eea9c4d455944f47b4012b180027fa724 | nestorast/Pythonbasic | /change_DMS.py | 1,682 | 3.609375 | 4 | import math
def calcular (latitud, longitud):
if latitud[0] == "N" :
gradolat = int(latitud[1])
minutolat = int(latitud[2:4])
segundolats = float(latitud[4:9])
latitud_decimal = gradolat + minutolat/60 + segundolats/3600
#print ("la latitud ingresada es " + str(gradolat) + " " + str(minutolat) + " " + str(segundolats))
print("el valor decimal es: " + str(round (latitud_decimal, 4)))
else :
gradolat = int(latitud[1])
minutolat = int(latitud[2:4])
segundolats = float(latitud[4:9])
latitud_decimal = gradolat + minutolat/60 + segundolats/3600
#print ("la latitud ingresada es " + str(gradolat) + " " + str(minutolat) + " " + str(segundolats))
print("el valor decimal de la latitud es: " + str(round (latitud_decimal, 4)))
if longitud[0] == "W" :
gradolon = int(longitud[1:3])
minutolon = int(longitud[3:5])
segundolon = float(longitud[5:10])
longitud_decimal = 0-(gradolon + minutolon/60 + segundolon/3600)
#print ("la latitud ingresada es " + str(gradolat) + " " + str(minutolat) + " " + str(segundolats))
print("el valor decimal de la longitud es: " + str(round (longitud_decimal, 4)))
def conver ():
print ("CONVERTIR DE DMS a DECIMAL")
print ("ejemplo para ingresar datos N51025.35 o S51025.35 lo mismo para la longitud W o E")
latitud = input("ingrese la latitud grados minutos segundos: ")
longitud = input("ingrese la longitud grados minutos segundos: ")
calcular (latitud, longitud)
if __name__== "__main__":
conver ()
|
8bd76da7a1b82235fd88b07d2f05af47ccd2bc23 | siddhartharao17/hackerrank | /src/varargs-demo.py | 1,009 | 5.03125 | 5 | # This program demonstrates the use of *args which is called variable non-keyworded arguments.
# This is used when you suspect that a function might accept multiple arguments rather than
# restricting it to just n number of args at compile time.
# Example of fixed args at compile time
# def multiply(x,y):
# print(x*y)
#
# multiply(5,4)
# multiply(3,5,4) # This will give an error saying "TypeError: multiply() takes 2 positional arguments but 3 were given"
# We want this function to accept multiple arguments at runtime and tell the compiler that we do not know in the beginning
# about the number of arguments we want to give.
# Example of variable args at runtime
def multiply(*args):
# now we don't have x and y to simply multiply them so we need to iterate through
# the list of args that are comma separated.
product=1
for number in args:
product=product*number
print(product)
multiply(5,4)
multiply(5,4,4,6)
multiply(5,4,3)
multiply(5,4,5,2,8,9)
multiply(5,4,6,12) |
c857f6a082a00d7392e68c03c5cbb221406a0041 | LeiscarT/LearningPython | /120 exercises/exercise_#7.py | 155 | 3.75 | 4 | nombreArchivo = input("ingrese el nombre del archivo: ")
extension = nombreArchivo.split('.')
print("La extension del archivo es: " + repr(extension[-1]))
|
060c0bdca4eb5e2bff9d38e9a176e0be5bfe96a9 | stt106/pythonfundamentals | /introduction/scalar-types.py | 1,538 | 4.3125 | 4 | # integer by default by specified by decimals but other forms are also available
print('decimal form: ' + str(10)) # with base 10
print('binary form: ' + str(0b10)) # with base 2
print('Octal form: ' + str(0o10)) # with base 8
print('hex form: ' + str(0x10)) # with base 16
# convert to int using int ctor
print(int(3.4))
print(int(-3.9))
print(int("4924")) # default base is 10
print(int("1000", 2)) # passing 2 as the base
# convert to float
print(3 + 4.0) # int and float result float
print(float("3.45"))
print(2.34e4)
print("inf") # +infinity
print('-inf') # -infinity
print('nan') # nan is a float number
# special type None which has sole value None often representing abstance of value and it's not evlauted by the REPL
a = None
print(a is None) # test equality
# boolean type: 0 (0.0), empty string, None and empty collection are falsy
print(bool(0))
print(bool(0.0))
print(bool(""))
print(bool([])) # the same applies for all other collections e.g. tuple, set, dict
print(bool(None)) # flase
# all other numbers and non-empty string and collections are truey, including the string 'False'
print(bool('False'))
print(bool(1.2))
print(bool(-3))
print(bool([1,2,3]))
# there is a shortcut to convert other types to boolean in conditional statement
if "eggs": # bool ctor is rarely used in python
print("sounds nice!")
# Flat is better than nested so use elif when possible to avoid nesting if under else block
# break terminates the innermost loop
|
fbf742598c61dc8bb54b490b07e276b88354df6d | Melmanco/INFO229 | /Tutorial_4_PyTest_TDD/romanos/roman_numerals.py | 1,286 | 3.609375 | 4 | def convert(num, num_type):
if num_type == 'num':
return {
1000: 'M',
900: "CM",
500: 'D',
400: "CD",
100: 'C',
90: "XC",
50: 'L',
40: "XL",
10: 'X',
9: "IX",
5: 'V',
4: 'IV',
1: 'I'
}[num]
elif num_type == 'rom':
return {
'M': 1000,
'CM': 900,
'D': 500,
'CD': 400,
'C': 100,
'XC': 90,
'L': 50,
'XL': 40,
'X': 10,
'IX': 9,
'V': 5,
'IV': 4,
'I': 1
}[num]
def numberToRoman(num):
stack = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
result = ''
while num > 0:
if num < stack[0]:
stack = stack[1:]
else:
result += convert(stack[0], 'num')
num -= stack[0]
return result
def romanToNumber(rom):
stack = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
result = 0
while rom > '':
if not rom.startswith(stack[0]):
stack = stack[1:]
else:
result += convert(stack[0], 'rom')
rom = rom[len(stack[0]):]
return result
|
424667bcb333b38134f471a6c35034667b428e6a | ReginaGates/ControlFlowChalleng_CompletePythonMasterclass | /programFlowChallenge_simplified.py | 904 | 3.890625 | 4 | #Complete Python Masterclass - Tim Buchalka & Jean-Paul Roberts
#Challeng - Program Flow
#Simplified
name = input("What is your name? ")
user_IP_address = input("Hello, {}, what is your IP address? ".format(name))
seg_count = 0
new_string = ''
# if user_IP_address[-1] == '.':
# for char in user_IP_address:
# if char not in '0123456789':
# seg_count += 1
#
if user_IP_address[-1] != '.':
# for char in user_IP_address:
# if char not in '0123456789':
# seg_count += 1
# seg_count += 1
user_IP_address += '.'
#
# print("This IP address has {} segments.".format(seg_count))
#
# seg_count = 0
for char in user_IP_address:
if char in '0123456789':
new_string += char
elif char == '.':
seg_count += 1
print("Segment {0} has {1} digits.".format(seg_count, len(new_string)))
new_string = ''
|
094bc27362e171f83b2360627cf135b201bbc731 | hfuong/nbatwitter | /src/playerlist.py | 1,514 | 3.5 | 4 | # Import relevant modules
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import csv
# Get web page with dynamic content that requires scrolling to load
driver = webdriver.Chrome(executable_path = "C:/Users/holly/PycharmProjects/chromedriver.exe")
driver.get("https://nba.com/players/")
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll bottom of page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Pause scrolling to allow page to load
time.sleep(1)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
html = driver.page_source
# Close browser window at end of session
driver.quit()
# Make BeautifulSoup object
page = BeautifulSoup(html, features = "lxml")
# Identify the specific sections with player names
playerParagraph = page.find_all('p', class_='nba-player-index__name')
# Compile list of only current player names
players = []
for p in playerParagraph:
players.append(p.get_text(strip = True, separator = ' '))
# Print only the text within the paragraph tags into a CSV
with open('data/currentplayers.csv', 'w', encoding = 'utf-8', newline = '') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['player'])
for player in players:
writer.writerow([player])
|
b163a0de3be4fb97add28b8902927cf6b073cfda | goutham-2411/PythonCalculator | /PythonCalculator.py | 6,220 | 4.34375 | 4 | # Programmer - python_scripts (Abhijith Warrier)
# PYTHON SCRIPT TO CREATE A SIMPLE GUI CALCULATOR & PERFORM THE CALCULATION eval() METHOD IN PYTHON
#
# The eval() allows to run Python code within itself. The eval() method parses the expression passed to it and runs
# python expression(code) within the program.
#
# The syntax of eval is - eval(expression, globals=None, locals=None)
# expression - This string is parsed and evaluated as a Python expression.
# globals (optional) - Dictionary to specify the available global methods & variables.
# locals (optional) - Dictionary to specify the available local methods & variables.
# Importing necessary packages
import tkinter as tk
from tkinter import *
# Defining CreateWidgets() function to create necessary tkinter widgets
def CreateWidgets():
CalcDisplay = Entry(root, bd=10, justify="right", font=("Comic Sans MS", 20, "bold"), textvariable=d_value, bg="sienna3")
CalcDisplay.grid(row=0, column=0, columnspan=5)
B_AllClear = Button(root, text="AC", bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=allclearEntry)
B_AllClear.grid(row=1, column=0, padx=5, pady=5)
B_Clear = Button(root, text="C", bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=clearEntry)
B_Clear.grid(row=1, column=1, padx=5, pady=5)
B_2 = Button(root, text='%', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('%'))
B_2.grid(row=1, column=2, padx=5, pady=5)
B_D = Button(root, text='/', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('/'))
B_D.grid(row=1, column=3, padx=5, pady=5)
B_7 = Button(root, text='7', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(7))
B_7.grid(row=2, column=0, padx=5, pady=5)
B_8 = Button(root, text='8', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(8))
B_8.grid(row=2, column=1, padx=5, pady=5)
B_9 = Button(root, text='9', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(9))
B_9.grid(row=2, column=2, padx=5, pady=5)
B_M = Button(root, text='*', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('*'))
B_M.grid(row=2, column=3, padx=5, pady=5)
B_4 = Button(root, text='4', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(4))
B_4.grid(row=3, column=0, padx=5, pady=5)
B_5 = Button(root, text='5', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(5))
B_5.grid(row=3, column=1, padx=5, pady=5)
B_6 = Button(root, text='6', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(6))
B_6.grid(row=3, column=2, padx=5, pady=5)
B_D = Button(root, text='-', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('-'))
B_D.grid(row=3, column=3, padx=5, pady=5)
B_1 = Button(root, text='1', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(1))
B_1.grid(row=4, column=0, padx=5, pady=5)
B_2 = Button(root, text='2', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(2))
B_2.grid(row=4, column=1, padx=5, pady=5)
B_3 = Button(root, text='3', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick(3))
B_3.grid(row=4, column=2, padx=5, pady=5)
B_A = Button(root, text='+', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('+'))
B_A.grid(row=4, column=3, padx=5, pady=5)
B_0 = Button(root, text='0', bd=5, font=("Comic Sans MS", 20, "bold"), width=10, height=2, command=lambda : buttonClick(0))
B_0.grid(row=5, column=0, padx=5, pady=10, columnspan=2)
B_DP = Button(root, text='.', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=lambda : buttonClick('.'))
B_DP.grid(row=5, column=2, padx=5, pady=10)
B_E = Button(root, text='=', bd=5, font=("Comic Sans MS", 20, "bold"), width=4, height=2, command=calculateResult)
B_E.grid(row=5, column=3, padx=5, pady=10)
# Defining the buttonClick() function with c_input to fetch user pressed button's value
def buttonClick(c_input):
# Declaring the c_expression variable as global
global c_expression
# Concatenating and storing the c_expression value with the user pressed button's value
c_expression = c_expression + str(c_input)
# Setting the Entry Widget value to that of the c_operatot value
d_value.set(c_expression)
# Defining the Browse() to save the file
def calculateResult():
global c_expression
# Calling the eval() with c_expression as input which has expression to be evaluated
# eval() parses the expression passed to it and run python expression within it
result = str(eval(c_expression))
# Setting the Entry Widget value to that of the result variable's value
d_value.set(result)
# Defining the allclearEntry() to clear the inputs in the Entry Widget
def allclearEntry():
global c_expression
# Setting the c_expression variable to empty string and diplaying it in the Widget
c_expression = ""
d_value.set(c_expression)
# Defining the clearEntry() to clear one input entry from the Entry Widget
def clearEntry():
# Declaring the c_expression & d_value variable as global
global c_expression, d_value
# Removing the last character from the Entry Widget Input
cleared_value = d_value.get()[:-1]
# Setting the c_expression variable to the d_value variable's value
c_expression = cleared_value
d_value.set(c_expression)
# Creating object root of tk
root = tk.Tk()
# Setting the title, window size, background color and disabling the resizing property
root.title('PyCalculator')
root.resizable(False, False)
root.configure(background='sienna4')
# Creating tkinter variable
d_value = StringVar()
c_expression = ""
CreateWidgets()
# Defining infinite loop to run application
root.mainloop()
|
bd11ecfe3c3aa89f7c86675e3b94fbec63f9b52a | frclasso/Aprendendo_computacao_com_Python | /Chap19-Filas/fila.py | 3,571 | 4.09375 | 4 | #!/usr/bin/env python3
class Node:
def __init__(self, carga=None, proximo=None):
self.carga=carga
self.proximo=proximo
def __str__(self):
return str(self.carga)
def imprimeLista(no):
while no:
print(no, end=" ")
no = no.proximo
print()
def imprimeDeTrasPraFrente(lista):
if lista == None: return
cabeca = lista
rabo = lista.proximo
Node.imprimeDeTrasPraFrente(rabo)
print(cabeca, end=" ")
def removeSegundo(lista):
if lista == None: return
primeiro = lista
segundo = lista.proximo #faz primeiro 'no' se referir ao terceiro
primeiro.proximo = segundo.proximo
segundo.proximo = None #separa o segundo 'no' do resto da lista
return segundo
class Queue:
def __init__(self):
self.length = 0
self.head = None
def isEmpty(self):
return (self.length == 0)
def insert(self, cargo):
node = Node(cargo)
node.next = None
if self.head == None: # if list is empty the new node goes first
self.head = node
else:
# find the last node in the list
last = self.head
while last.next: last = last.next
# append new node
last.next = node
self.length = self.length + 1
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length -1
return cargo
class ImprovedQueue:
def __init__(self):
self.length = 0
self.head = None
self.last = None
def isEmpty(self):
return self.length == 0
def insert(self, cargo):
node = Node(cargo)
node.next = None
if self.length == 0:
#if list is empty, the new node is head and last
self.head = self.last = node
else:
#find the last node
last = self.last
#append new node
last.next = node
self.last = node
self.length = self.length + 1
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length -1
if self.length == 0:
self.last = None
return cargo
class PriorityQueue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def insert(self, item):
self.items.append(item)
def remove(self):
maxi = 0
for i in range(1, len(self.items)):
if self.items[i] > self.items[maxi]:
maxi = i
item = self.items[maxi]
self.items[maxi:maxi + 1] = []
return item
class Golfer:
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return ("%-16s: %d" % (self.name, self.score))
def __cmp__(self, other):
if self.score < other.score: return 1 # less is more
if self.score > other.score: return -1
return 0
# q = PriorityQueue()
# q.insert(11)
# q.insert(12)
# q.insert(14)
# q.insert(13)
# while not q.isEmpty():print(q.remove())
tiger = Golfer("Tiger Woods", 61)
phil = Golfer("Phil Mickelson", 72)
hal = Golfer("Hall Sutton",69)
pq = PriorityQueue()
pq.insert(tiger)
pq.insert(phil)
pq.insert(hal)
while not pq.isEmpty():print(pq.remove())
'''line 106, in remove
if self.items[i] >= self.items[maxi]:
TypeError: '>=' not supported between instances of 'Golfer' and 'Golfer''' |
75e448ccf87c5caedb6bf9962daf59d02583cb55 | qinyj12/fluent-python-note | /1.2.py | 940 | 4.15625 | 4 | from math import hypot
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
# 用print调用
def __repr__(self):
# %r是把参数原样打印出来,这里用%s其实也是可以的
return 'Vector(%r, %r)' % (self.x, self.y)
# 用abs()调用
def __abs__(self):
return hypot(self.x, self.y)
# 用 Vector(x, y) + Vector(x, y) 调用,就是普通的加号
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
# 用for ... in ...调用
# 似乎一定要返回一个iter()对象,而根据文档,iter()只能返回iterator即迭代器,而迭代器自身又要有__iter__()方法,晕了。
# 反正这里如果直接返回一个list是会报错的,返回迭代器就没问题
def __iter__(self):
return iter([self.x, self.y])
for i in Vector(3, 4):
print(i) |
6a14e89e93fa2c049b389b5b84c3fc054b8fe939 | fengtao1994/ceshi | /3-1~3-10/for_while.py | 656 | 3.875 | 4 | #Python提供了for循环和while循环(没有do..while循环)
#for 循环 遍历打印全部数组
student=['ja','bob','ma','mic']
for stu in student: #赋值到 stu
print(stu) #平行打印全部
#计算1+2+3+...10的值
#Python 提供一个range()函数,可以生成一个整数序列,比如range(10)生成的序列是从0开始小于10的整数
sum=0
for i in range(11):
sum=sum+i
print(sum) #不平行打印最后,注意逻辑关系
#while循环:只要条件满足,就一直循环下去,条件不满足时退出循环
n=10
while n>0:
n=n-1
print(n)
print('over !')
|
5a92abc4592b3623554bf62e1f353aa6c99fa65a | himanshupatel96/GeneticAlgorithm | /mathsGA.py | 4,561 | 3.640625 | 4 | """ Use GA to find the optimal solution for a + 4b + 2c + 3d = 40 """
import random
from itertools import chain
import sys
mrate = 0.12
crate = 0.70
population = []
"""Generating Initial Population Randomly """
if len(sys.argv) == 2:
pop_size = int(sys.argv[1])
for i in range(1, pop_size):
x = []
for j in range(1, 5):
x.append(random.randint(0, 40))
population.append(x)
"""
#print("initial Population")
#print(population)
#print()
"""
""" Fitness Function """
def fitness(chromosome):
return abs((1*chromosome[0] + 4*chromosome[1] + 2*chromosome[2] + 3*chromosome[3]) - 40)
"""Crossover Operator """
def crossover(parent1, parent2):
global population
point = random.randint(0, len(parent1)-1)
t1 = [parent1[:point], parent2[point:]]
t2 = [parent1[point:], parent2[:point]]
population.append(list(chain.from_iterable(t1)))
population.append(list(chain.from_iterable(t2)))
""" Mutation Operator """
def mutation():
global population
total_gene = len(population) * 4
n = total_gene * mrate
""" How much mutation should be applied """
n = int(n)
while ( n ):
rindex = random.randint(0, len(population) - 1)
rval = random.randint(0, 40)
population[int(rindex/4)][rindex%4] = rval
n = n - 1
""" Tournament Selection """
def tournamentSelection(p):
global population
k = len(population) * 0.90
""" 70 % individuals are selected randomly """
k = int(k)
temp = [0] * k
for i in range(0, k):
""" Select k individual candidates to choose from """
r = random.randint(0, len(population) - 1)
temp[i] = r
best = None
for i in range(0, k):
if best == None or fitness(population[temp[i]]) > fitness(population[best]) :
best = temp[i]
second = None
for i in range(0, k):
A = fitness(population[temp[i]])
if second != None :
B = fitness(population[second])
if second == None or (A * (1 - A)) > (B * (1 - B)) :
second = temp[i]
return [best, second]
""" Elitism --- Removing worst 20 % candidate solutions at each generation """
def removeWorstPerformers():
global population
f = []
for i in range(0, len(population)):
"""Calculate the fitness of each individual """
f.append((fitness(population[i]), i))
f.sort()
#print(f)
d = len(population) * 0.2
d = int(d)
delete = f[len(population) - d:]
for i in range(0, len(delete)):
if delete[i][1] >= len(population):
continue
population.pop(delete[i][1])
""" Driver Function Which will do everything in this program """
def calculateFitnessAndOperations():
global population
iteration = 1000
flag = False
cnt = 1
while ( iteration ):
#print()
#print("Iteration",cnt)
#print()
cnt += 1
f = []
for i in range(0, len(population)):
x = fitness(population[i])
if ( x == 0 ):
#print("--------------------------------------------------------------------------------")
#print("Solution ")
#print(population[i])
#print("-------------------------------------------------------------------------------")
flag = True
break
f.append(x)
if flag == True :
break
total = 0
for i in range(0 , len(f)):
f[i] = (1 / (1 + f[i]))
total = total + f[i]
#print()
#print("Error" , total)
#print()
p = []
for i in range(0, len(f)):
p.append(f[i] / total)
pair = tournamentSelection(p)
crossover(population[pair[0]], population[pair[1]])
mutation()
if len(population) > 5 :
removeWorstPerformers()
#print("After Applying Mutation and Crossover Operations")
#print()
#print(len(population))
#print()
"""for i in range(0, len(population)):
if fitness(population[i]) >= 0 and fitness(population[i]) <= 1:
#print(population[i])
break
"""
iteration -= 1
print (pop_size, cnt)
calculateFitnessAndOperations()
|
5dedf557a831566bbbbd840af0f135af93daee5a | antoalv19/TP_solutions | /ch16_ex.py | 2,063 | 4.3125 | 4 | class Time:
'''Represents the time of day.
attributes: hour, minute, second
'''
def print_time(t):
print ('(%.2d:%.2d:%.2d)' % (t.hour, t.minute, t.second))
def is_after(t1, t2):
return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)
def mul_time(t, n):
'''Multiple time t by n
n: int
Returns a time tr
'''
return int_to_time(time_to_int(t) * n)
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
while sum.second >= 60:
sum.second -= 60
sum.minute += 1
while sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
def increment(t, sec):
'''Writes a inc function does not contain any loops
#for the second exercise of writing a pure function, I think you can just create a new object by copy.deepcopy(t) and modify the new object. I think it is quite simple so I will skip this one, if you differ please contact me and I will try to help
idea: using divmod
sec: seconds in IS
'''
t.second += sec
inc_min, t.second = div(t.seconds, 60)
t.minute += inc_min
inc_hour, t.minute = div(t.minute, 60)
t.hour += inc_hour
return t
def int_to_time(seconds):
"""Makes a new Time object.
seconds: int seconds since midnight.
"""
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def time_to_int(time):
"""Computes the number of seconds since midnight.
time: Time object.
"""
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
if __name__ == '__main__':
t = Time()
t.hour = 17
t.minute = 43
t.second = 6
print_time(mul_time(t, 3))
t2 = Time()
t2.hour = 17
t2.minute = 44
t2.second = 5
print_time(t)
start = Time()
start.hour = 9
start.minute =45
start.second = 0
duration = Time()
duration.hour = 1
duration.minute = 35
duration.second = 0
done = add_time(start, duration)
print_time(done)
print( is_after(t, t2) )
|
1b39dc89dc110e9e1505c176e271d6aac6ac671c | Debu04/My-Python-Projects | /First Fibonacci numbers using While loop.py | 502 | 4.21875 | 4 | '''
This code will be print the first 50
Fibonacci numbers using While loop
This will print the Fibonacci numbers which is below 50
We know that the First Fibonacci numbers is 0 and 1
So we take a = 0 and b = 1
Then we swapping the values to print the first fibonacci numbers till 50
'''
# Assigning the values
a = 0
b = 1
# Condition the loop will be run to 50
while b <= 50:
print(b)
# Swapping the values that is (a) will be (b) and (b) will be (a+b)
a,b = b,a+b |
92f5ed5bd1751905fcafd1041d1f19b698313dbd | Novicett/codingtest_with_python | /정렬/k번째수.py | 253 | 3.640625 | 4 | def solution(array, commands):
answer = []
for num in range(len(commands)):
arr = array[commands[num][0]-1:commands[num][1]]
arr.sort()
print(arr)
answer.append(arr[commands[num][2]-1])
return answer |
ed0063714be16906b59b416472538f3365a940c8 | vik407/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 212 | 3.6875 | 4 | #!/usr/bin/python3
def no_c(my_string):
_my_string = ""
for each_c in my_string:
if each_c in ['c', 'C']:
continue
else:
_my_string += each_c
return _my_string
|
14fede57a8035afb833a0dbea0c3782c37e1ac32 | GEEK1050/holbertonschool-web_back_end | /0x00-python_variable_annotations/7-to_kv.py | 319 | 3.9375 | 4 | #!/usr/bin/env python3
"""7-to_kv.pt"""
import typing
def to_kv(k: str, v: typing.Union[int, float]) -> typing.Tuple[str, float]:
"""
to_kv a function that takes as argument a string k,
an Union of int and float v and return a tuple containig
k and the result cube of v
"""
return (k, v ** 2)
|
75e5e0c57e75e34258393b2e5bc6fb051e8e1b4d | mhasanemon/Python-Scrapy | /Demo/Demo/spiders/status check/website_status.py | 631 | 3.59375 | 4 | import urllib.request as urltoopen;
def check_status(param):
status = urltoopen.urlopen(param);
return status.getcode()
#This checks if the website is up or down
urls = [
'https://bbc.co.uk ',
'https://cnn.com ',
'https://nytimes.com ',
'https://gglink.uk',
'https://ebay.com'
]
try:
with open('status.text','w') as status:
for u in urls:
if(check_status(u)==200):
status.write(u+ "Website is up \n\n" )
else :
status.write(u+"Website is down \n\n")
except:
print("Cannot finish the operation")
|
fffa04fb624061d10888d1fe61a9992747ba8616 | structuredworldcapital/Lab-de-Estudos | /guilherme.py - Organizar/aula18.py | 1,638 | 4.34375 | 4 | teste = list() #mesma coisa que teste = [] cria uma lista vazia
teste.append('Guilherme')
teste.append(40)
galera = list()
galera.append(teste[:]) #da pra add uma lista em outra lista, a lista teste ta dentro da lista galera
teste[0] = 'Maria' #mudei as informações de teste
teste[1] = 22
galera.append(teste[:]) #é preciso criar uma cópia com [:] senão as duas listas dentro de galera ficam iguais
print(galera)
galera = [['João',19], ['Ana',33],['Joaquim',13],['Maria',45]]
print(galera[0]) #printar o primeiro item da lista galera no caso João,19
print(galera[0][0])#printar o primeiro item do primeiro item da lista galera no caso só João
print(galera[2][1])
for pessoa in galera:
print(pessoa)
for pessoa in galera:
print(pessoa[0]) #só printa o primeiro item de cada pessoa no caso nome
for pessoa in galera:
print(pessoa[1]) #printa só a idade
for pessoa in galera:
print('{} tem {} anos de idade'.format(pessoa[0],pessoa[1]))
galera = list()
dado = list()
totmaior = totmenor = 0
for c in range(0,3):
dado.append(str(input('Nome: ')))
dado.append(int(input('Idade: ')))
galera.append(dado[:]) #se não fizer uma cópia na hora q der clear dado a lista galera tbm é apagada
dado.clear()
for pessoa in galera:
if pessoa[1] >= 18:
print('{} é maior de idade'.format(pessoa[0]))
totmaior += 1
else:
print('{} é menor de idade'.format(pessoa[0]))
totmenor += 1
print('Temos {} maiores e {} menores de idade'.format(totmaior, totmenor))
|
211168c5c2d9e0eeb159866c4955c3583864f56d | subsoontornlab/OCW_python | /functionEx.py | 545 | 3.984375 | 4 | import math
#get base
inputOK = False
while not inputOK:
base = float(input('Enter base: '))
if type(base) == type(1.0): inputOK = True
else: print('Error. Base must be a floating point number')
#get height
inputOK = False
while not inputOK:
height = float(input('Enter height: '))
if type(height) == type(1.0): inputOK = True
else: print('Error. Height must be a floating point number')
hyp = math.sqrt(base*base + height*height)
print('Base: ' + str(base) + ' ,height: ' + str(height) + ' ,hyp: ' + str(hyp))
|
7575faf802c57912588695334afdba9765704541 | ProjectOnePM/ProjectOneEjercicios | /Unidad 2 - IF/TP2_Ejer01.py | 116 | 3.875 | 4 | num=input("Ingrese el numero: ")
if num%2 == 0 :
print "Es un numero par "
else :
print "Es un numero impar " |
17a0a33189e1f68ed520a040ac070ba9196c9b42 | Aasthaengg/IBMdataset | /Python_codes/p02724/s107228967.py | 76 | 3.5 | 4 | x = int(input())
h500 = x // 500
h5 = (x%500) //5
print(h500 * 1000 + h5* 5) |
80081c09401221cce8a9e9434657445aba4dac35 | rokingshubham1/tic-tac-toe | /tic-tac-toe.py | 3,673 | 3.828125 | 4 | import random, os
board = [['-' for _ in range(3)] for _ in range(3)]
scores = {
'X' : -1,
'O' : 1,
'tie' : 0
}
#shubham jaishwal tic tac toe game
# --------------------------------------------- #
def whoHasWon():
for i in range(3):
if board[i][0] == board[i][1] == board[i][2]:
return str(board[i][0])
if board[0][i] == board[1][i] == board[2][i]:
return str(board[0][i])
if board[0][0] == board[1][1] == board[2][2] :
return str(board[0][0])
elif board[2][0] == board[1][1] == board[0][2] :
return str(board[2][0])
else:
for i in range(3):
for j in range(3):
if board[i][j] == '-' :
return '-'
return 'tie'
def checkIfGameOver():
# print board
os.system('cls')
for i in range(3):
for j in range(3):
print(board[i][j],end="\t")
print()
# check if game is over
gameover = 'tie'
for i in range(3):
if board[i][0] == board[i][1] == board[i][2]:
gameover = str(board[i][0])
if board[0][i] == board[1][i] == board[2][i]:
gameover = str(board[0][i])
if gameover == 'tie':
if board[0][0] == board[1][1] == board[2][2] :
gameover = str(board[0][0])
elif board[2][0] == board[1][1] == board[0][2] :
gameover = str(board[2][0])
else:
for i in range(3):
for j in range(3):
if board[i][j] == '-' :
gameover = '-'
if gameover == 'tie':
print("tie")
exit()
elif gameover == '-':
pass
else:
print(gameover thanks +" wins!!")
exit()
# --------------------------------------------- #
# *********************************************** #
def placeAiMove():
bestScore = -99999
bestMove = [ 0,0 ]
for i in range(3):
for j in range(3):
# is spot available???
if board[i][j] == '-':
board[i][j] = 'O'
score = minimax(board, 0, False)
board[i][j] = '-'
if score > bestScore :
bestScore = score
bestMove[0] = i
bestMove[1] = j
return bestMove[0], bestMove[1]
def minimax(board, depth, isMax):
result = whoHasWon()
if result != '-':
return scores[str(result)]
if isMax:
bestScore = -99999
for i in range(3):
for j in range(3):
if board[i][j] == '-':
board[i][j] = 'O'
score = minimax(board, depth+1, False)
board[i][j] = '-'
bestScore = max( score, bestScore )
return bestScore
else:
bestScore = 99999
for i in range(3):
for j in range(3):
if board[i][j] == '-':
board[i][j] = 'X'
score = minimax(board, depth+1, True)
board[i][j] = '-'
bestScore = min( score, bestScore )
return bestScore
# *********************************************** #
# Loop for the turns
# --------------------------------------------- #
while True:
# ---------
checkIfGameOver()
# ---------
print("x, y : ",end="")
x, y = [int(x) for x in input().split()]
board[x-1][y-1] = 'X'
# ---------
checkIfGameOver()
# ---------
placex, placey = placeAiMove()
board[placex][placey] = 'O'
# --------------------------------------------- #
|
49bf40b3dd23d1f71302185a2e68c380916b5704 | alexandraback/datacollection | /solutions_2692487_1/Python/schapel/Aosmos.py | 1,065 | 3.6875 | 4 | #!/usr/bin/python3
from sys import argv
def fewest(a, n, motes):
motes = sorted(motes)
fewest = n # fewest operations known to be needed so far - remove all!
added = 0 # number added so far to get to this point
i = 0
while i < n:
m = motes[i]
if a > m:
a += m # absorb mole
i += 1 # move to next mole
else:
fewest = min(fewest, n - i + added) # try removing all the larger ones
added += 1 # also try adding
a += a - 1 # largest mole possible
if added > fewest: break # give up trying to add because it won't be better than removing
return min(fewest, n - i + added)
if __name__ == "__main__":
import doctest
doctest.testmod()
# Google Code Jam I/O
infile = open(argv[1])
cases = int(infile.readline())
for i in range(cases):
a, n = map(int, infile.readline().split())
motes = map(int, infile.readline().split())
print('Case #{}: {}'.format(i+1, fewest(a, n, motes)))
|
1797e8ed58d85da08bf0709634153bcff4e7b768 | dongqi-wu/PyProD---A-AI-Friendly-Power-Distribution-System-Protection-Platform | /code/PyProD/agents/Agent_Template.py | 1,362 | 3.625 | 4 | # define an abstract class template of the Agent
class agent():
def __init__(self, bus1=None, bus2=None):
# name (string) of the buses
self.bus1 = bus1
self.bus2 = bus2
self.successors = None
self.model = self.build_model()
self.inputs = None
self.open = 0
# observation should be a list of the following:
# [Vseq, VLN, VLL, Iseq, Iph]
self.obs = None
self.phases = 3
self.svNum = None
self.actNum = None
self.trainable = True
self.rewardFcn = None
# process the internal state and return model output
# AbstractMethod
def process_state(self):
print(self.bus2)
pass
# convert a model ouput to the real trip command 0/1 (0 -> no trip, 1 -> trip)
def act(self, action):
# no wrapper by default
trip = action
return trip
# adjust the agent's parameters according to the environment
def configure(self, tier=None):
pass
# take a dssCase object and retrieve the observation it wants
# return in desired format for the Agent's model
def observe(self, case):
pass
# the environment should be set to train this agent, train the model if applicable
def train(self):
pass
#
def build_model(self):
pass
|
60edf0dc47d72bba51bdec6879ebca81969b69f3 | dctongsheng/my-python | /第三课字符串/string.py | 1,453 | 4.1875 | 4 | # _*_ coding:utf-8 _*_
'''
格式化输出 %d %f %s
'''
# name = "小伟"
# ge = 18
# a = '北京'
# print('我叫%s,我今年%d了,我住在%s'%(name,ge,a)) #注意一定要用逗号隔开
'''
常用字符串函数find index count repleace split capitalize title lower upper
'''
#find
str = 'i love python oo'
# print(str.find('o'))#返回的是该字符串的位置,注意引号
# print(str.find('w'))
#index
# print(str.index('o'))
# print(str.index('w'))#如果没有会报错
#count
print(str.count('o'))
print(str.count('o',2,5))#指定位置查找,返回该元素的出现的次数
#
# #replace
# print(str.replace('o','O',1))#后面的数字为替换的次数
#split
print(str.split(" ",1))#返回一个列表 #1为maxsplit表示分割为几个字符串
#capitalize upper
print(str.capitalize())#把字符串的首字母大写
print(str.upper())
#title
print(str.title())#每个单词的首字母大写
#startswith endswith
print(str.startswith('i'))#返回bool
#ljust rjust center 左对齐 右对齐 居中
#lstrip rstrip strip 去除空格
#partition 分割三部分 左边 自己 右边
print(str.partition('love'))#返回一个元组
#join 每个字母后面插入str1,返回一个新的字符串
str1 = " "
list = ["meizi","love","me"]
print(str1.join(list))
# isspace isalnum isdigit isalpha 判断空格 字母或数字 数字 字母
print(str.isalnum()) |
0195d4822b5fd956cf9d13b14033b87fcb49f356 | timhuttonco/l_e_calculator | /main.py | 775 | 4.0625 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
name3 = name1.lower() + name2.lower()
count_true = "true"
total_true = 0
count_love = "love"
total_love = 0
for x in count_true:
total_true += name3.count(x)
for y in count_love:
total_love += name3.count(y)
total_comb = int(str(total_true) + str(total_love))
if total_comb < 10 or total_comb > 90:
print(f"Your score is {total_comb}, you go together like coke and mentos.")
elif total_comb >40 and total_comb <50:
print(f"Your score is {total_comb}, you are alright together.")
else:
print(f"Your score is {total_comb}.")
|
c9c80b35ef98dd84ae1beb73e9d45605a8060c6a | AxiomeDuChoix/inf581 | /plot_price_function.py | 6,389 | 4.09375 | 4 | ##########################################################
# This file was used to plot the figures from the report #
##########################################################
import numpy as np
import random as rd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy.signal import argrelextrema
from math import log10
import function_repository
class PlotFunction():
plt.rcParams["figure.figsize"] = (8,8) # Size for the plot
def __init__(self, omega_0, period, step):
self.omega_0=omega_0
self.period=period
self.step=step
def plot_prices(self,quantities_sold, prices, x_high_price, y_high_price): # Plot the prices with an highlight on the high interest sets in the 'coffee' example
"""
Input: (np.array) quantities_sold containing the different quantities the agent might sell
(np.array) prices containing the corresponding sell prices
(np.array) x_high_price containing the sets of high interest for the buyer
(np.array) y_high_price containing the corresponding sell prices
"""
plt.ylim(np.min(prices), np.max(prices)*1.01)
# Plot the price values
plt.plot(quantities_sold, prices)
plt.title('Selling price of coffee according to the quantity of coffee sold')
plt.xlabel('Quantity of coffee sold (arbitrary units)')
plt.ylabel('Selling price (arbitrary units)')
# Visualize the sets of high interest
plt.vlines(x_high_price, -0.1, y_high_price,color='r')
plt.scatter(x_high_price, np.array([0 for i in range(len(x_high_price))]), marker='x', color='red')
for i in range(len(x_high_price)):
plt.text(x_high_price[i]-1.5, y_high_price[i]+0.1, str(x_high_price[i]), fontsize=10, color='red')
plt.text(quantities_sold[-1] * 0.55, prices[0] * 0.9, 'Volumes of shares of interest' + '\n' + 'to buyers are shown in red', fontsize= 12, color='red')
plt.show()
def selling_strategy(self,quantities_sold, prices, step, period, omega_0, decision='random'):
"""
Output : (np.array) sells containing the successive cumulative quantities of shares sold
"""
max_sold_shares = 1.5 * period # The maximum amount of shares the agent is allowed to sell at each iteration
if decision == 'random': # Random decisions from the agent
sells = [0]
sold_shares = 0
while sold_shares < quantities_sold[-1]:
possible_sold_quantity = quantities_sold[int(sold_shares/step):int(sold_shares/step)+int(max_sold_shares/step)]
new_sell = int(rd.choice(possible_sold_quantity))
sells += [new_sell]
sold_shares = new_sell
else: # Greedy strategy : he targets the local maxima
sells = [int(argrelextrema(prices, np.greater)[0][i]*step) for i in range(len(argrelextrema(prices, np.greater)[0]))]
sells = [0] + sells + [omega_0]
return np.array(sells)
def plot_price_strategy(self,quantities_sold, prices, sells,step):
# Allow the visualization in the coffee example
profit = 0
plt.figure(figsize=(8,8))
plt.plot(quantities_sold, prices)
plt.title('Selling price of coffee according to the quantity of coffee sold')
plt.xlabel('Quantity of coffee sold (arbitrary units)')
plt.ylabel('Selling price (arbitrary units)')
for i in range(len(sells)-1):
# Plot the rectangle
profit += (quantities_sold[int(sells[i+1]/step)]-quantities_sold[int(sells[i]/step)])*prices[int(sells[i+1]/step)]
rectangle = plt.Rectangle((quantities_sold[int(sells[i]/step)],0), quantities_sold[int(sells[i+1]/step)]-quantities_sold[int(sells[i]/step)], prices[int(sells[i+1]/step)], fc='None',ec="green",hatch='/',fill='False')
plt.gca().add_patch(rectangle)
plt.text(quantities_sold[-1] * 0.55, prices[0] * 0.9, 'Profit =' + str(profit), fontsize= 12, color='green')
plt.autoscale()
plt.show()
def main(self):
# Run main to plot all the figures from the report
quantities_sold = np.arange(0,self.omega_0+self.step,self.step) # Different quantities that the agent does sell
x_high_price = np.array([self.period * i for i in range(1,int(self.omega_0 / self.period)+1)]) # The packs of shares of interest for the buyer
y_high_price = function_repository.FunctionRepository(x_high_price, self.omega_0 ).cos_exp_function(self.period)
# Plot the price function
prices = function_repository.FunctionRepository(quantities_sold, self.omega_0).cos_exp_function( self.period)
self.plot_prices(quantities_sold, prices, x_high_price, y_high_price)
# Plot the price function
prices = function_repository.FunctionRepository(quantities_sold, self.omega_0).brownian_decr_function()
self.plot_prices(quantities_sold, prices, x_high_price, y_high_price)
# Plot the reward of a random selling strategy
sells_rd = self.selling_strategy(quantities_sold, prices, self.step, self.period, self.omega_0, 'random')
self.plot_price_strategy(quantities_sold, prices, sells_rd,self.step)
# Plot the reward of an optimal selling strategy
sells_opt = self.selling_strategy(quantities_sold, prices, self.step, self.period, self.omega_0, 'optimal')
self.plot_price_strategy(quantities_sold, prices, sells_opt, self.step)
|
2f779fe65046912edf36fcfef007eae42554743b | akimi-yano/algorithm-practice | /lc/1643.KthSmallestInstructions.py | 3,958 | 4.0625 | 4 | # 1643. Kth Smallest Instructions
# Hard
# 41
# 2
# Add to List
# Share
# Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
# The instructions are represented as a string, where each character is either:
# 'H', meaning move horizontally (go right), or
# 'V', meaning move vertically (go down).
# Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
# However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.
# Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.
# Example 1:
# Input: destination = [2,3], k = 1
# Output: "HHHVV"
# Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:
# ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
# Example 2:
# Input: destination = [2,3], k = 2
# Output: "HHVHV"
# Example 3:
# Input: destination = [2,3], k = 3
# Output: "HHVVH"
# Constraints:
# destination.length == 2
# 1 <= row, column <= 15
# 1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.
# This approach does not work !
# import heapq
# class Solution:
# def kthSmallestPath(self, destination: List[int], k: int) -> str:
# self.ROW = destination[0]
# self.COL = destination[1]
# self.K = k
# memo = {}
# def helper(row, col, path):
# key = (row, col, path)
# if key in memo:
# return memo[key]
# if row == self.ROW and col == self.COL:
# return [[]]
# if not 0<=row<=self.ROW or not 0<=col<=self.COL:
# return []
# temp = []
# [temp.append(["H"]+elem) for elem in helper(row+1,col, path)]
# [temp.append(["V"]+elem) for elem in helper(row,col+1, path)]
# return temp
# all_ins = ["".join(elem) for elem in helper(0,0,"")]
# max_heap = []
# for elem in all_ins:
# heapq.heappush(max_heap, elem)
# if len(max_heap)> self.K:
# heapq.heappop(max_heap)
# ans = ""
# for elem in max_heap[0]:
# if elem == "V":
# ans += "H"
# else:
# ans += "V"
# return ans
# This solution works !
'''
very special problem ! when find kth ... problems we do this sometimes (but sometimes its just heap, sort or quick select)
'''
class Solution:
def kthSmallestPath(self, destination: List[int], k: int) -> str:
self.ROW = destination[0]
self.COL = destination[1]
self.memo = {}
self.ans = ''
self.build_path(k, 0, 0)
return self.ans
def build_path(self, k, r, c):
if c < self.COL:
num = self.num_ways(r, c+1)
if k <= num:
self.ans += 'H'
self.build_path(k, r, c+1)
else:
self.ans += 'V'
self.build_path(k-num, r+1, c)
elif r < self.ROW:
self.ans += 'V'
self.build_path(k, r+1, c)
else:
pass
def num_ways(self, r, c):
key = (r, c)
if key in self.memo:
return self.memo[key]
ans = 0
if r == self.ROW and c == self.COL:
ans = 1
if r < self.ROW:
ans += self.num_ways(r+1, c)
if c < self.COL:
ans += self.num_ways(r, c+1)
self.memo[key] = ans
return ans |
a57429ee740d14528b5066b216f66ed466af1782 | VaibhavSingh-2104/py | /pay.py | 102 | 3.640625 | 4 |
hrs = input("Enter Hours:")
rate = input("Enter Rate:")
pay = float(hrs)*float(rate)
print(pay)
|
3ce87bbf2c7f18d2facee66119264398c9de0b86 | Aasthaengg/IBMdataset | /Python_codes/p03227/s417757610.py | 90 | 3.8125 | 4 | S=list(input())
if len(S)==2:
print("".join(S))
else:
S.reverse()
print("".join(S)) |
2c83791dfca843bc98774424a5748748dfce1414 | kumarjeetray/Programs | /Python/LassoDecrpyt.py | 1,866 | 4.4375 | 4 | def lassoLetter( letter, shiftAmount ):
# Invoke the ord function to translate the letter to its ASCII code
# Save the code value to the variable called letterCode
letterCode = ord(letter.lower())
# The ASCII number representation of lowercase letter a
aAscii = ord('a')
# The number of letters in the alphabet
alphabetSize = 26
# The formula to calculate the ASCII number for the decoded letter
# Take into account looping around the alphabet
trueLetterCode = aAscii + (((letterCode - aAscii) + shiftAmount) % alphabetSize)
# Convert the ASCII number to the character or letter
decodedLetter = chr(trueLetterCode)
# Send the decoded letter back
return decodedLetter
# Define a function to find the truth in a secret message
# Shift the letters in a word by a specified amount to discover the hidden word
def lassoWord( word, shiftAmount ):
# This variable is updated each time another letter is decoded
decodedWord = ""
# This for loop iterates through each letter in the word parameter
for letter in word:
# The lassoLetter() function is invoked with each letter and the shift amount
# The result (decoded letter) is stored in a variable called decodedLetter
decodedLetter = lassoLetter(letter, shiftAmount)
# The decodedLetter value is added to the end of the decodedWord value
decodedWord = decodedWord + decodedLetter
# The decodedWord is sent back to the line of code that invoked this function
return decodedWord
print( "Shifting WHY by 13 gives: \n" + lassoWord( "WHY", 13 ) )
print( "Shifting oskza by -18 gives: \n" + lassoWord( "oskza", -18 ) )
print( "Shifting ohupo by -1 gives: \n" + lassoWord( "ohupo", -1 ) )
print( "Shifting ED by 25 gives: \n" + lassoWord( "ED", 25 ) ) |
502234a76c3b6648051988d63db5607101b4351c | northwestcoder/simpledatagen | /module01/example03.py | 1,232 | 3.546875 | 4 | #
# for this example, you will need to pip install flask
# and/or read the docs on flask: https://flask.palletsprojects.com/en/1.1.x/
#
# this example builds on the previous example01 by providing
# a payload URL for fake data
#
# from this directory, you would start flask from the command line like so:
# $export FLASK_APP=example03.py
# $flask run
#
# it will then say
# "Running on http://127.0.0.1:5000/"
#
# and if you go to
#
# http://127.0.0.1:5000/randompayload
# or
# http://127.0.0.1:5000/staticpayload
#
# you should see 1,000 lines of randomly generated data
#
# each time you refresh the page the data will be rebuilt :)
from flask import Flask
import buildcsv_people
app = Flask(__name__)
staticdata = buildcsv_people.createData(headers=True, rows=1000, buildtransactions=False)
# this next route generates a var each time the route is called
@app.route('/randompayload')
def randompayload():
payload = buildcsv_people.createData(headers=True, rows=1000, buildtransactions=False)
return payload[0]
# this one uses 'staticdata' created outside of the route,
# so it will remain stable for the lifetime of the flask invocation
@app.route('/staticpayload')
def staticpayload():
return staticdata[0] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.