blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
06061280a8333db9d6b3aa747fd98ac8456c02e7 | poojithayadavalli/codekata | /word after article.py | 257 | 3.5625 | 4 | h=['the','a','an','A','An','The']
x=input().split()
y=[]
for i in range(len(x)):
if x[i] in h:
if (i+1)<len(x) and x[i]=='The':
y.append(x[i+1].capitalize())
elif (i+1)<len(x):
y.append(x[i+1])
print(' '.join(y))
|
3bc448474640ea1ea33ec5fc2c66ae813786389f | AmosFilho/-estcmp060- | /Árvore Fractal.py | 742 | 3.796875 | 4 | from turtle import *
speed('fastest')
rt(-90)
angle = 30
def fractal_tree(size, level):
if level > 0:
colormode(255)
# Splitting the rgb range for green into equal intervals for
# each level setting the colour according to the current level
pencolor(0, 255 // level, 0)
# Drawing the base
fd(size)
rt(angle)
# Recursive call for the right subtree
fractal_tree(0.8 * size, level - 1)
pencolor(0, 255 // level, 0)
lt(2 * angle)
# Recursive call for the left subtree
fractal_tree(0.8 * size, level - 1)
pencolor(0, 255 // level, 0)
rt(angle)
fd(-size)
fractal_tree(80, 7)
|
f1c0c46efba1ac1eeab2b8a6243a085ff5bb49e7 | giovannirosa/HackerRank | /TrocoSimples/entryTime.py | 1,861 | 3.921875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'entryTime' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING s
# 2. STRING keypad
#
def findIndexes(val, matrix):
return [(index, row.index(val))
for index, row in enumerate(matrix) if val in row][0]
def entryTime(s, keypad):
# 1) translate keyboard string to a matrix
kpMatrix = [[], [], []]
count = 0
index = 0
for k in keypad:
kpMatrix[index].append(k)
count += 1
if count > 2:
index += 1
count = 0
# 2) initialize values and walk through input keys
currKey = s[0]
totalTime = 0
for key in s:
# 2.1) get current and next indexes in matrix
currKeyIndex = findIndexes(currKey, kpMatrix)
nextKeyIndex = findIndexes(key, kpMatrix)
# 2.2) check if is same
if currKeyIndex[0] == nextKeyIndex[0] and currKeyIndex[1] == nextKeyIndex[1]:
currKey = key
continue
# 2.2) check if is same row
elif currKeyIndex[0] == nextKeyIndex[0]:
totalTime += abs(currKeyIndex[1] - nextKeyIndex[1])
# 2.3) check if differs more than 1 row
elif abs(currKeyIndex[0] - nextKeyIndex[0]) > 1:
totalTime += 2
# 2.4) check if differs exactly 1 row and differs less than 2 in column
elif abs(currKeyIndex[0] - nextKeyIndex[0]) == 1 and abs(currKeyIndex[1] - nextKeyIndex[1]) < 2:
totalTime += 1
# 2.5) any other case falls here
else:
totalTime += 2
currKey = key
# 3) returns total time
return totalTime
if __name__ == '__main__':
s = '423692'
keypad = '923857614'
result = entryTime(s, keypad)
print(result)
|
f3e601f60dd73770aa60c91a4758f08f5fa0f9c8 | Vijay-161/pythonProject1 | /vijay.py | 1,074 | 3.5 | 4 | from tkinter import *
root = Tk()
root.title("System")
root.iconbitmap("vj.ico")
root.maxsize(width=500, height=300)
root.minsize(width=300,height=200)
# root.geometry("500x300")
redbutton = Button(root, text="LEFT",fg="green",bg="yellow").pack(side=LEFT)
# redbutton.pack(side=LEFT)
greenbutton = Button(root,text = "RIGHT",fg="Black")
greenbutton.pack(side=RIGHT)
yellowbutton = Button(root,text = "UP",fg="blue")
yellowbutton.pack(side=TOP)
purplebutton = Button(root,text = "DOWN",fg="purple")
purplebutton.pack(side=BOTTOM)
# name = Label(root,text="Name").grid(row=0,column=0)
# e1 = Entry(root).grid(row=0,column=1)
# password = Label(root,text="Password").grid(row=1,column=0)
# e2 = Entry(root).grid(row=1,column=1)
# Login = Button(root,text="Login").grid(row=6,column=1)
# name = Label(root,text="Name").place(x=30,y=50)
# address = Label(root,text="Address").place(x=30,y=80)
# contact = Label(root,text="Contact").place(x=30,y=110)
# e1 =Entry(root).place(x=90,y=50)
# e1 =Entry(root).place(x=94,y=80)
# e1 =Entry(root).place(x=93,y=110)
root.mainloop()
|
0514fccd19f194a6169bc28e21771da55aaeab48 | Macmilonsaled/Primo | /Lesson1.py | 265 | 3.859375 | 4 | def even_or_odd(num):
if num % 4 == 0:
print("Dyelyatso na 4")
elif num % 2 == 0:
print("Chetnoe")
else:
print("Nechotnoye")
def main():
even_or_odd(int(input("Vvedite chislo ")))
if __name__ == "__main__":
main()
|
61668fd99d33e7a30792f327b06742b0758b112e | danielpza/codeforces-solutions | /71A - Way Too Long Words.py | 214 | 3.625 | 4 | #!/usr/bin/env python3
def abbr(word):
if len(word) <= 10:
return word
return word[0] + str(len(word) - 2) + word[-1]
amount = int(input())
for i in range(0, amount):
print(abbr(input()))
|
0bb704da0099869834b7e4f7dcec2faa8ace0a82 | ErsanSam/Data-Analyst-Career-Track | /4. Mengolah Dataset Dalam Jumlah Kecil sampai dengan Besar/Part 2/1. Penggabungan Series/4, join.py | 399 | 4 | 4 | import pandas as pd
df1 = pd.DataFrame({
'key':['k1','k2','k3','k4','k5'],
'val1':[200,500,0,500,100],
'val2':[30,50,100,20,10]
})
df2 = pd.DataFrame({
'key':['k1','k3','k5','k7','k10'],
'val3':[1,2,3,4,5],
'val4':[6,7,8,8,10]
})
#penerapan join dengan menggunakan set_index dan keyword how
join_df = df1.set_index("key").join(df2.set_index("key"),how='outer')
print(join_df) |
0cd9402ee4abc5d52422acf69d78f07f888c9c8f | enrico-secco/Python-Studies | /Sintaxe/1.3. Tuplas.py | 569 | 3.578125 | 4 |
# um_array = [] # Lista
# print(type(um_array))
#
# dicionarios = {} # Lista do tipo Dict
# print(type(dicionarios))
# Entendendo sobre tuplas
#Declaração de Listas do tipo Tuplas -> são dados fixos.
dias_da_semana=('Domingo','Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado') # -> convencional
dias_da_semana_2 = 'Domingo','Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'
# print(type(dias_da_semana))
# print(type(dias_da_semana))
# Tuplas de um único elemento
tupla1 = 'a',
tupla2 = ('b',)
print(type(tupla1))
print(type(tupla2))
|
13e94726844683a6138de6191e2e351d6635923e | mayur1101/Mangesh | /Python_Day4/Q6.py | 203 | 4.03125 | 4 | def Sum(number):
Last=number%10
first=0
while(number>=10):
number=number//10
first=number
return first + Last
number=int(input("Enter the number:"))
print(Sum(number)) |
c8e2fa85899e7bf965449305ca7a323da34b7480 | jfly/dotfiles | /homies/bin/dual_blueoot/util.py | 425 | 3.765625 | 4 |
def group_by(arr, *, unique=True, key):
grouped = {}
for el in arr:
k = key(el)
if unique:
assert k not in grouped, "The given key is not unique for the array"
grouped[k] = el
else:
if k not in grouped:
grouped[k] = []
grouped[k].append(el)
return grouped
def chunkify(arr, size):
return list(zip(*[iter(arr)]*size))
|
a0aeb81d7001765e1b26758e709c9b597b6471f7 | Marikyuun/AS91906 | /6. User Name Entry.py | 3,705 | 3.578125 | 4 | from tkinter import *
from functools import partial # To prevent unwanted windows
class Quiz:
def __init__(self):
# Formatting variables
background_color = "coral"
# Quiz Frame
self.quiz_frame = Frame(bg = background_color,
pady = 10)
self.quiz_frame.grid()
# Quiz Heading (row 0)
self.quiz_heading_label = Label(self.quiz_frame,
text = "Geography Quiz",
font = "calibri 16 bold", bg = background_color,
padx = 10, pady = 10)
self.quiz_heading_label.grid(row = 0)
# User Instructions (row 1)
self.quiz_instructions_label = Label(self.quiz_frame,
text = "Click on the button that "
"contains the correct answer."
"\n\nWhen you are ready press START.",
font = "calibri 10 italic", wrap = 290,
bg = background_color,
padx = 10, pady = 10)
self.quiz_instructions_label.grid(row = 1)
# Start Button (row 2)
self.quiz_start_button = Button(self.quiz_frame,
text = "START",
font = "calibri 16 bold", wrap = 290,
bg = "cyan",
padx = 10, pady = 10, command = self.name)
self.quiz_start_button.grid(row = 2)
def name(self):
Name(self)
class Name:
def __init__(self, parent):
background = "cyan"
# disable start button
parent.quiz_start_button.config(state = DISABLED)
# Sets up child window (ie: name entry box)
self.name_box = Toplevel()
# If users press cross at top, closes help and 'releases' help button
self.name_box.protocol('WM_DELETE_WINDOW', partial(self.close_name_entry, parent))
# Set up GUI Frame
self.name_frame = Frame(self.name_box, width = 300, bg = background)
self.name_frame.grid()
# Name Entry Heading (row 0)
self.name_label = Label(self.name_frame, font = "calibri 20 bold",bg = background, width = 30,
text = "Please Enter Your Username Below")
self.name_label.grid(row = 0)
# User Name Entry Box (row 1)
self.name_entry = Entry(self.name_frame, width = 30, bg = background, font = "calibri 16 bold", justify = 'center')
self.name_entry.grid(row = 1, pady = 20)
# User Name Submit Box (row 2)
self.name_submit_button = Button(self.name_frame, font= "calibri 16 bold", width = 30, pady = 5, bg = "coral",
text = "Submit", command = partial(self.name_record,parent))
self.name_submit_button.grid(row = 2, pady = 20)
def name_record(self, parent):
name = self.name_entry.get()
def close_name_entry(self, parent):
# Put help button back to normal...
parent.quiz_start_button.config(state = NORMAL)
self.name_box.destroy()
# main routine
if __name__ == "__main__":
root = Tk()
root.title("Geography Quiz")
something = Quiz()
root.mainloop()
|
f1e7c0429d6913856342195b067e94614fe24476 | LukaszSztuka/Jezyki-Skryptowe | /lab2/3-4.py | 168 | 3.625 | 4 | min = int(input("Podaj dolny zakres: "))
max = int(input("Podaj górny zakres: "))
for i in range(min, max+1):
if (i % 2) == 1 and (i % 17) == 0:
print(i)
|
9f2c8859ffea77df250724fb78baf04ea723f947 | manavkulshrestha/Computational_Physics | /1.24/euler.py | 257 | 3.5 | 4 | from numpy import exp, sin, cos, pi
def print_euler(alpha):
print(f'LHS = {exp((0+1j)*alpha)}\nRHS = {complex(cos(alpha),sin(alpha))}')
for i in range(0, 11):
print(f'{print_euler(i)}\n')
alpha = complex(input('Input alpha: '))
print_euler(alpha) |
2df09bd59db9e6e57567683ad76c8f978ab2344b | Aasthaengg/IBMdataset | /Python_codes/p03568/s588296033.py | 154 | 3.546875 | 4 | n = int(input())
A = list(map(int,input().split()))
even = odd = 0
for a in A:
if a%2:
odd += 1
else:
even += 1
print(3**n - 2**even)
|
fda5ddf205ad6f79ce3129be311bae0608fe7184 | Runsheng/bioinformatics_scripts | /wormbase/orthoget.py | 2,278 | 3.578125 | 4 | #!/usr/bin/env python
# Runsheng, 2016/01/25
# get a function to wrap all the para into one function to run in shell
import argparse
def ortho_to_list(orthfile):
gene_l=[]
with open(orthfile, "r") as f:
full_gene=f.read()
gene_l=full_gene.split("=")
return gene_l
def sp2_extract(gene_l, name):
"""
from the gene list, get the aim speciese out
para: gene_l, the file cutted after "=", leaving only the title and other
para: sp2name, the specie to query
"""
lines_new=[]
#lines=genestr.split("\n")
sp1_name=""
sp2_name=""
sp2_count=0
for block in gene_l:
sp2_count=0
if "#" not in block and (name+"\t") in block:
block_l=block.split("\n")
for line in block_l:
if line.startswith("WBGene"):
sp1_name=line.split("\t")[0]
if line.startswith(name):
sp2_name=line.split("\t")[1]
sp2_count+=1
lines_new.append((sp1_name,sp2_name))
if sp2_count>=2:
print name, "is 1:many orthlogs!"
else:
pass
return lines_new
if __name__=="__main__":
parser = argparse.ArgumentParser(description="""\n
To get the 1:n orthology pairs of C.elegans:human, using the orthology table for C.elegans \n
Example: python orthoget.py -f c_elegans.PRJNA275000.WS250.orthologs.txt -s Homo sapiens -o 2.txt #get the c.elegans orthlog with human form the file.
""")
parser.add_argument("--wormbase_orth_file","-f", help= "WormBase ortholog table can be fetched from wombase ftp directly")
parser.add_argument("--species_name", "-s")
parser.add_argument("--outfile", "-o")
args = parser.parse_args()
gene_l=ortho_to_list(args.wormbase_orth_file)
orth=sp2_extract(gene_l, args.species_name)
print("All gene number in the wormbase ortholog table file is %d" % len(gene_l))
print("The ortholog table with %s is %d long") % (args.species_name,len(orth))
with open(args.outfile, "w") as f:
for line in orth:
a,b=line
f.write(a+"\t"+b+"\n")
# example python orthoget.py -f "c_elegans.PRJNA275000.WS250.orthologs.txt" -s "Homo sapiens" -o 2.txt
|
2bf1c685885112fbcc584900f917fdd4cbe30064 | dbconfession78/interview_prep | /leetcode/65_valid_number.py | 1,553 | 4.09375 | 4 | # Instructions
"""
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
"""
import string
class Solution:
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
_len = len(s)
alpha = ['abcdfghijklmnopqrstuvwxyz']
nums = list('12345678990')
if _len == 1:
return s.isnumeric()
if all([x not in s for x in nums]):
return False
if s.startswith('e'):
return False
i = 0
while i < len(s):
while i < _len and s[i] not in nums:
i += 1
if i >= _len:
break
if s[i] in alpha:
return False
if s[i] == ' ':
if (s[i:] != (' ' * (_len - i))):
return False
i += 1
return True
def main():
print(Solution().isNumber("0")) # True
print(Solution().isNumber("0.1")) # True
print(Solution().isNumber("abc")) # False
print(Solution().isNumber("1 a")) # False
print(Solution().isNumber("2e10")) # True
print(Solution().isNumber(".")) # False
print(Solution().isNumber("1 ")) # True
print(Solution().isNumber(" ")) # False
print(Solution().isNumber(" 0")) # True
if __name__ == '__main__':
main() |
955381411cb7d7d39309c9d1706525cc26f6c861 | wattaihei/ProgrammingContest | /AtCoder/ABC-A/175probA.py | 137 | 3.9375 | 4 | S = input()
if S == "RRR":
ans = 3
elif S == "RRS" or S == "SRR":
ans = 2
elif "R" in S:
ans = 1
else:
ans = 0
print(ans) |
935c2e97f8fcadd8c0d60f930c552bfa32ea331f | Ujwal-Ramachandran/ITT-Lab | /Lab5/Q1a.py | 290 | 3.953125 | 4 | def cal(a,b,op):
if op=='+':
return a+b
elif op=='-':
return a-b
elif(op=='*'):
return a*b
elif(op=='/'):
return a//b
a,b= input("Enter 2 numbers : ").split()
op = input("Operation : ")
print(a,op,b,' = ',cal(int(a),int(b),op)) |
150c0bc58eb1d45c884859b265912012b1436dc4 | zdravkob98/Fundamentals-with-Python-May-2020 | /Programming Fundamentals Mid Exam - 29 February 2020 Group 1/02. MuOnline.py | 965 | 3.578125 | 4 | health = 100
bitcoin = 0
rooms = input().split('|')
for i in range( len(rooms)):
tolken = rooms[i].split(' ')
command = tolken[0]
number = int(tolken[1])
if command == 'potion':
if health == 100 :
print("You healed for 0 hp.")
elif health + number > 100:
print(f"You healed for {100 - health} hp.")
health = 100
else:
health += number
print(f"You healed for {number} hp.")
print(f"Current health: {health} hp.")
elif command == 'chest':
bitcoin += number
print(f"You found {number} bitcoins.")
else:
health -= number
if health > 0:
print(f"You slayed {command}.")
else:
print(f"You died! Killed by {command}." )
print(f"Best room: {i +1}")
break
if health > 0:
print(f"You've made it!")
print(f"Bitcoins: {bitcoin}")
print(f"Health: {health}")
|
4db813fc239442715c0b979041139723ddfa98e9 | CatmanIta/x-PlantForm-IGA | /turtles/turtle.py | 21,047 | 4.25 | 4 | """
Classes for drawing L-system structures.
The Turtle defines the points corresponding to the turtle representation of an L-system structure.
@author: Michele Pirovano
@copyright: 2013-2015
"""
import turtles.my_mathutils
import imp
imp.reload(turtles.my_mathutils)
from turtles.my_mathutils import *
from math import cos,sin,pi
import random
class Quad:
"""
This represents an oriented Quad.
"""
def __init__(self,pos,eul):
"""
@param pos: The position of the Quad
@param eul: The orientation of the Quad in euler angles
"""
self.pos = pos
self.eul = eul
class TurtleResult:
"""
A container for the results of drawing with a turtle.
"""
ID = 0
def __init__(self, instance_index, verts, edges, radii, leaves, bulbs, flowers, fruits):
self.idd = self.ID
self.ID += 1
self.instance_index = instance_index
self.verts = verts
self.edges = edges
self.radii = radii
self.leaves = leaves
self.bulbs = bulbs
self.flowers = flowers
self.fruits = fruits
def __str__(self):
s = "\nTurtle Result " + str(self.idd) + ":"
s += "\nVerts: " + str(len(self.verts))
s += "\nEdges: " + str(len(self.edges))
return s
class Turtle:
"""
A class that is used to convert a pL-String into a graphical structure.
"""
def __init__(self, verbose = False):
"""
Noise should be in the [0,1] range, with 0 meaning no noise and 1 meaning noise equal to the initial value.
"""
self.verbose = verbose
# Parameters that can be modified before drawing
self.angle = 30
self.step = 1
self.lengthNoise = 0
self.angleNoise = 0
self.randomSeed = None
self.defaultRadius = 0.1
self.tropism = (0,0,-1)
self.tropism_susceptibility = 0.4
self.elasticityDependsOnBranchRadius = False
self.heuristic_details_orientations = True # If True, the details will be oriented according to some heuristics, for better visual results
#TODO: self.force_radius_to_zero_on_ends = True
def loadParameters(self,turtleParameters):
"""
Loads parameters from a container.
"""
self.defaultRadius = turtleParameters.branch_radius
self.tropism_susceptibility = turtleParameters.tropism_susceptibility
def draw(self, structure, instance_index = 0, statisticsContainer = None):
"""
Draws from a pL-string
@note: the parameter structure must be a string, not a pString!
@param structure: The structure to convert into a graphical representation.
@param instance_index: Index of this instance in a set of randomized instances.
@param statisticsContainer: A container for statistics of this turtle, populated and then used externally.
"""
assert isinstance(structure,str), "The structure parameter must be a string"
# Statistics
saveStatistics = statisticsContainer is not None
if saveStatistics:
trunkWeightStatistic = 0 # Will be higher, the longer the trunk is
maxBranchWeightStatistic = 0 # Will be higher, the longer branches are (gets the maximum branch length)
undergroundWeightStatistic = 0 # Will be higher, the more the branch has vertices with y < 0
endLeavesCount = 0 # Will be higher, the more the leaves are towards the end-depth branches (ratio on the total number of leaves)
endBulbsCount = 0 # Will be higher, the more the bulbs are towards the end-depth branches (ratio on the total number of bulbs)
endFlowersCount = 0 # Will be higher, the more the leaves are flowers the end-depth branches (ratio on the total number of flowers)
fruitsCount = 0 # Will be higher, the more fruits are there (ratio on the total number of details)
detailsCount = 0 # Will be higher, the more generic details are there
if self.verbose: print("\nGot structure: " + structure)
# Each instance has a different seed (for randomization)
self.rnd = random.Random()
if self.randomSeed: self.rnd.seed(self.randomSeed+instance_index)
# Initializing the drawing
last_i = 0
tot_i = 0
index_stack = []
eul = Euler((0,0,0))
eul_stack = []
last_branch_euler = Euler((0,0,0))
pos = Vector((0,0,0))
pos_stack = []
leaves = [] # Array of leaves positions
bulbs = []
flowers = []
fruits = []
current_radius = self.defaultRadius
self.randoms = [] # Array of extracted random values
branch_depth = 0
branch_sizes = [self.defaultRadius] # Array of radii of each branch depth level, can be used for weight computation
branch_lengths = [0] # Array of lengths for each branch depth level, can be used for weight computation
radii_stack = []
radii = []
verts = []
edges = []
firstPointAdded = False
i = 0 # We'll iterate over all the characters
while i < len(structure):
c = structure[i]
if self.verbose: print("\nChecking character " + c + " at " + str(i))
if c == '!':
# Change branch radius
value, i = self.extractParameter(structure,i,self.defaultRadius)
value = max(1,value)
if self.verbose: print("CURRENT RADIUS: " + str(current_radius))
if c == 'F':
# Go forward, drawing an edge
value, i = self.extractParameter(structure,i,self.step)
# Randomize
rndValue = self.getRandom(last_i)
value = value + value*rndValue*self.lengthNoise
# Apply
up = Vector((0,0,1))
direction = Vector((0,0,1))
#print("Dir up rot: " + str(direction))
#print("Current rotation eulers: " + str(eul))
direction.rotateEul(eul) # Segment's heading
#print("Dir after rotation: " + str(direction))
# Add tropism: bend towards the tropism vector
# Vector tropism model (see "The Algorithmic Beauty of Plant" and "L-systems, Twining Plants, Lisp")
#branch_length = value
if self.elasticityDependsOnBranchRadius: elasticity = 1/current_radius
else: elasticity = 1
if self.tropism_susceptibility > 0:
tropism_vector = Vector(self.tropism)
#print("DIR: " + str(direction))
#print("tropism: " + str(tropism_vector*self.tropism_susceptibility*elasticity))
bending_quaternion = self.getQuaternionBetween(direction,tropism_vector*self.tropism_susceptibility*elasticity)
direction.rotateQuat(bending_quaternion)
#print("Bending quaternion: " + str(bending_quaternion))
#print("Dir after bending: " + str(direction))
# Save the new euler values
quaternion = self.getQuaternionBetween(up,direction)
#print("Quaternion from up to new dir: " + str(quaternion))
eul = quaternion.to_euler(eul) # Argument is the compatible euler
#print("New eul from quaternion: " + str(eul))
# Add the first point now, if needed
if firstPointAdded is False:
self.addPos(pos,verts,current_radius,radii)
firstPointAdded = True
# Add the new point
pos = pos+direction*value
self.addPos(pos,verts,current_radius,radii)
if self.verbose: print("Moving to " + str(pos) + " at direction " + str(direction) + " | index: " +str(last_i) + " to " + str(tot_i+1) + " with step " + str(value))
tot_i += 1
edges.append([last_i,tot_i])
last_i = tot_i
#print("CHECKING STACK: ")
#for p in pos_stack: print(p)
last_branch_euler = eul.copy()
if saveStatistics:
branch_lengths[branch_depth] += 1 # We sum the length of the branch for this depth level TODO: maybe add the 'value'? actual length?
branch_sizes[branch_depth] += current_radius # We sum the radius for each advancement of the branch for this depth level, we'll then average it
elif c == '+':
eul_delta, i = self.changeOrientation(structure,i,(1,0,0))
eul += eul_delta
elif c == '-':
eul_delta, i = self.changeOrientation(structure,i,(-1,0,0))
eul += eul_delta
elif c == '|':
eul.x += pi
elif c == '&':
eul_delta, i = self.changeOrientation(structure,i,(0,1,0))
eul += eul_delta
elif c == '^':
eul_delta, i = self.changeOrientation(structure,i,(0,-1,0))
eul += eul_delta
elif c == '\\':
eul_delta, i = self.changeOrientation(structure,i,(0,0,1))
eul += eul_delta
elif c == '/':
eul_delta, i = self.changeOrientation(structure,i,(0,0,-1))
eul += eul_delta
elif c == '[':
# Open a new branch
pos_stack.append(pos.copy())
eul_stack.append(eul.copy())
index_stack.append(last_i)
radii_stack.append(current_radius)
branch_depth+=1
if len(branch_lengths) <= branch_depth:
branch_lengths.append(0)
branch_sizes.append(current_radius)
else:
branch_lengths[branch_depth] = 0
branch_sizes[branch_depth] = current_radius
#print("Branching at " + str(pos) + " with index " + str(last_i))
#print("Pos stack has: ")
#for p in pos_stack:
# print(p)
#print("Orientation stack has: ")
#for p in orientation_stack:
# print(p)
elif c == ']':
# Close the latest open branch
#print("Pos stack had: ")
#for p in pos_stack:
# print(p)
if saveStatistics:
if branch_lengths[branch_depth] > maxBranchWeightStatistic:
maxBranchWeightStatistic = branch_lengths[branch_depth]
#print("Updated max branch weight to " + str(maxBranchWeightStatistic))
branch_depth-=1
last_pos = pos_stack[-1]
pos = last_pos.copy()
pos_stack = pos_stack[0:len(pos_stack)-1]#.remove(-1)
last_index = index_stack[-1]
last_i = last_index
index_stack = index_stack[0:len(index_stack)-1] #.remove(-1)
last_eul = eul_stack[-1]
eul = last_eul
eul_stack = eul_stack[0:len(eul_stack)-1]
last_radius = radii_stack[-1]
current_radius = last_radius
radii_stack = radii_stack[0:len(radii_stack)-1]
#print("Resuming from " + str(pos) + " with index " + str(last_i))
#print("Orientation stack has: ")
#for p in orientation_stack:
# print(p)
elif c == "L":
# This is a LEAF node, save its position and orientation
isEndPoint = self.checkIsEndPoint(i,structure)
tmp_eul = self.orientWithBranch(eul,last_branch_euler,isEndPoint)
q = Quad(pos.copy(),tmp_eul)
leaves.append(q)
if saveStatistics:
if isEndPoint: endLeavesCount += 1
detailsCount += 1
elif c == "B":
# This is a BULB node, save its position and orientation
isEndPoint = self.checkIsEndPoint(i,structure)
tmp_eul = self.orientWithBranch(eul,last_branch_euler,isEndPoint)
q = Quad(pos.copy(),tmp_eul)
bulbs.append(q)
if saveStatistics:
if isEndPoint: endBulbsCount += 1
detailsCount += 1
elif c == "K":
# This is a FLOWER node, save its position and orientation
isEndPoint = self.checkIsEndPoint(i,structure)
tmp_eul = self.orientWithBranch(eul,last_branch_euler,isEndPoint)
q = Quad(pos.copy(),tmp_eul)
flowers.append(q)
if saveStatistics:
if isEndPoint: endFlowersCount += 1
detailsCount += 1
elif c == "R":
# This is a FRUIT node, save its position and orientation
isEndPoint = self.checkIsEndPoint(i,structure)
tmp_eul = self.orientWithGround(eul, last_branch_euler, isEndPoint)
q = Quad(pos.copy(),tmp_eul)
fruits.append(q)
if saveStatistics:
if isEndPoint: fruitsCount += 1
detailsCount += 1
i+=1
#print(verts)
#print(edges)
result = TurtleResult(instance_index,verts,edges,radii,leaves,bulbs,flowers,fruits)
if saveStatistics:
trunkWeightStatistic = branch_lengths[0]
statisticsContainer.append(trunkWeightStatistic)
statisticsContainer.append(maxBranchWeightStatistic)
undergroundWeightStatistic = 0
for v in verts:
if v.z < 0: undergroundWeightStatistic += (-v.z)
statisticsContainer.append(undergroundWeightStatistic)
#print("Leaves: " + str(len(leaves)) + " of which ending: " + str(endLeavesCount))
#print("Flowers: " + str(len(flowers)) + " of which ending: " + str(endFlowersCount))
tot_details = len(leaves)+len(bulbs)+len(flowers)
if tot_details > 0: endDetails = (endLeavesCount + endBulbsCount + endFlowersCount)/tot_details
else: endDetails = 0
statisticsContainer.append(endDetails)
if detailsCount > 0: fruitsRatio = fruitsCount/detailsCount
else: fruitsRatio = 0
statisticsContainer.append(fruitsRatio)
# Branch size ratio is: 0 if the trunk and branches have similar radii, 1 if the branches have smaller radii and -1 if the trunk has smaller radius
for i in range(len(branch_sizes)):
#print("Brach size sum: " + str(branch_sizes[i]))
branch_sizes[i] = branch_sizes[i]/ max(1,branch_lengths[i])
#print("Brach size avg: " + str(branch_sizes[i]))
branch_deltas = [ (branch_sizes[i] - branch_sizes[i+1]) for i in range(len(branch_sizes)-1) ]
#print(branch_deltas)
if len(branch_deltas) > 0:
branch_size_ratio = sum(branch_deltas)/len(branch_deltas)
else:
branch_size_ratio = 0
branch_size_ratio = max(-1,min(1,branch_size_ratio))
statisticsContainer.append(branch_size_ratio)
"""
print("Branches statistics: ")
i = 0
for i in range(len(branch_sizes)):
s = "Depth " + str(i) + " size " + str(branch_sizes[i]) + " length " + str(branch_lengths[i])
if i < len(branch_sizes)-1:
s += " delta: " + str(branch_deltas[i])
print(s)"""
return result
def changeOrientation(self,structure,i,axisVector):
"""
Changes the orientation of the branch according to the chosen rotation
@param structure: The structure of the system
@param i: The current character's index
@param axisVector: The vector representing the axis of rotation
"""
value, i = self.extractParameter(structure,i,self.angle)
rnd_value = self.getRandom(i)
delta_value = self.angleNoise*rnd_value
value = value + delta_value*value
value = value/180*pi
eulOffset = Euler(axisVector)
#print("Orientation stack has: ")
#for p in orientation_stack:
# print(p)
if self.verbose: print("Rotating on " + str(eulOffset) + ": " + str(value) + " | (" + str(value*180/pi) + " deg)" + " results in " + str(eulOffset*value))
return eulOffset*value, i
def orientWithBranch(self,eul,last_branch_euler,isEndPoint):
"""
Returns a rotation oriented with a branch
"""
tmp_eul = eul.copy()
if self.heuristic_details_orientations: # Oriented according to the branch
if isEndPoint:
tmp_eul = last_branch_euler.copy() # Aligned to the last branch
else:
tmp_eul = last_branch_euler.copy() # Normal to the last branch
tmp_eul.rotate(Euler((90,0,0)))
return tmp_eul
def orientWithGround(self,eul,last_branch_euler,isEndPoint):
"""
Returns a rotation oriented towards the ground
"""
tmp_eul = eul.copy()
if self.heuristic_details_orientations: # Always oriented towards the ground
tmp_eul = Euler((0,0,0))
return tmp_eul
def checkIsEndPoint(self,i,structure):
"""
Check whether this is an end point (leaf node)
We need to make sure there is no F after this, before the branch closes!
Also, no branch must be opened!
"""
#print("Checking end point for node " + structure[i] + " at " + str(i))
tmp_i = i
#isEndPoint = True
while(tmp_i < len(structure)):
tmp_c = structure[tmp_i]
if tmp_c == "F" or tmp_c == "[":
#print("NO! Found another branch!")
return False
if tmp_c == "]":
#print("YES! Found end of branch!")
return True
tmp_i += 1
#print("YES! Found end of tree!")
return True
def getQuaternionBetween(self,u,v):
"""
Given two vectors, returns the quaternion representing the rotation between them.
From: http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors
"""
#print("U: " + str(u))
#print("V: " + str(v))
w = u.cross(v)
#print("CROSS: " + str(w))
d = u.dot(v)
#print("DOT: " + str(d))
q = Quaternion((1.0 + d, w.x, w.y, w.z));
#print("Q: " + str(q))
return q.normalized()
def getRandom(self,index):
""" Get a random value for the current 'branch depth' """
if index >= len(self.randoms):
rndValue = self.rnd.uniform(-1,+1)
self.randoms.append(rndValue)
else:
rndValue = self.randoms[index] # Re-use previously created random value
return float(rndValue)
def extractParameter(self,structure,i,default_value):
""" Extracts a parameter out of a piece of structure """
if i < len(structure)-1 and structure[i+1] == '(':
# Get the parameter value after this
param_value_string = ''
j=i+2
while True:
c2 = structure[j]
if c2 == ')':
break
else:
param_value_string += c2
j+=1
i = j # We place the index after the parameter
param_value = float(param_value_string)
if self.verbose: print("Found parameter: " + str(param_value))
return param_value, i
else:
return default_value, i
def addPos(self,v,verts,radius,radii):
""" Saves the current position of the turtle as a vertex """
verts.append(v.copy())
radii.append(radius)
def __str__(self):
s = ""
s += "\nTurtle:"
s += "\nAngle: " + str(self.angle)
s += "\nStep: " + str(self.step)
return s
if __name__ == "__main__":
print("Test turtle")
print("\nTEST - Creation")
t = Turtle(verbose = True)
print(t)
#s = "FFFL[LLF][++F]F(2)F(2)"
s = "!!+(39)F(2.2)!F(2)"
print("\nTEST - Drawing system " + s)
result = t.draw(s)
print(result)
print("\nEND TESTS")
#if renderResult: self.drawMesh(context,instance_index,verts,edges,radii,leaves,bulbs,flowers,fruits,suffix)
|
0c4d48c2f27ee22e7da1cb4cba70591503caf4de | jperilla/Machine-Learning | /Reinforcement Learning/car.py | 1,970 | 3.578125 | 4 | class Car:
def __init__(self, x, y, vx, vy, max_x, max_y):
self.position = CarPosition(x, y)
self.last_position = CarPosition(x, y)
self.velocity = CarVelocity(vx, vy)
self.last_velocity = CarVelocity(vx, vy)
self.max_x = max_x
self.max_y = max_y
def accelerate(self, ax, ay):
self.last_position = CarPosition(self.position.x, self.position.y)
self.last_velocity = CarVelocity(self.velocity.x, self.velocity.y)
self.velocity.accelerate(ax, ay)
self.__move()
def set_to_last_position(self):
self.position = self.last_position
def reset_velocity(self):
self.velocity.x = 0
self.velocity.y = 0
def get_state(self):
return tuple((self.position.x, self.position.y, self.velocity.x, self.velocity.y))
def set_state(self, state):
self.position.x = state[0]
self.position.y = state[1]
self.velocity.x = state[2]
self.velocity.y = state[3]
def __move(self):
self.position.x += self.velocity.x
self.position.y += self.velocity.y
# Limit to max values on track
if self.position.x < 0:
self.position.x = 0
if self.position.x >= self.max_x:
self.position.x = self.max_x - 1
if self.position.y < 0:
self.position.y = 0
if self.position.y >= self.max_y:
self.position.y = self.max_y - 1
class CarPosition:
def __init__(self, x, y):
self.x = x
self.y = y
class CarVelocity:
def __init__(self, vx, vy):
self.x = vx
self.y = vy
def accelerate(self, ax, ay):
if self.x + ax > 5:
self.x = 5
elif self.x + ax < -5:
self.x = -5
else:
self.x += ax
if self.y + ay > 5:
self.y = 5
elif self.y + ay < -5:
self.y = -5
else:
self.y += ay
|
dfe51d9008383ee0808d9c0042c7e1f35f37d36a | shivansamattya09/Pincode | /pincode.py | 653 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import csv
import numpy as np
import random
import math
state = input("Enter State : ")
df = pd.read_csv("/Users/shivanshamattya/Desktop/pincode/state1/" + state +".csv",)
# In[2]:
df.dropna(axis=0, how='any',inplace=True)
# In[3]:
district = df['DISTRICT'].to_numpy()
# In[4]:
district = np.array(district)
# In[5]:
pincode = df['PINCODE'].to_numpy()
pincode = np.array(pincode)
# In[6]:
ds = input("Enter Disctrict : ")
# In[7]:
for i in range(len(district)):
if district[i].lower()==ds.lower():
print(pincode[i])
# In[ ]:
# In[ ]:
|
c3f8a8de9149a49334627af33bc201cd7c66aa44 | HEroKuma/leetcode | /1604-least-number-of-unique-integers-after-k-removals/least-number-of-unique-integers-after-k-removals.py | 921 | 3.65625 | 4 | # Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
#
#
#
#
#
# Example 1:
#
#
# Input: arr = [5,5,4], k = 1
# Output: 1
# Explanation: Remove the single 4, only 5 is left.
#
# Example 2:
#
#
# Input: arr = [4,3,1,1,3,3,2], k = 3
# Output: 2
# Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
#
#
# Constraints:
#
#
# 1 <= arr.length <= 10^5
# 1 <= arr[i] <= 10^9
# 0 <= k <= arr.length
#
class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
from collections import Counter
count = sorted(Counter(arr).items(), key=lambda x: x[1])
removed = 0
for key, val in count:
if k >= val:
k -= val
removed += 1
else:
break
return len(count)-removed
|
66183b40c01c329f8bd0c8e986874a3ef374d523 | DenisRudakov0/Algorithm | /19 Угадайка слов.py | 4,785 | 3.65625 | 4 | from random import *
word_list = ['корабль', 'карандаш', 'медуза', 'грабитель', 'моряк', 'абонемент', 'авиасалон', 'бессонница',
'вакуум', 'велосипед', 'викторина', 'дрессировщик', 'жужелица', 'иероглиф', 'коктейль', 'крокодил']
def get_word(word_list):
return choice(word_list)
def display_hangman(tries):
stages = ['''
------
| |
| 0
| /|\\
| / \\
|
|
''',
'''
------
| |
| 0
| |\\
| / \\
|
|
''',
'''
------
| |
| 0
| |
| / \\
|
|
''',
'''
------
| |
| 0
| |
| \\
|
|
''',
'''
------
| |
| 0
| |
|
|
|
''',
'''
------
| |
| 0
|
|
|
|
''',
'''
------
| |
|
|
|
|
|
'''
]
return stages[tries]
def play(word):
print('Давайте начнем игру!')
word_completion = '_ ' * len(word) # строка, содержащая символы _ на каждую букву задуманного слова
guessed_letters = [] # список уже названных букв
guessed_words = [] # список уже названных слов
tries = 6 # количество попыток
word1 = word
while tries != 0:
print('Количество допустимых промахов: ', tries)
print(display_hangman(tries), 'Загаданное слово: ', word_completion)
s = input('Введите букву или слово: ').lower()
if s.isalpha() == True:
if len(s) == 1: # если 1 символ
if s not in guessed_letters:
guessed_letters.append(s)
if s in word:
for i in range(word.count(s)):
word_completion = word_completion[:word.index(s) * 2] + s + word_completion[word.index(s) * 2 + 1:]
word = word.replace(s, '1', 1)
if '_' not in word_completion:
return 'Поздравляем, вы угадали слово! Вы победили!'
else:
tries -= 1
print('К сожалению такой буквы нету. Попробуйте еще раз.')
else:
print('Вы уже вводили данный символ', guessed_letters)
continue
elif len(s) == len(word): # если слово целиком
if s not in guessed_words:
guessed_words.append(s)
if s == word1:
return 'Поздравляем, вы угадали слово! Вы победили!'
else:
tries -= 1
print('Вы не угадали =)')
else:
print('Вы уже вводили данное слово')
continue
else:
print('Вы ввели некоректные данные! Попробуйте еще раз.')
continue
print(display_hangman(tries))
return 'У вас не осталось больше попыток. К сожадению вы проиграли!'
while input('Начать новую игру? (y/n) ') == 'y':
word = get_word(word_list)
print(play(word))
print('Загаданное слово было: ', word)
print('Спасибо за игру. До встречи.')
|
fe2a5f6db97bfdb5509f3112a7ec50d1ce7d3a07 | Eazjay/Chaining_Methods | /chaining_methods.py | 965 | 3.84375 | 4 |
class User:
def __init__(self, first_name, last_name, age, account_balance):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.balance = account_balance
def make_deposit(self, amount):
self.balance += amount
return self
def make_withdrawal(self, amount):
self.balance -= amount
return self
def display_user_balance(self):
print(f"\n{self.first_name}'s account balance is: {self.balance}")
return self
Joel = User("Joel", "Okoh" ,35 ,500)
Joel.make_deposit(50).make_deposit(50).make_deposit(50).make_deposit(50).make_withdrawal(20).display_user_balance()
Babe = User("Katie", "Rose", 22, 50).make_deposit(50).make_deposit(100).make_withdrawal(10).make_withdrawal(20).display_user_balance()
Friend = User("Ossai", "J", 38, 450)
Friend.make_deposit(100).make_withdrawal(100).make_withdrawal(100).make_withdrawal(100).display_user_balance() |
c318a7baa3e8f3caa138ce383ba51652d8d934a0 | FaisalAlnahhas/Machine-Learning-Fall-18 | /K-means clustering.py | 4,339 | 4.15625 | 4 | ############################################
#Faisal Alnahhas
#k-means clustering
#UTA - Fall'18
#CSE 6363 - Machine Learning
#Assignment 3
############################################
# coding: utf-8
# In[23]:
import numpy as np
from sklearn import datasets
import pandas as pd
import random
# In[2]:
data = datasets.load_iris()
labels = data.target
print(type(data))
# In[24]:
print("Welcome to the k-means clustering for the Iris Data\n")
print("In this program you can choose any number between 1 and 150 (size of data set) to obtain accuracy for predicted output.\n")
print("The data can be obtained from: http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")
print("Or it can be imported from sklearn.datasets\n")
print("Please follow the prompt to see results.\n")
# In[3]:
df = pd.DataFrame(data= np.c_[data['data'], data['target']],
columns= data['feature_names'] + ['target'])
df = df.values
type(data)
print(type(df))
# In[25]:
Z = df[:, :4]
Z = Z.astype(np.float64)
Y = df[:, 4:5]
for i in range(50):
Y[i] = 1
for j in range(50,100):
Y[j] = 2
for j in range(100,150):
Y[j] = 3
Y = Y.astype(np.float64)
# In[6]:
num_clusters = int(input("How many clusters would you like? Please type a number between 1 and 10 \n"))
if num_clusters<1 or num_clusters>10 :
print("You can't have less than 1 cluster or greater 10: \n")
num_clusters = int(input("How many clusters would you like? Please type a number between 1 and 10 \n"))
# In[7]:
def random_generator(size, start, finish):
random_indeces = []
for i in range(size):
random_indeces.append(random.randint(start, finish))
return random_indeces
# random_generator(10, -10, 13)
# In[8]:
def euclidean_distance(centers, data):
norms = []
for i in range(len(centers)):
norms.append(np.linalg.norm(data-centers[i]))
return norms
# euclidean_distance(centroids, Z)
def make_centroids(num_clusters):
centeroid_indeces = random_generator(num_clusters, 0, len(Z))
# print(centeroid_indeces)
# print(len(centeroid_indeces))
centroids = []
for i in centeroid_indeces:
centroids.append(Z[i])
return centroids
centroids = make_centroids(num_clusters)
# In[10]:
def calc_distances(centers):
distances = {}
distance_list = []
min_index = []
for i in range(len(Z)):
distance = euclidean_distance(centroids, Z[i])
distance_list.append(min(distance))
min_index.append(np.argmin(distance))
# print((min_index))
# print(distance_list)
return distances, distance_list, min_index
# distances, distance_list, min_index = calc_distances(centroids)
# In[11]:
def make_clusters(distance_list, min_index):
clusters = {}
#unique elements in indeces to make dictionary
#if index[i] in dictionary, append element
unique = np.unique(min_index)
for i in unique:
clusters[unique[i]] = []
for k, v in clusters.items():
for i,j in zip(range(len(distance_list)), range(len(min_index))):
if min_index[j] == k:
v.append(distance_list[i])
return clusters
# clusters = make_clusters(distance_list, min_index)
# In[12]:
def cluster_size(cluster_dict):
clusters_size_list = []
for k,v in cluster_dict.items():
s = len(v)
clusters_size_list.append(s)
return clusters_size_list
# length_clusters = cluster_size(clusters)
# In[13]:
def calc_accuracy(t, a):
error = 0
t.sort()
# print(t)
for i in range(len(t)):
if t[i] != a[i]:
error += 1
error_percentage = (error/len(a))*100
print("accuracy = ", error_percentage, "%")
return error_percentage
# calc_accuracy(min_index, Y)
def update_centroids(clusters_dictionary):
for k,v in clusters_dictionary.items():
new_cluster = np.average(v)
clusters_dictionary[k] = new_cluster
return clusters_dictionary
# new_centroids = update_centroids(clusters)
for i in range(num_clusters):
distances, distance_list, min_index = calc_distances(centroids)
clusters = make_clusters(distance_list, min_index)
length_clusters = cluster_size(clusters)
new_centroids = centroids
new_centroids = update_centroids(clusters)
calc_accuracy(min_index,Y)
# In[ ]:
|
94de03141f724094e52e2f8dcbb246d26916383d | 2099454967/wbx | /04day/2-保护对象属性优化版.py | 437 | 3.515625 | 4 | class Dog():
def __init__(self):
self.__age = 1 #私有属性
pass
def wark(self):
print("汪汪叫")
def setAge(self,age):
if age <= 0:
print("传入年龄有误")
else:
self.__age = age
def getAge(self):
return self.__age
def __str__(self):
return "狗的年龄是%d"%self.__age
xiaohuang = Dog()
xiaohuang.setAge(-10)
#xiaohuang.__age = 10
print(xiaohuang.getAge())
print(xiaohuang)
xiaohuang.wark()
|
80983b7f7375608f7b6982287a0d8e8687402838 | julianaprado/forcaEuProfessor | /forcaEuProfessor.py | 4,694 | 3.671875 | 4 | import random
def forca(numRodadas):
lista = [ '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''',
'''
+---+
| |
O |
/|\ |
/ |
|
=========''',
'''
+---+
| |
O |
/|\ |
|
|
=========''',
'''
+---+
| |
O |
/| |
|
|
=========''',
'''
+---+
| |
O |
| |
|
|
=========''',
'''
+---+
| |
O |
|
|
|
=========''',
'''
+---+
| |
|
|
|
|
========='''
]
return lista[numRodadas]
def getPalavra():
palavras = ["Noite",
"Barba",
"Oriente",
"Temperatura",
"Ostra",
"Rodovia",
"Tomate",
"Estrutura",
"Vocal",
"Enigma",
"Escultor",
"Pendurado",
"Poema",
"Quarentena",
"Ficar",
"Casa",
"Tome",
"Cuidado",
"Fique",
"Bem",
"Sem",
"Festa",
"Junina",
"Aliens",
"Existem"]
return palavras[random.randint(0,len(palavras)-1)].upper()
def jogar():
palavra = getPalavra()
palavraCompleta = "_ " * len(palavra)
acertou = False
chutes=[]
tentativas = 6
while not acertou and tentativas > 0:
print(forca(tentativas) + "\n")
print(palavraCompleta + "\n")
print("Se quiser ver as letras que você já chutou aperte: '?'.")
chute = input("Qual letra você chuta?:\n").upper()
if chute.isalpha():
if chute == '=':
print("Essas são as letras que você já chutou: " + chutes + "\n")
if len(chute) == 1:
if chute in chutes:
print("Você já chutou essa letra: " + chute)
else:
if chute in palavra:
listaPalavraCompleta = palavraCompleta.split(" ")
indice = [i for i,letra in enumerate(palavra) if letra == chute]
novaPalavraCompleta = ""
palavraCompletaChecar = ""
print("Acertou a letra: "+ chute + "\n")
for index in indice:
listaPalavraCompleta[index] = chute
for i in range(len(listaPalavraCompleta)-1):
novaPalavraCompleta+= listaPalavraCompleta[i]
novaPalavraCompleta+=" "
palavraCompletaChecar+=listaPalavraCompleta[i]
palavraCompleta = novaPalavraCompleta
if palavraCompletaChecar == palavra:
acertou = True
else:
print("errou :(\n")
tentativas -= 1
chutes.append(chute)
elif len(chute) > len(palavra):
print("Resposta invalida.\n")
elif len(chute) == len(palavra):
if chute == palavra:
print("Você ganhou!!")
acertou = True
else:
print("Não é essa a palavra :(\n")
tentativas -= 1
else:
print("Resposta invalida insira uma letra, ou chute a palavra.\n")
else:
if chute == "?":
print("Você chutou essas letras: ")
print(chutes)
print("\n")
else:
print("Não aceitamos numeros.")
if acertou == True:
print("Parabens! Você acertou a palavra com " + str(tentativas) + " tentativa(s) sobrando.")
elif tentativas == 0 :
print("Você esgotou suas tentativas, a palavra era: " + palavra)
return
def main():
jogar()
while input("Deseja jogar novamente (S/N): \n").upper() == "S":
jogar()
return
main()
|
dbbf77a46a7f0cc7f43a7413ce0757b76a8ce251 | jbhennes/CSCI-220-Programming-1 | /Chapter 1/circleArea.py | 725 | 4.21875 | 4 | #Stalvey and class
#Purpose: This code calculates the area of a circle
# given the radius provided by the user
from math import *
def main():
print("Calculates the area of a circle.")
print()
#ask for input of radius
radius = input("Enter radius: ")
radius = eval(radius)
#calculate and output area
area = pi * radius * radius
print("Circle area =", area)
print("Sqrt of area =",sqrt(area))
## print("This is a new line.\n")
## print("Anlther\t\tvalue astlja lalksg kasey", end =" ")
## print("a;ljasld nfdsa ;ndsa jlkjlfdsag lask;nadia", end ="!!!!")
## print("lkdsajf lkdsaflkdsajflk jjdsaf daniel", end="Goodbye!")
## print("oahl nlvagas lkdsal")
main()
|
ace2857015f86348df519416f5d144ecf03a2f80 | leegangho/20190701 | /Python/other_다리를지나는트럭.py | 1,850 | 3.8125 | 4 | import collections
DUMMY_TRUCK=0
class Bridge(object):
def __init__(self,length,weight):
self._max_length=length
self._max_weight=weight
self._queue=collections.deque()
self._current_weight=0
def push(self,truck):
next_weight=self._current_weight+truck
if next_weight <= self._max_weight and len(self._queue) < self._max_length:
self._queue.append(truck)
self._current_weight=next_weight
return True
else:
False
def pop(self):
item=self._queue.popleft()
self._current_weight -= item
return item
def __len__(self):
return len(self._queue)
def __repr__(self):
return 'Bridge({}/{} : [{}])'.format(self._current_weight,self._max_weight,list(self._queue))
def solution(bridge_length,weight,truck_weight):
# Bridge 클래스를 사용해서 객체를 만들어냅니다.
# Bridge 클래스는 pop, push의 메서드 (기능)을 가지고 있습니다.
bridge=Bridge(bridge_length,weight)
# 트럭을 deque의 배열로 만들어 둡니다.
# 건너야할 트럭의 개수만큼!
trucks=collections.deque(w for w in truck_weight)
for _ in range(bridge_length):
bridge.push(DUMMY_TRUCK)
# 또한 다리 길이 만큼 만들어 둡니다.
# 최소 시간 카운트 시작!
count=0
while trucks:
bridge.pop()
if bridge.push(trucks[0]):
trucks.popleft()
else:
bridge.push(DUMMY_TRUCK)
count += 1
while bridge:
bridge.pop()
count += 1
return count
def main():
print(solution(2,10,[7,4,5,6]),8)
print(solution(100,100[10]),101)
print(solution(100,100,[10,10,10,10,10,10,10,10,10,10]),110)
#if __name__ == '__main__':
# main()
|
da9d235d2c26db945093380dd6a6b496c277aef4 | ajerit/python-projects | /laboratory1/Lab4/Lab04Ejercicio1.py | 1,190 | 3.890625 | 4 | #
# Adolfo Jeritson. 12-10523
#
# Descripcion: Dados los coeficientes de un polinomio, lo construye y
# muestra el grado del mismo
#
# 5/05/2015
#
# Variables
# coef : array(0,M] of int
# c: int
# M: int
# polinom: array[0, len(coef)+1) of str
# grado: int
# i: int
# Valores Iniciales
M = int(input("Introduza el valor de M (Limite del grado): "))
coef, polinom = [], []
for i in range(M+1):
c = int(input("Introduzca el coeficiente C" + str(i) + ": "))
if c == 0:
break
else:
coef.append(c)
# Precondicion
assert(M >= 0 and len(coef) <= M + 1)
# Calculos
for i in range(len(coef)):
if i == 0:
polinom.append(str(coef[i])) # El primer coeficiente no tiene variable
elif i == 1:
polinom.append(str(coef[i])+"X") # El segundo coeficiente es de grado 1
else:
polinom.append(str(coef[i])+"X^"+str(i))
if M == 0: # Consideramos el caso del polinomio cero
grado = 0
if coef == []:
polinom = [0]
else:
grado = len(coef) - 1
# Poscondicion
assert(grado <= M)
# Salida
print("El grado del polinomio es: " + str(grado))
print("La forma polinomial es: ")
for i in range(len(polinom)):
if i == len(polinom) - 1:
print(polinom[i])
else:
print(polinom[i]+"+", end="")
|
bab90ea66c283ac913ce142f60925e3c68c5615b | Superbeet/LeetCode | /Pinterest/English-formatted_Names.py | 3,615 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# list of names) and returns a string representing the English-formatted
# conjunction of those names.. more info on 1point3acres.com
#
# For example, given these names: ['Alice', 'Bob', 'Carlos', 'Diana'].
#
# The output would be: "Alice, Bob, Carlos and Diana"
def conjunctNames(names):
names = filter(None, names) # filter all meaningless charactres
line = ""
length = len(names)
for i in range(len(names)-1):
if i == len(names)-2:
line += names[i] +' and'
else:
line += names[i] +', '
if line == "":
line += names[length-1]
else:
line += ' ' + names[length-1]
return line
assert conjunctNames(["", "ab"]) == 'ab'
assert conjunctNames(["ab", ""]) == 'ab'
assert conjunctNames(['alex', 'peter', 'jeremy', 'joseph']) == 'alex, peter, jeremy and joseph'
assert conjunctNames(['alex', 'peter']) == 'alex and peter'
# Once the above is working, we iterate on the problem by adding a second
# argument to our function.
# This new argument is called `limit` and controls the maximum number of names
# that should be displayed. Any remaining items are "summarized" using the
# string "# more" (e.g. "Alice, Bob and 2 more" when `limit=2`)
def conjunctNames(names,li):
names = filter(None, names) # filter all meaningless charactres
line = ""
length = len(names)
limit = li
num = length - li
if num <= 0:
limit = length-1
for i in range(limit):
if names[i] == "":
continue
if i == limit-1:
line += names[i]+' and'
else:
line += names[i]+', '
if line == "":
line += names[length-1]
elif num > 0:
line += ' ' + str(num)+' more'
else:
line += ' ' + names[length-1]
return line
# print "[", conjunctNames(["ab"], 5),"]"
assert conjunctNames(["", "ab"], 5) == 'ab'
assert conjunctNames(["ab", ""], 5) == 'ab'
assert conjunctNames(['alex', 'peter', 'jeremy'], 2) == 'alex, peter and 1 more'
assert conjunctNames(['alex', 'peter', 'jeremy', 'joseph'], 2) == 'alex, peter and 2 more'
assert conjunctNames(['alex', 'peter', 'jeremy', 'joseph'], 3) == 'alex, peter, jeremy and 1 more'
assert conjunctNames(['alex', 'peter', 'jeremy', 'joseph'], 5) == 'alex, peter, jeremy and joseph'
assert conjunctNames(['alex', 'peter'], 5) == 'alex and peter'
# CODE READING(what's the purpose of this function)
def getFieldToItemsDict(list_of_items, field_name):
d = defaultdict(list)
for item in list_of_items:
d[getattr(item, field_name, None)].append(item)
#d[item.field_name].append(item)
return d
# find bug in this function, this is my corrected version, th bugs are some minor subscript bugs, note the edge cases
def sb(sorted_list, needle):
def sb_internal(low, high):
if not sorted_list:
return None
if low > high:
return None
pivot_pos = (low + high) / 2
if pivot_pos >= len(sorted_list):
return None
elif pivot_pos < 0:
return None
pivot = sorted_list[pivot_pos]
if needle == pivot:
return pivot
elif needle < pivot:
return sb_internal(low, pivot_pos)
else:
return sb_internal(pivot_pos + 1, high)
return sb_internal(0, len(sorted_list) - 1)
"""
2.二轮问了项目,preference,然后coding: code isBipartiteGraph,
注意robustness, graph can be not strongly connected.看代码习惯,
注意不让user有太多传进参数。这轮有点紧张,面得不好,跪了。
"""
|
bf7eaab5362146a9537816c5bd67b0b7944a2d04 | plazotronik/test_2 | /var.py | 268 | 3.65625 | 4 | #нзначаем переменную
var = 8
print( var )
# summa
var = var + var -13
print( var )
#new chislo
var = 3.142
print( var )
# string
var = 'Python in easy steps'
print( var )
#logical
var = True
print( var )
""" bolshoy commentariy
nerealno
bolshoy"""
|
675cd499c16d4a91a272c3e32752c5efda852178 | jchiefelk/ITEC-430 | /kyle/Homework4/set#2.py | 236 | 4 | 4 | #!/usr/bin/python
Stringlist = ["robot", "developer", "engineer", "AI", "data", "quantum", "computing", "statistics", "backend", "frontend"]
n = len(Stringlist)
#print len(Stringlist[2])
for x in range(n):
print len(Stringlist[x])
|
3a487097f8e75cf6c913aa2d837c66d310a82738 | tjscollins/algorithms-practice | /Python/Data Structures/bst.py | 3,002 | 3.96875 | 4 | class BSTNode:
def __init__(self, key, data):
self.key = key
self.data = data
self.left = None
self.right = None
self.parent = None
class BST:
def __init__(self):
self.root = None
self.size = 0
def insert(self, key, data):
if self.root is None:
self.root = BSTNode(key, data)
self.size += 1
else:
node = self.root
while node is not None:
if key < node.key:
if node.left is None:
node.left = BSTNode(key, data)
self.size += 1
node.left.parent = node
node = None
else:
node = node.left
elif key > node.key:
if node.right is None:
node.right = BSTNode(key, data)
self.size += 1
node.right.parent = node
node = None
else:
node = node.right
else:
# Ignore duplicate keys
node = None
def search(self, key):
node = self.root
while node is not None:
if key < node.key:
node = node.left
elif key > node.key:
node = node.right
else:
break
return node
def traverse_inorder(self):
out = []
node = self.root
while node.left is not None:
node = node.left
while node is not None:
out.append(node.key)
# print(out)
node = self.__next__(node)
return out
def delete(self, key):
node = self.search(key)
if node is not None:
if node.left is None or node.right is None:
if node is node.parent.left:
node.parent.left = node.left or node.right
if node.parent.left is not None:
node.parent.left.parent = node.parent
else:
node.parent.right = node.left or node.right
if node.parent.right is not None:
node.parent.right.parent = node.parent
return node
else:
n = self.__next__(node)
node.key, n.key = n.key, node.key
node.data, n.data = n.data, node.data
return self.delete(node.key)
def __next__(self, node):
if node.right is not None:
current = node.right
while current.left is not None:
current = current.left
return current
else:
current = node
while current.parent is not None and current is current.parent.right:
current = current.parent
return current.parent
|
f6aa43eb3031c8bf4392241742a8042203056b57 | TatsuLee/pythonPractice | /leet/singleLink.py | 1,407 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Node(object):
def __init__(self, val, next):
self.val = val
self.next = next
def show(self):
print "Showing list:"
current_node = self
while current_node is not None:
print current_node.val, "->",
current_node = current_node.next
print None
class SingleList(object):
head = None
tail = None
def show(self):
print "Showing list val:"
current_node = self.head
while current_node is not None:
print current_node.val, "->",
current_node = current_node.next
print None
def append(self, val):
node = Node(val, None)
if self.head is None:
self.head = node
else:
self.tail.next = node
self.tail = node
def remove(self, node_value):
current_node = self.head
previous_node = None
while current_node is not None:
if current_node.val == node_value:
# if this is the first node (head)
if previous_node is not None:
previous_node.next = current_node.next
else:
self.head = current_node.next
# needed for the next iteration
previous_node = current_node
current_node = current_node.next
|
6a91629a3c0dcfe993cb3ef9f66718a69a45e81f | nnininnine/Data_Structure_lab | /Test_Exam/testClass.py | 164 | 3.625 | 4 | from StackClass import stack
from Queue import queue
num = input('Enter your number : ').split()
l = queue()
for i in num:
l.enQueue(int(i))
print(l.mirror()) |
a4f2dce0a2d041b536435955ad980a993ce63570 | OkkarMin/approximate-computing-tool | /ErrorAnalyser/AdderErrorAnalyzer.py | 10,908 | 3.515625 | 4 | import random
import math
from . import ApproxAdders
## Error Calculations (AE, MAE, RMSE)
# HEAA
def HEAA(tot_num_bits, inaccurate_bits):
HEAA_estimate_AE = 0.0
HEAA_estimate_MAE = 0.0
HEAA_estimate_RMSE = 0.0
if tot_num_bits <= 10:
for num1 in range(2 ** tot_num_bits):
for num2 in range(2 ** tot_num_bits):
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HEAA_estimate_sum = ApproxAdders.HEAA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HEAA_estimate_AE += HEAA_estimate_sum - accurate_sum
HEAA_estimate_MAE += abs(HEAA_estimate_sum - accurate_sum)
HEAA_estimate_RMSE += (HEAA_estimate_sum - accurate_sum) ** 2
HEAA_estimate_AE /= 2 ** (2 * tot_num_bits)
print("HEAA average error", HEAA_estimate_AE)
HEAA_estimate_MAE /= 2 ** (2 * tot_num_bits)
print("HEAA mean absolute error", HEAA_estimate_MAE)
HEAA_estimate_RMSE /= 2 ** (2 * tot_num_bits)
HEAA_estimate_RMSE = math.sqrt(HEAA_estimate_RMSE)
print("HEAA Root Mean Square Error", HEAA_estimate_RMSE)
return (HEAA_estimate_AE, HEAA_estimate_MAE, HEAA_estimate_RMSE)
else:
print(
"\n Since Total Number of bits>10, \n \
Approximate Error Anaylsis is performed\n \
using million random input combinations...\n"
)
num_rand_values = 1000000
for it1 in range(num_rand_values):
num1 = random.randrange(2 ** tot_num_bits)
num2 = random.randrange(2 ** tot_num_bits)
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HEAA_estimate_sum = ApproxAdders.HEAA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HEAA_estimate_AE += HEAA_estimate_sum - accurate_sum
HEAA_estimate_MAE += abs(HEAA_estimate_sum - accurate_sum)
HEAA_estimate_RMSE += (HEAA_estimate_sum - accurate_sum) ** 2
HEAA_estimate_AE /= num_rand_values
print()
print("HEAA average error", HEAA_estimate_AE)
print()
HEAA_estimate_MAE /= num_rand_values
print("HEAA mean absolute error", HEAA_estimate_MAE)
print()
HEAA_estimate_RMSE /= num_rand_values
HEAA_estimate_RMSE = math.sqrt(HEAA_estimate_RMSE)
print("HEAA Root Mean Square Error", HEAA_estimate_RMSE)
print()
return (HEAA_estimate_AE, HEAA_estimate_MAE, HEAA_estimate_RMSE)
# HOERAA
def HOERAA(tot_num_bits, inaccurate_bits):
HOERAA_estimate_AE = 0.0
HOERAA_estimate_MAE = 0.0
HOERAA_estimate_RMSE = 0.0
if tot_num_bits <= 10:
print("\n Performing Accurate Error Anaylsis...\n")
for num1 in range(2 ** tot_num_bits):
for num2 in range(2 ** tot_num_bits):
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HOERAA_estimate_sum = ApproxAdders.HOERAA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HOERAA_estimate_AE += HOERAA_estimate_sum - accurate_sum
HOERAA_estimate_MAE += abs(HOERAA_estimate_sum - accurate_sum)
HOERAA_estimate_RMSE += (HOERAA_estimate_sum - accurate_sum) ** 2
HOERAA_estimate_AE /= 2 ** (2 * tot_num_bits)
print()
print("HOERAA average error", HOERAA_estimate_AE)
print()
HOERAA_estimate_MAE /= 2 ** (2 * tot_num_bits)
print("HOERAA mean absolute error", HOERAA_estimate_MAE)
print()
HOERAA_estimate_RMSE /= 2 ** (2 * tot_num_bits)
HOERAA_estimate_RMSE = math.sqrt(HOERAA_estimate_RMSE)
print("HOERAA Root Mean Square Error", HOERAA_estimate_RMSE)
print()
return (HOERAA_estimate_AE, HOERAA_estimate_MAE, HOERAA_estimate_RMSE)
else:
print(
"\n Since Total Number of bits>10, \n \
Approximate Error Anaylsis is performed\n \
using million random input combinations...\n"
)
num_rand_values = 1000000
for it1 in range(num_rand_values):
num1 = random.randrange(2 ** tot_num_bits)
num2 = random.randrange(2 ** tot_num_bits)
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HOERAA_estimate_sum = ApproxAdders.HOERAA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HOERAA_estimate_AE += HOERAA_estimate_sum - accurate_sum
HOERAA_estimate_MAE += abs(HOERAA_estimate_sum - accurate_sum)
HOERAA_estimate_RMSE += (HOERAA_estimate_sum - accurate_sum) ** 2
HOERAA_estimate_AE /= num_rand_values
print()
print("HOERAA average error", HOERAA_estimate_AE)
print()
HOERAA_estimate_MAE /= num_rand_values
print("HOERAA mean absolute error", HOERAA_estimate_MAE)
print()
HOERAA_estimate_RMSE /= num_rand_values
HOERAA_estimate_RMSE = math.sqrt(HOERAA_estimate_RMSE)
print("HOERAA Root Mean Square Error", HOERAA_estimate_RMSE)
print()
return (HOERAA_estimate_AE, HOERAA_estimate_MAE, HOERAA_estimate_RMSE)
# HOAANED
def HOAANED(tot_num_bits, inaccurate_bits):
HOAANED_estimate_AE = 0.0
HOAANED_estimate_MAE = 0.0
HOAANED_estimate_RMSE = 0.0
if tot_num_bits <= 10:
print("\n Performing Accurate Error Anaylsis...\n")
for num1 in range(2 ** tot_num_bits):
for num2 in range(2 ** tot_num_bits):
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HOAANED_estimate_sum = ApproxAdders.HOAANED_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HOAANED_estimate_AE += HOAANED_estimate_sum - accurate_sum
HOAANED_estimate_MAE += abs(HOAANED_estimate_sum - accurate_sum)
HOAANED_estimate_RMSE += (HOAANED_estimate_sum - accurate_sum) ** 2
HOAANED_estimate_AE /= 2 ** (2 * tot_num_bits)
print()
print("HOAANED average error", HOAANED_estimate_AE)
print()
HOAANED_estimate_MAE /= 2 ** (2 * tot_num_bits)
print("HOAANED mean absolute error", HOAANED_estimate_MAE)
print()
HOAANED_estimate_RMSE /= 2 ** (2 * tot_num_bits)
HOAANED_estimate_RMSE = math.sqrt(HOAANED_estimate_RMSE)
print("HOAANED Root Mean Square Error", HOAANED_estimate_RMSE)
print()
return (HOAANED_estimate_AE, HOAANED_estimate_MAE, HOAANED_estimate_RMSE)
else:
print(
"\n Since Total Number of bits>10, \n \
Approximate Error Anaylsis is performed\n \
using million random input combinations...\n"
)
num_rand_values = 1000000
for it1 in range(num_rand_values):
num1 = random.randrange(2 ** tot_num_bits)
num2 = random.randrange(2 ** tot_num_bits)
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
HOAANED_estimate_sum = ApproxAdders.HOAANED_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
HOAANED_estimate_AE += HOAANED_estimate_sum - accurate_sum
HOAANED_estimate_MAE += abs(HOAANED_estimate_sum - accurate_sum)
HOAANED_estimate_RMSE += (HOAANED_estimate_sum - accurate_sum) ** 2
HOAANED_estimate_AE /= num_rand_values
print()
print("HOAANED average error", HOAANED_estimate_AE)
print()
HOAANED_estimate_MAE /= num_rand_values
print("HOAANED mean absolute error", HOAANED_estimate_MAE)
print()
HOAANED_estimate_RMSE /= num_rand_values
HOAANED_estimate_RMSE = math.sqrt(HOAANED_estimate_RMSE)
print("HOAANED Root Mean Square Error", HOAANED_estimate_RMSE)
print()
return (HOAANED_estimate_AE, HOAANED_estimate_MAE, HOAANED_estimate_RMSE)
# M-HERLOA
def M_HERLOA(tot_num_bits, inaccurate_bits):
M_HERLOA_estimate_AE = 0.0
M_HERLOA_estimate_MAE = 0.0
M_HERLOA_estimate_RMSE = 0.0
if tot_num_bits <= 10:
print("\n Performing Accurate Error Anaylsis...\n")
for num1 in range(2 ** tot_num_bits):
for num2 in range(2 ** tot_num_bits):
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
M_HERLOA_estimate_sum = ApproxAdders.M_HERLOA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
M_HERLOA_estimate_AE += M_HERLOA_estimate_sum - accurate_sum
M_HERLOA_estimate_MAE += abs(M_HERLOA_estimate_sum - accurate_sum)
M_HERLOA_estimate_RMSE += (M_HERLOA_estimate_sum - accurate_sum) ** 2
M_HERLOA_estimate_AE /= 2 ** (2 * tot_num_bits)
print()
print("M_HERLOA average error", M_HERLOA_estimate_AE)
print()
M_HERLOA_estimate_MAE /= 2 ** (2 * tot_num_bits)
print("M_HERLOA mean absolute error", M_HERLOA_estimate_MAE)
print()
M_HERLOA_estimate_RMSE /= 2 ** (2 * tot_num_bits)
M_HERLOA_estimate_RMSE = math.sqrt(M_HERLOA_estimate_RMSE)
print("M_HERLOA Root Mean Square Error", M_HERLOA_estimate_RMSE)
print()
return (M_HERLOA_estimate_AE, M_HERLOA_estimate_MAE, M_HERLOA_estimate_RMSE)
else:
print(
"\n Since Total Number of bits>10, \n \
Approximate Error Anaylsis is performed\n \
using million random input combinations...\n"
)
num_rand_values = 1000000
for it1 in range(num_rand_values):
num1 = random.randrange(2 ** tot_num_bits)
num2 = random.randrange(2 ** tot_num_bits)
accurate_sum = ApproxAdders.accurate_adder(num1, num2, tot_num_bits)
M_HERLOA_estimate_sum = ApproxAdders.M_HERLOA_approx(
num1, num2, tot_num_bits, inaccurate_bits
)
M_HERLOA_estimate_AE += M_HERLOA_estimate_sum - accurate_sum
M_HERLOA_estimate_MAE += abs(M_HERLOA_estimate_sum - accurate_sum)
M_HERLOA_estimate_RMSE += (M_HERLOA_estimate_sum - accurate_sum) ** 2
M_HERLOA_estimate_AE /= num_rand_values
print()
print("M_HERLOA average error", M_HERLOA_estimate_AE)
print()
M_HERLOA_estimate_MAE /= num_rand_values
print("M_HERLOA mean absolute error", M_HERLOA_estimate_MAE)
print()
M_HERLOA_estimate_RMSE /= num_rand_values
M_HERLOA_estimate_RMSE = math.sqrt(M_HERLOA_estimate_RMSE)
print("M_HERLOA Root Mean Square Error", M_HERLOA_estimate_RMSE)
print()
return (M_HERLOA_estimate_AE, M_HERLOA_estimate_MAE, M_HERLOA_estimate_RMSE)
|
c40690532492e017e611074a1af7e749f819d2ac | sridharbe81/python_sample_program | /cont.py | 401 | 3.96875 | 4 |
# Normal Fibonacci
def fib(max):
numbers = []
a,b = 0,1
while a<max:
numbers.append(a)
a,b = b, a+b
return numbers
print(fib(10))
#Fibonacci using Generator
def fib(max):
a,b = 0,1
while a<max:
yield a
a,b = b, a+b
obj = fib(10)
print(obj)
print(next(obj))
print(next(obj))
print(next(obj))
print(next(obj))
|
f23e7b3ac47c92141928c3a1b6d83fee2b2bd2dc | dionysus/cryptography | /caesarCipher_V03.py | 1,265 | 4.1875 | 4 | # ----- Caeser Cipher v03 ----- #
LIBRARY = '?aZbY1cXdW2eVfU3gTh4SiRj5QkPl6OmNn7MoLp8KqJ9rIs0HtG uFvE,wDxC.yBzA!'
def encrypt(plaintext: str, keyphrase: int) -> str:
'''
Using the Ceaser Cipher method to shift the alpha characters of the string
plaintext in lowercase by the key amount, then return the encrypted string.
'''
ciphertext = ''
key_list = []
for ch in keyphrase:
key_list += [ord(ch)]
j = 0
while j in range(len(plaintext)):
key = key_list[j % len(key_list)]
index = LIBRARY.find(plaintext[j])
if index != -1:
ciphertext += LIBRARY[(index + key) % len(LIBRARY)]
else:
ciphertext += plaintext[j]
j += 1
return ciphertext
while True:
plaintext = str(input('Enter your message: '))
while True:
key = input('Enter a keyphrase: ')
if not key.isalnum():
print('Please use only letters a-Z and numbers 0-9.')
if len(key) < 8:
print('Key must be at least 8 characters long.')
if key.isalnum() and len(key) >= 8:
break
print ('\n' + encrypt(plaintext, key) + '\n') |
a3b2ee82b0496a2f85550fb08d2af35fe6ba377e | leofoch/PY | /ImfoPermanente.py | 2,230 | 3.546875 | 4 | import pickle
class Persona:
def __init__(self,nombre,genero,edad):
self.nombre=nombre
self.genero=genero
self.edad=edad
print("se creo una persona nueva con el mobre: ", self.nombre)
def __str__(self):
return "{} {} {}".format(self.nombre,self.genero,self.edad)
class ListaPersonas:
personas=[]
def __init__(self):
listaDePersonas=open("FicheroExterno","ab+")
listaDePersonas.seek(0)
try:
self.personas=pickle.load(listaDePersonas)
except:
print ("El fichero esta vacio")
finally:
print("finally")
listaDePersonas.close()
del(listaDePersonas)
def agregarPersonas(self,p):
print("Agrego")
self.personas.append(p)
self.guardarPersonasEnFicheroExterno()
def mostrarPersonas(self):
for i in self.personas:
print(i)
def guardarPersonasEnFicheroExterno(self):
listaDePersonas=open("FicheroExterno","wb")
pickle.dump(self.personas,listaDePersonas)
listaDePersonas.close()
del(listaDePersonas)
def MostrarInfoFicheroExterno(self):
print("la info del Fichero es la siguiente: ")
for p in self.personas:
print(p)
class ArchivoFuente:
lineasFuente=[]
def __init__(self):
listaFuente=open("FicheroFuente.txt","r")
try:
self.lineasFuente=listaFuente.readlines()
except:
print ("El fichero fuente esta vacio")
finally:
print("finally")
listaFuente.close()
del(listaFuente)
print(self.lineasFuente[0])
miFuente=ArchivoFuente()
miLista=ListaPersonas()
for i in miFuente.lineasFuente:
persona=miFuente.lineasFuente[0]
#persona=Persona("Juan","Masculino",78)
miLista.agregarPersonas(persona)
miLista.guardarPersonasEnFicheroExterno()
miLista.MostrarInfoFicheroExterno()
#p=Persona("Ana","Femenino",33)
#miLista.agregarPersonas(p)
#p=Persona("lia","Femenino",19)
#miLista.agregarPersonas(p)
#p=Persona("Juan","Masculino",78)
#miLista.agregarPersonas(p)
#miLista.mostrarPersonas()
|
e693ea0bd9e59f9d0f22e384ef0e364c634b2555 | andrewFisherUa/Advanced_Python_Course | /Lesson_6/lesson_6_practical.py | 4,784 | 4.0625 | 4 | # 1) Создать свою структуру данных Список, которая поддерживает
# индексацию. Методы pop, append, insert, remove, clear. Перегрузить
# операцию сложения для списков, которая возвращает новый расширенный
# объект.
class MyCustomList:
def __init__(self, *args):
self._list = list(*args)
def __str__(self):
return str(self._list)
def __setitem__(self, index, value):
self.insert(index, value)
def __getitem__(self, index):
if isinstance(index , int) and index <= len(self)-1:
return self._list[index]
raise IndexError("index out if range")
def __len__(self):
value = 0
for i in self._list:
value += 1
return value
def append(self, value):
self._list = self._list + [value]
def remove(self, value):
if value not in self._list:
raise ValueError(f"ho-ho, {value} not in mycustomlist")
else:
for i in self._list:
if i == value:
index = self._list.index(i)
del self._list[index]
break
def insert(self, index, value):
if index == 0:
self._list = [value] + self._list
elif index > len(self._list)-1 or -index < -len(self._list)-1:
raise IndexError("ho-ho, your index out of range")
elif index == len(self._list) - 1:
self._list = self._list + [value]
else:
self._list = self._list[:index] + [value] + self._list[index:]
def clear(self):
self._list = []
def pop(self, index=-1):
if index == -1:
value_to_return = self._list[-1]
self._list = self._list[0:-1]
return value_to_return
elif index > len(self._list)-1 or -index < -len(self._list)-1:
raise IndexError("ho-ho, your index out of range")
else:
value_to_return = self._list[index]
del self._list[index]
return value_to_return
def __add__(self, other):
return self._list + other._list
# # если задачей подразумевалось не использовать конструкцию выше, то можно, к примету так:
# new_list = []
# for i in self._list:
# new_list.append(i)
# for i in other._list:
# new_list.append(i)
# return new_list
my_list_obj = MyCustomList((10,20,30,40,50))
# append
my_list_obj.append(100)
print(my_list_obj)
# pop
print(my_list_obj.pop(2))
print(my_list_obj)
# insert
my_list_obj[0] = 111
print(my_list_obj)
print(my_list_obj[0])
# remove
print(my_list_obj.remove(10))
print(my_list_obj)
# clear
my_list_obj.clear()
print(my_list_obj)
my_list_obj = MyCustomList((10,20,30,40,50))
my_list_obj_2 = MyCustomList((1,2,3,4,5))
# __add__
print(my_list_obj + my_list_obj_2)
# 2) Создать свою структуру данных Словарь, которая поддерживает методы, get, items, keys, values.
# Так же перегрузить операцию сложения для словарей, которая возвращает новый расширенный объект.
class MyCustomDict:
def __init__(self, **kwargs):
self._dict = kwargs
def __str__(self):
return str(self._dict)
def __getitem__(self, key):
if key not in self._dict:
raise KeyError(f"ho-ho, there is no {key} in mycustomdict")
else:
return self._dict[key]
def items(self):
return_list = []
for i in self._dict:
return_list.append((i, self._dict[i]))
return return_list
def keys(self):
return_list = []
for i in self._dict:
return_list.append(i)
return return_list
def values(self):
return_list = []
for i in self._dict:
return_list.append(self._dict[i])
return return_list
def __add__(self, other):
for i in self._dict:
if i in other._dict:
raise KeyError("Ho-ho. Keys from 'left' odject intersect with keys from 'right' odject")
dict_to_return = self._dict
for i in other._dict:
dict_to_return[i] = other._dict[i]
return dict_to_return
my_dict_obj = MyCustomDict(a=1,b=2,c=3)
print(my_dict_obj)
#get
print(my_dict_obj['c'])
#items
print(my_dict_obj.items())
#keys
print(my_dict_obj.keys())
#values
print(my_dict_obj.values())
# __add__
my_dict_obj2 = MyCustomDict(g=4,f=5)
print(my_dict_obj + my_dict_obj2)
|
00178d59307cf8873bf456313b566380c1d96f16 | ericbollinger/AdventOfCode2017 | /Day11/second.py | 1,251 | 3.796875 | 4 | import math
def findWayBack(x,y):
cur = 0
while (x != 0 or y != 0):
if (x == y):
return cur + x / 0.5
if (x == 0):
return cur + math.fabs(x - y)
if (y == 0):
return cur + (math.fabs(x - y) * 2)
if (x > 0):
x -= 0.5
else:
x += 0.5
if (y > 0):
y -= 0.5
else:
y += 0.5
cur += 1
return cur
steps = []
with open('input.txt') as f:
steps = f.readline().strip()
steps = steps.split(",")
x = 0
y = 0
topX = 0
topY = 0
furthest = 0
for s in steps:
if (s == "n"):
y += 1
elif (s == "ne"):
y += 0.5
x += 0.5
elif (s == "se"):
y -= 0.5
x += 0.5
elif (s == "s"):
y -= 1
elif (s == "sw"):
y -= 0.5
x -= 0.5
elif (s == "nw"):
y += 0.5
x -= 0.5
if (math.fabs(x) > topX or math.fabs(y) > topY):
topX = math.fabs(x)
topY = math.fabs(y)
distance = findWayBack(x,y)
if (distance > furthest):
furthest = distance
print "x: " + repr(x)
print "y: " + repr(y)
print "Final: " + repr(int(findWayBack(x,y)))
print "Furthest: " + repr(int(furthest))
|
df1a32083dc76a3d79c0eaba26b7abf98a51b4f5 | aluhrs/Optimal_Bike_Share_Locations | /elevation.py | 6,699 | 3.9375 | 4 | """
This file:
1) Pulls elevation data from Google Maps API for all of the points in the Crowd_Sourced table in the database.
2) Reads the json data from Google Maps and updates the elevation column in the database with the elevation data.
3) Pulls the elevation data back out, creates a radius of about 3 block radius around each point
4) Calculates the elevation grade
5) Send back to the database a key to let the database know a point has been flagged as upvoted for elevation
"""
import config
import json
import math
import model
import os
import urllib2
# this should be inside of a function
points = model.session.query(model.CrowdSourced).all()
def get_location(points):
"""Encode the url"""
elevations = []
for point in range(len(points)):
if points[point].elevation == None:
if len(elevations) < 300:
# TODO - verify this will work
# get_elevation_from_GMAPI(points[point])
# id = points[point].id
# latitude = points[point].latitude
# longitude = points[point].longitude
# url = build_url(latitude, longitude)
# elevation_data = get_elevation(url)
# elevation = parse(elevation_data)
# TODO - see if this is till needed here - update_elevation(elevation_data)
curr = model.session.query(model.CrowdSourced).filter_by(id=id).one()
curr.elevation = float(elevation)
model.session.add(curr)
elevations.append(elevation)
model.session.commit()
#model.session.commit()
print "The elevations have been added to the database"
def get_elevation_from_GMAPI(point):
"""Builds the url needed to hit Google Maps API, reads the response from
Google Maps API and returns the elevation"""
id = point.id
latitude = point.latitude
longitude = point.longitude
url = build_url(latitude, longitude)
elevation_data = get_elevation(url)
elevation = parse(elevation_data)
return elevation
def build_url(latitude, longitude):
"""Use urllib2 to open the url"""
locations = str(latitude) + "," + str(longitude)
url = "https://maps.googleapis.com/maps/api/elevation/json?locations=%s&sensor=false&key="+config.GOOGLE_API_KEY
return url % locations
def get_elevation(url):
"""Get elevation for each point from Google Maps API"""
response = urllib2.urlopen(url)
json_data = json.loads(response.read())
return json_data
def parse(json_data):
"""Returns the elevation"""
return json_data["results"][0]["elevation"]
def create_file(data):
"""Creates a file and writes the Google Maps API Places data to it"""
new_file = open("./static/elevation.txt", 'w')
new_file.write(json.dumps(data))
new_file.close()
print "Your file elevation.txt has been created."
def calc_rise(dictionary):
"""Get the difference between the lowest and the highest. This is in meters"""
for d in dictionary:
if dictionary[d]["dictel"]["el"] != []:
#diff = max(dictionary[d]["list of elevations"])
maximum = dictionary[d]["dictel"]["el"]
original = dictionary[d]["el_o"]
dictionary[d]["eldiff"] = maximum - original
else:
dictionary[d]["eldiff"] = 0
return dictionary
def calc_run(dictionary):
"""Calculates the distance bewteen points"""
for d in dictionary:
if dictionary[d]["dictel"]["el"] > 0:
lat1 = dictionary[d]["lat_o"]
long1 = dictionary[d]["lng_o"]
lat2 = dictionary[d]["dictel"]["lat"]
long2 = dictionary[d]["dictel"]["lng"]
#Convert latitude and longitude to
#spherical coordinates in radians.
degrees_to_radians = math.pi/180.0
# phi = 90 - latitude
phi1 = (90.0 - lat1)*degrees_to_radians
phi2 = (90.0 - lat2)*degrees_to_radians
# theta = longitude
theta1 = long1*degrees_to_radians
theta2 = long2*degrees_to_radians
# Compute spherical distance from spherical coordinates.
# For two locations in spherical coordinates
# (1, theta, phi) and (1, theta, phi)
# cosine( arc length ) =
# sin phi sin phi' cos(theta-theta') + cos phi cos phi'
# distance = rho * arc length
cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +
math.cos(phi1)*math.cos(phi2))
# Remember to multiply arc by the radius of the earth
arc = (math.acos( cos )) * 6373000
dictionary[d]["distance"] = arc
return dictionary
def calc_elevation_grade(dictionary):
"""Calculte the elevation incline by dividing the rise by the run"""
for d in dictionary:
if dictionary[d]["eldiff"] != 0 and dictionary[d]["dictel"]["el"] > 0:
dictionary[d]["eldiffpercent"] = (dictionary[d]["eldiff"]/dictionary[d]["distance"]) * 100
else:
dictionary[d]["eldiffpercent"] = 0
return dictionary
def send_to_db_elevation(dictionary):
"""If the difference in Elevation is less than 5%, update
elevation_reason as True"""
for d in dictionary:
if dictionary[d]["eldiffpercent"] < 5:
id = d
upvote = model.session.query(model.CrowdSourced).filter_by(id=id).one()
upvote.elevation_reason = True
model.session.add(upvote)
print "Point with id %r has added elevation as a reason" % id
model.session.commit()
print "All of the points have been added to the db as elevation_reason."
def update_elevation():
"""If the elevation of the current point is similar to the elevation surrounding it
the point is flagged in the database as elevation_reason = True"""
the_app = model.CrowdSourced()
all_elevation = the_app.to_dict()
#print all_elevation
# for each point, get the elevation, and check for the elevation of
# surrounding data points within .004 range of each lat/lng
d = {}
for i in all_elevation:
lat_i = i["latitude"]
high_lat_i = lat_i + .002
low_lat_i = lat_i - .002
lng_i = i["longitude"]
high_lng_i = lng_i + .002
low_lng_i = lng_i - .002
d[i["id"]] = {}
d[i["id"]]["lat_o"] = lat_i
d[i["id"]]["lng_o"] = lng_i
d[i["id"]]["el_o"] = i["elevation"]
d[i["id"]]["dictel"] = {}
d[i["id"]]["dictel"]["el"] = 0
for j in all_elevation:
#print j
lat_j = j["latitude"]
lng_j = j["longitude"]
el_j = j["elevation"]
# if the lats and longs don't equal each other
if lat_i != lat_j and lng_i != lng_j:
# create a radius of .002 in any direction
if lat_j < high_lat_i and lat_j > low_lat_i and lng_j < high_lng_i and lng_j > low_lng_i:
if el_j >= d[i["id"]]["dictel"]["el"]:
d[i["id"]]["dictel"]["lat"] = lat_j
d[i["id"]]["dictel"]["lng"] = lng_j
d[i["id"]]["dictel"]["el"] = el_j
rise = calc_rise(d)
run = calc_run(rise)
percentage = calc_elevation_grade(rise)
upvoted = send_to_db_elevation(percentage)
return json.dumps(percentage)
if __name__ == "__main__":
#url = get_location(points)
elevation = update_elevation()
create_file(elevation) |
c0876e0d0736e58163e3360e3a26f6b26861fd8e | Digm74/pythonProject_rep | /var.py | 865 | 4.28125 | 4 | print('Варианты записи физических и логических строк')
print('''i=5 # Физическая строка на ней расположена логическая строка
print(i) # Физическая строка на ней расположена логическая строка''')
i=5 # Физическая строка
print(i) # Физическая строка
print('''a=45;print(a) # Физическая строка на которой записаны две логические строки''')
a=45;print(a) # Физическая строка на которой записаны две логические строки
print('Тоже самое ' '''Физическая строка на которой записаны две логические строки b=33;print(b);''')
b=33;print(b); |
e847ebbcba5a73040159704310aed86ca8c677e7 | j611062000/Coursera_Algo._Standford | /Graph Search, Shortest Paths, and Data Structures/medianMaintenance.py | 3,180 | 3.859375 | 4 | from heapDataStructure import Heap
def printHeap(HeapFormedian):
print("maxHeap.Heap=%s" % (HeapFormedian.maxHeap.Heap), end=" | ")
print("minHeap.Heap=%s" % (HeapFormedian.minHeap.Heap))
def printTop(HeapFormedian):
print(
"L Top:{} || R Top:{}".format(
HeapFormedian.leftTop,
HeapFormedian.rightTop))
class HeapFormedian:
"""
median
[max heap] [min heap]
smaller than median greater than median
"""
def __init__(self, dataset):
self.maxHeap = Heap([], "M")
self.minHeap = Heap([], "m")
self.leftTop = None
self.rightTop = None
self.median = None
for element in dataset:
self.addNode(element)
print("\n\n")
def addNode(self, node):
print("new node:", node)
if self.median is None:
self.median = node
self.minHeap.addNode(node)
elif node <= self.median:
self.maxHeap.addNode(node)
print("new node to left, because of <={}".format(self.median))
elif node > self.median:
self.minHeap.addNode(node)
print("new node to right, because of >{}".format(self.median))
print("before balanceing:", end=" ")
printHeap(self)
if not self.isBalance():
self.balanceing()
print("after balanceing :", end=" ")
printHeap(self)
# revising the top value of heaps respectively
self.reviseHeapTop()
printTop(self)
self.median = self.getMedian()
def isBalance(self):
rightnodes = len(self.minHeap.Heap)
leftnodes = len(self.maxHeap.Heap)
if (rightnodes - leftnodes) == 1 or (rightnodes - leftnodes) == 0:
return True
else:
return False
def reviseHeapTop(self):
lenOfLeftHeap = len(self.maxHeap.Heap)
lenOfRightHeap = len(self.minHeap.Heap)
if lenOfLeftHeap >= 2:
self.leftTop = self.maxHeap.Heap[1]
elif lenOfLeftHeap < 2:
self.leftTop = None
if lenOfRightHeap >= 2:
self.rightTop = self.minHeap.Heap[1]
elif lenOfLeftHeap < 2:
self.rightTop = None
def balanceing(self):
while not self.isBalance():
left_nodes = len(self.maxHeap.Heap)
right_nodes = len(self.minHeap.Heap)
if left_nodes > right_nodes:
self.minHeap.addNode(self.maxHeap.extract())
elif right_nodes > left_nodes:
self.maxHeap.addNode(self.minHeap.extract())
def getMedian(self):
assert self.isBalance
if self.rightTop is not None and self.leftTop is not None:
if len(self.maxHeap.Heap) == len(self.minHeap.Heap):
return (self.leftTop + self.rightTop) / 2
else:
return self.rightTop
else:
return self.rightTop
def test():
testData = [[10, 99, 100, 1, 2, 2, 4, 1, 0, 100, 88]]
for test in testData:
testcase = HeapFormedian(test)
if __name__ == "__main__":
test()
|
055ccfaef9fef5dad2cf63c86d560236745f6cc8 | kilbooky/hackerrank | /30days/11_2d_arrays.py | 1,798 | 3.75 | 4 | #!/bin/python3
import sys
# (provided by hackerrank -- get input into 2x2 array)
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
# now, sum values of each hourglass
#!/bin/python3
import sys
# (provided -- get input into 2x2 array)
arr = []
for arr_i in range(6):
arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')]
arr.append(arr_t)
# now, sum values of each hourglass
for i in range(len(arr)):
for j in range(len(arr[i])):
# make sure we're not indexing out of range (ie, i <= 3, j <= 3)
if (j > len(arr) - 3) or (i > len(arr) - 3):
break
# get values in hourglass pattern
tot = arr[i][j] + arr[i][j+1] + arr[i][j+2] + \
arr[i+1][j+1] + \
arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]
# unless its the first pass, watermark (account for negative numbers)
if (i == 0) and (j == 0):
highest = tot
if tot > highest:
highest = tot
print (highest)for i in range(len(arr)):
print (highest)for i in range(len(arr)):
for j in range(len(arr[i])):
# make sure we're not indexing out of range (ie, i <= 3, j <= 3)
if (j > len(arr) - 3) or (i > len(arr) - 3):
break
# get values in hourglass pattern
tot = arr[i][j] + arr[i][j+1] + arr[i][j+2] + \
arr[i+1][j+1] + \
arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]
# unless its the first pass, watermark (account for negative numbers)
if (i == 0) and (j == 0):
highest = tot
if tot > highest:
highest = tot
print (highest) |
e649eb8b0d89e4682370ecde6b7edf573a80af7f | Allen-C-Guan/Leetcode-Answer | /python_part/Leetcode/DP/Mid/面试题14- I. 剪绳子/DP.py | 805 | 3.515625 | 4 | '''
这道题就应该用dp,作为一个python用户,如果没有用恰当的方法,根本就跑不过的
dp[i]定义的是: 以i为长度的绳子,最少减一刀的最大值。(这个值的是最小剪一刀的最优解)
i长度的组成分为两部分:
i-j 和 j
其中j部分是一定不剪开的(因为j会遍历的),而i-j要分为,i-j是一刀不剪(i-j)还是至少剪一刀(dp[i-j])
因此dp方程为:
dp[i] = max(dp[i-j]*j, dp[i], (i-j)*j)
'''
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 2: return 1
dp = [1 for _ in range(n+1)]
dp[2] = 2
for i in range(3,n+1):
for j in range(1,i):
dp[i] = max(dp[i-j]*j, dp[i], (i-j)*j)
return dp[-1]
foo = Solution()
print(foo.cuttingRope(6)) |
982e1ee33b6dee3966fc3ef49963aae1121a3af6 | AMAN123956/Python-Daily-Learning | /Day20(Snake Game Part-1)/turtles.py | 255 | 3.8125 | 4 | from turtle import Turtle
segments=[]
position=[(0,0),(-20,0),(-40,0)]
for i in range(0,3):
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
new_segment.goto(position[i])
segments.append(new_segment)
|
bd16f48383b0b9446c3c722a7d683e1a089135eb | CyberKnight1803/ML_from_scratch | /ML_from_scratch/supervised_learning/FLD.py | 3,577 | 3.53125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class FLD():
def getWeights(self, X_p, X_n):
"""
Parameters :
Shape = (N, D) i.e (examples, features)
X_p : Positive examples
X_n : Negativ Examples
Return:
W : Unit Vector
"""
M_p = np.mean(X_p, axis = 0)
M_n = np.mean(X_n, axis = 0)
S1 = np.cov(X_p.T)
S2 = np.cov(X_n.T)
Sw = np.add(S1, S2)
Sw_inv = np.linalg.inv(Sw)
W = np.dot(Sw_inv, (M_p - M_n))
W = W / np.linalg.norm(W)
return W
def getGaussianCurve(self, X, W):
"""
Parameters :
X : Input training examples of a particular class
W : Unit vector
Returns :
x, y, Mean, std, var of gaussian distribution
"""
X_1D = np.dot(W, X.T)
mean = np.mean(X_1D)
std = np.std(X_1D)
var = np.var(X_1D)
X_1D = np.sort(X_1D)
exp = -((X_1D - mean)**2) / (2 * var)
y = (1 / np.sqrt(2 * np.pi * var)) * np.exp(exp)
GD = {
'x': X_1D,
'y': y,
'mean': mean,
'std': std,
'var': var
}
return GD
def getIntersectionPoint(self, X_p, X_n, W):
"""
Finds the intersection point by solving the Quadratic equation
Returns:
Intersection point, Guassian Distribution stats of both classes.
"""
gdP = self.getGaussianCurve(X_p, W)
gdN = self.getGaussianCurve(X_n, W)
m_p, v_p = gdP['mean'], gdP['var']
m_n, v_n = gdN['mean'], gdN['var']
a = (1 / v_p) - (1 / v_n)
b = 2 * (m_p / v_p - m_n / v_n)
c = (((m_n ** 2)/v_n - (m_p ** 2)/v_p) + np.log(v_n/v_p))
roots = np.roots([a, b, c])
return roots[1], gdP, gdN
def predictions(self, X, W, threshold):
projections = np.dot(W, X.T).reshape(-1, 1)
P = (projections > threshold).astype(int).reshape(-1, 1)
return P
def accuracy(self, y, P):
acc = np.sum(y == P) / len(y)
return acc * 100
def Model(self, X_p, X_n, X, y_p, y_n, y):
W = self.getWeights(X_p, X_n)
t, gdP, gdN = self.getIntersectionPoint(X_p, X_n, W)
P = self.predictions(X, W, t)
acc = self.accuracy(y, P)
self.modelStats = {
'weight': W,
'threshold': t,
'gdP': gdP,
'gdN': gdN,
'predictions': P,
'acc': acc
}
return self.modelStats
def plot1D_projections(self, y):
P = self.modelStats['predictions']
threshold = self.modelStats['threshold']
gdP = self.modelStats['gdP']
gdN = self.modelStats['gdN']
points = pd.DataFrame(np.concatenate((P, y)))
pPoints = points.loc[points[1] == 1][[0]]
nPoints = points.loc[points[1] == 0][[0]]
plt.plot(pPoints, np.ones(pPoints.shape), '.', color = 'r', label = 'Class 1')
plt.plot(nPoints, np.ones(nPoints.shape), '.', color = 'b', label = 'Class 0')
plt.plot([threshold], [1], '.', color = 'black', label = 'Threshold', markersize=10)
plt.plot([gdP['mean']], [1], 'x', color = 'black', label = "Class 1 mean", markersize = 8)
plt.plot([gdN['mean']], [1], 'x', color = 'black', label = "Class 0 mean", markersize = 8)
plt.title('Projections onto vector W')
plt.legend(loc = 'upper right')
plt.show()
|
28b9b0bb14a1dc0d8ae3426e47d1302cc0128135 | stevenwang/flaskJSONRPCServer | /flaskJSONRPCServer/example/rr1.py | 502 | 3.671875 | 4 | data=[]
def arrMedian(arr, arrMap=None):
if not len(arr): return 0
elif len(arr)==1: return arr[0]
if not arrMap:
arrMap=sorted(range(len(arr)), key=lambda i:arr[i], reverse=False)
if len(arrMap)%2:
median=arr[arrMap[len(arrMap)/2]]
else:
median=(arr[arrMap[(len(arrMap)-1)/2]]+arr[arrMap[(len(arrMap)-1)/2+1]])/2.0
return median
def compute():
if not len(data): s='No data'
else:
s=arrMedian(data)
return '"compute()" method from rr1 module: %s'%s
|
0fab74bd50ebc8c49c4baabc75b4e1d1202b9e33 | JamCrumpet/Lesson-notes | /Lesson 7 function/7.13_making_an_argument_optional.py | 1,550 | 4.8125 | 5 | # sometime you have to make an argument optional so the user can choose to input the extra argument
# you can use default values to make an argument optional
# for example if we want to let users input their full names and make middle names optional
def get_formatted_name(first_name, middle_name, last_name):
"""Return a full name that is neatly formatted."""
full_name = first_name + " " + middle_name + " " + last_name
return full_name.title()
musician = get_formatted_name("john", "lee", "hooker")
print(musician)
# this function works when given a first, middle, and last name
# but middle names are not always needed
# to make the middle name optional we can give the middle_name argument an empty default value ...
# ... and ignore the argument unless the the user provides a value
# to make get_formatted_name to work without a middle name we set middle_name to an empty string and ...
# ... create an if statement
def v2_get_formatted_name(first_name, last_name, middle_name= ""):
"""Return a full name that is neatly formatted."""
if middle_name: # if the user inputs a middle name
full_name = first_name + " " + middle_name + " " + last_name
else: # if middle name is empty
full_name = first_name + " " + last_name
return full_name.title()
musician = v2_get_formatted_name("frank", "sinatra")
print(musician)
musician = v2_get_formatted_name("jimi","hendrix")
print(musician)
musician = v2_get_formatted_name("john", "hooker", "lee")
print(musician) |
92d2e48959380fba1fcd622f3ef4cbd1104630ce | SasCezar/PedestrianTrajectoryClustering | /ptcpy/trajectory_clustering/common.py | 200 | 3.5 | 4 | """
Created on 4. 5. 2015
@author: janbednarik
"""
from math import *
def euclid_dist(p1, p2):
assert (len(p1) == len(p2))
return sqrt(sum([(p1[i] - p2[i]) ** 2 for i in range(len(p1))]))
|
5a491921d9b02016098a78da2a722a0ec8df6001 | Ankitsingh1998/ML-DL-AI_internship | /Day089_KMeans_clustering.py | 2,671 | 4.3125 | 4 | #Day089 - kMeans (Unsupervised Machine Learning)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('xclara.csv')
df.shape #shape of dataframe
df.columns.to_list() #column_names into list
df.ndim #dimension of dataframe
df.isnull().any(axis=0) #axis = 0 for row wise null value checking
#type(df) #dataframe type is pandas.core.frame.DataFrame
features = df.iloc[:,[0,1]].values #values - to convert dataframe into numpy array
#type(features)
x = features[:,0]
y = features[:,1]
plt.scatter(x, y)
plt.show()
#K-means clustering: 3 clusters
from sklearn.cluster import KMeans #dir(sklearn.cluster)
#3 clustering is given because we already visualized it
kmeans_model = KMeans(n_clusters=3, init = 'k-means++', random_state=42)
predict_cluster = kmeans_model.fit_predict(features) #features passed only - Unsupervised ML
print(predict_cluster)
#Visualizing the clusters seperately
#plt.scatter(features[:,0][y_kmeans==0], features[:,1][y_kmeans==0])
plt.scatter(features[predict_cluster == 0, 0], features[predict_cluster == 0, 1], c='cyan', label='Cluster1')
plt.scatter(features[predict_cluster == 1, 0], features[predict_cluster == 1, 1], c='red', label='Cluster2')
plt.scatter(features[predict_cluster == 2, 0], features[predict_cluster == 2, 1], c='yellow', label='Cluster3')
plt.show()
"""
Centroid of the clusters:
Explain the concept of Center of Mass = Centroid
Sum of x coordinates
x of centroid = -----------------------
Total number of values
Sum of y coordinates
y of centroid = -----------------------
Total number of values
"""
print(kmeans_model.cluster_centers_) #coordinates of all centroids
print(kmeans_model.cluster_centers_[:, 0]) #x-coordinate of all centroids
print(kmeans_model.cluster_centers_[:, 1]) #y-coordinate of all centroids
#Visualizing the clusters seperately with their centroids
plt.scatter(features[predict_cluster == 0, 0], features[predict_cluster == 0, 1], c='cyan', label='Cluster1')
plt.scatter(features[predict_cluster == 1, 0], features[predict_cluster == 1, 1], c='red', label='Cluster2')
plt.scatter(features[predict_cluster == 2, 0], features[predict_cluster == 2, 1], c='yellow', label='Cluster3')
plt.scatter(kmeans_model.cluster_centers_[:, 0], kmeans_model.cluster_centers_[:, 1], c = 'black', label = 'Centroids')
plt.title('Clusters of datapoints alongwith their centroids')
plt.xlabel('X-Cordindates')
plt.ylabel('Y-Cordinates')
plt.legend()
plt.show()
|
b62a407d0bae68c178d7d8ebb1de373a3b71bf71 | MuhummadShohag/PythonAutomation | /OS_Module/introduction_os_module.py | 1,345 | 3.984375 | 4 | '''
OS_Module: This module is used to work/interact with operating system to automate many more task
like creating directory, removing directory, identifying current directory and many more
* You can work both operating system through os_module
'''
import os
# os.sep is the (or a most common) pathname separator ('/' or '\\')
print(os.sep)
# When you taken path to your folder, you set also two lashes('\')
# path="path"
# print(path)
# os.getcwd(), it is show current working directory
print(os.getcwd())
# os.chdir(), it is changing directory
# print(os.chdir("path"))
# print(os.getcwd())
# os.listdir(), it is show list of directory
# print(os.listdir())
# print(os.listdir("path"))
# os.mkdir(), it is create new directory
# print(os.mkdir('good'))
# os.makedirs(), it is create new directory through recursive way
# print(os.makedirs("path"))
# print(os.listdir("path"))
# os.rmdir(), it is remove directory, os.remove(), it is remove file
# print(os.rmdir("path"))
# os.rename(src,), it is rename file name
# print(os.makedirs("path"))
# a="path"
# b="path"
# print(os.rename(a,b))
# print(os.listdir())
# os.environ, to get enviroment of your operating system
# print(os.environ)
# os.getpid(), you can find process id
# print(os.getpid())
# print(os.remove("path"))
print(os.listdir())
os.system('cls')
|
0f9049d50ad970070a544e407d42411ff4bf0d47 | 824zzy/Leetcode | /G_BinarySearch/BasicBinarySearch/L1_1533_Find_the_Index_of_the_Large_Integer.py | 517 | 3.640625 | 4 | """ https://leetcode.com/problems/find-the-index-of-the-large-integer/
binary search
"""
class Solution:
def getIndex(self, reader) -> int:
l, r = 0, reader.length()-1
while l<r:
m = (l+r)//2
if (r-l)&1:
res = reader.compareSub(l, m, m+1, r)
if res==1: r = m
else: l = m+1
else:
res = reader.compareSub(l, m-1, m+1, r)
if res==1: r = m
else: l = m
return l |
ec5805e954cb371664cd0aa165d375b52063cab6 | sheauyu/sapy | /src/figures/F5_30_filter_images.py | 1,320 | 3.59375 | 4 | """ Demonstration on how to filter images """
# author: Thomas Haslwanter
# date: April-2021
# Import the standard packages
import numpy as np
import matplotlib.pyplot as plt
import os
# For the image filtering
from scipy import ndimage
# Import formatting commands
from utilities.my_style import set_fonts, show_data
# Get the data
import skimage as ski
img = ski.data.camera()
# for the filtering, the data must not be uint
img_f = np.array(img, dtype=float)
# Make the filters
Filters = []
Filters.append(np.ones((11,11))/121)
Filters.append(np.array([np.ones(11),np.zeros(11),-1*np.ones(11)]))
Filters.append(Filters[-1].T)
# Filter the images
filtered = []
for filt in Filters:
filtered.append( ndimage.correlate(img_f, filt) )
# Make the plots
fig, axs = plt.subplots(3,2, figsize=(6,8))
plt.gray()
axs[0,0].imshow(img)
axs[0,1].imshow(filtered[0])
axs[1,0].imshow(filtered[1])
axs[1,1].imshow(filtered[2])
axs[2,0].imshow(filtered[1]>125)
axs[2,1].imshow(filtered[2]>125)
# Remove the ticks and labels
for axis in axs.ravel():
axis.axes.get_xaxis().set_visible(False)
axis.axes.get_yaxis().set_visible(False)
# Reduce the space between the plots
plt.tight_layout()
# Save and show the figure
out_file = 'filter_demo.jpg'
show_data(out_file) |
12b2327626d2ae54ab17ac1943421f42dc9b21be | NicholasPiano/scripts | /scratch/Python/packing/packing.py | 397 | 3.734375 | 4 | #!usr/bin/python
#objects for box, field, and algorithm
#methods to run algorithm and return properties of box arrangement
#file output
import vector
#all vectors are in three dimensions
#field class
class field:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class box:
def __init__(self, x, y, z, mass, h, w, l, theta, phi):
class face:
def __init__(self, x, y): |
ad621e68466b60df795ec62e5d8660bf7a89a218 | csaden/euler | /0044euler_PentagonNumbers.py | 928 | 3.796875 | 4 | # Pentagonal numbers are generated by the formula,
# Pn=n(3n-1)/2. The first ten pentagonal numbers are:
# 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
# It can be seen that P4 + P7 = 22 + 70 = 92 = P8.
# However, their difference, 70 - 22 = 48, is not pentagonal.
# Find the pair of pentagonal numbers, Pj and Pk,
# for which their sum and difference are pentagonal
# and D = |Pk - Pj| is minimised; what is the value of D?
def getPentagonalNumbers(max_n):
return [n*(3*n-1)/2 for n in range(1, max_n + 1)]
def isPentagonal(a, b):
global pents
if a + b not in pents:
return False
if b - a not in pents:
return False
return True
pents = getPentagonalNumbers(10000)
print len(pents)
def getMorePents(l):
for i in range(0, len(l)):
for j in range(i+1, len(l)):
first = l[i]
second = l[j]
if isPentagonal(first, second):
print first, second, second - first
return "DONE"
getMorePents(pents) |
31b38157ec3fa4eb03334880cdef4a5a1a3e5e85 | Magnificent-Big-J/advent-of-code-2017 | /08/registers_part_two.py | 1,415 | 3.734375 | 4 | """
--- Part Two ---
To be safe, the CPU also needs to know the highest value held in any register
during this process so that it can decide how much memory to allocate to these
operations. For example, in the above instructions, the highest value ever held
was 10 (in register c after the third instruction was evaluated).
"""
import re
registers = {}
max_register_value = 0
with open('input.txt') as f:
for line in f:
result = re.search('(?P<register>[a-z]+) (?P<op>inc|dec) (?P<amt>-?\d+) '
'if (?P<cond_register>[a-z]+) (?P<cond>.+) '
'(?P<cond_amt>-?\d+)', line.strip())
register = result.group('register')
op = result.group('op')
amt = int(result.group('amt'))
cond_register = result.group('cond_register')
cond = result.group('cond')
cond_amt = int(result.group('cond_amt'))
if register not in registers:
registers[register] = 0
if cond_register not in registers:
registers[cond_register] = 0
if eval('{} {} {}'.format(registers[cond_register], cond, cond_amt)):
if op == 'inc':
registers[register] += amt
elif op == 'dec':
registers[register] -= amt
if registers[register] > max_register_value:
max_register_value = registers[register]
print(max_register_value)
|
bffb24698769188589de72b0454a4d94401b8f30 | hacktheinterview/hacktheinterview | /problems/58/Main.py | 371 | 3.78125 | 4 | import math
#--SPLIT--
#-class Solution:
# @param a : string
# @return an integer
#- def lengthOfLastWord(self, a):
#--SPLIT--
class Solution:
def lengthOfLastWord(self, a):
return 0
#--SPLIT--
if __name__ == "__main__":
test_cases = int(raw_input())
for i in range(test_cases):
a = raw_input()
solution = Solution()
print(solution.lengthOfLastWord(a))
|
b8f12627e88fea77b9f502cc3d751667eece6173 | cmnaveen/study_cmp | /python/break_continue.py | 572 | 3.859375 | 4 |
#prime number
for n in range(2,19):
for x in range(2,n):
if n % x == 0:
print n, 'equals',x,'*',n/x
break
else:
print n, 'is a prime number'
# even odd numbers
for num in range(2,19):
if num % 2 == 0:
print "even num:",num
continue
print "odd num:", num
# pass statements
#while True:
# pass
class MyEmptyClass:
pass
def initlog(*args):
pass
def fib(n): # function defination
a,b = 0,1
while a < n:
print a,
a,b =b ,a+b
fib(20) # function call
|
39e2a7b43ca07dc7df05a06d6b3b181d6d9c56d1 | xSandie/python_data_structure | /C1_LinkedList/reverse_neighbor_1_7/reverse.py | 1,075 | 3.984375 | 4 | from C1_LinkedList.LNode import LNode
def reverse(head):
#判断链表是否为空
if head is None or head.next is None:
return
cur = head.next#对cur与cur.next进行对调
pre = head
next_next = None#当前节点的后继节点的后继节点
while cur is not None and cur.next is not None:
next_next = cur.next.next
pre.next = cur.next
cur.next.next = cur
cur.next = next_next
pre = cur
cur = next_next
if __name__=="__main__":
i=1
head =LNode()
head.next = None
tmp = None
cur = head
while i<8:
tmp = LNode()
tmp.data = i
tmp.next = None
cur.next = tmp
cur = tmp
i +=1
print("顺序输出:")
cur = head.next
while cur != None:
print(cur.data,end=' ')
cur = cur.next
reverse (head)
print("\n逆序输出:")
cur = head.next
while cur != None:
print(cur.data,end=' ')
cur = cur.next
cur = head.next
while cur != None:
cur = cur.next
|
6d10e93b7da1c117c5d83631b521341a8a58d6f9 | humrochagf/flask-reveal | /flask_reveal/tools/helpers.py | 1,976 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import os
import shutil
import tarfile
import zipfile
try:
# Python 3
FileNotFoundError
except NameError:
# Python 2
FileNotFoundError = IOError
def move_and_replace(src, dst):
"""
Helper function used to move files from one place to another,
creating os replacing them if needed
:param src: source directory
:param dst: destination directory
"""
src = os.path.abspath(src)
dst = os.path.abspath(dst)
for src_dir, _, files in os.walk(src):
# using os walk to navigate through the directory tree
# keep te dir structure by replacing the source root to
# the destination on walked path
dst_dir = src_dir.replace(src, dst)
if not os.path.exists(dst_dir):
os.mkdir(dst_dir) # to copy not fail, create the not existing dirs
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file) # to copy not fail, create existing files
shutil.move(src_file, dst_dir) # move the files
shutil.rmtree(src) # remove the dir structure from the source
def extract_file(compressed_file, path='.'):
if os.path.isfile(compressed_file):
if tarfile.is_tarfile(compressed_file):
with tarfile.open(compressed_file, 'r:gz') as tfile:
basename = tfile.members[0].name
tfile.extractall(path+'/')
elif zipfile.is_zipfile(compressed_file):
with zipfile.ZipFile(compressed_file, 'r') as zfile:
basename = zfile.namelist()[0]
zfile.extractall(path)
else:
raise NotImplementedError('File type not supported')
else:
raise FileNotFoundError(
'{0} is not a valid file'.format(compressed_file))
return os.path.abspath(os.path.join(path, basename))
|
03542bb32e7b68802d29dd3edb6a972f75a3e75a | PFZ86/LeetcodePractice | /Math/0326_PowerOfThree_E.py | 587 | 4.03125 | 4 | # https://leetcode.com/problems/power-of-three/
# Solution 1: the iterative method
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return False
while n > 1:
if n%3 != 0:
return False
n /= 3
return True
# Solution 2: trick
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return (n > 0) and (1162261467%n == 0)
|
120c25b2aa19af0bb271502061f37e560bde57b6 | ar2126/Ngram-Viewer | /N Gram Viewer/trending.py | 1,979 | 4.0625 | 4 | """
Finds the top 10 and bottom trending words based on a given start and end year
author: Aidan Rubenstein
"""
from wordData import *
import operator
class WordTrend(struct):
_slots = ((str, 'word'), (float, 'trend'))
def trending(words, startYr, endYr):
"""
Iterates through the words dictionary and finds the count value at or after the first instance of startYr and
endYr and creates a WordTrend instance of the word and its trend. This instance is then put into a list
precondition: dictionary of words, start year, and end year are given
postcondition: list of WordTrend objects is returned
"""
keys = words.keys()
word = []
for i in keys:
top = 0
bottom = 0
for q in words[i]:
if q.year == startYr and q.count >= 1000:
top = q.count
if q.year == endYr and q.count >= 1000:
bottom = q.count
if top != 0 and bottom != 0:
word.append(WordTrend(i, top/bottom))
word = sorted(word, key=operator.attrgetter('trend'))
return word
def main():
"""
Prints the top 10 and bottom 10 values in the word list retrieved from trending
"""
user = input("Enter word file: ")
startYr = int(input("Enter starting year: "))
endYr = int(input("Enter ending year: "))
word = trending(readWordFile(user), startYr, endYr)
print("\nTop 10 words from ", startYr, " to ", endYr, ":")
if len(word) >= 10:
for i in range(10):
print(word[i].word)
else:
for i in range(len(word)):
print(word[i].word)
print("\nBottom 10 words from ", startYr, " to ", endYr, ":")
if len(word) >= 10:
for i in range(len(word)-1, len(word)-11, -1):
print(word[i].word)
else:
for i in range(len(word)-1, -1, -1):
print(word[i].word)
if __name__ == '__main__':
main()
|
75f1e68ca1452cb36f240627012de4b7a84aac68 | mtharanya/python-programming- | /largestnum.py | 223 | 3.65625 | 4 | alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest, larger = alist[0], alist[0]
for num in alist:
if num > largest:
largest, larger = num, largest
elif num > larger:
larger = num
print larger
|
cd621b5d4391d5c48cdb3ef7c6c0369d07d740d6 | Take-Take-gg/20460065-Ejercicios-Phyton | /Ejercicios-05/Datos_compuestos-01.py | 900 | 4 | 4 | # Datos compuestos 01
"""
1.- Realiza una función separar(lista) que tome una lista de números enteros
desordenados y devuelva dos listas ordenadas. La primera con los números pares y la
segunda con los números impares.
"""
numeros = []
for var in range(int(input("Cuantos numeros agregaras a la lista? "))):
numeros.append(input(f"Agrega el registro {var+1}: "))
pares = []
impares = []
def separar(numeros):
for var in numeros:
if int(var)%2==0:
pares.append(int(var))
elif int(var)%2 == 1:
impares.append(int(var))
separar(numeros)
print(f"Lista de numeros: {numeros}")
print(f"Lista de pares desordenados: {pares}\nLista de impares desordenados: {impares}")
pares_ordenados = sorted(pares)
impares_ordenados = sorted(impares)
print(f"Lista de pares ordenados: {pares_ordenados}")
print(f"Lista de impares ordenados: {impares_ordenados}")
|
12b936b19c003f2e7dfa5d65eadf7dc4a23d4335 | mshekhar/random-algs | /general/sequence-reconstruction.py | 1,873 | 3.78125 | 4 | import collections
from Queue import Queue
class Solution(object):
def construct_graph(self, seqs):
graph = {}
for seq in seqs:
i = 0
while i < len(seq):
if seq[i] not in graph:
graph[seq[i]] = set()
if i + 1 < len(seq) and seq[i] != seq[i + 1]:
graph[seq[i]].add(seq[i + 1])
i += 1
return graph
def topological_sort(self, graph):
in_degrees = collections.Counter()
for i in graph:
for j in graph[i]:
in_degrees[j] += 1
queue = Queue()
for i in graph:
if in_degrees[i] == 0:
queue.put(i)
if queue.qsize() > 1:
return []
topological_order = []
while queue.qsize() > 0:
node = queue.get()
topological_order.append(node)
for i in graph[node]:
in_degrees[i] -= 1
if in_degrees[i] == 0:
queue.put(i)
if queue.qsize() > 1:
return []
return topological_order
def sequenceReconstruction(self, org, seqs):
"""
:type org: List[int]
:type seqs: List[List[int]]
:rtype: bool
"""
graph = self.construct_graph(seqs)
topological_order = self.topological_sort(graph)
if topological_order == org:
return True
return False
print Solution().sequenceReconstruction([1, 2, 3], [[1, 2], [1, 3]])
print Solution().sequenceReconstruction([1, 2, 3], [[1, 2]])
print Solution().sequenceReconstruction([1, 2, 3], [[1, 2], [1, 3], [2, 3]])
print Solution().sequenceReconstruction([4, 1, 5, 2, 6, 3], [[5, 2, 6, 3], [4, 1, 5, 2]])
print Solution().sequenceReconstruction(1, [1, 1])
|
b77981ed595cb39f899498dcd2f0b9b550a68d0d | benjiaming/leetcode | /test_reverse_words_in_string_iii.py | 456 | 3.78125 | 4 | import unittest
from reverse_words_in_string_iii import Solution
class TestSolution(unittest.TestCase):
def test_reverse_words_in_string_iii(self):
solution = Solution()
self.assertEqual(solution.reverseWords(""), "")
self.assertEqual(solution.reverseWords(" "), "")
self.assertEqual(solution.reverseWords("Let's take LeetCode contest"), "s'teL ekat edoCteeL tsetnoc")
if __name__ == '__main__':
unittest.main() |
3d1c8214ab319ba022751b38a13b1651e270a71b | sent1nu11/password-manager | /main.py | 1,257 | 3.5625 | 4 | from tkinter import *
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
# ---------------------------- SAVE PASSWORD ------------------------------- #
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
canvas = Canvas(width=200, height=200)
logo_img = PhotoImage(file="logo.png")
canvas.create_image(100, 100, image=logo_img)
canvas.grid(row=0, column=1)
#Labels
website_label = Label(text="Website:")
website_label.grid(row=1, column=0)
email_label = Label(text="Email/Username:")
email_label.grid(row=2, column=0)
password_label = Label(text="Password:")
password_label.grid(row=3, column=0)
#Entries
website_entry = Entry(width=35)
website_entry.grid(row=1, column=1, columnspan=2)
website_entry.focus()
email_entry = Entry(width=35)
email_entry.grid(row=2, column=1, columnspan=2)
email_entry.insert(0, "roger@gmail.com")
password_entry = Entry(width=21)
password_entry.grid(row=3, column=1)
#Buttons
generate_password_button = Button(text="Generate Password")
generate_password_button.grid(row=3, column=2)
add_button = Button(text="Add", width=36)
add_button.grid(row=4, column=1, columnspan=2)
window.mainloop()
|
9f28e93d0f84132cebac314e086dcc5b3330cb9a | IronE-G-G/algorithm | /leetcode/101-200题/108convertSortedArr2BST.py | 1,468 | 3.859375 | 4 | """
108 将有序数组转化成二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
答案不是唯一的原因是当数组长度为偶数的时候
构建的树的根节点既能选中间偏左也能选中间偏右的元素
"""
def helper(left, right):
if left == right:
return None
# 保证所有左右子树的元素数量相差不大于1
iroot = (left + right) // 2
root = TreeNode(nums[iroot])
if left + 1 == right:
return root
leftTree = helper(left, iroot)
rightTree = helper(iroot + 1, right)
root.left = leftTree
root.right = rightTree
return root
return helper(0, len(nums))
|
c1753f0d9186180204b79ee8abc22111fa3d7bbf | cowboybebophan/LeetCode | /Solutions/784. Letter Case Permutation.py | 995 | 3.8125 | 4 | """
https://leetcode.com/problems/letter-case-permutation/discuss/342024/Python3-recursive-solution-beats-98-with-explanation
"""
# DFS + Recursion
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res = []
self.dfs(S, 0, res, '')
return res
def dfs(self, S, index, res, path):
if index == len(S):
res.append(path)
return
if S[index].isalpha():
self.dfs(S, index + 1, res, path + S[index].lower())
self.dfs(S, index + 1, res, path + S[index].upper())
if not S[index].isalpha():
self.dfs(S, index + 1, res, path + S[index])
# Solution 2
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res = ['']
for ch in S:
if ch.isalpha():
res = [i + j for i in res for j in [ch.lower(), ch.upper()]]
else:
res = [i + ch for i in res ]
return res
|
e2b376b685ba3c63471935f3918f1a6304f84d75 | vaishnavi-consultants/Computer-Science | /Python-Draft1/Projects/sqlite/sqlite_insert.py | 789 | 4.375 | 4 | # Python code to demonstrate table creation and
# insertions with SQL
# importing module
# python sqlite.py Insert Accounts employee "3, 'Maha', '240000', 'M', 'Software'"
import sqlite3
def sqlite3_insert_rec(dbname, tablename, rec):
# connecting to the database
db_name = dbname+".db"
connection = sqlite3.connect(db_name)
# cursor
crsr = connection.cursor()
# SQL command to insert the data in the table
sql_command = """INSERT INTO """ + tablename + """ VALUES (""" + rec + """);"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
|
9efa904f7c715d03ba90eb8422fbaaa1655e707e | spezifisch/leetcode-problems | /search-insert-position/one.py | 444 | 3.875 | 4 | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
i = 0
len_nums = len(nums)
while i < len_nums:
if nums[i] >= target:
return i
i += 1
return i
# Runtime: 40 ms, faster than 49.32% of Python3 online submissions for Search Insert Position.
# Memory Usage: 13.7 MB, less than 5.11% of Python3 online submissions for Search Insert Position.
|
8c88d0a5871946a56d708cef8ea365d54795d5d7 | Aygulx/AI_P2_AygulBayramova | /csp.py | 8,479 | 3.609375 | 4 |
# defining CSP
class CSP:
"""
A class used to represent a CSP problem.
...
Attributes
----------
variables : list
Vertives of the graph
neighbors : dictionary
Represents neighbors of each vertex
domain : list
All possible values(colors)
Methods
-------
def constraint(self, color1, color2)
def add_val(self, var, val, assignment)
def remove_val(self, var, assignment)
def not_conflict(self, var, val, assignment)
def conflict_num(self, var, val, assignment):
"""
def __init__(self, variables, domain, neighbors):
self.variables = variables
self.neighbors = neighbors
self.domain = domain
def constraint(self, color1, color2):
"""Checks if constraint is satisfied for given values """
return color1 != color2
def add_val(self, var, val, assignment):
"""adds new {var: val} pair to assignment"""
assignment[var] = val
#apply AC-3 after assigning value - MAC algorithm
AC3(self)
def remove_val(self, var, assignment):
"""removes {var: val} pair from assignment"""
if var in assignment:
del assignment[var]
def not_conflict(self, var, val, assignment):
"""Checks if there is a conflict in values of assignment """
is_not_conf = True
for var2 in self.neighbors[var]:
#get value of var2
val2 = assignment.get(var2, None)
#check is constraint is satisfied
#if not and value is not None return False
if val2 != None and not self.constraint(val, val2):
is_not_conf = False
break
return is_not_conf
def conflict_num(self, var, val, assignment):
"""Returns number of the conflicting values of assignment """
num_conf = 0
for var2 in self.neighbors[var]:
val2 = assignment.get(var2, None)
#check is constraint is satisfied
#if not and value is not None add 1 to counter
if val2 != None and not self.constraint(val, val2):
num_conf += 1
return num_conf
# Backtracking Search
def backtracking_search(csp):
"""Backtracking search for graph coloring problem"""
global assignment
return recursive_backtracking(assignment, csp)
def recursive_backtracking(assignment, csp):
"""Recursive depth-first search for backtracking"""
#check if assignment is complete
if len(assignment) == len(csp.variables):
return assignment
var = select_unassigned_variable(assignment, csp)
for val in order_domain_values(var, assignment, csp):
if csp.not_conflict(var, val, assignment):
#if no conflict assign new value to var
csp.add_val(var, val, assignment)
result = recursive_backtracking(assignment, csp)
#if result is failure, remove value
if result is not None:
return result
csp.remove_val(var, assignment)
return None
# selecting variable - heuristics
def mrv(variables):
"""minimum remaining values (MRV) heuristic to select variable"""
min_var = variables[0]
min_rem = rem_legal_values(csp, min_var, assignment)
#find variable with minimum remaining values
for var in variables:
rem_vals = rem_legal_values(csp, var, assignment)
if rem_vals < min_rem:
min_var, min_rem = var, rem_vals
return min_var
def rem_legal_values(csp, var, assignment):
"""Returns number for remaining possible "legal" values"""
num = 0
#calculate number of remaining variables
for color in csp.domain[var]:
if csp.conflict_num(var, color, assignment) == 0:
num += 1
return num
def select_unassigned_variable(assignment, csp):
"""selects next unassigned variable using MRV"""
#get list of unassigned variables
unassigned = [var for var in csp.variables
if var not in assignment]
return mrv(unassigned)
# selecting value - heuristics
def lcv(var, domain):
"""least-constraining-value heuristic to select value"""
#sort domain by number of conflicts
return sorted(domain, key=lambda val: csp.conflict_num(var, val, assignment))
def order_domain_values(var, assignment, csp):
"""orders values in a specific way to select value using LCV"""
#get domain for given variable
domain = csp.domain[var]
return lcv(var, domain)
# AC-3 constraint propagation (MAC)
def AC3(csp):
""" Maintaining Arc Consistency for constraint propagation"""
#simulate queue using list
queue = [(Xi, Xk) for Xi in csp.variables for Xk in csp.neighbors[Xi]]
while queue:
#get element from start
(Xi, Xj) = queue.pop(0)
if remove_inconsistent_values(csp, Xi, Xj):
for Xk in csp.neighbors[Xi]:
#add element to the end of queue
queue.append((Xk, Xi))
def remove_inconsistent_values(csp, Xi, Xj):
"""Removes inconsistent values from domain"""
removed = False
for x in csp.domain[Xi]:
#check if there is a non-conflicting value y for x
is_not_conflict = False
for y in csp.domain[Xj]:
if csp.constraint(x, y):
is_not_conflict = True
break
#if no non-conflicting val left, remove x from domain
if is_not_conflict == False :
csp.domain[Xi].remove(x)
removed = True
return removed
# reading from input file
def file_reader(filepath):
"""Reads input file and generates data"""
global edges
global vertices
global color_num
with open(filepath, "r") as filestream:
for line in filestream:
if line.startswith("#"):
continue
#get number of colors
elif line.startswith("colors"):
line = line.rstrip('\n')
color_num = int(line.split("=")[1])
#get edges and vertices
else:
line = line.rstrip('\n')
start, end = map(int, line.split(","))
vertices.add(start)
vertices.add(end)
edges.append((start,end))
edges.append((end, start))
def plot_grap():
"""
Plots visualizations of resulting colored graph
Note: MAX number of colors - 6
If number of colors will be more than 6, all colors
greater and equal to 6 will be assigned as gray
"""
import networkx as nx
import matplotlib.pyplot as plt
#create graph from edge list
g = nx.from_edgelist(edges)
#assign colors to vertices
for i in range(min(vertices),max(vertices)+1):
g.nodes[i]['color'] = assignment[i]
#create color map for visualization
color_map = []
for i in range(min(vertices),max(vertices)+1):
if g.nodes[i]['color'] == 1:
color_map.append('blue')
elif g.nodes[i]['color'] ==2:
color_map.append('green')
elif g.nodes[i]['color'] ==3:
color_map.append('red')
elif g.nodes[i]['color'] == 4:
color_map.append('pink')
elif g.nodes[i]['color'] == 5:
color_map.append('purple')
else:
color_map.append('gray')
#visualize graph
nx.draw(g, node_color=color_map,with_labels=True)
plt.show()
# main program - solving graph coloring
if __name__ == '__main__':
#initialize edges, vertices, etc.
edges = []
vertices = set()
color_num = 0
domain = dict()
assignment = dict()
inputpath = input('Enter your file path: ')
file_reader(inputpath)
#generate neighbors dictionary
neighbors = dict()
vertices = sorted(list(vertices))
for vertex in vertices:
neighbors[vertex] = []
domain[vertex] = list(range(1, color_num + 1))
for edge in edges:
neighbors[edge[0]].append(edge[1])
#initialize CSP problem with given values
csp = CSP(vertices, domain, neighbors)
print(backtracking_search(csp))
# to see graph visualization uncomment below:
#plot_grap()
|
04f4ba4f2c4113e63be5102688e806f6867dd03e | rezmont/prep | /moderate/check-tic-tac-toe.py | 851 | 3.578125 | 4 | import random
def print_grid(grid):
print '\n'.join([str(l) for l in grid])
def check_if_won(grid):
"""row"""
for i in xrange(3):
set_row = set()
set_col = set()
for j in xrange(3):
set_row.add(grid[i][j])
set_col.add(grid[j][i])
if len(set_row)==1:
return list(set_row)[0]
if len(set_col)==1:
return list(set_col)[0]
set_diag1 = set()
set_diag2 = set()
for i in xrange(3):
set_diag1.add(grid[i][i])
set_diag2.add(grid[2-i][i])
if len(set_diag1)==1:
return list(set_diag1)[0]
if len(set_diag2)==1:
return list(set_diag2)[0]
if __name__ == '__main__':
grid = [[ random.randint(0,2) for _ in xrange(3)] for _ in xrange(3)]
print grid
print_grid(grid)
print check_if_won(grid) |
5f995166a5b818e1fe0f8194a71f1d26b58e36fd | francescaser/pyAcademy | /Esercizi base 22-02/FuncContOccorrenzaLettera.py | 420 | 3.75 | 4 | # Crea una funzione che presi in input una stringa (nome) e
# un carattere (i.e. stringa di lunghezza 1),
# conti le occorrenze del carattere all’interno della stringa
def find(parola, lettera):
contatore = 0
i = 0
while i<len(parola):
if parola[i]==lettera:
contatore += 1
i+=1
return contatore
# esiste la funzione parola.count(lettera) per contare l'occorrenza
|
b54fe1f28056991042cf8eb75995ad1ebefbb866 | hermesvf/Calculator-the-game | /solve.py | 3,356 | 3.890625 | 4 | #!/usr/bin/env python3
from sys import argv
from itertools import product
DEBUG = 0
def debug(s):
if DEBUG == 1:
print(s)
actions = { 'addition' :'+', \
'substract' :'-', \
'product' :'*', \
'division' :'/', \
'exchange' :'X', \
'append' :'A', \
'alter_sign':'S', \
'shift_left':'L', \
'reverse' :'R'
}
def usage():
print("Usage: "+argv[0]+" <source> <target> <steps> <op_1> [<op_2> ... <op_n>]")
usage = {}
usage['addition '] = "Adds one number. Example: +2"
usage['substract '] = "Substracts one number. Example: -5"
usage['product '] = "Multiplies by one number. Examples: *6 , *-2"
usage['division '] = "Divides by one number. Examples: /4 , /-3"
usage['exchange '] = "Replaces the occurrences of some number x for some other y. Examples: X-12:3, X6:-9"
usage['append '] = "Appends a number to another. Example: A5"
usage['alter_sign'] = "Is equivalent to multiply by -1. Usage: S"
usage['shift_left'] = "Removes the last digit. Usage: L"
usage['reverse '] = "Reverses the number digit by digit. Usage: R"
print(" Operations available:")
for k in usage.keys():
print('\t'+k,':',usage[k])
exit(1)
def addOptionNode(l,op):
debug("Adding op "+op)
id = op[0]
if id == actions['addition']:
l.append((lambda x: x + int(op.split(id)[1]),op))
elif id == actions['product']:
l.append((lambda x: x * int(op.split(id)[1]),op))
elif id == actions['division']:
l.append((lambda x: x / int(op.split(id)[1]),op))
elif id == actions['substract']:
l.append((lambda x: x - int(op.split(id)[1]),op))
elif id == actions['append']:
l.append((lambda x: x * 10 + int(op.split(id)[1]),op))
elif id == actions['alter_sign']:
l.append((lambda x: -x,'+/-'))
elif id == actions['exchange']:
l.append((lambda x: int(str(x).replace(str(int(op[1:].split(':')[0])),\
str(int(op[1:].split(':')[1])))),\
op[1:].split(':')[0]+'->'+op[1:].split(':')[1]))
elif id == actions['shift_left']:
l.append((lambda x: -((-x - -x%10) // 10) if x < 0 \
else (x - x%10) // 10,'<<'))
elif id == actions['reverse']:
l.append((lambda x: int(''.join(reversed(str(x)))),'Reverse'))
else:
raise Exception("Unrecognized operation:", op)
def evaluation(source, stack):
evaluated = source
for op in stack:
evaluated = op[0](evaluated)
debug("evaluation of source "+str(source)+ " with stack "\
+ str([op[1] for op in stack]) + " was " + str(evaluated))
return evaluated
def printHeader():
print("Source: " + str(source) + " Target: " + str(target)\
+ " Steps: " + str(steps))
def collect_operations(opts):
for arg in argv[4:]:
addOptionNode(opts,arg)
def find_one_solution(opts):
for chain in product(opts,repeat=steps):
try:
if evaluation(source,chain) == target:
return chain
except:
debug("exception catched during evaluation: "+str(source)+" "+\
str([op[1] for op in chain]))
return None
if __name__ == "__main__":
if len(argv) < 5:
usage()
try:
source, target, steps = [int(a) for a in argv[1:4]]
operations = []
collect_operations(operations)
except Exception as e:
print(repr(e))
usage()
printHeader()
found = find_one_solution(operations)
if found is not None:
print("--- Target found ---")
print([op[1] for op in found])
else:
print("No solution was found")
|
3602d74c9e268d133efe4d19b05c15d677a93d66 | t0etag/Python | /Python2/Labs/Lab06cX.py | 2,381 | 4.15625 | 4 | """LAB 06c
In your data file is a program named servercheck.py. It reads two files
(servers and updates) and converts the contents into two sets. The
updates are not always correct. You will find all of the set
operations/methods in Python Notes. Using just these
operations/methods, your job is as follows:
1. Determine whether the list of updates exists in the master server list.
Print a message indicating whether or not this is true.
2. If it is not true (and you know it isn't), create a new set containing the
update items that are NOT in the master server set. Print the number
and names of the unmatched servers.
3. Create a new master server set that excludes the valid updates.
4. Print the number of items in the original master server set and the
new master server set as well as the number of valid updates.
5. Write the contents of the new master server set to a printable
external file using the writelines file method. (See Python Notes)
"""
#reads two files (servers and updates) and converts the contents into two sets
updates = set(open('Python2/Labs/serverupdates.txt', 'r'))
servers = set(open('Python2/Labs/servers.txt', 'r'))
#print(updates)
#print(servers)
# Determine whether the list of updates exists in the master server list.
both = servers.intersection(updates)
#print(both)
#Print a message indicating whether or not this is true.
found = updates.issubset(servers)
if found == True:
print("Some updates not found in master list.")
"""
If it is not true (and you know it isn't), create a new set containing the
update items that are NOT in the master server set. Print the number
and names of the unmatched servers.
"""
diff = updates.difference(servers)
cnt=0
for i in diff:
cnt+=1
print(cnt, "server updates not found.")
for i in diff:
print(i, end=" ")
inter = updates.intersection(servers)
icnt = 0
for i in inter:
icnt+=1
print("Valid Updates:",icnt)
scnt = 0
for i in servers:
scnt+=1
print("Original Servers:",scnt)
uniq = updates.union(servers)
ucnt = 0
for i in uniq:
ucnt+=1
print("New Servers:",ucnt)
# Print the number of items in the original master server set and the
# new master server set as well as the number of valid updates
#writelines
#uniq.writelines()
#print(uniq.issubset(diff)) #False
#print(uniq.issuperset(diff)) #True |
c35252e4110e7c0ef3ead3a40cd4435fdcb888ca | Jbflow93/projectpython | /projectattm@.py | 1,509 | 4.125 | 4 | import random #any time i use random have to import first
def about_me():
print("Hi, My name is Jabari\n Im from Chicago\n My favorite team are the Denver Nuggets") # \n helps space out your strings
def q():
question1 = ["what state you live in?","How old are you?", "What is your favorite animal?"] #[] when making a list
n = random.randrange(0,len(question1)) #--> random function
print(n)
q()
ex_dict={} #{} when dealing with the dict
def Guestbook(ex_dict):ßå
fname = (input("what is your first name"))
lname = (input("what is your last name?"))
Note2me =(input("Leave a Note"))
ex_d={fname + lname:Note2me} #taking user input to put into a place holder dict. holds the value for the dict.
print(ex_dict)
ex_dict.update(ex_d) #.update is the function to update to dict
# print(fname + lname)
# ex_d = {fname}
# i=0
# while i < 2:
# Guestbook(ex_dict)
# i+=1
def ran():
n =random.randrange(0,2)
if n == 0: # == comparing variables while = assigns the variable
print("I believe i can Fly")
if n == 1:
print("You Can Do It")
if n == 2:
print("Having fun isnt hard when you got a library card")
ran()
i=""
while i != "goodbye":
i = input("""Hi my name is ___ ,\n
Enter "about" to learn more about me\n
Enter "q&a" to ask me a question\n
Enter "guestbook" to get added to my guestbook\n
Enter "random" for something random\n
Enter "goodbye" to say goodbye!""")
|
71f59141147284855dbb9c3e61de5e080ddc759f | mrPepcha/devops-python | /HW_lesson_7/HW_lesson_7.3.py | 2,076 | 3.703125 | 4 | #3. Реализовать программу работы с органическими клетками, состоящими из ячеек.
# Необходимо создать класс Клетка. В его конструкторе инициализировать параметр,
# соответствующий количеству ячеек клетки (целое число). В классе должны быть реализованы методы перегрузки
# арифметических операторов: сложение (add()), вычитание (sub()), умножение (mul()), деление (truediv()).
# Данные методы должны применяться только к клеткам и выполнять увеличение, уменьшение, умножение и
# целочисленное (с округлением до целого) деление клеток, соответственно
class Cell:
def __init__(self, count: int):
self._count = count
def __add__(self, other: "Cell") -> "Cell":
return Cell(self._count + other._count)
def __sub__(self, other: "Cell") -> "Cell":
if self._count > other._count:
return Cell(self._count - other._count)
print(f"{self._count} - {other._count}: разность ячеек <= 0")
def __mul__(self, other: "Cell") -> "Cell":
return Cell(self._count * other._count)
def __truediv__(self, other: "Cell") -> "Cell":
return Cell(self._count // other._count)
def make_order(self, per_row: int) -> str:
rows, tail = self._count // per_row, self._count % per_row
return '\n'.join(['*' * per_row] * rows + (['*' * tail] if tail else []))
def __str__(self) -> str:
return f"Клетка состоит из {self._count} ячеек"
c1 = Cell(16)
print(c1)
c2 = Cell(7)
print(c2)
print(c1 + c2)
print(c1 - c2)
print(c2 - c1)
print(c1 * c2)
print(c1 / c2)
print((c1 * c2).make_order(13))
|
c5fe33b12d65204cf065aeff0ffb7db2c37fa916 | dotastar/Leetcode-Design-CompanyEx | /Array/Insertion_Sort_List.py | 1,031 | 4.15625 | 4 | Sort a linked list using insertion sort.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if not head:
return head
dummy = ListNode(0)
dummy.next = head
current = head
while current.next:
if current.next.val < current.val:
pre = dummy
while pre.next.val < current.next.val:
pre = pre.next
temp = current.next
current.next = temp.next
temp.next = pre.next
pre.next = temp
else:
current = current.next
return dummy.next
# In order to skip the Time Limited Exceed, we did not scan through the head every time
# Only we check if the current.next.val < current.val, we need to insert
|
b15c7f66e5d574148dc9ac92344d92440ec0744f | arossouw/study | /python/math/factorial.py | 204 | 4.28125 | 4 | #!/usr/bin/python
# recursive function for factorial
# factorial example: 4! = 4 * 3 * 2 * 1 = 24
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
print factorial(4)
|
44d49e8ac8d2be472d6386b68844b56ab2c761fc | AK-1121/code_extraction | /python/python_22977.py | 176 | 3.96875 | 4 | # Dictionaries in Python and different ways of accessing it
for key in phonebook:
if key.startswith("Sm"):
print "Phone number of %s is %d" % (key, phonebook[key])
|
fa1b8c59f4a190a26a09156e186791a0e9ca7896 | josecervan/Python-Developer-EOI | /module2/exam/p2.py | 416 | 3.6875 | 4 | import datetime
def meetup_date(year, month):
assert year > 0
assert 1 <= month <= 12
new_date = datetime.date(year, month, 1)
while new_date.strftime('%A') != 'Thursday':
new_date += datetime.timedelta(days=1)
new_date += datetime.timedelta(days=7)
return new_date
print(meetup_date(2012, 3))
print(meetup_date(2015, 2))
print(meetup_date(2018, 6))
print(meetup_date(2020, 1))
|
36e360ab9854a1059c4d8fb9c01aa4f1ede54866 | VasilyShcherbinin/LCS-Suite | /XCS/Problem_Parity.py | 3,792 | 3.65625 | 4 | """
Name: Problem_Parity.py
Author: Vasily Shcherbinin
Created: December 29, 2018
Description: Parity Problem
Input: Binary string
Output: No. of 1’s modulo 2
"""
import random
bits = 11
instances = 10
def generate_parity_instance(bits):
""" """
num_bits = sanity_check(bits)
if num_bits is None:
print("Problem_Parity: ERROR - Specified binary string size is smaller than or 0")
else:
condition = []
one_count = 0
# Generate random boolean string
for i in range(bits):
condition.append(str(random.randint(0, 1)))
for j in range(len(condition)):
if int(condition[j]) == 1:
one_count += 1
if one_count % 2 == 0:
output = 0
else:
output = 1
return [condition, output]
def generate_complete_parity_data(myfile, bits):
""" Attempts to generate a complete non-redundant parity dataset."""
print("Problem_Parity: Attempting to generate complete parity dataset")
num_bits = sanity_check(bits)
if num_bits is None:
print("Problem_Parity: ERROR - Specified binary string bits is smaller than or 0")
else:
try:
fp = open("Demo_Datasets/" + myfile, "w")
# Make File Header
for i in range(num_bits):
fp.write('B_' + str(i) + "\t") # Bits
fp.write("Class" + "\n") # Class
for i in range(2 ** num_bits):
binary_str = bin(i)
string_array = binary_str.split('b')
binary = string_array[1]
while len(binary) < num_bits:
binary = "0" + binary
one_count = 0
for j in binary:
if int(j) == 1:
one_count += 1
if one_count % 2 == 0:
output = 0
else:
output = 1
for j in range(num_bits):
fp.write(binary[j] + "\t")
fp.write(str(output) + "\n")
fp.close()
print("Problem_Parity: Dataset Generation Complete")
except:
print(
"ERROR - Cannot generate all data instances for specified binary due to computational limitations")
def sanity_check(bits):
if bits > 0:
return bits
return None
def generate_parity_data(myfile, bits, instances):
""" """
print("Problem_Parity: Attempting to Generate parity dataset with " + str(instances) + " instances.")
num_bits = sanity_check(bits)
if num_bits is None:
print("Problem_Parity: ERROR - Specified binary string bits is smaller than or 0")
else:
fp = open("Demo_Datasets/" + myfile, "w")
# Make File Header
for i in range(num_bits):
fp.write('B_' + str(i) + "\t") # Bits
fp.write("Class" + "\n") # Class
for i in range(instances):
instance = generate_parity_instance(bits)
for j in instance[0]:
fp.write(str(j) + "\t")
fp.write(str(instance[1]) + "\n")
fp.close()
print("Problem_Parity: File Generated")
def randomize():
with open("../XCS/Demo_Datasets/"+str(bits)+"Parity_Data_Complete.txt", 'r') as source:
data = [(random.random(), line) for line in source]
data[1:] = sorted(data[1:])
with open("../XCS/Demo_Datasets/"+str(bits)+"Parity_Data_Complete_Randomized.txt", 'w') as target:
for _, line in data:
target.write(line)
if __name__ == '__main__':
#generate_parity_data(str(bits)+"-"+str(instances)+"Parity_Data.txt", bits, instances)
generate_complete_parity_data(str(bits)+"Parity_Data_Complete.txt", bits)
randomize() |
5e8519d5e072edf669177340f6eb56a9426a7f5d | nadhiyap/play2 | /smin.py | 142 | 3.65625 | 4 | a=int(input("enter number"))
l=[]
for i in range(a):
b=int(input("enter number"))
l.append(b)
b=min(l)
l.remove(b)
print(min(l))
|
eed94712e305b261d97adc901df6081e77f553b9 | ivhak/TDT4113 | /a4/src/calculator.py | 6,075 | 3.75 | 4 | '''
Calculator that runs in a loop and evaluates expressions given by the user
'''
import math
import numbers
import re
import sys
import numpy as np
from containers import Queue, Stack
from wrappers import Function, Operator
class Calculator():
'''
The calculator takes a string in the form of an equation, parses it into
operators, operands, functions and parentheses. It then converts from infix
to reverse polish notation and evaluates the expression.
'''
def __init__(self, debug=False):
self.functions = {
'EXP': Function(np.exp),
'LOG': Function(np.log),
'SIN': Function(np.sin),
'COS': Function(np.cos),
'SQRT': Function(np.sqrt),
'ABS': Function(np.abs)
}
self.constants = {
'PI': math.pi,
'TAU': math.tau,
'E': math.e
}
self.operators = {
'+': Operator(np.add, strength=0),
'~': Operator(np.subtract, strength=0),
'/': Operator(np.divide, strength=1),
'*': Operator(np.multiply, strength=1),
}
self.output_queue = Queue()
self.debug = debug
def calculate(self):
'''
Calculate the value of the RPN-equation stored in output_queue.
'''
stack = Stack()
while not self.output_queue.is_empty():
elem = self.output_queue.pop()
if isinstance(elem, numbers.Number):
stack.push(elem)
if isinstance(elem, Function):
_input = stack.pop()
stack.push(elem.execute(_input))
if isinstance(elem, Operator):
_second = stack.pop()
_first = stack.pop()
stack.push(elem.execute(_first, _second))
return stack.pop()
def generate_output_queue(self, input_list):
'''
Converts a list of operators, functions, operands, constants and
parentheses from infix notation to reverse polish notation using the
shunting-yard algorithm
'''
def operator_precedence(top, elem):
'''
Function to determine wether to pop from op_stack
'''
precedence = False
precedence |= isinstance(top, Function)
if isinstance(top, Operator):
precedence |= top.strength >= elem.strength
precedence &= top != '('
return precedence
self.output_queue = Queue()
op_stack = Stack()
for elem in input_list:
if isinstance(elem, numbers.Number):
self.output_queue.push(elem)
if isinstance(elem, Function):
op_stack.push(elem)
if isinstance(elem, Operator):
if not op_stack.is_empty():
top = op_stack.peek()
while top is not None and operator_precedence(top, elem):
self.output_queue.push(op_stack.pop())
if not op_stack.is_empty():
top = op_stack.peek()
else:
top = None
op_stack.push(elem)
if elem == '(':
op_stack.push(elem)
if elem == ')':
next_op = op_stack.pop()
while next_op != '(':
self.output_queue.push(next_op)
next_op = op_stack.pop()
while not op_stack.is_empty():
elem = op_stack.pop()
self.output_queue.push(elem)
if self.debug:
print(f'\nParsed string: {input_list}')
print(f'Output queue: {self.output_queue._items}\n')
def parse_string_to_list(self, input_str):
'''
Parse input_str into a list of operators, operands, parentheses,
constants and functions, using regular expressions. Then substitute the
functions and operators found with their corresponding wrapper object.
Strings in the form of positive or negative integers/floats are
converted to float.
'''
re_parts = (
r'-?\d+\.\d+', # Floating point numbers
r'-?\d+', # Integers
r'\(|\)', # Parentheses
r'\+|\~|\*|/|', # Operators
'|'.join(self.functions.keys()), # Functions
'|'.join(self.constants.keys()), # Constants
)
regex = '|'.join(re_parts)
# re.findall preserves the order of the matches
matches = re.findall(regex, input_str.upper())
result = []
for match in matches:
# Function
if match in self.functions.keys():
result += [self.functions[match]]
# Operator
elif match in self.operators.keys():
result += [self.operators[match]]
# Constants
elif match in self.constants.keys():
result += [self.constants[match]]
# Parentheses
elif match in ('(', ')'):
result += [match]
# Probably a number
else:
try:
result += [float(match)]
except ValueError:
pass
return result
def main():
'''
Run the interactive calculator
'''
debug = False
if len(sys.argv) == 2 and sys.argv[1] == "-d":
debug = True
calc = Calculator(debug=debug)
print('Disclaimer: The operator minus is written as "~"')
print('Enter an equation')
while True:
try:
equation = input('> ')
arg_list = calc.parse_string_to_list(equation)
calc.generate_output_queue(arg_list)
res = calc.calculate()
print(f' {equation} = {res}')
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
main()
|
cfc1924b593305f8eb3bbb5cdf7bc5fe41ac9b82 | mananvyas/python-practice | /operators.py | 304 | 3.859375 | 4 | #Operator supports multiplying string
lotsOfHello = "hello" * 10
print(lotsOfHello)
#Do not support string and number concat wtih +
#lotsOfHello = "hello" + 10
#print(lotsOfHello)
#Supports forming new list with * operator similar to support with string as above
mylist = [2,3,4]
print(mylist * 3)
|
8a9741489abbe7d6f25b7468e0ee6fecba94c74a | adityasingh108/python-Practice | /DSa/algorithm/insertion_sort1.py | 161 | 3.71875 | 4 | # from tkinter.constants import NUMERIC
def insertion_sort():
numbers=[i for i in range(100) if i%2!=0]
print(numbers)
insertion_sort() |
ffc56cf0367f4d06cf1052261fadd055c6332e40 | jihunroh/ProjectEuler-Python | /ProjectEulerCommons/GeometricalNumbers.py | 702 | 3.59375 | 4 | from math import sqrt
from itertools import count
def generate_triangular():
for i in count(1):
yield int(i* (i + 1) * 0.5)
def generate_pentagonal():
for i in count(1):
yield pentagonal(i)
def pentagonal(i):
return int(i* (3 * i - 1) * 0.5)
def is_triangular(n):
return ((-1 + sqrt(1 + 8 * n)) / 2).is_integer()
def is_pentagonal(n):
return ((1 + sqrt(1 + 24 * n)) / 6).is_integer()
def is_hexagonal(n):
return ((1 + sqrt(1 + 8 * n)) / 4).is_integer()
def is_heptagonal(n):
return ((3 + sqrt(9 + 40 * n)) / 10).is_integer()
def is_octagonal(n):
return ((1 + sqrt(1 + 6 * n)) / 3).is_integer()
def is_square(n):
return sqrt(n).is_integer() |
0a9ed1c1ef632080c2cd82b204ee5a552d0204c2 | Evangeline-T/6.009-1-solution | /lab7/lab.py | 14,817 | 3.5 | 4 | # NO ADDITIONAL IMPORTS!
import doctest
from text_tokenize import tokenize_sentences
class Trie:
def __init__(self, key_type):
self.value = None
self.children = dict()
self.key_type = key_type
def __setitem__(self, key, value):
"""
Add a key with the given value to the trie, or reassign the associated
value if it is already present in the trie. Assume that key is an
immutable ordered sequence. Raise a TypeError if the given key is of
the wrong type.
"""
key_type = type(key)
if self.key_type != key_type: # If the key type is not the same, return a Type Error.
raise TypeError
if len(key) == 0: # When we are done with the key, set the value as told.
self.value = value
return
if key[:1] in self.children: # We index like this to take into account tuples; if the next letter is in the children already, continue along that branch.
self.children[key[:1]][key[1:]] = value
else:
new_trie = Trie(key_type) # Create a new branch if the child does not exist and continue.
self.children[key[:1]] = new_trie
new_trie[key[1:]] = value
def __getitem__(self, key):
"""
Return the value for the specified prefix. If the given key is not in
the trie, raise a KeyError. If the given key is of the wrong type,
raise a TypeError.
>>> t = Trie(tuple)
>>> t[2, ] = 'cat'
>>> t[1, 0, 1, 80] = 'tomato'
>>> t[2, ]
'cat'
>>> t[1, 0, 1, 80]
'tomato'
"""
key_type = type(key)
if self.key_type != key_type: # If the key type is not the same, return a Type Error.
raise TypeError
if len(key) == 0:
if self.value == None:
raise KeyError # If we get to the end of the key, and the value is None, return a KeyError.
return self.value
else:
next_trie = self.children[key[:1]] # We go to the next trie, and recurse.
return next_trie[key[1:]]
def __delitem__(self, key):
"""
Delete the given key from the trie if it exists. If the given key is not in
the trie, raise a KeyError. If the given key is of the wrong type,
raise a TypeError.
>>> t = Trie(str)
>>> t['bat'] = True
>>> t['bar'] = True
>>> t['bark'] = True
>>> del t['bar']
>>> t['bar']
Traceback (most recent call last):
...
KeyError
"""
self[key] # This checks to see if we will get a key or type error.
self[key] = None # We set the key's value to None, as if we were deleting it.
def __contains__(self, key):
"""
Is key a key in the trie? return True or False.
>>> t = Trie(tuple)
>>> t[2, ] = 'cat'
>>> t[1, 0, 1, 80] = 'tomato'
>>> (2, ) in t
True
>>> (1,) in t
False
"""
try:
self[key]
except KeyError:
return False
else:
return True
def __iter__(self):
"""
Generator of (key, value) pairs for all keys/values in this trie and
its children. Must be a generator!
"""
def recursive_step(trie, key): # Make a recursive function that goes through the children for us.
if trie.value: # If the current node has a value, yield the current node and its value.
yield (key, trie.value)
for child in trie.children: # Do the same for all the children.
yield from recursive_step(trie.children[child], key + child)
if self.key_type == tuple: # Get the correct initial key for the very first node.
key = ()
else:
key = ""
return recursive_step(self, key)
def make_word_trie(text):
"""
Given a piece of text as a single string, create a Trie whose keys are the
words in the text, and whose values are the number of times the associated
word appears in the text
>>> t = make_word_trie("Hello, my name is Isuf. I am from London and study at MIT in the USA")
>>> t['hello']
1
>>> 'my' in t
True
"""
sentences = tokenize_sentences(text)
word_freq = {}
for i in range(len(sentences)):
words_in_sentence = sentences[i].split(" ")
for word in words_in_sentence: # We get each word that hasn't been put in the dictionary and initialize it's value to 1.
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
word_trie = Trie(str) # We create a Trie that has a str type.
for word in word_freq:
word_trie[word] = word_freq[word] # We set each word as a key with its frequency as its value.
return word_trie
def make_phrase_trie(text):
"""
Given a piece of text as a single string, create a Trie whose keys are the
sentences in the text (as tuples of individual words) and whose values are
the number of times the associated sentence appears in the text.
>>> t = make_phrase_trie("Hello. There is a cat in my house. I'm not sure why. There is a cat in my house.")
>>> t[('hello',)]
1
>>> ('there', 'is', 'a', 'cat', 'in', 'my', 'house') in t
True
"""
sentences = tokenize_sentences(text)
sentence_freq = {}
for sentence in sentences:
if sentence not in sentence_freq:
sentence_freq[sentence] = 1
else:
sentence_freq[sentence] += 1
sentence_trie = Trie(tuple)
for sentence in sentence_freq:
sentence_trie[tuple(sentence.split(" "))] = sentence_freq[sentence] # We do a similar thing to above except we use sentences and use tuples.
return sentence_trie
def autocomplete(trie, prefix, max_count=None):
"""
Return the list of the most-frequently occurring elements that start with
the given prefix. Include only the top max_count elements if max_count is
specified, otherwise return all.
Raise a TypeError if the given prefix is of an inappropriate type for the
trie.
>>> t = Trie(str)
>>> t['read'] = 7
>>> t['red'] = 3
>>> t['reads'] = 9
>>> t['hello'] = 2
>>> t['help'] = 10
>>> autocomplete(t, 're', 1)
['reads']
>>> autocomplete(t, 're')
['reads', 'read', 'red']
>>> autocomplete(t, 'e')
[]
"""
if trie.key_type != type(prefix): # If the types are not correct, raise a TypeError.
raise TypeError
pointer = 0
next_trie = trie
while pointer < len(prefix): # We go along the prefix, and make sure that the children still exist.
try:
next_trie = next_trie.children[prefix[pointer:pointer + 1]] # Indexing like this takes into account tuples and strings.
pointer += 1
except KeyError: # If the prefix is not in the trie, return an empty list.
return []
sorted_list = sorted(next_trie, key = lambda p: p[1], reverse = True) # We sort all the nodes and values by value is descending order.
sorted_words = [prefix + rest for rest, freq in sorted_list] # Create a list of the prefix plus the rest of the word based on the list above.
if max_count == None:
return sorted_words # Return all the sorted words if max_count is None.
else:
return sorted_words[:max_count] # If max_count is not none, return the sorted words up to the max count.
def letter_insert(word):
"""
Return a list of all possible words when inserting each letter from the
alphabet into each place in the word.
"""
output = []
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for letter in alphabet:
for i in range(len(word)):
new_word = word[:i] + letter + word[i:]
if new_word not in output:
output.append(new_word)
return output
def letter_delete(word):
"""
Return a list of possble words from a given word when deleting each letter
from that word.
"""
output = []
for i in range(len(word)):
output.append(word[:i] + word[i + 1:])
return output
def replace_letter(word):
"""
Return a list of all possible words when replacing a letter from that word
with any letter from the alphabet.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
output = []
for letter in alphabet:
for i in range(len(word)):
new_word = word[:i] + letter + word[i + 1:]
if new_word not in output:
output.append(new_word)
return output
def letter_swap(word):
"""
Return a list of words from a given word where every 2 adjacent letters
are swapped.
"""
word = list(word)
output = []
for i in range(len(word) - 1):
mutated_word = ""
output.append(mutated_word.join(word[:i] + [word[i + 1]] + [word[i]] + word[i + 2:]))
return output
def autocorrect(trie, prefix, max_count=None):
"""
Return the list of the most-frequent words that start with prefix or that
are valid words that differ from prefix by a small edit. Include up to
max_count elements from the autocompletion. If autocompletion produces
fewer than max_count elements, include the most-frequently-occurring valid
edits of the given word as well, up to max_count total elements.
>>> t = Trie(str)
>>> t['read'] = 7
>>> t['red'] = 3
>>> t['reads'] = 9
>>> t['hello'] = 2
>>> t['help'] = 10
>>> autocorrect(t, 'rel')
['red']
>>> autocorrect(t, 'red', 3)
['red', 'read']
>>> autocorrect(t, 'he', 1)
['help']
"""
if max_count is None or type(max_count) != int: # If max count is None or not an integer, we do autocomplete with None, else we do autocomplete with the max_count.
auto_corrected_words = autocomplete(trie, prefix, None)
else:
auto_corrected_words = autocomplete(trie, prefix, max_count)
all_possible_edits = list(set(letter_insert(prefix) + letter_delete(prefix) + replace_letter(prefix) + letter_swap(prefix))) # We get all the possible edits.
valid_edits = []
for edit in all_possible_edits:
if edit in trie:
valid_edits.append((edit, trie[edit])) # Now we get just the edits in the trie.
sorted_edits = sorted(valid_edits, key = lambda p: p[1], reverse = True) # Sort the edits based on their frequency.
words = auto_corrected_words
i = 0
while True:
if max_count is not None:
if len(words) == max_count: # Once the number of words we have is equal to max_count, we can break.
break
edit = sorted_edits[i][0] # We get each of the valid edits and check if it is words.
if edit not in words:
words.append(edit)
if edit == sorted_edits[-1][0]: # If we are on the last word, we can break.
break
i += 1
return words
def word_filter(trie, pattern):
"""
Return list of (word, freq) for all words in trie that match pattern.
pattern is a string, interpreted as explained below:
* matches any sequence of zero or more characters,
? matches any single character,
otherwise char in pattern char must equal char in word.
>>> t = Trie(str)
>>> t['read'] = 7
>>> t['red'] = 3
>>> t['reads'] = 9
>>> t['hello'] = 2
>>> t['help'] = 10
>>> word_filter(t, "r*d")
[('red', 3), ('read', 7)]
>>> word_filter(t, "??")
[]
>>> word_filter(t, "he?*")
[('hello', 2), ('help', 10)]
"""
def word_filter_recursive(trie, pattern, key = ''):
output = []
if not pattern: # If we are at the end of the pattern, we can return the key, value.
if trie.value:
return [(key, trie.value)]
elif pattern[0] == "*":
output.extend(word_filter_recursive(trie, pattern[1:], key)) # If we have a *, we add a sequence of size 0 and the sequences with the children.
for child in trie.children:
output.extend(word_filter_recursive(trie.children[child], pattern, key + child))
elif pattern[0] == '?': # If we have a ?, we just add the child and carry on.
for child in trie.children:
output.extend(word_filter_recursive(trie.children[child], pattern[1:], key + child))
else:
for child in trie.children:
if child == pattern[0]: # If we have a letter, we check that they match and move on with those.
output.extend(word_filter_recursive(trie.children[child], pattern[1:], key + child))
return output
patterned_words = set(word_filter_recursive(trie, pattern)) # Create a set to remove duplicates.
return list(patterned_words) # Turn into list.
# you can include test cases of your own in the block below.
if __name__ == '__main__':
doctest.testmod()
# with open("alice.txt", encoding="utf-8") as f:
# alice = f.read()
# alice_sentence = make_phrase_trie(alice)
# # print(autocomplete(alice_sentence, (), 6))
# alice_words = make_word_trie(alice)
# # print(autocorrect(alice_words, 'hear', 12))
# # print(len(autocomplete(alice_sentence, ())))
# # print(s um(alice_sentence[i] for i in autocomplete(alice_sentence, ())))
# with open("meta.txt", encoding="utf-8") as f:
# meta = f.read()
# meta_words = make_word_trie(meta)
# # print(autocomplete(meta_words, 'gre', 6))
# # print(word_filter(meta_words, 'c*h'))
# with open("tale.txt", encoding="utf-8") as f:
# tale = f.read()
# tale_words = make_word_trie(tale)
# # print(word_filter(tale_words, 'r?c*t'))
# with open("pride.txt", encoding="utf-8") as f:
# pride = f.read()
# pride_words = make_word_trie(pride)
# # print(autocorrect(pride_words, 'hear'))
# with open("dracula.txt", encoding="utf-8") as f:
# dracula = f.read()
# dracula_words = make_word_trie(dracula)
# # print(len(autocomplete(dracula_words, "")))
# # print(sum(dracula_words[i] for i in autocomplete(dracula_words, "")))
|
e070dc6d07b0cb71425c3510bf98c4d147ed2908 | StRobertCHSCS/ics2o1-201819-igothackked | /unit_2/2_7_2_Loop_Patterns.py | 123 | 4.09375 | 4 |
number = int(input("Enter a number: "))
while number > 0:
print(number)
number = number - 1
print("Blastoff!!!") |
3a3d63af71de70e7c62e7a29d9fc8e911f16a8df | gnibre/leetcode | /super_ugly_number.py | 1,661 | 3.65625 | 4 | import heapq
# heapq, is a heap or not? why can't i use first n
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
# k <=100;
# O(N) to get smallest
# rule, list itself, became the base for each prime.
k = len(primes)
res = [1]
pp = [0] * k # prime list, next candidate index in the res.
pc = [ [primes[i], i] for i in xrange(0,k)]
hp = [] # used as heap to sort.
for v in pc:
heapq.heappush(hp,v)
# mip = 0
sz = 1
while sz<n:
mi = heapq.heappop(hp)
cdd = mi[0]
mip = mi[1]
if res[-1] != cdd:
res.append(cdd)
sz+=1
# even it's not added to res, pp should still be updated.
pp[mip]+=1
heapq.heappush(hp,[ res[pp[mip]]*primes[mip], mip])
# print res
return res[n-1]
# while sz<n:
# # O(N) # TLE at n =100,000
# mi = sys.maxint
# for i in xrange(0,k):
# cdd = res[pp[i]] * primes[i]
# if cdd < mi:
# mi = cdd
# mip = i
# # pick mip
# if res[-1] != mi:
# res.append(mi)
# sz+=1
# # even it's not added to res, pp should still be updated.
# pp[mip]+=1
# print res
# return res[n-1]
|
068fc2f88ec93d2599259cf7f2d7f33332dbfea3 | PandaRec/Laba1 | /Laba1/7.1.py | 263 | 3.75 | 4 | count_of_rows = int(input())
rows = list()
flag = False
for i in range(count_of_rows):
rows.append(input())
for txt in rows:
if txt.lower().__contains__("кот"):
print("МЯУ")
flag = True
break
if not flag:
print("нет")
|
ff6b38c5446ef10c35c67a318be36a030458b206 | Zetinator/cracking_the_coding_interview | /python/string_rotation.py | 514 | 4.21875 | 4 | """1.9 String Rotation: Assume you have a method isSubst ring which checks if one word is a substring
of another. Given two strings, 51 and 52, write code to check if 52 is a rotation of 51 using only one
call to isSubstring (e.g., "waterbottle" is a rotation of "erbottlewat").
"""
def string_rotation(string_1: str, string_2: str)-> bool:
return string_2 in string_1 + string_1
# test
t_1 = "waterbottle"
t_2 = "erbottlewat"
print(f'string_rotation: test: {t_1} vs {t_2}, ans: {string_rotation(t_1, t_2)}')
|
e5f8f54b4b2f7c8e4c3d2a9eafa4854928b5dd04 | zhouyuanp/python | /Object/Inherit.py | 814 | 4.03125 | 4 | #测试继承的基本使用
class Person:
def __init__(self,name,age):
self.name = name
self.__age = age #私有属性
def say_age(self):
print("我也不知道是该坚持还是该放弃")
class Student(Person): #子类继承父类的属性和方法
def __init__(self,name,age,score):
Person.__init__(self,name,age) #调用父类的构造器 #调用父类的方法 父类名.方法名(方法参数) #继承父类的属性#必须显式的调用父类初始化方法,不然解释器不会去调用
self.score = score
#Student-->Person--->object 类
print(Student.mro()) #打印类的继承层次
s = Student("娃哈哈",218,20)
s.say_age()
print(s.name)
#print(s.age)
print(s._Person__age) #调用到私有属性
print(dir(s)) #查看属性
|
0fac0007644bbaad9ba489ca138ec9cc256f2249 | anishst/Learn | /Programming/Python/DateTime Operations/DateTime_Practice.py | 1,413 | 3.875 | 4 | import time #https://docs.python.org/2/library/time.html
import datetime
from datetime import timedelta
# strftime #https://docs.python.org/2/library/time.html#time.strftime
print(time.strftime("%m/%d/%Y"))
print(time.strftime("%Y-%m-%d"))
print(time.strftime("%d-%m-%Y %H:%M:%S %p")) # timestamp
print(time.tzname)
print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
# datetime related https://docs.python.org/2/library/datetime.html
print(datetime.date.today())
print("Counting time until")
today = datetime.date.today()
nyd = datetime.date(2019, 1,1)
print("There are ",(nyd-today).days, " days until {} ".format(nyd))
print("Show elapsed days")
today = datetime.date.today()
nyd = datetime.date(2018,10,1)
print("It has been ",(today-nyd).days, " days since {} ".format(nyd))
bd = datetime.date(1979,7,1)
today = datetime.date.today()
print("You are ",(today-bd).days, " days old")
print("**** subtract days from date ***")
print(datetime.date.today() - timedelta(days=10))
print(datetime.date.today() - timedelta(days=365*7))
# Script execution time
# method 1
print("Testing Timing Script")
start_time = time.time()
time.sleep(3)
print("Script completed in: {:.2f} seconds".format(time.time() - start_time))
# method 2
import timeit
start_time = timeit.default_timer()
# code you want to evaluate
time.sleep(3)
elapsed = timeit.default_timer() - start_time
print(elapsed)
|
0234fe70753c553dd4352bf84ff1c83c24652355 | lamkavan/cs-learning-2019 | /Lessons/Section_3/Docstring/Docstrings.py | 2,965 | 4.53125 | 5 | ### The following describes basic docstrings for Python ###
# We use docstrings to document our code. Documenting the code makes it easier to read
# and understand. It is good practice, but not required for the code to work.
# We only cover docstrings for classes and functions/methods here.
# Note that there are many formats for docstrings and depending on which one you
# use the documentation will look a bit different.
# We begin with two examples of writing docstrings for functions.
def print_list_contents(input_list):
"""
Prints to the console the elements of input_list with each element
on a new line
Args:
input_list (list): A list of elements
Returns:
None
"""
for item in input_list:
print(item)
def compute_multiplication(input_list, factor):
"""
Takes a list of numbers, input_list, and returns a list where each number
is replaced with the product when multiplied with factor
Args:
input_list (list of num): A list of numbers
factor (int, float): A number to multiply list number(s) with
Returns:
list: The original list with all the numbers multiplied by factor
"""
return [num * factor for num in input_list]
# Ok do you understand the examples? Not too bad right? Anyhow below is the general format.
def function_name(arg1, arg2, arg3):
"""
<Description of function goes here>
Args:
arg1 (<type of arg1>): <Description of arg1>
arg2 (<type of arg2>): <Description of arg2>
arg3 (<type of arg3>): <Description of arg3>
Returns:
<return type>: Description of the return
"""
# Blah blah blah (this is where the actual function is and is not part of docstring)
pass
# Ok now lets talk about classes and the methods under a class. The best way to learn is just to see an example.
class Car:
"""
A car (Here we want to describe the class)
Attributes:
age (int): The car's age
color (str): The car's color
name (str): The car's name in all upper case letters
"""
def __init__(self, age, color, name):
"""
The constructor for car
Args:
age (int): The car's age
color (str): The car's color
name (str): The car's name
"""
self.age = age
self.color = color
self.name = name.upper()
def car_name(self):
"""
Prints the car's name to the console
Returns:
None
"""
print(self.name)
# Alright notice how the constructor method does not have the return part in the docstring.
# This is because the constructor should not return anything other than none.
# Also notice that we never include self in the Args section of the docstring.
# The docstrings for methods is the same for functions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.