blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
c64ca0f36740727948fa9af6d82e8894fa8955c0 | MichalisPanayides/AmbulanceDecisionGame | /src/ambulance_game/markov/waiting.py | 18,662 | 3.90625 | 4 | """
Code to calculate the mean waiting time.
"""
import functools
import itertools
import numpy as np
from .markov import (
build_states,
get_markov_state_probabilities,
get_steady_state_algebraically,
get_transition_matrix,
)
from .utils import (
expected_time_in_markov_state_ignoring_arrivals,
is_accepting_state,
is_waiting_state,
)
@functools.lru_cache(maxsize=None)
def get_waiting_time_for_each_state_recursively(
state,
class_type,
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
):
"""Performs a recursive algorithm to get the expected waiting time of individuals
when they enter the model at a given state. Given an arriving state the algorithm
moves down to all subsequent states until it reaches one that is not a waiting
state.
Class 1:
- If (u,v) not a waiting state: return 0
- Next state s_d = (0, v - 1)
- w(u,v) = c(u,v) + w(s_d)
Class 2:
- If (u,v) not a waiting state: return 0
- Next state: s_n = (u-1, v), if u >= 1 and v=T
s_n = (u, v - 1), otherwise
- w(u,v) = c(u,v) + w(s_n)
Note: For all class 1 individuals the recursive formula acts in a linear manner
meaning that an individual will have the same waiting time when arriving at
any state of the same column e.g (2, 3) or (5, 3).
Parameters
----------
state : tuple
class_type : int
lambda_2 : float
lambda_1 : float
mu : float
num_of_servers : int
threshold : int
system_capacity : int
buffer_capacity : int
Returns
-------
float
The expected waiting time from the arriving state of an individual until
service
"""
if not is_waiting_state(state, num_of_servers):
return 0
if state[0] >= 1 and state[1] == threshold:
next_state = (state[0] - 1, state[1])
else:
next_state = (state[0], state[1] - 1)
wait = expected_time_in_markov_state_ignoring_arrivals(
state=state,
class_type=class_type,
num_of_servers=num_of_servers,
mu=mu,
threshold=threshold,
)
wait += get_waiting_time_for_each_state_recursively(
state=next_state,
class_type=class_type,
lambda_2=lambda_2,
lambda_1=lambda_1,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
return wait
def mean_waiting_time_formula_using_recursive_approach(
all_states,
pi,
class_type,
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
**kwargs, # pylint: disable=unused-argument
):
"""
Get the mean waiting time by using a recursive formula.
This function solves the following expression:
W = Σ[w(u,v) * π(u,v)] / Σ[π(u,v)] ,
where: - both summations occur over all accepting states (u,v)
- w(u,v) is the recursive waiting time of state (u,v)
- π(u,v) is the probability of being at state (u,v)
All w(u,v) terms are calculated recursively by going through the waiting
times of all previous states.
Parameters
----------
all_states : list
pi : array
class_type : int
lambda_2 : float
lambda_1 : float
mu : float
num_of_servers : int
threshold : int
system_capacity : int
buffer_capacity : int
Returns
-------
float
"""
mean_waiting_time = 0
probability_of_accepting = 0
for u, v in all_states:
if is_accepting_state(
state=(u, v),
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
):
arriving_state = (u, v + 1)
if class_type == 1 and v >= threshold:
arriving_state = (u + 1, v)
current_state_wait = get_waiting_time_for_each_state_recursively(
state=arriving_state,
class_type=class_type,
lambda_2=lambda_2,
lambda_1=lambda_1,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
mean_waiting_time += current_state_wait * pi[u, v]
probability_of_accepting += pi[u, v]
return mean_waiting_time / probability_of_accepting
def get_coefficients_row_of_array_for_state(
state, class_type, mu, num_of_servers, threshold, system_capacity, buffer_capacity
):
"""
For direct approach: Constructs a row of the coefficients matrix. The row to
be constructed corresponds to the waiting time equation for a given state
(u,v) where:
w(u,v) = 0 , if (u,v) not in WaitingStates
= c(u,v) + w(u - 1, v) , if u > 0 and v = T
= c(u,v) + w(u, v - 1) ,
i.e. the waiting time for state (u,v) is equal to:
-> the sojourn time of that state PLUS
-> the waiting time of the next state
The equations can also be written as:
-w(u,v) + w(u - 1, v) = -c(u,v)
-w(u,v) + w(u, v - 1) = -c(u,v)
where all w(u,v) are considered as unknown variables and
X = [w(1,T), ... ,w(1,N), w(2,T), ... ,w(2,N), ... , w(M,T), ... , w(M,N)]
The outputs of this function are:
- the vector M_{(u,v)} s.t. M_{(u,v)} * X = -c(u,v)
- The value of -c(u,v)
"""
lhs_coefficient_row = np.zeros([buffer_capacity + 1, system_capacity + 1])
lhs_coefficient_row[state[0], state[1]] = -1
for (u, v) in itertools.product(range(1, buffer_capacity + 1), range(threshold)):
lhs_coefficient_row[u, v] = np.NaN
rhs_value = 0
if is_waiting_state(state, num_of_servers):
if state[0] >= 1 and state[1] == threshold:
next_state = (state[0] - 1, state[1])
else:
next_state = (state[0], state[1] - 1)
lhs_coefficient_row[next_state[0], next_state[1]] = 1
rhs_value = -expected_time_in_markov_state_ignoring_arrivals(
state=state,
class_type=class_type,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
)
vectorised_array = np.hstack(
(
lhs_coefficient_row[0, :threshold],
lhs_coefficient_row[:, threshold:].flatten("F"),
)
)
return vectorised_array, rhs_value
def get_waiting_time_linear_system(
class_type, mu, num_of_servers, threshold, system_capacity, buffer_capacity
):
"""
For direct approach: Obtain the linear system M X = b by finding the array M
and the column vector b that are required. Here M is denoted as
"all_coefficients_array" and b as "constant_column".
The function stacks the outputs of get_coefficients_row_of_array_for_state()
for all states. In essence all outputs are stacked together to form a square
matrix (M) and equivalently a column vector (b) that will be used to find X
s.t. M*X=b
"""
all_coefficients_array = np.array([])
all_states = build_states(
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
for state in all_states:
lhs_vector, rhs_value = get_coefficients_row_of_array_for_state(
state=state,
class_type=class_type,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
if len(all_coefficients_array) == 0:
all_coefficients_array = [lhs_vector]
constant_column = [rhs_value]
else:
all_coefficients_array = np.vstack([all_coefficients_array, lhs_vector])
constant_column.append(rhs_value)
return all_coefficients_array, constant_column
def convert_solution_to_correct_array_format(
array, all_states, system_capacity, buffer_capacity
):
"""
For direct approach: Convert the solution into a format that matches the
state probabilities array. The given array is a one-dimensional array with
the blocking times of each state given in the following format:
[w(1,T), w(1,T+1), ... ,w(1,N), w(2,T), ... ,w(2,N), ... , w(M,T), ... , w(M,N)]
The converted array becomes:
w(0,0), w(0,1) , ... , w(0,T), ... , w(0,N)
w(1,T), ... , w(1,N)
. . .
. . .
. . .
w(M,T), ... , w(M,N)
"""
array_with_correct_shape = np.zeros([buffer_capacity + 1, system_capacity + 1])
for index, (u, v) in enumerate(all_states):
array_with_correct_shape[u, v] = array[index]
return array_with_correct_shape
def get_waiting_times_of_all_states_using_direct_approach(
class_type,
all_states,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
):
"""
For direct approach: Solve M*X = b using numpy.linalg.solve() where:
M = The array containing the coefficients of all w(u,v) equations
b = Vector of constants of equations
X = All w(u,v) variables of the equations
"""
M, b = get_waiting_time_linear_system(
class_type=class_type,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
state_waiting_times = np.linalg.solve(M, b)
state_waiting_times = convert_solution_to_correct_array_format(
array=state_waiting_times,
all_states=all_states,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
return state_waiting_times
def mean_waiting_time_formula_using_direct_approach(
all_states,
pi,
class_type,
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
**kwargs, # pylint: disable=unused-argument
):
"""
Get the mean waiting time by using a direct approach.
"""
waiting_times = get_waiting_times_of_all_states_using_direct_approach(
class_type=class_type,
all_states=all_states,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
mean_waiting_time, prob_accept_class_2_ind = 0, 0
for (u, v) in all_states:
if is_accepting_state(
state=(u, v),
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
):
arriving_state = (u, v + 1)
if class_type == 1 and v >= threshold:
arriving_state = (u + 1, v)
mean_waiting_time += waiting_times[arriving_state] * pi[u, v]
prob_accept_class_2_ind += pi[u, v]
return mean_waiting_time / prob_accept_class_2_ind
def mean_waiting_time_formula_using_closed_form_approach(
all_states,
pi,
class_type,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
**kwargs, # pylint: disable=unused-argument
):
"""
Get the mean waiting time by using a closed-form formula.
Parameters
----------
all_states : list
pi : array
class_type : int
mu : float
num_of_servers : int
threshold : int
system_capacity : int
buffer_capacity : int
Returns
-------
float
"""
sojourn_time = 1 / (num_of_servers * mu)
if class_type == 0:
mean_waiting_time = np.sum(
[
(state[1] - num_of_servers + 1) * pi[state] * sojourn_time
for state in all_states
if is_accepting_state(
state=state,
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
and state[1] >= num_of_servers
]
) / np.sum(
[
pi[state]
for state in all_states
if is_accepting_state(
state=state,
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
]
)
# TODO: Break function into 2 functions
if class_type == 1:
mean_waiting_time = np.sum(
[
(min(state[1] + 1, threshold) - num_of_servers)
* pi[state]
* sojourn_time
for state in all_states
if is_accepting_state(
state=state,
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
and min(state[1], threshold) >= num_of_servers
]
) / np.sum(
[
pi[state]
for state in all_states
if is_accepting_state(
state=state,
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
]
)
return mean_waiting_time
def overall_waiting_time_formula(
all_states,
pi,
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
waiting_formula,
**kwargs, # pylint: disable=unused-argument
):
"""
Gets the overall waiting time for all individuals by calculating both class 1
and class 2 waiting times. Thus, considering the probability that an individual
is lost to the system (for both classes) calculates the overall waiting time.
Parameters
----------
all_states : list
pi : array
lambda_1 : float
lambda_2 : float
mu : float
num_of_servers : int
threshold : int
system_capacity : int
buffer_capacity : int
waiting_formula : function
Returns
-------
float
The overall mean waiting time by combining class 1 and class 2 individuals
"""
mean_waiting_times_for_each_class = [
waiting_formula(
all_states=all_states,
pi=pi,
class_type=class_type,
lambda_2=lambda_2,
lambda_1=lambda_1,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
for class_type in range(2)
]
prob_accept = [
np.sum(
[
pi[state]
for state in all_states
if is_accepting_state(
state=state,
class_type=class_type,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
]
)
for class_type in range(2)
]
class_rates = [
prob_accept[class_type]
/ ((lambda_2 * prob_accept[1]) + (lambda_1 * prob_accept[0]))
for class_type in range(2)
]
class_rates[0] *= lambda_1
class_rates[1] *= lambda_2
mean_waiting_time = np.sum(
[
mean_waiting_times_for_each_class[class_type] * class_rates[class_type]
for class_type in range(2)
]
)
return mean_waiting_time
def get_mean_waiting_time_using_markov_state_probabilities(
lambda_2,
lambda_1,
mu,
num_of_servers,
threshold,
system_capacity,
buffer_capacity,
class_type=None,
waiting_formula=mean_waiting_time_formula_using_closed_form_approach,
):
"""
Gets the mean waiting time by using either the recursive formula,
closed-form formula or the direct approach. This function solves the
following expression:
W = Σ[w(u,v) * π(u,v)] / Σ[π(u,v)] ,
where: - both summations occur over all accepting states (u,v)
- w(u,v) is the recursive waiting time of state (u,v)
- π(u,v) is the probability of being at state (u,v)
All three formulas aim to solve the same expression by using different
approaches to calculate the terms w(u,v).
Parameters
----------
lambda_2 : float
lambda_1 : float
mu : float
num_of_servers : int
threshold : int
system_capacity : int
buffer_capacity : int
class_type : int, optional
formula : str, optional
Returns
-------
float
The mean waiting time in the system of either class 1,
class 2 individuals or the overall of both
"""
transition_matrix = get_transition_matrix(
lambda_2=lambda_2,
lambda_1=lambda_1,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
all_states = build_states(
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
)
pi = get_steady_state_algebraically(
Q=transition_matrix, algebraic_function=np.linalg.solve
)
pi = get_markov_state_probabilities(pi=pi, all_states=all_states, output=np.ndarray)
if class_type is None:
get_mean_waiting_time = overall_waiting_time_formula
else:
get_mean_waiting_time = waiting_formula
mean_waiting_time = get_mean_waiting_time(
all_states=all_states,
pi=pi,
class_type=class_type,
lambda_2=lambda_2,
lambda_1=lambda_1,
mu=mu,
num_of_servers=num_of_servers,
threshold=threshold,
system_capacity=system_capacity,
buffer_capacity=buffer_capacity,
waiting_formula=waiting_formula,
)
return mean_waiting_time
|
d05e8125d47e32945a7a29c5cf6a13a3c6f44247 | shmink/Waypointer | /phantom3.py | 3,626 | 3.515625 | 4 | #!/usr/bin/python
"""
Take the csv file created and then take legitimate waypoints and plot
them on google maps using their api.
@auther: Tom Nicklin
"""
import csv
import simplemap
import webbrowser
csvfile = 'FLY015.csv'
def get_coordinates(file):
with open(file, 'rb') as csvfile:
# printing specifics
readmorelikecashmore = csv.DictReader(csvfile)
coordinates = [ [ row['Latitude'], row['Longitude'] ] for row in readmorelikecashmore]
# When we get the gps coordinates, some of them are 500. That doesn't exist on maps, as a result gmaps just doesn't function.
# Here we santise (ignore) those results.
sanitised = []
for x in range(0, len(coordinates)):
# When phantom 3 powers up and doesn't have a gps lock it leaves the cells empty in csv file.
# google maps assumes this to 0,0 so we have incorrect waypoints added to map.
# The if statments makes it so we check if the cell is empty or not, if not add it to the list of points.
if((coordinates[x][0] or coordinates[x][1]) != ''):
sanitised.append(coordinates[x])
# Finally we return the result.
return sanitised
# Here we change the formatting of the waypoints so gmaps api can use them to plot lines
def make_points(coords):
if(coords):
# Firstly we don't need the way point number in this as we already have our waypoints in order.
for x in range(0, len(coords)):
if(len(coords[x]) > 2):
coords[x].pop(0)
# List comprehensions are fun. Basically telling it the format I want and then it has its
# own little for loop and then changes all elements. It's more obvious when you look at
# var points in a generated html file.
new_list = [{'lat': float(d[0]), 'lng': float(d[1])} for d in coords]
# Return the new list after the list comprehension.
return new_list
##################################################
# #
# Create html using the following: #
# #
##################################################
# Map title is the text in the tab on whatever browser
map_title = csvfile
# This gets the coordinates from the above function
gps_markers = get_coordinates(csvfile)
# We need a clone of gps_markers because python assigns by reference.
# In short it means if you change the copy you'll ALSO change the original. Not good.
# On top of that gps_markers is a 2D list so it requires a bit more thought.
new_gps = [sublist[:] for sublist in gps_markers]
# Due to there being so many waypoints generated from the dat file it's easier to only keep
# the first and last waypoint and then identify which is which with hover text.
# The rest of the flight will just be a line of where the drone went.
gps_markers[0].insert(0, 'Start')
gps_markers[-1].insert(0, 'End')
gps_markers = [ gps_markers[0], gps_markers[-1] ]
# Use said copy to do something different without effecting the original.
plots = make_points(new_gps)
# Get header info in the form of a string that we can then send as a message to the webpage
#alert = get_header_info(pudfile)
# Here we generate the html page by passing the above
# information to the relevant files
example_map = simplemap.Map(map_title, markers=gps_markers, points=plots)
# We also need a name for the html file that's being outputted
example_map.write(csvfile + '.html')
# Finally we finish the script by opening the html
# file with whatever is the defult browser
webbrowser.open_new(csvfile + '.html')
# Give some indication that the process has finished and now we just open the html file.
print '\nWriting ' + csvfile + '.hmtl...'
|
84dcfe0242f5bb366301cd513d26e695985d38e7 | ForritunarkeppniFramhaldsskolanna/Keppnir | /2023/problems/asciikassi/submissions/partially_accepted/chatgpt_0.py | 243 | 3.671875 | 4 | #!/usr/bin/python3
n = int(input().strip())
if n == 0:
print("++")
print("++")
else:
print("+" + "-" * (n * 2 - 2) + "+")
for i in range(n):
print("|" + " " * (n * 2 - 2) + "|")
print("+" + "-" * (n * 2 - 2) + "+")
|
db556074ad87c87989ca06a041d444196dc3e7b6 | Vishesh0412/MyCaptain_Assignments | /Print_positive_numbers.py | 104 | 3.703125 | 4 | myList = [71, 23, -64, 3, -11, -19]
num = 0
for num in myList:
if num >= 0:
print(num)
|
99d7c7e50f281b863818ad6289e08c160f9e6890 | MikePolinske/Samples | /Homework2B.python | 203 | 3.78125 | 4 | #!/usr/bin/python
price = input("What is the cost of the item? ");
salesTax = input("What is the sales tax rate (Expressed as 0.XX)? ");
print "The full price of the item is $", price * (1 + salesTax); |
959944451bc1b4fb36518f650069273fcfe11752 | rajatkashyap/Python | /ThreeSum.py | 653 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 10:11:46 2019
'[-1, 0, 1, 2, -1, -4]
'[-4, -1, -1, 0, 1, 2]
@author: u40mv02
"""
def threeSum(nums):
z=len(nums)-1
res=[]
nums.sort()
for x in range(len(nums)-2):
y=x+1
while(y<z):
s=nums[x]+nums[y]+nums[z]
if s<0:
y=y+1
if s>0:
z=z-1
if s==0:
if [nums[x],nums[y],nums[z]] not in res:
res.append([nums[x],nums[y],nums[z]])
x+=1
return res
print threeSum([-1, 0, 1, 2, -1, -4,1,5])
|
a02ff297937fcaa26391809692a2b14e7b71707e | Machendra/python_notes | /fetching_files.py | 681 | 3.96875 | 4 | import os
req_path=input("please enter your dir path: ")
if os.path.isfile(req_path):
print(f'the given path is file please enter a valid path of dir: ')
else:
all_f_dir=os.listdir(req_path)
if all_f_dir==0:
print(f'there are no files in the {req_path} please choose another dir')
else:
req_ex=input('please enter required extension .sh .py .txt')
req_files=[]
for each_f in all_f_dir:
if each_f.endswith(req_ex):
req_files.append(each_f)
if len(req_files)==0:
print (f'please enter valid extensions there are no files ending with {req_ex} ')
else:
print(f'there are {len(req_files)} in the {req_path} ')
print(f'so the files are: {req_files} ' )
|
c2e9ff5311a6441f45c19c0207062b6129e9f581 | Pulkit12dhingra/Python_and_the_Web | /Scripts/API/Random_Album_API/Random_Album_API/logics/app_logic.py | 968 | 3.53125 | 4 | import pandas as pd
import random
class GetRandomAlbum:
"""Class to get random album from dataset"""
def __init__(self, context):
""" """
self.context = context
self.__out = []
self.dataset = None
def load_dataset(self):
"""loading the dataset into pandas"""
self.dataset = pd.read_csv(
"Random_Album_API/dataset/albumlist.csv", engine="python"
)
def get_random_album(self):
"""Get a random album from dataset"""
self.__out = self.dataset.iloc[[random.randint(0, 499)]].to_dict("record")
def get_all_album(self):
"""In case if you want all the records"""
self.__out = self.dataset.to_dict("record")
def driver_method(self):
"""A method for all methods"""
self.load_dataset()
if self.context == "random":
self.get_random_album()
else:
self.get_all_album()
return self.__out
|
974fbf862f52cb201d31bfd4af684c7db641c57e | jayzane/leetcodePy | /linked_list/19_remove_nth_node_from_end.py | 3,968 | 3.578125 | 4 | """
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
"""
from common.init_data import ListNode, init_list_node, print_list_node, algorithm_func_multi_exec, linked_examples
class Solution:
"""
一次遍历
使用哈希表记录每个位置对应的结点,再将对应结点的前驱点接上其后继点
时间复杂度:O(n),n是链表长度
空间复杂度:O(n)
"""
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# n有效检验
if n <= 0:
return head
p = head
hash_map = {}
count = 0
while p:
count += 1
hash_map[count] = p
p = p.next
# n有效检验
if n > count:
return head
# 删除点的前驱点
prev_cnt = count - n
# 只有一个结点,并且被删除
if count == 1:
return None
elif prev_cnt == 0:
# 删除头结点
return hash_map[prev_cnt + 1 + 1]
hash_map[prev_cnt].next = hash_map[prev_cnt].next.next # 包括了删除尾结点的情况
return head
class SolutionA:
"""
优化Solution,使用哨兵结点
时间复杂度:O(n)
"""
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# n有效检验
if n <= 0 or head is None: # head为空表情况
return head
pre_head = ListNode(-1)
pre_head.next = head
p = pre_head
hash_map = {}
count = -1
while p:
count += 1
hash_map[count] = p
p = p.next
# n有效检验
if n > count:
return head
# 删除点的前驱点
prev_cnt = count - n
# 使用哨兵,减少了一些判断
hash_map[prev_cnt].next = hash_map[prev_cnt].next.next
return pre_head.next
class SolutionB:
"""
两次遍历,删除倒数n个结点相当于删除第l-n个结点
时间复杂度:O(n)
空间复杂度:O(1)
"""
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# n有效检验
if n <= 0:
return head
pre_head = ListNode(-1)
pre_head.next = head
p = pre_head
count = -1
# 计数
while p:
count += 1
p = p.next
# n有效检验
if n > count:
return head
p = pre_head
count = count - n # 这个是删除点的前驱点
while count > 0:
count -= 1
p = p.next
p.next = p.next.next
return pre_head.next
class SolutionC:
"""
使用双指针,第一个指针在n+1个位置开始,第二个指针在头开始,同时移动,最后第一个指针到底NULL,此时第二个指针所在位置则是被删除
结点的前驱点
时间复杂度:O(n)
"""
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# n有效检验
if n <= 0:
return head
pre_head = ListNode(-1)
pre_head.next = head
first = second = pre_head
m = n + 1
# 第一个指针先走n+1
while m > 0:
first = first.next
m -= 1
if first is None and m > 0:
# n太大了
return head
# 第一个指针肯定先走完
while first:
first = first.next
second = second.next
# 此时第二指针为删除点的前驱点
second.next = second.next.next
return pre_head.next
if __name__ == '__main__':
sol = SolutionC()
args_list = [(1, ), (1, ), (2, ), (2, )]
algorithm_func_multi_exec(linked_examples, sol.removeNthFromEnd, args_list)
|
44970442e2e0bbcea4dd389310efa973b4d6117d | ValentinPortais/LPython | /function/month.py | 227 | 4.0625 | 4 | def MonthName(n):
"Function to find a month name"
mname=['January','February','March','April','May','June','July','August','September','October','November','December']
z=mname[n-1]
return z
#Usage
print(MonthName(1))
|
d011499a607a3376b384f05e4d2ad73762ef39dd | gerashdo/files-testing | /pruebas_aceptacion/edades/features/steps/edades.py | 451 | 3.59375 | 4 |
class Edad:
def calcularEdad(self, num = -1):
if isinstance(num, str):
return 'Solo numeros'
if num < 0:
return 'No existes'
if num < 14:
return 'Eres niño'
elif num < 18:
return 'Eres adolescente'
elif num < 66:
return 'Eres adulto'
elif num < 121:
return 'Eres adulto mayor'
else:
return 'Eres Mumm-Ra' |
bcfcc7bae25fd9d76b109dd19ccf3187322dc158 | wmstack/gci_matrix_multiplication | /matmul_custom.py | 2,807 | 3.59375 | 4 | import numba
@numba.jit
def dot_loop_jit(x,y):
sum = 0
for i in range(len(x)):
sum+= x[i]*y[i]
return sum
@numba.jit
def matmul_jit(x, y):
#generic matmul
#not just matmul of n x n matrices
#matmul, the length of a row of the first matrix 'x'
#is equal to the length of a column of the second matrix 'y'
#so we do the dot_product of the ith row in x, and jth column in y
#then put the result in (i,j) in the resulting array
#note that the shape is (rows, cells)
#so the length of the row is the number of cells
#the length of a column is the number of rows
row_len_x = len(x[0])
col_len_y = len(y)
assert row_len_x == col_len_y
#resulting dimensions
row_len_y = len(y[0])
col_len_x = len(x)
# a dot product of the ith row in x, x[i]
# and jth col in y, [y[k][j] for k in range(col_len_y)])
# for each (i, j)
# or . for j in range(row_len_y)
# for i in range(col_len_x)
#the for j comes first becuase shape is (rows, cells)
#and the cells of the row are the inner arrays so loop through the cells first
#then loop through the rows
#otherwise it is transposed
return [[dot_loop_jit(x[i],[y[k][j] for k in range(col_len_y)]) for j in range(row_len_y)] for i in range(col_len_x)]
#return [[dot_loop(x[i],y[:,j]) for j in range(row_len_y)] for i in range(col_len_x)]
def dot_loop_no_jit(x,y):
sum = 0
for i in range(len(x)):
sum+= x[i]*y[i]
return sum
def matmul_no_jit(x, y):
#generic matmul
#not just matmul of n x n matrices
#matmul, the length of a row of the first matrix 'x'
#is equal to the length of a column of the second matrix 'y'
#so we do the dot_product of the ith row in x, and jth column in y
#then put the result in (i,j) in the resulting array
#note that the shape is (rows, cells)
#so the length of the row is the number of cells
#the length of a column is the number of rows
row_len_x = len(x[0])
col_len_y = len(y)
assert row_len_x == col_len_y
#resulting dimensions
row_len_y = len(y[0])
col_len_x = len(x)
# a dot product of the ith row in x, x[i]
# and jth col in y, [y[k][j] for k in range(col_len_y)])
# for each (i, j)
# or . for j in range(row_len_y)
# for i in range(col_len_x)
#the for j comes first becuase shape is (rows, cells)
#and the cells of the row are the inner arrays so loop through the cells first
#then loop through the rows
#otherwise it is transposed
return [[dot_loop_no_jit(x[i],[y[k][j] for k in range(col_len_y)]) for j in range(row_len_y)] for i in range(col_len_x)]
#return [[dot_loop(x[i],y[:,j]) for j in range(row_len_y)] for i in range(col_len_x)] |
729b45a3420e0dce798b8650cea28221c205814d | marythought/sea-c34-python | /examples/session06/tmnt.py | 1,031 | 4.21875 | 4 | class Turtle(object):
def __init__(self, name):
"""Initialize a turtle."""
self.name = name
def announce(self):
"""Print out an introduction."""
print("{name} says hello.".format(self.name))
class TMNT(Turtle):
def __init__(self, name, color, weapon):
"""Initialize a teenage mutant ninja turtle with properties."""
self.name = name
self.color = color
self.weapon = weapon
def announce(self):
"""Print out an introduction."""
intro = "{name} wears {color} and has a {weapon}"
print(intro.format(
name=self.name,
color=self.color,
weapon=self.weapon
))
if (__name__ == "__main__"):
t1 = TMNT("Leonardo", "blue", "katana")
t2 = TMNT("Raphael", "red", "sai")
t3 = TMNT("Donatello", "purple", "bo staff")
t4 = TMNT("Michelangelo", "orange", "nun-chuks")
t5 = Turtle("World Turtle")
turtles = [t1, t2, t3, t4, t5]
for t in turtles:
t.announce()
|
c87ccef39675a0d1a7f8039af416a26336ec5bb8 | Geoffrey-lusitano/Exercices | /Exercice 6.13.py | 816 | 4.03125 | 4 | # CONSIGNES
# Ecrivez un algorithme permettant, toujours sur le même principe, à l’utilisateur de saisir un nombre déterminé de valeurs. Le programme, une fois la saisie terminée, renvoie la plus grande valeur en précisant quelle position elle occupe dans le tableau. On prendra soin d’effectuer la saisie dans un premier temps, et la recherche de la plus grande valeur du tableau dans un second temps.
# vARIABLE A Nombre Ecrire ""
# Tableau
# Si i dans liste Variable A
# ajouter dans Tableau Nombre
# Variable B = Max de Tableau
# Ecrire Variable B
# Ecrire Position tableau Variabel B
nombre = int(input("saisisez un nombre de valeurs : "))
tab = []
for ii in range(nombre):
tab.append(int(input("Entrer la valeur :")))
resultat = max(tab)
print(resultat)
print(tab.index(resultat)) |
089d6424a5391b2f0af09c6450d301dc1f87324f | Voxny404/FahrenheitTOcelsius | /Fahrenheit to Celsius.py | 1,137 | 3.9375 | 4 | from tkinter import *
# main function
#-----------
root = Tk()
#-----------
#head Text
#------------------------------------------
Label(root, text="Fahrenheit converter").pack(ipadx = 5, ipady = 5, side = TOP)
Label(root, text="by Jessica Nicole Voxny404").pack(ipadx = 5, ipady = 5, side =BOTTOM)
Label(root, text="Enter degrees: ").pack(ipadx = 0, ipady = 0, side = LEFT)
#------------------------------------------
# Fahrenheit converter
#-------------------------------------
def evaluate(event):
fahrenheit = float(user.get())
celsius = (fahrenheit-32)*5/9
res.config(text= round (celsius,2,))
#--------------------------------------
#user entry point
#------------------------------
user = Entry(root, text="Red")
user.bind("<Return>", evaluate)
user.pack(side = LEFT)
res = Label(root)
res.pack(side = BOTTOM)
#-------------------------------
# text button
#-------------------------------------------------
Label(root, text="Celsius").pack(side = BOTTOM)
#-------------------------------------------------
#Loop to main function
#---------------------
root.mainloop()
#---------------------
#made in Germany by Jessica Nicole Voxny404
|
5a5b1e71fa04a3c0209f1414c80a0d88ab05a28e | kokot300/python-core-and-advanced | /classprogramer.py | 486 | 3.625 | 4 | class Programer:
def setName(self,n): #setter methid
self.name=n
def getName(self): #getter method
return self.name
def setSalary(self,s):
self.salary=s
def getSalary(self):
return self.salary
def setTech(self,t):
self.technologies=t
def getTech(self):
return self.technologies
p1=Programer()
p1.setName("john")
p1.setSalary(100)
p1.setTech("java")
print(p1.getName())
print(p1.getSalary())
print(p1.getTech()) |
df1fdca4ff230853b4ca0c2ade6e9e6917f43a79 | baHarmon1/SodaMachineTesting_repo | /test_soda_machine.py | 7,765 | 3.546875 | 4 | from cans import Cola
from coins import Quarter, Dime, Nickel, Penny
import unittest
from soda_machine import SodaMachine
import coins
class TestFillRegister(unittest.TestCase):
"""Test the register method for its size"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_register_filled(self):
"""Test that the soda machine register has a list of size 88"""
register_length = len(self.soda_machine.register)
self.assertEqual(88, register_length)
class TestFillInventory(unittest.TestCase):
"""Test the fill inventory method"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_inventory_length(self):
"""Test the length of the inventory"""
inventory_length = len(self.soda_machine.inventory)
self.assertEqual(30, inventory_length)
class TestGetCoinFromRegister(unittest.TestCase):
"""Test the get coin from the register method"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_get_coin_register_quarter(self):
"""Test that 'Quarter' can be returned from the register"""
returned_coin = self.soda_machine.get_coin_from_register("Quarter")
self.assertEqual("Quarter", returned_coin.name)
def test_get_coin_register_dime(self):
"""Test that 'Dime' can be returned from the register"""
returned_coin = self.soda_machine.get_coin_from_register("Dime")
self.assertEqual("Dime", returned_coin.name)
def test_get_coin_register_nickle(self):
"""Test that 'Nickel' can be returned from the register"""
returned_coin = self.soda_machine.get_coin_from_register("Nickel")
self.assertEqual("Nickel", returned_coin.name)
def test_get_coin_register_penny(self):
"""Test that 'Penny' can be returned from the register"""
returned_coin = self.soda_machine.get_coin_from_register("Penny")
self.assertEqual("Penny", returned_coin.name)
def test_passing_string(self):
"""Test the 'None' can be returned from the register"""
returned_coin = self.soda_machine.get_coin_from_register("Invalid")
self.assertIsNone(returned_coin)
class TestRegisterHasCoin(unittest.TestCase):
"""Test all types of coins that can be returned from the register"""
def setUp(self):
self.has_coin = SodaMachine()
def test_register_has_quarters(self):
"""Tests that 'Quarter' type can be returned from register"""
coin_type = self.has_coin.register_has_coin("Quarter")
self.assertTrue(coin_type)
def test_register_has_dimes(self):
"""Tests that 'Dime' type can be returned from register"""
coin_type = self.has_coin.register_has_coin("Dime")
self.assertTrue(coin_type)
def test_register_has_nickel(self):
"""Tests that 'Nickel' type can be returned from register"""
coin_type = self.has_coin.register_has_coin("Nickel")
self.assertTrue(coin_type)
def test_register_has_pennies(self):
"""Tests that 'Penny' type can be returned from register"""
coin_type = self.has_coin.register_has_coin("Penny")
self.assertTrue(coin_type)
def test_fake_coin(self):
"""Tests that a 'non-valid' coin name cannot be returned from register"""
coin_type = self.has_coin.register_has_coin("Invalid")
self.assertFalse(coin_type)
class TestDetermineChangeValue(unittest.TestCase):
"""Test types of coins that can be returned from the register"""
def setUp(self):
self.value = SodaMachine()
def test_higher_total_payment(self):
"""Tests that we receive the correct value"""
higher_payment = self.value.determine_change_value(20, 5)
self.assertEqual(15, higher_payment)
def test_higher_soda_price(self):
"""Tests that we receive the correct value"""
higher_soda = self.value.determine_change_value(5, 20)
self.assertEqual(-15, higher_soda)
def test_two_equal_values(self):
"""Tests that we receive the correct value"""
equal_values = self.value.determine_change_value(10, 10)
self.assertEqual(0, equal_values)
class TestCalculateCoinValue(unittest.TestCase):
"""Test calculates the values of coins in a list"""
def setUp(self):
self.coin_value = SodaMachine()
def test_calculate_coins_value(self):
"""Test the calculation of a list with each coin"""
quarter_1 = coins.Quarter()
dime_1 = coins.Dime()
nickel_1 = coins.Nickel()
penny_1 = coins.Penny()
coin_list = []
coin_list.append(quarter_1)
coin_list.append(dime_1)
coin_list.append(nickel_1)
coin_list.append(penny_1)
total_value = self.coin_value.calculate_coin_value(coin_list)
self.assertEqual(.41, total_value)
def test_calculate_empty_list(self):
"""Test the calculation of the value of an empty list"""
coin_list = []
total_value = self.coin_value.calculate_coin_value(coin_list)
self.assertEqual(0, total_value)
class TestGetInventorySoda(unittest.TestCase):
"""Test the get_inventory_soda method in the SodaMachine class"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_pass_cola_return_soda_name_cola(self):
"""Test by passing in cola, and return the correct name"""
cola_test = self.soda_machine.get_inventory_soda("Cola")
self.assertEqual(cola_test.name, "Cola")
def test_pass_orange_soda_return_soda_name_orange_soda(self):
"""Test be passing in orange_soda, and return the correct name"""
orange_soda_test = self.soda_machine.get_inventory_soda("Orange Soda")
self.assertEqual(orange_soda_test.name, "Orange Soda")
def test_pass_rootbeer_return_soda_name_rootbeer(self):
"""Test be passing in rootbeer, and return the correct name"""
rootbeer_test = self.soda_machine.get_inventory_soda("Root Beer")
self.assertEqual(rootbeer_test.name, "Root Beer")
def test_pass_incorrect_string_return_none(self):
"""Test by passing an incorrect string through get_inventory_soda, and return None"""
incorrect_test = self.soda_machine.get_inventory_soda("Mountain dew")
self.assertEqual(incorrect_test, None)
class TestReturnInventory(unittest.TestCase):
"""Test the return_inventory method of the SodaMachine class"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_pass_can_return_updated_list(self):
"""Test by instantiating and passing a can through the return_inventory and return an updated list"""
cola_1 = Cola()
self.soda_machine.return_inventory(cola_1)
returned_list = len(self.soda_machine.inventory)
self.assertEqual(returned_list, 31)
class TestDepositCoinsIntoRegister(unittest.TestCase):
"""Test deposit_coins_into_register method in the SodaMachine class"""
def setUp(self):
self.soda_machine = SodaMachine()
def test_pass_list_of_each_coin_return_92(self):
"""Test by creating a list with each coin in it, then passing the list and getting a return of of 92"""
list_of_each_coin = []
quarter_1 = Quarter()
dime_1 = Dime()
nickel_1 = Nickel()
penny_1 = Penny()
list_of_each_coin.append(quarter_1)
list_of_each_coin.append(dime_1)
list_of_each_coin.append(nickel_1)
list_of_each_coin.append(penny_1)
self.soda_machine.deposit_coins_into_register(list_of_each_coin)
passed_coins = len(self.soda_machine.register)
self.assertEqual(passed_coins, 92)
if __name__ == "__main__":
unittest.main()
|
3ef8d3c66be1757b05957af72209103710885f87 | master-walker/TestPython | /src/Test/TestDict.py | 435 | 4.0625 | 4 | #!/usr/bin/env python
#coding=utf-8
'''
Created on 2017年5月8日
@author: Administrator
'''
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
#删除字典
print dict1
del dict1['Name']
print dict1
#清空dict
dict1.clear()
print dict1
#删除字典
# del dict1
# print dict1
#str(dict)
#输出字典可打印的字符串表示。
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print str(dict1)
|
786917cccddf87c7ea92a5dd1e4ad6574c21ee2e | amanda/practice | /euler/problem3.py | 238 | 3.65625 | 4 | num = 600851475143
def largest_prime_factor(n):
divided = n
for i in range(2, n+1):
while divided % i == 0:
divided = divided/i
if divided == 1:
return i
return n
if __name__ == '__main__':
print largest_prime_factor(num)
|
fef9baf7cb0839fbf351498e1dedd390d6df73ed | piantado/LOTlib3 | /Examples/EvenOdd/Model.py | 3,191 | 3.734375 | 4 | """ A simple exmaple to show use of a Lexicon """
WORDS = ['even', 'odd']
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Grammar
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from LOTlib3.Grammar import Grammar
from LOTlib3.Miscellaneous import q
grammar = Grammar()
grammar.add_rule('START', '', ['BOOL'], 1.)
grammar.add_rule('BOOL', '(%s == %s)', ['NUMBER', 'NUMBER'], 1.)
grammar.add_rule('BOOL', '(not %s)', ['BOOL'], 1.)
grammar.add_rule('BOOL', '(%s and %s)', ['BOOL', 'BOOL'], 1.)
grammar.add_rule('BOOL', '(%s or %s)', ['BOOL', 'BOOL'], 1.) # use the short_circuit form
grammar.add_rule('NUMBER', 'x', None, 1.)
grammar.add_rule('NUMBER', '1', None, 1.)
grammar.add_rule('NUMBER', '0', None, 1.)
grammar.add_rule('NUMBER', 'plus_', ['NUMBER', 'NUMBER'], 1.)
grammar.add_rule('NUMBER', 'minus_', ['NUMBER', 'NUMBER'], 1.)
for w in WORDS:
grammar.add_rule('BOOL', 'lexicon', [q(w), 'NUMBER'], 1.)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from LOTlib3.DataAndObjects import FunctionData
def make_data(n=1, alpha=0.99):
data = []
for x in range(1, 10):
data.append( FunctionData(input=['even', x], output=(x % 2 == 0), alpha=alpha) )
data.append( FunctionData(input=['odd', x], output=(x % 2 == 1), alpha=alpha) )
return data*n
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Hypothesis
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from LOTlib3.Hypotheses.Lexicon.RecursiveLexicon import RecursiveLexicon
from LOTlib3.Hypotheses.LOTHypothesis import LOTHypothesis
from LOTlib3.Hypotheses.Likelihoods.BinaryLikelihood import BinaryLikelihood
class MyHypothesis(BinaryLikelihood, RecursiveLexicon):
def __init__(self, **kwargs):
RecursiveLexicon.__init__(self, **kwargs)
for w in WORDS:
self.set_word(w, LOTHypothesis(grammar, display='lambda lexicon, x: %s'))
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Main
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == "__main__":
from LOTlib3 import break_ctrlc
from LOTlib3.Miscellaneous import qq
from LOTlib3.TopN import TopN
from LOTlib3.Samplers.MetropolisHastings import MetropolisHastingsSampler
h0 = MyHypothesis()
data = make_data()
top = TopN(N=10)
thin = 100
for i, h in enumerate(break_ctrlc(MetropolisHastingsSampler(h0, data))):
top << h
if i % thin == 0:
print("#", i, h.posterior_score, h.prior, h.likelihood, qq(h))
for h in top:
print(h.posterior_score, h.prior, h.likelihood, qq(h))
|
8ff36e200c5df95d22af1c74b1ed80312d119948 | hemanthkumar25/MyProjects | /Python/BinarySearch.py | 483 | 4 | 4 | def binarySearch(arr,item):
start = 0;
end = len(arr)-1;
found = False
while(start<=end) and not found:
mid = (start+end)/2
if(arr[mid])==item:
found = True
else:
if(item > arr[mid]):
start = mid+1
else:
end = mid-1
return found
arr = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(arr, 3))
print(binarySearch(arr, 13))
|
e2ae9875008937afb9a05d5abbbfa94ea6276f7d | panditaot/tarea1 | /divisible3.py | 187 | 3.984375 | 4 | def n(m):
x = m%3
if x == 0:
return True
else:
return False
m = int(input("Ingrese un número entero para comprobar si es divisible entre tres "))
print(n(m))
|
75975bb15cd668ab7feb4e38df3a8ac77a211d6a | arnabs542/interview-notes | /notes/algo-ds-practice/problems/stack_queue/print_backet_number.py | 752 | 4.0625 | 4 | '''
Given an expression exp of length n consisting of some brackets.
The task is to print the bracket numbers when the expression is being parsed.
Example:
Input:
3
(a+(b*c))+(d/e)
((())(()))
((((()
Output:
1 2 2 1 3 3
1 2 3 3 2 4 5 5 4 1
1 2 3 4 5 5
Explanation:
Test case 1:The highlighted brackets in the given expression (a+(b*c))+(d/e) has been assigned the numbers as: 1 2 2 1 3 3.
SOLUTION:
Define a variable left_bnum = 1.
Create a stack right_bnum.
Now, for i = 0 to n-1.
If exp[i] == ‘(‘, then print left_bnum, push left_bnum on to the stack right_bnum and finally increment left_bnum by 1.
Else if exp[i] == ‘)’, then print the top element of the stack right_bnum and then pop the top element from the stack.
'''
|
7c7aecc94288280ea36d48a25d4c05fd3ed8e2aa | ChangxingJiang/LeetCode | /1301-1400/1324/1324_Python_1.py | 517 | 4.03125 | 4 | import itertools
from typing import List
class Solution:
def printVertically(self, s: str) -> List[str]:
return ["".join(elem).rstrip() for elem in itertools.zip_longest(*s.split(), fillvalue=" ")]
if __name__ == "__main__":
print(Solution().printVertically(s="HOW ARE YOU")) # ["HAY","ORO","WEU"]
print(Solution().printVertically(s="TO BE OR NOT TO BE")) # ["TBONTB","OEROOE"," T"]
print(Solution().printVertically(s="CONTEST IS COMING")) # ["CIC","OSO","N M","T I","E N","S G","T"]
|
91bcab1432c55e4b8e304967285c23512ccefc61 | Uluturk0/python-Week1 | /lessons_score_calculation.py | 1,286 | 4 | 4 | '''
Developer: Ömer ULUTÜRK
Date: 01.02.2020
Purpose of Software: Reinforcement of learned Python Code and Self-improvement
What does program do? : The program takes the student name and surname,
names of lesson, midterm scores and final scores.
And it gives average score and result that specify as "pass" or "failed".
'''
print("Welcome to The Lesson Point Calculation Program")
student=input("Please enter your name and surname:").upper()
student_number=input("Please enter your student number:")
lessons=[]
lesson1_midterm_note=[]
lesson1_final_note=[]
average_note=[]
for i in range (0,4):
lesson_name=input(f"Please enter your {i+1}. lesson:")
lessons.append(lesson_name)
midterm=int(input(f"Please enter midterm note for {lessons[i]} lesson:"))
lesson1_midterm_note.append(midterm)
final=int(input(f"Please enter final note for {lessons[i]} lesson:"))
lesson1_final_note.append(final)
average=(lesson1_midterm_note[i]*0.4)+(lesson1_final_note[i]*0.6)
average_note.append(average)
print("Name:",student, " Number:",student_number)
for i in range (0,4):
if average_note[i] > 50:
print(f"{lessons[i]}: PASSED ({average_note[i]})")
else:
print(f"{lessons[i]}: FAILED ({average_note[i]})")
|
7781f152ca85f3683aa8af0bc2a9f1ee7ebabbdb | mdsahil369/Python-Problem-Solve | /divide apple each other.py | 550 | 3.59375 | 4 | # 10 apple mn=2,mx=4--->2 is divisor of 10,3 isn't divisor of 10,4 is divisor of 10.
# 1.get input
# 2.processing
# 3.and give output
amound_of_apple = int(input('Which amound of apple avelable in harry : '))
min_number = int(input('min number : '))
max_number = int(input('max number : '))
if min_number != max_number :
for i in range(min_number,max_number+1):
if amound_of_apple%i == 0:
print(f'{i} is divison of {amound_of_apple} And each people get {amound_of_apple/i} Apple')
else:
print(f'{i} is\'nt divison of {amound_of_apple}')
|
a49dd72d6cbff23a1d4849d9026356a5f7c27961 | ferhsilvestre/algoritmos | /Lista 5/ex7.py | 839 | 3.828125 | 4 | # 7. Faça um algoritmo que calcule e apresente a média de alturas superior a 1,80 de 10 alunos. Informe também quantos e quais (índice/posição) são os alunos. Não use nenhuma função pronta da linguagem Python.
import sys
altura = []
altura_m = 0
cont = 0
indice = []
for i in range(10):
altura.append(float(input("Digite a altura do aluno: ")))
for i in range(10):
if altura[i] > 1.8:
altura_m += altura[i]
cont += 1
indice.append(i)
if cont == 0: # caso nenhum aluno tenha altura não vai dar erro
print('Não tem nenhum aluno com altura superior a 1.80')
sys.exit()
media = altura_m / cont
print(f'A media de altura dos alunos superiores a 1.80 é de {media:.2f}')
print(f'Existem {cont} alunos com altura superior a 1.80, e eles se encontram no índice {indice}')
|
633f974163bd72327fed9c796a7d56d93c72749f | chenbokaix250/ForSomeForMySelf | /python算法实践/排序/select_sort.py | 489 | 3.734375 | 4 | # __*__ coding=utf-8 __*__
def select_sort_simple(li):
li_new = []
for i in range(len(li)):
min_val = min(li)
li_new.append(min_val)
li.remove(min_val)
return li_new
def select_sort(li):
for i in range(len(li)-1):
min_loc = i
for j in range(i+1,len(li)):
if li[j] < li[min_loc]:
min_loc = j
li[i],li[min_loc] = li[min_loc],li[i]
return li
li = [3,2,4,1,5,6,8,7,9]
print(select_sort(li))
|
8b204926dbcaa5e110d761fb581965a30f923d54 | brunpersilva/python-treino2 | /ex13.py | 133 | 3.859375 | 4 | c = float(input('Qual a temperatura em Ceusius?'))
f = float(c * 1.8) + 32
print('{} celcius é igual a {} fahrenheit'.format(c, f))
|
add62ff5570798b15ca80e521da1cd2f76763afd | Ahha5775/Knights-Tour-Python | /bye.py | 3,229 | 3.765625 | 4 | #NOTE: assumes board already exists and is only compatible with board as list of coordinates!
def coor_sub(a,b):
"""Subtracts coordinate list b from coordinate list a."""
return [a[0]-b[0],a[1]-b[1]]
def test_legal(move,k_cor):
"""Checks proposed move to chess coordinates on chessboard for the knight at k_cor.
returns True if legal and False if illegal or already visited."""
global board
poss=[[1,2],[1,-2],[-1,2],[-1,-2],
[2,1],[2,-1],[-2,1],[-2,-1]]
if coor_sub(k_cor,move) in poss:
if move in board:
return True
return False
def alg2coords(text):
"""Converts algebraic notation to list [x,y]."""
x=text[0].lower()
y=text[1]
let2coords={"a":0,
"b":1,
"c":2,
"d":3,
"e":4,
"f":5,
"g":6,
"h":7}
y=int(y)-1 #a1 maps to [0,0] not [0,1]
return [let2coords[x],y]
def coords2alg(coords):
"""Converts coordinates s a list [x,y] to algebraic notation."""
x=coords[0]
y=coords[1]
x=chr(x+65).lower()
y=str(y+1)
return x+y
pos = [[1,2],[1,-2],[-1,2],[-1,-2],[2,1],[-2,1],[2,-1],[-2,-1]]
place=input("What coordinates do you want? ")
k_cor=alg2coords(place)
move = []
board = []
for i in range(64):
move.append(0)
for i in range(8):
for x in range(8):
board.append([i,x])
for i in range(len(board)):
if(board[i] == [k_cor[0],k_cor[1]]):
del(board[i])
break #makes board, deletes starting value
last_c = []
running = True
while(running == True): #creates loop that runs program (necessary because have to define varaibles beforehand and run multiple times)
prev = []
re= 1
n_move = 0
while(re == 1):
re = 0
for i in range(len(move)):
while(not [k_cor[0] + pos[move[i]][0], k_cor[1] + pos[move[i]][1]] in board): #checks if points + move is not in board if so, increases move value by one, checks if no moves
move[i] += 1
re = 1
if(move[i] > 7):
prev = move
prev[i-1]+=1
for x in range(len(move)-i): #also checks if completed and prints results *kinda*
if(board == []):
print(last_c)
prev[i+x] = 0
n_move = 1
break
if(n_move == 0):
k_cor[0],k_cor[1] = k_cor[0] + pos[move[i]][0], k_cor[1] + pos[move[i]][1]
last_c.append([k_cor[0],k_cor[1]])
for i in range(len(board)):
if(board[i] == [k_cor[0],k_cor[1]]):
del(board[i])
break
if(n_move == 1):
break
it = len(prev)
prev[it-1] += 1
x=1
while(move[it-x] > 7): #puts next series into list
prev[it-x] = 0
x += 1
prev[it-x] += 1
if(x == it):
print("No solution")
break
move = prev
board = []
for i in range(8):
for x in range(8):
board.append([i,x])
|
7c363ec6da74d132b968c871db3087f1c5e1af41 | MirsadHTX/Temp | /TestChat1.py | 344 | 3.515625 | 4 | from chatterbot import ChatBot
chatbot = ChatBot(
'Ron Obvious',
trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)
# Train based on the english corpus
chatbot.train("chatterbot.corpus.english")
while (True):
textToChat = input('Ask something')
textFromChat = chatbot.get_response("textToChat")
print(textFromChat) |
58cc33c91679dd439470b41db7e1340fe83ad5dd | Mahiuha/skaehub-assignment | /day3/2-numpy_weekdays.py | 343 | 3.859375 | 4 | #import the numpy library
#prompt the user for the year
#prompt the user for the month
#print to the user the number of weekdays as output
import numpy as np
print('Enter From Day YYYY-MM e.g 2021-07')
start_count = input()
print('Enter To Day YYYY-MM e.g 2021-07')
stop_count = input()
s= np.busday_count(start_count, stop_count)
print(s)
|
640f78e0876c034f8a536b1ec1523d4481540f55 | Aasthaengg/IBMdataset | /Python_codes/p02948/s122102819.py | 2,240 | 3.609375 | 4 | """
案件を報酬を受け取るまでにかかる時間で降順ソートしておく。
"""
class segTree:
def __init__(self,n,identity):
if bin(n).count("1") == 1:
self.leaves = 2**(n.bit_length()-1)
else:
self.leaves = 2**n.bit_length()
self.identity = identity
self.tree = [[self.identity,-1] for i in range(self.leaves*2)]
for i in range(self.leaves,self.leaves*2):
self.tree[i] = [self.identity,i-self.leaves]
def merge(self,x,y):
#ここにマージ処理を書く
if x[0] < y[0]:
return x[::1]
else:
return y[::1]
def update(self,i,x):
i = i+self.leaves
self.tree[i][0] = x
i >>= 1
while i > 0:
self.tree[i] = self.merge(self.tree[i*2],self.tree[i*2+1])
i >>= 1
def query(self,l,r):
#[l:r)のクエリ結果を返す
l = l + self.leaves
r = r + self.leaves
res = [self.identity,-1]
while l < r:
if l&1:
res = self.merge(res,self.tree[l])
l += 1
if r&1:
r -= 1
res = self.merge(res,self.tree[r])
l >>= 1
r >>= 1
return res
N,M = map(int,input().split())
M += 1
sgt = segTree(N,float("INF"))
AB = [list(map(int,input().split())) for _ in range(N)]
AB.sort(key=lambda x: -x[0])
today = 1
for i in range(N):
a,b = AB[i]
due = M-a
#M日までに報酬を受け取るためには、何日までに働かなくてはいけないかを求める。
if today <= due:
#今日の日付がdue以下であれば、今日その仕事をこなす
sgt.update(today-1,b)
today += 1
else:
if due < 1:
continue
#今日の日付がdueを過ぎてしまっている場合は、due以前の労働で報酬がb以下の仕事のうち、報酬がもっとも低い仕事を塗り替える。
tmp = sgt.query(0,due)
if tmp[0] < b:
sgt.update(tmp[1],b)
ans = 0
for i in range(N):
if sgt.tree[i+sgt.leaves][0] != float("INF"):
ans += sgt.tree[i+sgt.leaves][0]
print(ans)
|
0de90e08a4ca3ec1ff6cc10b183283fbd78d47bd | anaxmnenik/Mk-PT1-41-21 | /Tasks/ostrovski_oleg/task_1/quadratic equation.py | 578 | 4.03125 | 4 | import math
print("Введите коэффициенты для уравнения")
print("ax^2 + bx + c = 0:")
a = int(input('введите число a = '))
b = int(input('введите число b = '))
c = int(input('введите число c = '))
print()
d = b ** 2 - 4 * a * c
print("Дискриминант D = " + str(d))
if d > 0:
x1 = (-b + math.sqrt(d)) / (2 * a)
x2 = (-b - math.sqrt(d)) / (2 * a)
print("x1 = %.2f \nx2 = %.2f" % (x1, x2))
elif d == 0:
x = -b / (2 * a)
print("x = %.2f" % x)
else:
print('нет корней') |
03645ac61136f955936792a66211e2cb7a0cf65a | xyl5869/learnpy | /day2/dict.py | 522 | 3.625 | 4 | #!/usr/bin/python
# encoding:utf8
# Author:Along
ab = {
'Swaroop': '[email protected]',
'Larry':'[email protected]',
'Matsumoto': '[email protected]',
'Spammer': '[email protected]'
}
print("Swaroop's address is",ab['Swaroop'])
print("Larry's address is",ab['Larry'])
del ab['Spammer']
print('\nThere are {} contacts in address-book\n'.format(len(ab)))
for name,address in ab.items():
print('Contact {} at {}'.format(name,address))
ab['Guido'] = '[email protected]'
if 'Guido' in ab:
print("\nGuido's address is",ab['Guido'])
print(ab.items()) |
4dc6e032212649d5e47ad94991f818fb5c9f8169 | terrameijar/PythonUnitConverter | /modules/metric/centimeters.py | 1,673 | 3.796875 | 4 | def centimeters_millimeters(n, api=False):
b = float(n) * 10
if api == True:
return b
if float(n) == 1:
print str(n) + ' centimeter = ' + str(b) + ' millimeter(s).'
else:
print str(n) + ' centimeters = ' + str(b) + ' millimeter(s).'
def centimeters_decimeters(n, api=False):
b = float(n) / 10
if api == True:
return b
if float(n) == 1:
print str(n) + ' centimeter = ' + str(b) + ' decimeter(s).'
else:
print str(n) + ' centimeters = ' + str(b) + ' decimeter(s).'
def centimeters_meters(n, api=False):
b = float(n) / 100
if api == True:
return b
if float(n) == 1:
print str(n) + ' centimeter = ' + str(b) + ' meter(s).'
else:
print str(n) + ' centimeters = ' + str(b) + ' meter(s).'
def centimeters_kilometers(n, api=False):
b = float(n) / 1000
if api == True:
return b
if float(n) == 1:
print str(n) + ' centimeter = ' + str(b) + ' kilometer(s).'
else:
print str(n) + ' centimeters = ' + str(b) + ' kilometer(s).'
def centimeter():
try:
a = float(raw_input('How many centimeters would you like to convert? '))
except ValueError:
print 'You need to enter a number!'
foot()
b = raw_input('What you you like to convert to? [M]illimeters, [D]ecimeters, [Me]ters, [K]ilometers: ')
if b == 'M' or b == 'm':
centimeters_millimeters(a)
if b == 'D' or b == 'd':
centimeters_decimeters(a)
if b == 'Me' or b == 'me' or b == 'mE':
centimeters_meters(a)
if b == 'K' or b == 'k':
centimeters_kilometers(a)
|
fb4c58d9c7933bed25058badd5e4049861807ff7 | dondropo/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 331 | 4.1875 | 4 | #!/usr/bin/python3
"""
Module that writes a string to a text file (UTF8)
and returns the number of characters written
"""
def write_file(filename="", text=""):
"""Write a text inside a file"""
writer = 0
with open(filename, mode='w', encoding='UTF-8') as file:
writer = file.write(text)
return writer
|
1bb51313810c310908942af99eb85268e533cb50 | satlawa/ucy_dsa_projects | /Project_2/problem_2.py | 4,094 | 4.375 | 4 | #------------------------------------------------------#
# problem 2 - Search in a Rotated Sorted Array
#------------------------------------------------------#
def find_pivot(array):
'''Find pivot index in Rotated Sorted Array
args:
array(list): a sorted array of items of the same type
returns:
int: the index of the pivot
-1: if the pivot is not found
'''
pivot = -1
start_index = 0
end_index = len(array) - 1
while start_index <= end_index:
mid_index = (start_index + end_index)//2 # integer division in Python 3
mid_element = array[mid_index]
if array[start_index] <= array[end_index]: # we have found the element
return start_index
elif array[start_index] <= array[mid_index]: # the target is less than mid element
start_index = mid_index + 1 # we will only search in the left half
elif array[mid_index] <= array[end_index]:
end_index = mid_index
else: # the target is greater than mid element
start_index = mid_element + 1 # we will search only in the right half
return pivot
def binary_search(array, target, start_index, end_index):
'''Binary search algorithm using iteration
args:
array(list): a sorted array of items
target(int): the element you're searching for
start_index(int): start index for the serarch
end_index(int): end index for the serarch
returns:
int: the index of the target, if found, in the source
-1: if the target is not found
'''
while start_index <= end_index:
mid_index = (start_index + end_index)//2 # integer division in Python 3
mid_element = array[mid_index]
if target == mid_element: # we have found the element
return mid_index
elif target < mid_element: # the target is less than mid element
end_index = mid_index - 1 # we will only search in the left half
else: # the target is greater than mid element
start_index = mid_index + 1 # we will search only in the right half
return -1
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(list), number(int): Input array to search and the target
Returns:
int: Index or -1 (if not found)
"""
if input_list is None or not input_list or number is None:
return -1
pivot_index = find_pivot(input_list)
if number <= input_list[-1]:
start_index = pivot_index
end_index = len(input_list)
elif number > input_list[-1]:
start_index = 0
end_index = pivot_index
index = binary_search(input_list, number, start_index, end_index)
return index
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass array: {} value: {}".format(input_list, number))
else:
print("Fail")
# Standard test cases
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
# Pass array: [6, 7, 8, 9, 10, 1, 2, 3, 4] value: 6
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
# Pass array: [6, 7, 8, 9, 10, 1, 2, 3, 4] value: 1
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
# Pass array: [6, 7, 8, 1, 2, 3, 4] value: 8
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
# Pass array: [6, 7, 8, 1, 2, 3, 4] value: 1
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
# Pass array: [6, 7, 8, 1, 2, 3, 4] value: 10
# Edge test cases
test_function([[0], 0])
# Pass array: [0] value: 0
test_function([[], -1])
# Pass array: [] value: -1
|
83a11a434ab57e11db71f1103c8a83017be086ca | Hndz93/1erParcialEjercisios | /ejercisio3.py | 263 | 3.921875 | 4 | InicioSesion = ("Nombre y clave")
print ("Ingrese Usuario : ")
usuario = input("Parcial")
print ("Ingrese Clave : ")
clave = int(input(1234))
if (usuario=="Parcial" and clave==1234):
print("nombre usuario incorrecto")
else:
print("Clave de acceso incorecto") |
3a32700eefa0e3c6a2389829fbdd2a3aef830ad7 | aliceslombardi/exercicios-algoritimos | /lista-exercicios-computacional-thinking/exercicio04.py | 73 | 3.609375 | 4 | x = int(input("x"))
y = int(input("y"))
potencia = x ** y
print(potencia) |
48fe2fbb091316a82c366f567aef9c089e73a574 | TejasviniK/Python-Practice-Codes | /getCaptitals.py | 255 | 4.125 | 4 | def get_capitals(the_string):
capStr = ""
for s in the_string :
if ord(s) >= 67 and ord(s) <= 90:
capStr += s
return capStr
print(get_capitals("CS1301"))
print(get_capitals("Georgia Institute of Technology"))
|
35c00de7dd44c25b0da2f21bb64202399e88a6f2 | Xiangtuo/leetcode | /python/JZ26_二叉搜索树与双向链表.py | 797 | 3.6875 | 4 | # 题目描述
# 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.head = None
self.pre = None
def Convert(self, pRootOfTree):
if pRootOfTree is None:
return
self.Convert(pRootOfTree.left)
if self.head is None:
self.head = pRootOfTree
pRootOfTree.left = self.pre
if self.pre is not None:
self.pre.right = pRootOfTree
self.pre = pRootOfTree
self.Convert(pRootOfTree.right)
return self.head
|
eaf08fbd48a086ca0558b91fc0bcb00f64c9084f | zaferwer/my-first-repo | /Hello.py | 248 | 3.9375 | 4 | <<<<<<< HEAD
print("Hello World")
yas = input('yasını gir')
chronic = input ('hastalık')
risk = bool (yas == 'yes' or chronic =='yes')
print(risk)
help(len)
=======
print("Hello World")
>>>>>>> a08daceccaba833f5aa10f5808b7c0c0adb23f7c
|
96419b3914b2c75aa7452b8e83becef2497aa204 | tsgreenwood-flatiron-data-science/dsc-1-final-project | /haversine.py | 660 | 3.6875 | 4 | from math import radians, cos, sin, asin, sqrt
def distance_from_flatiron(coords_tuple):
#'''47.610361, -122.336107'''
'''COPIED FROM STACKOVERFLOW MICHAEL DUNN
INSPIRED BY DAVID KASPAR THE RAINBOW UNICORN'''
lon1, lat1, lon2, lat2 = coords_tuple[1], coords_tuple[0], -122.336107, 47.610361
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r |
65a29b4b2fa58957a3ae89711fd923fd94113f10 | moabdelmoez/road_to_pythonista | /Lec 6/7- removing vowels.py | 246 | 4.1875 | 4 | def remove_vowels():
word = input("please enter a word: ")
no_vowel = ''
for ch in word:
if ch in 'aoei':
continue
else:
no_vowel = no_vowel + ch
print(no_vowel)
remove_vowels()
|
8f136aa7054e7ba1cb02671fe4cf4cfbd3189a71 | debajyoti-ghosh/Pythonshala | /OOPs/Empty_class.py | 670 | 3.90625 | 4 | class student:
pass # as class without any attribute or method are not allowed so pass statement is added.
student1= student() # object,named student1 of class, named student is created
student2 = student() # another instant or object of the same class
student1.name = "Rajib" # attributs added to the object, though not a proper way
student1.marks = 85 # to add attributes to the objects, usually we want to put attributes inside the class,
# so that all the objects created from the class have these attributes by default
# similarly we also put methods inside the class, so the all the objects can access them
print(student1.name)
print(student1.marks) |
123ab02be57e6c137f96882ebc47c8aeace786ea | NadiaAlmutlak/Intro-Python | /Desktop/IntroPython/Homework2/1.py | 3,972 | 3.890625 | 4 |
#stock risk and return simulation - Homework 2 - Nadia AlMutlak Na2736
import pandas as pd
import matplotlib.pyplot as plt
import math
import argparse
import numpy as np
#Code from data_access.py. to compute the average value for a list of number
def compute_average(num_list):
count = len(num_list)
total = 0
for i in range(0,count):
total = total + num_list[i]
avg = total/count
return avg
#Task one get data from from files
#Taken from data_access.py.
# This function takes a ticker symbol and loads a data frame
# with the data stored in a CSV file in the current directory.
def get_data_from_file(ticker):
f_name = ticker + ".csv"
df = pd.read_csv(f_name, delimiter=",")
return df
#computes the daily drift and then takes that information to compute the standard deviation, returns both of them
def compute_mu_and_sigma(df):
adjClose = df['Adj Close']
count = len(adjClose)
relative_change_list = []
for i in range(1, count):
relative_change = ((adjClose[i]-adjClose[i-1])/adjClose[i-1])
relative_change_list.append(relative_change)
daily_drift = compute_average(relative_change_list)
diff_mean_list = []
for i in range(0, len(relative_change_list)):
diff_from_mean = (relative_change_list[i]-daily_drift)**2
diff_mean_list.insert(i, diff_from_mean)
count = len(diff_mean_list)
sum = 0
for i in range(0,count):
sum = sum + diff_mean_list[i]
avg = sum/(count-1)
std_deviation = math.sqrt(avg)
return daily_drift, std_deviation
# Task 2 computes random daily return
def random_daily_return(s, mu, sigma):
R = np.random.uniform(0,1)
delta = (s*mu) + (s*sigma*R)
return (s + delta)
# Task 3 returns a list of a years worth of random daily returns
def random_stock_year(s, mu, sigma):
random_walk_list = [s]
for i in range(1,252):
random_walk_list.append(random_daily_return(random_walk_list[i-1], mu, sigma))
return random_walk_list
#Task 4 main method that parses for number of smulations and which ticker,
# then computes and plots them
def main():
list_of_tickers = ['AAPL', 'GOOG', 'AMZN']
ticker = 'AAPL'
simluations = 10
interactive = False
if (interactive == False):
parser = argparse.ArgumentParser(description='Predict stock return and risk with Geometric Brownian Motion ')
parser.add_argument('--ticker', default='AAPL', type=str, help='ticker of stock to analyze')
parser.add_argument('--simulations', default=10, type=int, help='number of simulations to run')
args = parser.parse_args()
if args.simulations <= 0:
print("Number of simulations must be greater than 0")
quit()
if args.ticker not in list_of_tickers:
print("Ticker must be one of the following: ", list_of_tickers)
quit()
simulations = int(args.simulations)
ticker = args.ticker
else:
ticker = input("Enter the ticker of the stock to be analyzed:")
simulations = input("Enter the number of simulations to be run:")
if ticker not in list_of_tickers:
print("Will use default AAPL because no correct ticker was provided")
ticker = 'AAPL'
if simulations is '' or int(simulations) <= 0:
print("Number of simulations must be greater than 0. Will run 10 simulations")
simulations = 10
df = get_data_from_file(ticker)
mu, sigma = compute_mu_and_sigma(df)
starting_price_list = df['Close']
starting_price = starting_price_list[len(starting_price_list)-1]
print ("Starting Price: ", starting_price, " Mu: ", mu, " Sigma: ", sigma)
print('Simulating {} trials...' .format(int(simulations)))
for i in range(int(simulations)):
a = random_stock_year(starting_price, mu, sigma)
plt.plot(a)
plt.show()
#runs the program at start
if __name__ == "__main__":
main() |
d82d2c78d40b13f7a13f786181f1d27c34425302 | orasraf1241/World_Weather | /python/types_and_loops.py | 1,101 | 4.25 | 4 | def is_even(arg):
""" This funcs check is the number is even or odd"""
if arg % 2 == 1:
print("not even")
else:
print("even")
def print_str(string, number=1):
"""This func print the string number of time but if the user dont insert number the func s print the str once"""
for x in range(number):
print(string)
def leap_year(year):
"""Check if is a leap year"""
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
return False
def revers(num1):
"""This func revers the num"""
print(str(num1)[::-1])
def grades(x):
"""This funcs return the grad by word"""
if 0 < x < 10:
print('F')
elif 10 < x < 30:
print('E')
elif 30 < x < 50:
print("D")
elif 50 < x < 70:
print('C')
elif 70 < x < 90:
print('B')
elif 90 < x < 100:
print('A')
if __name__ == "__main__":
is_even(3)
print_str("or asraf 5", 5)
leap_year(400)
leap_year(4)
print(leap_year(300))
revers(1234)
grades(76)
print("Hello World!")
|
03c0f6fd551be9e8d81dcf244643c68cb152132a | suhairmu/pythonprograms | /object oriented programmimg/bank.py | 1,030 | 3.75 | 4 | '''
bank
bname
acc no
balance
createaccount()
deposit()
withdrawl()
balEnq()
'''
import datetime
class Bank:
bname="sbi"
def createAccount(self,bname,accno,balance):
#self.bname=bname
self.accno=accno
self.balance=3000
def deposit(self,amt):
self.balance+=amt
print("your ",Bank.bname,"account has been credited with amount",amt) #static variable can invoke by class name also (Bank,bname)
print("on ",datetime.datetime.now(),"current balance=",self.balance)
def withdraw(self,amt):
if(amt>self.balance):
print("insufficient fund")
else:
self.balance-=amt #self.balance=self.balance-amt
print("your ", self.bname, "account has been debited with amount", amt)
print("on ", datetime.datetime.now(), "current balance=", self.balance)
def balanceEnq(self):
print("your account balance =",self.balance)
obj=Bank()
obj.createAccount("sbi",1003,1000)
obj.withdraw(500)
obj.balanceEnq() |
2cf6f866760610a9bcc8b9ba2e94f189cc116d5a | ymmy1/CS50_HW | /pset7/houses/roster.py | 612 | 3.6875 | 4 | import sys
from cs50 import SQL
# validating the arguments
if len(sys.argv) != 2:
print("Usage python roster.py house")
exit(1)
# setting db
db = SQL("sqlite:///students.db")
stName = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first",
sys.argv[1])
# outprint
for i in range(0, len(stName), 1):
print(stName[i]["first"], end=' ')
# if person has middle name, print middle name
if stName[i]["middle"]:
print(stName[i]["middle"], end=' ')
print(stName[i]["last"], end=', ')
print(f"born {stName[i]['birth']}") |
8ca96f86ecd666624afce9dfa90fb4c3861e4aa3 | nishant-sethi/HackerRank | /EdgeverveCodingChallenge/Hockey_stick.py | 439 | 3.5625 | 4 | '''
Created on Jun 1, 2018
@author: nishant.sethi
'''
import math
def rowColEntry(n,r):
return math.factorial(n)/(math.factorial(r)*(math.factorial(n-r)))
n,l=(11,3)
lst=[]
x=1
a=n
while x!=l-1:
lst.append(rowColEntry(a,x))
a+=1
x+=1
print(lst)
ans=[1]
a=1
for i in lst:
print(a+int(i))
ans.append(a+int(i))
a=a+int(i)
result=''
for i in ans:
result+=str(i)+'+'
print(result[:-1]) |
a45ffeadf7c60bf9d957c6bf54e532ecc03b36cd | hoctor/median | /main.py | 461 | 4.03125 | 4 | fname = raw_input("(Entre com o nome do arquivo) Enter file name: ")
num_words = 0
num_char = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
num_char += sum(len(word) for word in words)
median = float(num_char/float(num_words))
print("(Numero de palavras) Number of words:")
print(num_words)
print(" (Numero de letras) Number of letters")
print(num_char)
print("median")
print(median) |
d0476a44ecf86885e12f4f86c70c7cf37429e5b9 | ojudz08/Python-Beginner | /Exercises/Chapter 5/Exercise1.py | 528 | 3.953125 | 4 | print('\nExercise 1. Edited Listing 5.3: Add Non Negative')
print('Exits when negative values are inputed and then sums all non negative values')
entry = 0 # Initialize, make sure loop is entered
sum = 0 # Intialize sum
print('\nEnter numbers to sum, negative number ends list: ')
while entry >= 0:
entry = eval(input())
if entry > 0:
sum += entry
print('Sum = ', sum)
print('Answer: Yes, it will achieve the same result. Once 0 is inpute as for >= 0, the total will not chanage. So same as > 0') |
40714ee3b84c3463abdc95ca86d4d5803a4f94d3 | samir-0711/Leetcode-Python | /212. Word Search II.py | 3,250 | 3.734375 | 4 | class Solution(object):
def findWords(self, board, words):
result = []
row = len(board)
col = len(board[0])
if row == 0 or board == None or words == []:
return result
trie = Trie()
for word in words:
trie.insert(word)
visited = [[False for y in range(col)] for x in range(row)]
def traverse(x, y, findWord):
if x < 0 or x >= row or y < 0 or y >= col:
return
if visited[x][y]: return
newWord = findWord + board[x][y]
if not trie.startsWith(newWord):
return
if trie.search(newWord):
result.append(newWord)
visited[x][y] = True
traverse(x - 1, y, newWord)
traverse(x + 1, y, newWord)
traverse(x, y - 1, newWord)
traverse(x, y + 1, newWord)
visited[x][y] = False
for i in range(row):
for j in range(col):
traverse(i, j, '')
return list(set(result))
class TrieNode():
def __init__(self):
self.children = {}
self.isWord = False
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for letter in word:
child = curr.children.get(letter)
if child == None:
child = TrieNode()
curr.children[letter] = child
curr = child
curr.isWord = True
def search(self, word):
curr = self.root
for letter in word:
child = curr.children.get(letter)
if child == None:
return False
curr = child
return curr.isWord
def startsWith(self, prefix):
curr = self.root
for letter in prefix:
child = curr.children.get(letter)
if child == None:
return False
curr = child
return True
words1 = ['oath', 'pea', 'eat', 'rain']
board2 = [
['o', 'a', 'a', 'n'],
['e', 't', 'a', 'e'],
['i', 'h', 'k', 'r'],
['i', 'f', 'l', 'v']
]
board2 = ["baabab","abaaaa","abaaab","ababba","aabbab","aabbba","aabaab"]
words2 = ["bbaabaabaaaaabaababaaaaababb","aabbaaabaaabaabaaaaaabbaaaba","babaababbbbbbbaabaababaabaaa","bbbaaabaabbaaababababbbbbaaa","babbabbbbaabbabaaaaaabbbaaab","bbbababbbbbbbababbabbbbbabaa","babababbababaabbbbabbbbabbba","abbbbbbaabaaabaaababaabbabba","aabaabababbbbbbababbbababbaa","aabbbbabbaababaaaabababbaaba","ababaababaaabbabbaabbaabbaba","abaabbbaaaaababbbaaaaabbbaab","aabbabaabaabbabababaaabbbaab","baaabaaaabbabaaabaabababaaaa","aaabbabaaaababbabbaabbaabbaa","aaabaaaaabaabbabaabbbbaabaaa","abbaabbaaaabbaababababbaabbb","baabaababbbbaaaabaaabbababbb","aabaababbaababbaaabaabababab","abbaaabbaabaabaabbbbaabbbbbb","aaababaabbaaabbbaaabbabbabab","bbababbbabbbbabbbbabbbbbabaa","abbbaabbbaaababbbababbababba","bbbbbbbabbbababbabaabababaab","aaaababaabbbbabaaaaabaaaaabb","bbaaabbbbabbaaabbaabbabbaaba","aabaabbbbaabaabbabaabababaaa","abbababbbaababaabbababababbb","aabbbabbaaaababbbbabbababbbb","babbbaabababbbbbbbbbaabbabaa"]
solution = Solution()
print(solution.findWords(board2, words2))
|
5c674ffcae4d6aaa4849ba8b1e044e82c883750b | rickthegeek/Week15FinalProject | /Week15FinalProject/Week15FinalProject.py | 15,981 | 3.875 | 4 | #Project: CIS 177 WEEK 15 FINAL PROJECT
#Project Location: projects\cis177\Week15Project
#File: Week15FinalProject.py
#Purpose: This is an implementation of a student information system for XYZ Community college
# for Week 15 - the final project of the year
# NOTE: The program depends on StudentClass.py
#Revision: 1.0 / 8 MAY 2017
#Created: 8 MAY 2017
#Author: Rick Miller <[email protected]>
nextAvailableStudentNumber = 10000 # This is the next available student number, We want 5 digit numbers so init it to 10000 (and it is a global)
import StudentClass
currentStudents = {} # This will be the dictionary of the studentIDs and student records
def addStudent(studentDict, Student, newStudentNumber):
# This routine will actuallt add the given student record to the given dict.
# Also, we will increment the next available student number here
global nextAvailableStudentNumber
studentDict[newStudentNumber] = Student
nextAvailableStudentNumber += 1
def printAll(studentDict):
# This routine will simply step through all the records in the given dict, print the ID, then print the record for the ID
# Note: If there are no students in the dict, tell the user and do nothing.
if len(studentDict) > 0:
print('Printing list of all students:')
for ID, Student in studentDict.items():
print('\nStudent ID:', ID) # Print a black line before each student record, for neatness
print(Student)
else:
print('No students on file. Please add some students, then try again!')
def addNewStudent(studentDict):
global nextAvailableStudentNumber
newStudentNumber = nextAvailableStudentNumber
print('Add a new student - new ID will be', newStudentNumber)
myNewStudent = StudentClass.Student()
myNewStudent.firstName = input('Student\'s first name: ')
myNewStudent.lastName = input('Students\'s last name: ')
myNewStudent.gpa = float(input('Student\'s GPA: '))
myNewStudent.major = input('Student\'s major: ')
print('\nAbout to create this student with ID', newStudentNumber)
print(myNewStudent)
isOK = input('Add this student? ')[0].lower()
if isOK == 'y':
addStudent(currentStudents, myNewStudent, newStudentNumber)
print('Student',newStudentNumber,'added!')
print('The next available ID is:', nextAvailableStudentNumber)
else:
print('Cancelled!')
def findStudentByID(studentDict):
# This function will accept an input to pass to findStudent(). Note, that
# I would have combined this function and the findStudent function into one, but
# the spec called for a function called findStudent with two paramaters.
# So, this function just gets the second paramater to pass to findStudent
try:
idToFind=int(input('Please enter the student ID to find -> '))
findStudent(studentDict, idToFind)
except ValueError:
print('Sorry, student IDs are numbers only. Returning to main menu.')
def largeGPA(studentDict):
# This function will look through the given dictionary
# and will print the information with the highest GPA
# We will look at each student ID in turn, and if the
# student's GPA is higher than the previous student's GPA
# then we will note that student's ID. If the studetnt's GPA
# is not higher than the GPA for the student on file, then
# we will skip to the next student record. Once we have checked
# all the students in the dict, the student with the highest GPA
# will be the one we recorded, and then we will print that student's info
# Note: If there are no students in the given dict, we will let the user know
# and then do nothing
if len(studentDict) > 0:
highestGPA = 0.0 # This is where we will store the highest GPA we found so far
highestGPAStudentID = 0 # This is where we will store the ID of the highest GPA found so far
for studentID in studentDict: # Check each student's record in the given dict
if studentDict[studentID].gpa > highestGPA: # if the GPA for the current student ID is higher than the one we found so far...
highestGPAStudentID = studentID # ... store their ID as the highest GPA we found so far...
highestGPA = studentDict[studentID].gpa # ... then record their GPA as the highest GPA we found so far...
print('\nStudent with the highest GPA is:') # now tell the user the student with the highest GPA
print('Student ID:',highestGPAStudentID) # NOTE: If there are two or more students with the highest GPA (as in if the highest GPA is 3.5)
print(studentDict[highestGPAStudentID]) # and more than student has that GPA, this function will return the student with the highest ID
# I would have created a list of students with sharing the highest GPA, but, the spec just said to print the student with the highest GPA...
else:
print('No students on file. Please add some students, then try again!')
def updateGPA(idToUpdate, studentDict, gpa):
# This function will check if the idToUpdate is in the dict, and if it is
# then we will update that record with the GPA given. If the ID does not exist,
# we will tell the user that no changes were made.
if idToUpdate in studentDict.keys():
studentDict[idToUpdate].gpa = gpa
print('Student ID',idToUpdate,'updated to',gpa)
else:
print('ID not found, no changes made.')
def askAndUpdateGPA(studentDict):
# This routine is a wrapper for the updateGPA functuion. It will
# ask the user for the ID of the student to update, and the new GPA, then
# pass that info to the updateGPA function. Again, I would have combined them
# all into one function, but, the spec is the spec.... :)
# Note: If there are no students in the given dict, tell the user, and do nothing.
if len(studentDict) > 0:
try: # If the user enters something other than a number, these statements will cause an exception so we want to handle it
idToUpdate = int(input('Please enter the ID for the student you want to update -> ')) # Convert the entry to an int, because the dict keys are ints
newGPA = float(input('Please enter the new GPA for the student -> ')) # and convert this entry to a float, because thats what's in the dict
updateGPA(idToUpdate, studentDict, newGPA) # finally, we update the dict with the new GPA
except ValueError: # user enters something other than a number, or nothing at all...
print('Sorry, I was expecting a number, No action taken.')
else:
print('No students on file. Please add some students, then try again!')
def findStudent(studentDict, idToFind):
# In this function we are given the dict and the id, so we are going to see if the
# student ID exists in the dictionary. If it does, then we will print the student record
# if not, we will tell the user that the ID entered is not on file.
if idToFind in studentDict.keys():
print('Information for student ID:', idToFind)
print(studentDict[idToFind])
else:
print('Sorry, that ID is not on file.')
def findGPA(studentDict, GPA):
# This routine will step through the given studentDict and will create a list
# of the student IDs where the gpa is equal or higher to the given gpa, and at
# the end, the list of the students will be printed.
gpasToPrint = [] # This will be our list of students we will need to print
for studentID in studentDict:
if studentDict[studentID].gpa >= GPA: # if the current student's GPA is higher than the GPA we are looking for...
gpasToPrint.append(studentID) # ...add it to the list
if len(gpasToPrint) > 0: # If the list is not empty, print the list
for studentId in gpasToPrint: # step through the each entry in our list
print('Student ID:', studentId) # print the ID
print(studentDict[studentId]) # and the student record for that ID
else: # we didn't find any students meeting the criteria so tell the user
print('No students found with a GPA equal to or higher than', GPA)
def askGPAsToFind(studentDict):
# This is a wrapper for the findGPA function. We will ask the user for the
# GPA to find, and then we will give that to findGPA function which will print
# the list of students with a GPA higher or equal to the GPA given.
# NOTE: As always, if the given dict is empty, tell the user and do nothing...
if len(studentDict) > 0:
try: # If the uer enters a non-numeric entry, or nothing at all, we want to handle it gracefully...
gpaToFind = float(input('Please enter the GPA to find. Students with a GPA higher than\nor equal to the given GPA will be printed. -> '))
findGPA(studentDict, gpaToFind) # convert the user's entry to a float, then call the findGPA function to actually look for the GPAs
except ValueError: # User entered a non-numeric entry or nothing at all...
print('Sorry, I was looking for a number. No action taken.\n')
else:
print('No students on file. Please add some students, then try again!')
def findMajor(studentDict, major):
# This function will search through the given studentDict for each student with
# a major equal to the given major. Note that for when comparing, all the comparisions
# will be done in lower case, so that if a student's major is entered as MATH, Math, or math,
# or even MaTh, the search will match. Each studen ID will be added to a list, then
# the students in the list will be printed.
foundStudents = [] # This is where we will keep the students we find
for studentID in studentDict:
if studentDict[studentID].major.lower() == major.lower(): # compare the lowercase version of the major in the current student record to the lowercase version of the given major
foundStudents.append(studentID) # If they match, add it to the list
if len(foundStudents) > 0: # If we found any students, print the list of the students we found...
print('Found the following students:')
for studentID in foundStudents: # Loop through the list
print('Student ID:', studentID) # ...and print each student's ID...
print(studentDict[studentID]) # ...and their record
else: # Nobody found with that major, so tell the user
print('Sorry. No students found with major', major)
def askMajorToFind(studentDict):
# This is a wrapper for the findMajor function. Here we will ask for the major to find
# and pass the given dict and the major to the findMajor function
# Also, this is where we check if the given dict is empty. if it is, we tell the user and then do nothing
if len(studentDict) > 0:
majorToFind = input('\nFind all students with which major? ')
findMajor(studentDict, majorToFind)
else:
print('No students on file. Please add some students, then try again!')
def updateMajor(studentDict, idnumber, major):
# This routine will update the record by the given idnumber in the given studentDict,
# with the given major. Once done, the user will be told it has been update, and
# if the idnumber isn't found, the user will be told that no action was taken.
if idnumber in studentDict.keys():
studentDict[idnumber].major = major
print('Record updated! New record for student',idnumber)
print(studentDict[idnumber])
else:
print('ID not found. No action taken.\n')
def askIDToUpdateMajor(studentDict):
# This routine will ask what student to update, and the new major, then will
# send that info to the updateMajor function which will handle the actual updating
# of the student record in the dictionary.
# Note: If there are no entries in the given dict, tell the user and do nothing.
if len(studentDict) > 0:
try: # If the user enters a non-numeric entry, or nothing at all, we want to handle it gracefully...
idToUpdate = int(input('What student ID would you like to upate? ')) # Find out what student ID we want to update, convert it to an int
majorToUpdate = input('Please enter the new major -> ') # and find out what major we want that student to have
updateMajor(studentDict, idToUpdate, majorToUpdate) # Note: There is no checking for what major is entered. Since it is a string, the user can enter anything and it wll be the new major
except ValueError: # User entered a non-numeric entry, or nothing at all so tell the user
print('Sorry, all Student IDs are a five digit number. No action taken.')
print('Returning to the main menu.')
else:
print('No students on file. Please add some students, then try again!')
def showMenu():
# This function simply shows the user the main menu
print('\nXYZ Community College Student Management System')
print('-----------------------------------------------')
print('A - Add student')
print('F - Find student by ID')
print('G - Find the student with the highest GPA')
print('L - List all students with a GPA equal to or higher than a given GPA')
print('M - Update a student\'s major')
print('P - Print a list of all students')
print('U - Update a student\'s GPA')
print('R - Find all students with a given majo(R)')
print('Z - Clear database and add example student data to database (debug!)')
print('Q - Quit')
def addExampleStudents(studentDict):
# This function will empty out, then add a few example students to the given studentDict
# This is primarily a debug functions, but, I'm leaving it in so the user doesn't need
# to add a bunch of students for testing.
studentDict.clear() # Clear the database
# Now, let's add some example students
addStudent(studentDict, StudentClass.Student('Rick', 'Miller', 3.55, 'Engineering'), nextAvailableStudentNumber)
addStudent(studentDict, StudentClass.Student('Steve', 'Miller', 2.51, 'Basketweaving'), nextAvailableStudentNumber)
addStudent(studentDict, StudentClass.Student('John', 'Doe', 2.01, 'Chemistry'), nextAvailableStudentNumber)
addStudent(studentDict, StudentClass.Student('Harry', 'Potter', 3.95, 'Magic'), nextAvailableStudentNumber)
addStudent(studentDict, StudentClass.Student('Ron', 'Weaseley', 3.21, 'Magic'), nextAvailableStudentNumber)
addStudent(studentDict, StudentClass.Student('Kent', 'Dorfman', 0.01, 'Chemistry'), nextAvailableStudentNumber)
print('Database cleared and example students added!')
# *** MAIN PROGRAM BEGINS HERE ***
# First, show the user the menu
showMenu()
userInput =''
# Repeat the following until the user enters 'q'
while userInput != 'q':
try:
userInput = input('\nMain Menu: Enter your choice (? for menu) -> ')[0].lower()
if userInput == 'a':
addNewStudent(currentStudents)
elif userInput == 'p':
printAll(currentStudents)
elif userInput == 'f':
findStudentByID(currentStudents)
elif userInput == 'g':
largeGPA(currentStudents)
elif userInput == 'l':
askGPAsToFind(currentStudents)
elif userInput == 'u':
askAndUpdateGPA(currentStudents)
elif userInput == 'm':
askIDToUpdateMajor(currentStudents)
elif userInput == 'z':
addExampleStudents(currentStudents)
elif userInput == 'r':
askMajorToFind(currentStudents)
elif userInput == 'q':
pass # Do nothing here, we just want to exit the loop.
else:
showMenu()
except IndexError: # user entered an empty string, or something weird happened so show them the menu.
showMenu()
# If the user entered 'q', we end up here, so it's the end of the program, so tell the user
print('End of program.') |
57a0e0c8a92291c6444c2452d1ec43edf276b636 | NIihLopes/Projetos_Pessoais | /Jogo_da_sorte.py | 829 | 3.8125 | 4 | import random
def gerando_numero_da_sorte():
numeros_da_sorte = random.randrange(1,60)
return numeros_da_sorte
def continuar():
print('** Digite 1 para gerar um Numero! **')
print('** Digite 2 para encerrar! **')
gerar_numero = int(input("digite:"))
if gerar_numero == int(1):
resposta = True
return resposta
else:
resposta = False
return resposta
jogo_premiado = []
print('** INICIO -- BOA SORTE **')
continua = continuar()
while continua:
if continua == True:
jogo_premiado.append(gerando_numero_da_sorte())
print(jogo_premiado)
continua = continuar()
elif continua == False:
break
else:
print('* resposta inválida * Tente novamente *')
continuar()
print('esse é seu jogo! ',jogo_premiado)
|
9727980d6ec22cbd23b393d00dbc3a2253bc0356 | unamfi/sistop-2020-2 | /tareas/1/LoidiJavier/elevador.py | 1,190 | 3.671875 | 4 | #!/usr/bin/python3
from threading import Semaphore, Thread
from random import randint
from time import sleep
lugares = Semaphore(5)
alumnos_a_bordo = []
total_alumnos=20
def proviene():
return randint(1,5)
def destino(este_no):
dest = randint(1,5)
while dest == este_no:
dest = randint(1,5)
return dest
def elevador():
llevados=0
while(True):
for i in alumnos_a_bordo:
print("Llevando a alumno ",i[0]," del piso ",i[1]," al piso ",i[2],". Hay ",len(alumnos_a_bordo)," a bordo")
alumnos_a_bordo.remove(i)
llevados+=1
lugares.release()
print("estado de semaforo: ",lugares._value,"\n\n")
if(llevados==total_alumnos):
return
def alumno(num):
vengo_de = proviene()
voy_a = destino(vengo_de)
print('El alumno %d viene de %d y va a %d \n' % (num, vengo_de, voy_a))
lugares.acquire()
alumnos_a_bordo.append([num,vengo_de,voy_a])
for i in range(1,total_alumnos+1):
t = Thread(target = alumno, args = [i])
t.start()
e = Thread(target = elevador, args = [])
e.start()
|
d5aae4ec195d06cd401c8f90a9039fe2c5adf0ba | surajwate/file-finder | /getfiles.py | 531 | 3.609375 | 4 | import os
def scantree(path):
"""Recursively scan a directory tree
:param str path: path to scan
:rtype: os.DirEntry
:return: DirEntry via generator
"""
for entry in os.scandir(path):
yield entry
if entry.is_dir(follow_symlinks=False):
yield from scantree(entry.path)
def showfiles(dir):
for entry in scantree(dir):
if entry.name.endswith(".md") and entry.is_file():
print(entry.name, entry.path, entry.is_file())
if __name__ == "__main__":
pass
|
8d8da8964fe8d75111b51d070f4fc8ef31421479 | amitropp/HackIDC | /maps_utils.py | 1,959 | 3.734375 | 4 | import requests
from dataframes import branches
FILE_NAME = "branches_distances.csv"
# The maximum duration travel we are allowing from out source to the destination
MAX_DURATION = 1800
our_key = "AIzaSyBcFvf4T7TWk-DQgq-YxU5Z6yZn0GvDGPs"
url = "https://maps.googleapis.com/maps/api/distancematrix/json" + \
"?units=imperial" + "&origins={0}&destinations={1}&key=" + our_key
def get_unicode(s): # pass test
if isinstance(s, unicode):
return s.encode("utf-8")
return s
def find_closest_branches(customer_address):
""" This function returns a list of branche's ids in ascending order by their distance from the costumer"""
# If the duration travel is less than the maximum - add it to the list
# The branche's ids that are in the transport distance
relevant_branches = []
min_duration = float('Inf')
min_id = -1
branches_array = []
for idx, branch in branches.iterrows():
address = branch.address
curr_url = url.format(get_unicode(address), get_unicode(customer_address))
# Convert to json format
response = requests.get(curr_url).json()
# print 'response', response
# Return the duration time from the origin to destination (in seconds)
curr_dur = response["rows"][0]["elements"][0]["duration"]["value"]
curr_id = branch.branch_id
branches_array += [(curr_id, curr_dur)]
if min_duration > curr_dur:
min_duration = curr_dur
min_id = curr_id
# sort the array by duration
sorted_list = sorted(branches_array, key=lambda x: x[1])
for i in range(len(sorted_list)):
if sorted_list[i][1] <= MAX_DURATION:
relevant_branches.append(sorted_list[i][0])
# In case that the closet branch to the customer farthest from the MAX_DURATION - return the specific branch
elif min_duration > MAX_DURATION:
return [min_id]
else:
break
return relevant_branches
|
dc6becdd2babfa4cc04f1e7f307ba0090f2d45bc | sachin121103/Small-Projects | /prime-numbers.py | 295 | 4.125 | 4 | # Find if a given number is prime
def isPrime(num):
factors_list = []
for i in range(2, num):
if num % i == 0:
factors_list.append(i)
if factors_list:
print("The number is not prime")
else:
print("The number is prime")
isPrime(4)
|
a39229aa20fbdd0140cb1281b25779c955bd2be9 | pallabbarman/python | /Basic/ifelse.py | 193 | 4.0625 | 4 | x = 10
y = 20
z = 30
if x > y:
print('x is greater than y')
elif x < y:
print('y is greater than x')
elif x == y:
print('x is equal y')
else:
print('z is greater than x and y')
|
d1266f2981bb3406f2080879dc6eded4dfabe1e9 | JLMarshall63/myGeneralPythonCode | /DateTimeFunc.py | 3,005 | 3.96875 | 4 | from datetime import datetime
dt = datetime.now()
print '%s/%s/%s' % (dt.month, dt.day, dt.year)
print dt
print dt.month
print dt.day
print dt.year
print '%s-%s-%s' % (dt.month, dt.day, dt.year)
print dt.hour
print dt.minute
print dt.second
print '%s:%s:%s' % (dt.hour, dt.minute, dt.second)
print '%s/%s/%s %s:%s:%s' % (dt.month, dt.day,
dt.year, dt.hour, dt.minute, dt.second)
import datetime
today = datetime.date.today()
print(today)
oneday = datetime.timedelta(days=1)
tomorrow = today + oneday
print("Tomorrow is: ", tomorrow)
bdate = datetime.date(1952,11,11)
print(bdate.strftime("%A"))
from datetime import datetime, timedelta
d1 = datetime(year=2017, month=9, day=11,hour=16, minute=34)
d2 = datetime(year=1952, month=11, day=11,hour=9, minute=2)
td = d1 - d2
ts = td.total_seconds()
print 'total seconds: ', ts
seconds_in_day = timedelta(days=1).total_seconds()
print 'seconds in day', seconds_in_day
days = ts/seconds_in_day
print 'days: ', days
years = days/365.2524
print years
d1 = datetime(year=2017, month=9, day=11,hour=16, minute=34)
d2 = datetime(year=1952, month=11, day=11,hour=9, minute=2)
def age_years(d1, d2):
td = d1 - d2
ts = td.total_seconds()
seconds_in_day = timedelta(days=1).total_seconds()
days = ts/seconds_in_day
years = days/365.2524
return years
print 'Years: ',age_years(d1, d2)
##
import datetime
print(dir (datetime))
gvr = datetime.date(1952,11,11)
print(gvr)
print(gvr.year)
print(gvr.month)
print(gvr.day)
print(gvr.strftime("%A,%B,%d,%Y"))
message = "John was born on {:%A,%B,%d,%Y}."
print(message.format(gvr))
mill = datetime.date(2000,1,1)
dt = datetime.timedelta(100)
print (mill + dt)
launch_date = datetime.date(2017, 3, 30)
launch_time = datetime.time(22,27,0)
launch_datetime = datetime.datetime(2017, 3, 30, 22,27,0)
print(launch_date)
print(launch_time)
print(launch_datetime)
now = datetime.datetime.today()
print(now)
moon_landing = "7/20/1969"
moon_landing_dt = datetime.datetime.strptime(moon_landing, "%m/%d/%Y")
print (moon_landing_dt)
print (type(moon_landing_dt))
xmas = datetime.date(2017, 12, 25)
print xmas
diff = xmas - today
print diff
import datetime
Year = int(input("Enter year born"))
Month = int(input("Enter month born"))
Day = int(input("Enter day born"))
dob = datetime.datetime(Year, Month, Day)
age = (datetime.datetime.now() - dob)
print("You are " + str(age.days)+ " days old.")
convertdays = int(age.days)
ageyears = convertdays/365.0
print("Or " + str(ageyears) + " years old.")
def age_of_human(Year, Month, Day):
dob = datetime.datetime(Year, Month, Day)
age = (datetime.datetime.now() - dob)
print("You are " + str(age.days)+ " days old.")
convertdays = int(age.days)
ageyears = convertdays/365.0
print("Or " + str(ageyears) + " years old.")
age_of_human(Year, Month, Day)
|
11ebf63c43d1e274c5af7b6815d983f3c07dc0d6 | wudongdong1000/Liaopractice | /practice_20.py | 576 | 3.75 | 4 | #请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性:
class Student(object):
def __init__(self,name,gender):
self.name=name
self.set_gender(gender)
def get_gender(self):
return self.__gender
def set_gender(self,gender):
if gender.title()=='Male' or 'Female':
self.__gender=gender
else:
raise ValueError('wrong value')
mike=Student('Mike','Female')
print(mike.get_gender())
mike.set_gender('male')
print(mike.get_gender()) |
ebae059dce9e615d264ddb5b97332eb2e3f9650b | PDXDevCampJuly/Summer_Lyn1 | /Week 3/test_die_roll.py | 1,610 | 3.828125 | 4 | __author__ = 'summerlynbryant'
import unittest
from Wk3_mon_die import Die
class DieRollTest(unittest.TestCase):
"""Test the functionality of the Die class' roll function"""
def setUp(self):
self.possible_values = [1, 2, 3, "Dog", "Cat", "Hippo"]
self.new_die = Die(self.possible_values)
print(self.shortDescription())
# def tearDown(self):
# del self.possible_values -----> or a print statement
# print(self._testMethodName)
def test_roll_once(self):
"""Roll the die once and ensure the value is in the possibleValues"""
self.assertIn(self.new_die.roll(), self.possible_values, "Rolled value not in possibleValues of Die")
def test_rolled_value_changes(self):
""" Roll the die a number of time and make sure it changes value"""
holding_value = self.new_die.roll()
for i in range(10):
if self.new_die.roll() != holding_value:
# print("Rolled Die value is different than Holding Value {}"
# .format(new_die.currentValue, holding_value))
self.assertTrue(True)
return
print("Die value did not change from Holding Value for 10 rolls")
self.assertTrue(False)
def test_currentValue_is_updated_to_rolled_value(self):
"""Make sure that the Die's currentValue is updated to match what is rolled."""
self.new_die.currentValue = 5
self.assertEqual(self.new_die.roll(), self.new_die.currentValue, "Current Value was not different from rolled")
if __name__ == '__main__':
unittest.main()
|
aedad14914db7624e8d65e910a1ed91beb769f45 | RomanSchigolev/Python__Lessons | /Conditional_Operator/final_work.py | 9,915 | 4.21875 | 4 | # 1. Напишите программу, которая определяет, оканчивается ли год с данным номером на два нуля.
# Если год оканчивается, то выведите «YES», иначе выведите «NO».
#
# Формат входных данных
# На вход программе подаётся натуральное число.
#
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
year = int(input())
if year % 100 == 0:
print("YES")
else:
print("NO")
# 2. Заданы две клетки шахматной доски. Напишите программу, которая определяет имеют ли указанные клетки один цвет или нет.
# Если они покрашены в один цвет, то выведите слово «YES», а если в разные цвета — то «NO».
#
# Формат входных данных
# На вход программе подаётся четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, потом для второй клетки.
#
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
col1, row1, col2, row2 = [int(input()) for _ in range(4)]
if col1 % 2 == 0 and row1 % 2 != 0 or col1 % 2 != 0 and row1 % 2 == 0:
if col2 % 2 == 0 and row2 % 2 != 0 or col2 % 2 != 0 and row2 % 2 == 0:
print("YES")
else:
print("NO")
elif col1 % 2 == 0 and row1 % 2 == 0 or col1 % 2 != 0 and row1 % 2 != 0:
if col2 % 2 == 0 and row2 % 2 == 0 or col2 % 2 != 0 and row2 % 2 != 0:
print("YES")
else:
print("NO")
else:
print("NO")
# 3. Футбольная команда набирает девочек от 10 до 15 лет включительно [10;15].
# Напишите программу, которая запрашивает возраст и пол претендента,
# используя обозначение пола буквы m (от male – мужчина) и f (от female – женщина)
# и определяет подходит ли претендент для вступления в команду или нет.
# Если претендент подходит, то выведите «YES», иначе выведите «NO».
#
# Формат входных данных
# На вход программе подаётся натуральное число – возраст претендента и буква обозначающая пол m (мужчина) или f (женщина).
#
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
age, gender = int(input()), input()
if 10 <= age <= 15 and gender == "f":
print("YES")
else:
print("NO")
# 4. Напишите программу, которая считывает целое число и выводит соответствующую ему римскую цифру.
# Если число находится вне диапазона 1-10, то программа должна вывести текст «ошибка».
# В таблице приведены римские цифры для чисел от 1 до 10.
# Формат входных данных
# На вход программе подаётся целое число.
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
# в лоб
number = int(input())
if 1 <= number <= 10:
if number == 1:
print("I")
elif number == 2:
print("II")
elif number == 3:
print("III")
elif number == 4:
print("IV")
elif number == 5:
print("V")
elif number == 6:
print("VI")
elif number == 7:
print("VII")
elif number == 8:
print("VIII")
elif number == 9:
print("IX")
elif number == 10:
print("X")
else:
print("ошибка")
# or
number = int(input())
dictionary = {1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X'}
if number < 1 or number > 10:
print("ошибка")
else:
print(dictionary[number])
# 5. Напишите программу, которая принимает на вход число и в зависимости от условий выводит текст «YES», либо «NO».
# Условия:
# если число нечётное, то вывести «YES»;
# если число чётное в диапазоне от 2 до 5 (включительно), то вывести «NO»;
# если число чётное в диапазоне от 6 до 20 (включительно), то вывести «YES»;
# если число чётное и больше 20, то вывести «NO».
# Формат входных данных
# На вход программе подаётся натуральное число.
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
number = int(input())
if number % 2 != 0:
print("YES")
elif number % 2 == 0 and 2 <= number <= 5:
print("NO")
elif number % 2 == 0 and 6 <= number <= 20:
print("YES")
elif number > 20 and number % 2 == 0:
print("NO")
# or
number = int(input())
print("YES" if number % 2 != 0 or 6 <= number <= 20 else 'NO')
# 6. Даны две различные клетки шахматной доски.
# Напишите программу, которая определяет, может ли слон попасть с первой клетки на вторую одним ходом.
# Программа получает на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки, потом для второй клетки.
# Программа должна вывести «YES», если из первой клетки ходом слона можно попасть во вторую или «NO» в противном случае.
# Формат входных данных
# На вход программе подаётся четыре числа от 1 до 8.
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
# Примечание. Шахматный слон ходит по диагоналям.
col1, row1, col2, row2 = [int(input()) for _ in range(4)]
if abs(col1 - col2) == abs(row1 - row2):
print("YES")
else:
print("NO")
# 7. Даны две различные клетки шахматной доски.
# Напишите программу, которая определяет, может ли конь попасть с первой клетки на вторую одним ходом.
# Программа получает на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки,
# потом для второй клетки. Программа должна вывести «YES», если из первой клетки ходом коня можно попасть во вторую или «NO» в противном случае.
# Формат входных данных
# На вход программе подаётся четыре числа от 1 до 8.
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
# Примечание. Шахматный конь ходит буквой «Г».
col1, row1, col2, row2 = [int(input()) for _ in range(4)]
if abs(col1 - col2) == 1 and abs(row1 - row2) == 2 or abs(col1 - col2) == 2 and abs(row1 - row2) == 1:
print("YES")
else:
print("NO")
# 8. Даны две различные клетки шахматной доски.
# Напишите программу, которая определяет, может ли ферзь попасть с первой клетки на вторую одним ходом.
# Программа получает на вход четыре числа от 1 до 8 каждое, задающие номер столбца и номер строки сначала для первой клетки,
# потом для второй клетки. Программа должна вывести «YES», если из первой клетки ходом ферзя можно попасть во вторую или «NO» в противном случае.
# Формат входных данных
# На вход программе подаётся четыре числа от 1 до 8.
# Формат выходных данных
# Программа должна вывести текст в соответствии с условием задачи.
# Примечание. Шахматный ферзь ходит по диагонали, горизонтали или вертикали.
col1, row1, col2, row2 = [int(input()) for _ in range(4)]
if col1 == col2 or row1 == row2 or abs(col1 - col2) == abs(row1 - row2):
print("YES")
else:
print("NO")
|
566e5c2d334b0ceb7b5bc6bd868f5a381b08ac15 | zentabit/pythonjects | /cipher.py | 1,293 | 4.21875 | 4 | # Nicer cipher by Email
from cipher_keys import bin_key
from cipher_keys import caesar_key
# Conversion from letters to binary
def binariate(text, key):
output = ""
output += "In my encoding, this would make:\n"
for c in text:
output += format(key.index(c), '06b') + ' '
output += "\nIn ASCII coding, that would be: \n"
for c in text:
output += format(ord(c), '08b') + ' '
return output
# Caesar cipher generator
def caesar(steps, text, key):
stepped = ""
for char in text: # For every char in the input
if char == " ": # Check if char is whitespace, in that case just add a whitespace
stepped += char
elif (key.index(char) + steps) > (len(key) - 1): # Else if the address we are looking for overflows, go to the beginning and add correct char
stepped += key[((key.index(char) + steps) - len(key))]
else: # Else just add the char that is n steps away
stepped += key[(key.index(char) + steps)]
return stepped
ch = input("Select a choice, 1 for binary, 2 for caesar: ")
if ch is "1":
print(binariate(input("Text to convert: "), bin_key))
elif ch is "2":
print(caesar(text=input('Text to chiffrera: '), steps=int(input("How many steps? ")), key=caesar_key))
|
81c80c0dd8d7a8406b87018546fd4c8d72fa69d4 | adriaanbd/data-structures-and-algorithms | /Python/trees/binary/dfs_traversals.py | 1,444 | 4.28125 | 4 | """
DFS Workbook
In this workbook we will try out the three main types of
Depth First Binary Tree Traversal: Pre-order, In-order and Post-order.
In each of the cells below you will implement a pre, in and post order
traversal of the tree by printing the node's value when you visit it.
Before we traverse anything though, we need a binary tree to traverse.
The following code creates implements a simple Tree class and creates a tree
called my_tree with the following stucture:
A
/ \
B C
/ \
D E
\
F
"""
class Tree:
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value
def __str__(self):
return str(self.value)
def print_tree_preorder(tree):
"""
Implement a pre-order traversal here
Args:
tree(object): A binary tree input
Returns:
None
"""
def print_tree_inorder(tree):
"""
Implement a in-order traversal here
Args:
tree(object): A binary tree input
Returns:
None
"""
def print_tree_postorder(tree):
"""
Implement a post-order traversal here
Args:
tree(object): A binary tree input
Returns:
None
"""
f = Tree("F")
e = Tree("E", None, f)
d = Tree("D")
b = Tree("B", d, e)
c = Tree("C")
a = Tree("A", b, c)
my_tree = a
print_tree_preorder(my_tree)
print_tree_inorder(my_tree)
print_tree_postorder(my_tree) |
29eb123a0c24bdfef14fcc900b2c8faa7e819dea | Dr-Jinay/Hacker-Rank-Python-coding-practice | /writeafunction.py | 407 | 3.9375 | 4 | # Write a function in Python - Hacker Rank Solution
def is_leap(year):
leap = False
# Write your logic here
# Write a function in Python - Hacker Rank Solution START
if year%400==0 :
leap = True
elif year%4 == 0 and year%100 != 0:
leap = True
return leap
# Write a function in Python - Hacker Rank Solution END
year = int()
print (is_leap(year)) |
4a0ebcc56687b2d5752b87dde72cee4d8adcf6fd | sivaprasadreddynooli/Python_tutorials_for_beginners- | /Fibonacci_series.py | 414 | 4.1875 | 4 | #cube = lambda x: # complete the lambda function
def fibonacci(n):
l = []
if n == 1:
l= [0]
if n == 2:
l = [0,1]
if n > 2:
l = [0,1]
for i in range(2,n):
l.append(l[i-1] + l[i-2])
return l
# return a list of fibonacci numbers
def cube(x):
return x**3
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) |
e1cc06636717ff5574b2e11a1ec00639a1adda85 | gabrysb/210CT | /Question11.py | 1,444 | 4.28125 | 4 | class Node(object):
def __init__(self, value):
self.value=value
self.next=None
self.prev=None
class List(object):
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existing list?
if n!=None:
x.next=n.next
n.next=x
x.prev=n
if x.next!=None:
x.next.prev=x
if self.head==None:
self.head=self.tail=x
x.prev=x.next=None
elif self.tail==n:
self.tail=x
def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print "List: ",",".join(values)
if __name__ == '__main__':
l=List()
l.insert(None, Node(4))
l.insert(l.head,Node(6))
l.insert(l.head,Node(8))
l.display()
""" Implement the node delete function in the programming language of your choice based on the template provided."""
def delete(self,x):
"""Takes the links from the surrounding nodes and removes the node in question by omitting it from the chain of links."""
if x.prev != None:
x.prev.next = x.next
else:
self.head = x.next
if x.next != None:
x.next.prev = x.prev
else:
self.tail = x.prev
|
7affe1ed4c561ae915784ac28020c7a6c73df24d | duanxuepeng11/Alive | /pythonDemo/函数式编程/高阶函数.py | 1,389 | 3.609375 | 4 | print(abs(-19))
# abs = 10
# print(abs(-19))
# 函数可以作为参数传递
def add(x,y,f):
return f(x) + f(y)
print(add(-3,5,abs))
def f(x):
return x*x
r = map(f,[1,2,3,4,5])
print(list(r))
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
from functools import reduce
def add(x,y):
return x+y
print(reduce(add,[1,2,3,4,5]))
list1 = [1,2,3,45]
print(sum(list1))
def fn(x,y):
return x*10 + y
print(reduce(fn,[1,3,5,7,9]))
# print({'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}['13579'])
def toUpp(str):
name = str[0].upper()+str[1:].lower()
return name
L1 = ['adam', 'LISA', 'barTfddFdas']
L2 = list(map(toUpp, L1))
print(L2)
def is_odd(n):
return n % 2 == 1
filter1 = list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))
print(filter1)
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
# 结果: ['A', 'B', 'C']
sorted([36, 5, -12, 9, -21])
sor1 = sorted([36, 5, -12, 9, -21], key=abs)
print(sor1)
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
#排序都是默认小——》大顺序排列的
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower,reverse=True) #反向排序
L = [('Aob', 75), ('Adam', 92), ('Bart', 66), ('Esa', 88)]
def mysorted(t):
print(t[0],"===",t[1])
return t[0].lower()
pass
res = sorted(L,key=mysorted)
print(res)
|
c52fbe1111d1d26b4b558a5f94f24b9109f41d43 | davidadamojr/data_science_from_scratch | /network_analysis/centrality.py | 3,270 | 3.625 | 4 | from collections import deque
def shortest_paths_from(from_user):
# a dictionary from "user_id" to *all* shortest paths to that user
shortest_paths_to = { from_user["id"] : [[]] }
# a queue of (previous user, next user) that we need to check
# starts out with all pairs (from_user, friend_of_from_user)
frontier = deque((from_user, friend)
for friend in from_user["friends"])
# keep going until we empty the queue
while frontier:
prev_user, user = frontier.popleft() # remove the user who is first in the queue
user_id = user["id"]
# because of the way we are adding to the queue,
# necessarily we already know some shortest paths to prev_user
paths_to_prev_user = shortest_paths_to[prev_user["id"]]
new_paths_to_user = [path + [user_id] for path in paths_to_prev_user]
# it is possible we already know a shortest path
old_paths_to_user = shortest_paths_to.get(user_id, [])
# what is the shortest path to here that we have seen so far?
if old_paths_to_user:
min_path_length = len(old_paths_to_user[0])
else:
min_path_length = float('inf')
# only keep paths that are not too long and are actually new
new_paths_to_user = [path
for path in new_paths_to_user
if len(path) <= min_path_length
and path not in old_paths_to_user]
# add never-seen neighbors to the frontier
frontier.extend((user, friend)
for friend in user["friends"]
if friend["id"] not in shortest_paths_to)
return shortest_paths_to
users = [
{"id": 0, "name": "Hero"},
{"id": 1, "name": "Dunn"},
{"id": 2, "name": "Sue"},
{"id": 3, "name": "Chi"},
{"id": 4, "name": "Thor"},
{"id": 5, "name": "Clive"},
{"id": 6, "name": "Hicks"},
{"id": 7, "name": "Devin"},
{"id": 8, "name": "Kate"},
{"id": 9, "name": "Klein"}
]
friendships = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)]
for user in users:
user["friends"] = []
user["shortest_paths"] = shortest_paths_from(user)
user["betweenness_centrality"] = 0.0
for i, j in friendships:
# this works because user[i] is the user whose id is i
users[i]["friends"].append(users[j]) # add i as a friend of j
users[j]["friends"].append(users[i]) # add j as a friend of i
for source in users:
source_id = source["id"]
for target_id, paths in source["shortest_paths"].iteritems():
if source_id < target_id: # do not double count
num_paths = len(paths) # how many shortest paths?
contrib = 1 / num_paths
for path in paths:
for id in path:
if id not in [source_id, target_id]:
users[id]["betweenness_centrality"] += contrib
def farness(user):
"""the sum of the lengths of the shortest paths to each other user"""
return sum(len(paths[0])
for paths in user["shortest_paths"].values())
for user in users:
user["closeness_centrality"] = 1 / farness(user) |
f70b182127d08471d093c0b2615b1392fbd2e16c | HBharathi/Python-Programming | /Class.py | 202 | 3.734375 | 4 | class Point:
def move(self):
print("draw a line")
def join(self):
print("join the points")
point1 = Point()
point1.x=10
point1.y=20
point1.join()
point1.move()
print(point1.x)
|
f441571b92d50bbefd70bd4a7d448aef8ddb2b68 | wliustc/study_higher_python3 | /LEGB/装饰器.py | 533 | 3.734375 | 4 | # coding=utf-8
def outer(func):
print('ahaha')
def inner(msg):
print('before do...')
func(msg)
print('after do...')
return inner
print('1')
@outer
def do(msg):
print('do %s...' % msg)
print('2')
def outer1(func):
def inner():
print('outer 1')
func()
return inner
def outer2(func):
def inner():
print('outer 2')
func()
return inner
@outer2
@outer1
def did():
print('did something...')
msg = 'chicken'
for i in range(10):
do(msg)
did() |
7e853e907e0c71bf739de178ffe1bb1f0e6b6145 | douglasmsi/sourcePython | /loop.py | 184 | 3.953125 | 4 | #!/usr/bin/python3
soma = 0
while True:
num = int(input("Digite um numero ou 0 para sair : "))
if num == 0:
break
soma += num
print('Total: {}'.format(soma))
|
8579af3991fd9d9e766e429d42cf003aeb087980 | pallavipsap/Two-Pointers-2 | /240_search_a_2D_matrix_II.py | 803 | 3.90625 | 4 | # June 11, 2020
# Try different approaches ( think if heaps can work)
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# Time complexity : O(m^n)
# Pass through the entire matrix
# Space compexity : O(1)
# No extra space needed, just traverse and compare
# Method 1: Brute force
'''
- Searching through the entire matrix
'''
# does not work in leetcode
row = len(matrix)
col = len(matrix[0])
for i in range(row):
for j in range(col):
if matrix[row][col] == target:
return True
return False
|
9be5654c5c67e0e61b08aff76fa535436eed2edf | fwang1395/LeetCode | /python/String/ReverseInteger.py | 1,059 | 4.21875 | 4 | #!/usr/bin/python
# _*_ coding:UTF-8 _*_
'''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2的31幂, 2的31幂 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x == 0:
return x
flag = "-" if x<0 else ""
string_y = str(abs(x))[::-1]
while string_y[0] == '0':
length = len(string_y)
string_y = string_y[1::] if length>1 else "0"
string_y = flag+string_y
ret = int(string_y)
return ret if ret >= -2147483648 and ret < 2147483648 else 0
if __name__ == '__main__':
solution = Solution()
x = 0
print solution.reverse(x)
|
ded38559de45675f052939817c994c12a4b14fa2 | harish-999/my_py_codes | /cube of a number.py | 93 | 4.0625 | 4 | num = float(input('enter a number'))
cu = num * num * num
print('the cube of',num,'is :',cu)
|
0eb04051faba307307c14e6836ea736effebab30 | FrodeWY/Python_test01 | /src/test04/CustomizeClass.py | 3,196 | 3.984375 | 4 | class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return 'student name:' + self.name
s = Student('wy')
print(s)
class Fib:
def __init__(self):
self.a, self.b = 1, 1
# 如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,
# 该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。
def __iter__(self):
return self
def __next__(self):
if self.a > 10000:
raise StopIteration()
self.a, self.b = self.b, self.a + self.b
return self.a
# 表现得像list那样按照下标取出元素,需要实现__getitem__()方法:
def __getitem__(self, item):
a, b = 1, 1
if isinstance(item, int):
for i in range(item):
a, b = b, a + b
return a
if isinstance(item, slice):
start = item.start
if start is None:
start = 0
stop = item.stop
L = []
for i in range(stop):
if i >= start:
L.append(a)
a, b = b, a + b
return L
# 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性,这样,我们就有机会返回score的值
def __getattr__(self, item):
if item == 'age':
return 99
if item == 'score':
return lambda: 25
raise AttributeError('student has no attribute %s' % item)
f = Fib()
# for i in Fib():
# print(i)
print(f[2])
print(f[:5])
print(f.age)
print(f.score)
print(f.score())
# 注意到任意调用如s.abc都会返回None,这是因为我们定义的__getattr__默认返回就是None。要让class只响应特定的几个属性,我们就要按照约定,抛出AttributeError的错误:
# print(f.ss)
class Chain:
def __init__(self, path='api'):
self._path = path
def __getattr__(self, item):
return Chain("%s/%s" % (self._path, item))
def __str__(self):
return self._path
print(Chain().status.user.list)
class Student2:
def __init__(self, name):
self.name = name
def print2(self):
print("print2")
def __call__(self, *args, **kwargs):
print("my name is %s" % self.name)
Student2.print2(Student2('sd')) # 等同实例变量调用,直接使用类调用要传一个实例
# 任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。请看示例
s = Student2("lili")
s()
# 怎么判断一个变量是对象还是函数呢?其实,更多的时候,我们需要判断一个对象是否能被调用,能被调用的对象就是一个Callable对象,比如函数和我们上面定义的带有__call__()的类实例:
print(callable(Student2('ss')))
print(callable(Student('ss')))
print(callable(max))
|
a9146b87d9662332ca08b4dbdf0b17d9b80c9566 | samruddhi221/Python_DS_Algo | /OOP_in_python/Examples/AmazonLockerHub.py | 6,522 | 4.15625 | 4 | """
Problem Statement:
1. Find the right locker for the package according to its size.
lockerSize >= packageSize
2. only 1 package in a locker
Functional Requirements:
1. User:
- Open the locker with the code
- pick the package
2. Delivery Guy:
- place the package to the locker
3. Locker System:
- find the available lockers
- generate code
- send the generated code to the user
- keep track of empty and full lockers
ASSUME: there is always an available locker
flow of events:
1. Delivery Person reaches the hub with n
"""
from enum import Enum
import numpy as np
import uuid
class Size(Enum):
small = 1
medium = 2
large = 3
class PackageStatus(Enum):
shipped = 1
in_transit = 2
delivered = 3
class Locker:
"""
1. add package
2. remove package
"""
def __init__(self, size: Size, id: int):
self.id = id
self.size = size
self.package = None
def addPackage(self, package: Package)->None:
self.package = package
def removePackage(self):
self.package = None
class Code:
def __init__(self):
self.uuid = uuid.uuid1()
def __eq__(self, other):
return self.uuid == other.uuid
class User:
"""
1. generate code
2. notify user
"""
def __init__(self, name, address):
self.user_name = name
self.address = address
self.code = None
def generate_code(self):
self.code = Code()
def notify(self):
# send code to user
print("code sent to the recepient.")
def authenticate_user(self, code):
return self.code == code
class Package:
"""
"""
def __init__(self, size: Size, id: int, user: User, status: PackageStatus):
self.id = id
self.size = size
self.state = status
self.recipient = user
def delivered(self, package):
self.state = PackageStatus.delivered
class LockerManager:
"""
1. receive the package
2. check if the locker is available
3. accept/reject package
4. assign and update locker state
5. authenticate user
6. deliver package and update the locker state
"""
def __init__(self, id, locationId):
self.id = id
self.locationId = locationId
self.n_small = 10 # 10
self.n_medium = 10 # 10
self.n_large = 10 # 10
self.smallEmpty = [Locker(Size.small, i) for i in range(self.n_small)]
self.smallFull = []
self.mediumEmpty = [Locker(Size.medium, i+self.n_small) for i in range(self.n_medium)]
self.mediumFull = []
self.largeEmpty = [Locker(Size.large, i+self.n_small+self.n_medium) for i in range(self.n_large)]
self.largeFull = []
self.lockerUserMap = {}
self.assignLockerMap = {}
def receive_package(self, pacuserkage: Package) -> bool:
"""
:param package: package object
:return: True if package is accepted(assigned locker) in the locker
"""
locker = self.__find_locker(package)
if not locker:
return False # None of the lockers are free, reject the package
else:
# assign package to locker
locker.addPackage(package)
# # assign code to the locker
# self.assignLockerMap[code] = locker
# notify user
locker.package.recipient.notify()
# move package to occupied list
self.__update_locker_state_to_occupied(locker)
return True
def deliver_package(self, code:Code) -> bool:
"""
1. Verify the code
2. Open the locker and deliver package
3. update the locker state
:param code:
:return: True if package was successfully delivered else false
"""
locker = self.__get_locker_from_code(code)
if not locker:
return False
locker.package.delivered()
self.__update_locker_state_to_empty(locker)
return True
def __find_locker(self, package: Package):
if len(self.smallEmpty)+len(self.mediumEmpty)+len(self.largeEmpty) == 0:
return None
else:
package_size = package.size
if package_size == Size.large:
return self.__get_large_locker()
elif package_size == Size.medium:
locker = self.__get_medium_locker()
if not locker:
locker = self.__get_large_locker()
return locker
elif package_size == Size.small:
locker = self.__get_small_locker()
if not locker:
locker = self.__get_medium_locker()
if not locker:
locker = self.__get_large_locker()
return locker
def __get_small_locker(self):
if len(self.smallEmpty) > 0:
locker = self.smallEmpty.pop()
return locker
else:
return None
def __get_medium_locker(self):
if len(self.mediumEmpty) > 0:
locker = self.mediumEmpty.pop()
return locker
else:
return None
def __get_large_locker(self):
if len(self.largeEmpty) > 0:
locker = self.largeEmpty.pop()
return locker
else:
return None
def __update_locker_state_to_occupied(self, locker: Locker):
if locker.size == Size.small:
self.smallFull.append(locker)
elif locker.size == Size.medium:
self.mediumFull.append(locker)
else:
self.largeFull.append(locker)
def __get_locker_from_code(self, code: Code):
for locker in self.smallFull:
if locker.package.recipient.authenticate_user(code):
return locker
for locker in self.mediumFull:
if locker.package.recipient.authenticate_user(code):
return locker
for locker in self.largeFull:
if locker.package.recipient.authenticate_user(code):
return locker
return None
def __update_locker_state_to_empty(self, locker: Locker):
if locker.size == Size.small:
self.smallFull.remove(locker)
self.smallEmpty.append(locker)
elif locker.size == Size.medium:
self.mediumFull.remove(locker)
self.mediumEmpty.append(locker)
else:
self.largeFull.remove(locker)
self.largeEmpty.append(locker)
|
85bf81464ccc8ba3fd96219906d0a2b3b58f66f6 | bongjour/effective_python | /part2/doco.py | 1,032 | 4.09375 | 4 | import time
class Timer(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
start_time = time.time()
result = self.func(*args, **kwargs)
end_time = time.time()
print("실행시간은 {time}초 입니다.".format(time=(end_time - start_time)))
return result
def get_timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print("실행시간은 {time}초 입니다.".format(time=(end_time - start_time)))
return result
return wrapper
@get_timer
@Timer
def fibonacci_iterative(n):
prev_n, cur_n = 0, 1
i = 1
while i < n:
cur_n, prev_n = cur_n + prev_n, cur_n
i += 1
return cur_n
@get_timer
def fibonacci_recursive(n):
if n == 0 or n == 1:
return n
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
fibonacci_iterative(200)
# fibonacci_recursive(200)
|
7b4d2c66b712d4c1d69cdde950dfa1fbefd51471 | hjlarry/practise-py | /standard_library/Concurrency/Subprocess/subprocess_basic.py | 2,081 | 3.625 | 4 | """
subprocess 模块提供了了三个 API 处理进程:
1. Python 3.5 中添加的 run() 函数,是一个运行进程的 API,也可以收集其输出
2. call(),check_call() 以及 check_output() 是从 Python2 继承的较早的高级 API。
3. 类 Popen 是一个低级 API,用于构建其他的 API 以及用于更复杂的进程交互。Popen 构造函数接受参数设置新进程,以便父进程可以通过管道与它通信。
"""
import subprocess
print("一、 subprocess.run()")
completed = subprocess.run(["ls", "-l"])
print("return code:", completed.returncode)
# shell为True则subprocess创建一个新的中间shell进程运行命令。默认的行为是直接运行命令
completed = subprocess.run("echo $HOME", stdout=subprocess.PIPE, shell=True)
print("returncode:", completed.returncode)
print(completed.stdout)
print()
print("二、 是否验证错误")
try:
subprocess.run(["false"], check=True)
except subprocess.CalledProcessError as err:
print("ERROR:", err)
try:
subprocess.run(["false"])
except subprocess.CalledProcessError as err:
print("ERROR?:", err)
print()
print("三、 不同的stdout设置")
try:
completed = subprocess.run(
"echo to stdout; echo to stderr 1>&2; exit 1",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except subprocess.CalledProcessError as err:
print("ERROR:", err)
else:
print("returncode:", completed.returncode)
print("stdout is {!r}".format(completed.stdout))
print("stderr is {!r}".format(completed.stderr))
# 某些情况下,输出不应该被展示和捕获,使用 DEVNULL 抑制输出流。
try:
completed = subprocess.run(
"echo to stdout; echo to stderr 1>&2; exit 1",
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except subprocess.CalledProcessError as err:
print("ERROR:", err)
else:
print("returncode:", completed.returncode)
print("stdout is {!r}".format(completed.stdout))
print("stderr is {!r}".format(completed.stderr))
|
689ef61a7cfa09496ae8d5861add63d3311cee7a | mingyyy/onsite | /week_01/05_lists/Exercise_02.py | 502 | 4.09375 | 4 | '''
Given the two lists below, find the elements that are the same
and put them in a new list.
Put the elements that are different in another list.
Print both.
'''
list_one = [0, 4, 6, 18, 25, 42, 100]
list_two = [1, 4, 9, 24, 42, 88, 99, 100]
common_list = []
other_list = []
for i in list_one:
if i in list_two:
common_list.append(i)
else:
other_list.append(i)
for i in list_two:
if i not in list_one:
other_list.append(i)
print(common_list)
print(other_list) |
36fa465f0e35dc493b3fadc587464ca4e7921be1 | aflaxman/performance_of_insilicova_replication_archive | /src/metrics.py | 13,539 | 3.796875 | 4 | from __future__ import division
import math
import pandas as pd
import numpy as np
def calc_sensitivity(cause, actual, predicted):
"""Calculate sensitivity for a single cause
Sensitivity is also known true positive rate, recall, or probability of
detection. It is the number of correct predictions for the given cause
over the total number of predictions for the cause:
.. math::
sensitivity = \\frac{TP}{P} = \\frac{TP}{TP + FN}
where TP is the number of true postives prections, P is the number of true
positives in the sample, and FN is the number of false positives
predictions.
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Returns:
float
"""
true_positive = ((actual == cause) & (predicted == cause)).sum()
n_predicted = (actual == cause).sum()
return true_positive / n_predicted if n_predicted else np.nan
def calc_specificity(cause, actual, predicted):
"""Calculate specificity for a single cause
Specificity is also know as the true negative rate. It is the number of
prediction which are correctly determined to not be the given cause over
the total number that to not belong to the cause
.. math::
specificity = \\frac{TN}{N} = \\frac{TN}{TN + FP}
where TN is the number of true negatives predictions, N is the number of
samples which are not the given cause, and FP is the number of false
positive predictions.
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Returns:
float
"""
true_negative = ((actual != cause) & (predicted != cause)).sum()
n_not_cause = (actual != cause).sum()
return true_negative / n_not_cause if n_not_cause else np.nan
def calc_positive_predictive_value(cause, actual, predicted):
"""Calculate positive predictive value (PPV) for a single cause
Positive predictive value is also known as precision. It is the number of
correct predictions for a given cause over the total number of predictions
of the cause:
.. math::
PPV = \\frac{TP}{PP} = \\frac{TP}{TP + FP}
where TP is the number of true positive predictions, PP is the number of
positive predictions, and FP is the number of false positive predictions.
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Returns:
float
"""
true_positive = ((actual == cause) & (predicted == cause)).sum()
n_called = (predicted == cause).sum()
return true_positive / n_called if n_called else np.nan
def calc_negative_predictive_value(cause, actual, predicted):
"""Calculate negative predictive value (NPV) for a single cause
Negative predictive value is the number of prediction correctly determined
to not belong to the given cause over the total number of predicted to
not be the cause:
.. math::
NPV = \\frac{TN}{NP} = \\frac{TN}{TN + FP}
where TN is the number of true negative predictions, NP is the number of
negative predictions, and FP is the number of false positive predictions.
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Returns:
float
"""
true_negative = ((actual != cause) & (predicted != cause)).sum()
n_not_predicted = (predicted != cause).sum()
return true_negative / n_not_predicted if n_not_predicted else np.nan
def calc_specific_accuracy(cause, actual, predicted):
"""Calculate accuracy for a single cause
Accuracy for a single cause is the number of predictions correctly
classified with regard to this cause over the entire population.
Misclassification of other labels among true negative predictions does
not affect this statistic.
.. math::
accuracy = \\frac{TP + TN}{TP + FP + FN + TN}
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Returns:
float
"""
true_positive = ((actual == cause) & (predicted == cause)).sum()
true_negative = ((actual != cause) & (predicted != cause)).sum()
return (true_positive + true_negative) / len(actual)
def calc_overall_correctness(actual, predicted):
"""Calculate the proportion of correct individual-level predictions
Args:
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level prediction
Return:
float
"""
return (actual == predicted).sum() / len(actual)
def calc_ccc(cause, actual, predicted):
"""Calculate chance-corrected concordance for a single cause
Chance corrected metrics are derived from the general equation:
.. math::
K_j = \\frac{P(observed)_j - P(expected)_j}{1 - P(expected)_j}
where K\ :sub:`J` is the corrected statistic for class j, P(observed)\
:sub:`j` is the observed probability of j, and P(expected)\ :sub:`j` is
the expected probability of j.
Concordance is a multiclass generalization of sensitivity which captures
number of observation on the diagonal of the misclassification matrix over
the whole sample. This is corrected for chance by making the naive
assumption that the likelihood of predicting a given cause purely by chance
is uniformly distributed across cause. This differs from Cohen's kappa
which assumes the likelihood of predicting a cause purely due to chance is
a function of its true prevalences in the sample. The naive assumption
gives estimates which are more comparable across study populations with
different true underlying cause distributions and across studies which use
different number of causes. For cause j, CCC is calculated as:
.. math::
CCC_j = \\frac{\\Big( \\frac{TP_j}{TP_j + FN_j}\\Big) - (\\frac{1}{N})}
{1 - (\\frac{1}{N})}
where TP is the true positive rate and FN is the false negative rate
and N is the total number of observations.
Args:
cause: a label in the actual and predicted series
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
Returns:
float
"""
sensitivity = calc_sensitivity(cause, actual, predicted)
chance = 1 / len(actual.unique())
return (sensitivity - chance) / (1 - chance)
def agg_cause_specific_metrics(agg, metric, actual, predicted, weights=None):
"""Aggregate cause specific metrics into a single estimate
It is useful to have a single performance metric at the individual-level.
Some metrics only produce cause-specific estimates. These estimates can be
aggregated in different ways to produce a single overall performance
estimate.
Args:
agg (function): A function to aggregate across cause-specific estimates
with the following sigature (sequence [, weights]) --> float where
weights is a sequence with the same length as the number of actual
prediction labels.
metric (function): A function to compute cause specific metrics withthe
following sigature: (label, pd.Series, pd.Series) --> float where
label is a str or int value in the series.
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
weights (bool or sequence): use the true distribution as weights when
aggregating across causes
Returns:
float
Example:
>>> agg_cause_specific_metrics(np.median, calc_ccc, actual, predicted)
>>> agg_cause_specific_metrics(np.average, calc_ccc, actual, predicted,
weights=True)
"""
causes = actual.unique()
if weights is True:
csmf_true = (actual.value_counts() / len(actual)).loc[causes].values
w = {'weights': csmf_true}
elif weights:
w = weights
else:
w = dict()
return agg([metric(cause, actual, predicted) for cause in causes], **w)
def calc_mean_ccc(actual, predicted):
"""Calculate mean chance-corrected concordance across all causes
Murray et al. recommend using the unweighted mean of the cause-specific
chance-corrected concordance as an overall estimate of individual-level
performance.
Args:
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
Returns:
float
"""
return agg_cause_specific_metrics(calc_ccc, np.mean, actual, predicted)
def calc_median_ccc(actual, predicted):
"""Calculate median chance-corrected concordance across all causes
Args:
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
Returns:
float
"""
return agg_cause_specific_metrics(calc_ccc, np.median, actual, predicted)
def calc_csmf_accuracy_from_csmf(actual, predicted):
"""Calculate Cause-Specific Mortality Fraction (CSMF) accuracy from CSMF
estimates
.. math::
CSMF Accuracy = 1 - \\frac{\\sum_{j=1}^k |CSMF_j^{true}-CSMF_j^{pred}|}
{2 \\Big(1 - Minimum\\Big(CSMF_j^{true}\\Big)\\Big)}
Args:
actual (pd.Series): true population level CSMFs
predicted (pd.Series): predicted population level CSMFs
Returns:
float
"""
if not np.allclose(actual.sum(), predicted.sum(), 1):
raise ValueError('CSMFs must sum to 1.')
return 1 - (predicted - actual).abs().sum() / (2 * (1 - actual.min()))
def calc_csmf_accuracy(actual, predicted):
"""Calculate Cause-Specific Mortality Fraction (CSMF) accuracy from
individual level predictions
Args:
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
Returns:
float
"""
csmf_pred = pd.Series(predicted).value_counts(dropna=False) / len(actual)
csmf_true = pd.Series(actual).value_counts(dropna=False) / len(actual)
# Drop causes in the prediction which do not appear in the actual
csmf_pred = csmf_pred.loc[csmf_true.index].fillna(0)
return calc_csmf_accuracy_from_csmf(csmf_true, csmf_pred)
def correct_csmf_accuracy(uncorrected):
"""Correct Cause-Specific Mortality Fraction accuracy for chance
Chance corrected metrics are derived from the general equation:
.. math::
K_j = \\frac{P(observed)_j - P(expected)_j}{1 - P(expected)_j}
where K\ :sub:`j` is the corrected statistic for class j, P(observed)\
:sub:`j` is the observed probability of j, and P(expected)\ :sub:`j` is
the expected probability of j. It can be shown analytically and through
simulation, that the expected CSMF accuracy tends towards 1 - e\ :sup:`-1`
as the number of samples and classes tend towards infinity:
.. math::
\\lim_{N, j \\to \\infty} P(expected)_j = 1 - e^{-1}
We use this approximation to correct CSMF accuracy for chance regardless
of the number of samples or class:
.. math::
CCCSMF = \\frac{CSMF - (1 - e^{-1})}{1 - (1 - e^{-1})}
\\approx \\frac{CSMF - 0.632}{1 - 0.632}
This provides a more interpretable metric in which 1.0 is perfect,
0.0 is equivalent to chance and negative values are worst than chance.
Args:
uncorrected (float): Cause-Specific Mortality (CSMF) accuracy
Returns:
float
"""
return (uncorrected - (1 - math.e**-1)) / (1 - (1 - math.e**-1))
def calc_cccsmf_accuracy(actual, predicted):
"""Calculate Chance-Corrected CSMF accuracy from individual level
predictions
Args:
actual (pd.Series): true individual level classification
predicted (pd.Series): individual level predictions
Returns:
float
"""
return correct_csmf_accuracy(calc_csmf_accuracy(actual, predicted))
def calc_cccsmf_accuracy_from_csmf(actual, predicted):
"""Calculate Chance-Corrected Cause-Specific Mortality Fraction (CSMF)
accuracy from CSMF estimates
Args:
actual (pd.Series): true population level CSMFs
predicted (pd.Series): predicted population level CSMFs
Returns:
float
"""
csmf = calc_csmf_accuracy_from_csmf(actual, predicted)
return correct_csmf_accuracy(csmf)
def calc_median_and_ui(arr, n=500, random_state=None):
"""Calculate median and uncertain in median via bootstrapping.
Args:
arr: sequence of values to calculate statistics over
n: number of bootstraps to perform
Returns:
tuple:
* median (float)
* uncertainty: tuple of floats, lower and upper bounds
"""
if not random_state:
random_state = np.random.RandomState()
sampled = [np.median(random_state.choice(arr, len(arr)))
for _ in range(500)]
return np.median(arr), tuple(np.percentile(sampled, (2.5, 97.5)))
|
b3d079787e65ec9f494d7e0f36f04d5c47af0174 | BrentLittle/100DaysOfPython | /Day019 - Instances, State and Higher Order Functions/turtleRace.py | 945 | 4.0625 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
screen.setup(width = 500, height = 400)
isRaceOn = False
userBet = screen.textinput(title = "Make a Bet", prompt = "Enter a color: ")
turtleColors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtleObjects = []
xLoc, yLoc = -230, -100
for color in turtleColors:
turtle = Turtle(shape = "turtle")
turtle.color(color)
turtle.penup()
turtle.goto(x = xLoc, y = yLoc)
turtleObjects.append(turtle)
yLoc += 40
if userBet:
isRaceOn = True
while isRaceOn:
for turtle in turtleObjects:
turtle.forward(random.randint(0,10))
if turtle.xcor() > 230:
isRaceOn = False
if turtle.color() == userBet.lower():
print("You Win!")
else:
print("Thanks for playing!")
print(f"The Winner of the Race was the {turtle.color()[0]} turtle")
screen.exitonclick() |
741b65cb559112836b72bd80663ce104cb9db149 | foobar167/junkyard | /simple_scripts/polygon_drawing.py | 21,505 | 3.546875 | 4 | # Drawing polygon on the image
import tkinter as tk
from tkinter import ttk
from datetime import datetime
from PIL import Image, ImageTk
class AutoScrollbar(ttk.Scrollbar):
""" A scrollbar that hides itself if it's not needed.
Works only if you use the grid geometry manager """
def set(self, lo, hi):
if float(lo) <= 0.0 and float(hi) >= 1.0:
self.grid_remove()
else:
self.grid()
ttk.Scrollbar.set(self, lo, hi)
def pack(self, **kw):
raise tk.TclError('Cannot use pack with the widget ' + self.__class__.__name__)
def place(self, **kw):
raise tk.TclError('Cannot use place with the widget ' + self.__class__.__name__)
class CanvasImage:
""" Image on the canvas """
def __init__(self, parent, impath):
""" Initialize the canvas """
# Create frame container for the canvas and scrolling bars. Make it expandable
self.imframe = ttk.Frame(parent) # parent of the CanvasImage objects
# Vertical and horizontal scrollbars for canvas
vbar = AutoScrollbar(self.imframe, orient='vertical')
hbar = AutoScrollbar(self.imframe, orient='horizontal')
vbar.grid(row=0, column=1, sticky='ns')
hbar.grid(row=1, column=0, sticky='we')
# Create canvas and put image on it
self.canvas = tk.Canvas(self.imframe, highlightthickness=0,
xscrollcommand=hbar.set, yscrollcommand=vbar.set)
self.canvas.grid(row=0, column=0, sticky='nswe')
self.canvas.update() # wait till canvas is created
vbar.configure(command=self.scroll_y) # bind scrollbars to the canvas
hbar.configure(command=self.scroll_x)
# Bind events to the Canvas
self.canvas.bind('<Configure>', self.show_image) # canvas is resized
self.canvas.bind('<ButtonPress-3>', self.move_from)
self.canvas.bind('<B3-Motion>', self.move_to)
self.canvas.bind('<MouseWheel>', self.wheel) # with Windows and MacOS, but not Linux
self.canvas.bind('<Button-5>', self.wheel) # only with Linux, wheel scroll down
self.canvas.bind('<Button-4>', self.wheel) # only with Linux, wheel scroll up
self.image = Image.open(impath) # open image
self.im_width, self.im_height = self.image.size
self.imscale = 1.0 # scale for the canvaas image
self.delta = 1.3 # zoom magnitude
# Put image into container rectangle and use it to set proper coordinates to the image
self.container = self.canvas.create_rectangle(0, 0, self.im_width, self.im_height, width=0)
self.show_image() # show image on the screen
self.canvas.focus_set() # set focus on the canvas
def scroll_y(self, *args):
""" Scroll canvas vertically and redraw the image """
self.canvas.yview(*args) # scroll vertically
self.show_image() # redraw the image
def scroll_x(self, *args):
""" Scroll canvas horizontally and redraw the image """
self.canvas.xview(*args) # scroll horizontally
self.show_image() # redraw the image
def show_image(self, event=None):
""" Show image on the canvas """
box_image = self.canvas.coords(self.container) # get image area
box_canvas = (self.canvas.canvasx(0), # get visible area of the canvas
self.canvas.canvasy(0),
self.canvas.canvasx(self.canvas.winfo_width()),
self.canvas.canvasy(self.canvas.winfo_height()))
box_img_int = tuple(map(round, box_image)) # convert to integer or it will not work properly
# Get scroll region box
box_scroll = [min(box_img_int[0], box_canvas[0]), min(box_img_int[1], box_canvas[1]),
max(box_img_int[2], box_canvas[2]), max(box_img_int[3], box_canvas[3])]
# Horizontal part of the image is in the visible area
if box_scroll[0] == box_canvas[0] and box_scroll[2] == box_canvas[2]:
box_scroll[0] = box_img_int[0]
box_scroll[2] = box_img_int[2]
# Vertical part of the image is in the visible area
if box_scroll[1] == box_canvas[1] and box_scroll[3] == box_canvas[3]:
box_scroll[1] = box_img_int[1]
box_scroll[3] = box_img_int[3]
# Convert scroll region to tuple and to integer
self.canvas.configure(scrollregion=tuple(map(round, box_scroll))) # set scroll region
x1 = max(box_canvas[0] - box_image[0], 0) # get coordinates (x1,y1,x2,y2) of the image tile
y1 = max(box_canvas[1] - box_image[1], 0)
x2 = min(box_canvas[2], box_image[2]) - box_image[0]
y2 = min(box_canvas[3], box_image[3]) - box_image[1]
if round(x2 - x1) > 0 and round(y2 - y1) > 0: # show image if it in the visible area
image = self.image.crop((round(x1 / self.imscale), round(y1 / self.imscale),
round(x2 / self.imscale), round(y2 / self.imscale)))
imagetk = ImageTk.PhotoImage(image.resize((round(x2 - x1), round(y2 - y1))))
imageid = self.canvas.create_image(max(box_canvas[0], box_img_int[0]),
max(box_canvas[1], box_img_int[1]),
anchor='nw', image=imagetk)
self.canvas.lower(imageid) # set image into background
self.canvas.imagetk = imagetk # keep an extra reference to prevent garbage-collection
def move_from(self, event):
""" Remember previous coordinates for scrolling with the mouse """
self.canvas.scan_mark(event.x, event.y)
def move_to(self, event):
""" Drag (move) canvas to the new position """
self.canvas.scan_dragto(event.x, event.y, gain=1)
self.show_image() # redraw the image
def outside(self, x, y):
""" Checks if the point (x,y) is outside the image area """
bbox = self.canvas.coords(self.container) # get image area
if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]:
return False # point (x,y) is inside the image area
else:
return True # point (x,y) is outside the image area
def wheel(self, event):
""" Zoom with mouse wheel """
x = self.canvas.canvasx(event.x)
y = self.canvas.canvasy(event.y)
if self.outside(x, y): return # zoom only inside image area
scale = 1.0
# Respond to Linux (event.num) or Windows (event.delta) wheel event
if event.num == 5 or event.delta == -120: # scroll down
i = min(self.im_width, self.im_height)
if round(i * self.imscale) < 30: return # image is less than 30 pixels
self.imscale /= self.delta
scale /= self.delta
if event.num == 4 or event.delta == 120: # scroll up
i = min(self.canvas.winfo_width(), self.canvas.winfo_height())
if i < self.imscale: return # 1 pixel is bigger than the visible area
self.imscale *= self.delta
scale *= self.delta
self.canvas.scale('all', x, y, scale, scale) # rescale all canvas objects
# Redraw some figures before showing image on the screen
self.redraw_figures()
self.show_image()
def redraw_figures(self):
""" Dummy function to redraw figures in the children classes """
pass
def grid(self, **kw):
""" Put CanvasImage on the parent widget """
self.imframe.grid(**kw) # place CanvasImage widget on the grid
self.imframe.grid(sticky='nswe') # make frame container sticky
self.imframe.rowconfigure(0, weight=1) # make canvas expandable
self.imframe.columnconfigure(0, weight=1)
def pack(self, **kw):
""" Exception: cannot use pack with this widget """
raise Exception('Cannot use pack with the widget ' + self.__class__.__name__)
def place(self, **kw):
""" Exceiption: cannot use place with this widget """
raise Exception('Cannot use place with the widget ' + self.__class__.__name__)
class Polygons(CanvasImage):
""" Class of Polygons. Inherit CanvasImage class """
def __init__(self, parent, impath):
""" Initialize the Polygons """
CanvasImage.__init__(self, parent, impath) # call __init__ of the CanvasImage class
self.canvas.bind('<ButtonPress-1>', self.set_edge) # set new edge
self.canvas.bind('<Motion>', self.motion) # handle mouse motion
self.canvas.bind('<Delete>', self.delete_roi) # delete selected polygon
# Polygon parameters
self.width_line = 2 # lines width
self.dash = (1, 1) # dash pattern
self.color_draw = 'red' # color to draw
self.color_active = 'yellow' # color of active figures
self.color_point = 'blue' # color of pointed figures
self.color_back = '#808080' # background color
self.stipple = 'gray12' # value of stipple
self.tag_edge_start = '1st_edge' # starting edge of the polygon
self.tag_edge = 'edge' # edges of the polygon
self.tag_edge_id = 'edge_id' # part of unique ID of the edge
self.tag_poly = 'polygon' # polygon tag
self.tag_const = 'poly' # constant tag for polygon
self.tag_poly_line = 'poly_line' # edge of the polygon
self.tag_circle = 'circle' # sticking circle tag
self.radius_stick = 10 # distance where line sticks to the polygon's staring point
self.radius_circle = 3 # radius of the sticking circle
self.edge = None # current edge of the new polygon
self.polygon = [] # vertices of the polygon
self.selected_poly = [] # selected polygons
def set_edge(self, event):
""" Set edge of the polygon """
if self.edge and ' '.join(map(str, self.dash)) == self.canvas.itemcget(self.edge, 'dash'):
return # the edge is out of scope or self-crossing with other edges
x = self.canvas.canvasx(event.x) # get coordinates of the event on the canvas
y = self.canvas.canvasy(event.y)
if not self.edge: # start drawing polygon
self.draw_edge(x, y, self.tag_edge_start)
# Draw sticking circle
self.canvas.create_oval(x - self.radius_circle, y - self.radius_circle,
x + self.radius_circle, y + self.radius_circle,
width=0, fill=self.color_draw,
tags=(self.tag_edge, self.tag_circle))
else: # continue drawing polygon
x1, y1, x2, y2 = self.canvas.coords(self.tag_edge_start) # get coords of the 1st edge
x3, y3, x4, y4 = self.canvas.coords(self.edge) # get coordinates of the current edge
if x4 == x1 and y4 == y1: # finish drawing polygon
if len(self.polygon) > 2: # draw polygon on the zoomed image canvas
bbox = self.canvas.coords(self.container) # get image area
vertices = list(map((lambda i: (i[0] * self.imscale + bbox[0],
i[1] * self.imscale + bbox[1])), self.polygon))
# Create identification tag
# [:-3] means microseconds to milliseconds, anyway there are zeros on Windows OS
tag_id = datetime.now().strftime('%Y-%m-%d_%H-%M-%S.%f')[:-3]
# Create polygon. 2nd tag is ALWAYS a unique tag ID + constant string.
self.canvas.create_polygon(vertices, fill=self.color_point,
stipple=self.stipple, width=0, state='hidden',
tags=(self.tag_poly, tag_id + self.tag_const))
# Create polyline. 2nd tag is ALWAYS a unique tag ID.
for j in range(len(vertices)-1):
self.canvas.create_line(vertices[j], vertices[j+1], width=self.width_line,
fill=self.color_back, tags=(self.tag_poly_line, tag_id))
self.canvas.create_line(vertices[-1], vertices[0], width=self.width_line,
fill=self.color_back, tags=(self.tag_poly_line, tag_id))
self.delete_edges() # delete edges of drawn polygon
else:
self.draw_edge(x, y) # continue drawing polygon, set new edge
def draw_edge(self, x, y, tags=None):
""" Draw edge of the polygon """
if len(self.polygon) > 1:
x1, y1, x2, y2 = self.canvas.coords(self.edge)
if x1 == x2 and y1 == y2:
return # don't draw edge in the same point, otherwise it'll be self-intersection
edge_id = self.tag_edge_id + str(len(self.polygon))
self.edge = self.canvas.create_line(x, y, x, y, fill=self.color_draw, width=self.width_line,
tags=(tags, self.tag_edge, edge_id,))
bbox = self.canvas.coords(self.container) # get image area
x1 = round((x - bbox[0]) / self.imscale) # get (x,y) on the image without zoom
y1 = round((y - bbox[1]) / self.imscale)
self.polygon.append((x1, y1)) # add new vertex to the list of polygon vertices
def motion(self, event):
""" Track mouse position over the canvas """
if self.edge: # relocate edge of the polygon
x = self.canvas.canvasx(event.x) # get coordinates of the event on the canvas
y = self.canvas.canvasy(event.y)
x1, y1, x2, y2 = self.canvas.coords(self.tag_edge_start) # get coordinates of the 1st edge
x3, y3, x4, y4 = self.canvas.coords(self.edge) # get coordinates of the current edge
dx = x - x1
dy = y - y1
# Set new coordinates of the edge
if self.radius_stick * self.radius_stick > dx * dx + dy * dy:
self.canvas.coords(self.edge, x3, y3, x1, y1) # stick to the beginning
self.set_dash(x1, y1) # set dash for edge segment
else:
self.canvas.coords(self.edge, x3, y3, x, y) # follow the mouse movements
self.set_dash(x, y) # set dash for edge segment
# Handle polygons on the canvas
self.deselect_roi() # change color and zeroize selected roi polygon
self.select_roi() # change color and select roi polygon
def set_dash(self, x, y):
""" Set dash for edge segment """
# If outside of the image or polygon self-intersection is occurred
if self.outside(x, y) or self.polygon_selfintersection():
self.canvas.itemconfigure(self.edge, dash=self.dash) # set dashed line
else:
self.canvas.itemconfigure(self.edge, dash='') # set solid line
def deselect_roi(self):
""" Deselect current roi object """
if not self.selected_poly: return # selected polygons list is empty
for i in self.selected_poly:
self.canvas.itemconfigure(i, fill=self.color_back) # deselect lines
self.canvas.itemconfigure(i + self.tag_const, state='hidden') # hide polygon
self.selected_poly.clear() # clear the list
def select_roi(self):
""" Select and change color of the current roi object """
if self.edge: return # new polygon is being created now
i = self.canvas.find_withtag('current') # id of the current object
tags = self.canvas.gettags(i) # get tags of the current object
if self.tag_poly_line in tags: # if it's a roi polygon. 2nd tag is ALWAYS a unique tag ID
self.canvas.itemconfigure(tags[1], fill=self.color_point) # select lines
self.canvas.itemconfigure(tags[1] + self.tag_const, state='normal') # show polygon
self.selected_poly.append(tags[1]) # remember 2nd unique tag_id
def redraw_figures(self):
""" Overwritten method. Redraw sticking circle """
bbox = self.canvas.coords(self.tag_circle)
if bbox: # radius of sticky circle is unchanged
cx = (bbox[0] + bbox[2]) / 2 # center of the circle
cy = (bbox[1] + bbox[3]) / 2
self.canvas.coords(self.tag_circle,
cx - self.radius_circle, cy - self.radius_circle,
cx + self.radius_circle, cy + self.radius_circle)
def delete_edges(self):
""" Delete edges of drawn polygon """
self.edge = None # delete all edges and set current edge to None
self.canvas.delete(self.tag_edge) # delete all edges
self.polygon.clear() # remove all items from vertices list
def delete_roi(self, event=None):
""" Delete selected polygon """
if self.edge: # if polygon is being drawing, delete it
self.delete_edges() # delete edges of drawn polygon
elif self.selected_poly: # delete selected polygon
for i in self.selected_poly:
self.canvas.delete(i) # delete lines
self.canvas.delete(i + self.tag_const) # delete polygon
self.selected_poly.clear() # clear the list
@staticmethod
def orientation(p1, p2, p3):
""" Find orientation of ordered triplet (p1, p2, p3). Returns following values:
0 --> p1, p2 and p3 are collinear
-1 --> clockwise
1 --> counterclockwise """
val = (p2[0] - p1[0]) * (p3[1] - p2[1]) - (p2[1] - p1[1]) * (p3[0] - p2[0])
if val < 0: return -1 # clockwise
elif val > 0: return 1 # counterclockwise
else: return 0 # collinear
@staticmethod
def on_segment(p1, p2, p3):
""" Given three collinear points p1, p2, p3, the function checks
if point p2 lies on line segment p1-p3 """
# noinspection PyChainedComparisons
if p2[0] <= max(p1[0], p3[0]) and p2[0] >= min(p1[0], p3[0]) and \
p2[1] <= max(p1[1], p3[1]) and p2[1] >= min(p1[1], p3[1]):
return True
return False
def intersect(self, p1, p2, p3, p4):
""" Return True if line segments p1-p2 and p3-p4 intersect, otherwise return False """
# Find 4 orientations
o1 = self.orientation(p1, p2, p3)
o2 = self.orientation(p1, p2, p4)
o3 = self.orientation(p3, p4, p1)
o4 = self.orientation(p3, p4, p2)
# General case
if o1 != o2 and o3 != o4: return True # segments intersect
# Segments p1-p2 and p3-p4 are collinear
if o1 == o2 == 0:
# p3 lies on segment p1-p2
if self.on_segment(p1, p3, p2): return True
# p4 lies on segment p1-p2
if self.on_segment(p1, p4, p2): return True
# p1 lies on segment p3-p4
if self.on_segment(p3, p1, p4): return True
return False # doesn't intersect
def penultimate_intersect(self, p1, p2, p3):
""" Check penultimate (last but one) edge,
where p1 and p4 coincide with the current edge """
if self.orientation(p1, p2, p3) == 0 and not self.on_segment(p3, p1, p2):
return True
else:
return False
def first_intersect(self, p1, p2, p3, p4):
""" Check the 1st edge, where points p2 and p3 CAN coincide """
if p2[0] == p3[0] and p2[1] == p3[1]: return False # p2 and p3 coincide -- this is OK
if p1[0] == p3[0] and p1[1] == p3[1]: return False # there is only 1 edge
# There is only 2 edges
if p1[0] == p4[0] and p1[1] == p4[1]: return self.penultimate_intersect(p1, p2, p3)
return self.intersect(p1, p2, p3, p4) # General case
def polygon_selfintersection(self):
""" Check if polygon has self-intersections """
x1, y1, x2, y2 = self.canvas.coords(self.edge) # get coords of the current edge
for i in range(1, len(self.polygon)-2): # don't include the 1st ant the last 2 edges
x3, y3, x4, y4 = self.canvas.coords(self.tag_edge_id + str(i))
if self.intersect((x1, y1), (x2, y2), (x3, y3), (x4, y4)): return True
# Check penultimate (last but one) edge, where points p1 and p4 coincide
j = len(self.polygon) - 2
if j > 0: # 2 or more edges
x3, y3, x4, y4 = self.canvas.coords(self.tag_edge_id + str(j))
if self.penultimate_intersect((x1, y1), (x2, y2), (x3, y3)): return True
# Check the 1st edge, where points p2 and p3 can coincide
x3, y3, x4, y4 = self.canvas.coords(self.tag_edge_start)
if self.first_intersect((x1, y1), (x2, y2), (x3, y3), (x4, y4)): return True
return False # there is no self-intersections in the polygon
class MainWindow(ttk.Frame):
""" Main window class """
def __init__(self, mainframe, path):
""" Initialize the main Frame """
ttk.Frame.__init__(self, master=mainframe)
self.master.title('Draw polygons')
self.master.geometry('800x600')
self.master.rowconfigure(0, weight=1) # make the CanvasImage expandable
self.master.columnconfigure(0, weight=1)
polygons = Polygons(self.master, path)
polygons.grid(row=0, column=0)
filename = '../data/doge.jpg' # place path to your image here
root = tk.Tk()
app = MainWindow(root, path=filename)
root.mainloop()
|
30ffb079040aa70adea8e5bee3b937f4abede977 | zekiahmetbayar/python-learning | /Bolum1_Problemler/yakit_hesapla.py | 388 | 3.890625 | 4 | # Bir aracın kilometrede ne kadar yaktığı ve kaç kilometre yol yaptığı bilgilerini alın ve sürücünü toplam ne kadar ödemesini gerektiğini hesaplayın.
km_yakit = float(input("Kilometrede kaç tl yaktığınızı giriniz : "))
km_yol = int(input("Kaç kilometre yol yaptığınızı giriniz : "))
print("Yaktığınız toplam yakıt : {} TL'dir. ".format(km_yakit*km_yol)) |
059ab1e030ac7c23a0eac0052a3921745e1b71f5 | Kovitwk/IT1805Grp2 | /Record.py | 957 | 4.0625 | 4 | class Record:
def __init__(self, height, weight, date):
self.__height = height
self.__weight = weight
self.__bmi = (float(weight)/(float(height)*float(height)))
self.__level = ''
self.__date = date
def get_date(self):
return self.__date
def get_height(self):
return self.__height
def get_weight(self):
return self.__weight
def get_bmi(self):
return round(self.__bmi, 2)
def get_fitness_level(self):
if self.__bmi < 18:
print("Underweight, Fitness level = Unhealthy")
self.__level = "Underweight, Unhealthy"
elif self.__bmi < 25:
print("Normal, Fitness level = Healthy")
self.__level = "Normal, Healthy"
else:
print("Overweight, Fitness level = Unhealthy")
self.__level = "Overweight, Unhealthy"
return self.__level
|
ac251afc06df77f854a3b6ebe4e8785d92244726 | Freshield/LEARN_Python_Crawler | /example/13/╡┌13.8.py | 880 | 4.03125 | 4 | # 导入concurrent.futures模块
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import datetime
# 线程的执行方法
def print_value(value):
print('Thread' + str(value))
# 每个进程里面的线程
def myThread(value):
Thread = ThreadPoolExecutor(max_workers=2)
Thread.submit(print_value, datetime.datetime.now())
Thread.submit(print_value, datetime.datetime.now())
# 创建两个进程,每个进程执行myThread方法,myThread主要将每个进程通过线程执行
# 如果不填写max_workers=2,会根据计算机的每一个CPU创建一个Python进程,如果四核就创建四个进程
def myProcess():
pool = ProcessPoolExecutor(max_workers=2)
pool.submit(myThread, datetime.datetime.now())
pool.submit(myThread, datetime.datetime.now())
if __name__ == '__main__':
myProcess() |
e4c2d6aafc02e7ff24d24f3eabfd2f0aed5b4539 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/sbysiz002/piglatin.py | 1,028 | 3.53125 | 4 | def getFirstVowel(w):
#return the position of the first occurence of a vowel in a string
for i in range(1,len(w)):
if w[i] in "aeiou":
return i
def toPigLatin(s):
vowel = ['a','e','i','o','u']
newSent = ''
for word in s.split(' '):
if word[0] in vowel:
newSent += ' '+word+"way"
else:
#split the word into two parts
pos = getFirstVowel(word)
pre = word[0:pos]
suf = word[pos::]
newSent += ' '+suf+'a'+pre+"ay"
newSent = newSent[1:]
return newSent
def toEnglish(s):
lang=''
for word in s.split(' '):
tmp = word[::-1]
if tmp[0:3] == "yaw":
lang+=' '+word[0:-3]
else:
word = word[::-1]
word = word[2:]
x = word.find('a')
st = word[0:x]
end = word[(x+1):]
new_word = st[::-1]+end[::-1]
lang+=' '+new_word
return lang[1:] |
10d4d994d6ddaa3fcb20720bfe970121d81b5588 | vietthanh179980123/VoVietThanh_58474_CA20B1 | /page_63_project_10.py | 1,275 | 3.96875 | 4 | """
Author: Võ Viết Thanh
Date: 05/09/2021
Program: An employee’s total weekly pay equals the hourly wage multiplied by the total
number of regular hours plus any overtime pay. Overtime pay equals the total
overtime hours multiplied by 1.5 times the hourly wage. Write a program that
takes as inputs the hourly wage, total regular hours, and total overtime hours and
displays an employee’s total weekly pay
Solution:
1. Analys
- Displays an employee’s total weekly pay
2. Inputs
- The hourly wage
- Total regular hours
- Total overtime hours
3. Outputs
- An employee’s total weekly pay
4. Design
- The hourly wage
- Total regular hours
- Total overtime hours
- The formulas are:
+ An employee's total weekly pay = ( the hourly wage * regular hour ) + over time pay
....
"""
# Request the inputs
hourlywage=float(input("Nhap luong theo gio cua ban: "))
regularhour=int(input("Nhap thoi gian lam viec trong ngay: "))
overtimehour=int(input("Nhap thoi gian tang ca: "))
overtimepay=overtimehour*1.5
# Compute an employee's total weekly pay
total=(hourlywage*regularhour)+overtimepay
# Display the number of minute of a year
print("Tong luong ma ban nhan duoc trong 1 tuan la: ",total)
|
b1ac7cbae6acd087af2e34360b398fc7574a2b98 | Artembbk/fmsh | /Python/quadric.py | 744 | 3.78125 | 4 | from math import sqrt
a, b, c = map(int, input("Введите коэфиценты квадратного уравнения через пробел: ").split())
if a != 0:
d = b**2 - 4*a*c
if d > 0:
x1 = ( -b-sqrt(d) )/2*a
x2 = ( -b+sqrt(d) )/2*a
print("x1 = {}; x2 = {}".format(x1, x2))
elif d == 0:
x = -b/2*a
print("x1 = x2 = {}".format(x))
else:
print("Данное уравнение не имеет действительных решений")
else:
if b!=0:
x = -c/b
print("x ={}".format(x))
else:
if c==0:
print("Данное уравнение имеет бесконечное колчество решиний")
else:
print("Данное уравнение не имеет решений") |
d233f630f471758bdd628b3f46de1077e009d753 | Heast1/HHWCS | /RemoveVowels.py | 339 | 3.984375 | 4 | def RemoveVowels(str):
vowels = "AaEeIiOoUu" # a string of vowels
for i in str:
if(i in vowels):
str = str.replace(i, "") # replaces the char with space
return str
print("Enter a line: ")
string = input()
print("The mutated string is ", RemoveVowels(string)) |
9ee41caafa204624d48dd57d2dd39cfc8ccb3829 | yuninje/Algorithm_Solve | /Baekjoon/[ 01914 ] 하노이 탑.py | 328 | 3.953125 | 4 | # https://www.acmicpc.net/problem/1914
def Hanoi(start, end, height):
if height == 1:
print(str(start) + " " + str(end))
return
Hanoi(start, 6-start-end, height-1)
print(str(start) + " " + str(end))
Hanoi(6-start-end, end, height-1)
N = int(input())
print((1<<N)-1)
if N <= 20:
Hanoi(1,3,N) |
77358a70ba80e9727ba9b13715debec30fa63ff1 | lucascmb/Sistemas_Distribuidos | /Modulo 1/Laboratório 1/echo_passivo.py | 964 | 3.5625 | 4 | import socket
#define o host e a porta de conexão que a parte passiva irá receber conexões
HOST = ''
PORT = 5000
#instancia o socket
socket_passivo = socket.socket()
#define o host e a porta ao qual esse socket estará ouvindo
socket_passivo.bind((HOST, PORT))
# define o limite maximo de 5 conexoes pendentes e coloca-se em modo de espera por conexao
socket_passivo.listen(5)
#aceita uma conexão de socket, criando uma nova instancia de socket e recuperando o endereço de conexão
novo_socket, endereco = socket_passivo.accept()
while True:
#espera até receber a mensagem em bytes (bloqueante)
msg = novo_socket.recv(1024)
#se a string recebida for 'fechar conexao', encerra o loop
if str(msg, encoding='utf-8') == 'fechar conexao': break
#reenvia a mensagem recebida
novo_socket.send(msg)
#encerra o socket criado para a conexão com a parte ativa
novo_socket.close()
#encerra o socket principal
socket_passivo.close()
|
8e267b6b2496aa362ea7bd4149fd347f68caf7da | renbstux/geek-python | /Tipo String.py | 1,520 | 4.28125 | 4 | """
Tipo String
Já vimos que em Python um dado é considerado do tipo string sempre que:
Estiver entre aspas simples -> 'uma string', '234', 'a', 'True', '42.3'
Estiver entre aspas Duplas -> "uma string", "234", "a", "True", "42.3"
Estiver entre aspas simples triplas -> '''uma string''', '''234''', '''a''', '''True''', '''42.3'''
"""
# Estiver entre aspas Duplas Triplas -> """uma string""", """234""", """a""", """True""", """42.3"""
"""
nome = 'Renato de Souza'
print(nome)
print(type(nome))
nome = "Renato's Bar"
print(nome)
print(type(nome))
nome = "Melissa \nLuz" # \n e como se desse um enter para separar a linha
print(nome)
print(type(nome))
nome = ""Melissa
Luz""
print(nome)
print(type(nome))
nome = 'Renato de Souza'
print(nome.upper())
print(nome.lower())
print(nome.split()) # Transforma em lista de Strings -
['Renato', 'de', 'Souza']
print(nome[0:6]) # Slice de String
print(nome[7:15]) # Slice de String
print(nome.split()[0])
print(nome.split()[2])
"""
# [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
# [ 'R', 'e', 'n', 'a', 't', 'o', ' ', 'd', 'e', ' ', 'S', 'o', 'u', 'z', 'a' ]
nome = 'Renato de Souza'
"""
[::-1] -> Comece do primeiro elemento, vá até o ultimo elemento e inverta
azuoS ed otaneR
print(nome[::-1]) # Pythônico -> Inversão da String
print(nome.replace('a', '@'))
Ren@to de Souz@
"""
print(nome[::-1]) # Pythônico -> Inversão da String
print(nome.replace('a', '@'))
texto = 'socorram me subino onibus em marrocos' # Palindromo
print(texto)
print(texto[::-1])
|
22589da04067c0a56b0e9b74bc990ba89ed3adff | sbeaumont/AoC | /2020/AoC-2020-14.py | 859 | 3.546875 | 4 | #!/usr/bin/env python3
"""Solution for Advent of Code challenge 2020 - Day 13"""
__author__ = "Serge Beaumont"
__date__ = "December 2020"
with open("AoC-2020-14-input.txt") as infile:
program = [line.strip() for line in infile.readlines()]
print(program)
def to_binary(i):
return [c for c in bin(i)[2:].zfill(36)]
def to_int(bits):
return int(bits, 2)
def mask_value(mask, value):
masked = [m if (m == '0') or (m == '1') else c for m, c in zip(mask, value)]
return ''.join(masked)
memory = dict()
mask = '0' * 36
for line in program:
if line[:4] == 'mask':
mask = line.split(' = ')[1]
else:
addr, num = line.split(' = ')
mem_addr = int(addr.strip()[4:-1])
memory[mem_addr] = mask_value(mask, to_binary(int(num)))
total = 0
for value in memory.values():
total += to_int(value)
print(total) |
82e00ed3c84090cb57be08e0e049bebd2cb48ba4 | RPCodeBox2/06_EDA_Matplotlib | /01_MatPlotLib_Basic_Code.py | 1,759 | 3.921875 | 4 |
# In[1] - Documentation
"""
Script - 01_MatPlotLib_Basic_Code.py
Decription - Basic coding pattern of Matplotlib
Author - Rana Pratap
Date - 2021
Version - 1.0
#!/usr/bin/env python
#coding: utf-8
"""
print(__doc__)
# In[2]: Import and Jupyter Notebook Settings
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline #Schema for Matplotlob')
# In[3]: Base Syntax
plt.plot([1,2,3,4,5])
# In[4]: Base Syntax, X axis and Label
plt.plot([1,2,3,4,5])
plt.ylabel("Sequence Numbers")
plt.show()
# In[5]: Base Syntax, X and Y axis with Labels
x = [1,2,3,4,5]
y = [10,20,20,40,50]
plt.plot(x,y)
plt.xlabel("Values")
plt.ylabel("Measure")
plt.show()
# In[6]: Base plot with line color and Pattern 1
x = [1,2,3,4,5]
y = [10,20,20,40,50]
plt.plot(x,y,'g--')
# In[7]: Base plot with line color and Pattern 2
x = [1,2,3,4,5]
y = [10,20,20,40,50]
plt.plot(x,y,'b--')
# In[8]: Base plot with line color and Pattern 3
x = [1,2,3,4,5]
y = [10,20,20,40,50]
plt.plot(x,y,'r-.')
# In[9]: NumPy data set and MatPlot graphs
import numpy as np
data = np.arange(0,10,0.5)
data
# In[10]: Base plot with line color and Pattern 4
plt.plot(data,data*2,'y--')
# In[11]: Base plot with multi axis plot and designs
data = np.arange(0,6,0.2)
data
plt.figure(figsize=(10,10))
plt.plot(data,data,'r--',data,data**2,'b-.',data,data**3,'g^')
plt.grid(color='black',linestyle='-.',linewidth=0.4)
plt.show()
# In[12]: Plot X and Y with Grid patten
x = [1,2,3,4,5]
y = [10,20,20,40,50]
plt.figure(figsize=(10,10))
L1 = x
plt.plot(x,y,label='L1',lw='1',marker='^',ms=10,c='blue')
plt.title('Nonlinear Lines',style='normal',size=24)
plt.grid(color='black',linestyle='-.',linewidth=0.4)
plt.legend(loc='upper left')
plt.show()
# In[29]:
del(x,y,data)
del(L1)
|
3508a62600789b1121c97427a134c3b2f928fbd9 | chandanrawat176/Python | /encoded message.py | 411 | 4.03125 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = 3
newMessage = ''
message = input('Please enter a message: ')
for character in message:
if character in alphabet:
position = alphabet.find(character)
newposition = (position + key) % 26
newchar = alphabet[newposition]
#print('The new character is:', newchar)
newMessage += newchar
else:
character += newchar
print('your new message is', newMessage) |
e4ec993995906a229fd22a8066769ec2df407395 | BrianBalayon/50white | /Python/gui.py | 1,359 | 3.59375 | 4 | import tkinter as tk
from tkinter import filedialog
import percentCalc
_root = tk.Tk()
_txt_box = tk.Text(_root, height=3, width=30)
_choose_btn = tk.Button(_root, text='Choose a File', height=2, width=30, command=lambda: choose_file())
_calc_btn = tk.Button(_root, text="Calculate Whitespace", height=2, width=30,
command=lambda: percentCalc.calc(_root.filename))
def start_ui():
_root.title("Whitespace Detector")
_txt_box.insert(tk.END, "Please choose a file first")
_txt_box.pack()
_choose_btn.pack()
_calc_btn.pack()
# Causes window to stay open until close
_root.mainloop()
def choose_file():
# Opens file selection dialogue
# Variable store the full path of the image
_root.filename = filedialog.askopenfilename(initialdir="/",
title="Select file",
filetypes=(("jpeg files", "*.jpg"),
("pdf files", "*.pdf"),
("png files", "*.png"),
("all files", "*.*"))
)
_txt_box.insert('1.0', ("File chosen: " + _root.filename + "\n \n"))
def update_text(s):
_txt_box.insert('1.0', s)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.