blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
67341965a301d547ba5422c3d1e256a2f513999b | JoaolSoares/CursoEmVideo_python | /Exercicios/ex020.py | 360 | 3.5625 | 4 | from random import shuffle
a1 = input('Diga o nome de um aluno: ')
a2 = input('Diga o nome de um aluno: ')
a3 = input('Diga o nome de um aluno: ')
a4 = input('Diga o nome de um aluno: ')
lista = [a1, a2, a3, a4]
shuffle(lista)
print('')
print('{:-^70}' .format(''))
print('A ordem escolhida foi: {}' .format(lista))
print('{:-^70}' .format(''))
|
bc0e0a3075ea950cf67bc7bfe44201842624a81f | JoaolSoares/CursoEmVideo_python | /Exercicios/ex029.py | 223 | 3.71875 | 4 | n1 = int(input('Qual foi sua velocidade: '))
if n1 <= 80:
print('PARABENS! Por nao ter utrapassado o limite de 80km/h')
else:
print('ISSO NÃO FOI LEGAL! Você recebera uma multa de R${}' .format((n1 - 80) * 7)) |
fc95289439761478c89aaef10340dd1c0c149a36 | wangchengww/great-ape-Y-evolution | /palindrome_analysis/palindrome_read_depth/calculate_copy_number/Palindrome_scripts/line_up_columns.py | 4,441 | 3.609375 | 4 | #!/usr/bin/env python
import sys
def parse_columns(s):
if (".." in s):
(colLo,colHi) = s.split("..",1)
(colLo,colHi) = (int(colLo),int(colHi))
return [col-1 for col in xrange(colLo,colHi+1)]
else:
cols = s.split(",")
return [int(col)-1 for col in cols]
# commatize--
# Convert a numeric string into one with commas.
def commatize(s):
if (type(s) != str): s = str(s)
(prefix,val,suffix) = ("",s,"")
if (val.startswith("-")): (prefix,val) = ("-",val[1:])
if ("." in val):
(val,suffix) = val.split(".",1)
suffix = "." + suffix
try: int(val)
except: return s
digits = len(val)
if (digits > 3):
leader = digits % 3
chunks = []
if (leader != 0):
chunks += [val[:leader]]
chunks += [val[ix:ix+3] for ix in xrange(leader,digits,3)]
val = ",".join(chunks)
return prefix + val + suffix
spacer = " "
inSeparator = None
outSeparator = None
passComments = []
bunchExtras = None # column number after which we no longer align
rightJustify = [] # column numbers to right-justify
columnWidth = {} # map from column number to width
commas = [] # column numbers to commatize values (numeric string is assumed)
doubleSep = [] # column numbers to give a double output separator before
barSep = [] # column numbers to give a special output separator before
for arg in sys.argv[1:]:
if ("=" in arg):
argVal = arg.split("=",1)[1]
if (arg.startswith("--spacer=")):
spacer = argVal
elif (arg.startswith("--separator=")):
inSeparator = argVal
elif (arg == "--tabs"):
inSeparator = "\t"
elif (arg == "--bars"):
outSeparator = " |"
elif (arg == "--passcomments"):
passComments += ["#"]
elif (arg.startswith("--passcomments=")):
passComments += [argVal]
elif (arg.startswith("--bunch=")):
bunchExtras = int(argVal)
elif (arg.startswith("--rightjustify=")) or (arg.startswith("--right=")):
rightJustify += parse_columns(argVal)
elif (arg.startswith("--width=")):
for spec in argVal.split(","):
assert (":" in spec), "can't understand: %s" % arg
(col,w) = spec.split(":",1)
(col,w) = (int(col)-1,int(w))
assert (col not in columnWidth)
columnWidth[col] = w
elif (arg.startswith("--commas=")) or (arg.startswith("--commatize=")):
commas += parse_columns(argVal)
elif (arg.startswith("--double=")):
doubleSep += parse_columns(argVal)
elif (arg.startswith("--bar=")):
barSep += parse_columns(argVal)
elif (arg.startswith("--")):
assert (False), "unknown argument: %s" % arg
else:
assert (False), "unknown argument: %s" % arg
if (passComments == []): passComments = None
colToWidth = {}
for col in columnWidth: colToWidth[col] = columnWidth[col]
lines = []
for line in sys.stdin:
line = line.strip()
lines += [line]
if (line == ""): continue
if (passComments != None):
isComment = False
for prefix in passComments:
if (line.startswith(prefix)):
isComment = True
break
if (isComment):
continue
if (inSeparator == None): columns = line.split()
else: columns = line.split(inSeparator)
if (bunchExtras != None) and (len(columns) > bunchExtras):
columns = columns[:bunchExtras] + [" ".join(columns[bunchExtras:])]
for col in range(len(columns)):
if (col in columnWidth): continue
if (col in commas): w = len(commatize(columns[col]))
else: w = len(columns[col])
if (col not in colToWidth): colToWidth[col] = w
else: colToWidth[col] = max(w,colToWidth[col])
for line in lines:
if (line == ""):
print
continue
if (passComments != None):
isComment = False
for prefix in passComments:
if (line.startswith(prefix)):
isComment = True
break
if (isComment):
print line
continue
if (inSeparator == None): columns = line.split()
else: columns = line.split(inSeparator)
if (bunchExtras != None) and (len(columns) > bunchExtras):
columns = columns[:bunchExtras] + [" ".join(columns[bunchExtras:])]
for col in range(len(columns)):
if (col in rightJustify): fmt = "%*s"
else: fmt = "%-*s"
val = columns[col]
if (col in commas): val = commatize(val)
val = fmt % (colToWidth[col],val)
if (outSeparator != None):
val += outSeparator
if (col+1 in barSep): val += "|"
if (col+1 in doubleSep): val += outSeparator.strip()
else:
if (col+1 in barSep): val += " |"
columns[col] = val
line = spacer.join(columns)
print line.rstrip()
|
ebbffeb694f13ec4d1d5282089eb228a9709a422 | jet76/CS-4050 | /Project 04/SumsToN.py | 346 | 3.875 | 4 | def recurse(num, sum, out):
if sum > n:
return
else:
sum += num
if sum == n:
print(out + str(num))
return
else:
out += str(num) + " + "
for i in range(num, n + 1):
recurse(i, sum, out)
n = int(input("Enter a positive integer: "))
for i in range(1, n + 1):
recurse(i, 0, "") |
d6e556e4afd34c6a8056dfa1df965ba5f6fd5c48 | Z477/concurrent-program | /2_multi_threading/demo_5_threadpoolexecutor.py | 1,533 | 3.640625 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
Use concurrent.futures to implement multi thread
Created on Jun 30, 2019
@author: siqi.zeng
@change: Jun 30, 2019 siqi.zeng: initialization
'''
import concurrent.futures
import logging
import time
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [line:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def drink_water(name):
time.sleep(2)
logging.info("%s finish drink", name)
return "result of {}".format(name)
def eat_food(name):
time.sleep(2)
logging.info("%s finish eat", name)
return "result of {}".format(name)
def do_sports(name):
time.sleep(2)
logging.info("%s finish do sports", name)
return "result of {}".format(name)
def play_game(name):
time.sleep(2)
logging.info("%s finish play game", name)
return "result of {}".format(name)
def watch_tv(name):
time.sleep(2)
logging.info("%s finish watch TV", name)
return "result of {}".format(name)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
logging.info("start")
future_to_person = [executor.submit(drink_water, "A"), executor.submit(eat_food, "B"),
executor.submit(do_sports, "C"), executor.submit(play_game, "D"),
executor.submit(watch_tv, "E")]
concurrent.futures.wait(future_to_person, timeout=5)
for future_object in future_to_person:
result = future_object.result()
logging.info("%s", result)
logging.info("end")
|
ebd6f80484ef4a051fadde4199f8b27c366fa283 | JMSMonteiro/AED-Proj2 | /src/gui.py | 7,450 | 3.75 | 4 | from tkinter import *
from tkinter import messagebox
import main
########## FUNCTIONS JUST TO HAVE TEXT/CLEAR TEXT FROM THE ENTRIES ##########
#Still looking for a way to make all of these into 2 functions
def on_entry_click_0(event): #Cities Entry
"""function that gets called whenever entry is clicked"""
entry_cities.config(fg = 'black')
if entry_cities.get() == '# of cities':
entry_cities.delete(0, "end") #delete all the text in the entry
entry_cities.insert(0, '') #Insert blank for user input
def on_entry_click_1(event): #Cenario Entry
entry_cenario.config(fg = 'black')
if entry_cenario.get() == 'Cenario 1 or 2':
entry_cenario.delete(0, "end") #delete all the text in the entry
entry_cenario.insert(0, '') #Insert blank for user input
def on_focusout_0(event): #Cities Entry
if entry_cities.get() == '':
entry_cities.insert(0, '# of cities')
entry_cities.config(fg = 'grey')
elif not is_int(entry_cities.get()): #If the input isn't valid, the text goes red
entry_cities.config(fg = 'red')
def on_focusout_1(event): #Cenario Entry
if entry_cenario.get() == '':
entry_cenario.insert(0, 'Cenario 1 or 2')
entry_cenario.config(fg = 'grey')
elif not is_int(entry_cenario.get()): #If the input isn't valid, the text goes red
entry_cenario.config(fg = 'red')
########## CHECKBOX STUFF ###########
def on_check_cenario_1():
cenario_2_check.deselect()
def on_check_cenario_2():
cenario_1_check.deselect()
#J#M#S#M#o#n#t#e#i#r#o# THAT PART OF THE CODE THAT USES THE OTHER .py FILES AND DOES SOMETHING PRODUCTIVE #J#M#S#M#o#n#t#e#i#r#o#
def is_int(string):
try:
int(string)
return True
except ValueError:
return False
def check_values():
cities = is_int(entry_cities.get())
cenario = (cenario_1.get() or cenario_2.get())
algorithm = (brute.get() or brute_opt.get() or recursive.get() or recursive_g.get())
if cities and cenario and algorithm:
#do execute the program
#0 = brute || 1 = brute_optimised || 2 = recursive || 3 = recursive greedy
if int(entry_cities.get()) < 2:
messagebox.showerror("Invalid City Value", "The city number must be greater or equal to 2.")
return
map_graph = main.geraMapa(entry_cities.get(), [cenario_1.get(), cenario_2.get()])
if brute.get():
run('Results - Brute Force', 0, map_graph)
if brute_opt.get():
run('Results - Brute Force Optimized', 1, map_graph)
if recursive.get():
run('Results - Recursive', 2, map_graph)
if recursive_g.get():
run('Results - Recursive Greedy', 3, map_graph)
else:
if cities:
if int(entry_cities.get()) < 2:
messagebox.showerror("Invalid City Value", "The city number must be greater or equal to 2.")
if not cities:
messagebox.showerror("Invalid City Number", "The value of 'Number of cities' is not valid!")
if not cenario:
messagebox.showerror("Invalid Cenario", "Please select one of the cenarios.")
if not algorithm:
messagebox.showerror("Invalid Algorithm", "Please select at least one of the algorithms.")
def run(window_title, algorithm, map_graph):
results = main.main(map_graph, [cenario_1.get(), cenario_2.get()], algorithm)
###Popup Window with results###
pop_up = Toplevel()
pop_up.title(window_title)
#Pop-up labels
label_origin = Label(pop_up, text="City of origin: ")
label_total_dist = Label(pop_up,text="Total distance: ")
label_path = Label(pop_up, text="Route chosen: ")
label_time = Label(pop_up, text="Calculated in: ")
#Pop-up info to be displayed
grafo_info = Message(pop_up, width=400, text=str(results[0])) #Mess arround with the width parameter to fit all your needs
origin_info = Message(pop_up, width=300, text=str(results[1]))
total_dist_info = Message(pop_up, width=300, text=str(results[2]))
path_info = Message(pop_up, width=300, text=str(results[3]))
time_info = Message(pop_up, width=300, text=str(results[4]))
#Grid it!
label_origin.grid(row=10, pady=10, sticky=E)
label_total_dist.grid(row=12, pady=10, sticky=E)
label_path.grid(row=14, pady=10, sticky=E)
label_time.grid(row=16, pady=10, sticky=E)
grafo_info.grid(row=0, columnspan=4, pady=10, padx=10)
origin_info.grid(row=10, column=2, pady=10, sticky=W)
total_dist_info.grid(row=12, column=2, pady=10, sticky=W)
path_info.grid(row=14, column=2, pady=10, sticky=W)
time_info.grid(row=16, column=2, pady=10, sticky=W)
btn = Button(pop_up, text="Dismiss", command=pop_up.destroy)
btn.grid(row=100, pady=10, column=1, sticky=W)
########## ACTUAL TKINTER'S CODE STARTS HERE (Most of it anyways)##########
###Main Window with parameter and such###
root = Tk() #does stuff
root.wm_title("AED - Project #2") #Window Name
top_frame = Frame(root) #Creates top frame
top_frame.pack() #Packs the frame in the window
bottom_frame = Frame(root) #Creates bottom frame
bottom_frame.pack(side=BOTTOM) #Packs the frame in the window. under the other frame
calculate_btn = Button(bottom_frame,text="Calculate", fg="green", command=check_values) #button to start program
exit_btn = Button(bottom_frame, text="Exit", fg="green", command=root.quit) #button to exit the GUI
calculate_btn.pack(side=LEFT) #places the button as far to the left as it can
exit_btn.pack(side=LEFT) #places the button as far to the left as it can
#Grid for inputs and stuff
#sticky -> [N,S,W,E]
label_cities = Label(top_frame, text="Number of cities: ")
label_cenario = Label(top_frame, text="Cenario: ")
label_algorithm = Label(top_frame, text="Algorithm to be used: ")
label_filler = Label(top_frame, text="")
#Entry boxes text initial color and stuff
entry_cities = Entry(top_frame, fg='grey')
entry_min_dist = Entry(top_frame, fg='grey')
entry_max_dist = Entry(top_frame, fg='grey')
#entry boxes default text
entry_cities.insert(0, '# of cities')
#Var for checkboxes
cenario_1 = BooleanVar()
cenario_2 = BooleanVar()
brute = BooleanVar()
brute_opt = BooleanVar()
recursive = BooleanVar()
recursive_g = BooleanVar()
#Checkboxes for different algorithms
cenario_1_check = Checkbutton(top_frame, text="1", onvalue=True, offvalue=False, variable=cenario_1, command=on_check_cenario_1)
cenario_2_check = Checkbutton(top_frame, text="2", onvalue=True, offvalue=False, variable=cenario_2, command=on_check_cenario_2)
brute_check = Checkbutton(top_frame, text="Brute Force ", onvalue=True, offvalue=False, variable=brute)
brute_opt_check = Checkbutton(top_frame, text="Brute Force Optimized", onvalue=True, offvalue=False, variable=brute_opt)
recursive_check = Checkbutton(top_frame, text="Recursive ", onvalue=True, offvalue=False, variable=recursive)
recursive_g_check = Checkbutton(top_frame, text="Recursive Greedy", onvalue=True, offvalue=False, variable=recursive_g)
#binds
entry_cities.bind('<FocusIn>', on_entry_click_0)
entry_cities.bind('<FocusOut>', on_focusout_0)
#grid labels
label_cities.grid(row=0, pady=10, sticky=E)
label_cenario.grid(row=2, pady=10, sticky=E)
label_algorithm.grid(row=6, pady=10, sticky=E)
label_filler.grid(row=10, pady=10, sticky=E)
#grid Entries
entry_cities.grid(row=0, column=1)
#grid checkboxes
cenario_1_check.grid(row=2, column=1, sticky=W)
cenario_2_check.grid(row=2, column=1, sticky=E)
brute_check.grid(row=6, column=1, sticky=W)
brute_opt_check.grid(row=8, column=1, sticky=W)
recursive_check.grid(row=10, column=1, sticky=W)
recursive_g_check.grid(row=12, column=1, sticky=W)
root.mainloop() #required to run TkInter |
8ed94e5a5bc207a34271e2bb52029d7b6b71870d | darlenew/california | /california.py | 2,088 | 4.34375 | 4 | #!/usr/bin/env python
"""Print out a text calendar for the given year"""
import os
import sys
import calendar
FIRSTWEEKDAY = 6
WEEKEND = (5, 6) # day-of-week indices for saturday and sunday
def calabazas(year):
"""Print out a calendar, with one day per row"""
BREAK_AFTER_WEEKDAY = 6 # add a newline after this weekday
c = calendar.Calendar()
tc = calendar.TextCalendar(firstweekday=FIRSTWEEKDAY)
for month in range(1, 12+1):
print()
tc.prmonth(year, month)
print()
for day, weekday in c.itermonthdays2(year, month):
if day == 0:
continue
print("{:2} {} {}: ".format(day,
calendar.month_abbr[month],
calendar.day_abbr[weekday]))
if weekday == BREAK_AFTER_WEEKDAY:
print()
def calcium(year, weekends=True):
"""Print out a [YYYYMMDD] calendar, no breaks between weeks/months"""
tc = calendar.TextCalendar()
for month_index, month in enumerate(tc.yeardays2calendar(year, width=1), 1):
for week in month[0]: # ?
for day, weekday in week:
if not day:
continue
if not weekends and weekday in (WEEKEND):
print()
continue
print(f"[{year}{month_index:02}{day:02}]")
def calzone(year):
"""Prints YYYYMMDD calendar, like calcium without weekends"""
return calcium(year, weekends=False)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="print out a calendar")
parser.add_argument('year', metavar='YEAR', type=int, help='the calendar year')
parser.add_argument('style', metavar='STYLE', help='calendar style')
args = parser.parse_args()
style = {'calcium': calcium,
'calabazas': calabazas,
'calzone': calzone,
}
try:
style[args.style](args.year)
except KeyError:
raise(f"Calendar style {args.style} not found")
|
ab7b1bc5da6df5746bed215e196f2208301570df | jonathan-mcmillan/python_programs | /asdf;lkj.py | 1,126 | 3.5 | 4 | from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
for level in range(numLevels):
centerX = screenSize / 2
leftMostX = centerX - unitSize / 2 * level
centerY = (level +1) * unitSize
for blockCount in range(level +1):
block = Square(unitSize)
block.move(leftMostX + blockCount * unitSize, centerY)
block.move(centerX, centerY)
block.setFillColor('gray')
paper.add(block)
'''
from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
for level in range(numLevels):
width = (level +1) * unitSize
height = unitSize
block = Rectangle(width, height)
width = (level +1) * unitSize
block = Rectangle(width, unitSize)
block = Rectangle((level +1)* unitSize, unitSize)
these two do the same thing as the first set of code
centerX = screenSize/2
centerY = (level +1) * unitSize
block.move(centerX, centerY)
block.setFillColor('gray')
paper.add(block)
'''
|
e96bfc80489c56a2fef2d71ca5ae417f6738a539 | jonathan-mcmillan/python_programs | /notes_2⁄1.py | 591 | 3.671875 | 4 | groceries=['eggs','ham','toast','juice']
for item in groceries:
print item
count = 1
for item in groceries:
print str(count)+')'+item
count += 1
a = [6,2,4,3,2,4]
n=0
print a
for e in a:
a[n]= e*2
n +=1
print a
for i in range(len(a)):
a[i] *= 2
print a
m = [[3,4],[2,1]]
for i in range(2):
for j in range(2):
m[i][j] *= 3
print m
l = [[1,'eggs'],(2,'ham'),'toast',4.0]
print l[3]
print l[1]
print l[1][0]
print l[1][1]
print l[1][1][0]
t=('A','B','C','D','E')
for i in range(len(t)):
for j in range(i+1,len(t)):
print t[i], t[j]
|
7a3e2fb304cbb15c640e17841da60543e46e95eb | emrache/Python_600x | /Problem Set 9/ps9.py | 2,824 | 3.65625 | 4 | # 6.00 Problem Set 9
import numpy
import random
import pylab
from ps8b_precompiled_27 import *
#
# PROBLEM 1
#
def simulationDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 1.
Runs numTrials simulations to show the relationship between delayed
treatment and patient outcome using a histogram.
Histograms of final total virus populations are displayed for delays of 300,
150, 75, 0 timesteps (followed by an additional 150 timesteps of
simulation).
numTrials: number of simulation runs to execute (an integer)
"""
##setting up the time Steps, population variable
popAtEnd=[]
timeBegin=0
timeMiddle=75
timeEnd=timeMiddle+150
##going through all of the trials:
trialNum=0
while trialNum<numTrials:
##setting up baseline variables
numViruses=100
maxPop=1000
maxBirthProb=.1
clearProb=.05
resistances={'guttagonol': False}
mutProb=.005
##setting up the list of viruses to start
trialViruses=[]
for x in range(numViruses):
trialViruses.append(ResistantVirus(maxBirthProb, clearProb, resistances, mutProb))
##creating the test patient
testPatient=TreatedPatient(trialViruses, maxPop)
for step in range(timeBegin, timeMiddle):
testPatient.update()
testPatient.addPrescription('guttagonol')
for step in range(timeMiddle, timeEnd):
testPatient.update()
## print step
trialNum+=1
popAtEnd.append(testPatient.getTotalPop())
print popAtEnd
##create the gorram histogram
pylab.hist(popAtEnd,bins=10)
pylab.xlabel('End population if scrip added after '+ str(timeMiddle)+' steps')
pylab.ylabel('Number of Trials')
pylab.title ('End Virus Population')
pylab.show()
return
## ##create the gorram plot
## pylab.figure(1)
## pylab.plot(avgPopAtTime)
## pylab.plot(avgResistPopAtTime)
## pylab.title('Average Resistant Virus Population, drug introduced @ time')
## pylab.xlabel('Time Steps')
## pylab.ylabel('Average Virus Population')
## pylab.legend('total pop')
## pylab.show()
#
# PROBLEM 2
#
def simulationTwoDrugsDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 2.
Runs numTrials simulations to show the relationship between administration
of multiple drugs and patient outcome.
Histograms of final total virus populations are displayed for lag times of
300, 150, 75, 0 timesteps between adding drugs (followed by an additional
150 timesteps of simulation).
numTrials: number of simulation runs to execute (an integer)
"""
# TODO
|
85c0cb7b1fb3da5a3e4f20d60d1a55ca1576aad3 | rorjackson/Jack | /tkintergui.py | 553 | 3.9375 | 4 | from tkinter import *
win = Tk()
win.geometry('200x100')
name = Label(win, text="Name") # To create text label in window
password = Label(win,text="password")
email = Label(win, text="Email ID")
entry_1 = Entry(win)
entry_2 = Entry(win)
entry_3 = Entry(win)
# check = CHECKBUTTON(win,text ="keep me logged in")
name.grid(row=0, sticky = E)
password.grid(row=1,sticky = E)
email.grid(row=2, sticky = E)
entry_1.grid(row=0, column =1)
entry_2.grid(row=1, column =1)
entry_3.grid(row=2, column =1)
# check.grid(columnspan=2)
win.mainloop() |
d86ab402a950557261f140137b2771e84ceafbbe | priyankagarg112/LeetCode | /MayChallenge/MajorityElement.py | 875 | 4.15625 | 4 | '''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
from typing import List
#Solution1:
from collections import Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0]
#Solution2:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
visited = []
for i in nums:
if i in visited:
continue
if nums.count(i) > (len(nums)/2):
return i
visited.append(i)
if __name__ == "__main__":
print(Solution().majorityElement([3,1,3,2,3]))
|
92bbf967afbb85b943c9af46bde946b2d0d9fdf9 | tusshar2000/DSA-Python | /graphs/dfs_cycle_directed_graph.py | 2,502 | 3.71875 | 4 | # https://leetcode.com/problems/course-schedule/
from collections import defaultdict
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# defaultdict(list) makes work easier
graph = defaultdict(list)
# we need to have every node in our graph as a key even though there might be not
# any connection to it/ it is not a connected graph. Just a basic and easy # preparation.
graph = {node:[] for node in range(numCourses)}
# now we add the edges in reverse manner because input is given in that format.
for edge in prerequisites:
graph[edge[1]].append(edge[0])
is_possible = True
visited = [0]*(numCourses)
# note that we will be using 0,1,2 values for representing the state of our node
# in visited list.
# value 0 represents node is unprocessed.
# value 1 represents node is under process.
# value 2 represents node is processed.
def dfs(visited, node):
nonlocal is_possible
visited[node] = 1
for neighbour in graph[node]:
if visited[neighbour] == 0:
dfs(visited, neighbour)
# this is the condition where we find if a cycle exsits or not.
# if our neighbour node has a value 1 in visited list, it means that
# this node was still under process and we found another way through
# which we can access this, meaning we found a cycle.
if visited[neighbour] == 1:
is_possible = False
visited[node] = 2
# now for every node we check if it is unprocessed then call dfs for it,
# this way we are assured even if our graph in not fully connected we will
# be processing it.
for node in range(numCourses):
# I added another condition to check is_possible is still true then only
# process the node, as is_possible variable False value represents that
# our graph has cycle, so basically no need to process any node further.
if visited[node] == 0 and is_possible==True:
dfs(visited, node)
return is_possible |
5b9cd3610bf26e71e74df0a4a869b3969382b5ac | tusshar2000/DSA-Python | /graphs/word-search-using-dfs.py | 1,993 | 3.71875 | 4 | # https://leetcode.com/problems/word-search/
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
col = len(board[0])
row = len(board)
len_of_word = len(word)
is_possible = False #starting with it's not possible to form the string.
visited = set() #set for visited elements.
def dfs(visited, i, j, k):
nonlocal is_possible
# base-conditions, exit if already found a match or if trying to search out of #bounds.
if is_possible == True or i<0 or i>=row or j<0 or j>=col:
return
#add this element to visited
visited.add((i,j))
if board[i][j] == word[k]:
#we found the matching string.
if k == len_of_word - 1:
is_possible = True
return
#entering the dfs call only if that cell is unvisited.
if (i+1, j) not in visited:
dfs(visited, i+1, j, k+1)
if (i-1, j) not in visited:
dfs(visited, i-1, j, k+1)
if (i, j+1) not in visited:
dfs(visited, i, j+1, k+1)
if (i, j-1) not in visited:
dfs(visited, i, j-1, k+1)
#processing of this cell is done, so remove it from visited for next iterations.
visited.remove((i,j))
#dfs through each cell
for i in range(row):
for j in range(col):
#just return the answer if already found the solution.
if is_possible == True:
return is_possible
dfs(visited,i,j,0)
return is_possible |
78b22399df13bda1fa6519d86a1192cf358f6e87 | tusshar2000/DSA-Python | /binary tree/max_depth_of_n-ary_tree.py | 599 | 3.75 | 4 | https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
#BFS
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
queue = collections.deque([(root,1)])
while queue:
node, level = queue.popleft()
for child in node.children:
queue.append((child, level + 1))
return level
|
1e190699791483acd663a85db438602a6169e360 | kp646576/Simple-Compiler | /lexer.py | 4,596 | 3.625 | 4 | import sys
from scanner import Scanner
from token import Token
from symbolTable import symbolTable as st
def isAlpha(c):
if c:
c = ord(c)
return True if c >= 65 and c <= 90 or c >= 97 and c <= 122 else False
def isDigit(c):
if c:
c = ord(c)
return True if c <= 57 and c >= 48 else False
def isKeyword(c):
return True if c in st.keys() else False
def valKeyword(c):
return st[c] if c in st.keys() else ''
class Lexer:
def __init__(self, file):
self.line = 1
self.tokens = []
self.scanner = Scanner(file)
self.checkNext(self.scanner.read())
def checkNext(self, cur):
if cur == '\n':
self.line += 1
cur = self.scanner.read()
self.checkNext(cur)
else:
while cur == ' ' or cur == '\t':
cur = self.scanner.read()
if isDigit(cur) or cur == '.':
self.digitFSA(cur)
elif cur == '"':
self.stringFSA(cur)
elif isAlpha(cur) or cur == '_':
self.idFSA(cur)
else:
self.otherFSA(cur)
return
def digitFSA(self, n):
peek = self.scanner.read()
if n == '.':
if isDigit(peek):
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
self.tokens.append(Token(self.line, 'real', n))
else:
# Get digits before '.'
while isDigit(peek):
n += peek
peek = self.scanner.read()
# Is real
if peek == '.':
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
peek = self.scanner.read()
if peek == 'e':
n += peek
peek = self.scanner.read()
if peek == '+' or peek == '-':
n += peek
peek = self.scanner.read()
if not isDigit(peek):
self.eMessage(peek)
while isDigit(peek):
n += peek
peek = self.scanner.read()
self.tokens.append(Token(self.line, 'real', n))
elif peek == 'e':
n += peek
peek = self.scanner.read()
if peek == '+' or peek == '-':
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
peek = self.scanner.read()
self.tokens.append(Token(self.line, 'real', n))
# Is int
else:
self.tokens.append(Token(self.line, 'int', n))
self.checkNext(peek)
return
def stringFSA(self, c):
peek = self.scanner.read()
while peek != '"' and peek != '\n':
c += peek
peek = self.scanner.read()
if peek == '"':
c += peek
self.tokens.append(Token(self.line, 'string', c))
peek = self.scanner.read()
self.checkNext(peek)
else:
self.eMessage(c)
return
def idFSA(self, c):
peek = self.scanner.read()
# error when not num alph or _
while peek and (isAlpha(peek) or isDigit(peek) or peek == '_'):
c += peek
peek = self.scanner.read()
if peek == ' ' or peek == '\n' or isKeyword(peek):
keyword = valKeyword(c)
if keyword:
self.tokens.append(Token(self.line, keyword, c))
else:
self.tokens.append(Token(self.line, 'id', c))
else:
self.eMessage(peek)
self.checkNext(peek)
return
def otherFSA(self, c):
peek = self.scanner.read()
if peek:
k1 = valKeyword(c)
len2 = c + peek
k2 = valKeyword(len2)
# k2 first for longest prefix
if k2:
self.tokens.append(Token(self.line, k2, len2))
self.checkNext(self.scanner.read())
elif k1:
self.tokens.append(Token(self.line, k1, c))
self.checkNext(peek)
else:
self.eMessage(c)
return
def eMessage(self, e):
print >> sys.stderr, "Error on line " + str(self.line) + ": " + e + " is invalid."
|
5fbf2ff1591bdc0a50b2ad9758cf806bf7e4f6e8 | ttsiodras/VideoNavigator | /menu.py | 5,600 | 3.71875 | 4 | #!/usr/bin/env python
"""
A simple Pygame-based menu system: it scans folders and collects the single
image/movie pair within each folder. It then shows the collected pictures,
allowing you to navigate with up/down cursors; and when you hit ENTER,
it plays the related movie.
The configuration of folders, resolutions, players, etc is done with a
simple 'settings.ini' file.
"""
import sys
import os
import subprocess
from dataclasses import dataclass
from typing import List, Tuple
# pylint: disable=wrong-import-position
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame # NOQA
def panic(msg):
"""
Report error and abort.
"""
sys.stderr.write('[x] ' + msg + "\n")
sys.exit(1)
@dataclass
class Settings:
"""
Store all settings provided by user.
"""
video_folder: str
full_screen: bool
width_in_pixels: int
height_in_pixels: int
image_extensions: List[str]
movie_extensions: List[str]
command: str
def parse_settings() -> Settings:
"""
Parse 'settings.ini', return dictionary object with all settings.
"""
settings = {}
if not os.path.exists("settings.ini"):
panic("Missing settings.ini!")
for idx, line in enumerate(open("settings.ini", "r")):
if line.startswith('#'):
continue
try:
line = line.strip()
key, value = line.split('=')
key = key.strip()
value = value.strip()
except ValueError:
print("[x] Warning! Weird line", idx+1, " ignored:\n\t", line)
settings[key] = value
# Validate
if 'VideoFolder' not in settings:
panic("Did not find 'VideoFolder=' line in your settings.ini...")
for param in ['WidthInPixels', 'HeightInPixels']:
if param in settings:
try:
settings[param] = int(settings[param])
except ValueError:
panic("Invalid '%s=' line in your settings.ini..." % param)
# Default values
settings.setdefault('FullScreen', 'no')
settings['FullScreen'] = settings['FullScreen'].lower() == 'yes'
info_object = pygame.display.Info()
settings.setdefault('WidthInPixels', info_object.current_w)
settings.setdefault('HeightInPixels', info_object.current_h)
settings.setdefault(
'ImageExtensions', "jpg,jpeg,gif,png,webp")
settings['ImageExtensions'] = settings['ImageExtensions'].split(",")
settings.setdefault(
'MovieExtensions', "mkv,mp4,flv,avi,mov")
settings['MovieExtensions'] = settings['MovieExtensions'].split(",")
settings.setdefault(
'Command', r"C:\Program Files\VideoLAN\VLC\vlc.exe")
return Settings(
settings['VideoFolder'],
settings['FullScreen'],
settings['WidthInPixels'],
settings['HeightInPixels'],
settings['ImageExtensions'],
settings['MovieExtensions'],
settings['Command'])
def collect_all_videos(settings) -> List[Tuple[str, str]]:
"""
Scan the folder specified in the settings, and collect
images and movies.
Returns list of tuples containing (image,movie) paths.
"""
results = []
for root, unused_dirs, files in os.walk(
settings.video_folder, topdown=True):
found_images = [
x for x in files
if any(
x.lower().endswith(y)
for y in settings.image_extensions)
]
found_movies = [
x for x in files
if any(
x.lower().endswith(y)
for y in settings.movie_extensions)
]
if found_images and found_movies:
results.append((
root + os.sep + found_images[0],
root + os.sep + found_movies[0]))
return results
def main():
"""
The heart of the show.
"""
pygame.init()
settings = parse_settings()
args = []
args.append(
(settings.width_in_pixels, settings.height_in_pixels))
if settings.full_screen:
args.append(pygame.FULLSCREEN)
win = pygame.display.set_mode(*args)
images_and_movies = collect_all_videos(settings)
if not images_and_movies:
panic("No folders found...")
current_slot = 0
image = []
while True:
del image
image = pygame.image.load(images_and_movies[current_slot][0])
image = pygame.transform.scale(
image,
(settings.width_in_pixels, settings.height_in_pixels))
win.blit(image, (0, 0))
pygame.display.update()
while True:
evt = pygame.event.wait()
if evt.type == pygame.NOEVENT:
break
if evt.type == pygame.KEYUP:
break
if evt.key == pygame.K_SPACE or evt.key == pygame.K_RETURN:
pygame.quit()
cmd = [settings.command]
cmd.append(images_and_movies[current_slot][1])
subprocess.call(cmd)
pygame.init()
win = pygame.display.set_mode(
(settings.width_in_pixels, settings.height_in_pixels),
pygame.FULLSCREEN)
elif evt.key == pygame.K_DOWN:
current_slot = current_slot + 1
current_slot = current_slot % len(images_and_movies)
elif evt.key == pygame.K_UP:
current_slot = current_slot + len(images_and_movies) - 1
current_slot = current_slot % len(images_and_movies)
elif evt.key == pygame.K_ESCAPE:
pygame.quit()
break
if __name__ == "__main__":
main()
|
f03de31739574749ee56fabdeffdb43e0dc9229b | divannn/python | /math/sort_util.py | 71 | 3.546875 | 4 | def swap(list, i, j):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
|
61329cb09135f5634b1c64baa1db566836929a26 | shivamach/OldMine | /HelloWorld/python/strings.py | 527 | 4.375 | 4 | print("trying basic stuff out")
m1 = "hello"
m2 = "World"
name = "shivam"
univ = "universe"
print(m1,", ",m2)
print(m1.upper())
print(m2.lower())
message = '{}, {}. welcome !'.format(m1,m2.upper())
print(message)
message = message.replace(m2.upper(),name.upper())
#replacing with methods should be precise
print(message)
name = "not shivam"
#trying out replace with f strings
message = f'{m1}, {m2.upper()}. welcome!'
print(message)
message = message.replace(m2.upper(),name.upper())
print(message)
#everything covered ayyay |
433027b761e728e242c5b58c11866208fe39ca23 | caesarbonicillo/ITC110 | /quadraticEquation.py | 870 | 4.15625 | 4 | #quadratic quations must be a positive number
import math
def main():
print("this program finds real solutions to quadratic equations")
a = float(input("enter a coefficient a:"))
b = float(input("enter coefficient b:"))
c = float(input("enter coefficient c:"))
#run only if code is greater or qual to zero
discrim = b * b - 4 * a *c
if(discrim < 0): #1, 2, 3
print("no real roots") # should always put the default in before any real work that way it doesn't do any unnessesary work.
elif(discrim ==0):#1, 2, 1
root = -b / (2 * a)
print("there is a double root at", root)
else:#1, 5, 6
discRoot = math.sqrt(b * b -4 *a *c)
root1 = (-b + discRoot) / (2* a)
root2 = (-b - discRoot) / (2 * a)
print ("\nThe solutions are:", root1, root2)
main()
|
12c96ea6817d91f8d488f13c119752f747971c94 | caesarbonicillo/ITC110 | /Temperature.py | 496 | 4.125 | 4 | #convert Celsius to Fehrenheit
def main(): #this is a function
#input
celsius = eval (input ("Enter the temp in Celsius ")) #must convert to number call function EVAL
#processing
fahrenheit = round(9/5 * celsius + 32, 0)
#output
print (celsius, "The Fehrenheit temp is", fahrenheit)
main() # press f5 to run
def kiloMile():
kilo = eval (input("enter kilometers "))
miles = 1.6 * kilo
print ( kilo, "The conversion is", miles)
kiloMile()
|
27cf55f0f342a4cf7747f3ee7a13e56c5d91bfcc | loganwastlund/cs1410 | /frogger_assignment/froggerlib/frog.py | 675 | 3.546875 | 4 | from froggerlib.player_controllable import PlayerControllable
class Frog(PlayerControllable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0, hg=0, vg=0):
PlayerControllable.__init__(self, x, y, w, h, dx, dy, s, hg, vg)
return
def __str__(self):
s = "Frog<"+PlayerControllable.__str__(self)+">"
return s
def __repr__(self):
return str(self)
def test():
f = Frog()
f.setHorizontalGap(15)
f.setVerticalGap(15)
f.setSpeed(2)
print(f)
f.up()
print(f)
while not f.atDesiredLocation():
f.move()
print(f)
return
if __name__ == "__main__":
test()
|
a48246d152225d226d01bf5139ede5ec88149989 | loganwastlund/cs1410 | /frogger_assignment/froggerlib/truck.py | 551 | 3.71875 | 4 | from froggerlib.dodgeable import Dodgeable
import random
class Truck(Dodgeable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0):
Dodgeable.__init__(self, x, y, w, h, dx, dy, s)
return
def __str__(self):
s = "Truck<"+Dodgeable.__str__(self)+">"
return s
def __repr__(self):
return str(self)
def test():
r = Truck(5,5,10,10, -15, 10, 4)
print(r)
while not r.atDesiredLocation():
r.move()
print(r)
return
if __name__ == "__main__":
test()
|
ad3dcc55ba5993e6e902723f5b4170a259276530 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_getUserFloat.py | 3,461 | 3.84375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import main
class TestGetUserFloat(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *args, **kargs):
return
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
main.input = self.input_replacement
main.print = self.print_replacement
return
def test001_getUserFloatExists(self):
self.assertTrue('getUserFloat' in dir(main),
'Function "getUserFloat" is not defined, check your spelling')
return
def test002_getUserFloatSendsCorrectPrompt(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1.7"
self.input_response_list = [expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertEqual(expected_prompt, self.input_given_prompt)
return
def test003_getUserFloatGetsInput(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1"
self.input_response_list = [expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(1.0, actual_response)
return
def test004_getUserFloatStripsWhitespace(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1.7"
self.input_response_list = [" \t\n" + expected_response + " \t\n"]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(float(expected_response), actual_response)
return
def test005_getUserFloatBadInputCheck(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "7.6"
self.input_response_list = ["zero", "-1.7", "0", "0.0", "-20.0", "", "sixteen", expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(float(expected_response), actual_response,
'Your repsonse (%s) did not equal the expected response (%s)' % (actual_response, expected_response))
return
def test006_getUserFloatIgnoresBlankLines(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "10"
self.input_response_list = ["", "0.0", "hello", "-1.7", "\n", " \t\n" + expected_response + " \t\n"]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(10.0, actual_response)
return
if __name__ == '__main__':
unittest.main()
|
e72a2b169ddeb44b6c3ab9ee24d4818dbdc89e79 | loganwastlund/cs1410 | /isbn_assignment/isbnTests/test_findBook.py | 1,205 | 3.765625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
from isbnTests import isbn_index
class test_findBook( unittest.TestCase ):
def setUp(self):
return
def tearDown(self):
return
def test001_findBookExists(self):
self.assertTrue('findBook' in dir(isbn_index),
'Function "findBook" is not defined, check your spelling')
return
def test002_findBookFindsExistingBook(self):
isbn = "0000-00000000"
title = "Book Title"
expected = title
index = isbn_index.createIndex()
isbn_index.recordBook(index, isbn, title)
self.assertEqual(isbn_index.findBook(index, isbn), expected)
return
def test003_findBookDoesNotFindMissingBook(self):
isbn1 = "0000-00000000"
isbn2 = "0000-12345678"
title = "Book Title"
expected = ""
index = isbn_index.createIndex()
isbn_index.recordBook(index, isbn1, title)
self.assertEqual(isbn_index.findBook(index, isbn2), expected)
return
if __name__ == '__main__':
unittest.main()
|
5f7d558e0dc80f651c1b1fbc79b3748f17451b2c | loganwastlund/cs1410 | /asteroids_assignment/test_all_asteroids_part1/test_005_rock_004_createRandomPolygon.py | 3,624 | 3.515625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import math
import rock
class TestRockCreatePolygon( unittest.TestCase ):
def setUp( self ):
self.expected_x = 100
self.expected_y = 200
self.expected_dx = 0.0
self.expected_dy = 0.0
self.expected_rotation = 0
self.expected_world_width = 600
self.expected_world_height = 400
self.constructed_obj = rock.Rock( self.expected_x, self.expected_y, self.expected_world_width, self.expected_world_height )
return
def tearDown( self ):
return
def test001_generatesCorrectNumberOfPoints( self ):
number_of_points = 5
radius = 1.0
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
self.assertEqual( len( random_polygon ), number_of_points )
return
def test002_generatesCorrectRadius( self ):
number_of_points = 5
radius = 1.0
min_radius = 0.7
max_radius = 1.3
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
for random_point in random_polygon:
( x, y ) = random_point
random_distance = math.sqrt( x * x + y * y )
self.assertGreaterEqual( random_distance, min_radius )
self.assertLessEqual( random_distance, max_radius )
return
def test003_generatesCorrectAngle72( self ):
number_of_points = 5
radius = 1.0
expected_angle = 72
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
previous_angle = None
for random_point in random_polygon:
( x, y ) = random_point
current_angle = math.degrees( math.atan2( y, x ) )
if previous_angle is not None:
actual_angle = ( current_angle - previous_angle ) % 360
self.assertAlmostEqual( actual_angle , expected_angle )
previous_angle = current_angle
return
def test004_generatesCorrectAngle60( self ):
number_of_points = 6
radius = 1.0
expected_angle = 60
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
previous_angle = None
for random_point in random_polygon:
( x, y ) = random_point
current_angle = math.degrees( math.atan2( y, x ) )
if previous_angle is not None:
actual_angle = ( current_angle - previous_angle ) % 360
self.assertAlmostEqual( actual_angle , expected_angle )
previous_angle = current_angle
return
def test005_generatesCorrectRadius100( self ):
number_of_points = 5
radius = 100.0
min_radius = 70.0
max_radius = 130.0
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
for random_point in random_polygon:
( x, y ) = random_point
random_distance = math.sqrt( x * x + y * y )
self.assertGreaterEqual( random_distance, min_radius )
self.assertLessEqual( random_distance, max_radius )
return
def suite( ):
return unittest.TestLoader( ).loadTestsFromTestCase( TestRockCreatePolygon )
if __name__ == '__main__':
runner = unittest.TextTestRunner( )
runner.run( suite( ) )
|
a99ebf6cc65ac45f0837c615de75e10ccc3cbc72 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_eatFoodAction.py | 5,507 | 3.59375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import re
import main
class TestEatFoodAction(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *text, **kwargs):
line = " ".join(text) + "\n"
self.printed_lines.append(line)
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
main.input = self.input_replacement
self.printed_lines = []
main.print = self.print_replacement
def test001_eatFoodActionExists(self):
self.assertTrue('eatFoodAction' in dir(main),
'Function "eatFoodAction" is not defined, check your spelling')
def test002_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
self.input_response_list = ["400"]
eatFoodAction(cb)
actual_response = self.input_response_list[self.input_response_index]
self.assertEqual("400", actual_response)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
def test003_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
expected_response = "400"
self.input_response_list = ["0", "-1.7", "-20", "zero", "twleve", "", "\n", expected_response]
eatFoodAction(cb)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
expected = actual + float(expected_response)
actual = actual2
self.assertAlmostEqual(expected, actual, 2,
'Your result (%s) is not close enough to (%s). Did you use getUserFloat?' % (actual, expected))
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
def test004_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
expected_response = "998"
self.input_response_list = ["0", "-1.7", "-20", "zero", "twleve", "", "\n", expected_response, "500", "600", "700"]
eatFoodAction(cb)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
expected = actual + float(expected_response)
actual = actual2
self.assertAlmostEqual(expected, actual, 2,
'Your result (%s) is not close enough to (%s). Did you use getUserFloat?' % (actual, expected))
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
if __name__ == '__main__':
unittest.main()
|
def3e215af2f9d8c874d14ecba1b4b07cc233b4e | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_listTripsAction.py | 2,919 | 3.5625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import gas_mileage
class TestListTripsAction(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *text, **kwargs):
line = " ".join(text) + "\n"
self.printed_lines.append(line)
return
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
gas_mileage.input = self.input_replacement
self.printed_lines = []
gas_mileage.print = self.print_replacement
return
def test001_listTripsActionExists(self):
self.assertTrue('listTripsAction' in dir(gas_mileage),
'Function "listTripsAction" is not defined, check your spelling')
return
def test002_listTripsActionDoesNotUpdate(self):
from gas_mileage import listTripsAction
notebook = []
expected = []
self.input_response_list = ["???"]
listTripsAction(notebook)
self.assertListEqual(expected, notebook, "Your listTripsAction made changes to the notebook when it shouldn't")
self.assertGreaterEqual(len(self.printed_lines), 1, 'Make sure to print a message to the user about no trips being recorded')
def test003_listTripsActionPrintLines(self):
from gas_mileage import listTripsAction
notebook = [
{'date': "01/01/17", 'miles': 100.0, 'gallons': 5.0},
{'date': "01/02/17", 'miles': 300.0, 'gallons': 10.0}
]
expected = [
{'date': "01/01/17", 'miles': 100.0, 'gallons': 5.0},
{'date': "01/02/17", 'miles': 300.0, 'gallons': 10.0}
]
self.input_response_list = ["???"]
listTripsAction(notebook)
self.assertListEqual(expected, notebook, "Your listTripsAction made changes to the notebook when it shouldn't")
self.assertGreaterEqual(len(self.printed_lines), 2, 'You should print a line for each trip')
printed_text = "".join(self.printed_lines)
self.assertIn("01/01/17", printed_text)
self.assertIn("100.0", printed_text)
self.assertIn("5.0", printed_text)
self.assertIn("20.0", printed_text)
self.assertIn("01/02/17", printed_text)
self.assertIn("300.0", printed_text)
self.assertIn("10.0", printed_text)
self.assertIn("30.0", printed_text)
if __name__ == '__main__':
unittest.main()
|
5465a46981d4b4632a15d7003e2bf3b0c11aab1a | loganwastlund/cs1410 | /in_class/notes.py | 3,113 | 4.09375 | 4 | # dictionaries
d = {'key': 'value', 'name': 'Logan', 'id': 123, 'backpack': ['pencil', 'pen', 'pen', 'paper']}
d['name'] = 'John'
# how to update a key ^
d['dob'] = '01-17-18'
d['dob'] = '01-18-18'
# keys can be integers, strings, variables, but not lists. The value can be anything
print(d['backpack'][2])
# prints second pen ^
# if key in dictionary:
# how to check if key is in dictionary
# for key in dictionary:
# value = dictionary[key]
# if value == 'value':
# how to find a value in a dictionary
# del d['key']
# how to delete a key ^
# classes
# Classes:
# have abilities
# and traits
# a marker has:
# color
# erasable
# capacity
# tip size
# write
# use "class {name}:"
# Pascal Case
# StudlyCaps
class Marker:
def __init__(self):
self.color = (0, 0, 255)
self.erasable = True
self.capacity = 5
self.tipsize = 0.001
def write(self, length):
self.capacity -= self.tipsize * abs(length)
def show(self):
print(self.color, self.erasable, self.capacity, self.tipsize)
redexpo1 = Marker()
redexpo1.color = (255, 0, 0)
blueexpo1 = Marker()
blueexpo2 = Marker()
bluesharpie1 = Marker()
bluesharpie1.erasable = False
bluesharpie1.tipsize = 0.001/5
bluesharpie1.capacity = 5/2
print(redexpo1.color)
print(blueexpo1.color)
print(bluesharpie1.erasable)
print(blueexpo1.capacity)
blueexpo1.write(1000)
print(blueexpo1.capacity)
print(blueexpo2.capacity)
blueexpo2.write(75.8)
print(blueexpo2.capacity)
redexpo1.show()
blueexpo1.show()
blueexpo2.show()
bluesharpie1.write(1000)
bluesharpie1.show()
# copy
# import copy
# copy.copy()
# used to copy anything from objects to lists and dictionaries
# class Nothing:
#
# def __init__(self, something):
# self.something = something
# OR
# self.__something = something
# This makes it private so that you can't change it through self.__something = updated_value
# It would have to be through a function
# TODO: surprise Logan, remember this, it is cool!!!!!!!!!!!!!!!!!!!!!!!
TODO: surprise Logan, remember this, it is cool!!!!!!!!!!!!!!!!!!!!!!!
# just comment sentence out, as long as TODO: is at the start it will do this!
# collapse code -> Command + -
# operator overloading
# def __gt__(self): <-- Greater than (>)
# __ls__ <-- Less than (<)
# __eq__ <-- Equal to (==)
# __add__ <-- Add (+)
# __mul__ <-- Multiply(*)
# __iadd__ <-- Add (+=)
# unittest
import unittest
import sys
from unittest import TestCase, main
class Test(TestCase):
def setUp(self):
self.something = 'something'
self.othersomething = 'othersomething'
def test_a_test(self): # has to start with test
self.assertEqual(self.something + self.othersomething, 'somethingothersomething')
@unittest.skipIf(not sys.platform.startswith('darwin'), "This should be skipped") # only macs, mac = 'darwin'?
def test_b_test_mac(self):
self.fail('Just Because')
pass
if __name__ == "main":
main()
|
bef3086fbcdad462844ab8c80437366d2517b10c | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance.py | 883 | 3.546875 | 4 |
class CaloricBalance:
def __init__(self, gender, age, height, weight):
self.weight = weight
bmr = self.getBMR(gender, age, height, weight)
self.balance = bmr - (bmr * 2)
def getBMR(self, gender, age, height, weight):
bmr = 0.0
if gender == 'm':
bmr = 66 + (12.7 * height) + (6.23 * weight) - (6.8 * age)
if gender == 'f':
bmr = 655 + (4.7 * height) + (4.35 * weight) - (4.7 * age)
return bmr
def getBalance(self):
return self.balance
def recordActivity(self, caloric_burn_per_pound_per_minute, minutes):
calories_burned_per_minute = caloric_burn_per_pound_per_minute * self.weight
calories_burned = float(calories_burned_per_minute) * float(minutes)
self.balance -= calories_burned
def eatFood(self, calories):
self.balance += calories
|
a7ea4875f924aceeb06f252fa4d38313c6042436 | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_recordTrip.py | 2,457 | 3.8125 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import random
import gas_mileage
class TestRecordTrip(unittest.TestCase):
def test001_recordTripExists(self):
self.assertTrue('recordTrip' in dir(gas_mileage),
'Function "recordTrip" is not defined, check your spelling')
return
def test002_recordOneTrip(self):
# start with empty trip log
notebook = []
date = "01/01/2017"
miles = 300.0
gallons = 10.0
# record a trip
gas_mileage.recordTrip(notebook, date, miles, gallons)
# check total number of recorded trips
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == 1, 'We recorded 1 trip, your notebook had %d' % number_of_trips)
# get the recorded trip dictionary and check its values
trip = notebook[0]
self.assertDictEqual({'date': date, 'miles': miles, 'gallons': gallons}, trip)
def test003_recordMultipleTrips(self):
# start with empty trip log
notebook = []
# choose number of trips to generate
total_trips = random.randint(10, 20)
# generate and verify trips
for i in range(total_trips):
trip_number = i + 1
date = 'day' + str(trip_number)
ratio = random.randint(13, 34)
miles = float(random.randint(50, 250))
gallons = float(miles / ratio)
# record the trip
gas_mileage.recordTrip(notebook, date, miles, gallons)
# count the number of trips recorded so far
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == trip_number,
'We have recorded %d trips, your notebook had %d' % (trip_number, number_of_trips))
# get the last trip recorded and verify the values
trip = notebook[number_of_trips - 1]
self.assertDictEqual({'date':date, 'miles':miles, 'gallons':gallons}, trip)
# get the total number of trips and verify it is the correct number
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == total_trips,
'We recorded %d trips, your notebook had %d' % (total_trips, number_of_trips))
if __name__ == '__main__':
unittest.main()
|
3e419aa050aed59a0a9a5941f69cba22375eacc5 | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/ClimbingTheLeaderboard.py | 848 | 4 | 4 | """
An arcade game player wants to climb to the top of the leaderboard and track their
ranking. The game uses Dense Ranking, so its leaderboard works like this:
• The player with the highest score is ranked number on the leaderboard.
• Players who have equal scores receive the same ranking number, and the
next player(s) receive the immediately following ranking number.
"""
def climbing_leaderboard(N: list, M: list) -> list:
X = list(set(N))
X.sort(reverse=True)
J = []
j = len(X)
for m in M:
while (j>0) and (m >= X[j-1]):
j -= 1
J.append(j+1)
return J
if __name__ == '__main__':
n = int(input())
N = [int(i) for i in input().split()]
m = int(input())
M = [int(i) for i in input().split()]
J = climbing_leaderboard(N, M)
for j in J:
print(j) |
d6c282c0e9b51b97f6aa30d44b96ecd2fd9e405f | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/DesignerPDFViewer.py | 795 | 4.0625 | 4 | import os
"""
Sample Input
------------
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
abc
Sample Output
-------------
9
"""
def designer_viewer(h: list, word: str) -> int:
# 1) Convert word to lower case
word = word.lower()
# print(word)
# 2) Convert word to unicode representation - 97
coded = [ord(char) - 97 for char in word]
# print(coded)
# 3) For each chr in word find corresponding number in h
height_collection = [h[i] for i in coded]
# print(height_collection)
# 4) Return max number * length of word
return max(height_collection) * len(word)
if __name__ == '__main__':
# none return value
h = list(int(i) for i in input().rstrip().split())
word = input()
result = designer_viewer(h, word)
print(result)
|
fc16775fecae5b5b59885cdde7f6a5c4dcaf7ecf | BrandonIslas/Curso_Basico_Python | /ejemplo3CondicionalesCompuestas.py | 297 | 3.875 | 4 | sueldo1= int(input("Introduce un sueldo1: "))
sueldo2= int(input("Introduce un sueldo2: "))
if sueldo1 > sueldo2:
print("El sueldo1 "+ str(sueldo1)+ " es mayor que el sueldo2 ("+str(sueldo2) +")")
else:
print("El sueldo1 ("+ str(sueldo1)+ ") es menor que el sueldo2 ("+str(sueldo2) +")")
|
21385d2bce3d5ddfb79334cc1a274e108932d0f7 | BrandonIslas/Curso_Basico_Python | /Listas1.py | 993 | 3.984375 | 4 | lista=[] #DECLARACION DE LA LISTA
for k in range(10):
lista.append(input("Introduce el "+str(k)+" valor a la lista:"))
print("Los elementos de la lista son:"+str(lista))
valor=int(input("Introduce el valor a modificar de la lista por el indice"))
nuevo=input("Introduce el nuevo valor:")
lista[valor]=nuevo#MODIFICAR VALOR DE LA LISTA
print("Los elementos de la lista son:"+str(lista))
valor=int(input("Introduce el valor en el que se insertara el nuevo valor"))
nuevo=input("Introduce el nuevo valor:")
lista.insert(valor,nuevo)#INSERTAR VALOR A LA LISTA
print("Los elementos de la lista son:"+str(lista))
nuevo=input("Introduce el valor a eliminar")
lista.remove(nuevo) #ELIMINAR VALOR DE LA LISTA
print("Los elementos de la lista son:"+str(lista))
nuevo=input("Introduce el valor de la lista que se desea buscar:")
resultado=(nuevo in lista)
if (resultado):
print("Existe el elemento en la posicion: "+str(lista.index(nuevo)))
else:
print("El elemento no existe en la lista ")
|
db6decc20f095d23d6842efef66cc0de5fbb6893 | BrandonIslas/Curso_Basico_Python | /ProgramacionOrientadaaObjetos/FuncionalidadModuloAs.py | 212 | 4.03125 | 4 | from math import sqrt as raiz, pow as exponente
dato=int(input("Ingrese un valor entero: "))
raizcuadrada=raiz(dato)
cubo=exponente(dato,3)
print("La raiz cuadrada es: ",raizcuadrada)
print("El cubo es: ",cubo)
|
5b080ee8d026affda640ab1284aafe4464329621 | BrandonIslas/Curso_Basico_Python | /ejemplo6While2.py | 286 | 3.875 | 4 | #Ejercicio while 2
cantidad=0
x=1
n=int(input("Cuantas piezas cargara:"))
while x<=n:
largo=float(input("Ingrese la medida de la ( " +str(x) +" ) pieza"))
if largo>=1.2 and largo<=1.3:
cantidad=cantidad+1
x=x+1
print("La cantidad de piezas aptas son"+str(cantidad))
|
e2c69c7053081eb29da7875b1ae37122d8ad1f25 | yukiii-zhong/Leetcode | /Linked List/138. Copy List with Random Pointer.py | 1,444 | 4.09375 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
# Step1: Totally copy a list: iter1--> copy1 --> iter2 --> copy2
# Do not consider random in this step
iter = head
while iter:
copy = RandomListNode(iter.label)
copy.next = iter.next
iter.next = copy
iter = copy.next
# Step2: From the head, give random pointer to the copies
# Don't change the linkage, because the pointer is in random
# You should consider random may be Null
iter = head
while iter:
if iter.random:
iter.next.random = iter.random.next
else:
iter.next.random = None
iter = iter.next.next
# Step3: After all the value has been set, make the copy a new list
# The original list should not be changed
pre = dummy = RandomListNode(-1)
iter = head
while iter:
pre.next = iter.next
pre = pre.next
iter.next = iter.next.next
iter = iter.next
return dummy.next
|
15069d7c114bbac94c1eba39fd0c67da4588b56d | yukiii-zhong/Leetcode | /Linked List/24. Swap Nodes in Pairs.py | 1,289 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# if head and !head.next
pre = head
if head and head.next:
pre = head.next
head.next = self.swapPairs(pre.next)
pre.next = head
return pre
def swapPairs2_SLOW(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
curr = dummy
while head and head.next:
pre = head
curr.next = head.next
head = head.next.next
curr.next.next = pre
curr = curr.next.next
if head:
curr.next = head
else:
curr.next = None
return dummy.next |
906f40cc6ff0bd3eb51af097f84ae975e7ac3957 | yukiii-zhong/Leetcode | /Array/src/16. 3Sum Closest.py | 730 | 3.578125 | 4 | class Solution:
def threeSumClosest(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
closest = nums[0]+nums[1]+nums[2]
for a in range(len(nums)-2):
i=a+1
j=len(nums)-1
while j>i:
sum = nums[a] + nums[i] + nums[j]
if sum == target:
return sum
if abs(closest-target)>abs(sum-target):
closest = sum
if sum < target:
i +=1
else:
j -= 1
return closest
nums = [-3,-2,-5,3,-4]
print(Solution().threeSumClosest(nums,-1)) |
0ec7dd4c022d0d7e9db17817daca8bf7fc721e18 | yukiii-zhong/Leetcode | /Linked List/143. Reorder List.py | 1,545 | 3.65625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
pre = dummy = ListNode("#")
pre.next = head
slow = head
fast = head
while fast and fast.next:
pre = pre.next
slow = slow.next
fast = fast.next.next
pre.next = None
trav = self.traverse(slow)
while head and trav:
headTemp = head.next
head.next = trav
travTemp = trav.next
pre = trav
trav.next = headTemp
head = headTemp
trav = travTemp
if trav:
pre.next = trav
return dummy.next
def traverse(self,head):
pre = None
while head:
temp = head.next
head.next = pre
pre = head
head = temp
return pre
def __init__(self):
self. a = 1
L1 = ListNode(1)
#L1 = L1.newValue([1,2,3,4,5])
S1 = Solution()
print(S1.reorderList(L1)) |
0d3bb69003e43914bb44c4b3a228635aec14222e | yukiii-zhong/Leetcode | /problems/7. Reverse Integer.py | 487 | 3.5 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < -(2 ** 31) or x > 2 ** 31 - 1:
return 0
if x == 0:
return x
elif x < 0:
return self.reverse(-x) * (-1)
# x>0
rev = 0
while x > 0:
x, rev = x // 10, x % 10 + rev * 10
if rev > 2 ** 31 - 1:
rev = 0
break
return rev
|
9b00ed3ea091453040f192c3e2018f7745970627 | yukiii-zhong/Leetcode | /Linked List/142. Linked List Cycle II.py | 1,191 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = head
visited = set()
while node:
if node in visited:
return node
else:
visited.add(node)
node = node.next
return None
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
ptr2 = self.meetPoint(head)
if ptr2 == None:
return None
ptr1 = head
while ptr1:
if ptr1 == ptr2:
return ptr1
else:
ptr1 = ptr1.next
ptr2 = ptr2.next
def meetPoint(self,head):
# Return the meet Point of slow and fast pointers
fast = head
slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
return fast
return None |
eb4b875ea3f86babccc588f48ab8a27d95ce7934 | yukiii-zhong/Leetcode | /Linked List/ListNode.py | 596 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution:
def __init__(self):
self. a = 1
L1 = ListNode(1)
L1 = L1.newValue([9,1,3])
S1 = Solution()
|
947af29568cc8fb642503115d2a4c7d582b1c274 | yukiii-zhong/Leetcode | /problems/9. Palindrome Number.py | 1,248 | 3.734375 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x <0:
return False
elif x == 0:
return True
# turn the int to an digit list
dig = []
while x > 0:
dig.append(x % 10)
x = x // 10
def palinDig(dig):
if len(dig) <=1:
return True
return dig[0] == dig[-1] and palinDig(dig[1:-1])
return palinDig(dig)
# In Python, you can directly tranfer the int to a String
def isPalindrome2(self, x):
if x < 0:
return False
elif x == 0:
return True
str_x = str(x)
i = 0
j = len(str_x)-1
while j>i:
if str_x[i] == str_x[j]:
i += 1
j -= 1
else:
return False
return True
# Without extra space
def isPalindrome3(self, x):
if x <0 or (x % 10 ==0 and x != 0):
return False
reverted = 0
while x > reverted:
x, rem = x // 10, x % 10
reverted = reverted *10 + rem
return x == reverted or x == reverted // 10 |
405cebe01e5875b953e07be442398b3e67275d88 | lockmachine/DeepLearningFromScratch | /ch04/gradient_descent.py | 2,233 | 3.515625 | 4 | #!/usr/bin/env python3
# coding: utf-8
import sys,os
sys.path.append(os.pardir)
import numpy as np
import matplotlib.pyplot as plt
from numerical_gradient import numerical_gradient
def gradient_descent(f, init_x, lr = 0.01, step_num=100):
x = init_x
grad_data = np.zeros(0)
for i in range(step_num):
grad = numerical_gradient(f, x)
x = x - lr * grad
# 途中の勾配を保存
if i == 0:
x_history = x.reshape(1, -1)
grad_data = grad.reshape(1, -1)
elif i % 10 == 0:
x_history = np.append(x_history, x.reshape(1, -1), axis=0)
grad_data = np.append(grad_data, grad.reshape(1, -1), axis=0)
return x, grad_data, x_history
def function_2(x):
if x.ndim == 1:
return np.sum(x**2)
else:
return np.sum(x**2, axis=1)
if __name__ == "__main__":
# f(x0, x1) = x0^2 + x1^2 の最小値を勾配法で求めよ
init_x = np.array([-3.0, 4.0])
# x = np.arange(-4.0, 4.0, 0.1) # (80, )
# y = np.arange(-4.0, 4.0, 0.1) # (80, )
# x_con = np.vstack((x, y)) # (2, 80)
# Z = function_2(x_con)
# X, Y = np.meshgrid(x, y) # メッシュグリッドの生成
# plt.contour(X, Y, Z)
# plt.gca().set_aspect('equal')
# plt.show()
# 学習率が大きすぎる例
x_large, grad_x_large, x_large_history = gradient_descent(function_2, init_x, lr = 10.0, step_num=100)
print("学習率が大きすぎる場合:" + str(x_large))
print(function_2(x_large))
# plt.plot(grad_x_large[:, 0], grad_x_large[:, 1], "o")
plt.plot(x_large_history[:, 0], x_large_history[:, 1], "o")
# 学習率が小さすぎる例
x_small, grad_x_small, x_small_history = gradient_descent(function_2, init_x, lr = 1e-10, step_num=100)
print("学習率が小さすぎる場合:" + str(x_small))
print(function_2(x_small))
# plt.plot(grad_x_small[:, 0], grad_x_small[:, 1], "x")
plt.plot(x_small_history[:, 0], x_small_history[:, 1], "x")
# デフォルトの学習率
x_default, grad_x_default, x_default_history = gradient_descent(function_2, init_x, lr = 0.01, step_num=100)
print("デフォルトの学習率:" + str(x_default))
print(function_2(x_default))
# plt.plot(grad_x_default[:, 0], grad_x_default[:, 1], ".")
plt.plot(x_default_history[:, 0], x_default_history[:, 1], ".")
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.show()
|
2c8ddb9a521e97f69e56db1a3ef504c7503c55b1 | Tuffour-Akwasi/Day2 | /part3.py | 672 | 3.875 | 4 | some_var = 5
if some_var > 10:
print('some_var is smaller than 10')
elif some_var < 10:
print("some_var is less than 10")
else:
print("some_var is needed")
print("dog " is "a mammal")
print("cat" is "a mammal")
print("mouse " is "a mammal")
for animal in ["dog","cat","mouse"]:
print("{0} is a mammal".format(animal))
for i in range(4):
print(i)
for i in range(4,8):
print(i)
'''x = 0
while x < 4:
print(x)
x += 1
'''
def add(x,y):
print("x is {0} and y is {1}".format(x,y))
return x + y
add(5,6)
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness")
x = 5
def sex_x(num):
x = num
print(x)
|
b261cd770064d7e35b55d80821053c79efd62e22 | L111235/Python-code | /嵩天python3/两数之和(字典).py | 1,468 | 3.765625 | 4 | '''给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的
那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
'''
def twoSum( nums, target) :
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
lookup = {} #建一个空字典
#(1,2,3)代表tuple元组数据类型,元组是一种不可变序列。
#['p', 'y', 't', 'h', 'o', 'n']代表list列表数据类型
#{'lili': 'girl', 'jon': 'boy'}代表dict字典数据类型,字典是由键对值组组成
for i in range(n):
tmp = target - nums[i] #tmp可以理解为nums[j]
if tmp in lookup: #判断nums[i]+nums[j]是否等于target
return [lookup[tmp], i]
lookup[nums[i]] = i #在字典lookup里增加键为nums[i]、值为i的数据
'''
把nums[i]为键、i为值添加到字典lookup中,然后用后续的target-nums[i]与字典中的
nums[i]值进行对比,就可以把执行一个循环的时间变为一个数值与字典中的值进行对比
的时间
#列表中的元素或者字典中的键值可以是int数值
#假如nums中有两个相同元素2,2,且target是4的话,第一个tmp会保存在字典中,第二个
#会直接输出
'''
|
3f365ba40640a9396a784cb3d597a91775bac3ef | L111235/Python-code | /嵩天python3/科赫雪花(递归迭代).py | 867 | 3.65625 | 4 | #科赫雪花
import turtle as t
def koch(size,n):
if n==0:
t.fd(size)
else:
for angle in [0,60,-120,60]:
t.left(angle)
koch(size/3,n-1)
#n-1阶科赫曲线相当于0阶,n阶相当于1阶
#用一阶图形替代0阶线段画二阶科赫曲线
#用n-1阶图形替代0阶线段画n阶科赫曲线
#将最小size的3倍长的线段替换为一阶科赫曲线
#只画了第n阶的科赫曲线
#每递归一次size都要除以3,初始n阶科赫曲线的size固定
def main():
t.setup(800,800,200,20)
t.width(2)
t.penup()
t.goto(-200,150)
t.pendown()
a=120
for i in range(360//a):#对商取整,range函数参数必须为int型,不能是float
koch(400,3)
t.right(a)
t.hideturtle()
t.done
main()
|
edba9fdc0690c73ee47c88f6d77ade4054c2a70d | L111235/Python-code | /力扣/11.盛最多的水-双指针法.py | 827 | 3.75 | 4 | '''
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
'''
#双指针法
def maxArea(height):
#双指针法:短线段不变, 长线段向内收缩的话,无论之后的线段再长,
#也要以短线段长度为基准,但两条线段之间的距离却缩短了,
#所以不可能比之前装的水多
maxarea=0
i=0
j=len(height)-1
while i<j:
if height[i]<height[j]:
maxarea=max(maxarea,(j-i)*height[i])
i+=1
else:
maxarea=max(maxarea,(j-i)*height[j])
j-=1
return maxarea
height=[1,8,6,2,5,4,8,3,7]
print(maxArea(height)) |
dab7423796be87917bf76e78455eb0fc2853cb33 | L111235/Python-code | /嵩天python3/Hello World.py | 237 | 3.9375 | 4 | a=input('请输入一个整数:')
a=int(a)
if a==0:
print('Hello World 啊!')
elif a>0:
print('He\nll\no \nWo\nrl\nd 啊!')
elif a<0:
print('H\ne\nl\nl\no\n \nW\no\nr\nl\nd 啊!')
else:
print('输入格式有误') |
f88803a8d0b44c62fb19c0e90c5d9e8ad0f43878 | antoniovukovic/test7 | /test.py | 211 | 3.578125 | 4 | # -*- coding: utf-8 -*-
secretNum = 6
test = int(raw_input("Odaberi jedan broj, sigurno ćeš pogriješiti: "))
if test == secretNum:
print("Bravo, 6.")
else:
print("Nisi pogodio prijatelju") |
47f296fe941b489c59dd1952ad6ca111a8a86e8a | pandeesh/CodeFights | /Challenges/sum_of_odd_nos.py | 661 | 3.75 | 4 | #!/usr/bin/env python
"""
Example
For a = 3 and b = 5 the output should be 0.
For a = 3006 and b = 4090 the output should be 1923016.
Note
If you don't want to read the text below, maybe your code won't pass time and memory limits. ;)
[input] integer a
The first integer, -1 < a < 1e8.
[input] integer b
The second integer, 0 < b < 1e8 + 1.
[output] integer
Return the answer modulo 10000007
"""
__author__ = 'pandeesh'
import math
def sumofoddnumbers(a, b):
start_pos = math.ceil( a / 2 )
end_pos = math.floor( b / 2 )
return end_pos ** 2 - start_pos ** 2
#tests
x = sumofoddnumbers(3,5)
print(x)
x = sumofoddnumbers(30,4090)
print(x)
|
d8325a2d9e1214a72880b37b023d4af1a8d88469 | pandeesh/CodeFights | /Challenges/find_and_replace.py | 556 | 4.28125 | 4 | #!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to find in the originalString.
[input] string stringToReplace
A string to replace with.
[output] string
The resulting string.
"""
def findAndReplace(o, s, r):
"""
o - original string
s - substitute
r - replace
"""
return re.sub(s,r,o)
|
5fa88d472f98e125a2dd79e2d6986630bbb28396 | pandeesh/CodeFights | /Challenges/palindromic_no.py | 393 | 4.125 | 4 | #!/usr/bin/env python
"""
You're given a digit N.
Your task is to return "1234...N...4321".
Example:
For N = 5, the output is "123454321".
For N = 8, the output is "123456787654321".
[input] integer N
0 < N < 10
[output] string
"""
def Palindromic_Number(N):
s = ''
for i in range(1,N):
s = s + str(i)
return s + str(N) + s[::-1]
#tests
print(Palindromic_Number(5))
|
2f8478b92851cbf82d84d06cae05bd4ab4f9d161 | donghyoya/swp1-test | /Hello175(숫자 맞추기).py | 542 | 3.515625 | 4 | import random
num_selected = int(input("AI의 범위를 정하세요:"))
ai_random = random.randrange(1,num_selected)
try_number = 1
while try_number < 10:
try_number += 1
num_player = int(input("AI가 생각하는 수를 추측해보세요:"))
if ai_random < num_player:
print("당신은 AI보다 높은수를 생각하고 있습니다.")
if ai_random > num_player:
print("당신은 AI보다 낮은수를 생각하고 있습니다.")
else:
break;
print("{}번 만에 찾으셧습니다!".format(try_number))
|
a69789bfada6cdab50325c5d2c9ff3edf887aebe | dhasl002/Algorithms-DataStructures | /stack.py | 1,562 | 4.3125 | 4 | class Stack:
def __init__(self):
self.elements = []
def pop(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
self.elements.pop(len(self.elements)-1)
return top_element
else:
print("The stack is empty, you cannot pop")
def push(self, element):
self.elements.append(element)
def peek(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
else:
print("The stack is empty, you cannot peek")
return top_element
def is_empty(self):
if len(self.elements) > 0:
return False
else:
return True
def access_element_n(self, n):
if n > len(self.elements)-1:
return None
tmp_stack = Stack()
for i in range(0, n-1):
tmp_stack.push(self.pop())
element_to_return = self.peek()
for i in range(0, n-1):
self.push(tmp_stack.pop())
return element_to_return
if __name__ == "__main__":
print("Creating a stack with values 0-4")
stack = Stack()
for i in range(0, 5):
stack.push(i)
print("Is the stack we built empty? {}".format(stack.is_empty()))
print("Peek the top of the stack: {}".format(stack.peek()))
print("Pop the top of the stack: {}".format(stack.pop()))
print("Peek to make sure the pop worked: {}".format(stack.peek()))
print("Access the 3rd element: {}".format(stack.access_element_n(2)))
|
d9910eb3deaa08b03c3d5ee6b1aac7ee2a8b5f49 | RuchikDama24/IUB_CSCI_B551_EAI | /Assignment 2/part2/SebastianAutoPlayer.py | 7,877 | 3.859375 | 4 | # Automatic Sebastian game player
# B551 Fall 2020
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice object which records the
# result of the first roll (state of 5 dice) and current Scorecard.
# You should implement this method so that it returns a (0-based) list
# of dice indices that should be re-rolled.
#
# 2. It then re-rolls the specified dice, and calls second_roll, with
# the new state of the dice and scorecard. This method should also return
# a list of dice indices that should be re-rolled.
#
# 3. Finally it calls third_roll, with the final state of the dice.
# This function should return the name of a scorecard category that
# this roll should be recorded under. The names of the scorecard entries
# are given in Scorecard.Categories.
#
# this is one layer with comments
from SebastianState import Dice
from SebastianState import Scorecard
import random
class SebastianAutoPlayer:
def __init__(self):
pass
#Score Function: to calculate the scores for the dice roll with the parameters : dice_roll- dice combination, reroll_number: to check which function is calling the score function,
#scorecard=holds all the score values, score_dict= dictionary which holds the computed scores for the different dice combinations so it can be reused again
def score(self,dice_roll,reroll_number,scorecard,score_dict):
s=Scorecard()
score_card=scorecard.scorecard
d=Dice()
#if third rolls calls this score function, then the scoreboard is an object of type dice, else, if called from first or second reroll it is a list of dice rolls
if (reroll_number=="third"):
d.dice=dice_roll.dice
else:
d.dice=dice_roll
Categories = [ "primis", "secundus", "tertium", "quartus", "quintus", "sextus", "company", "prattle", "squadron", "triplex", "quadrupla", "quintuplicatam", "pandemonium" ]
#checking if the score card list exists, as, in the first call the score card is not yet created
if bool(score_card):
for i in score_card:
Categories.remove(i) #removing all those categories which have already been assigned in this game
#calculate the scores for each category in this dice combination
all_good=False # var:all_good lets us know if the scores for this combination has already been computed and if it is present in the dictionary of pre computed scores
if (reroll_number!="third") and d.dice in score_dict:
all_good=True
for category in Categories:
if category not in score_dict[d.dice]:
all_good=False
if all_good is True:
s.scorecard=score_dict[d.dice] #scores for the dice combination is already computed, hence retrieved from the dictionary
else:
for category in Categories: #call the record function of the class Scorecard to retrieve the scores of the dice combination
s.record(category,d)
if (reroll_number!="third"):
score_dict[d.dice]=s.scorecard #store the scoreboard values of the dice in the dictionary
max_category=max(s.scorecard,key=s.scorecard.get) #choose the category with the max score from the scores computed from the categories which are yet to be assinged
if (reroll_number=="third"): #if called from 3rd reroll return the category with the max score else return the max score itself
return max_category
return(s.scorecard[max_category],score_dict)
# Idea derived from expectation_of_reroll() function in program shown in the
# Discussion 8 Walkthrough of CSCI 551 - Spring 2021
# Function to calculate the expectation value
def expection_score_second_reroll(self,roll,reroll,scorecard,score_dict):
exp=0
roll_dice=roll.dice
reroll_score_dict=score_dict
#compute the scores for the dice combinations with the given rerolls
for outcome_a in ((roll_dice[0],) if not reroll[0] else range(1,7)):
for outcome_b in ((roll_dice[1],) if not reroll[1] else range(1,7)):
for outcome_c in ((roll_dice[2],) if not reroll[2] else range(1,7)):
for outcome_d in ((roll_dice[3],) if not reroll[3] else range(1,7)):
for outcome_e in ((roll_dice[4],) if not reroll[4] else range(1,7)):
exp_score=(self.score((outcome_a,outcome_b,outcome_c,outcome_d,outcome_e),"second",scorecard,reroll_score_dict))
reroll_score_dict=exp_score[1]
exp+=exp_score[0]
#calculate the expected value by multiplying the probabilty over all the rerolls and the sum of the scores of the dice rolls
expected_value=exp*1/(6**sum(reroll))
return(expected_value,reroll_score_dict)
#Function to find the best possible rerolls for the first dice roll
def first_roll(self, dice, scorecard):
score_dict={}
roll=dice
current_max=(0,0) #holds the indices and the max value
#compute all the possible rerolls or combinations possible for the dice roll
possible_rerolls=[(roll_a,roll_b,roll_c,roll_d,roll_e) for roll_a in (True,False) for roll_b in (True,False) for roll_c in (True,False) for roll_d in (True,False) for roll_e in (True,False) ]
for reroll in possible_rerolls:
exp_score=(self.expection_score_second_reroll(roll,reroll,scorecard,score_dict))
score_dict=exp_score[1]
if(exp_score[0]>current_max[0]): #compute the maximum of the scores
current_max=(exp_score[0],reroll)
#get the roll combination for which you got the maximum score (eg:-[1,2] means roll the 1st and 2nd die)
reroll_index=[ i for i,j in enumerate(current_max[1]) if j is True]
return reroll_index # return the indices to re roll
#Function to find the best possible rerolls for the second dice roll
def second_roll(self, dice, scorecard):
score_dict={}
roll=dice
current_max=(0,0) #tuple which holds the indices of the dice combination and the max value
#compute all the possible rerolls or combinations possible for the dice roll
possible_rerolls=[(roll_a,roll_b,roll_c,roll_d,roll_e) for roll_a in (True,False) for roll_b in (True,False) for roll_c in (True,False) for roll_d in (True,False) for roll_e in (True,False) ]
for reroll in possible_rerolls:
exp_score=(self.expection_score_second_reroll(roll,reroll,scorecard,score_dict))
score_dict=exp_score[1]
if(exp_score[0]>current_max[0]): #compute the maximum of the scores
current_max=(exp_score[0],reroll)
#get the roll combination for which you got the maximum score(eg:-[1,2] means roll the 1st and 2nd die)
reroll_index=[ i for i,j in enumerate(current_max[1]) if j is True]
return reroll_index# return the indices to re roll
#return the best category for which the 3 rolled dice belongs to out of all the categories by choosing the maximum category value
def third_roll(self, dice, scorecard):
score_dict={}
scorecard_category=self.score(dice,"third",scorecard,score_dict)
return scorecard_category
|
fcb556abbd51a184f6dce990399fac1049b2e5a7 | davidlyness/Advent-of-Code-2018 | /17/main.py | 2,660 | 3.65625 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 17"""
import collections
def find_water_overflow(water_x, water_y, step):
"""Locate bucket overflow in a given direction."""
while True:
next_cell = grid[water_y + 1][water_x]
current_cell = grid[water_y][water_x]
if current_cell == "#":
water_x -= step
return water_x, False
elif next_cell == ".":
sources.append((water_x, water_y))
return water_x, True
elif current_cell == "|" and next_cell == "|":
return water_x, True
water_x += step
scans = []
for line in open("puzzle_input").read().split("\n"):
clay_start, clay_range = line.split(", ")
clay_start = int(clay_start.split("=")[1])
range1, range2 = map(int, clay_range[2:].split(".."))
scans.append((line[0], clay_start, range1, range2))
x_min, x_max = float("inf"), float("-inf")
y_min, y_max = float("inf"), float("-inf")
for range_type, point, range_start, range_end in scans:
if range_type == "x":
x_min, x_max = min(point, x_min), max(point, x_max)
y_min, y_max = min(range_start, y_min), max(range_end, y_max)
else:
x_min, x_max = min(range_start, x_min), max(range_end, x_max)
y_min, y_max = min(point, y_min), max(point, y_max)
x_min -= 1
x_max += 1
grid = [["." for _ in range(x_max - x_min)] for _ in range(y_max + 1)]
for range_type, point, range_start, range_end in scans:
for i in range(range_start, range_end + 1):
if range_type == "x":
x, y = point, i
else:
x, y = i, point
grid[y][x - x_min] = "#"
sources = [(500 - x_min, 0)]
while sources:
x_source, y_source = sources.pop()
y_source += 1
while y_source <= y_max:
cell = grid[y_source][x_source]
if cell == "|":
break
elif cell == ".":
grid[y_source][x_source] = "|"
y_source += 1
elif cell in("#", "~"):
y_source -= 1
left_amount, left_overflow = find_water_overflow(x_source, y_source, -1)
right_amount, right_overflow = find_water_overflow(x_source, y_source, 1)
for x in range(left_amount, right_amount + 1):
if left_overflow or right_overflow:
grid[y_source][x] = "|"
else:
grid[y_source][x] = "~"
symbol_counts = collections.Counter(cell for row in grid[y_min:] for cell in row)
def part_one():
"""Solution to Part 1"""
return symbol_counts["~"] + symbol_counts["|"]
def part_two():
"""Solution to Part 2"""
return symbol_counts["~"]
|
7358df3f9f86fda07fbd980364aa9d2877eed918 | davidlyness/Advent-of-Code-2018 | /09/main.py | 935 | 3.78125 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 9"""
import collections
import re
with open("puzzle_input") as f:
match = re.search("(?P<players>\d+) players; last marble is worth (?P<points>\d+) points", f.read())
num_players = int(match.group("players"))
num_points = int(match.group("points"))
def run_marble_game(players, max_points):
"""Run marble game with specified number of players and points."""
marbles = collections.deque([0])
scores = collections.defaultdict(int)
for marble in range(1, max_points + 1):
if marble % 23 > 0:
marbles.rotate(-1)
marbles.append(marble)
else:
marbles.rotate(7)
scores[marble % players] += marble + marbles.pop()
marbles.rotate(-1)
return max(scores.values())
# Part One
print(run_marble_game(num_players, num_points))
# Part Two
print(run_marble_game(num_players, num_points * 100))
|
cb3f6144b597cb5dc22ce03d9ac54dd7abe3aee4 | Bitcents/exercism_tracks | /python/hangman/hangman.py | 1,425 | 3.6875 | 4 | # Game status categories
# Change the values as you see fit
STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_ONGOING = "ongoing"
class Hangman:
def __init__(self, word):
self.remaining_guesses = 9
self.status = STATUS_ONGOING
self.__word = word
self.remaining_characters = set()
self.guessed_characters = set()
for letter in word:
self.remaining_characters.add(letter)
def guess(self, char):
# Check if the game is still going on
if self.status != STATUS_ONGOING:
raise ValueError('game is over')
if char in self.remaining_characters:
self.remaining_characters.remove(char)
self.guessed_characters.add(char)
if len(self.remaining_characters) == 0:
self.status = STATUS_WIN
elif char in self.guessed_characters:
self.remaining_guesses -= 1
else:
self.remaining_guesses -= 1
# Check if there are any guesses left
if self.remaining_guesses < 0:
self.status = STATUS_LOSE
def get_masked_word(self):
masked_word = ""
for letter in self.__word:
if letter in self.remaining_characters:
masked_word += '_'
else:
masked_word += letter
return masked_word
def get_status(self):
return self.status
|
f4a3d3365a114ced431f2a84d6c2b7b631c97575 | Bitcents/exercism_tracks | /python/difference-of-squares/difference_of_squares.py | 240 | 3.9375 | 4 | def square_of_sum(number):
return (number*(number+1)//2)**2
def sum_of_squares(number):
return (number)*(2*number + 1)*(number + 1)//6
def difference_of_squares(number):
return square_of_sum(number) - sum_of_squares(number)
|
1ee723a5d3ac7ccd8883aa6b0e3b7129c90da52d | Bitcents/exercism_tracks | /python/pythagorean-triplet/pythagorean_triplet.py | 297 | 3.765625 | 4 | from math import sqrt
def triplets_with_sum(number):
results = []
for i in range(number//2, number//3, -1):
for j in range(i-1,i//2,-1):
k = sqrt(i*i - j*j)
if i + j + k == number and k < j:
results.append([int(k),j,i])
return results
|
a8934dd089aeb3763409d937502708680e59d765 | AnupritaPro/gittest | /list1.py | 845 | 3.78125 | 4 | #list
l1=[2011,2013,"anu","pratiksha"]
l2=[2021,22.22,2002,1111]
print "value of l1",l1
print ("value of ",l1[1])
print "value of ",l1[0:2]
print "length of list is:",len(l1)
print "minimum lenght",min(l2)
print "maximum length",max(l2)
l1.append("sarita")
print "add update",l1
l1.append(2011)
print l1
c=l1.count(2011)
print "count is",c
l1.extend(l2)
print l1
l2.insert(2,400)
print l2
#l1.pop(2)
print l1.pop()
print l1
l1.remove("anu")
print l1
l2.reverse()
print l2
l1.sort()
print l1
#directory
dict={'Name':'Anu','Age':50,'class':'bsc'};
print "dict['Name']:",dict['Name'];
print "dict['Age']:",dict['Age'];
dict['Age']=20
print "dict['Age']:",dict['Age'] #edit
dict['friend']="Sarita"
print "dict['friend']:",dict['friend'] #insert
#print dict
del dict['Name']
print "dict['Name']",dict['Name']
dict.clear();
print dict
#del dict
|
46193fb3b9db2783700ef0026a2e1d274eb43842 | ramesheerpina/AutomateBoringStuff | /AutomateBoringStuff.py | 517 | 4.09375 | 4 | print("I am thinking of a number between 1 and 20. \n")
import random
randomnum = random.randint(1,20)
for guesstaken in range(1,9):
print("Take Guess\n")
guess = int(input())
if guess < randomnum:
print("your guess is too low")
elif guess > randomnum:
print("your guess is too high")
else:
break
if guess == randomnum:
print("Good Job! You guessed my number in " + str(guesstaken) + " guesses")
else:
print("Nope. The number I was thinking of was "+str(randomnum)) |
33dbfd93f39cc11cca56d3099ac9310a3f488113 | javibolibic/SPSI | /kasiskiAttack.py | 5,683 | 3.640625 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
###################################################################
# _ _ _ _ _ _ _ _ #
# | | ____ _ ___(_)___| | _(_) / \ | |_| |_ __ _ ___| | __ #
# | |/ / _` / __| / __| |/ / | / _ \| __| __/ _` |/ __| |/ / #
# | < (_| \__ \ \__ \ <| |/ ___ \ |_| || (_| | (__| < #
# |_|\_\__,_|___/_|___/_|\_\_/_/ \_\__|\__\__,_|\___|_|\_\ #
# Creado por Antonio Miguel Pozo Cámara y Javier Bolívar Valverde #
# Universidad de Granada #
###################################################################
from fractions import gcd
import sys
import collections
# alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"
alphabet = "ABCDEFGHIJKLMNNOPQRSTUVWXYZ"
spanish = 0.0775
min_subs_size = 4
"""
Desencripta el texto plano a cifrado vigenère
"""
def decrypt(cipher, key):
key_index = 0
plain = ''
for i in cipher:
plain += chr((ord(i)-ord(key[key_index])-2*65) %26 +65)
if key_index < len(key) - 1:
key_index += 1
else:
key_index = 0
return plain
"""
busca todas las subcadenas de longitud 'l' en 'text'
modifica la variable global lista_ocurrencias, añadiendo la distancia entre dichas repeticiones.
"""
def findsubs(text, l, lista_ocurrencias):
for i in range(len(text)-l):
subcadena = text[i:i+l]
found = text[i+l:].find(subcadena)
if found != -1:
f = found+i+l
if i>0 and text[i-1:i+l] == text[f-1:f+l]:
continue
if i+l < len(text) and text[i:i+l+1] == text[f:f+l+1]:
continue
print "%-10s %3d " % (subcadena, found+l)
a = found+l
lista_ocurrencias.append(a)
return lista_ocurrencias
"""
excluye caracteres de text que no estan en el alfabeto alphabet
"""
def filter(text):
ctext = ""
for c in text:
c = c.upper()
if c in alphabet:
ctext += c
sys.stdout.write("Sin caracteres raros:")
sys.stdout.write(ctext)
return ctext
"""
Imprime la cadena pasada como argumento.
"""
def imprime(cadena):
sys.stdout.write("***** ")
for i in range(len(cadena)):
sys.stdout.write(cadena[i])
sys.stdout.write(" *****")
print""
"""
Calcula el índice de coincidencia de una cadena “cadena” en la posición “i”
"""
def indexofCoincidence(cadena, i):
N = len(cadena[i])
freqs = collections.Counter( cadena[i] )
freqsum = 0.0
for letter in alphabet:
freqsum += freqs[ letter ] * ( freqs[ letter ] - 1 )
IC = freqsum / (N*(N-1))
return IC
def splitText(ctext, mcd):
cadena=[[] for x in range(mcd)]
for i in range(0, (len(ctext)/mcd)):
j=0
if i == 0:
for j in range(0,mcd):
cadena[j].append(ctext[j])
else:
for j in range(0,mcd):
if i*mcd+j<len(ctext):
cadena[j].append(ctext[i*mcd+j])
return cadena
def ktest(text):
lista_ocurrencias = []
ctext = filter(text)
"""
el tamaño máximo de una cadena que se puede repetir en el texto tiene
de tamaño como máximo la longitud del texto / 2. Empieza desde esa longitud hacia abajo.
"""
for l in range(len(text)/2,min_subs_size-1,-1):
findsubs (ctext, l, lista_ocurrencias)
if len(lista_ocurrencias)<=1:
# print "asasdfasdfasdf"
sys.exit("No se han encontrado cadenas repetidas o no se ha podido dictaminar una longitud de clave válida")
mcd = reduce(gcd,lista_ocurrencias) #cálculo del máximo común divisor
print "Posible longitud de la clave = " + str(mcd)
if mcd ==1:
print "El programa no es concluyente. De la distancia entre subcadenas repetidas no se puede extraer un tamaño de clave válido"
return
# sys.exit(0)
print ""
cadena = splitText(ctext, mcd)
"""
contar las letras que más se repiten en cada una de las cadenas
"""
ocurrencias=0
clave=[]
vocurrencias=[[] for x in range(mcd)] #ocurrencias de cada caracter c en cada subcadena
for i in range(0, mcd):
sys.stdout.write("cadena[" + str(i) + "]== ")
for j in range(len(cadena[i])):
sys.stdout.write(cadena[i][j])
print ""
for c in alphabet:
ocurrencias = cadena[i].count(c);
vocurrencias[i].append(ocurrencias)
max1=0
max2=0
max3=0
letra1=''
letra2=''
letra3=''
maxocurrencias1=0
maxocurrencias2=0
for k in range(0, len(alphabet)):
cantidad = vocurrencias[i][k%len(alphabet)]
cantidad +=vocurrencias[i][(k+4)%len(alphabet)]
cantidad +=vocurrencias[i][(k+15)%len(alphabet)]
if cantidad > max1:
max3=max2
max2=max1
max1=cantidad
letra3=letra2
letra2=letra1
letra1=alphabet[k]
elif cantidad > max2:
max3=max2
max2=cantidad
letra3=letra2
letra2=alphabet[k]
elif cantidad > max3:
max3=cantidad
letra3=alphabet[k]
print "Primera letra más probable: " + letra1
print "Segunda letra más probable: " + letra2
print "Tercera letra más probable: " + letra3
"""
Cálculo del íncide de coincidencia
"""
IC = indexofCoincidence(cadena, i)
print "Indice de coincidencia de cadena[" + str(i) + "] %.3f" % IC, "({})".format( IC )
if IC < spanish:
print "(NO FIABLE)\n"
else:
print"(FIABLE)\n"
clave.append(letra1)
"""
imprimir las claves
"""
sys.stdout.write("POSIBLE CLAVE\t")
imprime(clave)
clavestring = ''.join(clave)
plano = decrypt(ctext, clavestring)
print "Posible texto plano: " + str(plano)
if __name__ == "__main__":
def main():
while True:
text =raw_input ("Introducir el texto cifrado: \n")
if len(text) == 0:
break
ktest(text)
main()
# *************************************CADENA DE EJEMPLO AQUÍ*************************************
# PPQCAXQVEKGYBNKMAZUYBNGBALJONITSZMJYIMVRAGVOHTVRAUCTKSGDDWUOXITLAZUVAVVRAZCVKBQPIWPOU
# PPQCAXQV EKGYBNKM AZUYBNGB ALJONITS ZMJYIMVR AGVOHTVR AUCTKSGD DWUOXITL AZUVAVVR AZCVKBQP IWPOU
|
546936ded7cbd026dfd23c02cffda693e9840c01 | aliensmart/week2_day4 | /terminalTeller2/account.py | 1,483 | 3.65625 | 4 | import json
import os
class Account:
filepath = "data.json"
def __init__(self, username):
self.username = username
self.pin = None
self.balance = 0.0
self.data = {}
self.load()
def load(self):
try:
with open(self.filepath, 'r') as json_file:
self.data = json.load(json_file)
except FileNotFoundError:
pass
if self.username in self.data:
self.balance = self.data[self.username]['balance']
self.pin = self.data[self.username]['pin']
def save(self):
self.data[self.username] = {
"balance": self.balance,
"pin": self.pin
}
with open(self.filepath, 'w') as json_file:
json.dump(self.data, json_file, indent=3)
def withdraw(self, amount):
if amount < 0:
raise ValueError("amount must be positive")
if self.balance < amount:
raise ValueError("amount must not be greater than balance")
self.balance -= amount
def deposit(self, amount):
if amount < 0:
raise ValueError("amount must be positive")
self.balance += amount
@classmethod
def login(cls, username, pin):
# Account.login("Greg", "1234")
# should return an account object with my data
account = cls(username)
if pin != account.pin:
return None
return account
|
83a2fe0e985ffa4d33987b15e6b4ed8a6eb5703b | Nbouchek/python-tutorials | /0001_ifelse.py | 836 | 4.375 | 4 | #!/bin/python3
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Input Format
#
# A single line containing a positive integer, .
#
# Constraints
#
# Output Format
#
# Print Weird if the number is weird; otherwise, print Not Weird.
#
# Sample Input 0
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input("Enter a number >>> ").strip())
if n % 2 == 1:
print("Weird")
if n % 2 == 0 and 2 <= n <= 5:
print("Not Weird")
if n % 2 == 0 and 6 <= n <= 20:
print("Weird")
if n % 2 == 0 and n > 20:
print("Not Weird")
|
4e3be7e82c018e9309bf2d16135cd12af6302328 | ByketPoe/gmitPandS | /week02/lab2.3.2sub.py | 790 | 4.0625 | 4 | # sub.py
# The purpose of this program is to subtract one number from another.
# author: Emma Farrell
# The input fuctions ask the user to input two numbers.
# This numbers are input as strings
# They must be cast as an integer using the int() function before the program can perform mathematical operations on it
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
# The result of subtracting the second number from the first number is calculted
# The result is printed with the format() function used to insert the variables within the string
answer = number1 - number2
print("{} minus {} is {}".format(number1, number2, answer))
# Errors occur when the user tries to enter a float or a string.
# The program is able to calculate minus numbers |
a30b0e3f5120fc484cd712f932171bd322e757df | ByketPoe/gmitPandS | /week04-flow/lab4.1.3gradeMod2.py | 1,152 | 4.25 | 4 | # grade.py
# The purpose of this program is to provide a grade based on the input percentage.
# It allows for rounding up of grades if the student is 0.5% away from a higher grade bracket.
# author: Emma Farrell
# The percentage is requested from the user and converted to a float.
# Float is appropriate in this occasion as we do not want people to fail based on rounding to an integer.
percentage = float(input("Enter the percentage: "))
# In this modification of the program, the percentage inputted by the user is rounded.
# As we want to round up if the first decimal place is 0.5 or greater, we do not need to state number of decimal places.
percentageRounded = round(percentage)
# The if statements are executed as in the original program, but evaluating the new variable "percentageRounded" instead of "percentage"
if percentageRounded < 0 or percentageRounded > 100:
print("Please enter a number between 0 and 100")
elif percentageRounded < 40:
print("Fail")
elif percentageRounded < 50:
print("Pass")
elif percentageRounded < 60:
print("Merit 1")
elif percentageRounded < 70:
print("Merit 2")
else:
print("Distinction") |
0037856dbebe4ada7ce5edf268bb83f7563e1169 | ByketPoe/gmitPandS | /week02/addOne.py | 327 | 3.90625 | 4 | # addOne.py
# The purpose of this program is to add 1 to a number
# author: Emma Farrell
# Read in the number and cast to an integer
number = int(input("Enter a number: "))
# Add one to the number and assign the result to the variable addOne
addOne = number + 1
# Print the result
print('{} plus one is {}'.format(number, addOne)) |
0c64591006436bfdf1c666b79f4d2e90da5afcff | ByketPoe/gmitPandS | /week02/nameAndAge.py | 353 | 4.0625 | 4 | # nameAndAge.py
# The purpose of this program is to
# author: Emma Farrell
# Request the name and age of the user
name = input('What is your name? ')
age = input('What is your age? ')
# Output the name and age (using indexing)
print('Hello {0}, your age is {1}'.format(name, age))
# Modified version
print('Hello {0}, \tyour age is {1}'.format(name, age)) |
6f16bc65643470b2bca5401667c9537d88187656 | ByketPoe/gmitPandS | /week04-flow/lab4.1.1isEven.py | 742 | 4.5 | 4 | # isEven.py
# The purpose of this program is to use modulus and if statements to determine if a number is odd or even.
# author: Emma Farrell
# I prefer to use phrases like "text" or "whole number" instead of "string" and "integer" as I beleive they are more user friendly.
number = int(input("Enter a whole number: "))
# Modulus (%) is used to calculated the remainder of the input number divided by 2.
# The if statement evaluates if the remainder is equal to 0.
# If true, the number is even and a message to indicate this is printed.
# Otherwise, the number is odd and the message diplayed will state that it is odd.
if (number % 2) == 0:
print("{} is an even number".format(number))
else:
print("{} is an odd number".format(number)) |
0a13765ecbc3d4c6cae6e666e9ec67149eb7d1a0 | smiks/CodeWars | /ValidateSudoku/program.py | 3,002 | 3.59375 | 4 | __author__ = 'Sandi'
class Sudoku(object):
def __init__(self, sudo):
self.sudo = sudo
def check(self, row):
for v in row.values():
if v != 1:
return False
return True
def is_valid(self):
su = self.sudo # less typing in the future
""" check dimensions """
shouldBe = len(su)
for row in su:
if len(row) != shouldBe:
return False
""" assign allowed values """
allowedValues = {i for i in range(1,shouldBe+1)}
""" check rows """
nums = [{i:0 for i in range(1, shouldBe+1)}for _ in range(shouldBe)]
for e, row in enumerate(su):
for el in row:
if not isinstance(el, int) or el not in allowedValues:
return False
nums[e][el] += 1
if not self.check(nums[e]):
return False
""" check columns """
nums = [{i:0 for i in range(1, shouldBe+1)}for _ in range(shouldBe)]
for e, col in enumerate(zip(*su)):
for el in col:
if isinstance(el, bool) or not isinstance(el, int) or el not in allowedValues:
return False
nums[e][el] += 1
if not self.check(nums[e]):
return False
""" check quadrants """
qsize = int(shouldBe**0.5)
""" iterate through quadrants """
for i in range(qsize):
for j in range(qsize):
toCheck = {i:0 for i in range(1, shouldBe+1)}
""" iterate through single quadrant """
for row in range(i*qsize, (i+1)*qsize):
for col in range(j*qsize, (j+1)*qsize):
tmp = su[row][col]
toCheck[tmp] += 1
if not self.check(toCheck):
return False
return True
goodSudoku1 = Sudoku([
[7,8,4, 1,5,9, 3,2,6],
[5,3,9, 6,7,2, 8,4,1],
[6,1,2, 4,3,8, 7,5,9],
[9,2,8, 7,1,5, 4,6,3],
[3,5,7, 8,4,6, 1,9,2],
[4,6,1, 9,2,3, 5,8,7],
[8,7,6, 3,9,4, 2,1,5],
[2,4,3, 5,6,1, 9,7,8],
[1,9,5, 2,8,7, 6,3,4]
])
goodSudoku2 = Sudoku([
[1,4, 2,3],
[3,2, 4,1],
[4,1, 3,2],
[2,3, 1,4]
])
badSudoku2 = Sudoku([
[1,2,3,4,5],
[1,2,3,4],
[1,2,3,4],
[1]
])
badSudoku3 = Sudoku([[True]])
badSudoku4 = Sudoku([[1, 4, 4, 3, 'a'], [3, 2, 4, 1], [4, 1, 3, 3], [2, 0, 1, 4], ['', False, None, '4']])
badSudoku5 = Sudoku([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 1, 5, 6, 4, 8, 9, 7], [3, 1, 2, 6, 4, 5, 9, 7, 8], [4, 5, 6, 7, 8, 9, 1, 2, 3], [5, 6, 4, 8, 9, 7, 2, 3, 1], [6, 4, 5, 9, 7, 8, 3, 1, 2], [7, 8, 9, 1, 2, 3, 4, 5, 6], [8, 9, 7, 2, 3, 1, 5, 6, 4], [9, 7, 8, 3, 1, 2, 6, 4, 5]])
""" valid sudokus """
assert goodSudoku1.is_valid()
assert goodSudoku2.is_valid()
""" invalid sudokus """
assert not badSudoku2.is_valid()
assert not badSudoku3.is_valid()
assert not badSudoku4.is_valid()
assert not badSudoku5.is_valid() |
acb07871af074d9a4560ffca24697c2bcdda5403 | bhavyavj/python-challenges | /problem6.py | 950 | 4.09375 | 4 | #!/usr/bin/python3
options='''
press 1 to view the contents of a file
press 2 cat -n => to show line numbers
press 3 cat -e => to add $ sign at the end of the line
press 4 to view multiple files at once
'''
print(options)
opt=input("Enter your choice")
if (opt==1):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
print(data)
f.close()
if (opt==2):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
a=data.split('\n')
line_no=1
for i in a:
print(str(line_no)+" "+i)
line_no=line_no+1
if (opt==3):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
a=data.split('\n')
for i in a:
print(i+"$")
if (opt==4):
noOfFiles=int(input('Enter no. of files :'))
filenames=[]
print("Press enter after writing a file name")
print('Enter name of files :')
for i in range(noOfFiles):
name=input()
filenames.append(name)
for i in filenames:
f=open(i,'r')
print(f.read())
f.close()
|
4f70866e867bc46f9c609efece8a7338a3f5ad64 | kee007ney/scripts | /toy.py | 282 | 3.9375 | 4 | import csv
"""
This script will use xxx.csv as an input and output all the rows with the row number.
"""
with open("A.csv", 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in csvreader:
for j in xrange(0,len(row)):
print (j,row[j])
|
5a983b9c67438e27c89c5f973d9d09b05dc6ca79 | airje/codewars | /whatsthefloor.py | 123 | 3.546875 | 4 | def get_real_floor(n):
if n>13:
return n-2
elif n>0 and n<14:
return n-1
else:
return n |
7d38c44f7a46926dbf041ceb774a08284cdf8204 | airje/codewars | /findthenextperfectsquare.py | 213 | 3.921875 | 4 | import math as m
def find_next_square(n):
# Return the next square if sq is a square, -1 otherwise
result = (m.sqrt(n)+1)**2
if result-int(result) > 0:
return -1
else:
return result |
8b6646f5da8840e82476bb97f9e5c2668963a612 | Aeronyx/School | /conversations.py | 1,531 | 3.921875 | 4 | # File: conversations.py
# Name: George Trammell
# Date: 9/8/19
# Desc: Program has a discussion with the user.
# Sources: None
# OMH
from time import sleep
# Initial Greeting
print('Hello! What is your name?')
name = input('Name: ')
# Capitalize name if uncapitalized
name = name[0].upper() + name[1:]
print('Hello %s! \n' %(name))
sleep(1)
# First Question
print('%s, Do you have any pets?' %(name))
sleep(1)
# Response tree for amount of pets
pets = input('Type \'y\' for Yes and \'n\' for No: ')
# Nested if statement for appropriate response
if pets == 'y':
print('Wonderful. How many pets? \n')
sleep(.5)
petNumber = int(input('Number of pets (integer): '))
if petNumber > 2:
print('That\'s a lotta pets! You make me proud.')
elif petNumber == 2:
print('I hope you love your duo very much.')
elif petNumber == 1:
print('One loving companion is all you need.')
elif petNumber < 0:
print('You can\'t have negative pets!')
print('Thanks for playing!')
# No pets, ask about eye color instead
elif pets == 'n':
print('\nUnbelieveable. This program is terminated. \n')
sleep(1)
print('Kidding. Sorta. What color are your eyes?')
eyeColor = input('Eye color: ')
eyeColor = eyeColor[0].upper() + eyeColor[1:]
sleep(.5)
print('Processing...')
sleep(1.5)
print('%s\'s a beautiful color! You\'ve been redeemed.' %(eyeColor))
print('Thanks for playing!')
# Incorrect entry
else:
print('You didn\'t follow instructions! Try again.') |
38b6119f2584c44b97990c72d983b4e55275fc2e | akashchevli/Competitive-Programming | /FindBit.py | 1,349 | 4 | 4 | """
Write a program to find out the bits of the given number
Input
Enter number:7
How many bits want:4
Output
0111
Description
The original bits of number 7 is 111, but the user want 4 bits so you have added zeros in front of the bits
Input
Enter number:12
How many bits want:2
Output:
Actual bits is greater than the bits you want
Description
The original bits of number 12 is 1100, but the user enters 2 bits which is less than the length of the original bits
that's why it will be thrown an error
"""
result = ''
negative = False
def getBit(n):
global result, negative
if str(n)[0] == '-':
n = str(n)[1:]
negative = True
n = int(n)
if n == 0 or n == 1:
return str(n).zfill(bits)
next_n = n // 2
rem = n % 2
result += str(rem)
if next_n == 1:
result = str(next_n) + result[::-1]
size = len(result)
if bits < size:
return "Actual bits is greater than the bits you want"
if negative:
return '-' + result.zfill(bits)
return result.zfill(bits)
return getBit(next_n)
n = int(input("Enter number:"))
bits = int(input("How many bits want:"))
print(getBit(n)) |
dd256c28dcb505d183faf042d1ef88f8661435d9 | yaozeye/python | /learner/exercise/greatest_common_divisor.py | 635 | 3.984375 | 4 | # Python Greatest Common Divisor
# Code by Yaoze Ye
# https://yaozeye.github.io
# 09 April 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
num1 = int(input('The first number: '))
num2 = int(input('The second number: '))
num3 = min(num1, num2)
for i in range(1, num3 + 1):
if num1 % i == 0 and num2 % i == 0:
greatest_common_divisor = i
print('The maximum common divisor of %d and %d is %d.' % (num1, num2, greatest_common_divisor))
least_common_multiple = (num1 * num2) / greatest_common_divisor
print('The minimum common multiple of %d and %d is %d.' % (num1, num2, least_common_multiple))
|
e836385db2c976c6b1c779e25f0717a0eb4f57f9 | yaozeye/python | /learner/exercise/rectangle_area.py | 264 | 3.625 | 4 | # Python Rectangle Area
# Code by Yaoze Ye
# https://yaozeye.github.io
# 19 March, 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
length = float(input())
width = float(input())
area = length * width
print("{:.2f}".format(area))
|
a708feba667fb030f755e5564c9cd1772a127dbc | econocoffee/Econo-Maths | /fun.py | 247 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 18:19:07 2020
@author: gdolores
"""
def area_r():
print(" Radio : ")
Radio = float(input())
return(" El área es: " + str( ( Radio ** 2 ) * 3.1416 )) |
b8d30e11c617a20d87e105c74cdcb05f8b9147d3 | eralpkor/cs-module-project-iterative-sorting | /src/searching/searching.py | 900 | 4.0625 | 4 | def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
low = 0
high = len(arr) - 1
# While we haven't narrowed it down to one element ...
while low <= high:
# ... check the middle element
mid = (low + high) // 2
guess = arr[mid]
# Found the item.
if guess == target:
return mid
# The guess was too high.
if guess > target:
high = mid - 1
# The guess was too low.
else:
low = mid + 1
return -1 # not found
# list1 = ['eat', 'sleep', 'repeat']
# str2 = 'dude'
# obj1 = enumerate(list1)
# obj2 = enumerate(str2)
# print(list(enumerate(list1)))
# print(list(enumerate(str2)))
# print(list(obj1))
|
4bac91f95ecabfd99ddc83c288f667c743f00e9a | abtahi-tajwar/python-algo-implementation | /dfs.py | 705 | 4.03125 | 4 | # Calling dfs function will traverse and print using dfs method
def graphSort(graph):
newGraph = dict()
for key in graph:
lst = graph[key]
lst.sort()
newGraph[key] = lst
return newGraph
stack = []
def dfs(graphMap, currentNode):
graph = graphSort(graphMap)
dict_map = dict()
for node in graphMap:
dict_map[node] = False
traverse(graph, currentNode, dict_map)
def traverse(graph, currentNode, dict_map):
stack.append(currentNode)
for node in graph[currentNode]:
if node not in stack:
traverse(graph, node, dict_map)
if dict_map[stack[-1]] != True:
dict_map[stack[-1]] = True
print(stack.pop())
|
4dc6ecdfe3063f3015801cf13472f7f77d742f0a | Denton044/Machine-Learning | /PythonPractice/python-programming-beginner/Python Basics-1.py | 2,217 | 4.5625 | 5 | ## 1. Programming And Data Science ##
england = 135
india = 124
united_states = 134
china = 123
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print (china)
print (united_states)
print (india)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact = 122.5
print(china_name, china_rounded, china_exact)
## 4. The Type Function ##
china_name = "China"
china_exact = 122.5
print (type(china_exact))
## 5. Converting Types ##
china_rounded = 123
int_to_str = str(china_rounded)
str_to_int = int(int_to_str)
## 6. Comments ##
#temperature in China
china = 123
#temperature in India
india = 124
#temperature in United__States
united_states = 134
## 7. Arithmetic Operators ##
china_plus_10 = china + 10
us_times_100 = united_states *100
print (china_plus_10, us_times_100)
## 8. Order Of Operations ##
china = 123
india = 124
united_states = 134
china_celsius = (china - 32) * 0.56
india_celsius = (india - 32) * 0.56
us_celsius = (united_states -32) *0.56
## 10. Using A List To Store Multiple Values ##
countries = []
temperatures = []
countries.append('China')
countries.append('India')
countries.append('United States')
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
print (countries, temperatures)
## 11. Creating Lists With Values ##
temps = ['China', 122.5, 'India', 124.0, 'United States', 134.1]
## 12. Accessing Elements In A List ##
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
# Add your code here.
china = countries[0]
china_temperature = temperatures[0]
## 13. Retrieving The Length Of A List ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
two_sum = len(countries) + len(temperatures)
## 14. Slicing Lists ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
countries_slice = countries[1:4]
temperatures_slice = temperatures[-3:] |
342201ebee1eea4fcf8e381dfbdba93caae0af61 | Denton044/Machine-Learning | /PythonPractice/data-analysis-intermediate/Pandas Internals_ Series-145.py | 1,021 | 3.734375 | 4 | ## 1. Data Structures ##
import pandas as pd
fandango = pd.read_csv("fandango_score_comparison.csv")
fandango.head()
## 2. Integer Indexes ##
fandango = pd.read_csv('fandango_score_comparison.csv')
series_film = fandango['FILM']
print(series_film[0:5])
series_rt = fandango['RottenTomatoes']
print(series_rt[:5])
## 3. Custom Indexes ##
# Import the Series object from pandas
from pandas import Series
film_names = series_film.values
rt_scores = series_rt.values
series_custom = pandas.Series(data = rt_scores, index= film_names)
print(series_custom)
## 4. Integer Index Preservation ##
series_custom = Series(rt_scores , index=film_names)
series_custom[['Minions (2015)', 'Leviathan (2014)']]
fiveten = series_custom[5:11]
print(fiveten)
## 5. Reindexing ##
original_index = series_custom.index
sorted_index = sorted(original_index)
sorted_by_index = series_custom.reindex(sorted_index)
## 6. Sorting ##
sc2 = series_custom.sort_index()
sc3 = series_custom.sort_values()
print(sc2[0:10])
print(sc3[0:10]) |
572fe2d092fa65fb3beec45c1ed467e65529998b | ChandanShastri/PGPTP | /Tools/separateByYear.py | 660 | 3.5 | 4 | #!/usr/bin/env python
'''
Created on Oct 13, 2014
@author: waldo
'''
import sys
import os
import csv
def makeOutFile(outdict, term, fname, header):
outfile = csv.writer(open(term + '/' + fname, 'w'))
outdict[term] = outfile
outfile.writerow(header)
if __name__ == '__main__':
if len(sys.argv) < 1:
print 'Usage: separateByYear csvFile'
sys.exit(1)
fname = sys.argv[1]
fin = csv.reader(open(fname, 'rU'))
header = fin.next()
outdict = {}
for l in fin:
term = l[1]
if term not in outdict:
makeOutFile(outdict, term, fname, header)
outdict[term].writerow(l) |
6fa32bc3efeb0a908468e6f9cec210846cd69085 | yoli202/cursopython | /ejerciciosBasicos/main3.py | 396 | 4.40625 | 4 | '''
Escribir un programa que pregunte el nombre del usuario en la consola
y después de que el usuario lo introduzca muestre por pantalla <NOMBRE>
tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y
<n> es el número de letras que tienen el nombre.
'''
name = input(" Introduce tu nombre: ")
print(name.upper() + " Tu nombre tiene " + str(len(name)) + (" letras")) |
0606fc6b61277a99f4c5146df4784e2ae5f70e50 | VadimSerov/Zarina2 | /Python и C++/Untitled-3.py | 269 | 3.65625 | 4 | import random
random.seed()
n=int(input("введите разменость массива "))
a=[]
for i in range(0,n) :
a.append(random.randint(0,100))
print(a)
k=int(input("введите целое число для проверки "))
aver=sum(a)
print(aver) |
0c729c03c7a3ed808fe246ae5df3494e6857ac5b | adelbast/Space-Conquest-3012 | /src/Tile/Map.py | 1,144 | 3.65625 | 4 | __author__ = "Arnaud Girardin &Alexandre Laplante-Turpin& Antoine Delbast"
import csv
class Map:
def __init__(self, path):
self.map = []
self.startingPoint =[]
self.numRow = 0
self.numCol = 0
self.generateMapFromFile(path)
def generateMapFromFile(self, path):
#Lecture de la map dans le fichier csv
with open(path, 'r') as f:
reader = csv.reader(f)
for row in reader:
self.numCol = len(row)
self.map.append(row)
self.numRow +=1
self.startingPoint.append((4,4))
self.startingPoint.append((self.numCol-4,self.numRow-4))
self.startingPoint.append((self.numCol-4,int((self.numRow/2)-4)))
self.startingPoint.append((self.numCol-4,4))
self.startingPoint.append((int((self.numCol/2)-5),self.numRow-4))
self.startingPoint.append((52,52))
self.startingPoint.append((int(self.numCol/2-4),4))
self.startingPoint.append((4,self.numRow-9))
self.startingPoint.append((15,int((self.numRow/2)+3)))
|
e34a8e5ccc558f833d4c50fdc538d1d1cec51616 | rhrhdhdh1/rhrhdhdh1 | /moving/이동하기.py | 959 | 3.59375 | 4 | import moveclass
lo = moveclass.Point2D(100, 100)
lo1 = moveclass.Point2D(0, 0)
atype = 2
btype = 3
Time = 0
T = 0
T2 = 0
unit0 = moveclass.Unit(lo, atype)
p = lo
unit2 = moveclass.Unit(lo1, btype)
p1 = lo1
lenge1 = moveclass.lenge1(lo, lo1)
while True:
Time += 1
print()
T += 1
T2 += 1
ctl = input('a. 0번유닛 조작 b. 1번유닛 조작 c. 둘다 조작 엔터는 통과 ')
if ctl == 'a' or ctl == 'c':
T = 0
x = int(input('x좌표'))
y = int(input('y좌표'))
p = moveclass.Point2D(x, y)
t = unit0.time(p)
if ctl == 'b' or ctl == 'c':
T2 = 0
x1= int(input('x좌표'))
y1 = int(input('y좌표'))
p1 = moveclass.Point2D(x1, y1)
t1 = unit2.time(p1)
print('0번 유닛 위치는')
unit0.move1(p, T)
print('2번유닛 위치는')
unit2.move1(p1, T2)
c = lenge1.lenge()
print(c)
|
abd16a8c5cd1d032134cdb3afd3a1cb9d8153da1 | rajat1994/LeetCode-PythonSolns | /Topics/Recursion/permutation_with_case_change.py | 324 | 3.8125 | 4 | def permutation_with_case_change (ip,op):
if ip == "":
print(op)
return
op1 = op
op2 = op
op1 = op1 + ip[0]
op2 = op2 + ip[0].upper()
ip = ip[1:]
permutation_with_case_change(ip,op1)
permutation_with_case_change(ip,op2)
permutation_with_case_change("ab", "")
|
c1fb5165232637d91f4ca68a696f9aaa850b87cd | rajat1994/LeetCode-PythonSolns | /Arrays/queue.py | 488 | 3.6875 | 4 | from collections import deque
class Queue:
def __init__ (self):
self.buffer = deque()
def enqueue(self,data):
return self.buffer.appendleft(data)
def dequeue(self):
return self.buffer.pop()
def isempty(self):
return len(self.buffer) == 0
def length(self):
return len(self.buffer)
Q = Queue()
Q.enqueue(2)
Q.enqueue(3)
Q.enqueue(4)
Q.enqueue(6)
print(Q.length())
print(Q.dequeue())
print(Q.length())
print(Q.isempty()) |
471050a9fce4fae1fde774b2be629d428499a8ae | lsieber/BestListData | /src/io/exportCSV.py | 349 | 3.5 | 4 | import csv
def exportCSV(table, filename):
with open(filename, mode='w', newline='', encoding='utf-8') as file:
test_writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in table:
#row.append(" ")
test_writer.writerow(row)
print("exported file" + filename) |
31a698480e214a38bf5954b16f0589f9516038c3 | annaprzybysz/projektFUW | /sprspr.py | 545 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
# arr = []
# for i in range(100):
# c = np.random.rand(10, 10)
# arr.append(c)
# plt.imshow(arr[45])
# plt.show()
def data_gen():
while True:
yield np.random.rand(10)
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim('1', '2', '3')
def update(data):
line.set_ydata(data)
return line,
ani = FuncAnimation(fig, update, data_gen, interval=100)
plt.show() |
5901b1fcabefe69b1ecc24f2e15ffe2d3daed18b | MaurizioAlt/ProgrammingLanguages | /Python/sample.py | 454 | 4.125 | 4 |
#input
name = input("What is your name? ")
age = input("What is your age? ")
city = input("What is your city ")
enjoy = input("What do you enjoy? ")
print("Hello " + name + ". Your age is " + age )
print("You live in " + city)
print("And you enjoy " + enjoy)
#string stuff
text = "Who dis? "
print(text*3)
#or for lists
listname.reverse
#reverse
print(text[::-1])
len(text)
#if condition:
# code...
#else if condition:
# code...
#else:
# code...
|
a3d36d9a9c98a858ed5b26cb03cb917c0e0889b3 | soni-aditya/pan-aadhar-ocr | /pan.py | 2,659 | 3.609375 | 4 | import re
import string
from processing import clean_text
def clean_gibbersh(arr):
'''
From an input array of OCR text, removes the gibberish and noise, such as,
symbols and empty strings
'''
arr = [x for x in arr if len(x) > 3]
t = 0
d = 0
for i in range(len(arr)):
if "india" in arr[i].lower():
d = i
if "income" in arr[i].lower() or "tax" in arr[i].lower():
t = i
del arr[:max([d, t])+1]
print("d= ", d, t)
print(arr)
for i in range(len(arr)):
arr[i] = arr[i].replace("!", "i")
arr[i] = clean_text(arr[i])
temp = list(arr[i])
for j in range(len(temp)):
#if not ((j >= "A" and j <= "Z") or j == " "):
# arr[i].replace(j, "")
if (temp[j] in string.punctuation) and (temp[j] not in ",/-" ):
#arr[i].replace(j, "")
temp[j] = ""
arr[i] = "".join(temp).strip()
return (arr)
def extract_pan(text_in):
'''
From the array of text, searches for the PAN number using regex
'''
try:
pan_regex = r"[A-Z]{5}[0-9]{4}[A-Z]{1}"
# pan = re.compile(pan_regex)
for i in text_in:
# print(i)
pan = re.findall(pan_regex, i)
if len(pan) > 0:
return (pan[0])
except:
print("Error in PAN Number Extraction")
def extract_dob(text_in):
'''
From the array of text, searches for the Data of Birth using regex
'''
try:
# pan = re.compile(pan_regex)
dob_regex = r"\d{1,2}\/\d{1,2}\/\d{4}"
for i in text_in:
# print(i)
dob = re.findall(dob_regex, i)
if len(dob) > 0:
return (dob[0])
except:
print("Error in DOB extraction")
def check_names(arr):
'''
From the array of text, searches for the person names using specific pattern
TODO: Improvements
'''
names = []
for i in arr:
flag = False
for j in i:
if not ((j >= "A" and j <= "Z") or j == " "):
flag = True
break
if not flag and i != "":
names.append(i)
return (names)
def get_labels_from_pan(text_in):
imp = {}
text_in = clean_gibbersh(text_in)
# print(text_in)
imp["PAN No"] = extract_pan(text_in)
imp["Date Of Birth"] = extract_dob(text_in)
names = check_names(text_in)
imp["Name"] = names[0]
try:
imp["Father's Name"] = names[1]
except:
pass
return(imp)
|
9881a1a5d57b81528b0607185ece6a930817c8ac | EastTown2000/ITGK | /Øvinger/Øving 6/lett_og_blandet.py | 352 | 3.78125 | 4 | def is_six_at_edge(liste):
return liste[0] == 6 or liste[-1] == 6
print(is_six_at_edge([1,2,3,4,5,6]))
print(is_six_at_edge([1,2,3,4,5,6,7]))
def average(liste):
return sum(liste) / len(liste)
print(average([1,3,5,7,9,11]))
def median(liste):
liste.sort()
indeks = int(len(liste) / 2)
return liste[indeks]
print(median([1,2,4,5,7,9,10])) |
e9880136681f934261cfbb6cf1ddb5bbfb541c8e | EastTown2000/ITGK | /Øvinger/Øving 6/generelt_om_lister.py | 227 | 3.59375 | 4 | my_first_list = [1, 2, 3, 4, 5, 6]
print(my_first_list)
print(len(my_first_list))
my_first_list[-2] = 'pluss'
print(my_first_list)
my_second_list = my_first_list[-3:]
print(my_second_list)
print(my_second_list, 'er lik 10') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.