blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ce4fd60b35e0e78f312eb180f35b6901f4f51a01 | naama19-meet/y2s18-python_review | /exercises/for_loops.py | 105 | 3.5 | 4 | # Write your solution for 1.1 here!
i=0
count=0
for i in range (101):
count=i+count
print(count)
|
f61362b6ec7b144e2a98b59982e656c661d234d4 | Stephon01/rpg-ddg | /Map.py | 927 | 3.5625 | 4 | # Course: CS 30
# Period: 1
# Date created: 20/01/21
# Date last modified: 20/01/21
# Name: Stephon Murray
# Description: Maps and Modules
class MapTile:
def __init__(user, x, y):
user.x = x
user.y = y
def intro_text(user):
class StartTile(MapTile):
def intro_text(user):
raise NotImplementedError("Create a subclass instead!")
class StartTile(MapTile):
def intro_text(user):
return """ stuck in the dark shadows of death, u naturally become to see in the dark """
class BoringTile(MapTile):
def intro_text(user):
return """ boring part of the krypt """
class VictoryTile(MapTile):
def intro_text(user):
return """ to the end of the hallway you see ermacs orb"""
world_map = [
[None,StartTile(1,0),None],
[None,BoringTile(1,1),None],
[None,VictoryTile(1,3),None]
]
def tile_at(x, y):
if x < 0 or y < 0:
return None
|
32828010fb54d6ccafec6ba255d1fde94a8b5ceb | ziggyman/python | /guru99if.py | 1,018 | 4.03125 | 4 | def main():
x,y = 10,8
st = 'I am a string'
if x < y:
st = 'x is smaller than y'
elif x == y:
st = 'x is equal to y'
else:
st = 'x is greater than y'
print(st)
st = ("x is less than y" if (x < y) else "x is greater than or equal to y")
print(st)
total = 100
country = "US"
#country = "AU"
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
def SwitchExample(argument):
switcher = {
0: " This is Case Zero ",
1: " This is Case One ",
2: " This is Case Two ",
}
return switcher.get(argument, "nothing")
if __name__ == '__main__':
# main()
argument = 3
print(SwitchExample(argument))
|
44fa790bf6244840c5361e194ab02bb755960cf9 | deepanshusingh1209/cuddly-disco | /PrimeNo..py | 256 | 3.984375 | 4 | num=int(input("enter a no."))
if(num>1):
for i in range (2,num):
if(num%i==0):
print(num,"is not a prime no.")
print(num,"is",num//i,"times of",i)
break
else:
print(num,"is a prime no.")
|
1f639df38b56f0fd5f7f2e02ea9bac8ed78c8dec | grigor-stoyanov/PythonFundamentals | /Functions/tribonnaci.py | 252 | 3.84375 | 4 | def tribonacci_seq(count):
a = []
result = 1
for i in range(1, count + 1):
a.append(result)
print(result)
result = sum(a)
if i > 2:
a.pop(0)
seq_length = int(input())
tribonacci_seq(seq_length)
|
5876e95bd87e1dd3da9ca57030ac4f081db87592 | Rosthouse/AdventOfCode2019 | /challenge12_part1.py | 3,330 | 3.625 | 4 | import utils
import math
def getStartPositions(path: str) -> [(int, int, int)]:
lines = path.splitlines()
planets = []
for line in lines:
positions = line.replace("<", "").replace(
">", "").replace(" ", "").split(",")
position = tuple([int(x.split("=")[-1]) for x in positions])
# position = (int(positions[0][:1]), int(
# positions[1][:1]), int(positions[2][:1]))
planets.append(position)
return planets
def calculateEnergy(positions: [(int, int, int)], velocities: [(int, int, int)]) -> None:
# Then, it might help to calculate the total energy in the system. The total energy for
# a single moon is its potential energy multiplied by its kinetic energy. A moon's potential
# energy is the sum of the absolute values of its x, y, and z position coordinates.
# A moon's kinetic energy is the sum of the absolute values of its velocity coordinates.
# Below, each line shows the calculations for a moon's potential energy (pot), kinetic energy (kin), and total energy:
potTot = 0
kinTot = 0
totEn = 0
for pos, vel in zip(positions, velocities):
pot = sum(utils.absVec(pos))
kin = sum(utils.absVec(vel))
potTot += pot
kinTot += kin
en = pot * kin
totEn += en
print(f"{pos}/{vel}: pot = {pot}, kin = {kin}, total = {en}")
print(
f"Total pot energy: {potTot}; Total kin energy: {kinTot}; Total energy: {totEn}")
def simulate(positions: [(int, int, int)], iterations) -> None:
velocities = [(0, 0, 0) for x in range(0, len(positions), 1)]
for i in range(0, iterations, 1):
print(f"Iteration {i}")
# To apply gravity, consider every pair of moons. On each axis (x, y, and z),
# the velocity of each moon changes by exactly +1 or -1 to pull the moons together.
# For example, if Ganymede has an x position of 3, and Callisto has a x position of 5,
# then Ganymede's x velocity changes by +1 (because 5 > 3) and Callisto's x velocity
# changes by -1 (because 3 < 5). However, if the positions on a given axis are the
# same, the velocity on that axis does not change for that pair of moons.
for center in range(0, len(positions), 1):
for neighbor in range(0, len(positions), 1):
diff = utils.subtract(positions[neighbor], positions[center])
signed = tuple([utils.sign(x) for x in diff])
velocities[center] = utils.add(velocities[center], signed)
for p in range(0, len(positions), 1):
positions[p] = utils.add(positions[p], velocities[p])
message = [f"Position: {positions[x]}, velocity: {velocities[x]}" for x in range(
0, len(positions), 1)]
for m in message:
print(m)
calculateEnergy(positions, velocities)
startPositions = getStartPositions("""<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>""")
print(f"Start: {startPositions}")
simulate(startPositions, 10)
startPositions = getStartPositions("""<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>""")
simulate(startPositions, 100)
startPositions = getStartPositions(open("./res/challenge12.txt").read())
simulate(startPositions, 1000)
|
df85107f949463711db8f29abecd46a483e11353 | serdarcw/python_notes | /python_exercises/Return Only the Integer(Easy).py | 938 | 4.15625 | 4 | ERROR: type should be string, got "\nhttps://edabit.com/challenge/DG2HLRqxFXxbaEDX4\n\nReturn Only the Integer\nWrite a function that takes a list of elements and returns only the integers.\n\nExamples\nreturn_only_integer([9, 2, \"space\", \"car\", \"lion\", 16]) ➞ [9, 2, 16]\n\nreturn_only_integer([\"hello\", 81, \"basketball\", 123, \"fox\"]) ➞ [81, 123]\n\nreturn_only_integer([10, \"121\", 56, 20, \"car\", 3, \"lion\"]) ➞ [10, 56, 20, 3]\n\nreturn_only_integer([\"String\", True, 3.3, 1]) ➞ [1]\n\n\ndef return_only_integer(lst):\n\treturn [i for i in lst if type(i)==int]\n\n\n\ndef return_only_integer(lst):\n\tlst2 = []\n\tfor x in lst:\n\t\tif type(x) == int:\n\t\t\tlst2.append(x)\n\treturn lst2\n\n\n\n\ndef return_only_integer(lst):\n\tnewLst = []\n\tfor i in range(len(lst)):\n\t\tif (type(lst[i]) == int):\n\t\t\tnewLst.append(lst[i])\n\treturn newLst\n\n\ndef return_only_integer(lst):\n result = []\n\n for i in range(0, len(lst)):\n if type(lst[i]) == int:\n result.append(lst[i])\n\n return result" |
d2d5d5aa231f0dbda2d086991678c54487bd794f | herbeth98/Backup- | /ALGORI/ATIVIDADE/questao2.py | 299 | 4.15625 | 4 | #2) Faça um algoritmo que seja capaz de identificar se uma letra é vogal ou consoante.
letra= str(input("Insira a letra: "))
if letra == 'a' or letra == "e" or letra == "i" or letra == "o" or letra == "u":
print("A letra é uma vogal!")
else:
print("A letra é uma consoante!") |
4a2186d1443b1dcba7bd4a02c93afe9cb55e4855 | Ustabil/Python-part-one | /mini_projects/guess_the_number/guess_the_number.py | 2,497 | 4.28125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
#Codeskulptor URL: http://www.codeskulptor.org/#user40_06oB2cbaGvb17j2.py
import simplegui
import random
current_game = 0
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
# remove this when you add your code
global secret_number
if current_game == 0:
range100()
elif current_game == 1:
range1000()
else:
print "Something bad happened..."
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
# remove this when you add your code
global secret_number
global allowed_Guesses
global current_game
current_game = 0
allowed_Guesses = 7
secret_number = random.randrange(0, 100)
print "\nGuess a number between 0 and 100, within", allowed_Guesses, "guesses!"
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
global allowed_Guesses
global current_game
current_game = 1
allowed_Guesses = 10
secret_number = random.randrange(0, 1000)
print "\nGuess a number between 0 and 1000, within", allowed_Guesses, "guesses!"
def input_guess(guess):
# main game logic goes here
global allowed_Guesses
guess = int(guess)
allowed_Guesses -= 1
# remove this when you add your code
print "\nGuess was", guess
if guess == secret_number:
print "Correct!"
new_game()
elif allowed_Guesses == 0:
print "No more guesses!"
new_game()
elif guess > secret_number:
print "Lower!"
print "Remaining guesses:", allowed_Guesses
elif guess < secret_number:
print "Higher!"
print "Remaining guesses:", allowed_Guesses
else:
print "Something weird happened o.O"
# create frame
frame = simplegui.create_frame('Guess the Number', 200, 200)
# register event handlers for control elements and start frame
button1 = frame.add_button('Range is 0 - 100', range100, 200)
button2 = frame.add_button('Range is 0 - 1000', range1000, 200)
inp = frame.add_input('Enter a guess:', input_guess, 200)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
|
ff44a147ad49553da5cb5dd96dac76b3893db7ee | Psp29/basic-python | /chapter 9/03_write.py | 418 | 4.28125 | 4 | # write mode:- it will overwrite the whole file
f = open('another.txt', 'w')
f.write("Please write this line to the file\n")
f.write("Please write this line to the file\n")
f.write("Please write this line to the file\n")
f.write("Please write this line to the file\n")
f.close
# Append mode:- It will append/add the lines at the end of the file.
# f = open('another.txt', 'a')
# f.write(" i am appending.")
# f.close
|
6a00b1430f2a660007c2d21d760322e4761a31e1 | thomasmontoya123/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 437 | 3.578125 | 4 | #!/usr/bin/python3
'''
My int module
'''
class MyInt(int):
'''
Class My int inherits from int
'''
def __init__(self, n):
'''
Constructor
'''
self.__n = n
def __eq__(self, second):
'''
changes == for !=
'''
return (self.__n != second)
def __ne__(self, second):
'''
changes != for ==
'''
return(self.__n == second)
|
597f0af7b0cfd1d41195555572ebf43d226ca9fd | anti0xidant/MIT6001 | /interdiff.py | 1,965 | 3.96875 | 4 | def dict_interdiff(d1, d2):
'''
d1, d2: dicts whose keys and values are integers
Returns a tuple of dictionaries according to the instructions above
'''
intersectD = {}
differenceD = {}
history = []
# For every element in the first dictionary:
for key in d1:
# If it exists in the other dictionary:
if key in d2:
# Calculate the intersect add it to intersect ditionary
intersect = f(d1[key], d2[key])
intersectD[key] = intersect
# Mark it as completed in history
history.append(key)
# Else (it is unique):
else:
# Add it to difference dictionary
differenceD[key] = d1[key]
# For every element in second dictionary:
for key in d2:
# If it hasn't been marked in history:
if key not in history:
# Add it to difference dictionary.
differenceD[key] = d2[key]
# Return.
return (intersectD, differenceD)
def f(a, b):
return a + b
def interdiffTest():
# case[0] = d1
# case[1] = d2
# case[2] = expected
cases = (({}, {}, ({}, {})),
({1:10}, {2:10}, ({}, {1:10, 2:10})),
({1:10}, {1:20}, ({1:30}, {})),
({}, {1:10}, ({}, {1:10})),
({1:10, 2:10, 3:10}, {1:10, 2:10, 3:10}, ({1:20, 2:20, 3:20}, {})),
({1:10, 2:10, 3:10, 4:10, 5:10}, {1:10, 2:10, 3:10, 6:10, 7:10}, ({1:20, 2:20, 3:20}, {4:10, 5:10, 6:10, 7:10})))
print 'Testing dict_interdiff()'
print 'Number of cases:', len(cases)
for i in range(len(cases)):
expected = cases[i][2]
actual = dict_interdiff(cases[i][0], cases[i][1])
if expected == actual:
result = 'Success'
else:
result = 'FAILURE'
print 'Test', i + 1, '-', result
print 'Epected:', expected
print 'Actual:', actual
print '\nEnd of tests.'
|
3a3c0e0962ee39db558d6181a60975b14378e6b0 | anmolshkl/Breaking-News-Detection-on-Twitter | /LSH/buckets.py | 2,539 | 3.828125 | 4 | import tweet
from collections import deque
import random
class Bucket:
'''
The Bucket class is an object which encapsulates a hash table.
It has methods for insertion and retrieval.
'''
hash_table = {}
def __init__(self, size):
self.size = size
def contains(self, hsh):
return hsh in self.hash_table
def getCollisions(self, hsh):
if hsh in self.hash_table:
return list(self.hash_table[hsh])
else:
return []
def insertToBck(self, hsh, tweet):
if hsh not in self.hash_table:
self.hash_table[hsh] = deque([],maxlen=self.size) #for O(1) queue operations
self.hash_table[hsh].append(tweet)
class BucketsDB:
'''
The BucketsDB class is an object which encapsulates all the different buckets
and takes care of hashing.
'''
bucket_rndm_vec = [] # stores K random vectors for every Bucket/Hash Table
bucket_list = [] # stores Bucket object/Hash Table object for every L bucket
def __init__(self, L=0, k=0, size=0):
self.L = L
self.k = k
self.size = size # queue size
for i in xrange(self.L):
random_vectors = []
for j in xrange(self.k):
random_vectors.append([])
# append random vectors
BucketsDB.bucket_rndm_vec.append(random_vectors)
# create and append new Bucket object foor L Hash Tables
BucketsDB.bucket_list.append(Bucket(self.size))
def updateRndVec(self, size):
'''
Increases the size of all the random vectors by "size"
ie no of unique words(dimensions) encountered
'''
if size <= 0:
return
for bckt in xrange(self.L):
for i in xrange(self.k):
lst = BucketsDB.bucket_rndm_vec[bckt][i]
for index in xrange(size):
lst.append(random.gauss(0.0,1.0))
def getPossibleNeighbors(self, tweet):
poss = []
r_bckt_count = 0
for bck in BucketsDB.bucket_list:
vec = tweet.getVector()
small_hash = 0
for i in xrange(self.k):
dotProd = sum([v*BucketsDB.bucket_rndm_vec[r_bckt_count][i][ky] for ky,v in vec.iteritems()])
if dotProd >= 0:
small_hash = small_hash | (1 << i)
r_bckt_count += 1
poss += bck.getCollisions(small_hash)
bck.insertToBck(small_hash, tweet)
return poss
|
5cae86ef848c8bf517afb62b32befc696ec828e8 | parralopera/prueba_def | /Declarar variables.py | 436 | 3.90625 | 4 | '''
Con esto de hacen los Comentarios
'''
for i in range(0,5)
print(i)
count: 0
while count < 5:
print(count)
count+=1
while True:
count2 = 0
while True:
if count2 == 10:
break
count2+=1
while True:
data = input("Ingresa 1 - 2")
if(data != '1' or data != '2'):
print(u"Opcion no valida")
if(data == '1' or data == '2':
break |
f5775484409c25a11d8838ba73026a072653d53a | hardcodder/OS_Scheduling_Simulator | /all.py | 21,118 | 3.5625 | 4 | from queue import Queue
import matplotlib.pyplot as plt
def swap(a , b):
return b , a
def arrange_arrival_with_priority(process_id , arrival_time , burst_time , priority):
length = len(process_id)
for i in range(length):
for j in range(length - 1):
if(priority[j] < priority[j + 1]):
arrival_time[j] , arrival_time[j + 1] = swap(arrival_time[j] , arrival_time[j + 1])
burst_time[j] , burst_time[j + 1] = swap(burst_time[j] , burst_time[j + 1])
priority[j] , priority[j + 1] = swap(priority[j] , priority[j + 1])
process_id[j] , process_id[j + 1] = swap(process_id[j] , process_id[j + 1])
return process_id , arrival_time , burst_time , priority
def arrange_arrival_with_priority1(process_id , arrival_time , burst_time , priority):
length = len(process_id)
for i in range(length):
for j in range(length - 1):
if(arrival_time[j] > arrival_time[j + 1]):
arrival_time[j] , arrival_time[j + 1] = swap(arrival_time[j] , arrival_time[j + 1])
burst_time[j] , burst_time[j + 1] = swap(burst_time[j] , burst_time[j + 1])
priority[j] , priority[j + 1] = swap(priority[j] , priority[j + 1])
process_id[j] , process_id[j + 1] = swap(process_id[j] , process_id[j + 1])
return process_id , arrival_time , burst_time , priority
#For sorting normal
def arrange_arrival(process_id , arrival_time , burst_time):
length = len(process_id)
for i in range(length):
for j in range(length - 1):
if(arrival_time[j] > arrival_time[j + 1]):
arrival_time[j] , arrival_time[j + 1] = swap(arrival_time[j] , arrival_time[j + 1])
burst_time[j] , burst_time[j + 1] = swap(burst_time[j] , burst_time[j + 1])
priority[j] , priority[j + 1] = swap(priority[j] , priority[j + 1])
return process_id , arrival_time , burst_time
#For sorting normal
def arrange_burst(process_id , arrival_time , burst_time):
length = len(process_id)
for i in range(length):
for j in range(length - 1):
if(burst_time[j] > burst_time[j + 1]):
arrival_time[j] , arrival_time[j + 1] = swap(arrival_time[j] , arrival_time[j + 1])
burst_time[j] , burst_time[j + 1] = swap(burst_time[j] , burst_time[j + 1])
process_id[j] , process_id[j + 1] = swap(process_id[j] , process_id[j + 1])
return process_id , arrival_time , burst_time
#ROUND ROBIN
def round_robin(process_id , burst_time , arrival_time , time_quantum):
curr_time = 0
length = len(process_id)
completetion_time = [0]*(length)
a_queue = Queue(maxsize=length)
id_queue = Queue(maxsize=length)
curr_a = 0
curr_id = 0
i = 0
while(i < length):
if(i == 0):
a_queue.put(burst_time[i])
id_queue.put(process_id[i])
curr_a = a_queue.get()
curr_id = id_queue.get()
curr_time = arrival_time[i]
else:
if(curr_time >= arrival_time[i]):
a_queue.put(burst_time[i])
id_queue.put(process_id[i])
else:
if(time_quantum >= curr_a):
curr_time += curr_a
curr_a = 0
completetion_time[curr_id - 1] = curr_time
if(not a_queue.empty()):
curr_a = a_queue.get()
curr_id = id_queue.get()
i -= 1
else:
curr_time += time_quantum
curr_a -= time_quantum
while(i < length and curr_time >= arrival_time[i]):
a_queue.put(burst_time[i])
id_queue.put(process_id[i])
i += 1
i -= 1
a_queue.put(curr_a)
id_queue.put(curr_id)
curr_a = a_queue.get()
curr_id = id_queue.get()
i+=1
while(not a_queue.empty()):
if(time_quantum >= curr_a):
curr_time += curr_a
completetion_time[curr_id - 1] = curr_time
if(not a_queue.empty()):
curr_a = a_queue.get()
curr_id = id_queue.get()
else:
curr_time += time_quantum
curr_a -= time_quantum
a_queue.put(curr_a)
id_queue.put(curr_id)
curr_a = a_queue.get()
curr_id = id_queue.get()
else:
curr_time += curr_a
completetion_time[curr_id - 1] = curr_time
return completetion_time
def priority_non_preemptive(process_id , arrival_time , burst_time , priority):
crr_time = 0
length = len(process_id)
completion_time = [0]*(length)
temp_process = []
temp_arrival = []
temp_priority = []
temp_burst = []
o_of_exec = []
i = 0
while(i < length):
if(i == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
crr_time = arrival_time[i]
else:
if(arrival_time[i] <= crr_time):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
else:
if(len(temp_arrival) == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
crr_time = arrival_time[i]
else:
temp_process , temp_arrival , temp_burst , temp_priority = arrange_arrival_with_priority(temp_process , temp_arrival , temp_burst , temp_priority)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
temp_priority = temp_priority[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
temp_priority = []
i-=1
i+=1
while(len(temp_arrival) > 0):
temp_process , temp_arrival , temp_burst , temp_priority = arrange_arrival_with_priority(temp_process , temp_arrival , temp_burst , temp_priority)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
temp_priority = temp_priority[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
temp_priority = []
return completion_time
#PRIORITY PRE EMPTIVE
def priority_preemptive(process_id , arrival_time , burst_time , priority):
crr_time = 0
next_time = 0
length = len(process_id)
completion_time = [0]*(length)
temp_process = []
temp_arrival = []
temp_priority = []
temp_burst = []
o_of_exec = []
i = 0
while(i < length):
if(i == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
crr_time = arrival_time[i]
if i < length - 1:
next_time = arrival_time[i + 1]
else:
if(arrival_time[i] <= crr_time):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
if i < length - 1:
next_time = arrival_time[i + 1]
else:
if(len(temp_process) == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
temp_priority.append(priority[i])
crr_time = arrival_time[i]
if i < length - 1:
next_time = arrival_time[i + 1]
else:
temp_process , temp_arrival , temp_burst , temp_priority = arrange_arrival_with_priority(temp_process , temp_arrival , temp_burst , temp_priority)
if(next_time - crr_time >= temp_burst[0]):
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
temp_priority = temp_priority[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
temp_priority = []
i-=1
else:
temp_burst[0] = temp_burst[0] - (next_time - crr_time)
crr_time = crr_time + (next_time - crr_time)
i -= 1
i += 1
while(len(temp_arrival) > 0):
temp_process , temp_arrival , temp_burst , temp_priority = arrange_arrival_with_priority(temp_process , temp_arrival , temp_burst , temp_priority)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
temp_priority = temp_priority[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
temp_priority = []
return completion_time
#FCFS
def FCFS(processes , burst_time , arrival_time):
n = len(processes)
completion_time = [0]*n
curr_time = 0
for i in range(n):
#Checking whether the process has yet arrived or not
#If not arrived , then increasing the current time to make the process arrive
if(curr_time < arrival_time[i]):
curr_time = arrival_time[i]
#now calculating the completion time
curr_time = curr_time + burst_time[i]
completion_time[processes[i] - 1] = curr_time
return completion_time
#SJF PRE EMPTIVE
def SJF_preemptive(process_id , arrival_time , burst_time):
crr_time = 0
next_time = 0
length = len(process_id)
completion_time = [0]*(length)
temp_process = []
temp_arrival = []
temp_burst = []
o_of_exec = []
i = 0
while(i < length):
if(i == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
crr_time = arrival_time[i]
if i < length - 1:
next_time = arrival_time[i + 1]
else:
if(arrival_time[i] <= crr_time):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
if i < length - 1:
next_time = arrival_time[i + 1]
else:
if(len(temp_process) == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
crr_time = arrival_time[i]
if i < length - 1:
next_time = arrival_time[i + 1]
else:
temp_process , temp_arrival , temp_burst = arrange_burst(temp_process , temp_arrival , temp_burst)
if(next_time - crr_time >= temp_burst[0]):
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
i-=1
else:
temp_burst[0] = temp_burst[0] - (next_time - crr_time)
crr_time = crr_time + (next_time - crr_time)
i -= 1
i += 1
while(len(temp_arrival) > 0):
temp_process , temp_arrival , temp_burst = arrange_burst(temp_process , temp_arrival , temp_burst)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
return completion_time
#SJF NON PRE EMPTIVE
def SJF_non_preemptive(process_id , arrival_time , burst_time):
crr_time = 0
length = len(process_id)
completion_time = [0]*(length)
temp_process = []
temp_arrival = []
temp_burst = []
o_of_exec = []
i = 0
while(i < length):
if(i == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
crr_time = arrival_time[i]
else:
if(arrival_time[i] <= crr_time):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
else:
if(len(temp_arrival) == 0):
temp_arrival.append(arrival_time[i])
temp_process.append(process_id[i])
temp_burst.append(burst_time[i])
crr_time = arrival_time[i]
else:
temp_process , temp_arrival , temp_burst = arrange_burst(temp_process , temp_arrival , temp_burst)
print(temp_process , temp_arrival , temp_burst)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
i-=1
i+=1
while(len(temp_arrival) > 0):
temp_process , temp_arrival , temp_burst = arrange_burst(temp_process , temp_arrival , temp_burst)
print(temp_process , temp_arrival , temp_burst)
#executing the first process
crr_time += temp_burst[0]
completion_time[temp_process[0] - 1] = crr_time
if(len(temp_process) > 0):
temp_process = temp_process[1:]
temp_arrival = temp_arrival[1:]
temp_burst = temp_burst[1:]
else:
temp_process = []
temp_arrival = []
temp_burst = []
return completion_time
def cal_turnaround_time(arrival_time , completion_time):
n = len(completion_time)
turnaround_time = []
for i in range(n):
turnaround_time.append(completion_time[i] - arrival_time[i])
return turnaround_time
def cal_waiting_time(turnaround_time , burst_time):
n = len(turnaround_time)
waiting_time = []
for i in range(n):
waiting_time.append(turnaround_time[i] - burst_time[i])
return waiting_time
def cal_avg_waiting_time(waiting_time):
sum = 0
for i in range(len(waiting_time)):
sum += waiting_time[i]
return sum/len(waiting_time)
def cal_avg_turnaround_time(turnaround_time):
sum = 0
for i in range(len(turnaround_time)):
sum += turnaround_time[i]
return sum/len(turnaround_time)
def plot_completion_time(processes , completion_time):
plt.plot(processes , completion_time ,color = "blue" , label = "completion time")
sum = 0
for i in range(len(completion_time)):
sum += completion_time[i]
plt.plot(processes , [len(processes)*1.0/sum]*len(processes) , color = "green" , label = "avg throughput")
plt.scatter(processes ,completion_time , color="red")
plt.ylabel("completetion time")
plt.xlabel("Process Id")
plt.title("Completion time plot")
plt.legend()
plt.show()
def plot_waiting_time(process , waiting_time , avg_waiting_time):
plt.plot(process , waiting_time ,color = "blue" , label = "waiting time")
plt.plot(process , [avg_waiting_time]*len(process) , color = "green" , label = "avg waiting time")
plt.scatter(process ,waiting_time , color="red")
plt.ylabel("Waiting time")
plt.xlabel("Process Id")
plt.title("Waiting time plot")
plt.legend()
plt.show()
def plot_turnaround_time(process , turnaround_time , avg_turnaround_time):
plt.plot(process , turnaround_time ,color = "blue" , label = "job elapsed time")
plt.plot(process , [avg_turnaround_time]*len(process) , color = "green" , label = "avg job elapsed time")
plt.scatter(process ,turnaround_time , color="red")
plt.ylabel("Job elpased time")
plt.xlabel("Process Id")
plt.title("Job elapsed time plot")
plt.legend()
plt.show()
if __name__ == "__main__":
process_id = [1 ,2 , 3 , 4 , 5 , 6]
arrival_time = [0 ,1 , 2 ,3 , 4 , 5]
burst_time = [7 , 5 , 3 , 1 , 2 , 1]
# #arranging w.r.t. arrival time
# process_id , arrival_time , burst_time , priority = arrange_arrival_with_priority1(process_id , arrival_time , burst_time , priority)
process_id , arrival_time , burst_time = arrange_arrival(process_id , arrival_time , burst_time )
completion_time = SJF_preemptive(process_id , arrival_time , burst_time)
arrival_time , process_id , burst_time = arrange_arrival(arrival_time , process_id , burst_time )
print("Process Id")
print(process_id)
print("arrival time")
print(arrival_time)
print("burst time")
print(burst_time)
print("Completion time")
print(completion_time)
plot_completion_time(process_id, completion_time)
# arrival_time , process_id , burst_time = arrange_arrival(arrival_time , process_id , burst_time )
# # #arranging w.r.t process id
# # arrival_time ,process_id , burst_time , priority = arrange_arrival_with_priority(arrival_time , process_id , burst_time , priority)
# print(process_id , burst_time , arrival_time , completion_time)
# #calculating turnaround time
# turnaround_time = cal_turnaround_time(arrival_time , completion_time)
# print(turnaround_time)
# #calculating waiting time
# waiting_time = cal_waiting_time(turnaround_time , burst_time)
# print(waiting_time)
# #calculating average waiting time
# avg_waiting_time = cal_avg_waiting_tinme(waiting_time)
# print(completion_time , turnaround_time , waiting_time , avg_waiting_time)
# plot_completion_time(process_id, completion_time) |
2d51a368eb351800e65886e76e48511aeda35398 | lomnpi/data-structures-and-algorithms-python | /DataStructures/queues.py | 726 | 3.59375 | 4 | from DataStructures.heaps import MinHeap, MaxHeap
class ArrayBasedQueue:
def __init__(self) -> None:
self.__container = []
self.__size = 0
def isEmpty(self) -> bool:
return len(self.__container) == 0
def enqueue(self, item) -> None:
self.__container.append(item)
self.__size += 1
def dequeue(self) -> object:
if self.__size > 0:
self.__size -= 1
return self.__container.pop(0)
class MinPriorityQueue(MinHeap):
def __init__(self, container=...) -> None:
super().__init__(container=container)
class MaxPriorityQueue(MaxHeap):
def __init__(self, container=...) -> None:
super().__init__(container=container)
|
b00db62c3690312980c3bb44e10a4e506779ba7f | KGC9175/Baekjoon_Algorithm | /Sorting/14593.py | 152 | 3.5625 | 4 | # 프로그래밍 경시대회
n = int(input())
lst = []
for i in range(n):
lst.append(list(map(int, input().split())))
print(lst, list(lst[0]))
|
13bd43f9289d341f1ebfe80ecd2d0f3e7addc018 | Ingvarrcoding/c-s-on-Python | /Lesson_1/3.py | 586 | 3.5 | 4 | # 3. Определить, какие из слов «attribute», «класс», «функция», «type» невозможно записать в байтовом типе.
str_1 = b'attribute'
str_2 = b'класс'
str_3 = b'функция'
str_4 = b'type'
print(str_1)
print(str_2)
print(str_3)
print(str_4)
'''
Для слов на кирилице появляется ошибка "SyntaxError: bytes can only contain ASCII literal characters."
В байтовом типе в коротком виде возможна запись только на латинице.
''' |
78e5265cfa050b6fba5ba70b75ab137ed2d1f1e5 | nehatomar12/Data-structures-and-Algorithms | /Tree/3.connect_node_level.py | 1,114 | 3.9375 | 4 | class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
self.nextRight = None
def in_order(root):
if not root:
return
in_order(root.left)
print(root.data,end=" ")
in_order(root.right)
def printLevelByLevel(root):
# print level by level
if root:
node = root
while node:
print('{}'.format(node.data), end=' ')
node = node.nextRight
print()
if root.left:
printLevelByLevel(root.left)
else:
printLevelByLevel(root.right)
def connect(root):
q = [root]
q.append(None)
while q:
node = q.pop(0)
if node:
node.nextRight = q[0]
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
elif q:
q.append(None)
root = Node(10)
root.left = Node(3)
root.right = Node(5)
root.left.left = Node(4)
root.left.right = Node(1)
root.right.right = Node(2)
connect(root)
in_order(root)
print()
printLevelByLevel(root) |
0b3f7a5f33a954125110268355bb530d9757e97f | dejac001/DataStructures | /sorting_algorithms/radix_sort.py | 2,080 | 3.90625 | 4 | """sort words alphabetically"""
class Queue:
"""First in, first out"""
def __init__(self):
self.items = []
def add(self, item):
"""add to queue"""
self.items.append(item)
def remove(self):
"""remove from queue"""
return self.items.pop(0)
def __iter__(self):
return self.items.__iter__()
def __len__(self):
return self.items.__len__()
class Stack(Queue):
"""Last in, first out"""
def __init__(self):
Queue.__init__(self)
def remove(self):
return self.items.pop(-1)
def sort(my_list: list):
my_stack = Stack()
my_stack.items = my_list
# find largest string length
largest_length = -1
for i in my_stack:
if len(i) > largest_length:
largest_length = len(i)
# i = largest_length - 1 # index for comparison; start at end
# make stacks
sum = ''
for i in my_stack:
sum += i
unique_letters_sorted = sorted(set(sum))
data = {
i: Stack() for i in unique_letters_sorted
}
data[None] = Stack() # for those with length less than i
def termination_func(lst, length):
count = 0
for i in lst:
if len(i) <= length:
count += 1
return count > 1
# termination condition: when there is 1 or less word of length i + 1
while termination_func(my_stack, largest_length):
# take from queue (my_list) to stacks
while len(my_stack) > 0:
i = my_stack.remove()
if len(i) < largest_length:
data[None].add(i)
else:
data[i[largest_length-1]].add(i)
# tack back from stacks to queue
for i in range(len(data[None])):
my_stack.add(data[None].remove())
for key in unique_letters_sorted:
for i in range(len(data[key])):
my_stack.add(data[key].remove())
largest_length -= 1
return my_stack.items
if __name__ == '__main__':
a = sort(['i', 'is', 'it', 'its'])
print(a)
|
1076f484e42a49e7b9ea3d5cfd6b03e316883c27 | GabrielGCamata/BouncyNumber | /bouncyNumber.py | 1,902 | 4 | 4 | # num = 10352
# print(num%10)
# num = num // 10
# print(num%10)
# print(" ")
# print(num%10)
# num = num // 10
# print(num%10)
# Função para ver se o numero é Saltitante
def bouncy(num):
numeroDireita = num % 10 # número mais a direita
numeroEsquerda = 0 # penultimo número mais a direita
sequenciaIncremental = 0 # flag para ver se é crescente
sequenciaDecremental = 0 # flag para ver se é decrescente
num = num //10 #já leu o numero mais a direita, pega a parte inteira da divisao
while num > 0:
numeroEsquerda = num % 10
if(numeroDireita > numeroEsquerda): # verifica se é decrescente
sequenciaIncremental = 1
if(numeroDireita < numeroEsquerda): # verifica se é crescente
sequenciaDecremental = 1
if(sequenciaIncremental and sequenciaDecremental): # se existir uma sequencia crescente e decrescente no número significa que é Bouncy Number
return 1
num = num // 10 # anda uma casa, pega a parte inteira da divisao
numeroDireita = numeroEsquerda # atualizo o mais a direita com o que era o penultimo
return 0
### testando a funcao
# if (bouncy(631) == 1):
# print("numero saltitante")
# else:
# print("numero nao é saltitante")
# if (bouncy(567) == 1):
# print("numero saltitante")
# else:
# print("numero nao é saltitante")
#### Encontra o numero que a proporcao de bouncy number é passado
def porcentagem(proporcao):
count = 0
number = 100 # inicia de 100
while count < proporcao/100 * number : # Enquanto nao chegar a porcentagem - Regra de 3
if bouncy(number):
count += 1 #conta a quantidade de BouncyNumber
if count < proporcao/100 * number :
number += 1 # incrementa o numero
return number
print(porcentagem(99))
|
5c76c6e5d35cd5da1afb40efc0659c093cc93960 | HakimKamari/Bar_Chart | /bar_chart.py | 898 | 3.90625 | 4 | # Data visualisation
#
# (C) 2020 Noorhakim bin Mohamed Kamari, Singapore, Singapore
# Released under GNU Public License (GPL)
# email: hakimkamari@outlook.com
# -----------------------------------------------------------
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv('singapore-citizens-by-ethnic-group-and-sex-end-june-annual.csv')
# I want to look only at the year 1990
df = df[df['year'] == 1990]
# I also want to look at the 3 various ethnic groups
index = ['Total Malays', 'Total Chinese', 'Total Indians']
df = df[df.level_1.isin(index)]
print(df)
# Plotting the bar chart
New_Colors = ['green','blue','purple']
plt.bar(df['level_1'], df['value'], color = New_Colors)
plt.title('1990 Ethnic Representation')
plt.xlabel('Ethnic Groups in Singapore')
plt.ylabel('Population/ Ethnic Group (in millions)')
plt.show()
|
0f4ceb4b6c113b05646cd77c8aaa2e0da0fcbcb7 | TheXDS/FizzBuzz | /src/Python/fizzbuzz.py | 164 | 3.5 | 4 | for j in range(1, 100):
o = ""
if (j % 3) == 0:
o += "Fizz"
if (j % 5) == 0:
o += "Buzz"
if o == "":
o = str(j)
print(o) |
62b6d7e90f054445160565e5b5709ba9edf20043 | sidv/Assignments | /Athira_VS/aug13/swap_case_str.py | 747 | 3.734375 | 4 | s = '''A computer is a machine that can be programmed to carry out sequences of
arithmetic or logical operations automatically. Modern computers can perform
generic sets of operations known as programs. These programs enable computers
to perform a wide range of tasks. A computer system is a complete computer
that includes the hardware operating system main software and peripheral
equipment needed and used for full operation. This term may also refer
to a group of computers that are linked and function together'''
#print(s.swapcase())
res = ""
n = len(s)
for i in range(n):
if s[i].isupper():
res = res + s[i].lower()
elif s[i].islower():
res = res + s[i].upper()
else:
res = res + s[i]
print(res) |
4fe7b9053b09924427f9ecd9fbc522381981fef3 | jumpmanhou/python-learning | /workspace/新建文件夹/Leetcode/medium/rotateImage.py | 218 | 3.65625 | 4 | '''
Created on 2016-7-9
@author: 37942
'''
class Solution(object):
def rotate(self,matrix):
return [list(col[::-1]) for col in zip(*matrix)]
s = Solution()
print (s.rotate([[1,2,3],[4,5,6],[7,8,9]])) |
15fb9c3ac0903cc9657a0e77e97514af3fbd0ee6 | EBERTONSCHIPPNIK/Pequenos-codigospy | /contaSegundos.py | 350 | 3.625 | 4 | segundos_str = input("Por favor, entre com o numero de segundos que deseja converter: ")
total_segs = int(segundos_str)
horas = total_segs // 3600
segs_restantes = total_segs % 3600
minutos = segs_restantes //60
segs_restantes_final = segs_restantes % 60
print(horas, "horas, ", minutos, "minutos e", segs_restantes_final, "segundos. ")
|
9bf9b76921041d83589d7a4019fcbeb9cf0424ef | rdasxy/programming-autograder | /problems/CS101/0009/solution.py | 96 | 3.53125 | 4 | times = int(raw_input("Type in a number."))
for k in range(1, times+1):
print(k * '*')
|
8eee53dc7ee001fe307d79dde7acb5a607cee9e1 | sarahpcw/PythonDictsJson | /cfunctions.py | 1,069 | 3.59375 | 4 | class cfunctions (): # to create class
# indent all the functions
def __init__(self, name ):
print( 'init of parent', __name__)
self.name = name
def printCompanyMessage(self): # self
print ( "Welcome to ", self.name , "! Parent Class ")
def printPersonalGreeting(self):
print ( "Hi", self.firstname, "thanks for requesting a quote!" )
def calcArea (self, l,w):
area = l*w
print ( "Area", area )
return area
def calcPrice(self, area):
carpetSQMPrice = 15.00
carpetPrice = carpetSQMPrice * area
return carpetPrice
def calcLabourPrice(self, area):
labourSQMPrice = 15.00
labourPrice = labourSQMPrice * area
return labourPrice
def calcTravelFee(self, distance):
fee =0
if distance < 10 :
fee = 0
elif distance > 10 and distance< 20 :
fee = 10
elif distance > 20 :
fee = 20
return fee |
707c3e6a1a3d7fc58e778fbf34bcfdca76f04736 | skiry/University | /Fundamentals of Programming/LC/Main/Div.py | 1,513 | 3.78125 | 4 | '''
Created on 3 dec. 2017
@author: Skiry
'''
from Main.StringToDigit import *
def division(number1, number2, base):
'''
input : 2 numbers and the base in which the division will be made
output : a string with the corresponding result
'''
finalResult = []
lenFinalResult = len(number1)
# the final result will have the lenght of the first number or less
lenFinalResult = 0
# we check if the first digit is greater than the number to divide and if so, we put the quotient on the first position
# in the result vector, otherwise we continue normally with the "carry" and a digit from the first number
try:
if strToDigit(number1[0]) >= strToDigit(number2):
finalResult.append(0)
finalResult[0] = strToDigit(number1[0]) // strToDigit(number2)
lenFinalResult = 1
carry = strToDigit(number1[0]) % strToDigit(number2)
except Exception:
print("The numbers are incorrect!")
if len(number1) > 1:
for i in range(1,len(number1)):
try:
finalResult.append(0)
finalResult[lenFinalResult] = carry * base + strToDigit(number1[i])
carry = finalResult[lenFinalResult] % strToDigit(number2)
finalResult[lenFinalResult] //= strToDigit(number2)
except Exception:
print("The numbers are incorrect!")
lenFinalResult += 1
return (finalResult,carry)
|
83b88115d68f3d221dd1d31389a5035040ea3e19 | hentimes/practica | /cadenas/numtel.py | 500 | 4.125 | 4 | # Pedir numero de telefono con prefijo + numero + ext.
# Imprimir solo numero de telefono
print ("Ingrese el numero telefonico con codigo y extension:")
c = input("Ingrese el codigo de pais: +")
n = input(f"Ingrese el numero telefonico: +{c} ")
e = input(f"Ingrese el numero de extension: +{c} {n} ")
print (f"El numero telefonico registrado es: {n}")
"""
Respuesta sugerida:
tel = input("Introduce un numero de tel con formato +xx-xxxxxxxxx-xx: ")
print ('El numero de tel es ', tel[4:-3])
"""
|
8740e6233f9d65b5a26f34c5fe5520bf825fe8a2 | kimmyoo/python_leetcode | /0.LIST AND ARRAY/414_third_maximum_number/solution.py | 693 | 3.859375 | 4 | from collections import deque
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#remember to use set to get distint elements of the input
#e.g. [1, 1, 2]
if len(set(nums)) < 3:
return max(nums)
res = []
for i in range(3):
res.append(float("-inf"))
for num in nums:
res.sort()
#remember to ignore repeating num
if num > min(res) and num not in res:
if len(res) > 2: res.pop(0)
res.append(num)
res.sort()
return res[0] |
cd799a157e43fde260a041521b23ef41037b8162 | raghubgowda/python | /beginer/phoneNumber.py | 415 | 4.25 | 4 | phoneNumber = input('Please enter your phone number in xxx-yyy-zzzz format: ')
numbers = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine",
}
converted: str = ''
for item in phoneNumber:
if item != '-':
converted += numbers.get(item) + ' '
else:
converted += item + ' '
print(converted) |
bc25a2df68c916c26515120131eeb1145ce7e130 | theGreenJedi/Path | /Python Books/Python-Network-Programming/fopnp-m/py2/chapter08/squares.py | 631 | 3.828125 | 4 | #!/usr/bin/env python
# Foundations of Python Network Programming - Chapter 8 - squares.py
# Using memcached to cache expensive results.
import memcache, random, time, timeit
mc = memcache.Client(['127.0.0.1:11211'])
def compute_square(n):
value = mc.get('sq:%d' % n)
if value is None:
time.sleep(0.001) # pretend that computing a square is expensive
value = n * n
mc.set('sq:%d' % n, value)
return value
def make_request():
compute_square(random.randint(0, 5000))
print 'Ten successive runs:',
for i in range(1, 11):
print '%.2fs' % timeit.timeit(make_request, number=2000),
print
|
6213a0721cb75bcc1c7e60c578bee26cee22bf47 | artemkondyukov/scientific_calculator | /tests/operandtest.py | 3,313 | 3.796875 | 4 | import unittest
from operand import Operand
class OperandTest(unittest.TestCase):
def test_constructor(self):
op_0 = Operand([0, 0, 0, 0, 1])
op_1 = Operand([0, 0, 0, 0])
op_2 = Operand([0, 0, 0])
op_3 = Operand([0, 0])
op_4 = Operand([0])
self.assertNotEqual(op_0, op_1)
self.assertEqual(op_1, op_2)
self.assertEqual(op_2, op_3)
self.assertEqual(op_4, op_4)
def test_add_eq_length(self):
op_1 = Operand([1, 2, 3])
op_2 = Operand([4, 5, 6])
result = Operand([5, 7, 9])
self.assertEqual(op_1 + op_2, result)
def test_add_neq_length(self):
op_1 = Operand([1, 2, 3])
op_2 = Operand([4, 5, 6, 0, 3])
result = Operand([5, 7, 9, 0, 3])
self.assertEqual(op_1 + op_2, result)
def test_add_res_zero(self):
op_1 = Operand([0, -3])
op_2 = Operand([0, 3])
result = Operand([0])
self.assertEqual(op_1 + op_2, result)
def test_sub_eq_length(self):
op_1 = Operand([1, 2, 3])
op_2 = Operand([4, 5, 6])
result = Operand([-3, -3, -3])
self.assertEqual(op_1 - op_2, result)
def test_sub_neq_length(self):
op_1 = Operand([1, 2, 3])
op_2 = Operand([4, 5, 6, 0, 3])
result = Operand([-3, -3, -3, 0, -3])
self.assertEqual(op_1 - op_2, result)
def test_sub_res_zero(self):
op_1 = Operand([0, 0, 0, 0, 3])
op_2 = Operand([0, 0, 0, 0, 3])
result = Operand([0])
self.assertEqual(op_1 - op_2, result)
def test_mul(self):
op_1 = Operand([2, 3])
op_2 = Operand([0, 4, 2])
result = Operand([0, 8, 16, 6])
self.assertEqual(op_1 * op_2, result)
def test_mul_res_zero(self):
op_1 = Operand([0])
op_2 = Operand([1, 2, 3, 4])
result = Operand([0])
self.assertEqual(op_1 * op_2, result)
def test_div_trivial(self):
op_1 = Operand([0, 3, 3])
op_2 = Operand([3])
result = Operand([0, 1, 1])
self.assertEqual(op_1 / op_2, result)
def test_div(self):
op_1 = Operand([0, 3, 3])
op_2 = Operand([3, 3])
result = Operand([0, 1])
self.assertEqual(op_1 / op_2, result)
def test_div_by_zero(self):
op_1 = Operand([1])
op_2 = Operand([0])
with self.assertRaises(ZeroDivisionError):
op_1 / op_2
def test_div_neg(self):
op_1 = Operand([1])
op_2 = Operand([0, 1])
with self.assertRaises(NotImplementedError):
op_1 / op_2
def test_log_polynomial(self):
op_1 = Operand([0, 1])
op_2 = Operand([2])
with self.assertRaises(NotImplementedError):
op_1.log(op_2)
with self.assertRaises(NotImplementedError):
op_2.log(op_1)
def test_log(self):
op_1 = Operand([2.71828])
op_2 = Operand([7.35928])
self.assertAlmostEqual(op_2.log(op_1).polynomial[0], 2, places=2)
def test_varstring(self):
op_0 = Operand([1, 2])
op_1 = Operand([1., 2.])
result = "1 + 2a"
self.assertEqual(op_0.varstring("a"), result)
self.assertEqual(op_0.varstring("a"), op_1.varstring("a"))
if __name__ == "__main__":
unittest.main()
|
dd5a0dd8a4bdfa41a7898a8dd3b620ee9f84f3dd | paulcbogdan/NFL-play-by-player | /utils.py | 1,221 | 3.53125 | 4 | import os
import pickle
def pickle_wrap(filename, callback, easy_override=False):
if os.path.isfile(filename) and not easy_override:
with open(filename, "rb") as file:
return pickle.load(file)
else:
output = callback()
with open(filename, "wb") as new_file:
pickle.dump(output, new_file)
return output
def get_date_mapping(starting_date_number):
# doesn't work. issue where it gives dates like october 0th rather than sept 30th. easy to fix but also
# doesn't account for some months being 31 days while others are 30
first_num = int(str(starting_date_number)[-1])
all_numbers = []
for wk in range(1, 16):
all_numbers.append((wk - 1) * 7 + first_num)
all_numbers.append((wk - 1) * 7 + 3 + first_num)
all_numbers.append((wk - 1) * 7 + 4 + first_num)
all_date_numbers = {}
for num in all_numbers:
day = num % 30
month = 9 + int(num / 30)
if day < 10:
date_num = str(month) + '0' + str(day)
else:
date_num = str(month) + str(day)
week = int((num - first_num) / 7) + 1
all_date_numbers[date_num] = week
return all_date_numbers
|
f51966142d57a7b7933e6162c8c4e63a5e88d0e0 | dooleys23/Data_Structures_and_Algorithms_in_Python_Goodrich | /C1/18.py | 416 | 4.34375 | 4 | '''
SD
C18 Demonstrate how to use python's list comprehension syntax to produce
[0,2,6,12,20,30,42,56,72,90]
count = 0
iteration_list = []
for x in range(0,20,2):
count = count + x
iteration_list.append(count)
print(iteration_list)
'''
# lists comprehensions can only contain expressions. count = count + 1 is an assignment (statement)
# so you cannot use it there
print[int((x*x)+x) for x in range(10)]
|
9a16fa97d8501919b46dfd30bf13878781317c20 | PaulaMihalcea/Smartyard-SY4.0 | /modules/increase_day.py | 1,146 | 3.96875 | 4 | def increase_day(date):
year = int(date[0:4])
month = int(date[5:7])
day = int(date[8:10])
if day == 28: # February check
if month == 2:
if year % 4 == 0:
day = 29
else:
month = 3
day = 1
else:
day += 1
elif day == 29: # Another February check
if month == 2:
month = 3
day = 1
else:
day += 1
elif day == 30: # Months with 30 days check
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
day = 31
else:
month = str(int(month) + 1)
day = 1
elif day == 31: # Months with 31 days check
if month == 12:
year = str(int(year) + 1)
month = 1
day = 1
else:
month += 1
day = 1
else: # Everything else (from day 1 to day 27 included)
day = str(int(day) + 1)
inc_date = str(year) + '-' + str(month).zfill(2) + '-' + str(day).zfill(2) # YYYY-MM-DD format
return inc_date
|
167d2626b21cff593de5c5f9948588babc5581ed | injun/Thinkful | /unit_2/chi_squared.py | 646 | 3.609375 | 4 | import matplotlib.pyplot as plt
from scipy import stats
import collections
import pandas as pd
# load the reduced version of the Lending Club Data
loansData = pd.read_csv('https://spark-public.s3.amazonaws.com/dataanalysis/loansData.csv')
# Clean null rows
loansData.dropna(inplace='True')
# Determine frequency (counts of observations for each number if credit lines) AND plot it
freq = collections.Counter(loansData['Open.CREDIT.Lines'])
# plt.figure()
# plt.bar(freq.keys(), freq.values(), width = 1)
# plt.show()
# Perform chi-squared test
result = stats.chisquare(freq.values())
print "chi_squared = ", result[0]
print "p > ", result[1]
|
3521d45d0be0d2823840d47845f411d9c9072519 | SachinPitale/Python3 | /Python-2020/Chapter_3/for_loop_example.py | 167 | 4 | 4 | sum = 0
for i in range(1, 11):
sum = sum + i
print(sum)
n = int(input("Enter your Number : "))
total = 0
for i in range(n + 1):
total += i
print(total)
|
fed861a56d6d6177824c4d00dd1940a963b06fff | zephyrzambrano/SSW-567-HW-04a | /HW_04a_Zephyr_Zambrano.py | 2,906 | 3.953125 | 4 | """
Homework 04a - Develop with the Perspective of the Tester in mind
Zephyr Zambrano
"""
import urllib.request
import json
def get_input(prompt):
""" Gets input from the user. Keeps asking the user for input until they enter something. """
while True: #makes sure the user enters something before going through the rest of the code
s = input(prompt)
if s == "": #handles the user pressing enter without typing text first
print("\nOops! You forgot to enter some text! Please try again.")
else:
return s
def get_repo_data(user):
""" Submits a request to the GitHub API to get the repository data from a specific
GitHub user. Parses this data and returns a list of repos for that specific user.
API Link: https://api.github.com/users/<ID>/repos
"""
beginning = "https://api.github.com/users/"
end = "/repos"
url = beginning + user + end
data = ""
try: # attempts to send a request to the API
data = urllib.request.urlopen(url).read().decode()
except ValueError as e: # request is unsuccessful
raise ValueError("Website cannot be reached. Please try again with valid input data.")
else: # parse and return data
data = json.loads(data)
repo_list = []
for item in data:
for key, value in item.items():
if key == "name":
repo_list.append(value)
return repo_list
def get_commit_data(user, repo):
""" Submits a request to the GitHub API to get the number of commits for
a repository on a specific user's GitHub account. Parses this data and
returns the number of commits in a specific repository.
API Link: https://api.github.com/repos/<ID>/<REPO>/commits
"""
beginning = "https://api.github.com/repos/"
end = "/commits"
url = beginning + user + "/" + repo + end
data = ""
try: # attempts to send a request to the API
data = urllib.request.urlopen(url).read().decode()
except ValueError as e: # request is unsuccessful
raise ValueError("Website cannot be reached. Please try again with valid input data.")
else: # parse and return data
data = json.loads(data)
return len(data)
def main():
""" Gets repository and commit data from a specific GitHub user,
and prints this data to the user. """
print("Please enter a GitHub ID: \n")
i = get_input("Enter text: ")
print()
repo_list = get_repo_data(i)
# repo_list = get_repo_data("zephyrzambrano")
# print(repo_list)
commit_dict = {}
for repo in repo_list:
commits = get_commit_data("zephyrzambrano", repo)
commit_dict[repo] = commits
# print(commit_dict)
for key, value in commit_dict.items():
print(f"Repo: {key} -> Number of commits: {value}")
if __name__ == "__main__":
main()
|
99f8e520d8471744e03c9a8088c7f16fde462b78 | 6185541513/exercism | /python/isogram/isogram.py | 139 | 3.75 | 4 | import re
def is_isogram(string):
str_alpha = re.sub('[^a-z]*', '', string.lower())
return len(str_alpha) == len(set(str_alpha))
|
bd7381050b53cb4e74b214a2695ec193216901a7 | aarizvi/bioinformatics | /algorithms-in-sequence-analysis/programming_class/transpose_abbas.py | 2,416 | 3.984375 | 4 | import sys
def read_sequence(in_file):
f = open(in_file) #opens input file
seq = f.read().rstrip().upper() #reads input file
f.close #closes input file
return seq
#make a dictionary of 3 codon nucleotides into amino acids (codon_table.txt)
def translate(input_file):
f = open(input_file) #opens codon_table.txt
codon_dict = {} #creates an empty dictionary that will translate the codons into amino acids
for l in f:
words = l.split()
codon = words[0]
letter = words[1]
codon_dict[codon] = letter
return codon_dict
def triplet(input_file):
split = [] #creates empty list to add triplets with their amino acid
x = ''
seq = open(input_file) #grabs sequence file
for i in range(seq[i:i+3]): #range from sequence from position 0 to 3 of the string
if len(seq) == 3: #ensures that if the sequence has a 3 nucleotides in a split codon
x = codon_dict[codon]
split.append(x)
return split
def find_ORFs(seq, trans_dict):
trans_list = [] #empty list that will have my translated list
for j in range(0,3): #for loop to change starting position from 0 to 3 for ORF)
ORF = seq[j:]
x = ''
translate = False
for i in range(0, len(ORF), 3):
triplet = ORF[i:i+3] #defines variable triplet three successive nucleotides
if len(triplet) == 3: #if the codon is equal to 3 nucleotides, translate it
amino_acid = trans_dict[triplet] #translates the codon sequence into amino acids
if amino_acid == 'M': #if statement to define the start codon (Met)
translate = True
elif amino_acid == '*': #if there is a stop codon (*) it will stop translation
translate = False
if translate == True:
x += amino_acid #add the amino_acids to the empty string x
trans_list.append(x) #add x to the empty list trans_list'
return trans_list
def main(seq_file,dict_file):
seq = read_sequence(seq_file)
print seq #prints the sequence
codon_dict = translate(dict_file)
codon_list = triplet(split)
print codon_list #prints the triplets of sequence and their amino acid codon pair
if __name__ == "__main__":
main(sys.argv[1],sys.argv[2]) #argument 1 is the sequence file, argument 2 is the codon_table
|
3b4ce82780d3fcf7a4f69246ab319f990dcf6658 | nskadam02/python-programs | /pattern3.py | 177 | 3.859375 | 4 | def Pattern():
num=int(input("Enter Number"));
for i in range(num):
for i in range(1,num+1):
print(i,end=" ");
print("\r");
Pattern();
|
a19f52bfcc314129f1ca6485e6ce2925bcfbd332 | dcruzp/mundialDiscreta-I | /D2TheWall/code/D2TheWall.py | 912 | 3.671875 | 4 | import sys
MOD = 10**6+3 # el modulo que es un numero primo
fact = [1] * (7* 10**5 + 10) #un array de tamano 7* 10**5 + 10 para guaradar los valores del factorial precalculado
# para calcular el factorial modulo MOD hasta la cuota superior que es 5*10^5 + 2 * 10^5
for i in range (1,len(fact)):
fact[i] = (fact[i-1] * i) % MOD
# Calcula el Coeficiente binomico modulo MOD
def Binom(n,k):
return (fact[n] * (pow (fact[n-k] , MOD -2,MOD)*pow (fact[k] , MOD -2,MOD)) % MOD)%MOD
# n-> numero total de bloques con los que se pueden armar el muro
# C-> cantidad de columnas que tiene que tener el muro a construir
def solution(n,C):
return (Binom(n+C,C)) -1 # calcular el coeficiente binomico n+c en c y restarle el caso en el que el muro no tiene bloques que es en un caso (por lo tanto se le resta 1 )
if __name__ == "__main__":
n,c = map(int,input().split())
print(solution(n,c)) |
95624e4d911fb29e8481f4ce76cfbbe1695aa79b | madeibao/PythonAlgorithm | /PartC/py验证IP地址.py | 842 | 3.53125 | 4 |
# 验证IP地址
# @param IP string字符串 一个IP地址字符串
# @return string字符串
class Solution:
def solve(self , IP ):
a=IP.strip().split(".")
b=IP.strip().split(":")
if "." in IP and len(a)<4 or len(a)>4 or "" in a:
return "Neither"
elif ":" in IP and len(b)<8 or len(b)>8 or "" in b:
return "Neither"
elif len(a)==4:
for s in a:
if int(s)>=255 or s[0]=="0":
return "Neither"
return "IPv4"
elif len(b)==8:
for s in b:
if len(s)>=2 and s[0]=="0" and s[2]=="0" or len(s)>4:
return "Neither"
return "IPv6"
if __name__ == "__main__":
s = Solution()
str2 ="2001:0db8:85a3:0:0:8A2E:0370:7334"
print(s.solve(str2))
|
4b27c8b2a74ae6affe2915f974d5e8f3ecc8d4ed | Stas-Krasnagir/word_search | /word_search.py | 1,123 | 3.6875 | 4 | class Solution:
def exist_word(self, board, word):
for i in range(len(board)):
for j in range(len(board[0])):
if self._exist_word(board, word, i, j):
return True
print(7)
return False
def _exist_word(self, board, word, i, j):
if board[i][j] == word[0]:
if not word[1:]:
return True
board[i][j] = " "
if i > 0 and self._exist_word(board, word[1:], i - 1, j): # верхний
print(1)
return True
if i < len(board) - 1 and self._exist_word(board, word[1:], i + 1, j): # нижний
print(2)
return True
if j > 0 and self._exist_word(board, word[1:], i, j - 1): # левый
print(3)
return True
if j < len(board[0]) - 1 and self._exist_word(board, word[1:], i, j + 1): # правый
print(4)
return True
print(5)
return False
else:
print(6)
return False
|
5515ac701f0f1a2155496308a20bd5d554b1fee0 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Basic - Part-I/program-43.py | 815 | 3.703125 | 4 | # !/usr/bin/env python3
#####################################################################################
# #
# Program purpose: Get OS name, platform and release information. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : August 9, 2019 #
# #
#####################################################################################
if __name__ == "__main__":
import os
import platform
print(f"Operating System name: {os.name}")
print(f"Platform name: {platform.system()}")
print(f"Release date: {platform.release()}") |
1bb0e39ee20fc2ebb0ee33d809d0332df24396fb | royqh1979/python_libs_usage | /References/Data.Analysis/TimeSeries/1-4-1-basics.py | 975 | 3.5 | 4 | # 从数据文件中导入
import pandas as pd
import matplotlib.pyplot as plt
# 读入数据
data = pd.read_csv("data\\airpassengers.csv")
# 只保留x列
data=data[["x"]]
# 添加时间索引
# index = pd.Index(sm.tsa.datetools.dates_from_range("1949m1","1960m12"))
index = pd.date_range(start='1949-01', end='1961-01', freq='M')
data.index = index
# 聚集操作,计算年均值 和 半年标准差,注意resample使用
year_mean=data.resample("Y").mean()
half_year_std = data.resample("6M").std()
print(year_mean)
print(half_year_std)
# 用matplotlib画时序图
fig = plt.figure()
ax = fig.add_subplot()
data.x.plot(ax=ax)
ax.set_ylabel("Passengers (1000's)")
#plt.show()
# 年度统计,注意resample使用
fig = plt.figure()
ax = fig.add_subplot()
data.x.resample("Y").sum().plot(ax=ax)
#plt.show()
# 按月画箱图,注意groupby使用
fig = plt.figure()
ax = fig.add_subplot()
data.groupby(lambda x:x.month).boxplot(ax=ax,subplots=False)
plt.show()
|
fc126c3388dbc5f397b3c0c1d33490bc705bb2ae | oleksa-oleksa/Python | /Data_Structures_and_Algorithms_in_Python_ud513/lesson_03_05_recursion.py | 480 | 3.8125 | 4 | def get_fib_loop(position):
if position == 0:
return 0
if position == 1:
return 1
first = 0
second = 1
nextt = first + second
i = 0
while i < position:
first = second
second = next
nextt = first + second
i += 1
return nextt
def get_fib_recursion(position):
if position == 0 or position == 1:
return position
return get_fib_recursion(position - 1) + get_fib_recursion(position - 2)
|
42c20064adf7d3d73710ccc60a842baca7425b54 | naayoung/Baekjoon | /Step/Stage 3/11721_열 개씩 끊어 출력하기.py | 960 | 3.515625 | 4 | # 문제
# 알파벳 소문자와 대문자로만 이루어진 길이가 N인 단어가 주어진다.
# 한 줄에 10글자씩 끊어서 출력하는 프로그램을 작성하시오.
# 입력
# 첫째 줄에 단어가 주어진다. 단어는 알파벳 소문자와 대문자로만 이루어져 있으며, 길이는 100을 넘지 않는다. 길이가 0인 단어는 주어지지 않는다.
# 출력
# 입력으로 주어진 단어를 열 개씩 끊어서 한 줄에 하나씩 출력한다. 단어의 길이가 10의 배수가 아닌 경우에는 마지막 줄에는 10개 미만의 글자만 출력할 수도 있다.
n = list(map(str, input('')))
count = 0
if 0 < len(n) < 100:
for i in range(len(n)):
print(n[i], end='')
count += 1
if count == 10:
print('')
count = 0
else:
print('단어길이를 0이상 100자 이하로 줄여주세요')
# 2
s = input()
while s:
print(s[:10])
s = s[10:]
|
0ebfd99bdb0f7064dc106425a70e559746542ad4 | yasinsahn/machine_learning_udemy | /coding/part2_regression/regression_models/polynomial_regression/polynomial_regression.py | 2,149 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
2021.09.12
author: yasin sahin
written for constructing polynomial regression model
"""
# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# importing the data
dataset = pd.read_csv('Position_Salaries.csv')
x = dataset.iloc[:,1:-1].values
y = dataset.iloc[:,-1].values
# training linear regression model on whole data
linear_regressor = LinearRegression()
linear_regressor.fit(x,y)
# training polynomial regression model on whole data
polynomial_transformer = PolynomialFeatures(degree=4) # creating polynomial transformer object for specified degree
x_poly = polynomial_transformer.fit_transform(x) # transform linear independent variable to polynomial
linear_regressor_2 = LinearRegression()
linear_regressor_2.fit(x_poly,y) # fit linear regression for polynomial independent variable
# plotting linear regression results
plt.scatter(x, y, color='red') # scatter plot for dataset
plt.plot(x, linear_regressor.predict(x), color='blue') # prediction plot
plt.title('Truth or Bluff (Linear Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary ($)')
plt.show()
# plotting polynomial regression results
x_grid = np.arange(min(x),max(x),0.1) # gridding array to have a smoother curve
x_grid = x_grid.reshape(len(x_grid),1) # reshaping to use in prediction
plt.scatter(x, y, color='red') # scatter plot for dataset
plt.plot(x_grid, linear_regressor_2.predict\
(polynomial_transformer.fit_transform(x_grid)), color='blue') # prediction plot
plt.title('Truth or Bluff (Polynomial Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary ($)')
plt.show()
# predicting single results with linear and polynomial regressions
linear_reg_salary_prediction = linear_regressor.predict([[6.5]]) # predicting single result for linear regression
polynomial_reg_salary_prediction =\
linear_regressor_2.predict(polynomial_transformer.fit_transform([[6.5]]))
print(linear_reg_salary_prediction)
print(polynomial_reg_salary_prediction) |
1c2f14998a57fd248f48617ddf172a3875a95e78 | abdullah-afzal/Record_Book_using_File_Handaling | /Record.py | 13,369 | 3.953125 | 4 | import string
import re
class Record:
def addRecord(self):
self.name = input("Enter Name:\t")
while self.name.strip() == "":
print("Name can not be empty :)")
self.name = input("Enter First Name:\t")
self.mobile = input("Enter Mobile number:\t")
while not(self.mobile.isdigit()):
print("Invalid mobile number")
self.mobile = input("Enter a valid mobile number:\t")
self.phone = input("Enter Landline number:\t")
while not(self.phone.isdigit()):
self.phone = input("Enter a valid phone number:\t")
self.email = input("Enter Email:\t")
emailExpression = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
while not(re.search(emailExpression,self.email)):
self.email=input("Enter a valid Email address:\t")
self.website = input("Enter Website:\t")
websiteExpression = '^[a-z0-9]+[\._]?[a-z0-9]+\w+[.]\w{2,3}$'
while not (re.search(websiteExpression, self.website)):
self.website = input("Enter a valid site address:\t")
self.city = input("Enter City:\t")
while self.city.strip() == "":
print("City name can not be empty :)")
self.city = input("Enter valid city name:\t")
self.profession = input("Enter Profession\t")
while self.profession.strip() == "":
print("Profession name can not be empty :)")
self.city = input("Enter valid Profession:\t")
fileReader = open('Addressbook.txt')
bool = 1
for line in fileReader:
if line != "\n":
part = line.split(",")
if self.mobile == part[1] or self.phone == part[2] or self.email == part[3]:
bool = 0
fileReader.close()
if bool == 0:
print("Record already exist with matching parameters")
elif bool == 1:
file = open('Addressbook.txt', 'a')
file.write(
self.name + "," + self.mobile + "," + self.phone + "," + self.email + "," + self.website + "," + self.city + "," + self.profession)
file.write("\n")
file.close()
print("-------Record Added-------")
def display(self, part):
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
print("Name = " + part[0])
print("Mobile = " + part[1])
print("Phone = " + part[2])
print("Email = " + part[3])
print("Website = " + part[4])
print("City = " + part[5])
print("Profession = " + part[6])
def searchByExactName(self, name):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if name == part[0]:
bool = 1
self.display(part)
return bool
def searchByExactMobile(self, mobile):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if mobile == part[1]:
bool = 1
self.display(part)
return bool
def searchByExactPhone(self, phone):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if phone == part[2]:
bool = 1
self.display(part)
return bool
def searchByExactEmail(self, email):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if email == part[3]:
bool = 1
self.display(part)
return bool
def searchByExactWeb(self, site):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if site == part[4]:
bool = 1
self.display(part)
return bool
def searchByExactCity(self, city):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if city == part[5]:
bool = 1
self.display(part)
return bool
def searchByExactProfession(self, profession):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if profession == part[6]:
bool = 1
self.display(part)
return bool
def searchByName(self,name):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if name in part[0]:
bool = 1
self.display(part)
return bool
def searchByMobile(self,mobile):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if mobile in part[1]:
bool = 1
self.display(part)
return bool
def searchBYphone(self,phone):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if phone in part[2]:
bool = 1
self.display(part)
return bool
def searchByEmail(self,email):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if email in part[3]:
bool = 1
self.display(part)
return bool
def searchByWeb(self,site):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if site in part[4]:
bool = 1
self.display(part)
return bool
def searchByCity(self,city):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if city in part[5]:
bool = 1
self.display(part)
return bool
def searchByProfession(self,profession):
bool = 0
fileReader = open('Addressbook.txt')
for line in fileReader:
if line != "\n":
part = line.split(",")
if profession in part[6]:
bool = 1
self.display(part)
return bool
def VIPdelete(self,name,mobile):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if name == part[0] and mobile == part[1]:
bool = 1
else:
fileReader.write(line)
return bool
def deleteAllContactByName(self,name):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if name != part[0]:
fileReader.write(line)
else:
bool = 1
return bool
def deleteAllContactByMobile(self,mobile):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if mobile != part[1]:
fileReader.write(line)
else:
bool = 1
return bool
def deleteAllContactByCity(self,city):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if city != part[5]:
fileReader.write(line)
else:
bool = 1
return bool
def updateByName(self,oname,omobile,uname):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(uname+","+part[1]+","+part[2]+","+part[3]+","+part[4]+","+part[5]+","+part[6])
else:
fileReader.write(line)
return bool
def updateByMobile(self,oname,omobile,mobile):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0] + "," + mobile + "," + part[2] + "," + part[3] + "," + part[4] + "," + part[5] + "," +part[6])
else:
fileReader.write(line)
return bool
def updateByCity(self,oname,omobile,city):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0]+ "," + part[1] + "," + part[2] + "," + part[3] + "," + part[4] + "," + city + "," +part[6])
else:
fileReader.write(line)
return bool
def updateByWeb(self,oname,omobile,web):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0] + "," + part[1] + "," + part[2] + "," + part[3] + "," + web + "," + part[5] + "," + part[6])
else:
fileReader.write(line)
return bool
def updateByEmail(self,oname,omobile,email):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0] + "," + part[1] + "," + part[2] + "," + email + "," + part[4] + "," + part[5] + "," + part[6])
else:
fileReader.write(line)
return bool
def updateByPhone(self,oname,omobile,ph):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0] + "," + part[1] + "," + ph + "," + part[3] + "," + part[4] + "," + part[5] + "," + part[6])
else:
fileReader.write(line)
return bool
def updateByProfession(self,oname,omobile,prof):
bool = 0
fileReader = open("Addressbook.txt", "r")
lines = fileReader.readlines()
fileReader = open("Addressbook.txt", "w")
for line in lines:
if line != "\n":
part = line.split(",")
if oname == part[0] and omobile == part[1]:
fileReader.write(part[0] + "," + part[1] + "," + part[2] + "," + part[3] + "," + part[4] + "," + part[5] + "," +prof)
else:
fileReader.write(line)
return bool |
459948b014f421132ced51b0d59ceb0e2cdb2f75 | HarishMusthyala1230/Python_Coding | /BruteForce_DSA.py | 844 | 4.15625 | 4 | " Python program for performing bruteforce attack on DSA"
# Function for calculating inverse
def inverse(a,q):
for i in range(1,q):
if ((a*i)%q) == 1:
inv = i
return inv
# Inputing global public values (p,q,g)
p = int(input("Enter the value of p: "))
q = int(input("Enter the value of q: "))
g = int(input("Enter the value of g: "))
r = int(input("Enter the value of r: "))
s = int(input("Enter the value of s: "))
H_M = int(input("Enter the value of H(M): "))
# For finding secret key number(k)
for i in range(1,q):
if r == (pow(g,i)%p)%q:
k = i
print("Secret key(k): ",k)
# For finding private key(x)
for n in range(1,q):
if s == (inverse(k,q)*(H_M+(n*r)))%q:
x = n
print("private Key(x): ",x)
|
41b6e41af44e171bcad5abd5e5ca894721254204 | Joboing/opencv-python | /算法刷题/动态规划/6_rob.py | 1,315 | 3.96875 | 4 | '''
打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,
影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,
如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
示例 1:
输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入: [2,7,9,3,1]
输出: 12
解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
偷窃到的最高金额 = 2 + 9 + 1 = 12 。
'''
class Solution(object):
def rob(self, nums):
l = len(nums)
if l == 0:
return 0
if l == 1:
return nums[0]
if l == 2:
return max(nums[0], nums[1])
nums[1] = max(nums[0], nums[1])
for i in range(2, l):
nums[i] = max(nums[i - 2] + nums[i], nums[i - 1])
print(nums)
return nums[len(nums) - 1]
if __name__ == '__main__':
a = Solution()
print(a.rob([2, 7, 9, 3, 1]))
|
d7cfe2e9bda3950d5029177e7cc1e626843de90b | mawaldne/projecteuler | /python/problem19.py | 585 | 3.96875 | 4 | from datetime import date
from datetime import timedelta
startDate = date(1901, 1, 1) # year, month, day
endDate = date(2000, 12, 31) # year, month, day
dayofWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
count=0;
while (startDate != endDate):
if (date.weekday(startDate) == 6 and startDate.day == 1):
count += 1;
print (date.weekday(startDate), startDate.day)
print("The day of the week on %s was a %s" % (startDate.strftime("%d%b%Y"), dayofWeek[date.weekday(startDate)]))
startDate = startDate + timedelta(days=1)
print(count); |
bb49521c740e76dbe21ffddc4146e5264217fd0f | zodang/python_practice | /high_challenge/심화문제 8.3.2.py | 481 | 3.546875 | 4 | student_tup = (('211101', '최성훈', '010-1234-4500'),('211102', '김은지', '010-2230-6540'),('211103', '이세은', '010-3232-7788'))
student_dic = {}
for i in range(len(student_tup)):
student_dic[student_tup[i][0]] = [student_tup[i][1], student_tup[i][2]]
studentNum = input("학번을 입력하시오: ")
studentName = student_dic[studentNum][0]
studentPhoneNum = student_dic[studentNum][1]
print("이름:", studentName)
print("연락처:", studentPhoneNum)
|
a79d7d5b7e33b2be8480c1170d68100c7c9a9e81 | ucookie/basic-python | /12/02_上下文管理器.py | 652 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 方法1
class OpenFile(object):
def __init__(self, filepath):
self.__file = open(filepath)
def print_line(self):
for line in self.__file:
print(line)
def __enter__(self):
return self.__file
def __exit__(self, exc_type, exc_value, traceback):
self.__file.close()
return True
a = OpenFile('file.txt')
a.print_line()
# 方法2
try:
f = open('file.txt')
for line in f:
print(line)
except Exception as e:
print(e)
finally:
f.close()
# 方法3:使用with
with open('file.txt') as fobj:
print(fobj.read()) |
109655999dec63ee7178d4090db3abb696eea60a | nvnnv/Leetcode | /612. Check If Two Expression Trees are Equivalent.py | 880 | 3.84375 | 4 | # Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
xxoo = {'a':3, 'b':22,'c':333,'d':444,'e':575,'f':606,'g':177,'h':88, 'i':99,'j':10,'k':11, 'l':102,'m':139,'n':147, 'o':315, 'p':106, 'q':717, 'r':718,'s':1019,'t':209,'u':121,'v':2020,'w':213,'x':240,'y':2345,'z':2677}
def ssum(n):
if n is None:
return 0
l = ssum(n.left)
r = ssum(n.right)
if xxoo.get(n.val) is not None:
return xxoo[n.val]
if n.val == '+':
return l+r
a = ssum(root1)
b = ssum(root2)
return a == b
|
04406ffb29308cfc14535a7b04f7f25329093bbd | abhikrish06/PythonPractice | /LC_n_Misc/lrgt_num_grt.py | 647 | 3.828125 | 4 | # Largest Number Greater Than Twice of Others
def lrgt_num_gtr(nums):
#nums.sort()
#print(nums)
max_num = max(nums)
print(max_num)
for i in range(len(nums)):
val = 2 * nums[i]
print("val: ", val)
if max_num >= val:
print("in IF")
continue
elif max_num == nums[i]:
print("in ELIF")
continue
else:
print("in Else")
return -1
return nums.index(max_num)
#print(lrgt_num_gtr([1, 3, 0, 6]))
#print(lrgt_num_gtr([1, 2, 3, 4]))
#print(lrgt_num_gtr([0, 0, 0, 1]))
print(lrgt_num_gtr([0,0,3,2])) |
b952d7fc5f8e42b0acc50cc1605699bf4113fde0 | colbyktang/cosc2316_sp19 | /Python/pandasDataFrame_csv_null.py | 305 | 3.59375 | 4 | import pandas as pd
import numpy as np
# dictionary of lists
dict = {'First Score':[100,90, np.nan, 95],
'Second Score': [30, 45, 56, np.nan],
'Third Score': [np.nan, 40, 80, 98]}
# creating a dataframe from a list
df = pd.DataFrame(dict)
# using isnull() function
print (df.isnull())
|
b1b6120e1eca6ed00f0f7ff79ea66b168059733e | balajimanikandanm/python3 | /Mergesort.py | 152 | 3.609375 | 4 | n1=int(input())
arr1=list()
for x in range(n1):
arr2=list(map(int,input().split()))
arr1=arr1+arr2
arr1=sorted(arr1)
for s in arr1:
print(s,end=" ")
|
37ed4153af029d7a7f56c09b5b7aba3a105d7a0d | ddizoya/Python | /pkg/6_8_2.py | 644 | 3.625 | 4 | __author__ = 'ddizoya'
class Cadena:
def __init__(self, str):
self.str = str
def incrustrar(self):
tam = len(self.str)
corch=""
for i in range(tam):
if i == 0:
corch = corch + "{}"
elif i==tam:
corch = corch +",'"
else:
corch = corch + ",{}"
str2 = corch.format(*self.str)
print(str2)
#Otra forma de hacerlo si el tama?o no es variable
#print('{},{},{},{}'.format(*self.str))
def main():
obj = Cadena("Cadena1");
obj.incrustrar()
if __name__ == '__main__':
main() |
ae4c5f551511aeb0751bfb572ef6b525300bdffa | with-zack/LeetCode | /python/letter-combinations-of-a-phone-number.py | 624 | 3.5 | 4 | class Solution:
def __init__(self):
self.table = {'2':'abc', '3':'def','4':'ghi','5':'jkl',
'6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
def letterCombinations(self, digits: str) -> List[str]:
result = []
for digit in digits:
if len(result)<1:
for char in self.table[digit]:
result.append(char)
else:
new = []
for string in result:
for char in self.table[digit]:
new.append(string+char)
result = new
return result
|
6998213f4bf62c3f8c520c438959d47e45ce2eb3 | YCPan-tw/DS2017FALL | /hw4/programming/r05546028.py | 2,083 | 3.546875 | 4 | import csv
import copy
#read the file,amd default name is "Input"
def readf():
f = open('Input','rt',newline='')
row = csv.reader(f, delimiter=",")
dataf = list()
for line in row:
if len(line) != 0:
dataf.append(line)
return dataf
def calculate(data):
max_value_temp = 0
min_value_temp = data[len(data)-1]
max_value = 0
min_value = data[len(data)-1]
max_loc = 0
min_loc = 0
max_loc_temp = 0
min_loc_temp = 0
diff = 0
diff_max = 0
for i in range(len(data)-1,-1,-1):
data[i] = int(data[i])
if data[i] >= max_value:
max_value_temp = data[i]
max_loc_temp = i
if data[i] <= int(min_value_temp):
min_value_temp = data[i]
min_loc_temp = i
if min_loc_temp <= max_loc_temp:
diff = data[max_loc_temp] - data[min_loc_temp]
#difference 要一直計算
if diff_max <= diff :
diff_max = copy.deepcopy(diff)
max_value = copy.deepcopy(max_value_temp)
min_value = copy.deepcopy(min_value_temp)
min_value_temp =copy.deepcopy(max_value)
max_loc = copy.deepcopy(max_loc_temp)
min_loc = copy.deepcopy(min_loc_temp)
diff = 0
max_list = [min_loc,max_loc,diff_max]
return max_list
def write_answer(answer,path='Output '):
fp = open(path,'w')
for wd in answer:
for i in range(len(wd)):
fp.write(str(wd[i]))
if i != len(wd)-1:
fp.write(',')
fp.write('\n')
fp.close()
if __name__ =="__main__":
data = readf()
answer_list=list()
for i in range(len(data)):
calculate(data[i])
answer_list.append(calculate(data[i]))
write_answer(answer_list)
|
cf10706af3f77e92d52c69ca8ccce495fa2fa81a | miklashevichaleksandr/lesson1 | /info.py | 148 | 3.640625 | 4 | user_info = {}
user_info['first_name'] = input('Enter your first name: ')
user_info['last_name'] = input('Enter your last name: ')
print(user_info) |
fe222ed4befb2f7abb175b4ad48847d3e97812d9 | tangzch/Python-Learning | /codeForPython/string_function_test.py | 138 | 3.59375 | 4 | str="hello python1"
print(str.isalnum())
print(str.isalpha())
print(str.join(str,'-'))
#print(str)
|
33498d8e585583324019c99ea2978567148395fa | finalyearProjct/math-visualisation | /GUI_Tkinter/inverse_window.py | 3,379 | 4.3125 | 4 | from tkinter import *
import inverse_transform_sampling
class Inverse_Window():
def function(self):
object = inverse_transform_sampling.ITS()
object.start()
def __init__(self):
self.window = Tk()
self.window.title("Inverse Transform Sampling")
self.window.geometry("810x600")
self.window.configure(bg="black")
self.heading = Label(self.window, text="Inverse Transform Sampling", padx=5, pady=10, font=("Helvetica 16"), bg="black", fg="cyan")
self.frame1 = LabelFrame(self.window, text="What is Inverse Sampling Transform?", font=("Helvetica 13"), padx=10, pady=10, bg="black", fg="yellow")
self.describe = Label(self.frame1, text="Inverse transform sampling (also known as Inversion Sampling) is a basic method \nfor pseudo-random number sampling, i.e., for generating sample numbers at \nrandom from any probability distribution given its cumulative distribution function. \nThe cumulative distribution for a random variable X is FX(x)=P(X≤x). ", font=("Helvetica", 11), bg="black", fg="cyan")
self.frame2 = LabelFrame(self.window, text="How is it done?", padx=5, pady=5, font=("Helvetica", 11), bg="black", fg="yellow")
self.step1 = Label(self.frame2, text="Step 1: First, independent realizations of a randow variable is generated.", font=("Helvetica", 11), bg="black", fg="cyan")
self.step2 = Label(self.frame2, text="Step 2: We are randomly choosing a proportion of the area under the curve", font=("Helvetica", 11), bg="black", fg="cyan")
self.step3 = Label(self.frame2, text="and returning the number in the domain such that exactly this proportion", font=("Helvetica", 11), bg="black", fg="cyan")
self.step4 = Label(self.frame2, text="of the area occurs to the left of that number.", font=("Helvetica", 11), bg="black", fg="cyan")
self.step5 = Label(self.frame2, text="Step 3: Intuitively, we are unlikely to choose a number in the far end ", font=("Helvetica", 11), bg="black", fg="cyan")
self.step6 = Label(self.frame2, text="of tails because there is very little area in them which would", font=("Helvetica", 11), bg="black", fg="cyan")
self.step7 = Label(self.frame2, text="require choosing a number very close to zero or one. ", font=("Helvetica", 11), bg="black", fg="cyan")
self.button = Button(self.window, text="Animate", width=13, command=self.function, pady=10, bg="black", fg="yellow", font=("Helvetica 11"))
self.heading.grid(row=0, column=0, sticky=W, pady=20, columnspan=2, padx=30)
self.frame1.grid(row=1, column=0, sticky=W, padx=30, pady=10)
self.describe.grid(row=1, column=0, sticky=W, pady=10)
self.frame2.grid(row=3, column=0, rowspan=13, columnspan=2, padx=30, pady=5, sticky=W)
self.step1.grid(row=3, column=0, sticky=W)
self.step2.grid(row=4, column=0, sticky=W)
self.step3.grid(row=5, column=0, sticky=W)
self.step4.grid(row=6, column=0, sticky=W)
self.step5.grid(row=7, column=0, sticky=W)
self.step6.grid(row=8, column=0, sticky=W)
self.step7.grid(row=9, column=0, sticky=W)
self.button.grid(row=1, column=3, padx=20, pady=10)
self.window.mainloop()
# object = Inverse_Window()
|
0aedd43fd685c050f300b29d7899c85ac6a81eaa | RobertHan96/CodeUP_BASIC100_Algorithm | /1088.py | 637 | 3.75 | 4 | # 1부터 입력한 정수까지 1씩 증가시켜 출력하는 프로그램을 작성하되,
# 3의 배수인 경우는 출력하지 않도록 만들어보자.
# 예를 들면,
# 1 2 4 5 7 8 10 11 13 14 ...
# 와 같이 출력하는 것이다.
# 참고
# 반복문 안에서 continue;가 실행되면 그 아래의 내용을 건너뛰고, 다음 반복을 수행한다.
# 즉, 다음 반복으로 넘어가는 것이다.
def skipThree():
num = int(input("1~100 사이의 정수를 입력하세요"))
i = 0
while i < num:
i += 1
if i % 3 == 0:
continue
print(i, end=" ")
skipThree()
|
6676f25be02e474cfe5c44cabf71abaf103849a1 | shaoda06/python_work | /Part_I_Basics/examples/example_5_3_3_amusement_park.py | 905 | 3.59375 | 4 | # • Admission for anyone under age 4 is free.
# • Admission for anyone between the ages of 4 and 18 is $5.
# • Admission for anyone age 18 or older is $10.
# • Admission for anyone 65 or older is $5.
age = 12
if age < 4:
print("Your admission cost is: $0.")
elif age < 18:
print("Your admission cost is: $5.")
elif age < 65:
print("Your admission cost is: $10.")
else:
print("Your admission cost is: $5.")
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is: $" + str(price) + ".")
if age < 4:
price = 0
elif age > 18 and age < 65:
price = 10
else:
price = 5
print("Your admission cost is: $" + str(price) + ".")
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is: $" + str(price) + ".")
|
a84bfe9dab2830b31c1ed6ea7aff1e50cbb96743 | joewofford/GDSIP-Week-0 | /Day2/dict_exercise.py | 1,704 | 4.21875 | 4 | def dict_to_str(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is separated by a new
line.
For example:
a: 1
b: 2
For nice pythonic code, use iteritems!
Note: it's possible to do this in 1 line using list comprehensions and the
join method.
'''
#l = []
#for item in d:
# l.append(item + ': ' + str(d[item]))
#return '\n'.join(l)
return '\n'.join(item + ': ' + str(d[item]) for item in d)
def dict_to_str_sorted(d):
'''
INPUT: dict
OUTPUT: str
Return a str containing each key and value in dict d. Keys and values are
separated by a colon and a space. Each key-value pair is sorted in ascending order by key.
This is sorted version of dict_to_str().
Note: This one is also doable in one line!
'''
l = []
for item in sorted(d):
l.append(item + ': ' + str(d[item]))
return '\n'.join(l)
def dict_difference(d1, d2):
'''
INPUT: dict, dict
OUTPUT: dict
Combine the two dictionaries, d1 and d2 as follows. The keys are the union of the keys
from each dictionary. If the keys are in both dictionaries then the values should be the
absolute value of the difference between the two values. If a value is only in one dictionary, the
value should be the absolute value of that value.
'''
for item1 in d1:
if item1 in d2:
d2[item1] = abs(d2[item1] - d1[item1])
else:
d2[item1] = abs(d1[item1])
for item in d2:
if d2[item] < 0:
d2[item] = abs(d2[item])
return d2
|
b321fd88f090fc48f85188cb3c9bd8813725c1f0 | ddanuj/machine-learning | /Assignment-1/hw1_perceptron.py | 3,584 | 3.796875 | 4 | from __future__ import division, print_function
from typing import List, Tuple, Callable
import numpy as np
import scipy
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, nb_features=2, max_iteration=10, margin=1e-4):
'''
Args :
nb_features : Number of features
max_iteration : maximum iterations. You algorithm should terminate after this
many iterations even if it is not converged
margin is the min value, we use this instead of comparing with 0 in the algorithm
'''
self.nb_features = 2
self.w = [0 for i in range(0,nb_features+1)]
self.margin = margin
self.max_iteration = max_iteration
def train(self, features: List[List[float]], labels: List[int]) -> bool:
'''
Args :
features : List of features. First element of each feature vector is 1
to account for bias
labels : label of each feature [-1,1]
Returns :
True/ False : return True if the algorithm converges else False.
'''
############################################################################
# TODO : complete this function.
# This should take a list of features and labels [-1,1] and should update
# to correct weights w. Note that w[0] is the bias term. and first term is
# expected to be 1 --- accounting for the bias
############################################################################
import math
assert len(features) == len(labels)
cnt = 0
i = 0
label = 0
while cnt < self.max_iteration:
mistakes = 0
for i in range(len(features)):
x = features[i]
value = np.matmul(np.array(self.w).T,np.array(x))
if value >= self.margin:
label = 1
else:
label = -1
if label != labels[i]:
mistakes = mistakes + 1
sum_of_sqares = 0.0
for j in x:
sum_of_sqares = sum_of_sqares + math.pow(j,2)
self.w = self.w + ((labels[i]/math.sqrt(sum_of_sqares))*np.array(x))
if mistakes == 0:
return True
cnt = cnt + 1
if cnt == self.max_iteration:
return False
def reset(self):
self.w = [0 for i in range(0,self.nb_features+1)]
def predict(self, features: List[List[float]]) -> List[int]:
'''
Args :
features : List of features. First element of each feature vector is 1
to account for bias
Returns :
labels : List of integers of [-1,1]
'''
############################################################################
# TODO : complete this function.
# This should take a list of features and labels [-1,1] and use the learned
# weights to predict the label
############################################################################
pred_labels = []
for x in features:
value = np.matmul(self.w,np.array(x).transpose())
if value >= self.margin:
pred_labels.append(1)
else:
pred_labels.append(-1)
return pred_labels
def get_weights(self) -> Tuple[List[float], float]:
return self.w
|
c1dc3c5e25419e8be50b9ae7b3f56a972446df14 | shiosakana/Grokking-Algorithm-practice | /selection_sort.py | 755 | 4.0625 | 4 | # input data
my_list = [5, 3, 6, 2, 10]
# find Maximum
# @list: the list for finding the maximum
# @return : the maximum_index in the list
def find_maximum(max_list):
maximum = max_list[0]
maximum_index = 0
for i in range(1, len(max_list)):
if maximum < max_list[i]:
maximum = max_list[i]
maximum_index = i
return maximum_index
# selection_sort ---- Des
# @sort_list: the list for sorting
# @return : the list after sorting
def selection_sort(sort_list):
result = []
length = len(sort_list)
for i in range(length):
index = find_maximum(sort_list)
result.append(sort_list[index])
del sort_list[index]
return result
# test section
print(selection_sort(my_list))
|
9b51ef463bd0c4b4a102ae46da45521ab3875a8b | teesamuel/Udacityproblemvsalgorithm | /problem_6.py | 891 | 4 | 4 | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if len(ints) < 1 :
return (-1,-1)
lowest=ints[0]
highest=ints[0]
for item in ints:
if ints[item] < lowest :
lowest = ints[item]
if ints[item] > highest:
highest = ints[item]
return (lowest,highest)
## Example Test Case
import random
l = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(l)
print ("Pass" if ((0, 9) == get_min_max(l)) else "Fail")
l = [i for i in range(0, 99)] # a list containing 0 - 98
random.shuffle(l)
print ("Pass" if ((0, 98) == get_min_max(l)) else "Fail")
l = [i for i in range(0, 80)] # a list containing 0 - 79
random.shuffle(l)
print ("Pass" if ((0, 79) == get_min_max(l)) else "Fail") |
422c3b08a658bfab6732871d8f2505f157a44d2f | ptiforka/vigenere_cipher | /main.py | 1,138 | 3.765625 | 4 | import string
symbols = string.printable
def encrypt(key, text):
result = []
space = 0
for index, ch in enumerate(text):
if ch != ' ':
mj = symbols.index(ch)
kj = symbols.index(key[(index - space) % len(key)])
cj = (mj + kj) % len(symbols)
result.append(symbols[cj])
else:
space += 1
result.append(' ')
return ''.join(result)
def decrypt(key, text):
result = []
space = 0
for index, ch in enumerate(text):
if ch != ' ':
cj = symbols.index(ch)
kj = symbols.index(key[(index - space) % len(key)])
mj = (cj - kj) % len(symbols)
result.append(symbols[mj])
else:
space += 1
result.append(' ')
return ''.join(result)
first = encrypt('klic', 'SUPER 123 tajnytext')
second = encrypt('klic', 'tajny text s mezerama')
third = encrypt('dlouhyklic', 'mega zasifrovany text')
print(f"""
{first} = {decrypt('klic', first)}
{second} = {decrypt('klic', second)}
{third} = {decrypt('dlouhyklic', third)}
""")
|
8768a60f4d6d8724793e20169cef5bc22d88fead | Vasu7052/Hands-on-Numpy | /Advanced Operations/indexing_with_boolean_arrays.py | 238 | 3.84375 | 4 | import numpy as np
a1 = np.arange(12).reshape(3,4)
a2 = a1 > 4
print(a2)
print("-------Getting only elements that are true-----------")
print(a1[a2])
print("------------Replacing true numbers by -1 -------------")
a1[a2] = -1
print(a1) |
26c5bf6f2f5c2f0f401dc130219e60e90baf42df | wjaneal/ICS3U | /WN/Python/factorial.py | 160 | 4.0625 | 4 | #Recursive function: factorial calls itself
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
for i in range(1,10):
print factorial(i)
|
c2994e6dc1e7f0a2b6e5a0d145802d442d20597e | Xtreme-89/Python-projects | /Tech Project Challenge.py | 1,607 | 3.734375 | 4 | q = open("test_qs.txt" , "r")
a = open("test_ans.txt", "r")
Ans1 = "b", "B"
Ans2 = "c", "C"
Ans3 = "a", "A"
Ans4 = "d", "D"
Ans5 = "b", "B"
score = 0
Title = "SUPER HARD GENERAL KNOWLEDGE QUIZ!\n(no seriously its so hard that you may have to use GOOGLE)"
good = "Well done, you're really smart. Now onto the next question."
bad = "Well, you're wrong. Hopefully you get something else right"
caps = "Don't use caps pls. That counts as a wrong answer because I cba to add caps to the code"
# AU(number) is the user's answers
print(Title)
print("")
print("You don't have to use capitals while answering, btw.")
print(q.read())
AU1 = str(input(""))
if AU1 == Ans1:
score += 1
print(good)
elif AU1 == "B":
score = score
print(caps)
else:
score = score
print(bad)
AU2 = str(input(""))
if AU2 == Ans2:
score += 1
print(good)
elif AU2 == "C":
score = score
print(caps)
else:
score = score
print(bad)
AU3 = str(input(""))
if AU3 == Ans3:
score += 1
print(good)
elif AU3 == "A":
score = score
print(caps)
else:
score = score
print(bad)
AU4 = str(input(""))
if AU4 == Ans4:
score += 1
print(good)
elif AU4 == "D":
score = score
print(caps)
else:
score = score
print(bad)
AU5 = str(input(""))
if AU5 == Ans5:
score += 1
print("Well done")
elif AU5 == "B":
score = score
print(caps)
else:
score = score
print("That was your last chance.")
print('''
---THE QUIZ IS OVER---''')
print("\nYour score: " + str(score) + "/5")
q.close()
a.close()
quit |
4e8c2e8ca376e570b18e17de5ebc7dadbc693e82 | aj07mm/hacking_snippets | /generate_wordlist_permutations.py | 95 | 3.875 | 4 | import itertools
for word in itertools.permutations(['a','b','c'], 3):
print ''.join(word)
|
6e3d4248ee8f060b55841776d1ffa685d980dcb7 | j3ffyang/ai | /scripts/numpy/13rotation_matrix.py | 250 | 3.5625 | 4 | # https://scipython.com/book/chapter-6-numpy/examples/creating-a-rotation-matrix-in-numpy/
import numpy as np
theta= np.radians(30)
c, s= np.cos(theta), np.sin(theta)
R= np.array(((c, -s), (s, c)))
print(R)
R= np.array([[c, -s], [s, c]])
print(R)
|
4f3274affe397aeea5eda1f3c449d4132af58417 | aleczekk/python | /divisors_of_number.py | 311 | 3.796875 | 4 | num = int(input('Enter number to devide: '))
x = list(range(1, num+1)) # convert iterable string to list
k = []
for element in x:
if num % element == 0: # if reminder num/element from list x is = 0, then append it to new list k
k.append(element) # list to store deviders
print('Dzielniki: ', k)
|
208545e1a71bddea4ea0a776abf294ceb46f4e2a | MounikaRapuru/serverclient | /arithmetic.py | 164 | 3.8125 | 4 | a,b=eval(input("Enter two values : "))
sum=a+b
sub=a-b
mul=a*b
div=a/b
print("sum is",sum)
print("sub is",sub)
print("mul is",mul)
print("divison is",div)
|
2054707afee9ec3224324588b9235ebccc4c2977 | rawgni/empireofcode | /fizz_buzz.py | 194 | 3.734375 | 4 | def fizz_buzz(number):
if number % 3 == 0 and number % 5 == 0:
return "Fizz Buzz"
if number % 3 == 0:
return "Fizz"
return "Buzz" if number % 5 == 0 else str(number)
|
ea98bb702a0b57fd8b59f9304331011106597ed3 | coco-in-bluemoon/baekjoon-online-judge | /CLASS 1/2920: 음계/solution.py | 814 | 3.859375 | 4 | def solution(notes):
start_note = notes[0]
if start_note not in [1, 8]:
return 'mixed'
status = 'ascending' if start_note == 1 else 'descending'
NUM_NOTE = 8
for index, note in enumerate(notes):
if status == 'ascending':
if note != (index + 1):
return 'mixed'
elif status == 'descending':
if note != (NUM_NOTE - index):
return 'mixed'
return status
if __name__ == "__main__":
notes = [1, 2, 3, 4, 5, 6, 7, 8]
assert solution(notes) == 'ascending'
notes = [8, 7, 6, 5, 4, 3, 2, 1]
assert solution(notes) == 'descending'
notes = [8, 1, 7, 2, 6, 3, 5, 4]
assert solution(notes) == 'mixed'
notes = list(map(int, input().split()))
answer = solution(notes)
print(answer)
|
e201c993146142ea539e3edcfd28494b640fe28e | jianhui-ben/leetcode_python | /567. Permutation in String.py | 1,204 | 3.859375 | 4 | #567. Permutation in String
#Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.
#Example 1:
#Input: s1 = "ab" s2 = "eidbaooo"
#Output: True
#Explanation: s2 contains one permutation of s1 ("ba").
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
## idea 1: order dict to store s1
## time O(n), space O(n)
stored=dict(collections.Counter(s1))
left, right= 0, 0
while right<len(s2):
if s2[right] in stored:
if stored[s2[right]]==1:
stored.pop(s2[right])
else:
stored[s2[right]]-=1
right+=1
else:
if left==right:
right+=1
elif s2[left] in stored:
stored[s2[left]]+=1
else:
stored[s2[left]]=1
left+=1
if not stored: return True
return False
## idea 2: use backtracking to get all permutations
## time O(N!)
|
bfdec504b65254edcf16566f221369a2c75ac675 | TechPuppies/leetcode-python | /subsets.py | 1,342 | 3.640625 | 4 | # coding=utf-8
# AC Rate: 27.9%
# SOURCE URL: https://oj.leetcode.com/problems/subsets/
#
#
# Given a set of distinct integers, S, return all possible subsets.
#
# Note:
#
# Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
#
#
#
# For example,
# If S = [1,2,3], a solution is:
#
#
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
#
import unittest
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
S.sort()
# return self.helper(S, 0)
# change it into bottom up
start = [[]]
for i in range(len(S))[::-1]:
res = []
for j in start:
res.append([S[i]] + j)
res.append(j)
start = res
return start
# def helper(self, S, i):
# if i >= len(S):
# return [[]]
# si1 = self.helper(S, i+1)
# # no point to dp
# return [[S[i]] + ss for ss in si1] + \
# [ss for ss in si1]
class Test(unittest.TestCase):
def test(self):
s = Solution()
self.assertEqual(s.subsets([1,2,3]),
[[1, 2, 3], [2, 3], [1, 3], [3], [1, 2], [2], [1], []])
if __name__ == '__main__':
unittest.main()
|
7c36c9b987ccda4cc01daeb96af21fdf4020de56 | maxmailman/GeekBrains | /Python2/04_SQLAlchemy/base_classic.py | 880 | 3.515625 | 4 | import sqlalchemy
from sqlalchemy import create_engine # Для соединения с СУБД используется функция create_engine()
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.orm import mapper
print("Версия SQLAlchemy:", sqlalchemy.__version__) # посмотреть версию SQLALchemy
engine = create_engine('sqlite:///mydb.sqlite', echo=True, pool_recycle=7200)
metadata = MetaData()
users_table = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('name', String(50))
)
metadata.create_all(engine)
class User:
def __init__(self, name):
self.name = name
def __repr__(self):
return "<User ('%s')>" % self.name
mapper(User, users_table)
user = User('Max')
print(user)
print(user.id) |
49298f2c581f61e6d318b2f2ec543926550fbab8 | zhugezuo/100exercises | /004.py | 996 | 3.84375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def isLeapYear(iYear):
if (iYear % 4 != 0) or (iYear % 100 == 0 and iYear % 400 != 0):
return 0
else:
return 1
iMonth = [[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
year = int(raw_input('year:\n'))
month = int(raw_input('month:\n'))
if month < 1 or month > 12:
print "输入错误!"
else:
day = int(raw_input('day:\n'))
if day < 1 or day > iMonth[isLeapYear(year)][month]:
print "输入错误!"
else:
total = 0
for x in range(month):
total += iMonth[isLeapYear(year)][x]
print total + day
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
if 0 < month <= 12:
s = months[month - 1]
else:
print 'data error'
s += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1
if (leap == 1) and (month > 2):
s += 1
print 'it is the %dth day.' % s
|
ed934223e253703151089386c915c3aca7ba6eae | Hexotical/Astr119Hw2 | /while.py | 95 | 3.71875 | 4 | i = 0
while(i<119):
print(i) #print out value of i which acts as a counter
i += 10 |
89da70f583547b8ccdd05ad5867e6c6932d33eed | aditya-doshatti/Leetcode | /climbing_stairs_70.py | 805 | 3.765625 | 4 | '''
70. Climbing Stairs
Easy
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
https://leetcode.com/problems/climbing-stairs/
'''
class Solution:
def climbStairs(self, n: int) -> int:
dic = {}
def recurse(n):
if n == 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n in dic:
return dic[n]
retVal = recurse(n-1) + recurse(n-2)
dic[n] = retVal
return retVal
return recurse(n)
|
7c2a50a2e93b2dc061b785cf8814f7b615e9160c | Hroque1987/Python_learning | /Number.py | 447 | 4.125 | 4 | largest = None
smallest = None
while True:
num=input('Enter value: ')
if num == 'done':
break
try:
num=int(num)
except:
print('Wrong Number')
continue
if largest is None:
largest=num
smallest=num
elif num > largest:
largest=num
elif num < smallest:
smallest=num
print('Largest',largest)
print('Smallest',smallest)
print('All DONE')
|
0d047e61d4eebed4f781d263badc12bfde93f522 | Eddienewpath/leetPy | /leetcode/reference/_sort/sorts_practice.py | 2,178 | 4.0625 | 4 | def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
print(arr)
def bubble_sort(arr):
for i in range(len(arr)-1, 0, -1):
for j in range(i):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
def insertion_sort(arr):
for i in range(1, len(arr)):
cur_val = arr[i]
cur_pos = i
# every thing greater than cur_val will be shift right one step
while cur_pos > 0 and arr[cur_pos-1] > cur_val:
arr[cur_pos] = arr[cur_pos-1]
cur_pos -= 1
# found the insertion pos and assign cur val to this pos.
arr[cur_pos] = cur_val
print(arr)
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
i, j = 0, 0
k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j +=1
k += 1
while i < len(left):
arr[k] = left[i]
k += 1
i += 1
while j < len(right):
arr[k] = right[j]
k += 1
j += 1
def quick_sort(arr):
def partition(arr, start, end):
par = start
pivot = arr[end]
for i in range(start, end+1):
if arr[i] <= pivot:
arr[i], arr[par] = arr[par], arr[i]
par += 1
return par - 1
def quick_sort_helper(arr, start, end):
if start >= end: return
p = partition(arr, start , end)
quick_sort_helper(arr, start, p-1)
quick_sort_helper(arr, p+1, end)
quick_sort_helper(arr, 0, len(arr)-1)
print(arr)
arr = [3,2,5,1,7,4,6]
# selection_sort(arr)
# bubble_sort(arr)
# insertion_sort(arr)
# merge_sort(arr)
# print(arr)
quick_sort(arr)
|
1522952815068e7ca8740aa7902c0bfbe1f6066b | hyejshin/AppliedDataScienceWithPythonSpecialization | /5.Applied_Social_Network_Analysis_in_Python/Assignment2.py | 7,239 | 4.40625 | 4 |
# coding: utf-8
# ---
#
# _You are currently looking at **version 1.2** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-social-network-analysis/resources/yPcBs) course resource._
#
# ---
# # Assignment 2 - Network Connectivity
#
# In this assignment you will go through the process of importing and analyzing an internal email communication network between employees of a mid-sized manufacturing company.
# Each node represents an employee and each directed edge between two nodes represents an individual email. The left node represents the sender and the right node represents the recipient.
# In[2]:
import networkx as nx
# This line must be commented out when submitting to the autograder
# !head email_network.txt
# ### Question 1
#
# Using networkx, load up the directed multigraph from `email_network.txt`. Make sure the node names are strings.
#
# *This function should return a directed multigraph networkx graph.*
# ### Question 2
#
# How many employees and emails are represented in the graph from Question 1?
#
# *This function should return a tuple (#employees, #emails).*
# In[3]:
import pandas as pd
def answer_one():
df = pd.read_csv('email_network.txt', sep='\t', header=0)
df.rename(columns={'#Sender': 'Sender'}, inplace=True)
df['Sender'] = df['Sender'].apply(str)
df['Recipient'] = df['Recipient'].apply(str)
records = df[['Sender', 'Recipient']].to_records(index=False)
result = list(records)
G = nx.MultiDiGraph()
G.add_edges_from(result)
return G
G = answer_one()
# G.edges()
# G.degree("1")
# In[4]:
def answer_two():
G = answer_one()
edgeNum = len(G.edges())
nodeNum = len(G.nodes())
return (nodeNum, edgeNum)
answer_two()
# ### Question 3
#
# * Part 1. Assume that information in this company can only be exchanged through email.
#
# When an employee sends an email to another employee, a communication channel has been created, allowing the sender to provide information to the receiver, but not vice versa.
#
# Based on the emails sent in the data, is it possible for information to go from every employee to every other employee?
#
#
# * Part 2. Now assume that a communication channel established by an email allows information to be exchanged both ways.
#
# Based on the emails sent in the data, is it possible for information to go from every employee to every other employee?
#
#
# *This function should return a tuple of bools (part1, part2).*
# In[5]:
def answer_three():
G = answer_one()
part1 = nx.is_strongly_connected(G)
part2 = nx.is_weakly_connected(G)
return (part1, part2)
answer_three()
# ### Question 4
#
# How many nodes are in the largest (in terms of nodes) weakly connected component?
#
# *This function should return an int.*
# In[6]:
def answer_four():
G = answer_one()
num =len(max(nx.weakly_connected_components(G)))
return num
answer_four()
# ### Question 5
#
# How many nodes are in the largest (in terms of nodes) strongly connected component?
#
# *This function should return an int*
# In[7]:
def answer_five():
G = answer_one()
num = len(max(nx.strongly_connected_components(G), key=len))
return num
answer_five()
# ### Question 6
#
# Using the NetworkX function strongly_connected_component_subgraphs, find the subgraph of nodes in a largest strongly connected component.
# Call this graph G_sc.
#
# *This function should return a networkx MultiDiGraph named G_sc.*
# In[8]:
def answer_six():
G = answer_one()
G_sc = max(nx.strongly_connected_component_subgraphs(G), key=len)
return G_sc
answer_six()
# ### Question 7
#
# What is the average distance between nodes in G_sc?
#
# *This function should return a float.*
# In[9]:
def answer_seven():
G_sc = answer_six()
averageDistance = nx.average_shortest_path_length(G_sc)
return averageDistance
answer_seven()
# ### Question 8
#
# What is the largest possible distance between two employees in G_sc?
#
# *This function should return an int.*
# In[10]:
def answer_eight():
G_sc = answer_six()
diameter = nx.diameter(G_sc)
return diameter
answer_eight()
# ### Question 9
#
# What is the set of nodes in G_sc with eccentricity equal to the diameter?
#
# *This function should return a set of the node(s).*
# In[11]:
def answer_nine():
G_sc = answer_six()
diameter = answer_eight()
eccentricity = nx.eccentricity(G_sc)
nodes = set()
for key in eccentricity:
if eccentricity[key] == diameter:
nodes.add(key)
return nodes
answer_nine()
# ### Question 10
#
# What is the set of node(s) in G_sc with eccentricity equal to the radius?
#
# *This function should return a set of the node(s).*
# In[12]:
def answer_ten():
G_sc = answer_six()
radius = nx.radius(G_sc)
eccentricity = nx.eccentricity(G_sc)
nodes = set()
for key in eccentricity:
if eccentricity[key] == radius:
nodes.add(key)
return nodes
answer_ten()
# ### Question 11
#
# Which node in G_sc is connected to the most other nodes by a shortest path of length equal to the diameter of G_sc?
#
# How many nodes are connected to this node?
#
#
# *This function should return a tuple (name of node, number of satisfied connected nodes).*
# In[17]:
def answer_eleven():
G_sc = answer_six()
diameter = nx.diameter(G_sc)
nodes = answer_nine()
maxCount = 0
name = '0'
for u in G_sc.nodes():
count = 0
shortestPath = nx.shortest_path(G_sc, source=u)
for v in shortestPath:
if len(shortestPath[v]) == diameter + 1:
count += 1
if maxCount < count:
maxCount = count
name = u
return (name, maxCount)
answer_eleven()
# In[51]:
def answer_twelve():
# Your Code Here
return # Your Answer Here
G = nx.DiGraph()
G.add_edge(1,2); G.add_edge(1,4)
G.add_edge(3,1); G.add_edge(3,2)
G.add_edge(3,4); G.add_edge(2,3)
G.add_edge(4,3)
print("periphery:", nx.periphery(G))
print("diameter:", nx.diameter(G))
print("all shortest paths starting at 1:",
nx.shortest_path(G, 1))
# ### Question 13
#
# Construct an undirected graph G_un using G_sc (you can ignore the attributes).
#
# *This function should return a networkx Graph.*
# In[14]:
def answer_thirteen():
G_sc = answer_six()
G_un = nx.Graph()
for u, v in G_sc.edges():
G_un.add_edge(u, v)
return G_un
G = answer_thirteen()
# len(G.edges())
# ### Question 14
#
# What is the transitivity and average clustering coefficient of graph G_un?
#
# *This function should return a tuple (transitivity, avg clustering).*
# In[15]:
def answer_fourteen():
G_un = answer_thirteen()
avgClustering = nx.average_clustering(G_un)
transitivity = nx.transitivity(G_un)
return (transitivity, avgClustering)
answer_fourteen()
# In[ ]:
|
af3243ec49eb94054b117bacfebfe00bed0591d0 | MikeKrueger75/dev101 | /lesson3/digga1_1.py | 325 | 3.828125 | 4 |
number1 = raw_input("Bitte nennen Sie eine Zahl ")
number2 = raw_input("Bitte nennen Sie eine weitere Zahl ")
if int(number1) > int(number2):
print "Die hoechste Zahl ist " + str(number1)
elif int(number1) == int(number2):
print "Die Zahlen sind gleich gross"
else:
print "Die hoechste Zahl ist " + str(number2)
|
7071f7ddd600458ef524a99c8e75e8f64100dd61 | nps1984/machine-learning | /charm/charm_professor.py | 5,859 | 3.796875 | 4 | """ This algorithm replicates the Charm algorithm
from Chapter 9 in Data Science and Machine
learning.
"""
import sys
import pandas as pd
def create_dict_from_file(filename):
""" Read in a file of itemsets
each row is considered the transaction id
and each line contains the items associated
with it.
This function returns a dictionary that
has a key set as the tid and has values
the list of items (strings)
"""
f = open(filename, 'r')
d = {}
for tids, line_items in enumerate(f):
d[tids] = [j.strip('\n') for j in line_items.split(' ')
if j != '\n']
return d
def create_database(itemset):
"Uses dummy indexing to create the binary database"
return pd.Series(itemset).str.join('|').str.get_dummies()
def create_initial_list(database):
# Returns a list of each column name with the tids it appears
base_list = []
for col in database.columns:
base_list.append(([col], list(database[database[col] == 1
].index.values)))
return base_list
def join_items(a_list, b_list):
""" This function returns the unique union of two
lists elements as a list
"""
return list(set(a_list + b_list))
def join_tids(a_list, b_list):
""" This function returns the intersection of two
sets of tids as a list
"""
return list(set(a_list).intersection(b_list))
def list_equal(a_list, b_list):
""" This function returns if the two lists of
tids are equal
"""
return (len(a_list) == len(b_list) and set(a_list) == set(b_list))
def list_contained(a_list, b_list):
# This function checks if a is contained in b
return all([element in b_list for element in a_list])
def check_closed(tup_item, closed_list):
""" Check if the tup_item (itemset,tids) meets two
conditions: if itemset isn't a subset of a
any previous closed itemset AND the tids are not
the same
"""
if not closed_list:
return True
for itemset, tids in closed_list:
if (list_contained(tup_item[0], itemset) and
list_equal(tup_item[1], tids)):
return False
return True
def find_replace_items(find_list, replace_list, ref_list):
return_list = []
for itemset, tids in ref_list:
if list_contained(find_list, itemset):
new_items = list(set(itemset + replace_list))
else:
new_items = itemset
return_list.append((new_items, tids))
return return_list
def charm(p_list, minsup, c_list):
""" This is the implementation of charm
where we are passed:
p_list: a list of (itemset, tids)
minsup: a parameter of the freq threshold
c_list: closed list of itemsets
"""
# Sort the p_list in increasing support
sorted_p_list = sorted(p_list, key = lambda
entry: len(entry[1]))
for i in range(len(sorted_p_list)):
p_temp = []
for j in range(i+1, len(sorted_p_list)):
if sorted_p_list[j] == ([],[]): pass
joined_items = join_items(sorted_p_list[i][0],
sorted_p_list[j][0])
joined_tids = join_tids(sorted_p_list[i][1],
sorted_p_list[j][1])
if len(joined_tids) >= minsup:
if list_equal(sorted_p_list[i][1],
sorted_p_list[j][1]):
sorted_p_list[j] = ([],[])
temp_items = sorted_p_list[i][0]
sorted_p_list = find_replace_items(temp_items,
joined_items,
sorted_p_list)
p_temp = find_replace_items(temp_items,
joined_items,
p_temp)
else:
if list_contained(sorted_p_list[i][1],
sorted_p_list[j][1]):
temp_items = sorted_p_list[i][0]
sorted_p_list = find_replace_items(temp_items,
joined_items,
sorted_p_list)
p_temp = find_replace_items(temp_items,
joined_items,
p_temp)
else:
p_temp.append((joined_items, joined_tids))
if p_temp:
charm(p_temp, minsup, c_list)
if check_closed(sorted_p_list[i], c_list):
c_list.append(sorted_p_list[i])
if __name__ == '__main__':
# Check if the command line arguments are given
try:
print('Filename: ', sys.argv[1])
print('Min Support: ', sys.argv[2])
except:
print('You need both a filename and minimum support value!')
minsup = int(sys.argv[2])
dict_itemset = create_dict_from_file(sys.argv[1])
database = create_database(dict_itemset)
base_item_list = create_initial_list(database)
filtered_list = [(item, tids) for item, tids in base_item_list
if len(tids) >= minsup]
closed_sets = []
# execute charm
charm(filtered_list, minsup, closed_sets)
# Sort and print. Filter out the empty set
closed_sets = sorted([(i,j) for i,j in closed_sets if i != []], key=lambda x: x[1])
for entry in closed_sets:
print(entry[0], len(entry[1])) |
a35da698f0f3d1623f9822633e1ee52e87e14f65 | andresdh/CodeFights | /Core/02_At the Crossroads/14_tennisSet.py | 1,107 | 4.21875 | 4 | # In tennis, a set is finished when one of the players wins 6 games and the other
# one wins less than 5, or, if both players win at least 5 games, until one of
# the players wins 7 games.
#
# Determine if it is possible for a tennis set to be finished with the score
# score1 : score2.
#
# Example
#
# For score1 = 3 and score2 = 6, the output should be
# tennisSet(score1, score2) = true;
#
# For score1 = 8 and score2 = 5, the output should be
# tennisSet(score1, score2) = false.
#
# Since both players won at least 5 games, the set would've ended once one of
# them won the 7th one.
#
# For score1 = 6 and score2 = 5, the output should be
# tennisSet(score1, score2) = false.
def tennisSet(score1, score2):
flg = False
maxset = [5,6]
if score1 == score2:
flg = False
else:
if score1 == 7 or score2 == 7:
if score1 in maxset or score2 in maxset:
flg = True
elif score1 == 6 or score2 == 6:
if score1 < 5 or score2 < 5:
flg = True
return flg
score1 = 7
score2 = 2
print(tennisSet(score1,score2))
|
e5c8b210aa97f6f7f7b622599db925d984b5a01a | mabdulqa/BME205 | /Assignment4/problem11.py | 5,727 | 3.78125 | 4 | #!/usr/bin/env python3
########################################################################
# File: problem11.py
# executable: problem11.py
# Purpose: Make DeBruijn graph of a string.
# stderr: errors and status
# stdout: any named out file of the users choosing.
#
# Author: Mohammad Abdulqader (mabdulqa)
#
# Notes: Problem 4 of 7 for Assignment 4
#
########################################################################
########################################################################
# Genome
########################################################################
class Genome:
'''
The goal of Genome class is to find the the DeBruijn sequence.
The following functions are used in the Genome class.
- DeBruijn: function finds the deBruijn sequnce of a given set of sequences.
- Visit: Visits all adj nodes until a contig is completed.
- buildSeq: Builds a sequence produced from Visit
- buildContigs: connects contigs that may be related.
- getGraph: returns the graph to the user.
- writeNodes: writes out the patterns of the kmers
- kmerComposition: returns the kmers in a given sequence
Classes within Genome:
- Node: produces a note to hold all k-1mers.
'''
class Node:
'''
Node class has the following duties
- Holds the data in the node.
'''
def __init__(self, kmer):
''' The information within the node. '''
self.data = kmer
@staticmethod
def buildSeq(Nodes):
''' Build the sequence from all the nodes. '''
seq = ''
seq+= Nodes[0]
for nucleotide in range(1, len(Nodes)): seq+= Nodes[nucleotide][-1:]
return seq
@staticmethod
def buildConitgs(Nodes, k):
''' Connect all possible contigs. '''
sequences = []
seq = Nodes[0]
for i in range(len(Nodes)-1):
if Nodes[i][-(k):] == Nodes[i+1][:k]:
seq+=Nodes[i+1][k:]
else:
sequences.append(seq)
seq = Node[i+1]
sequences.append(seq)
return sequences
@staticmethod
def kmerComposition(sequence, k):
''' return all kmers of size k from sequence. '''
for i in range(len(sequence) - k + 1):
kmer = sequence[i:i+k]
yield kmer
def __init__(self, sequence, k):
''' Initalize the head tail and cursor. '''
self.N = {} # dictionary with all the Nodes
self.Graph = {} # adj matrix
self.k = k
for kmer in self.kmerComposition(sequence, k):
# set up the k-1mers and thier node pointers
k1left, k1right = kmer[:-1], kmer[1:]
leftNode, rightNode = None, None
# check if k-1mer in dictionary N
if k1left in self.N: leftNode = self.N[k1left]
else: leftNode = self.N[k1left] = self.Node(k1left)
if k1right in self.N: rightNode = self.N[k1right]
else: rightNode = self.N[k1right] = self.Node(k1right)
# add to adj matrix
self.Graph.setdefault(leftNode.data, []).append(rightNode.data)
def DeBruijn(self):
''' Find the DeBruijn sequence. '''
contigs = []
refG = dict.copy(self.Graph) # to save a copy of the graph
for node in self.Graph:
if len(self.Graph[node]) > 0:
walkpath = self.Visit(node)
contigs.append(walkpath)
#contigs.append(self.buildSeq(walkpath))
self.Graph = dict.copy(refG)
return self.buildConitgs(contigs[::-1], self.k -1)
def Visit(self, node):
''' Visits all the nodes until a node with no exit is found. '''
walkpath = []
currentNode = node
walkpath.append(currentNode)
while len(self.Graph[currentNode]) > 0:
adjNode = self.Graph[currentNode].pop()
walkpath.append(adjNode)
currentNode = adjNode
return self.buildSeq(walkpath)
def getGraph(self):
''' Gives Graph G of Genome class. '''
return dict.copy(self.Graph)
def writeNodes(self):
''' write the nodes '''
nodes = []
for i in self.Graph:
kmer = i
seq = ''
length = len(self.Graph[i]) - 1
kmers = sorted(self.Graph[i])
for k in range(length): seq+= kmers[k] +","
seq+= kmers[length]
nodes.append((kmer, seq))
return nodes
########################################################################
# Usage
########################################################################
class Usage(Exception):
'''
Used to signal a Usage error, evoking a usage statement and eventual exit when raised.
'''
def __init__(self, msg):
self.msg = msg
########################################################################
# main
########################################################################
import sys
def main():
''' Return the kmer compostion. '''
try:
if sys.stdin.isatty():
raise Usage("Usage: problem12.py <infile >outfile")
# parse the file
lines = sys.stdin.readlines()
sequence = lines[1].rstrip()
k = int(lines[0].rstrip())
# call the Genome class and get the nodes
G = Genome(sequence, k)
Graph = G.writeNodes()
# print
for kmer in Graph:
print("{} -> {}".format(kmer[0],kmer[1]))
except Usage as err:
print(err.msg)
if __name__ == "__main__":
main() |
1e2f5eadd803352cef7d631f1553e26ee9a5056c | xaveng/HackerRank | /Python/UtopianTree/Solution.py | 1,621 | 4.125 | 4 | '''
Created on 2016. 1. 17.
@author: SeoJeong
'''
'''
The Utopian Tree goes through 2 cycles of growth every year. Each spring, it doubles in height. Each summer, its height increases by 1 meter.
Laura plants a Utopian Tree sapling with a height of 1 meter at the onset of spring. How tall will her tree be after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T subsequent lines each contain an integer, N, denoting the number of cycles for that test case.
Constraints
1≤T≤10
0≤N≤60
Output Format
For each test case, print the height of the Utopian Tree after N cycles. Each height must be printed on a new line.
Sample Input
3
0
1
4
Sample Output
1
2
7
Explanation
There are 3 test cases.
In the first case (N=0), the initial height (H=1) of the tree remains unchanged.
In the second case (N=1), the tree doubles in height and is 2 meters tall after the spring cycle.
In the third case (N=4), the tree doubles its height in spring (H=2), then grows a meter in summer (H=3), then doubles after the next spring (H=6), and grows another meter after summer (H=7). Thus, at the end of 4 cycles, its height is 7 meters.
'''
def spring(current):
return current * 2;
pass
def summer(current):
return current + 1;
pass
def cycle(initial, numberOfCycle):
season = [spring, summer]
for i in range(numberOfCycle):
initial = season[i % len(season)](initial)
return initial
pass
if __name__ == '__main__':
for i in range(int(input())):
print(cycle(1, int(input().strip())))
pass
pass
|
c13e20f0625b963c24b3c549660b5c1222585a94 | Azfar320/Python_Problem_Solve | /Problem1019.py | 217 | 3.90625 | 4 | #Time_Conversion
Seconds = int(input(""))
sec = (Seconds%60)
min1 =int(Seconds/60)
if min1 >= 60:
min = int(min1%60)
hrs = int(min1/60)
else:
min = min1
hrs = 0
print("%d:"%hrs+"%d:"%min+"%d"%sec)
|
8f652edde3741a6f2a1a4b72afb20034f7866249 | mccarvik/cookbook_python | /1_data_structs_algos/1_16_filter_seq.py | 1,183 | 3.625 | 4 | from itertools import compress
import math
# filtering use list comprehension
mylist = [1,4,-5,10,-7,2,3,-1]
print([n for n in mylist if n>0])
print([n for n in mylist if n<0])
# Using a generator expression
pos = (n for n in mylist if n > 0)
print(pos)
for i in pos:
print(i)
values = ['1','2','-3','-','4','N/A','5']
def is_int(val):
try:
x = int(val)
return True
except ValueError:
return False
# using the builtin filter function
ivals = list(filter(is_int,values))
print(ivals)
# manipulate the values in the list comprehension
mylist = [1,4,-5,10,-7,2,3,-1]
print([math.sqrt(n) for n in mylist if n>0])
# can replace values as well
clip_neg = [n if n>0 else 0 for n in mylist]
print(clip_neg)
clip_pos = [n if n<0 else 0 for n in mylist]
print(clip_pos)
addresses = [
'5412 N CLARK',
'5148 N CLARK',
'5800 E 58TH',
'2122 N CLARK'
'5645 N RAVENSWOOD',
'1060 W ADDISON',
'4801 N BROADWAY',
'1039 W GRANVILLE',
]
# use the compress function from itertools to map the list of bools onto the
# list of addresses
counts = [ 0, 3, 10, 4, 1, 7, 6, 1]
more5 = [n>5 for n in counts]
print(more5)
print(list(compress(addresses,more5))) |
cd449af97742e0b320d3804e315ba94117cdf355 | ammar-assaf/Assignment2 | /String-2/double_char.py | 104 | 3.625 | 4 | def double_char(str):
out = ""
for i in range(len(str)):
out += str[i] + str[i]
return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.