blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
b595e156fb5bc03cbfcc0a59ce7d4f947b09b7d7 | glucianog/HackerHank | /Python/alphabetRangoli.py | 991 | 3.65625 | 4 | def writeDashes(n):
result = ""
for _ in range(n):
result+= "-"
return result
def writeLetters(n, lastLetter):
result = ""
aux = 0
for x in range(n):
result += chr(lastLetter - x)
if x < n-1:
result += "-"
aux = lastLetter - x
for x in range(1,n):
result += "-"
result += chr(aux+x)
return result
def rangoli(n, lastLetter):
for i in range(1,n):
string = writeDashes(2*n - 2*i) #left dashes
string += writeLetters(i, lastLetter)#letters
string += writeDashes(2*n - 2*i) #right dashes
print(string)
print(writeLetters(n, lastLetter))
for i in range(n-1,0,-1):
string = writeDashes(2*n - 2*i) #left dashes
string += writeLetters(i, lastLetter)#letters
string += writeDashes(2*n - 2*i) #right dashes
print(string)
if __name__ == '__main__':
n = int(input())
lastLetter = 96 + n
rangoli(n, lastLetter) |
c2d8fe69d77582f58b0017236e798fd6f6859a11 | travbrown/CS-0 | /Intro_classes.py | 2,908 | 3.984375 | 4 | class Person:
# This function is called whenever a new Person object is created. The
# self parameter refers to the object itself, i.e. the instance of the
# class that is being created.
def __init__(self, first, last):
self.first = first
self.middle = None
self.last = last
def __str__(self):
if self.middle != None:
return self.first + ' ' + self.middle + ' ' + self.last
return self.first + ' ' + self.last
def add_middle_name(self, middle):
self.middle = middle
class Student(Person):
def __init__(self, first, last):
super().__init__(first, last) # Call parent's __init__() function
self.grades = []
self.average = 0
def __str__(self):
return Person.__str__(self) + ' ' + str(self.grades)
def add_grade(self, grade, max_grade, weight):
self.grades.append((grade, max_grade, weight))
def grades_average(self):
max_weight,weighted_sum = 0,0
if self.grades == []:
return None
for grade, max_grade, weight in self.grades:
max_weight += weight
weighted_sum += ((grade/max_grade)*weight)
self.average = float(weighted_sum/max_weight)*100
return self.average
def __lt__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() < other.grades_average()
return False
def __gt__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() > other.grades_average()
return False
def __eq__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() == other.grades_average()
return False
def __ge__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() >= other.grades_average()
return False
def __le__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() <= other.grades_average()
return False
def __ne__(self, other):
if self.grades != [] and other.grades != []:
return self.grades_average() != other.grades_average()
return False
# This is to list all the methods in the Student class. See which one(s) of
# those you have to implement for part #3 of the assignment...
for f in [func for func in dir(Student) if callable(getattr(Student, func))]:
print(f)
me = Student('Travis','Brown')
me.add_grade(90,100,1.0)
me.add_grade(20,25,2.0)
him = Student('Daniel','Lawla')
him.add_grade(9,100,1.0)
him.add_grade(2,25,2.0)
print(me.__str__())
print(me.grades_average())
print(me.__lt__(him))
me.add_middle_name('Jordan')
print(me.__str__()) |
401f4e3313bf14611b7f65c827d0ca9317edffaa | kingsham/Python | /coin.py | 344 | 3.9375 | 4 | import random
heads=0
tails=0
count=0
while count < 100:
coin=random.randint(1,2)
if coin == 1:
print("Heads")
heads += 1
count += 1
elif coin ==2:
print("Tails!")
tails += 1
count += 1
print("You flipped heads",heads, "times")
print("\nand you flipped tails",tails, "times")
|
adbec5b42009bd07110ac215f46e5b67caba5244 | Chiiryuu/Minesweeper-AI | /helperFunctions.py | 11,848 | 3.984375 | 4 | import random
import fileInput as fileHelper
def colRowToIndex(col, row, height):
""" This function is used to take in a (col,row) pair along
with the height of the playBox and converts the (col,row)
pair to an index
"""
if (col < 0 or row < 0 or row >= height):
return -1
return col*height + row
def indexToColRow(index, height):
""" This function is used to take in an index along with the
height of the playBox and converts the index to a (col,row)
pair/
"""
col = index // height
row = index % height
return (col, row)
def getNeighbors(col, row, width, height):
""" This function is used to get all of the neighbors
of a certain (col,row) pair.
"""
neighbors = []
min = -1
max = width * height
neighbor = colRowToIndex(col-1, row-1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col-1, row, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col-1, row+1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col, row-1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col, row+1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col+1, row-1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col+1, row, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
neighbor = colRowToIndex(col+1, row+1, height)
if (neighbor > min and neighbor < max):
neighbors.append((9, neighbor))
return neighbors
def displayState(state):
""" This function is used to display the state of the
program. It takes in the stae with is a 2d array of
state tuples.
"""
rowSize = len(state)
colSize = len(state[0])
rowStrings = ['']*colSize
for i in range(rowSize):
for j in range(colSize):
rowStrings[j] += str(state[i][j][0]) + ' '
result = ''
for string in rowStrings:
result += string + '\n'
result = result.replace('-1','X').replace('-2','B').replace('0',' ').replace('9','?').replace('-3', 'F')
print(result)
return result
def getUnknowns(state):
""" Get a list of all of the unknowns in a state. It checks for the value
being -1, and if it is -1 then it will appent the index to the unknown
list.
"""
unknowns = []
height = len(state[0])
for i in range(len(state)):
for j in range(height):
val = state[i][j][0]
if (val == -1):
unknowns.append(colRowToIndex(i,j,height))
return unknowns
def chooseBestGuessV0(state, numBombs):
unknownList = []
height = len(state[0])
for i in range(len(state)):
for j in range(height):
val = state[i][j][0]
if (val == -1):
unknownList.append(colRowToIndex(i,j,height))
return (random.choice(unknownList),numBombs/len(unknownList))
def chooseBestGuessV1(state, numBombs):
""" Version 1 of the choose best guess function.
"""
guessList = []
unknownsToBombs = 0
for i in range(len(state)):
for j in range(len(state[i])):
val = state[i][j][0]
if (val == -1 or val == -2):
val = 5
unknowns = []
bombs = state[i][j][1]
difference = val-bombs
neighbors = state[i][j][2]
for neighbor in neighbors:
if (neighbor[0] == -1):
unknowns.append(neighbor[1])
localVal = len(unknowns) - difference
if (localVal > unknownsToBombs):
unknownsToBombs = localVal
guessList = unknowns
if (localVal == unknownsToBombs):
guessList.extend(unknowns)
#This is done because completely unknown squares are assigned a strange weight
if (len(guessList) == 0):
guessList = getUnknowns(state)
return (random.choice(guessList),unknownsToBombs)
def chooseBestGuessV2(state, numBombs):
guessList = []
unknownList = []
unknownsToBombs = -2
height = len(state[0])
for i in range(len(state)):
for j in range(height):
val = state[i][j][0]
if (val == -1 or val == -2):
unknownList.append((i,j))
for unknown in unknownList:
space = state[unknown[0]][unknown[1]]
localVal = 10
neighbors = space[2]
for neighbor in neighbors:
if (neighbor[0] == -1 or neighbor[1] == -2):
continue
neighborPos = indexToColRow(neighbor[1], height)
neighborState = state[neighborPos[0]][neighborPos[1]]
neighborNeighbors = neighborState[2]
val = neighborState[0]
unknowns = []
bombs = neighborState[1]
difference = val-bombs
for neighborNeighbor in neighborNeighbors:
if (neighborNeighbor[0] == -1):
unknowns.append(neighborNeighbor[1])
subLocalVal = len(unknowns) - difference
localVal = min(localVal, subLocalVal)
if (localVal == 10):
#unknowns = []
#for neighbor in neighbors:
# if (neighbor[0] == -1):
# unknowns.append(neighbor[1])
#localVal = len(unknowns) // 2
localVal = -2
if (localVal > unknownsToBombs):
unknownsToBombs = localVal
guessList = []
guessList.append(colRowToIndex(unknown[0],unknown[1],height))
if (localVal == unknownsToBombs):
guessList.append(colRowToIndex(unknown[0],unknown[1],height))
#print("Val: ",unknownsToBombs)
if (len(guessList) == 0):
guessList = unknownList
return (random.choice(guessList),unknownsToBombs)
def chooseBestGuessV3(state, numBombs):
""" Version 2 of the choose best guess function
"""
guessList = []
frontier = []
unknownsToBombs = 0
totalCombinations = 0
frontierValues = {}
height = len(state[0])
for i in range(len(state)):
for j in range(height):
val = state[i][j][0]
neighbors = state[i][j][2]
if (val > 0):
onFrontier=False
numNeighbors = 0
for neighbor in neighbors:
if (neighbor[0] == -1):
onFrontier = True
numNeighbors = numNeighbors + 1
if (onFrontier):
frontier.append((i,j,numNeighbors))
for member in frontier:
object = state[member[0]][member[1]]
neighbors = object[2]
unknownNeighbors = member[2]
bombs = state[i][j][1]
difference = object[0]-object[1]
for neighbor in neighbors:
neighborPos = indexToColRow(neighbor[1], height)
neighborObject = state[neighborPos[0]][neighborPos[1]]
if (neighborObject[0] == -1):
val = frontierValues.get(neighbor[1], (0,0))
frontierValues[neighbor[1]] = (val[0] + difference, val[1] + unknownNeighbors)
max = 1.0
for key in frontierValues:
val = frontierValues[key]
val = val[0] / val[1]
#print("val: ",val,", max: ",max,"val > max: ",val > max)
if (val < max):
guessList = []
guessList.append(key)
max = val
elif (abs(val - max) < 0.01):
guessList.append(key)
#print("Choosing 1 of ",len(guessList)," best guesses...")
#print(frontierValues)
#print("Frontier: ",len(frontier),", Bombs:",numBombs)
#This is done because completely unknown squares are assigned a strange weight
#guess = random.choice(frontier)
#guess = colRowToIndex(guess[0], guess[1], height)
#return guess
if (len(guessList) == 0):
guessList = getUnknowns(state)
return (random.choice(guessList), max)
def writeNeighbors(state):
""" This function is used to go through the current
state of the board and see if anything has changed
for the neighbors or number of bombs.
"""
height = len(state[0])
for i in range(len(state)):
for j in range(len(state[i])):
val = state[i][j][0]
bombs = state[i][j][1]
neighbors = state[i][j][2]
newNeighbors = []
for k in range(len(neighbors)):
#print(neighbors[k])
neigborPos = indexToColRow(neighbors[k][1], height)
neighborState = state[neigborPos[0]][neigborPos[1]]
if neighborState[0] == -2:
bombs+=1
elif neighborState[0] != 0:
newNeighbors.append((neighborState[0], neighbors[k][1]))
state[i][j] = newState = (val, bombs, newNeighbors)
def findBombs(state):
""" Function for finding the bombs in the state and
their locations.
"""
newBombs = []
for i in range(len(state)):
for j in range(len(state[i])):
unknowns = []
val = state[i][j][0]
bombs = state[i][j][1]
neighbors = state[i][j][2]
for neighbor in neighbors:
if (neighbor[0] == -1):
unknowns.append(neighbor[1])
if (val - bombs == len(unknowns)):
for unknown in unknowns:
if (not unknown in newBombs):
newBombs.append(unknown)
for k in reversed(range(len(neighbors))):
if (neighbors[k][1] in unknowns):
neighbors.pop(k)
bombs = bombs + len(unknowns)
state[i][j] = (val, bombs, neighbors)
for bomb in newBombs:
bombPos = indexToColRow(bomb, len(state[0]) )
state[bombPos[0]][bombPos[1]] = (-2, 0, [])
writeNeighbors(state)
return newBombs
def findSafes(state):
""" This function is used to check the current
state for locations that are safe to move
to (not a bomb)
"""
safes = []
for i in range(len(state)):
for j in range(len(state[i])):
unknowns = []
val = state[i][j][0]
bombs = state[i][j][1]
neighbors = state[i][j][2]
for neighbor in neighbors:
if (neighbor[0] == -1):
unknowns.append(neighbor[1])
if (val - bombs == 0):
for unknown in unknowns:
if (not unknown in safes):
safes.append(unknown)
for k in reversed(range(len(neighbors))):
if (neighbors[k][1] in unknowns):
neighbors.pop(k)
state[i][j] = (val, bombs, neighbors)
writeNeighbors(state)
return safes |
f2b62c41d565f09d320c8aa83d9696ad0d9b5c5a | reflectm/AutomatizationCourse_17.05 | /Lec2/source/main_another_read.py | 888 | 4.34375 | 4 | """
Считываем построчно из входного файла
* .readlines() - вычитывает также целиком весь файл, но возвращает список строк
* .readline() - вычитывает один блок , оканчивающийся `\n`
"""
file_handler = open("input.txt", "r")
words = file_handler.readlines() # Считвает все строки ('\n') и возвращает список строк
print([word.strip() for word in words]) # Отрезаем символы переноса на новую строку
file_handler.close()
# Итеративное построчное счтиывание из файла
new_file_handler = open("input.txt", "r")
line = new_file_handler.readline()
while line:
print("Current line:", line.strip())
line = new_file_handler.readline()
new_file_handler.close() |
b09988eb4ffd7cadf4acfd5994a119a6cb5ddd15 | DickyHendraP/Phyton-Projects-Protek | /Pratikum 05/latihan 2 nomor 4.py | 294 | 3.6875 | 4 | #program Modifikasi bintang dari kecil ke besar
#menjadi dari besar ke kecil
#membuat variable terlebih dahulu
kolom = 4
baris = 5
i = 0
#membuat perulangan
while (i < baris) :
j = 0
while (j <= kolom) :
print('* ', end='')
j += 1
print( ' ' )
i += 1
kolom -= 1
|
024ff501264de6ed6ee6ee02b221900d7f25cdd3 | dharani277/guvi | /codekata/absolute_beginner/addition_of_two_number.py | 307 | 4.09375 | 4 | # addition of two numbers
# get the two numbers as input from the user
a=float(input())
b=float(input())
# create function for addition
def add():
# add and round of the value
c=round(a+b)
# return the value c
return c
# call the function and store the output in s
s=add()
# print the value s
print(s)
|
94b71e883e5489627963d0569c9578e7b5a16b63 | RakhatAubakirov/Web-dev2020 | /Week-7/1/3/1/342.py | 129 | 3.734375 | 4 | #s = 0
#for x in range(100):
# s = s + input()
#print(s)
s = 0
for x in range(100):
s = s + int(input())
print(s) |
7129491880cbcbc2c176d0f7e86f0a95ac927564 | Thequantums/ECE183DA | /testing stuff/RRT.py | 4,975 | 3.53125 | 4 | import math
import random
import matplotlib.pyplot as plt
import numpy as np
origin = [250, 0, 0, 0] #Origin point, in form x,y,parent,cost
maxcoords = [500,500] #Max values of field. x,y form. Assumes bottom left is 0,0
stepsize = 5 #size of step to take (1=> unit vector step)
N = 5000 #Iterations to run
nodesList = [origin] #list of all nodes
obstacles = []#[[0,0,100,500],[400,0,500,500],[200,300,400,325],[100,350,250,375]] #obstacle list. Rectangles only, in form xmin, ymin, xmax, ymax
goal = [100,400,200,500] #goal. Rectangles only, in form xmin, ymin, xmax, ymax
searchdist = 4.9
searchdistOpt = 8
def finddist(node1,node2): #returns the euclidian distance between two nodes
dist = math.sqrt(pow(node1[0]-node2[0],2)+pow(node1[1]-node2[1],2))
return dist
def getCost(currentNode, nodelist):
totaldist = currentNode[3] + finddist(nodelist[currentNode[2]], currentNode)
return totaldist
#dumb stuff
def randomPoint(): #generates a random point
global maxcoords
point = [random.uniform(0,maxcoords[0]),random.uniform(0,maxcoords[1]),0,0]
return point
def obsCheck(point, obstacles): #checks if the point is inside an obstacle. if it is, returns the origin. ##FUTURE## return the closest allowed point
for o in obstacles:
if((o[0] < point[0] < o[2]) and (o[1] < point[1] < o[3])):
return[origin[0],origin[1],origin[2],origin[3]]
return point
def takestep(startnode,targetnode,nodes): #finds a point one unit step from startnode, in the direction of targetnode. Takes "node" in order to set new node's parent node in node[2]
dist = finddist(startnode,targetnode)
newx = ((targetnode[0] - startnode[0]) / dist) * stepsize
newy = ((targetnode[1] - startnode[1]) / dist) * stepsize
checkednode = obsCheck([newx + startnode[0], newy + startnode[1], nodes.index(startnode),startnode[3]], obstacles)
checkednode[3] = getCost(checkednode,nodes)
return checkednode
def findclosest(nodes,newnode): #finds the closest node to newnode in nodelist nodes
global searchdist
distances = []
mincost = N*stepsize*5
budgetnode = []
for i in nodes:
distances.append(finddist(i,newnode))
closenode = nodes[distances.index(min(distances))]
for i in nodes:
if finddist(i,closenode) < searchdist:
if i[3] < mincost:
mincost = i[3]
budgetnode = i
return budgetnode
def checkgoal(nodelist,node,goal): #checks if the point is within the goal. if not, it sets goalfound to false. if it is, it returns the node path it took and sets goalfound to false
goalpath = []
tracenode = []
if(goal[0] < node[0] < goal[2] and goal[1] < node[1] < goal [3]):
goalfound = True
tracenode = node
goalpath.append(tracenode)
while(tracenode[2] != 0):
tracetemp = nodelist[tracenode[2]]
goalpath.append(tracetemp)
tracenode = tracetemp
else:
goalfound = False
goalpath.append(origin)
return [goalfound,goalpath]
def initplot(goal,obstacles): #initializes plot by drawing obstacles, goal, and origin as well as setting the axes
goalbox = [[goal[0],goal[2],goal[2],goal[0],goal[0]],[goal[1],goal[1],goal[3],goal[3],goal[1]]]
for o in obstacles:
obsbox = [[o[0],o[2],o[2],o[0],o[0]],[o[1],o[1],o[3],o[3],o[1]]]
plt.plot(obsbox[0], obsbox[1], 'r')
plt.plot(goalbox[0],goalbox[1],'g')
plt.xlim(0, maxcoords[0])
plt.ylim(0, maxcoords[1])
def optimize(goalpath,nodes):
for k in reversed(goalpath):
index = goalpath.index(k)
for i in nodes:
if finddist(i, k) < searchdistOpt:
if i[3] < k[3]:
goalpath[index] = i
goalpath = [ii for n, ii in enumerate(goalpath) if ii not in goalpath[:n]]
return [goalpath, goalpath[0][3]]
#dumb stuff
def main():
initplot(goal,obstacles)
for k in range(0,N):
xrand = randomPoint()
xnear = findclosest(nodesList,xrand)
xnew = takestep(xnear,xrand,nodesList)
[goalbool,goalpath] = checkgoal(nodesList,xnew,goal)
if (goalbool):
print('PATH FOUND')
break
else:
nodesList.append(xnew)
print(k)
print('GENERATING MORE POINTS')
for j in range(k,N):
xrand = randomPoint()
xnear = findclosest(nodesList, xrand)
xnew = takestep(xnear, xrand, nodesList)
nodesList.append(xnew)
print(j)
prevpathcost = 1000000
[goalpath, pathcost] = optimize(goalpath, nodesList)
while(pathcost < prevpathcost):
prevpathcost = pathcost
[goalpath,pathcost] = optimize(goalpath,nodesList)
print('iteration')
print(goalpath)
[xg, yg, zg, eg] = list(zip(*(goalpath)))
plt.plot(xg, yg, 'y')
x,y,z,g = list(zip(*nodesList))
plt.scatter(x,y,s=1)
plt.show()
main() |
1a2a25ee816b6562d104314eb9971cb407cd41f2 | synchronizedlock/algorithm012 | /Week_02/n_ary_tree_level_order_bfs.py | 549 | 3.59375 | 4 | from typing import List
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return []
res = []
def bfs(node):
queue = [node]
while queue:
next = []
tmp = []
for node in queue:
tmp.append(node.val)
for ch in node.children:
next.append(ch)
res.append(tmp)
queue = next
bfs(root)
return res
|
3f252902b7bfd645944393b93d990c6bad6ecaff | AitorCle/calculadora.py | /calculadora.py | 607 | 3.625 | 4 | import sys
import decimal
def suma(A,B):
return A + B
def resta(A,B):
return A - B
def multiplicacion(A,B):
return A*B
def division(A,B):
return A/B
#Arguments control
if len(sys.argv) != 4:
sys.exit("Error in arguments(OPERATION ARG1 ARG2)")
try:
op1 = decimal.Decimal(sys.argv[2])
op2 = decimal.Decimal(sys.argv[3])
except decimal.InvalidOperation: #PRUEBA Y SI SALE EL ERROR INVALIDOPERATION ESCRIBE TAL
sys.exit("Operands must be numbers")
operacion = sys.argv[1]
#main
if operacion == "suma":
res = suma(op1,op2)
elif operacion == "resta":
res = resta(op1,op2)
print(res)
|
edf3b709a80813dd5e188e64ec44c92483eeaf0c | strynkch/networth | /networthORIG2.py | 3,202 | 3.703125 | 4 | import sqlite3
def ass_lib():
global carloan
global mort
bone = input('How much money do you have in your checking account? : ')
btwo = input('What about your savings account? : ')
invone = input('Do you have any investments? (stocks, bonds, CD..etc)(y/n): ')
if invone.lower() == 'y':
invone = input('How much are your investment(s) worth?: ')
if invone.lower() == 'n':
invone = '0'
car = input('Do you own a car? (y/n): ')
if car.lower == 'n':
car = '0'
carloan = '0'
if car.lower() == 'y':
a = input('How many cars do you own?: ')
if a == '0':
car = '0'
if a == '1':
car = input('How much is your car worth?: ')
if a >= '2':
car = input('How much is the sum total of your cars.')
if a >= '1':
carloan = input('How much do you owe towards a car loan?: ')
if car.lower == 'y':
carloan = input('How much do you owe towards a car loan?: ')
home = input('Do you own a home?(y/n): ')
if home == 'n':
home = '0'
mort = '0'
if home.lower() == 'y':
x = input('How many homes do you own? ')
if x == '0':
home = '0'
if x == '1':
home = input('What is the Market Value of your home?: ')
if x >= '2':
home = input('What is the total market value of the sum of each home?: ')
if x >= '1':
mort = input('Enter the amount you owe on your mortgage: ')
if home == 'y':
mort = input('Enter amount you owe on mortgage: ')
personalprop = input('Do you have Personal Property? Such as Jewelery, Art, Furniture, Electronics. Etc (y/n): ')
if personalprop.lower() == 'y':
personalprop = input('What is the sum of all Personal Property?: ')
if personalprop.lower() == 'n':
personalprop = '0'
insur = input('Do you have any insurance policies? (y/n): ')
if insur.lower() == 'n':
insur = '0'
if insur.lower() == 'y':
y = input('How many policies do you have?: ')
if y >= '2':
insur = input('What is the total value of all insurance policies?: ')
if y == '1':
insur = input('How much is your policy worth?: ')
if y == '0':
insur = '0'
aset = input('Value of any other assets: ')
stu = input('Value of any student loans: ')
credit = input('Do you have any credit cards? (y/n) :')
if credit.lower() == 'n':
credit = '0'
if credit.lower() == 'y':
b = input('How many credit cards do you own?: ')
if b == '0':
credit = 0
if b == '1':
credit = input('How much do you owe on your credit card?: ')
if b >= '2':
credit = input('How much do you owe on your credit cards?: ')
debt_one = input('Any other form of current debt: ')
result_one = float(bone) + float(btwo) + float(invone) + float(car) + float(home) + float(personalprop) + float(aset) + float(insur)
result_two = float(stu) + float(credit) + float(debt_one) + float(mort) + float(carloan)
print(result_one - result_two)
|
2ecc3f28876c9800225f64626509ca9e18bbd354 | SulmanK/Predicting-Hard-Drive-Failure | /Backblaze-parser.py | 2,980 | 3.765625 | 4 | import glob
import pandas as pd
def merged_csv(folder_name, output_name):
"Function to merge all csv files in a folder"
# Create empty dataframe with all columns
tmp_df = pd.read_csv('data/drive_stats_2019_Q1/2019-01-01.csv')
columns_df = tmp_df.columns.values
# Create empty dataframe
df = pd.DataFrame(columns = columns_df )
# Merge CSV's
folder_name = folder_name
file_type = 'csv'
unmutual_columns = []
# Initiliaze all files in the folder
for f in glob.glob(folder_name + "/*." + file_type):
# If it's the last file in the folder, it will append all entries.
if f == glob.glob(folder_name + "/*." + file_type)[-1]:
tmp_df = pd.read_csv(f)
# Drop columns that are unmutual
for x in tmp_df.columns.values:
if x not in df.columns.values:
unmutual_columns.append(x)
if len(unmutual_columns) > 0:
tmp_df = tmp_df.drop([str(x)], axis = 1)
df = df.append(tmp_df)
# If not the last file in the folder, append all entires that failed.
else:
tmp_df = pd.read_csv(f)
df = df.append(tmp_df[tmp_df['failure'] == 1])
output_name = output_name
df.to_csv(output_name, index = None, header = True)
# Create quarterly files
merged_csv('data/drive_stats_2019_Q1', 'data/Q1-2019.csv')
merged_csv('data/data_Q2_2019', 'data/Q2-2019.csv')
merged_csv('data/data_Q3_2019', 'data/Q3-2019.csv')
merged_csv('data/data_Q4_2019', 'data/Q4-2019.csv')
merged_csv('data/','data/Full-2019.csv')
# Create daily_hd_failure to track the frequency of failures per quarter
def daily_hd_failures(directories):
"Function which goes through various directories to record the number of hard drives and failures per day amd outputs a csv"
date_list = []
hard_drives_per_date = []
failures_per_date = []
# Loop through all individual date csv's and record the data
for folder_name in directories:
for f in glob.glob(folder_name + "/*." + 'csv'):
## Read in dataframe
tmp_df = pd.read_csv(f)
## Record the date list, the number of hard drives and failures per date.
date_list.append(tmp_df['date'].unique()[0])
hard_drives_per_date.append(tmp_df.shape[0])
failures_per_date.append(len(tmp_df[tmp_df['failure'] == 1]))
# Create dataframe of recorded data
data = {'date': date_list,
'hard_drives': hard_drives_per_date,
'failures': failures_per_date,
}
df = pd.DataFrame(data)
return df.to_csv('data/daily_hd_failures.csv', index = None, header = True)
daily_hd_failures(['data/drive_stats_2019_Q1', 'data/data_Q2_2019',
'data/data_Q3_2019', 'data/data_Q4_2019' ] |
8718936273c9bc727dc680d6b1a71e4ee2fe3b48 | DariaKisielewska/j-pet-framework-examples | /jenkins/root_6/compare_velocity_results.py | 931 | 3.625 | 4 | #!/usr/bin/python
from __future__ import print_function
import csv
import sys
def parse_file(input_file, test_file, multiplier):
input = open(input_file)
test = open(test_file)
for (input_line, test_line) in zip(input, test):
input_splitted = input_line.rstrip().split("\t")
test_splitted = test_line.rstrip().split("\t")
print(input_splitted)
value_diff = abs(
(float)(input_splitted[1]) - (float)(test_splitted[1]))
if (value_diff * (float)(multiplier)) <= abs((float)(input_splitted[2])) and (value_diff * (float)(multiplier)) <= abs((float)(test_splitted[2])):
continue
else:
print("Value diff %f, inputvalue diff: %s, testvalue diff: %s" %
(value_diff * (float)(multiplier), input_splitted[2], test_splitted[2]))
return 1
return 0
sys.exit(parse_file(sys.argv[1], sys.argv[2], sys.argv[3]))
|
8c475fdcdf47d8e26afa038da1bace01d4fb04d4 | Yjingqi/python_data_structuress | /DS3-/searchPractise.py | 2,020 | 3.703125 | 4 | '''
写一个函数,该函数需要一个列表和我们正在搜索的项作为参数,
并返回一个是否存在的布尔值,found = False
'''
# def sequetialSearch(alist,item):
# found = False
# pos = 0
# while pos < len(alist) and not found:
# if alist[pos] == item:
# found = True
# else:
# pos = pos + 1
# return found
# testList = [1,2,3,7,23,42,90]
# print(sequetialSearch(testList,90))
# # 从头到尾最好的情况是什么,最差的情况是什么
'''
升序[17,20,26,30,44,54,55,65,77,93]
假设寻找的项在列表中
假设寻找的项不在列表中,50
'''
# def orderSequetiaSearch(alist,item):
# pos = 0
# found = False
# stop = False
# while pos < len(alist) and not found and not stop:
# if alist[pos] == item:
# found = True
# else:
# if alist[pos] > item
# stop = True
# else:
# pos = pos + 1
# return found
'''
有序列表
二分查找:每次都从剩余项中的中间元素进行比对
'''
# def binarySeach(alist,item):
# found = False
# first = 0
# last = len(alist) - 1
# while first <= last and not found:
# #中间
# midpoint = (first + last)//2
# if alist[midpoint] ==item:
# found = True
# else:
# if item < alist[midpoint]:
# last = midpoint - 1
# else:
# first = midpoint + 1
# return found
# testList = [0,1,2,3,4,5,6,7,8,9]
# print(binarySeach(testList,6))
#递归实现二分查找
# def binarySeach(alist,item):
# if len(alist) == 0:
# return False
# midoint = len(alist)//2
# if alist[midoint] > item:
# return True
# else:
# if alist[midoint] > item:
# return binarySeach(alist[:midoint],item)
# else:
# return binarySeach(alist[:midoint + 1],item)
'''
Hash查找
'''
|
20b1c1e8fff0ead0d47495114e7ff68a33f037a8 | brajesh-rit/hardcore-programmer | /Heap/HEP_kth_largest.py | 646 | 3.890625 | 4 | #https://leetcode.com/problems/kth-largest-element-in-an-array/
#Given an integer array nums and an integer k, return the kth largest element in the array.
#Note that it is the kth largest element in the sorted order, not the kth distinct element.
#Successfully implement in leetcode
import heapq
class Solution(object):
def findKthLargest(self, nums, k):
queue = []
for i in range(len(nums)):
heapq.heappush(queue, nums[i])
if len(queue) > k:
heapq.heappop(queue)
return heapq.heappop(queue)
nums = [3,2,1,5,6,4]
k = 2
result = Solution()
print(result.findKthLargest(nums,k)) |
b8cb178bf3d9e159682760d9bbf5d89b3402a094 | avidLearnerInProgress/abswp-solutions | /table_printer.py | 590 | 3.640625 | 4 | table_data = [['apples', 'oranges', 'cherries', 'bananas'],
['Alice', 'Bob', 'Carol', 'David', ],
['dogs', 'cats', 'moose', 'goose']]
def print_table(table):
col_width = [0] * len(table)
for i in range(len(table[0])):
for j in range(len(table)):
if len(table[j][i]) > col_width[j]:
col_width[j] = len(table[j][i])
for z in range(len(table[0])):
for x in range(len(table)):
print(table[x][z].rjust(col_width[x] + 1), end="")
print()
if __name__ == "__main__":
print_table(table_data) |
2a2844f98e049b4b3beac685743bf2e3bd71b3b2 | AAAR-Salmon/procon | /introduction/model_answer/python/09_tenka1_programmer_contest_1998.py | 184 | 3.59375 | 4 | # 空の固定長配列はNoneを入れておくと高速に生成できます
a=[None] * 20
a[0]=a[1]=100
a[2]=200
for i in range(3,20):
a[i] = a[i-1] + a[i-2] + a[i-3]
print(a[19])
|
07a542e80e18cec360bdd1a0a88f92fe16c01161 | yozosann/python-learning | /!!!quadratic.py | 696 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
for n in (a,b,c):# 遍历三个参数
if not isinstance(n,(int,float)):#遍历判断参数是整型或浮点型
raise TypeError('你输入的是什么玩意儿')#错误提示
temp = b*b - 4*a*c
if temp < 0:
print('无解')
return
else:
return (-b + math.sqrt(temp))/(2 * a), (-b - math.sqrt(temp))/(2 * a)
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))
if quadratic(2, 3, 1) != (-0.5, -1.0):
print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
print('测试失败')
else:
print('测试成功') |
8f054506bc06527d980481057b418d503d8a42a3 | arpipati/python-practice | /element-search.py | 1,344 | 3.953125 | 4 | ## -- Problem URL: https://www.practicepython.org/exercise/2014/11/11/20-element-search.html
import random
import timeit
def search(item, nums):
mid = int(len(nums)/2)
# found = 1
# while found != 0:
if item == nums[mid]:
#found = 0
return True
elif item < nums[mid]:
if item in nums[:mid]:
#found = 0
return True
else:
return False
elif item > nums[mid]:
if item in nums[mid:]:
#found = 0
return True
else:
return False
else:
#found = 0
return False
def main():
nums = []
print("Please enter the length of the list.")
listLen = int(input())
for i in range(listLen):
nums.append(random.randint(0, listLen))
sortedNums = nums.sort()
#print("Sorted list has been generated:", nums)
print("Please enter the number to search in this list")
item = int(input())
found = search(item, nums)
if found == True:
print("Your number is present in this list")
#elif item not in sortedNums:
else:
print("Your element is not present in this list")
if __name__ == "__main__":
start = timeit.default_timer()
main()
stop = timeit.default_timer()
print('Program Run Time: ', stop - start) |
0d8a88776a8f8d75166c4a76ae3fd35153719bf0 | pepitogrilho/learning_python | /cConsolidation/c_DataTypes/100_NoneObject_001.py | 418 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
The None object represent absence of a value = NULL
"""
if None==None:
print("Nooooone1 !")
if ""==None:
print("Nooooone2 !")
if []==None:
print("Nooooone3 !")
None
print(None)
"""
The None object is returned by a function that doesn't return anything
"""
def hello():
print("hello")
hello_output = hello()
if hello_output == None:
print("NooooOoooone!")
|
7769badcbe7610232bf439f0ae3ea20787c91ac6 | yashdeep212/yash | /python_string/wordrevers.py | 116 | 3.765625 | 4 | str1="i am devloper and this is thoughtwin"
word=str1.split()
word.reverse()
output = " ".join(word)
print(output)
|
4ded2980f97dd4df76690226cec941280cb664a6 | SinkLineP/python3_development | /лекция 4/hi.py | 517 | 3.5625 | 4 | lst = []
dct = {}
def make_list(minumum, maximum, qty):
from random import random
for i in range(qty):
lst.append(int(random()*(maximum-minumum+1))+minumum)
def analysis():
for i in lst:
if i in dct:
dct[i] += 1
else:
dct[i] = 1
mn = int(input('Минимум: '))
mx = int(input('Максимум: '))
qty = int(input('Количество элементов: '))
make_list(mn,mx,qty)
analysis()
for i in sorted(dct):
print("'%d':%d" % (i,dct[i]) |
a8dc8c457932602853ee4fbdef89feeb98171fd9 | AshishS-1123/ML-Algorithms | /tests/Preprocessing/test_StandardScaler_unittest.py | 4,918 | 3.5625 | 4 | import unittest
from ML_Algo.Preprocessing import StandardScaler
import numpy as np
# List containing the input data to the model
data = np.asarray( [0.96878163, 0.15967837, 0.49141737, 0.00389698, 0.88201058,\
0.82652326, 0.5578806, 0.46005309, 0.37107311, 0.99547713] )
# List containing the expected data from the model
expected = np.asarray( [ 1.225483, -1.2714605, -0.24769312, -1.7522117, 0.957702,\
0.7864646, -0.04258351, -0.34448528, -0.6190831, 1.3078669 ] )
class TestStandardScaler(unittest.TestCase):
def test_Output(self):
'''
Test to check whether the StandardScaler gives correct value after transforming
'''
# Fit the Algo on the data
StandardScaler.fit(data)
# Get the transformed data
actual = StandardScaler.transform(data)
# Check if the calculated and expected values are equal (with a tolerance)
areEqual = np.allclose(actual, expected)
# If the arrays are not equal, print the required message
self.assertTrue( areEqual, "Transformed data is not equal to expected values")
def test_Mean(self):
'''
Test to check whether the mean of data calculated by the algorithm is correct
'''
# Fit the model on the data
StandardScaler.fit(data)
# Get the mean calculated by the model
actual = StandardScaler.get_mean()
# Get the actual mean using numpy
expected_ = np.mean(data)
# Check if both these value are almost equal
areEqual = np.isclose(actual, expected_)
# If they are not equal, print the required message
self.assertTrue(areEqual, "Mean value found in model does no match the actual mean")
def test_StdDev(self):
'''
Test to check whether the standard deviation found while fitting the data is correct
'''
# Fit the model on the data
StandardScaler.fit(data)
# Get the standard deviation calculated by the model
actual = StandardScaler.get_std()
# Get the actual standard deviation using numpy
expected_ = np.std(data)
# Check if both these value are almost equal
areEqual = np.isclose(actual, expected_)
# If they are not equal, print the required message
self.assertTrue(areEqual, "Standard deviation found in model does no match the actual standard deviation")
def test_FitAndTransform(self):
'''
Test to check whether applying the fit and transform method seperately gives correct result
'''
# Fit the Algo on the data
StandardScaler.fit(data)
# Get the transformed data
actual = StandardScaler.transform(data)
# Check if the calculated and expected values are equal (with a tolerance)
areEqual = np.allclose(actual, expected)
# If the arrays are not equal, print the required message
self.assertTrue( areEqual, "Applying Fit and Transform methods seperately did not give correct results")
def test_FitTransform(self):
'''
Tests to check whether applying the fit_transform method gives correct result
'''
# Fit and transform the data
actual = StandardScaler.fit_transform(data)
# Check if the calculated and expected values are equal (with a tolerance)
areEqual = np.allclose(actual, expected)
# If the arrays are not equal, print the required message
self.assertTrue( areEqual, "Applying fit_transform method did not give correct results")
def test_DataTypes(self):
'''
Test to check whether the methods work for different data types
'''
# Fit the model on int32 type data
actual = StandardScaler.fit_transform(data.astype(np.int32))
# Check if the model gave correct results
self.assertTrue( actual.size != 0, "Functions did not work on 32 bit integer data type")
# Fit the model on int8 type data
actual = StandardScaler.fit_transform(data.astype(np.int8))
# Check if the model gave the correct results
self.assertTrue( actual.size != 0, "Functions did not work on 8 bit integer data type")
# Fit the model on float type data
actual = StandardScaler.fit_transform(data.astype(np.float))
# Check if the model gave the correct results
self.assertTrue( actual.size != 0, "Functions did not work on float data type")
# Fit the model on double type data
actual = StandardScaler.fit_transform(data.astype(np.double))
# Check if the model gave the correct results
self.assertTrue( actual.size != 0, "Functions did not work on double data type")
if __name__ == '__main__':
unittest.main() |
e75f68e76501e0bbdfa5e96a72e18911b8600545 | sunny-/python | /match.py | 553 | 4.0625 | 4 | def match(wordlist,letters):
''' assumes: wordList is a list of words in lowercase.
lStr is a str of lowercase letters. No letter occurs in lStr
more than once returns: a list of all the words in wordList that
contain each of the letters in lStr exactly once and no letters not in lStr.'''
match = []
letters = sorted(letters)
for i in wordlist:
w=sorted(i)
if w == letters:
match.append(i)
return match
wordlist = ['apple', 'boy', 'cat']
letters = 'tac'
print (match(wordlist,letters))
|
b7d208e909ad037c383cc677aec86c50f703c412 | gustavoosantoos/LearningPython | /strings.py | 682 | 4.03125 | 4 | str1 = "Hello"
str2 = "World"
# Concatenações são normais
print(str1 + str2)
# Por que dá pra multiplicar uma string em Python? Só deus sabe...
num1 = 10
print(str1 * num1)
# Não há cast automático para string, a linha de baixo ocasiona erro
# print(str1 + num1)
# Cast para int de string
print(str1 + str(num1))
# Obter chars através do index
print(str1[0])
# Obter chars através de ranges
print(str1[0:3])
print(str1[3:5])
# Obter tamanho da string
print(len(str1))
# Trim
print(" teste 3 ".strip())
# Outros métodos
print(str1.upper())
print(str1.lower())
print(str1.capitalize())
print(str1.replace("l", "r"))
# Split
x = str1.split('l')
print(x) |
990f309ea37aa46b7999b6ceed30ef19f9ecda9b | segunar/BIG_data_sample_code | /2. Average Length and Percentage/my_python_mapreduce/Second_Round_MapReduce/my_meta-algorithm.py | 5,684 | 3.59375 | 4 | #!/usr/bin/python
# --------------------------------------------------------
# PYTHON PROGRAM
# Here is where we are going to define our set of...
# - Imports
# - Global Variables
# - Functions
# ...to achieve the functionality required.
# When executing > python 'this_file'.py in a terminal,
# the Python interpreter will load our program,
# but it will execute nothing yet.
# --------------------------------------------------------
import os
import codecs
import my_mapper
import my_reducer
# ------------------------------------------
# FUNCTION my_mapper_simulation
# ------------------------------------------
def my_mapper_simulation(input_directory, output_directory, my_mapper_input_parameters):
# 1. We create the results file
my_output_stream = codecs.open(output_directory + "my_mapper_results.txt", "w", encoding='utf-8')
# 2. We collect the list of files we have to process
file_names = os.listdir(input_directory)
# 3. We process each file sequentially
for file in file_names:
# 3.1. We open the file to be read
my_input_stream = codecs.open(input_directory + file, "r", encoding='utf-8')
# 3.2. We process it
my_mapper.my_map(my_input_stream, my_output_stream, my_mapper_input_parameters)
# 3.3. We close the file
my_input_stream.close()
# 4. We close the results file
my_output_stream.close()
# ------------------------------------------
# FUNCTION my_sort_simulation
# ------------------------------------------
def my_sort_simulation(output_directory):
# 1. We create the results file
my_output_stream = codecs.open(output_directory + "my_sort_results.txt", "w", encoding='utf-8')
# 2. We open the source file
my_input_stream = codecs.open(output_directory + "my_mapper_results.txt", "r", encoding='utf-8')
# 3. We traverse the lines of the source file
content = []
for line in my_input_stream:
# 3.1. We add the line's content to the list
line = line.replace('\n', '')
words = line.split('\t')
content.append( (words[0], words[1]) )
# 4. We sort the content
content.sort()
# 5. We print the sorted file to the output_stream
for item in content:
my_str = str(item[0]) + '\t' + str(item[1]) + '\n'
my_output_stream.write(my_str)
# 6. We close the file
my_output_stream.close()
# ------------------------------------------
# FUNCTION my_reducer_simulation
# ------------------------------------------
def my_reducer_simulation(output_directory, my_reducer_input_parameters):
# 1. We create the file we will write to
my_output_stream = codecs.open(output_directory + "my_reducer_results.txt", "w", encoding='utf-8')
# 2. We open the source file
my_input_stream = codecs.open(output_directory + "my_sort_results.txt", "r", encoding='utf-8')
# 3. We process it
my_reducer.my_reduce(my_input_stream, my_output_stream, my_reducer_input_parameters)
# 4. We close the source file
my_input_stream.close()
# 5. We close the file
my_output_stream.close()
# ------------------------------------------
# FUNCTION my_main
# ------------------------------------------
def my_main(input_directory,
output_directory,
my_mapper_input_parameters,
my_reducer_input_parameters,
keep_tmp_files
):
# 1. Map Stage: We simulate it by assuming that:
# One my_mapper.py process is assigned to each file
# All my_mapper.py processes are run sequentially
# The results are written to the file my_mapper_results.txt
my_mapper_simulation(input_directory, output_directory, my_mapper_input_parameters)
# 2. Sort Stage: We simulate it by assuming that:
# All results from my_map_simulation are written to the file my_mapper_results.txt
# The results are written to the file my_sort_results.txt
my_sort_simulation(output_directory)
# 3. Reduce Stage: We simulate it by assuming that:
# All results from my_sort_simulation are written to the file my_sort_results.txt
# There is a single my_reducer.py process
# The results are written to the file my_reducer_results.txt
my_reducer_simulation(output_directory, my_reducer_input_parameters)
# 4. If keep_tmp_files is False, we remove them
if (keep_tmp_files == False):
os.remove(output_directory + "my_mapper_results.txt")
os.remove(output_directory + "my_sort_results.txt")
# ---------------------------------------------------------------
# PYTHON EXECUTION
# This is the main entry point to the execution of our program.
# It provides a call to the 'main function' defined in our
# Python program, making the Python interpreter to trigger
# its execution.
# ---------------------------------------------------------------
if __name__ == '__main__':
# 1. Local or HDFS folders
input_directory = "../../my_dataset/"
output_directory = "../../my_result/Second_Round_MapReduce/"
# 2. my_mappper.py input parameters
# We list the parameters here
# We create a list with them all
my_mapper_input_parameters = []
# 3. my_reducer.py input parameters
# We list the parameters here
total_dataset_words = 938440
# We create a tuple with them all
my_reducer_input_parameters = [total_dataset_words]
# 4. We specify if we want verbose intermediate results to stay
keep_tmp_files = False
# 4. We call to my_main
my_main(input_directory,
output_directory,
my_mapper_input_parameters,
my_reducer_input_parameters,
keep_tmp_files
)
|
6446e451fc098a498384ac26964dd5f704861efd | tsm121/TDT4113 | /Øving 2/mostCommonPlayer.py | 1,713 | 3.703125 | 4 | import random
from action import Action
actions = ['rock','scissor','paper']
class MostCommonPlayer:
def __init__(self, name):
self.name = name
self.points = 0
self.actionController = Action()
def choose_action(self,other):
mostCommonChoice = self.mostCommon(other)
if mostCommonChoice == "":
choice = actions[random.randint(0, 2)]
self.actionController.play(choice)
return choice
elif mostCommonChoice == "rock":
self.actionController.play("paper")
return "paper"
elif mostCommonChoice == "scissor":
self.actionController.play("rock")
return "rock"
else:
self.actionController.play("scissor")
return "scissor"
def receive_results(self,point):
self.points += point
return 'Player ' + self.name + ' has ' + str(self.points) + 'points'
def set_name(self, name):
self.name = name
def get_action(self):
return self.actionController
def mostCommon(self,other):
tempS,tempR,tempP = 0,0,0
for x in other.get_action().gameHistory:
if x == "rock":
tempR += 1
elif x == "scissor":
tempS += 1
else:
tempP += 1
if tempS == tempR and tempS == tempP:
return ""
elif tempS > tempR and tempS > tempP:
return "scissor"
elif tempR > tempS and tempR > tempP:
return "rock"
else:
return "paper"
def get_name(self):
return self.name
|
baff73b0bc9a701b2e13cc518d18320eeaf1da0a | IMMYz/learn | /ex36.py | 1,703 | 4.0625 | 4 | def start():
print("Here is a long long bright way\nYou go 'right' or 'left'?")
way = input(">")
if way == 'left':
ugly_girl()
elif way == 'right':
pretty_girl()
else :
print("you can't type?")
def ugly_girl():
print("In the end of the road,there has a ugly girl")
print("You can tell her u are 'ugly' or u are 'pretty'")
question_again = False
while True:
next = input(">")
if next == 'ugly' :
dead("The ugly girl show her true face,it was very beautiful,but the light make you blind")
elif next =='pretty' and not question_again:
print("'I want hear you say the truth,her give you the second chance'")
question_again = True
elif next == 'pretty' and question_again:
print("The girl in fact is very ugly,and she give you a hug,\nasking you to give her a date")
date()
def pretty_girl():
print("In the end of road,there has a pretty girl")
print("You can tell her u are 'ugly' or u are 'pretty'")
next = input(">")
if next == 'ugly':
dead("'No one dare said it to me',and the girl break your dick")
elif next =='pretty':
print("The girl give you a hug,and have a date with you")
date()
def date():
print("You can take girl to the cinema 'watch movie' or you can take her to 'hotal'")
next = input(">")
if next == 'watch movie':
dead("You and the girl watched an boring movie,and the broke up")
elif next == 'hotal':
dead("you are a father.")
else:
print("nonono")
def dead(why):
print(why,"\nGAME OVER!!")
exit(0)
start()
|
bc858fab9a3688b50c483d71c266bd0a0034e6d1 | xCUDx/PycharmPythona-z | /hello/assignment23.py | 1,247 | 4.21875 | 4 | # Given the tuple below, destructure the three values and
# assign them to position, city and salary variables
# Do NOT use index positions (i.e. job_opening[1])
job_opening = ("Software Engineer", "New York City", 100000)
position, city, salary = job_opening
print(city)
# Given the tuple below,
# - destructure the first value and assign it to a street variable
# - destructure the last value and assign it to a zip_code variable
# - destructure the middle two values into a list and assign it to a city_and_state variable
address = ("35 Elm Street", "San Francisco", "CA", "94107")
street, *city_and_state, zip_code = address
print(city_and_state)
# Declare a sum_of_evens_and_odds function that accepts a tuple of numbers.
# It should return a tuple with two numeric values:
# -- the sum of the even numbers
# -- the sum of the odd numbers.
#
# sum_of_evens_and_odds((1, 2, 3, 4)) => (6, 4)
# sum_of_evens_and_odds((1, 3, 5)) => (0, 9)
# sum_of_evens_and_odds((2, 4, 6)) => (12, 0)
def sum_of_evens_and_odds(numbers):
even_numbers = [num for num in numbers if num % 2 ==0]
odd_numbers = [num for num in numbers if num % 2 !=0]
return (sum(even_numbers), (sum(odd_numbers)))
print(sum_of_evens_and_odds((1, 2, 3, 4)))
|
521e4e3c80ee6c405b512624607ace41f801d447 | ronnyarsenal/OS-file-operations | /Write.py | 158 | 3.609375 | 4 | __author__ = 'ron'
def CreateFile():
Name = input("what is the name of the file you wish to create")
file_object = open(Name,"w")
print(Name + " created")
|
bfdb181ac7583ef808df04b268ca5d2dc8f33aee | Courage-GL/FileCode | /Python/month02/day14/exsercise/exercise03.py | 692 | 3.75 | 4 | """
杨子荣拜山头
"""
from threading import Thread, Event, Lock
msg = None
e = Event()
lock =Lock()
def yangzirong():
# 也可以通过lock 使得线程里的代码先执行
lock.acquire()
print("拜山头")
global msg
msg = "天王盖地虎"
lock.release()
# e.set()
t = Thread(target=yangzirong)
t.start()
# 由于线程是抢cpu来执行的 所以 不确定到底是哪个先执行的
# 可以通过wait来阻塞 让线程先执行
# e.wait()
if msg == "天王盖地虎":
print("宝塔镇河妖")
print("是自己人,来坐。")
else:
print("不是自己人,弄出去杀了。")
print("卧槽,无情哈拉少。")
t.join()
|
82ccdb0347ad4f95af9683b36458aa638c5b5bc1 | tejamaramreddy/Programming | /seccondLargest.py | 344 | 3.984375 | 4 | def secondLargest(arr):
if len(arr) == 1:
print(arr[0])
return
largest = arr[0]
slargest = arr[0]
for i in arr:
if i > largest:
largest = i
elif i > slargest:
slargest = i
print(slargest)
arr = [3, 2, 1, 56, 10000, 167]
secondLargest(arr)
arr = [3]
secondLargest(arr) |
1f88f2b4cd6170e76fbef050c7a947901f851157 | punithakur/-graph | /adv. graph.py | 2,688 | 3.6875 | 4 | class node:
def __init__(self, data):
self.data=data
self.next=[]
class SN_graph:
def __init__(self,index=None):
self.head=[]
self.head.append(index)
def exchange(self,a,b):
a.next.append(b)
b.next.append(a)
def find(self,a):
for i in range(1,len(self.head)):
if a==self.head[i].data:
return self.head[i]
else:
return None
def insert(self,a):
ad=node(a)
self.head.append(ad)
return ad
def finding(self,x,y):
global x_add
global y_add
x_add=self.find(x)
y_add=self.find(y)
if(x_add):
pass
else:
x_add=self.insert(x)
if(y_add):
pass
else:
y_add=self.insert(y)
self.exchange(x_add,y_add)
def graph(self,x,y):
global x_add
global y_add
if(len(self.head)>1):
self.finding(x,y)
else:
x_add=self.insert(x)
y_add=self.insert(y)
self.exchange(x_add,y_add)
def printing(self):
for i in range(1,len(self.head)):
print("node data--",self.head[i].data)
try:
for j in range( len(self.head[i].next)):
print("node connected from--", self.head[i].next[j].data)
except Exception:
pass
def searching(self, k,l):
for i in range(1, len(self.head)):
if self.head[i].data==k:
for j in range(1,l):
d=self.head[i].next[j]
h=self.distance(d)
try:
for f in h:
print(l, "dis node", f.data)
except Exception:
print("no data found")
if l==1:
for f in self.head[i].next:
print(l,"dis node",f.data)
def distance(self,x):
x=x.next
if len(x)>=1:
return x
x_add=None
y_add=None
app=SN_graph()
while True:
print("1. insert the node")
print("2. print all the nodes")
print("3. searching node")
n=int(input())
if n==1:
a=int(input("enter first value--"))
s=int(input("enter secound value--"))
app.graph(a,s)
elif n==2:
app.printing()
elif n==3:
k=int(input("node value where u want to search--"))
l=int(input("how many distance--"))
app.searching(k,l)
|
82b0056e5ac7fd18387ccb1b91b659c37faf8847 | HenBK/django-rest-framework-api | /backend_test/utils/datetime_utils.py | 278 | 3.625 | 4 | import pytz
from datetime import datetime
def get_time_now(timezone='America/Santiago'):
"""
Gets local datetime for a specified timezone,
default argument value sets the timezone to the Chilean one
"""
return datetime.now(pytz.timezone(timezone)).time()
|
8900d5e25fe502dbb2dc02ee47d3c2c5b66dd31e | edu-athensoft/ceit4101python | /evaluate/evaluate_1_exercise/m9_datetime/question_9.py | 158 | 3.859375 | 4 | """
Write a Python program to find the date of the first Monday of a given week
"""
import time
print(time.asctime(time.strptime('2022 40 1', '%Y %W %w')))
|
860e8717f26fa711c9f60e7b393ddddb6fec272b | CoffeePlatypus/Python | /Lab/lab08/eval.py | 768 | 3.515625 | 4 | from character import Character
import utilities as u
def make_dict(lines) :
# print(lines)
d = {}
for i in range(0, len(lines), 3) :
d[lines[i+2]] = Character(lines[i],lines[i+1])
# print(d[lines[i+2]])
return d
def main() :
print("here")
d = make_dict(u.read_characters("characters.txt"))
u.print_menu(d)
ch = raw_input()
while ch != "quit":
if ch in d :
d[ch].increment_evil()
u.print_menu(d)
ch = raw_input()
# print d
max = 0
chr = "no evil"
for k in d.keys():
if d[k].get_evil() > max :
max = d[k].get_evil()
chr = d[k]
print("Most evil is {} with {}".format(chr.get_name(),max))
if __name__ == "__main__" :
main()
|
ed6bb5e3bd45c08d7bcebead205f7f68693305a8 | srihariprasad-r/leet-code | /love-babbar-450/searching-sorting/pair_with_difference.py | 608 | 3.71875 | 4 | def pairWithdifference(arr, N):
def binarysearch(arr, tgt):
left = 0
right = len(arr) - 1
mid = left + (right - left) // 2
if arr[mid] == tgt:
return mid
if arr[mid] > tgt:
right = mid - 1
else:
left = mid
return - 1
for i in range(len(arr)):
pair_element = arr[i] - N
idx = binarysearch(arr, pair_element)
if idx == -1:
continue
else:
return (arr[i], arr[idx])
return -1
arr = [90, 70, 20, 80, 50]
N = 80
print(pairWithdifference(arr, N)) |
0a14d00a92d323da543b2672347ecaececc3e128 | isabelyb/Python_MinTIC_2021 | /week_2/ejercicios5_20camisas.py | 679 | 3.84375 | 4 | """20. Hacer un algoritmo que calcule el total a pagar por la compra de camisas. Si se compran
tres camisas o más se aplica un descuento del 20% sobre el total de la compra y si son
menos de tres camisas un descuento del 10%
"""
def main():
pagar()
def pagar():
precio_camisa = 20000
camisas = int(input("Cuantas camisas va a comprar? "))
precio_regular = camisas * precio_camisa
pagar = ""
if camisas >= 3:
pagar = precio_regular - ((precio_regular*20)/100)
else:
pagar = precio_regular - ((precio_regular*10)/100)
print(f"El precio por comprar {camisas} camisas es: {pagar} pesos")
if __name__ == '__main__':
main() |
e1ac2e81cd0c38b9059a209a43a8be35601afaa4 | ericnwin/Python-Crash-Course-Lessons | /Chapter 8 Functions/8-9 Messages.py | 372 | 4.3125 | 4 | '''
8-9. Messages: Make a list containing a series of short text messages. Pass the
list to a function called show_messages() , which prints each text message.
'''
def show_messages(texts):
"""
Will output a series of text messages
"""
for text in texts:
print(f"Text: {text}")
text = ['i <3 you', 'b4 you go', 'haha lol']
show_messages(text)
|
957103c32301a07273c2e20c6a156412e0d1605e | egbulenko/vanculator | /lessons/Zadachy2.py | 479 | 3.734375 | 4 | import random
my_list = [1, 2, 3, 4]
print(my_list)
random.shuffle(my_list)
print(my_list)
my_list = [1, 3, 7, 4, 5]
nomer_elementa = 1
for e in my_list:
print("элемент", nomer_elementa, ": ", e)
nomer_elementa = nomer_elementa+1
# {'вопрос': '5 + 10 = ?',
# 'ответ': '15'},
for i in range (1, 10):
for j in range (1, 10):
print("{'вопрос': '" + str(i) + " * " + str(j) + " = ?', 'ответ': '" + str(i*j) + "'}" )
|
dc2defb04d9177aa8bceffa5169f6551552993de | thakurmhn/Learn-python-scripting | /oops_inheritance.py | 621 | 3.859375 | 4 | #!/usr/bin/env python3.7
'''
With inheritance we can use methods from one class to another class
'''
class Appserver():
def __init__(self,name,version):
self.name=name
self.version=version
return None
def display(self):
print(f"Name is: {self.name}\nVersion is: {self.version}")
class Webserver(Appserver): # Inherited Appserver class
def __init__(self,name,version):
self.name=name
self.version=version
return None
appobj=Appserver('Tomcat','7.9')
webobj=Webserver('Apache','2.4')
webobj.display() # there is no display() method in Appserver class but we inherited display() from tomcat class
|
a302fa44f40a9f74b1abaab98247554634748c88 | JamissonBarbosa/questPython | /codigosURIJudge/dividindoXpY.py | 228 | 3.78125 | 4 | n = int(input())
for i in range(n):
entrada = input().split(" ")
numeros = map(int, entrada)
x, y = numeros
if y == 0:
print("divisao impossivel")
else:
result = x / y
print(result) |
d03fcea051cfc0a6d26d50b8b2e2abc8b3e44125 | madhavinamballa/de_anza_pythonbootcamp | /loops/solved/loops.py | 556 | 3.875 | 4 | # Loop through a range of numbers (0 through 4)
for num in range(5):
print(num)
# Loop through a range of numbers (2 through 6 - yes 6! Up to, but not including, 7)
for num in range(2,7):
print(num)
# Iterate through letters in a string
class_name="pyhton"
string_length=len(class_name)
for i in range(string_length):
print(class_name[i])
# Iterate through a list
my_words=["apple","google","facebook",11,12,34,67]
for i in (len(my_words)):
print(my_words[i])
# Loop while a condition is being met
j=1
while j<6:
print(j)
j=j+1
|
e91d18f44e943d4a0ee3da01b7b4e72486aa9e44 | JerBushau/mst_web_scrape | /bin/data_cli.py | 3,529 | 3.796875 | 4 | """
Quick and simple CLI application to interact with the data collected by collect_mst3k_data.py
You must first run main.py to create you mst3k.json in order to use this CLI tool.
"""
import json
import random
def get_season():
"""Get season from user input"""
while True:
try:
season = int(input('Enter a season. > '))
except ValueError:
print('Try again. Hint: Enter a number.')
continue
if season < 0:
print('Please enter a positive number')
continue
elif season > 10:
print('There is only data available for the original 10 seasons.')
continue
else:
season_key = 'season_{}'.format(season)
return season, season_key
def get_episode(season, season_key):
"""Get episode number"""
while True:
try:
episode = int(input('Enter an episode number. > '))
except ValueError:
print('Try again. Hint: Enter a number.')
continue
if episode < 0:
print('Please enter a positive number')
continue
else:
eps_in_season = len(MST3K[season_key])
if episode > eps_in_season:
print('There are only {} episodes in season {}.'
.format(eps_in_season, season))
continue
episode_key = create_episode_key(season, episode)
return episode, episode_key
def create_episode_key(season, episode):
"""Create the string that will serve as the episode key"""
episode = str(episode)
if season == 0 and len(episode) == 1:
episode_key = '{}{}{}'.format('K', '0', episode)
return episode_key
elif season == 0 and len(episode) >= 2:
episode_key = '{}{}'.format('K', episode)
return episode_key
elif len(episode) == 1:
episode_key = '{}{}{}'.format(season, '0', episode)
return episode_key
elif len(episode) >= 2:
episode_key = '{}{}'.format(season, episode)
return episode_key
def get_quote(season_key, episode_key):
try:
return random.choice(MST3K[season_key][episode_key]['quotes'])
except KeyError:
print('\nDOH!\n')
def get_info():
season, season_key = get_season()
episode, episode_key = get_episode(season, season_key)
quote = get_quote(season_key, episode_key)
return season, season_key, episode, episode_key, quote
def print_results(info):
try:
print('\nMST3K Season: {} Episode: {} \n'
'Title: {}\nShort: {}\nRandom Riff: "{}"'
.format(info[0] if info[0] != 0 else 'KTMA',
info[2],
MST3K[info[1]][info[3]]['title'],
MST3K[info[1]][info[3]]['shorts']
if MST3K[info[1]][info[3]]['shorts'] else 'Short-less',
info[4]))
except KeyError:
print('something went wrong :( \n'
'make sure you\'re using a valid episode season combination')
def main_loop():
done = False
while not done:
print_results(get_info())
again = input('\nAgain? > ').lower()
if again not in ('',
'yes', 'y',
'sey','yse',
'eys', 'sye',
'hit me', ':)'):
done = True
if __name__ == '__main__':
with open('mst3k.json', 'r') as eps:
MST3K = json.load(eps)
main_loop()
|
7e91221f339028dd3483c9afdb01950fa450b01a | charaniveerla/CodingNinjas-Practice-Java-And-Python | /CodingNinjasJava/src/ZerosAndStarsPattern.py | 670 | 3.8125 | 4 | """
Zeros and Stars Pattern
Send Feedback
Print the following pattern
Pattern for N = 4
*000*000*
0*00*00*0
00*0*0*00
000***000
Input Format :
N (Total no. of rows)
Output Format :
Pattern in N lines
Sample Input 1 :
3
Sample Output 1 :
*00*00*
0*0*0*0
00***00
Sample Input 2 :
5
Sample Output 2 :
*0000*0000*
0*000*000*0
00*00*00*00
000*0*0*000
0000***0000
"""
## Read input as specified in the question.
## Print output as specified in the question.
n=int(input())
for i in range(1,n+1):#loop for rows
for j in range(1,(2*n)+2):
if(i==j or j==n+1 or i+j==(2*n)+2):
print("*",end="")
else:
print("0",end="")
print()
|
593526b9d64c03dc8a81d44da6b3eb388f814339 | longkun-uestc/examination | /剑指offer/包含min函数的栈.py | 1,320 | 3.703125 | 4 | class Solution:
stack = []
min_element = None
def push(self, node):
if len(self.stack) == 0:
self.min_element = node
elif node < self.min_element:
self.min_element = node
self.stack.append(node)
# write code here
def pop(self):
if len(self.stack) == 0:
raise Exception("empty stack")
else:
s = self.stack.pop()
if len(self.stack) == 0:
self.min_element = None
elif s <= self.min_element:
self.min_element = min(self.stack)
return s
# write code here
def top(self):
return self.stack[-1]
# write code here
def min(self):
if len(self.stack) == 0:
raise Exception("empty stack")
else:
return self.min_element
# 第二种写法,第一种写法贼傻逼
class Solution:
stack = []
def push(self, node):
self.stack.append(node)
# write code here
def pop(self):
if len(self.stack) == 0:
raise Exception("empty stack")
else:
return self.stack.pop()
# write code here
def top(self):
return self.stack[-1]
# write code here
def min(self):
return min(self.stack)
|
1d902626a5dbf7b4295d8daba1b99ec5fe8ea13f | LuckyGitHub777/Python-Foundations | /bmi-calculator.py | 543 | 4.3125 | 4 | #!/usr/bin/python
def calculate_bmi(height, weight):
BMI = (weight * 703 / (height *height))
if BMI < 18.5:
return 'Your BMI is ' + str(BMI) +'. Thats Under-weight.'
if BMI >= 18.5 and BMI < 25 :
return 'Your BMI is ' + str(BMI) +'. Thats a Normal Weight.'
if BMI > 25:
return 'Your BMI is ' + str(BMI) +'. Thats Over-weight.'
return BMI
height = input("Enter your height: ")
weight = input("Enter your weight: ")
height = int(height)
weight = int(weight)
print (calculate_bmi(height, weight))
|
c86dc05db42fd50cd2a8bf47526bd03204747a07 | hengyangKing/python-skin | /Python基础/code_day_2/multiplication_table.py | 210 | 3.6875 | 4 | #coding=utf-8
#num =round(float(raw_input("请输入你想看到的阶数/n")));
num = 9;
i = 1;
while i<=num:
j = 1
while j<=i:
print (" %d x %d = %d\t"%(j,i,i*j),end="")
j+=1
print ("");
i+=1;
|
8b2c285a7edf7eae6b3715514a4f6527eb1d65fc | UBC-MDS/picturepyfect | /picturepyfect/compression_pyfect.py | 7,137 | 3.578125 | 4 | import numpy as np
from picturepyfect.rotate_pyfect import rotate_pyfect
class DimensionError(Exception):
""" Raised when when a numpy array has the wrong shape. """
def compression_pyfect(image, kernel_size=2, pooling_function="max"):
"""
This function uses a lossy pooling algorithm to compress an image.
The function can be applied to single channel or 3-channel images.
The user passes an image which is to be compressed and the resulting
compressed numpy array is returned. The user can also specify the pooling
algorithm to be used and the size of the kernel
to apply over the image.
Parameters
----------
image : numpy.ndarray
A n*n or n*n*3 numpy array representing a single channel or a
3-channel image.
kernel_size : int
The size of the kernel to be passed over the image. The resulting
filter moving across the image will be a 2D array with dimensions
kernel_size x kernel_size.
Default: 2
pooling_function : str
The pooling algorithm to be used within a kernel. There are three
options: "max", "min", and "mean".
Default: "max"
Returns:
---------
numpy.ndarray
A numpy array representing the compressed image.
Examples
--------
>>> compression_pyfect(image, kernel_size=3, pooling_function="max")
array([[0.04737957, 0.04648845, 0.04256656, 0.04519495],
[0.04657273, 0.04489012, 0.04031093, 0.04047667],
[0.04641026, 0.04106843, 0.04560866, 0.04732271],
[0.0511907 , 0.04518351, 0.04946411, 0.04030291]])
"""
# Check if the image and kernel_size are valid inputs
check_values(image, kernel_size)
# Check for a valid pooling_function input
if pooling_function == "max":
pool_func = np.max
elif pooling_function == "min":
pool_func = np.min
elif pooling_function == "mean":
pool_func = np.mean
else:
raise ValueError(
"""
The pooling_function argument only takes a value of 'max',
'min', or 'mean'.
"""
)
# If image is not divisible by the kernel_size
# crop off the right side columns and the bottom rows
divisible_row = image.shape[0] // kernel_size * kernel_size
divisible_col = image.shape[1] // kernel_size * kernel_size
# If image is greyscale, compress just one colour band
if len(image.shape) == 2:
image = image[:divisible_row, :divisible_col]
b1 = pool_band(image, kernel_size, pool_func)
return b1
# If image is colour, compress all 3 colour bands
else:
image = image[:divisible_row, :divisible_col, :]
# Pool the 3 colour bands
b1 = pool_band(image[:, :, 0], kernel_size, pool_func)
b2 = pool_band(image[:, :, 1], kernel_size, pool_func)
b3 = pool_band(image[:, :, 2], kernel_size, pool_func)
# Combine the 3 colour bands
return np.dstack((b1, b2, b3))
def pool_band(band, kernel_size, pool_func):
"""
This function is to be used in conjunction with compression_pyfect
and compresses a single colour band of an image.
The function applies a lossy pooling algorithm to compress the specified
colour band and the resulting compressed numpy array is returned.
Parameters
----------
band : numpy.ndarray
A n*n numpy array representing a single colour band of an image.
kernel_size : int
The size of the kernel to be passed over the image. The resulting
filter moving across the image will be a 2D array with dimensions
kernel_size x kernel_size.
pooling_function : str
The pooling algorithm to be used within a kernel. There are three
options: "max", "min", and "mean".
Returns:
---------
numpy.ndarray
An n*n numpy array representing the compressed image.
Examples
--------
>>> pool_band(image, kernel_size=3, pooling_function="max")
array([[0.04737957, 0.04648845, 0.04256656, 0.04519495],
[0.04657273, 0.04489012, 0.04031093, 0.04047667],
[0.04641026, 0.04106843, 0.04560866, 0.04732271],
[0.0511907 , 0.04518351, 0.04946411, 0.04030291]])
"""
# Using this forum post as a guide and reference for the below code
# https://tinyurl.com/yhnbexcs
col = band.shape[1] // kernel_size
# The colour band to pool
pool_colour_band = band
# pool along the rows
pool_colour_band = pool_colour_band.reshape(-1, kernel_size)
pool_colour_band = pool_func(pool_colour_band, axis=1)
pool_colour_band = pool_colour_band.reshape(-1, col)
# rotate and pool along the rows again
# old pool_colour_band = np.rot90(pool_colour_band)
pool_colour_band = rotate_pyfect(pool_colour_band, n_rot=3)
pool_colour_band = pool_colour_band.reshape(-1, kernel_size)
pool_colour_band = pool_func(pool_colour_band, axis=1)
pool_colour_band = pool_colour_band.reshape(col, -1)
# rotate back to proper layout
# old pool_colour_band = np.rot90(pool_colour_band, 3)
pool_colour_band = rotate_pyfect(pool_colour_band, n_rot=1)
return pool_colour_band
def check_values(image, kernel_size):
"""
This function checks that the image and kernel size are valid inputs
and raises an error if not.
Parameters
----------
image : numpy.ndarray
A n*n or n*n*3 numpy array representing a single channel or 3-channel
image.
kernel_size : int
The size of the kernel to be passed over the image. The resulting
filter moving across the image will be a 2D array with dimensions
kernel_size x kernel_size.
Examples
--------
>>> check_values(image, kernel_size=3)
"""
if not isinstance(image, np.ndarray):
raise ValueError("Image must be a numpy array.")
if not isinstance(kernel_size, int):
raise ValueError(
"kernel_size must be a positive integer greater than 0."
)
if kernel_size < 1:
raise ValueError(
"kernel_size must be a positive integer greater than 0."
)
# Check if the image is of the correct shape.
# Greyscale and colour images both accepted
if len(image.shape) != 2 and len(image.shape) != 3:
raise DimensionError(
"""
The input image array needs to be of shape n x n,
or n x n x 3.
"""
)
# If the image is of size n x n x n,
# ensure that the third dimension equals 3.
if len(image.shape) == 3:
if image.shape[2] != 3:
raise DimensionError(
"""
The input image array needs to be of shape n x n,
or n x n x 3.
"""
)
# Check that the kernel_size is smaller than the image height and width
if image.shape[0] < kernel_size or image.shape[1] < kernel_size:
raise ValueError(
"""
The kernel size must not be larger than the height or width of
the input image array.
"""
)
|
c5f32f1815a915cc25939c2ff536b4ba8d9c0b15 | kangli-bionic/algorithm | /lintcode/946.py | 3,144 | 3.609375 | 4 | """
946. 233 Matrix
reference: https://zhuanlan.zhihu.com/p/42639682
my note: https://imgur.com/a/WtcwXXK
"""
class Solution:
"""
@param X: a list of integers
@param m: an integer
@return: return an integer
"""
def calcTheValueOfAnm(self, X, m):
mod = 10000007
if not X and m == 0:
return 0
transformation_matrix = self.build_transformation_matrix(len(X))
#last column = = transformation ^ x * first_column
answer = self.multiply_matrix(self.fast_power(transformation_matrix, m, mod), self.build_first_column(X), mod)
# answer at last column[n]
# return answer[len(X)] % mod
return answer[len(X)][0] % mod
def fast_power(self, matrix, power, mod):
answer = self.build_identity_matrix(len(matrix))
while power > 0:
if power & 1 == 1:
answer = self.multiply_matrix(answer, matrix, mod)
matrix = self.multiply_matrix(matrix, matrix, mod)
power >>= 1
return answer
"""
multiplying 2 matrix
@param: matrix1, matrix2
@returns: resulting matrix % mod, return -1 if unable
"""
def multiply_matrix(self, matrix1, matrix2, mod):
if not matrix1 or not matrix2:
return -1 #error
m = len(matrix1)
n = len(matrix1[0])
if len(matrix2) != n:
return -1 #error
p = len(matrix2[0])
result = [[0] * p for _ in range(m)]
for i in range(m):
for j in range(p):
sum = 0
for k in range(n):
sum += matrix1[i][k] * matrix2[k][j] % mod
result[i][j] = sum
return result
"""
Build transformation matrix.
If the X is of size n, the matrix is of size (n + 2) * (n + 2)
@param: n, size of X
@return: a tranformation matrix
"""
def build_transformation_matrix(self, n):
matrix = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n + 1):
matrix[i][0] = 10
for j in range(1, n + 1):
matrix[0][j] = 0
for j in range(1, n + 1):
matrix[n + 1][j] = 0
for i in range(n + 2):
matrix[i][n + 1] = 1
for i in range(1, n + 1):
for c in range(1, i + 1):
matrix[i][c] = 1
return matrix
"""
build first column
@param: X
@return: a matrix consists of first column.
It is built of size len(X) + 2,
with first element = 23 and last element = 3
and middle elements from X
"""
def build_first_column(self, X):
matrix = [[0] for _ in range(len(X) + 2)]
matrix[0][0] = 23
matrix[len(X) + 1][0] = 3
for i in range(1, len(X) + 1):
matrix[i][0] = X[i - 1]
return matrix
def build_identity_matrix(self, k):
matrix = [[0] * k for _ in range(k)]
for i in range(k):
matrix[i][i] = 1
return matrix
s = Solution()
X=[]
m=100
result = s.calcTheValueOfAnm(X, m)
# for i in result:
# print(i)
print (result)
|
73bd209dc6073db802acfa5eecc87747c9c1fd4e | AP-MI-2021/lab-4-JocaManuela | /main.py | 1,498 | 4.03125 | 4 | def read_list():
''' Citirea unei liste de numere întregi
Input:nr=câte numere să conțină lista
numerele din listă
Output:Lista cu numere
'''
list = []
n = int(input("Lungimea listei este: "))
element = int(input("Dați primul element "))
list.append(element)
for i in range(1, n):
element = int(input("Dați al {}-lea element ".format(i + 1)))
list.append(element)
return list
def numere_negative_nenule (list):
'''
Determină toate numerele negative nenule din listă
:param list: lista de numere întregi
:return: Returnează numerele negative nenule din lista dată
'''
rez = []
for x in list:
if x!=0 and x<0:
rez.append(x)
return rez
def test_numere_negative_nenule():
assert numere_negative_nenule([-1, -56, 0, 7]) == [-1,-56]
assert numere_negative_nenule([2,5,18,-23]) == [-23]
assert numere_negative_nenule([1,2,9,10]) == []
def show_menu():
print("1.Citire listă")
print("2.Afișarea tuturor numerelor negative nenule din listă ")
print("x.Ieșire")
def main():
list = []
while True:
show_menu()
op = input("Opțiune: ")
if op == "1":
list = read_list()
elif op == "2":
print(numere_negative_nenule(list))
elif op == "x":
break
else:
print("Opțiune invalidă")
main()
|
533c5640935da7cbbd3f003cad8f770c5bb56e8d | thiamsantos/python-labs | /src/rock_paper_scissors.py | 1,623 | 4.09375 | 4 | """
Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
Remember the rules:
Rock beats scissors
Scissors beats paper
Paper beats rock
"""
def rock_paper_scissors(player1_input, player2_input):
if ((player1_input == "rock" and player2_input == "scissors") or
(player1_input == "scissors" and player2_input == "paper") or
(player1_input == "paper" and player2_input == "rock")):
return 1
return 2
def create_player_time_message(player_name):
return "{player_name} it is your time. Do you wanna paper, scissors or rock? ".format(player_name=player_name)
def create_result_message(player, winner_play, looser_play):
return "{player} WON!!! {winner_play} beats {looser_play}".format(player=player, winner_play=winner_play, looser_play=looser_play)
def main():
player1 = input("Player 1, type your name: ")
player2 = input("Player 2, type your name: ")
quit_game = "y"
while quit_game == "y":
player1_input = input(create_player_time_message(player1))
player2_input = input(create_player_time_message(player2))
game_result = rock_paper_scissors(player1_input, player2_input)
if game_result == 1:
print(create_result_message(player1, player1_input, player2_input))
else:
print(create_result_message(player2, player2_input, player1_input))
quit_game = input("Do you wanna play again? [y/n] ")
if __name__ == "__main__":
main()
|
643494af1b83e6dc7828b1086fab10c0b9051a43 | tatiana-curt/Home_Task_10_06_19_Function_2.0 | /Home_Task_10_06_19_Function_2.0.py | 7,121 | 3.65625 | 4 |
class Contact:
def __init__(self, name, surname, phone, elected=False, *args, **kwargs):
self.name = name
self.surname = surname
self.phone = phone
self.elected = elected
self.kwargs = kwargs
self.dict = {'Имя': self.name,
'Фамилия': self.surname,
'Телефон': self.phone,
'В избранных': self.elected,
'Дополнительная информация': self.kwargs}
def print_dict(self):
for item in self.dict:
if item == 'Дополнительная информация':
print('Дополнительная информация:')
for item_2 in self.dict[item]:
yield (' ') + str(item_2) + (': ') + str(self.dict[item][item_2])
else:
yield str(item) + (': ') + str(self.dict[item])
def __str__(self):
for item in self.print_dict():
print(item)
jhon = Contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com')
try:
print(jhon)
except TypeError as e:
pass
# _________________2 Задача_______________________
#
contact_list = [Contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com'),
Contact('Anna', 'Smith', '+71234567805', telegram='@Anna', email='Anna@smith.com'),
Contact('Natali', 'Smith', '+71234567806', telegram='@Natali', email='Natali@smith.com'),
Contact('Mari', 'Smith', '+71234567801', telegram='@Mari', email='Mari@smith.com')]
class PhoneBook(Contact):
def __init__(self, *args, **kwargs):
self.kwargs = kwargs
self.name_book = args
def print_contact(self):
for info in self.kwargs.values():
try:
print(info)
except TypeError as e:
pass
def add_new_contact(self, name, surname, phone, elected=False, *args, **kwargs):
new_contact = Contact(name, surname, phone, elected, *args, **kwargs)
return new_contact
def remove_contact(self, input):
for key, info in list(self.kwargs.items()):
if info.phone == input:
del self.kwargs[key]
return self
def search_elected(self):
for info in self.kwargs.values():
if info.elected == True:
try:
print(info)
except TypeError as e:
pass
def search_for_contact_by_names(self, input):
for info in self.kwargs.values():
if info.name == input[0] and info.surname == input[1]:
try:
print(info)
except TypeError as e:
pass
def main():
phones_list = []
for contact in contact_list:
phone = PhoneBook('Mari_contact_book', contact=contact)
phones_list.append(phone)
while True:
user_input = input('Введите команду:\n'
'1 - вывод списка;\n'
'2 - добавить новый контакт;\n'
'3 - удалить контакт по номеру телефона;\n'
'4 - вывести все избранные номера;\n'
'5 - найти контакт по имени и фамилии;\n'
'q - выйти\n')
if user_input == '1':
for phone in phones_list:
phone.print_contact()
elif user_input == '2':
first_name = input('Введите имя: ')
last_name = input('Введите фамилию: ')
phone = input('Введите номер телефона: ')
elected = input('Является ли контакт избранным (да или нет) (необязательно): ')
if elected == 'да':
elected = True
else:
elected = False
additional_info_dict = {}
while True:
additional_info_list = list(input('Введите дополнительные контактные данные через пробел: ').split( ))
if len(additional_info_list) ==0:
break
else:
additional_info_dict[additional_info_list[0]] = additional_info_list[1]
additional_info_list.clear()
new_contact = phones_list[0].add_new_contact(first_name, last_name, phone, elected, **additional_info_dict)
contact_list.append(new_contact)
phones_list.append(PhoneBook('Mari_contact_book', contact=contact_list[-1]))
elif user_input == '3':
user_input = input('Введите номер телефона, чьей контакт нужно удалить: ')
for phone in phones_list:
phone.remove_contact(user_input)
print('Контакт удален')
elif user_input == '4':
for phone in phones_list:
phone.search_elected()
elif user_input == '5':
user_input = input('Введите имя и фамилию через пробел: ').split()
for phone in phones_list:
phone.search_for_contact_by_names(user_input)
elif user_input == 'q':
break
else:
print('Неверная команда')
main()
# contact_dict = {'contact_1': {'Имя': 'Jhon',
# 'Фамилия': 'Smith',
# 'Телефон': '71234567809',
# 'В избранных': 'False',
# 'Дополнительная информация': {'telegram': '@jhony', 'email': 'jhony@smith.com'}},
# 'contact_2': {'Имя': 'Anna',
# 'Фамилия': 'Smith',
# 'Телефон': '71234567800',
# 'В избранных': 'False',
# 'Дополнительная информация': {'telegram': '@Anna', 'email': 'Anna@smith.com'}},
# 'contact_3': {'Имя': 'Natali',
# 'Фамилия': 'Smith',
# 'Телефон': '71234567804',
# 'В избранных': 'False',
# 'Дополнительная информация': {'telegram': '@Natali', 'email': 'Natali@smith.com'}}}
# for item in contact_dict:
# print(item)
# for item_2 in contact_dict[item]:
# if item_2 == 'Дополнительная информация':
# print('telegram=', contact_dict[item][item_2]['telegram'],
# 'email=', contact_dict[item][item_2]['email'])
# else:
# print(contact_dict[item][item_2])
# contact_list.append(Contact()) |
7a47701b55d522c86e926707c46cba0baec94ed8 | simonhoo/python-study | /s001/function_abs.py | 202 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
def t_abs(n1):
return abs(n1)
def t_test():
n1 = input("请数据一个负数:")
n2 = t_abs(n1)
print '%s的绝对值是: %s' %(n1,n2)
t_test() |
1d9a8f33c83241ff2b01f23716ff6c2a652f5250 | gabialeixo/python-exercises | /exe080.py | 737 | 4.25 | 4 | #Crie um programa que o usuário possa digitar cinco valores e cadastre-os em uma lista, já na posição correta da inserção
#sem usar sort(). No final mostre a lista ordenada na tela.
valores = list()
for c in range(0,5):
num = int(input('Digite um valor: '))
if c == 0 or num > valores[-1]:
valores.append(num)
print('Adicionado ao final da lista...')
else:
posicao = 0
while posicao < len(valores):
if num <= valores[posicao]:
valores.insert(posicao, num)
print(f'Adicionado na posição {posicao} da lista.')
break
posicao += 1
print('-' * 50)
print(f'Os valores digitados em ordem, foram: {valores}')
|
8ae074132842509982985cc7e23357aca8d46eac | KellenKolbeck/graphics-intro-python | /intro_to_graphics.py | 3,038 | 4 | 4 | import pygame
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
WHITE = (0xFF, 0xFF, 0xFF)
PI = 3.141592653
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Kellen's Cool Game")
#Loop until the user clicks the close button
done = False
#Used to manage how fast the screen updates
clock = pygame.time.Clock()
# Main program loop
while not done:
# Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicks close
done = True # Flag that we are done so we exit the loop
#--- Game logic should go here
# Screen clearing code:
# First clear the screen to white. Don't put other drawing commmands
# above this or they will be erased with this command.
screen.fill(WHITE)
#--- Drawing code will go here
# Draw on the screen a green line from (0, 0) to (100, 100)
# that is 5 pixels wide.
pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
# Draw more lines
pygame.draw.line(screen, RED, [10, 50], [1000, 600], 40)
pygame.draw.line(screen, BLACK, [500, 60], [320, 340], 10)
pygame.draw.line(screen, GREEN, [45, 100], [450, 1], 15)
pygame.draw.rect(screen, BLACK, [55, 50, 20, 25])
pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5)
# Draw on the screen several lines from (0,10) to (100,110)
# 5 pixels wide using a for loop
for y_offset in range(100, 200, 20):
pygame.draw.line(screen,RED,[0,10+y_offset],[100,110+y_offset], 5)
# Draw x's to the screen
for x_offset in range(100, 400, 50):
pygame.draw.line(screen,BLACK,[x_offset,100],[x_offset-10,90], 2)
pygame.draw.line(screen,BLACK,[x_offset,90],[x_offset-10,100], 2)
# Draw a rectangle to the screen
pygame.draw.rect(screen, GREEN, [100, 100, 50, 25], 10)
# Draw an ellipse to the screen
pygame.draw.ellipse(screen, BLACK, [250, 250, 100, 100], 2)
# Draw multiple arcs in different quadrants of an ellipse
pygame.draw.arc(screen, GREEN, [100, 100, 250, 200], PI / 2, PI, 2)
pygame.draw.arc(screen, RED, [100, 100, 250, 200], 0, PI / 2, 2)
pygame.draw.arc(screen, BLACK, [100, 100, 250, 200], 3*PI / 2, 2* PI, 2)
pygame.draw.arc(screen, RED, [100, 100, 250, 200], PI, 3*PI / 2, 2)
# Draw a polygon
pygame.draw.polygon(screen, BLACK, [[200, 200], [300, 100], [15, 5]], 6)
# Drawing text to the screen
# Select the font to use, size, bold, italic
font = pygame.font.SysFont('Arial', 60, False, False)
# Render the text. "True" means anti-aliased text.
# Black is the color. The variable "BLACK" was defined earlier
# at the top of the program.
# Note: This line creates an image of the letters,
# but does not put the image of letters on screen yet
text = font.render("My text", True, BLACK)
# Put the image of the text on the screen at 250 x 250
screen.blit(text, [250, 250])
# Update the screen with what I have drawn
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
pygame.quit() |
7fece5df84c3dbbeac2b6574fe1fc83abbf42ff5 | Ryohei222/Competitive-Programming | /Library/Python/dijkstra.py | 1,332 | 3.5 | 4 | from heapq import heappush, heappop
INF = float('inf')
class WeightedEdge():
def __init__(self, src, to, cost):
self.src = src
self.to = to
self.cost = cost
def Dijkstra(G, s):
dist = [INF] * len(G)
dist[s] = 0
pq = []
heappush(pq, (0, s))
while len(pq) != 0:
top = heappop(pq)
cost = top[0]
v = top[1]
if dist[v] < cost:
continue
for edge in G[v]:
next_cost = cost + edge.cost
if dist[edge.to] <= next_cost:
continue
dist[edge.to] = next_cost
heappush(pq, (next_cost, edge.to))
return dist
if __name__ == "__main__":
"""
This library is verified by AOJ(https://onlinejudge.u-aizu.ac.jp/solutions/problem/GRL_1_A/review/3256417/kobaryo222/Python3)
入力
V E r (V:=頂点の数, E:=辺の数, r:=始点のインデックス)
src0 to0 cost0
src1 to1 cost1
.
.
srcE-1 toE-1 costE-1
"""
V, E, r = map(int, input().split())
G = [[] for i in range(V)]
for i in range(E):
src, to, cost = map(int, input().split())
G[src].append(WeightedEdge(src, to, cost))
dist = Dijkstra(G, r)
for i in range(V):
if dist[i] == INF:
print("INF")
else:
print(dist[i]) |
5bfe3cf90110eac28b3dad31ca5bf493533be385 | billcates/unscramble | /Task0.py | 816 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of texts and what is the last record of calls?
Print messages:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
t=(texts[0])
l=(len(calls))
g=(calls[l-1])
print("First record of texts, {a} texts {b} at time {c}".format(a=t[0],b=t[1],c=t[2]))
print("Last record of calls, {a} calls {b} at time {c}, lasting {d} seconds".format(a=g[0],b=g[1],c=g[2],d=g[3]))
|
0a655c5ad5459b961c93b0ea47a0b6165bb672b9 | AnoopKunju/code_eval | /moderate/decimal_to_binary.py2 | 568 | 4.15625 | 4 | #!/usr/bin/env python2
# encoding: utf-8
"""
Decimal to Binary.
Challenge Description:
Write a program to determine the number of 1 bits in the internal
representation of a given integer.
Input sample:
The first argument will be a path to a filename containing an integer, one per
line. E.g.
10
22
56
Output sample:
Print to stdout, the number of ones in the binary form of each number. E.g.
2
3
3
"""
import sys
with open(sys.argv[1], 'r') as input:
test_cases = input.read().strip().splitlines()
for test in test_cases:
print bin(int(test))[2:]
|
974f218f61ce2384c8393a062eafa001ddd5f6e5 | rvsp/cbse | /4_python.py | 535 | 4.34375 | 4 | # 4) Using recursive function find factorial of a natural number
# recursive function to calculate
def recursive(n):
if n == 1:
return n
else:
return n*recursive(n-1)
# Change this value for a different result
num = int(input('Enter natural number for factorial calculation : '))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of {} is {}".format(num,recursive(num))) |
8b41d2cbe68891921c0e6ce2a69fa77e5fea871f | yuwinzer/GB_Phyton_Algorithms | /les_01/task_01.py | 343 | 4.03125 | 4 | # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# блок ввода данных
a, b, c = [int(i) for i in input('Введите трехзначное число\n')]
sum_n = a + b + c
mul_n = a * b * c
print(sum_n)
print(mul_n)
|
cb8d185b5176589cf53d13a8734f58ed61ca4f85 | CaoLocBK/CaoXuanLoc-fundamental-C4E23 | /ses03/2login.py | 432 | 3.625 | 4 | superuser = "c4e"
pwd = "codethechange"
print("Hi there, this is a superuser gateway")
us1 = input("Username: ")
while True :
if us1 != superuser:
print("You are not superuser")
us1 = input("Username: ")
else:
break
pd = input("Password: ")
while True:
if pd != pwd:
print("Password is incorrect")
pd = input("Password: ")
else:
break
print("Welcome, c4e")
print('\a')
|
e9acec947400975e6cadee5ba4375f3fd17ae673 | kefirzhang/algorithms | /leetcode/python/easy/p606_tree2str.py | 695 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, t: TreeNode) -> str:
if t is None:
return ""
ret = str(t.val)
if t.left is None and t.right is None:
return ret
elif t.right is None:
return ret + "(" + self.tree2str(t.left) + ")"
else:
return ret + "(" + self.tree2str(t.left) + ")" + "(" + self.tree2str(t.right) + ")"
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.left.left = TreeNode(4)
tree.right = TreeNode(3)
slu = Solution()
print(slu.tree2str(tree))
|
0ec90d8e8e95205e054117ed6fb8d9875463ec36 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2506/60749/245697.py | 544 | 3.71875 | 4 | nums=input()
def judge(nums):
if len(nums)==1:
return True
for x in range(0,len(nums)-1):
if nums[x+1]<=nums[x]:
return False
return True
def judgelength(nums):
if judge(nums):
return len(nums)
for t in range(len(nums),0,-1):
for x in range(0,len(nums)-t+1):
res=[]
for k in range(x,x+t):
res.append(nums[k])
if judge(res):
return t
if judgelength(nums)==3:
print(5)
else:
print(judgelength(nums))
|
4a130cf38c2a1e9034f1d05b11cbc48aa4225271 | epicarts/python3_practice | /programmers/12899.py | 276 | 3.578125 | 4 | '''
https://programmers.co.kr/learn/courses/30/lessons/12899
124 나라
'''
#3으로 나누됨
def solution(n):
return convert(n - 1)
def convert(n):
T = "124"
a,b = divmod(n,3)
if a == 0:
return T[b]
else:
return convert(a-1) + T[b]
|
4d0508e30885cf44a76ce69e38cfca87985c97eb | ezzatisawesome/python-practice | /objects.py | 2,157 | 4.59375 | 5 | class Parent:
"""A class representing a parent"""
def __init__(self, fName="",lName=""):
self.fName = fName
self.lName = lName
fName = ""
lName = ""
def printName(self):
print("Full Name: " + self.fName + " " + self.lName)
class Mom(Parent):
"""A class representing a mom"""
def __init__(self, fName="", lName="", dressSize=0):
self.dressSize = dressSize
self.fName = fName
self.lName = lName
dressSize = -1
def printInfo(self):
self.printName()
print("Dress Size: " + str(self.dressSize))
class Dad(Parent):
"""A class representing a dad"""
def __init__(self, fName="", lName="", numScrewdrivers=0):
self.numScrewdrivers = numScrewdrivers
self.fName = fName
self.lName = lName
numScrewdrivers = -1
def printInfo(self):
self.printName()
print("Number of screwdrivers: " + str(self.numScrewdrivers))
class Pet():
"""A class representing a pet"""
def __init__(self, name=""):
self.name = name
name = ""
def printName(self):
print('Name: ' + self.name)
class Cat(Pet):
"""A class representing a cat"""
def __init__(self, name="", color="unknown"):
self.name = name
self.color = color
color = ""
def printInfo(self):
self.printName()
print('Color: ' + self.color)
class Dog(Pet):
"""A class representing a dog"""
def __init__(self, name="Dog", pantingRate=-1):
self.name = name
self.pantingRate = pantingRate
pantingRate = -1
def printInfo(self):
self.printName()
print('Panting rate: ' + str(self.pantingRate))
# Declare test objects
testParent = Parent('Pewdie', 'Pie')
testMom = Mom('Cruella', 'Deville', 12)
testDad = Dad('Arnold', 'Schwarzeneggar', 15)
testCat = Cat('Fluffly', 'yellow and pink')
testDog = Dog('Max', 100)
# Print info about test objects
print('***Printing info about test objects***\n')
testParent.printName()
testMom.printInfo()
testDad.printInfo()
testCat.printInfo()
testDog.printInfo()
input()
|
0c3983d70370120ced32632553ebc508489ad750 | NicolasB2/Python_Workshops | /Lab_2 (Vaccination scheme)/model.py | 1,102 | 3.59375 | 4 | class clinic:
def __init__(self):
self.patients = {}
def addPatient(self,patient):
self.patients[patient.name] = patient
def findPatient(self,name):
return self.patients.get(name)
class patient:
def __init__(self,name,age,stratum):
self.name = name
self.age = age
self.stratum = stratum
self.scheme = scheme()
def add_vaccine(self,vaccine):
self.scheme.add_Vaccine(vaccine)
def report(self):
return "Name: %s \nAge: %s \nScheme: %s\n" %(self.name,self.age,self.scheme.vaccines.__len__())
def reportScheme(self):
return self.scheme.report()
class scheme:
def __init__(self):
self.vaccines = []
def add_Vaccine(self,vaccine):
self.vaccines.append(vaccine)
def report(self):
r = ""
for x in self.vaccines:
r += "\t"+x.report()+"\n"
return r;
class vaccine:
def __init__(self,cost,name):
self.cost = cost
self.name = name
def report(self):
return ("Name: %s Cost: %s")%(self.name,self.cost)
|
2a2c650e9db7261dc9e1034fe16bbb2cc8e16932 | Anands-88/ownpracticedCodes | /narcissistic Number.py | 901 | 4.1875 | 4 | # Narcissistic Number
# Defining a function
def narcissistic_number():
total = 0 # set a variable and make it 0
number = int(input()) # Ask user to enter and convert it into INT
for digit in str(number): # use For loop to pick a digit and use str() Here digit will be str
total = total + int(digit) ** len(str(number)) # Convert digit into int and find the len of the number
# then do exponentiation. The loop automatically saves it to total var
return total == number # return total and check if the number equals total
print(narcissistic_number()) # call the function and print the output which returned from the function
# 2nd method(shortcut and minimum lines) using list comprehension
def narcissistic_number():
number = int(input())
return number == sum([int(digit) ** len(str(number)) for digit in str(number)])
print(narcissistic_number())
|
2056a85cc6037d2d5d26a0829d41da6d03a44d62 | WustAnt/Python-Algorithm | /Chapter3/3.3/3.3.3/stack_1.py | 851 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/8/1 10:02
# @Author : WuatAnt
# @File : stack_1.py
# @Project : Python数据结构与算法分析
"""
Stack()使用列表保存数据,默认将列表的头部作为栈的顶端
"""
class Stack:
"""
Stack():创建空栈
.push(item):将一个元素添加到栈的顶端
.pop():将栈顶端的元素移除,返回一个参数item
.peek():返回栈顶端的元素
.isEmpty():检查栈是否为空,返回布尔值
.size():返回栈中元素的数目
"""
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop(0)
def peek(self):
return self.items[0]
def size(self):
return len(self.items)
|
ff488792f4e8382fd680633b2f63be49677d73ac | hsiaotingluv/20181221_Python | /20200329 (file).py | 2,772 | 4.21875 | 4 | #Nested while loop (error trapping and robustness)
"""
maleSum = 0
femaleSum = 0
ans = 'y'
while (ans == 'y' or ans == 'Y'):
point = int(input("Enter the point: "))
sex = input("Enter sex: ")
while (sex != 'm' and sex != 'f'):
sex = input("Error. Enter sex (m or f): ")
if sex == 'm':
maleSum += point
else:
femaleSum += point
ans = input("Type y to continue, n to stop: ")
print("Total points for the male team:", maleSum)
print("Total points for the female team:", femaleSum)
"""
#Tutorial 2C
"""
#1
factorial = 1
num = int(input("Enter an integer: "))
N = num
while N > 1:
factorial *= N
N -= 1
print("The factorial of", num, "is", factorial)
"""
'''
A = float(input("Enter number to find square root: "))
X = float(input("Enter approximation: "))
epsilon = float(input("Enter epsilon: "))
error = epsilon
while error >= epsilon:
X = (X + A/X) / 2
error = abs(X - A/X) #abs for absolute
print(X)
'''
'''
#2
approx = 0
A = float(input("Enter a positive integer for approximating the square root: "))
while A <= 0:
print("Error. Please enter a postive real value.")
A = float(input("Enter a positive integer for approximating the square root: "))
X = float(input("Enter a positive approximation: "))
while X <= 0:
print("Error. Please enter a postive real value.")
X = float(input("Enter a positive approximation: "))
epilson = float(input("Enter the specified error allowance, epsilon: "))
while epilson <= 0:
print("Error. Please enter a postive real value.")
epilson = float(input("Enter the specified error allowance, epsilon: "))
approx = (X + A / X) / 2
while (X - A / X != epilson or A / X - X != epilson):
X = approx
approx = (X + A / X) / 2
print("The approximation square root of", A, "is", approx)
'''
"""
#3
ans = input("Enter item name or xyz to stop: ")
bill = 0
while ans != "xyz":
price = float(input("Enter price per item: "))
num = int(input("Enter quantity: "))
sumPrice = price * num
bill += sumPrice
print(num, ans, "\t", "$", end = "")
print("%.2f" % round(sumPrice, 2))
ans = input("Enter item name or xyz to stop: ")
print("Total bill", "\t", "$", end = "")
print("%.2f" % round(bill, 2))
"""
'''
file = open("test.txt", "r")
text = file.readlines()
print(text)
file = open("test.txt", "r")
for line in file:
line = line.strip() #remove \n #strip only the sides
a, b, c = line.split(",") #split the variables between the ","
print(a)
file.close()
'''
'''
file = open("test.txt", "w") #"w" will clear the file entirely
for i in range(4):
file.write("Hello World") #can only write string
file.write("!" * i)
file.write("\n")
file.close() #must close the file
'''
|
e0d131362c14190441946289999080b3412678f0 | JDHINCAMAN/Python_examples | /juego con tortuga 5.py | 295 | 3.546875 | 4 | import turtle
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "white", "green", "blue"]
name = ("juan")
for x in range(80):
t.pencolor(colors[x%4])
t.penup()
t.forward(x*4)
t.pendown()
t. write(name, font=("arial", int((x+4)/4), "bold"))
t.left(95)
|
b50cc63acf94d948b6202645969df1d6253fb7cd | amenoyoya/pyrpn | /main.py | 397 | 3.703125 | 4 | # encoding: utf-8
from libs.rpn import RPN
# 組み込み変数
variables = {
'HALF': 0.5,
'TEN': 10,
}
# 逆ポーランド記法で計算実行
## [1 2 + HALF - TEN * 1 2 / /]
## => ((1 + 2 - HALF) * TEN) / (1 / 2)
## => ((1 + 2 - 0.5) * 10) / (1 / 2)
## => 50.0
exp = [1, 2, '+', 'HALF', '-', 'TEN', '*', 1, 2, '/', '/']
answer = RPN.eval(exp, variables)
print(RPN.explain(answer))
|
4f74e75ad15d5c218f2382471266ea95b23ee434 | Nadim-Nion/Python-Programming | /Abstraction.py | 1,154 | 4.4375 | 4 | '''Abstract Method:When a method hasn't any body ,
then the method is called abstract method
Abstract Class:When a class contains an abstract method ,
then the class is called abstract class
We can't create and declare a object for any abstract class
Abstraction: Abstraction is used to hide the internal functionality of the function
from the users. The users only interact with the basic implementation
of the function, but inner working is hidden.
User is familiar with that "what function does" but they don't know "how it does."
'''
from abc import ABC,abstractclassmethod
class Shape(ABC): #ABC stands for Abstraction Base Class
def __init__(self,dim1,dim2):
self.dim1=dim1
self.dim2=dim2
@abstractclassmethod
def area(self):
pass
class Triangle(Shape):
#_init()
# area()
def area(self):
area=0.5*self.dim1*self.dim2
print("Area of Triangle=",area)
class Rectangle(Shape):
#_init()
# area()
def area(self):
area=self.dim1*self.dim2
print("Area of Rectangle=",area)
#S=Shape(10,20)
#S.area()
T=Triangle(10,20)
T.area()
R=Rectangle(10,20)
R.area() |
6ccecbe86f72168ec5158b6a57f175dc5b5c5737 | YashAgrawalforproject/Jarvis-AI | /main.py | 1,854 | 3.578125 | 4 | import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
engine = pyttsx3.init()
def speak(audio):
engine.say(audio)
engine.runAndWait()
def time_():
Time = datetime.datetime.now().strftime("%I:%M:%S")
speak("The current time is")
speak(Time)
def date_():
year = datetime.datetime.now().year
month = datetime.datetime.now().month
date = datetime.datetime.now().day
speak("The current date is")
speak(date)
speak(month)
speak(year)
def wishme():
speak("Welcome back MAK!")
time_()
date_()
#Greetings
hour = datetime.datetime.now().hour
if hour >= 6 and hour < 12:
speak("Good Morning Sir!")
elif hour>=12 and hour<18:
speak("Good Afternoon Sir!")
elif hour>=18 and hour<24:
speak("Good Evening Sir!")
else:
speak("Good Night Sir!")
speak("Jarvis at your service.Please tell me how can i help you today?")
def TakeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening.....")
r.pause_threshhold = 1
audio = r.listen(source)
try:
print("Recognizing.....")
query = r.recognize_google(audio,language='en-US')
print(query)
except Exception as e:
print(e)
print("Say that again please....")
return "None"
return query
if __name__ == "__main__":
wishme()
while True:
query = TakeCommand().lower()
if 'time' in query:
time_()
elif 'date' in query:
date_()
elif 'wikipedia' in query:
speak("Searching.....")
query=query.replace('wikipedia', '')
result = wikipedia.summary(query,sentences=3)
speak('According to Wikipedia')
print(result)
speak(result)
|
9a9553582b76f0bd3dfd40c8309bbe4f27699c6b | abespitalny/CodingPuzzles | /Leetcode/remove_linked_list_elements.py | 611 | 3.703125 | 4 | '''
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
'''
from leetcode import *
class Solution:
# Time: O(n)
# Space: O(1)
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(-1)
dummy.next = head
prev = dummy
ptr = dummy.next
while ptr != None:
if ptr.val == val:
prev.next = ptr.next
else:
prev = ptr
ptr = ptr.next
return dummy.next
|
a36701217d10a2e7a16ffcf3721c60ca5c63e1e4 | chihhua-liu/Python_Basic | /demo68.py | 523 | 3.84375 | 4 | class Team:
name = "Normal Team"
t1 = Team()
t2 = Team()
print(t1.name, t2.name, Team.name)
t1.name = 'Mobile R&D' # 實例 can overwrite
print(t1.name, t2.name, Team.name)
Team.name = 'standard team' # class can overwrite ,but 實例 first 不會改變
print(t1.name, t2.name, Team.name)
del t1.name # del 實例屬性後。 實例屬性=class屬性
print(t1.name, t2.name, Team.name)
t1.size = 7
t2.location = 'Taichung'
print(t1.size, t1.name, t2.location, t2.name) |
ce8b66aa9979fcf3c606a1dbef6946caea8ede6c | Rayhun/python-learning-repository | /while.py | 446 | 3.625 | 4 | ''' while loop '''
# i = 1 # loop starting value
# summation = 0 # 15, 5
# while i < 5:
# summation += i
# i = i + 1 # in, dec
# print(summation)
st_num = 0
# while st_num < 5:
# print("bd cse solved")
# st_num = st_num + 1
# while st_num < 5:
# st_num = st_num + 1
# if st_num == 4:
# continue
# print("rayhan" ,st_num)
result = 0 #res 3
num = 3 #num 4
for i in range(2):
result = result + num
num = num + 1
print(num) |
690901a43fc43a72638b155602570a86dd24f26f | mjh09/python-code-practice | /bishop_pawn.py | 469 | 3.65625 | 4 | def bishopAndPawn(bishop, pawn):
"""
Determines if a pawn is in range of a bishop
Parameters:
bishop (str) : letter/number coordinate ('a1')
pawn (str) : letter/nuber coordinate ('b2')
Returns:
Bool
"""
bish, paw = list(bishop), list(pawn)
letter_range = abs(ord(bish[0]) - ord(pawn[0]))
num_range = abs(int(bish[1]) - int(paw[1]))
if letter_range == num_range:
return True
return False |
6a590a86e614f2147e57aae9e92cc6117c198d5f | sandesh32/Data-Structures-and-algos | /Sorting_algos/python/Insertion_sort.py | 299 | 3.5 | 4 | def insertion(arr, n):
for i in range(1,n):
min_ind = arr[i]
j=i-1
while(j>=0 and arr[j]>min_ind):
arr[j+1] = arr[j]
j=j-1
arr[j+1] = min_ind
return arr
n=int(input())
l=list(map(int, input().strip().split()))[:n]
print(insertion(l,n)) |
3f90fa29e0e2fd3cd5f90cad4eaa3caaf5e3da81 | mitsuk-maksim/tg_mpei_course | /791. Custom Sort String.py | 212 | 3.53125 | 4 | # https://leetcode.com/problems/custom-sort-string/
class Solution:
def customSortString(self, S: str, T: str) -> str:
return "".join(sorted(T, key = lambda char: S.index(char) if char in S else 0))
|
fcbdf2209747dfd9fb2218a2609348bd8e0aabde | hhoangphuoc/data-structures-and-algorithms | /algorithm-questions/dynamic_programming/matrix_chain_multiplication.py | 2,403 | 4.34375 | 4 | # -*- coding: UTF-8 -*-
# Matrix chain multiplication
'''
Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not
actually to perform the multiplications, but merely to decide in which order to perform the multiplications.
Example:
Input: p[] = {40, 20, 30, 10, 30}
Output: 26000
There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30. Let the input 4 matrices be A, B, C and D.
The minimum number of multiplications are obtained by putting parenthesis in following way (A(BC))D -->
20*30*10 + 40*20*10 + 40*10*30
'''
import sys
def matrix_multiplication(array):
'''Recursive implementation to find the minimum cost of matrix multiplication'''
min_cost = sys.maxint
if len(array) < 3:
return 0
for i in range(1, len(array)-1):
cost = (array[i-1] * array[i] * array[i+1]) + matrix_multiplication((array[:i] + array[i+1:]))
if cost < min_cost:
min_cost = cost
return min_cost
def matrix_multiplication_2(arr, i, j):
'''Recursive implementation by passing indexes in the argument'''
if i == j:
return 0
min_count = sys.maxint
for k in range(i, j):
count = matrix_multiplication_2(arr, i, k) + matrix_multiplication_2(arr, k+1, j) + arr[i-1]*arr[k]*arr[j]
if count < min_count:
min_count = count
return min_count
def matrix_dynamic(arr):
'''Minimum count of matrix multiplication using dynamic implementation'''
n = len(arr)
# Initialize n * n matrix with None
mat = [[0] * n for i in range(n)]
# Considering all the possible chain lengths
for L in range(2, n):
for i in range(n-L+1):
j = i+L-1
# Cost would be zero when multiplying one matrix
if i == j:
matrix[i][j] = 0
else:
mat[i][j] = sys.maxint
for k in range(i, j):
res = mat[i][k] + mat[k+1][j] + arr[i-1] * arr[k] * arr[j]
if res < mat[i][j]:
mat[i][j] = res
return mat[1][n-1]
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
self.array = [40, 20, 30, 10, 30]
def test_recursive_matrix_multiplication(self):
self.assertEqual(matrix_multiplication(self.array), 26000)
def test_recursive_matrix_multiplication_2(self):
self.assertEqual(matrix_multiplication_2(self.array, 1, len(self.array)-1), 26000)
def test_matrix_dynamic(self):
self.assertEqual(matrix_dynamic(self.array), 26000)
if __name__ == "__main__":
unittest.main()
|
cb4a36e0dd66aba13562c28f24b9fb0b247e4a9e | nikhilsingh90/hello-world | /nuggets_calculator.py | 2,148 | 4.03125 | 4 | """
Calculates the packs of nuggets required
"""
def nuggets(number):
"""
Finds a combination of nugget packs (6,9,20) to purchase a given number of nuggets
Args: limit = the number of nuggets needed
Returns: a string
"""
try:
limit = int(number)
assert type(limit) == int, "input value is not an integer"
assert limit>=0, "input value is negative"
for c in range(int(limit/20)+1):
for b in range(int(limit/9)+1):
for a in range(int(limit/6)+1):
n=6*a+9*b+20*c
if n==limit:
return "6 packs = %s, 9 packs = %s, 20 packs = %s" %\
(str(a),str(b),str(c))
return "No soltuion for %s nuggets." % str(limit)
except:
return "An error occured, make sure you enter an Integer."
def test():
"""
This is a test for the nuggets function
"""
input("Testing 55")
answer = nuggets(55) #test 1
print (str(answer))
input("Testing 65")
answer = nuggets(65) #test 2
print (str(answer))
input("Testing 17")
answer = nuggets(17) #test 3 with no results
print (str(answer))
input("Testing 1210")
answer = nuggets(1210) #test 4 with large number
print (str(answer))
input("Testing 'h'")
answer = nuggets('h') #test 4 error due to string
print (str(answer))
input("Done Testing! Hit enter to exit")
def main():
print ("Nugget Program")
print ("="*30)
print ("")
user_input= str(input("Test or Run"))
if user_input.lower() == 'test':
print ("")
test()
else:
while True:
print ("")
user_input2= input("How many nuggets do you want for your party? (Type 'q' to exit): ")
if user_input2.lower() == 'q':
break
print("")
answer = nuggets(user_input2)
print (str(answer))
print ("")
if __name__ == "__main__":
main()
|
a6c2d569a9d1276524406d6bf44fab73987a3c24 | wooyeon1212/wooyeon1212 | /prblem 6.py | 141 | 3.546875 | 4 | Sum=0
for a in range(1,101):
b=a**2
Sum+=b
Sum2=0
for a in range(1,101):
Sum2+=a
realSum=Sum2**2-Sum
print realSum
|
3251029b16adc96cf95a2d6d1064fcdb1dfd3205 | PhilipeRLeal/pyBKB_v2 | /UBOS_2014/example_threshold_method.py | 1,996 | 4 | 4 | """
Brian Blaylock
Summer Research 2014
Using ceilometer aerosol backscatter thresholds to determind
the boundary layer heights.
This code is a simple example of using the threshold method
for estimating the boundary layer heights. Here we plot the
backscatter for a single observation. A threshold backscatter
value is subjectivity chosen as the height of the PBL.
"""
# Brian Blaylock
# Summer Research 2014
# Plot backscatter profile and threshold method
year = '2014'
month = '02'
day = '06'
station = 'URHCL'
from pydap.client import open_url
dataset = open_url("http://asn.mesowest.net/data/opendap/PUBLIC/"+year+"/"+month+"/"+day+"/"+station+"_"+year+month+day+".h5")
print('\n')
BackScatter = dataset['data']['BS'][:]
print BackScatter.shape
#pprint.pprint( BackScatter )
import numpy as np
import matplotlib.pyplot as plt
# Find threshold Function
# This will find the layer based on the threshold paramater
def find_threshold_index(threshold,profile):
current_index_height = 0 # start at 50 m
for i in profile:
print i
if i < threshold:
break
else:
current_index_height += 1
return current_index_height
# Simple Threshold Method
################################
bot_ind=0
top_ind=100
for i in range(100,200):
profile = BackScatter[i][bot_ind:top_ind]
threshold = -7.3
PBL_height = find_threshold_index(threshold, profile)*10
if PBL_height > 50:
print PBL_height
plt.figure(i)
plt.hold(True)
back1 = plt.plot(profile,np.arange(len(profile))*10)
thresh = plt.axvline(threshold, c='g',ls='--')
height = plt.axhline(PBL_height, c='r', linestyle='--')
plt.xlim([-8.5,-6.5])
plt.ylim([bot_ind*10, top_ind*10])
plt.legend((thresh,height),('Threshold value: '+str(threshold), 'Estimated Height: '+str(PBL_height)),loc='lower left')
plt.title('Mixed Layer Height Estimation: Threshold Method')
plt.xlabel('Backscatter (m^-1 * sr^-1)')
plt.ylabel('Height (m)')
plt.show() |
f5e3ecc2c7a50c0057f4919c337afefc73a509a1 | danorel/rental-predictor | /project/labaratory/preprocessing.py | 1,294 | 3.5 | 4 | import pandas as pd
import ast
from sklearn.preprocessing import StandardScaler
def scale_features(
df,
numeric_features
) -> pd.DataFrame:
"""
Scale the numerical features and return the pandas data frame with that modifications
:type df: pd.DataFrame
:type numeric_features: list
"""
scaled_features = df[numeric_features]
scaled_features = StandardScaler() \
.fit_transform(scaled_features)
df[numeric_features] = scaled_features
return df
def substitute(
df,
substitute_features
) -> pd.DataFrame:
"""
Substitute features with len property
:type df: pd.DataFrame
:type substitute_features: list
"""
for feature in substitute_features:
df[feature] = df[feature].map(lambda value: feature_to_len(feature, value))
return df
def feature_to_len(
feature,
value
):
"""
Extract the length of the feature
:type feature: str
:type value: object
"""
if not isinstance(value, object) or pd.isna(value) or pd.isnull(value):
return 0
if feature == 'description':
return len(str(value))
if feature == 'image_urls':
value = str(value)
value = ast.literal_eval(value)
return len(value)
return 0
|
a6f75bbcc1c07958fdb65ec2738ce141b9a158dc | 10125852/Python_Codes | /hourlyweather.py | 2,623 | 3.734375 | 4 | # Python code(Web scraping) to acquire Hourly Weather Data
# Python 3
import bs4 as bs
import urllib.request
import pandas as pd
import numpy as np
import csv
headers = ['Date', 'Time(EST)', 'Temp', 'Windchill', 'DewPoint', 'Humidity', 'Pressure', 'Visibility', 'WindDir', 'WindSpeed', 'GustSpeed', 'Precip', 'Events', 'Conditions']
# Empty list created to hold all hourly data that will be obtained in a dataframe for each day.
myDFs = []
for vYear in range(2016, 2017):
for vMonth in range(11, 13):
for vDay in range(1, 32):
# go to the next month, if it is a leap year and greater than the 29th or if it is not a leap year
# and greater than the 28th
if vYear % 4 == 0:
if vMonth == 2 and vDay > 29:
break
else:
if vMonth == 2 and vDay > 28:
break
# go to the next month, if it is april, june, september or november and greater than the 30th
if vMonth in [4, 6, 9, 11] and vDay > 30:
break
# defining the date string to export and go to the next day using the url
theDate = str(vYear) + "/" + str(vMonth) + "/" + str(vDay)
# Change Airport Location
theAirport = "KSFO"
theurl = "https://www.wunderground.com/history/airport/KSFO/" + theDate + "/DailyHistory.html"
dfs = pd.read_html(theurl)
# Hourly weather data table is the 4th table in the page. Define the dataframe to scrape.
table4 = dfs[4]
# Define Column Length
cLen = len(table4['Temp.'])
# Create a list of repeated date to append as a new column to the dataframe.
datelist = [theDate]
myDateList = datelist * cLen
#print(myDateList)
## Add a Date column to the data frame.
dateDF = pd.DataFrame([myDateList])
dateDFt = dateDF.transpose()
# To check transposed DFt
##print(dateDFt.head())
# Join 2 dataframes
myDF = dateDFt.join(table4)
# Append a dataframe object yeilded from above process to the list.
myDFs.append(myDF)
# Concatenate dataframes in the list and merge into one dataframe.
outputDF = pd.concat(myDFs)
# Write a csv file.
outputDF.to_csv("hourly_weather_SFO_1112_2016.csv")
|
4e79648f8a4267c1c5ed13b847576948d261a036 | raghupai/Python_Learning | /Python_Learning/IterationControlStructures/NestedLoopsVariation.py | 545 | 4.0625 | 4 | '''
Created on 07-May-2020
@author: raghuveer
'''
number_of_passengers=3
number_of_baggage=2
security_check=True
for passenger_count in range(1, number_of_passengers+1):
baggage_count =1
while (baggage_count<=number_of_baggage):
if(security_check==True):
print("Security check of passenger:", passenger_count, "-- baggage:", baggage_count,"baggage cleared")
else:
print("Security check of passenger:", passenger_count, "-- baggage:", baggage_count,"baggage not cleared")
baggage_count+=1 |
b67073b74b2103f0fb7fb5e31e7d5e0819f84299 | Vagacoder/Python_for_everyone | /Ch07/P7-7.py | 660 | 3.9375 | 4 | ##Ch07 P7.7
def checkWord(rawInputWord):
inputWord = rawInputWord.strip('.,;!?()').lower()
found = False
wordlist = open('words.txt', 'r')
for line in wordlist:
if inputWord in line:
found = True
break
if not found:
print(rawInputWord)
##
fileName = input('Please enter the name of file: ')
done = False
while not done :
try:
inFile = open(fileName, 'r')
done = True
except IOError:
print('Wrong file name, try again!')
for line in inFile:
words = line.split()
for word in words:
checkWord(word)
inFile.close()
|
06467f9a840ec996eedbe19c698e4d863719fcf6 | pastaTree/Data-Structures-and-Algorithms | /579_lowest_common_ancestor_iii.py | 1,437 | 4 | 4 | """579 Lowest Common Ancestor iii
Algorithm:
分治
Note:
"""
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param: root: The root of the binary search tree.
@param: A: A TreeNode in a Binary.
@param: B: A TreeNode in a Binary.
@return: Return the least common ancestor(LCA) of the two nodes.
"""
def __init__(self):
self.found = False
self.result = None
def lowestCommonAncestor3(self, root, A, B):
self.lowestCommonAncestor_helper(root, A, B)
return self.result
def lowestCommonAncestor_helper(self, node, A, B):
if node is None:
return 0
if self.found:
return
left = self.lowestCommonAncestor_helper(node.left, A, B)
right = self.lowestCommonAncestor_helper(node.right, A, B)
if left and right:
self.found, self.result = True, node
return
if left or right:
if node.val == A.val or node.val == B.val:
self.found, self.result = True, node
return
return 1
if node.val == A.val or node.val == B.val:
return 1
return 0
test_node = TreeNode(2)
test_node.left = TreeNode(1)
test_node.right = TreeNode(3)
sol = Solution()
print(sol.lowestCommonAncestor3(test_node, TreeNode(1), TreeNode(3)))
|
aba3b51d32076ad3b46d3d2c0c44558ad066984d | jimitogni/genetic_algorithm | /ga_frases.py | 2,865 | 3.890625 | 4 | #!/usr/bin/python
#coding: utf-8
import random
modelo = input("Digite o modelo: ")
tamanho_cromosomo = len(modelo)
tamanho_populacao = 100
geracoes = 50000
def peso_escolhido(items):
peso_total = sum((item[1] for item in items))
elemento = random.uniform(0, peso_total)
for item, peso in items:
if elemento < peso:
return item
elemento = elemento - peso
return item
#gera caracteres aleatórios para compor a populacao
def caracter_aleatorio():
return chr(int(random.randrange(32, 255, 1)))
#gera populacoes aleatórias de cromossomos com os caracteres aleatórios anteriores
def populacao_aleatoria():
populacao = []
for i in range(tamanho_populacao):
cromosomo = ""
for j in range(tamanho_cromosomo):
cromosomo += caracter_aleatorio()
populacao.append(cromosomo)
return populacao
#verifica a forca de um cromossomo, para saber se ele esta próximo ou não do que é esperado no modelo
def fitness(cromosomo):
fitness = 0
for i in range(tamanho_cromosomo):
fitness += abs(ord(cromosomo[i]) - ord(modelo[i]))
return fitness
#se o cromossomo ja for igual ao do modelo ele é mantido, se for diferente seu valor muda para outro que ainda não tenho passado pelo teste
def mutacao(cromosomo):
cromossomo_saida = ""
chance_mutacao = 100
for i in range(tamanho_cromosomo):
if int(random.random() * chance_mutacao) == 1:
cromossomo_saida += caracter_aleatorio()
else:
cromossomo_saida += cromosomo[i]
return cromossomo_saida
#cruzamento ou combinação de dois cromossomos gerando dois novos cromossomos
def crossover(cromosomo1, cromosomo2):
posicao = int(random.random() * tamanho_cromosomo)
return (cromosomo1[:posicao] + cromosomo2[posicao:], cromosomo2[:posicao] + cromosomo1[posicao:])
if __name__ == "__main__":
populacao = populacao_aleatoria()
for geracao in range(geracoes):
print("Geração %s | População: '%s'" % (geracao, populacao[0]))
peso_populacao = []
if(populacao[0] == modelo):
break
for individuo in populacao:
fitness_valor = fitness(individuo)
if fitness_valor == 0:
pares = (individuo, 1.0)
else:
pares = (individuo, 1.0 / fitness_valor)
peso_populacao.append(pares)
populacao = []
for i in range(int(tamanho_populacao)):
individuo1 = peso_escolhido(peso_populacao)
individuo2 = peso_escolhido(peso_populacao)
individuo1, individuo2 = crossover(individuo1, individuo2)
populacao.append(mutacao(individuo1))
populacao.append(mutacao(individuo2))
fit_string = populacao[0]
minimo_fitness = fitness(populacao[0])
for individuo in populacao:
fit_individuo = fitness(individuo)
if fit_individuo <= minimo_fitness:
fit_string = individuo
minimo_fitness = fit_individuo
print("População Final: %s" % fit_string)
|
918b00df4f44afe4682744b6c7cf0022046abee2 | varshabudihal/Leetcode-practice | /LinkedList/oddEvenList.py | 698 | 4 | 4 |
Problem:
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Solution:
class Solution:
def oddEvenList(self, head: ListNode):
if not head: return head
odd, even = head, head.next
evenHead = even
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = evenHead
return head
|
fb3abeafd05fa9f733668aed3059e7dbc925851e | apoorvaagrawal86/PythonLetsKodeIt | /PythonLetsKodeIt/Basic Syntax/string_methods_2.py | 651 | 4.1875 | 4 | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC', 1))
print(a.replace('abc', 'ABC', 2))
# Sub-Strings
# starting index is inclusive
# Ending index is exclusive
b = a[1]
print(b)
c = a[1:6]
print(c)
d = a[1:6:2]
print(d)
e = 'This is a string'
print(e)
print(e[:])
print(e[1:])
print(e[:6])
print(e[-1:])
print(e[-1])
print(e[:-1])
print(e[:len(e)])
print(e[::1])
print(e[::2])
# reverse string
print(e[::-1])
# cannot change the original string
e[1] = 'j'
# strings are immutable. You cannot change the memory allocation of a string. All changes are done at runtime.
|
26186aab49f23012ef817fa73a08e867675fecc4 | jayshah-07/30-days-of-Python-code-HackerRank | /Day_3 _ Intro_to_Conditional_Statements.py | 182 | 3.875 | 4 | #!/bin/python
import sys
N = int(raw_input().strip())
if N%2!=0:
print "Weird"
else:
if N in range(2,6) or N>20:
print "Not Weird"
else:
print "Weird"
|
afd060f8780c9b54e3377e0e7600f182b71c9a16 | swarnaprony/python_crash_course | /random_practice/working_with_list.py | 1,503 | 4.28125 | 4 | #working_with_list_practice
#date:04/03/2020
my_friends=["astu","lu","ri","mummum","shampu","nit"]
for friend_name in my_friends:
print(f"{friend_name.title()} is one of my friend")
print(f"wish to meet you soon {friend_name.title()}")
print("take care")
print(my_friends)
for value in range(-11,10):
print(value)
numbers=list(range(1,10))
print(numbers)
number_skipped=list(range(1,10,3))
even_numbers=list(range(2,20,2))
print(number_skipped)
print(even_numbers)
odd_numbers=list(range(1,20,2))
print(odd_numbers)
squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
qubes=[]
for values in range(1,20,3) :
qube=values**3
qubes.append(qube)
print(qubes)
qubic=[]
for numbers in range(2,11,2):
qubic.append(numbers**2)
print(qubic)
print(min(qubic))
print(max(squares))
print(sum(even_numbers))
square_list=[value**2 for value in range(1,11)]
print(square_list)
qube_list=[values**3 for values in range(20,41,5)]
print(qube_list)
print(qube_list[1:4])
print(qube_list[:4])
print(qube_list[1:])
print(qube_list[-2:])
#copied_qube_list=qube_list
copied_qube_list=qube_list[:]
print(copied_qube_list)
print(f"list of qube is {qube_list} \ncoppied qube list is {copied_qube_list}")
qube_list.append(" 100000")
copied_qube_list.append("200000")
print(qube_list)
print(copied_qube_list)
#tuples
new_tuple=("1","2","3")
print(new_tuple[1])
for value in new_tuple:
print(value)
new_tuple=("1","2","3","10")
for value in new_tuple:
print(value) |
e6969b05b531210b9c01ece71881f5ff40fa5109 | johnsonpthomas/python | /suminrange.py | 264 | 4.03125 | 4 |
def suminrange(a,b):
j = 0
for i in range(a,b+1):
#print(i)
j = j + i
print(j)
print('Sum of numbers between ' + str(a) + ' and ' + str(b) + ' is ' + str(j))
suminrange(1,2)
suminrange(1,3)
suminrange(1,4)
suminrange(1,5)
|
6667b49de44251700a4467fb7d2306d9bd14143a | Haruuuko/leetcode | /388.LongestAbsoluteFilePath.py | 2,947 | 4.03125 | 4 | '''
Suppose we abstract our file system by a string in the following manner:
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:
dir
subdir1
subdir2
file.ext
The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.
The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.
We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).
Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.
Note:
The name of a file contains at least a . and an extension.
The name of a directory or sub-directory will not contain a ..
Time complexity required: O(n) where n is the size of the input string.
Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
'''
import re
class Solution(object):
def lengthLongestPath(self, input):
"""
:type input: str
:rtype: int
"""
res, reslist = [], []
count = 1
arr = re.split('\n', input)
flist = arr[0:1]
if len(arr) >= 2:
for i in range(1, len(arr)):
flist += re.split('\t| ', arr[i])
for item in flist:
if item:
if count > len(res) + 1:
res.append(' ' * (count - len(res) - 1) + item)
elif count == len(res) + 1:
res.append(item)
elif count == len(res):
res[-1] = item
else:
res[count - 1:] = [item]
count = 1
if '.' in item:
reslist.append('/'.join(res))
else:
count += 1
if reslist == []: return 0
length = len(reslist[0])
for s in reslist:
if len(s) > length:
length = len(s)
return length
path = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
test = 'rzzmf\nv\n\tix\n\t\tiklav\n\t\t\ttqse\n\t\t\t\ttppzf\n\t\t\t\t\tzav\n\t\t\t\t\t\tkktei\n\t\t\t\t\t\t\thhmav\n\t\t\t\t\t\t\t\tbzvwf.txt'
print(Solution().lengthLongestPath(test))
|
2ba7f6b5fe885a76a95f5bf1d2baf359095bdc9a | rcanolorente/PythonLearning | /Python learning/Theory/Dictionaries.py | 1,671 | 4.25 | 4 | myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
print( 'My cat has ' + myCat['color'] + ' fur.')
#Unlike lists, items in dictionaries are unordered, therefore they cannot be sliced
spam = {12345: 'Luggage Combination', 42: 'The Answer'}
#Dictionaries can still use integer values as keys, just like lists use integers for indexes,
# but they do not have to start at 0 and can be any number.
#The keys(), values(), and items() Methods
spam = {'color': 'red', 'age': 42}
spam.keys()
for v in spam.values():
print(v)
for k in spam.keys():
print(k)
for i in spam.items():
print(i)
#Checking Whether a Key or Value Exists in a Dictionary
print('color' in spam.keys())
#It’s tedious to check whether a key exists in a dictionary before accessing that key’s value.
# Fortunately, dictionaries have a get() method that takes two arguments:
# the key of the value to retrieve and a fallback value to return if that key does not exist.
picnicItems = {'apples': 5, 'cups': 2}
print('I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.')
print( 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.')
# Because there is no 'eggs' key in the picnicItems dictionary, the default value 0 is returned by the get() method.
# Without using get(), the code would have caused an error message, such as in the following example:
spam = {'name': 'Pooka', 'age': 5}
spam.setdefault('color', 'black')
print(spam)
spam.setdefault('color', 'white') #When spam.setdefault('color', 'white') is called next, t
# he value for that key is not changed to 'white' because spam already has a key named 'color'.
print(spam)
spam = { 'cat' : 'soft'} |
9522d6f87e7edfb444c4ff5332c3c8d5f78da949 | Zadzi/Second | /tests.py | 1,528 | 3.59375 | 4 | import unittest
from calculator import CurrencyCalculator
class TestCurrencyCalculatorExist(unittest.TestCase):
def setUp(self):
self.calculator = CurrencyCalculator()
def testCurrencyCalculatorHasEuroExchangeRate(self):
assert self.calculator.euro_exchange_rate != None, "calculator euro_exchange_rate is None"
def testCurrencyCalculatorHasPoundExchangeRate(self):
assert self.calculator.pound_exchange_rate != None, "calculator pound_exchange_rate is None"
def testCurrencyCalculatorSetEuroExchangeRate(self):
self.calculator.setEuroExchangeRate(1.1)
assert self.calculator.euro_exchange_rate == 1.1, "calculator euro_exchange_rate did not set correctly"
def testCurrencyCalculatorSetPoundExchangeRate(self):
self.calculator.setPoundExchangeRate(502)
assert self.calculator.pound_exchange_rate == 502, "calculator pound_exchange_rate did not set correctly"
def testCurrencyCalculatrPoundsToPLN(self):
self.calculator.setPoundExchangeRate(4.6)
assert self.calculator.poundsToPLN(1) == 4.6, "calculator poundsTOPLN failed"
assert self.calculator.poundsToPLN(2) == 9.2, "calculator poundsTOPLN failed"
def testCurrencyCalculatorEurosToPLN(self):
self.calculator.setEuroExchangeRate(4.1)
assert self.calculator.eurosToPLN(1) == 4.1, "calculator eurosToPLN failed"
assert self.calculator.eurosToPLN(2) == 8.2, "calculator eurosToPLN failed"
if __name__ == "__main__":
unittest.main() |
9a80b6e0149648a4cb2039a1f60d26d1970799b3 | prasanna229/codes | /fibonaciiseries | 165 | 3.984375 | 4 | n = int(input("enter the value of n(number of iterations)"))
a = 0
b = 1
print(a)
print(b)
i = 0
for i in range(1,n+1):
print(b)
c = a+b
a = b
b = c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.