blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2e18828ffb8c2066745d3939d643d9dab296413a | WPettersson/kidney_utils | /kidney_utils/graph.py | 17,736 | 3.6875 | 4 | """A directed graph representing kidney patients and donors."""
try:
from queue import Queue
except ImportError:
from Queue import Queue
import community
import networkx
from progressbar import ProgressBar, Bar, Percentage
class Vertex(object):
"""A vertex in a directed graph."""
def __init__(self, desc, index):
self._desc = desc
self._leaving = []
self._entering = []
self._index = index
def desc(self):
"""Return a description of this vertex. This is the key used by the
graph to refer to this vertex.
"""
return self._desc
def add_out_edge(self, edge):
"""Add an edge leaving this vertex."""
self._leaving.append(edge)
def add_in_edge(self, edge):
"""Add an edge entering this vertex."""
self._entering.append(edge)
def edges_in(self):
"""The edges that leave this vertex."""
return self._entering
def edges_out(self):
"""The edges that leave this vertex."""
return self._leaving
def index(self):
"""The (integer) index of this vertex in the graph."""
return self._index
def neighbours_out(self):
"""Return the list of neighbours when leaving this vertex."""
return [edge.head() for edge in self.edges_out()]
def neighbours_in(self):
"""Return the list of neighbours which entering this vertex."""
return [edge.tail() for edge in self.edges_in()]
def all_neighbours(self):
"""Return all neighbours, for instance if treating this directed graph
as an undirected graph.
"""
return self.neighbours_in() + self.neighbours_out()
def __lt__(self, other):
return self.index() < other.index()
def __str__(self):
return "V%s" % (self._desc)
def __repr__(self):
return self.__str__()
class Edge(object):
"""An edge in a directed graph."""
def __init__(self, v1, v2, weight=1):
self._v1 = v1
self._v2 = v2
self._weight = weight
def tail(self):
"""The start of the edge."""
return self._v1
def head(self):
"""The end of the edge."""
return self._v2
def weight(self):
"""The weight of the edge."""
return self._weight
def __str__(self):
name = "%s->%s" % (self._v1, self._v2)
if self._weight != 1:
name += " (%.2f)" % (self._weight)
return name
def __repr__(self):
return self.__str__()
class Graph(object):
"""A directed graph representing kidney patients and donors."""
def __init__(self):
self._edges = []
self._vertices = {}
self._vertices_list = []
self._eccentricity = None
self._shortest_paths = None
self._nxgraph = networkx.DiGraph()
def size(self):
"""Size, aka number of vertices."""
return len(self._vertices)
def add_vertex(self, vert):
"""Add a vertex to the graph."""
if vert not in self._vertices.keys():
self._vertices[vert] = Vertex(vert, len(self._vertices_list))
self._vertices_list.append(self._vertices[vert])
def add_edge(self, vert_1, vert_2, weight=1):
"""Add an edge from vert_1 to vert_2 with weight."""
# Mark eccentricity and shortest-paths as not known
self._eccentricity = None
self._shortest_paths = None
self.add_vertex(vert_1)
self.add_vertex(vert_2)
edge = Edge(self._vertices[vert_1], self._vertices[vert_2], weight)
self._edges.append(edge)
self._vertices[vert_1].add_out_edge(edge)
self._vertices[vert_2].add_in_edge(edge)
if weight != 1:
self._nxgraph.add_edge(vert_1, vert_2, weight=weight)
else:
self._nxgraph.add_edge(vert_1, vert_2)
def vertex(self, index):
"""Get a Vertex from an index."""
return self._vertices[index]
def vertex_list(self):
"""The list of Vertex objects in this graph"""
return self._vertices_list
def edge_count(self):
"""Number of edges in the graph."""
return len(self._edges)
def edge_list(self):
"""List of Edge objects in this graph"""
return self._edges
def calculate_shortest_paths(self, quiet=True):
"""For each pair of distinct vertices u and v, calculate the shortest
path between u and v."""
if self._shortest_paths:
return
size = len(self._vertices)
self._shortest_paths = [[[] for _ in range(size)] for __ in range(size)]
count = len(self._vertices)
if not quiet:
pbar = ProgressBar(widgets=[Bar(), Percentage()], maxval=count)
pbar.start()
count = 0
for destination in self._vertices.values():
self.calculate_shortest_paths_to(destination)
if not quiet:
count += 1
pbar.update(count)
if not quiet:
pbar.finish()
def calculate_shortest_paths_to(self, dest):
"""Calculate all shortest paths to dest."""
to_check = Queue()
d_ind = dest.index()
# The neighbours have one hop to this vertex
for near in dest.neighbours_in():
self._shortest_paths[near.index()][d_ind] = [dest]
for to_do in near.neighbours_in():
to_check.put((to_do, near))
while not to_check.empty():
(source, next_vert) = to_check.get()
s_ind = source.index()
if self._shortest_paths[s_ind][d_ind]:
continue
path = [next_vert]
path.extend(self._shortest_paths[next_vert.index()][d_ind])
self._shortest_paths[s_ind][d_ind] = path
for to_do in source.neighbours_in():
to_check.put((to_do, source))
def strongly_connected_components(self):
"""Find the strongly connected components (SCC) of this graph.
This uses Tarjan's algorithm (Depth-first search and linear graph
algorithms, R. E. Tarjan, SIAM Journal on Computing, 1972), although
the Wikipedia article is also good reading in this case.
:return: A list of lists. Each inner list is a set of vertices which
are strongly connected in this graph.
"""
components = []
# Lazily using a list as a stack. Just use append/pop to access.
stack = list()
depth = 0
def strong_connect(vert):
"""Find the strongly connected component this vertex belongs to.
"""
nonlocal depth
vert.scc_index = depth
vert.scc_low_link = depth
depth += 1
vert.scc_on_stack = True
stack.append(vert)
for outgoing in vert.neighbours_out():
if not hasattr(outgoing, "scc_index"):
strong_connect(outgoing)
vert.scc_low_link = min(vert.scc_low_link,
outgoing.scc_low_link)
elif outgoing.scc_on_stack:
vert.scc_low_link = min(vert.scc_low_link,
outgoing.scc_low_link)
if vert.scc_low_link == vert.scc_index:
# Is a "root" of a SCC
component = []
while True:
adding = stack.pop()
adding.scc_on_stack = False
component.append(adding)
if adding is vert:
break
components.append(component)
for vert in self._vertices.values():
if not hasattr(vert, "scc_index"):
strong_connect(vert)
return components
def calculate_eccentricity(self):
"""Calculate the eccentricity of each vertex. For a vertex v, this is
the maximum of shortest_path(v,u) over all other vertices u."""
if not self._shortest_paths:
self.calculate_shortest_paths()
self._eccentricity = [max([len(path) for path in paths]) for paths in
self._shortest_paths]
def density(self):
"""Get the density of the graph."""
num_verts = len(self._vertices)
if num_verts < 2:
return 0
return float(len(self._edges))/(num_verts*(num_verts-1))
def out_degree_dist(self):
"""Get the out-degree distribution of the graph"""
#TODO
pass
def in_degree_dist(self):
"""Get the in-degree distribution of the graph"""
#TODO
pass
def find_cycles(self):
"""Find all simple directed graphs."""
cycles = list(networkx.algorithms.cycles.simple_cycles(self._nxgraph))
return cycles
def relevant_subsets(self, maxcycle, maxsize=None):
"""Finds all relevant subsets, as defined on page 6 of Maximising
expectation of the number of transplants in kidny exchange programs.
"""
if maxsize is None:
maxsize = len(self._vertices)
cycles = list(self.find_cycles())
cycles = [c for c in cycles if len(c) <= maxcycle]
omega = list()
for cycle in cycles:
subset = set()
for vert in cycle:
subset.add(vert)
omega.append(subset)
def _recurse(omega, verts, c_bar, maxcycle, maxsize):
for cycle in c_bar:
s_dash = set(verts)
for vert in cycle:
s_dash.add(vert)
if len(s_dash) > maxsize + maxcycle:
continue
if not [x for x in cycle if x in verts]:
continue
if s_dash not in omega:
omega.append(s_dash)
if len(s_dash) < maxsize + maxcycle:
c_hat = [c for c in c_bar if [v for v in c if v not in cycle]]
omega = _recurse(omega, s_dash, c_hat, maxcycle, maxsize)
return omega
for cycle in cycles:
verts = set(cycle)
c_bar = [c for c in cycles if [v for v in c if v not in cycle]]
if len(verts) < maxsize + maxcycle:
omega = _recurse(omega, verts, c_bar, maxcycle, maxsize)
return omega
def diameter(self):
"""Get the diameter of the graph"""
if not self._eccentricity:
self.calculate_eccentricity()
return max(self._eccentricity)
def radius(self, ignore_loops=True):
"""Get the radius of the graph"""
if not self._eccentricity:
self.calculate_eccentricity()
if ignore_loops:
return min([dist for dist in self._eccentricity if dist != 0])
return min(self._eccentricity)
def hop_plot(self):
"""Calculate how much of the graph can be reached in a given number of
hops. The returned values are the average of the reach for each
individual vertex.
:return: A list of tuples (a, b) where a is the number of hops,
and b is the proportion of the graph that can be reached in that many
hops.
"""
per_vertex = self.hop_plot_vertices()
# Make sure the list corresponding to each vertex is the same length
longest = max([len(x) for x in per_vertex])
results = [0] * longest
for vert in per_vertex:
for (distance, proportion) in vert:
results[distance-1] += proportion
for dist in range(len(vert), longest):
results[dist] += 1.0
results = [result/len(self._vertices) for result in results]
return results
def hop_plot_vertices(self):
"""Calculate how much of the graph can be reached in a given number of
hops, for each vertex.
:return: A list of list of tuples. One list of tuples is returned for
each vertex. The list contains tuples (a, b) where a is the number of
hops and b is the proportion of the graph that can be reached from this
vertex in a hops.
"""
results = []
num_verts = len(self._vertices)
self.calculate_shortest_paths()
for index, vert in enumerate(self._vertices):
verts_done = 0
distance = 1
result_here = []
paths = self._shortest_paths[index]
while verts_done < num_verts:
verts_done += len([x for x in paths if len(x) == distance])
result_here.append((distance, float(verts_done)/num_verts))
distance += 1
results.append(result_here)
return results
def best_partition(self):
"""Get the best possible partition of this graph into clusters. Uses
the louvain method described in Fast unfolding of communities in large
networks, Vincent D Blondel, Jean-Loup Guillaume, Renaud Lambiotte,
Renaud Lefebvre, Journal of Statistical Mechanics: Theory and
Experiment 2008(10), P10008 (12pp) and the python package from
https://github.com/taynaud/python-louvain/
"""
return community.best_partition(self._nxgraph)
def adjacency(self):
"""Return the adjacency matrix of this graph."""
matrix = []
for _, vert in self._vertices.items():
here = [0.] * len(self._vertices)
for edge in vert.edges_out():
here[edge.head().index()] += edge.weight()
for edge in vert.edges_in():
here[edge.tail().index()] += edge.weight()
matrix.append(here)
return matrix
def backarc(self):
"""Return the proportion of edges that have a back-arc.
Note that a value of 1 indicates that every edge has a back-arc.
"""
count = 0
edges = []
for edge in self._edges:
here = [edge.tail(), edge.head()]
edges.append(here)
if [edge.head(), edge.tail()] in edges:
count += 1
return (count / 2) / len(self._edges)
def group(self):
"""Return a grouping of the graph, where each group is a set of
vertices with the same edges going in and out.
"""
# A group is a mapping from a tuple (edges_in, edges_out) to a list of
# vertices with these particular edge sets.
groups = {}
def listhash(verts):
"""Create a string from a list, so we can hash it."""
return ",".join(str(vert) for vert in sorted(verts))
for vert in self._vertices_list:
added = False
for group, vertices in groups.items():
(neighbours_in, neighbours_out) = group
if (neighbours_in == listhash(vert.neighbours_in()) and
neighbours_out == listhash(vert.neighbours_out())):
vertices.append(vert)
added = True
break
if not added:
group = (listhash(vert.neighbours_in()), listhash(vert.neighbours_out()))
groups[group] = [vert]
return list(groups.values())
def approx_treewidth(self):
"""Computes an approximation of the treewidth of this graph, using the
Greedy Fill-In algorithm.
"""
decomp = Graph()
# Make decomp a copy of self. We modify this to find the treewidth.
# Then we throw it away, even though it's almost a complete tree
# decomposition, because I don't yet need that bit.
for edge in self._edges:
decomp.add_edge(edge.tail().desc(), edge.head().desc(), edge.weight())
for vert in self.vertex_list():
decomp.add_vertex(vert.desc())
used = [False] * decomp.size()
width = 0
def next_vert():
"""Get the next vertex to add to a bag, according to Greedy Fill-In
"""
least_added = -1
to_return = None
for vert in decomp.vertex_list():
if used[vert.index()]:
continue
num_added = 0
bag_size = 1
neighbours = vert.all_neighbours()
for vert_a in neighbours:
if used[vert_a.index()]:
continue
bag_size += 1
for vert_b in neighbours:
if used[vert_b.index()] or vert_b in vert_a.all_neighbours():
continue
num_added += 1
if least_added == -1 or num_added < least_added:
least_added = num_added
to_return = vert
this_bag_size = bag_size
return to_return, this_bag_size
for _ in range(self.size()):
best_choice, bag_size = next_vert()
if bag_size > width + 1:
width = bag_size - 1
used[best_choice.index()] = True
for vert in decomp.vertex_list():
if not used[vert.index()] and vert in best_choice.all_neighbours():
for other in decomp.vertex_list():
if vert == other:
continue
if used[other.index()] or other not in best_choice.all_neighbours():
continue
if other not in vert.all_neighbours():
decomp.add_edge(vert.desc(), other.desc())
return width
def __str__(self):
return "Graph on %d nodes" % len(self._vertices)
|
7f16ba35671249d6c1a90ee142900b25fd838cfe | hiroshi-horiguchi/100knocks | /000.py | 97 | 3.609375 | 4 | str = "stressed"
n_str = ""
for i in range(len(str)):
n_str = n_str + str[-i-1]
print(n_str) |
d9d5d5c55e3739a1f4ce8c73bf24f1d5124eabc8 | prabalbhandari04/python_ | /wap1.py | 107 | 4.03125 | 4 | n=int(input("enter number"))
if n%2==0:
print("number ids even")
else:
print("number is odd")
|
b120950654b9575e1b3184e1a19c6de492d24f7e | rrwt/daily-coding-challenge | /daily_problems/problem_101_to_200/problem_192.py | 943 | 4.25 | 4 | """
You are given an array of non-negative integers.
Let's say you start at the beginning of the array and are trying to advance to the end.
You can advance at most, the number of steps that you're currently on.
Determine whether you can get to the end of the array.
For example,
given the array [1, 3, 1, 2, 0, 1], we can go from indices 0 -> 1 -> 3 -> 5, so return true.
given the array [1, 2, 1, 0, 0], we can't reach the end, so return false.
"""
from typing import List
def can_reach_end(arr: List[int]) -> bool:
if arr[0] == 0:
return False
length = len(arr)
max_reach = 0
index = 0
while index <= max_reach:
max_reach = max(max_reach, arr[index] + index)
if max_reach >= length - 1:
return True
index += 1
return False
if __name__ == "__main__":
assert can_reach_end([1, 3, 1, 2, 0, 1]) is True
assert can_reach_end([1, 2, 1, 0, 0]) is False
|
87b8a18c15f84db1b5792af69a54d2f2dc705deb | sumit-mandal/machine-learning-complete | /part-1 Data Preprocessing/P14-Part1-Data-Preprocessing/Section 3 - Data Preprocessing in Python/Python/data_preprocessing_templates.py | 829 | 4.03125 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:,:-1].values #it means we take all rows and all columnns except last
Y = dataset.iloc[:,3].values #it shows all rows and only 3 column
#taking care of missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X[:, 1:3]) #used for fitting imputer object to matrix X
X[:, 1:3] = imputer.transform(X[:, 1:3]) #X[:, 1:3] variable is used to take columns for missing data
#imputer.transform(X[:, 1:3]) is method which is used to replace missing values with mean.
print(X)
#Encoding categorial data
from sklearn.preprocessing import LabelEncoder |
6c69009ebdaf8d82df2de466a6e5f38609be00d5 | farhanr8/PyExercises | /Codewars/ex29.py | 1,837 | 4.15625 | 4 | '''
https://www.codewars.com/kata/calculating-with-functions/
'''
def operate(x, func):
operation = func[0][0]
if operation == '+':
result = x + int(func[0][1])
elif operation == '-':
result = x - int(func[0][1])
elif operation == '*':
result = x * int(func[0][1])
elif operation == '/':
result = x // int(func[0][1])
return result
def zero(*func): #your code here
if func:
return operate(0, func)
else:
return 0
def one(*func): #your code here
if func:
return operate(1, func)
else:
return 1
def two(*func): #your code here
if func:
return operate(2, func)
else:
return 2
def three(*func): #your code here
if func:
return operate(3, func)
else:
return 3
def four(*func): #your code here
if func:
return operate(4, func)
else:
return 4
def five(*func): #your code here
if func:
return operate(5, func)
else:
return 5
def six(*func): #your code here
if func:
return operate(6, func)
else:
return 6
def seven(*func): #your code here
if func:
return operate(7, func)
else:
return 7
def eight(*func): #your code here
if func:
return operate(8, func)
else:
return 8
def nine(*func): #your code here
if func:
return operate(9, func)
else:
return 9
def plus(num): #your code here
op = '+' + str(num)
return op
def minus(num): #your code here
op = '-' + str(num)
return op
def times(num): #your code here
op = '*' + str(num)
return op
def divided_by(num): #your code here
op = '/' + str(num)
return op
def main():
print(seven(times(five())))
if __name__ == '__main__': main() |
4c6a4eda89d87e4d98576de3097a49cbf245e399 | Sanchezt99/numericalapp | /src/numericalapp/Equation_Systems/Methods/gaussSimple.py | 2,856 | 3.5625 | 4 | import numpy as np
def gauss_enter(a,size):
print(f"a {a} \n size {size}")
A = a[0:-size]
b = a[-size::]
print(f"A {A} \n b {b}")
A = np.array(A).reshape(size,size).astype(np.float64)
b = np.array(b).reshape(size,1).astype(np.float64)
return A,b
def gauss_elimination(a,b):
message = ""
etapas = []
matrixs = []
if a.shape[0] != a.shape[1]:
message += "Matrix A has to be square"
# file1.write("La matriz A debe ser cuadrada")
# file1.close()
# return message
if a.shape[1] != b.shape[0]:
message += "The number of columns of A must be the same as the number of rows of b"
# file1.write("El número de columnas de A debe ser el mismo al número de filas de b")
# file1.close()
# return message
if np.linalg.det(a) == 0:
print("DET = 0")
message = "Determinant of A must be different from zero"
# file1.write("El determinante de A debe ser diferente de 0")
# file1.close()
# return message
if message:
return message, [], [], []
if not message:
ns = "\n"*2
ab = np.concatenate((a,b), axis=1)
ab_original = np.copy(ab)
n,p = ab.shape
# file1.write("Eliminación Gaussiana Simple \n Etapa 0 \n")
ab = np.around(ab,6)
# file1.write(str(ab))
# file1.write(ns)
#ab.astype(float64)
if ab[0,0] == 0:
swap(ab,0,0)
for etapa in range(0,n-1):
etapas.append(etapa)
# file1.write(eta )
if ab[etapa,etapa] == 0:
ab = swap(ab,etapa)
for fila in range(etapa+1,n):
ab[fila,etapa::] = (ab[fila,etapa::] -(ab[fila, etapa]/ab[etapa,etapa] * ab[etapa,etapa::]))
ab1 = np.around(ab,3)
print(ab1)
matrixs.append(ab1)
# file1.write(str(ab))
# file1.write(ns)
# #break
x = sust_reg(ab)
# file1.write("Después de sustitución regresiva:\n x:\n")
# file1.write(str(x.T))
ans = np.round(x.T, 3).tolist()
return message, matrixs, ans, ab_original.tolist()
def swap(ab,etapa):
n, p = ab.shape
for i in range(etapa+1,n):
if ab[i,etapa] != 0:
ab[[etapa,i]] = ab[[i,etapa]]
return ab
def sust_reg(ab):
n = ab.shape[0]
x = np.zeros((1,n))
x[0,n-1] = ab[n-1,n]/ab[n-1,n-1]
for i in range(n-2,-1,-1):
# print("\n i",i)
aux = np.array([np.append( 1, x[0,i+1:n+1])])
aux1 = np.array([np.append(ab[i,n],-1 * ab[i,i+1:n])]).T
x[0,i] = np.dot(aux,aux1)/ab[i,i]
return x |
37ce6139868ea2ee70b5fff97ea7ae4a4e5a29d7 | Rishabhh/LeetCode-Solutions | /Arrays/419_Battle_ships_in_a_board.py | 646 | 3.796875 | 4 | class Solution:
def countBattleships(self, board):
"""
One-pass, O(1) space complexity.
Check if 'X' is left-most point of a ship.
:type board: List[List[str]]
:rtype: int
"""
res = 0
for r, row in enumerate(board):
for c, val in enumerate(row):
if val == 'X':
# check left
if r > 0 and board[r-1][c] == 'X':
continue
# check top
if c > 0 and board[r][c-1] == 'X':
continue
res += 1
return res
|
8fcc4929eb930f87f4068a2e616cfeafe2108b7b | JeromeSivadier/pyWebCrawler | /pyWebCrawler.py | 4,861 | 3.515625 | 4 | # coding=utf-8
import urllib2
from BeautifulSoup import BeautifulSoup
__version__ = "0.1"
AGENT = "%s/%s" % (__name__, __version__)
class Fetcher(object):
""" This class is designed to Fetch an URL and take all the links on the distant-page.
It will add the new urls to the URLS variable """
def __init__(self, url, urls, end):
self.url = url
self.urls = urls
self.end = end
def _addHeaders(self, request):
""" Add the headers to tell the website who we are """
request.add_header("User-Agent", AGENT)
def open(self):
""" Opens the url with urllib2 """
url = self.url
try:
request = urllib2.Request(url)
handle = urllib2.build_opener()
except IOError:
return None
return (request, handle)
def fetch(self):
""" Main function of the fetcher, will try to find the href
attributes inside the a tags and add them to the urls dictionnary """
tags = []
request, handle = self.open()
self._addHeaders(request)
if handle:
try:
# Reads the page and pass it to BS
content = unicode(handle.open(request).read(), "utf-8", errors="replace")
soup = BeautifulSoup(content)
# Searchs all the 'a' tags in the page
tags = soup('a')
except urllib2.HTTPError, error:
if error.code == 404:
print "ERROR: %s -> %s" % (error, error.url)
else:
print "ERROR: %s" % error
except urllib2.URLError, error:
print "ERROR: %s" % error
# Iterate over all the 'a' tags to find the 'href' attributes
for tag in tags:
href = tag.get("href")
# We dont need pdfs and no "false-links" and no url we have already
if (href is not None) and (href not in self.urls) and ("pdf" not in href):
# We only need http or https urls
if href.startswith("http://") or href.startswith("https://"):
self.urls[href] = dict()
self.urls[href]["parent"] = self.url
# If the URL in INSIDE our website, we keep it for the crawling
# Else it's here but we will not crawl it
# Self.end given by the user
if self.end in href:
self.urls[href]["toCrawl"] = True
else:
self.urls[href]["toCrawl"] = False
class Crawler(object):
""" This class is designed to crawl a website, starting at the root point and going deeper until
the specified depth is reached.
If the depth is None, it will crawl all the website.
The default ending condition is the root point, we don't want to crawl all the web..."""
def __init__(self, root, urls, ending_condition=None, depth=None):
self.root = root
self.urls = urls
self.depth = depth
self.remaining = -1
if ending_condition is None:
self.end = self.root
else:
self.end = ending_condition
def crawl(self):
""" Main function of the crawler, will crawl a website and fill the
urls dictionnary with the urls found in the website """
# Number of urls we have crawled
counter = 0
# Looks at the links in the root page
page = Fetcher(self.root, self.urls, self.end)
page.fetch()
print 'starting crawling'
# Urls remaining to crawl
to_crawl = [d for d in self.urls if self.urls[d]["toCrawl"] == True]
while to_crawl != [] and (self.depth > 0 or self.depth == None):
# For all the URLS remaining to crawl, we fetch it to take all the links
for url in to_crawl:
counter += 1
print "\n"
print "Fetching url : ", url, " (", counter, "/", self.remaining, ")"
page = Fetcher(url, self.urls, self.end)
self.urls[url]["toCrawl"] = False
page.fetch()
# At the end we decrease the depth : if it's equal to 0, it stops the crawling
if self.depth is not None:
self.depth -= 1
# Updating the urls to crawl
to_crawl = [d for d in self.urls if self.urls[d]["toCrawl"] == True]
self.remaining = len(to_crawl)
counter = 0
print "Remaining : ", self.remaining, " url(s) to crawl!", "\n"
print "Depth = ", self.depth, "\n"
|
cc613fb770a59a8cf7163cb42b541fedf6183bc1 | cheungnj/exercism | /python/armstrong-numbers/armstrong_numbers.py | 258 | 3.890625 | 4 | def is_armstrong(number):
num_string = str(number)
value = 0
length = len(num_string)
for c in num_string:
digit = int(c)
value += digit**length
if value > number:
return False
return value == number
|
dc619d397dab64a29b13ea560488141bb7f69da6 | minggaaaa/pycharm | /20211101/ex02.py | 284 | 3.859375 | 4 | #
# tuple = immutable =
# list = mutable
#
alist = [1,2,3]
btuple = (1,2,3)
print(alist)
print(btuple)
for i in alist:
print("alist i = ",i)
for i in btuple:
print("btuple i = ",i)
alist[1] =5
print(alist)
# btuple[1] = 5
# print(btuple)
s1 = "abcde"
s1[2] ='c'
print(s1) |
ee9fd8f76026b384b69342c22b350004ecf16d0c | brunocous/kbc_pyspark_training | /tests/test_distance_metrics.py | 804 | 3.546875 | 4 | """Exercise: implement a series of tests with which you validate the
correctness (or lack thereof) of the function great_circle_distance.
"""
import math
import pytest
from exercises.unit_test_demo.distance_metrics import great_circle_distance
def test_great_circle_distance():
# Write out at least two tests for the great_circle_distance function.
# Use these to answer the question: is the function correct?
p1, p2 = (0,0), (0,0)
northpole =(90, -22) # on the poles, longitude has no meaning
equator = (0, 89)
assert great_circle_distance(p1[0], p1[1], p2[0], p2[1]) == 0
expected = 6371*math.pi/2
assert great_circle_distance(northpole[0], northpole[1],
equator[0], equator[1]) == pytest.approx(expected)
|
cb8bd3f916370af063097baa82efbead39585059 | aerodame/sampler | /Algorithms/PairsSearch/Python/pairs_store.py | 1,080 | 3.859375 | 4 | """
PairsStore - Storing pairs of numbers and their sum key. Note that this is a general purpose
pairs store that could store pairs for numerous keys (hence the use of a Hashmap). A simpler
version of this would just be a list to store pairs for ONE key.
"""
class PairsStore:
def __init__(self):
# Initialize a HashMap ƒor our sums and pairs
self.T = {}
# get any pairs at key = k
def get_pairs(self, k):
if k in self.T:
return self.T[k]
else:
return [None]
# dump hash map
def dump_map(self):
print(f'Dump HashMap of {len(self.T)} sums')
for k in self.T:
print(f'sum:{k}, pairs: {self.T[k]}')
# Insert pair and sum (sum is the key in the HashMap)
def insert(self, x, y):
sum = x + y
pair = f'({x},{y})'
# get the key exists) then append the new string
if sum in self.T:
self.T[sum].append(pair)
# we must initialize the value (list) at key(sum), then append
else:
self.T[sum] = [pair] |
80989c0e5a09e2f3e9a4f68d8d5371a5422c347c | vipinpillai/ricochet-robots | /Ricochet.pyde | 8,770 | 4.0625 | 4 |
"""This program sets up and displays a puzzle based on the game
Ricochet Robots. The solve() method contains code to compute the solution to the puzzle."""
path_to_file_containing_puzzle = "test"
from Robot import Robot
from Robot import Node
import time
def solve():
"""This method will compute and return the solution if it exists, as a list of (row, column) tuples, zero-based.
Else, an exception will be raised stating a loop was detected and that no solution exists."""
robot = Robot(number_of_rows, number_of_columns, ball_location, goal_location, block_locations)
navigation_node = robot.navigate_best_heuristic()
if robot.loop_exists:
raise Exception('Loop detected! No solution exists.')
elif robot.goal_found:
return navigation_node.traversed_node_list
# -------------------------------------------------------------------------
# ----- The following code provides the GUI and should not be altered -----
def setup():
"""This method is called automatically once, when program starts.
"""
global game
size(300, 300) # arguments _must_ be literal integers, not variables!!!
read_puzzle(path_to_file_containing_puzzle)
game = Ricochet(number_of_rows, number_of_columns)
game.place_blocks(block_locations)
game.place_ball(ball_location)
game.place_goal(goal_location)
solution = solve()
game.set_path(solution)
def draw():
"""This method is called automatically 60 times a second.
Its job is to draw everything.
"""
background(255)
game.draw_grid(game.rows, game.columns)
game.draw_blocks()
game.draw_goal()
game.draw_ball()
game.move_ball()
def read_puzzle(file_path):
"""Read in a ricochet puzzle, putting results in global variables.
Values must be one per line, in the given order. Comments,
indicated with a # character, may occur after the value."""
global number_of_rows, number_of_columns, block_locations
global ball_location, goal_location
file = open(file_path, "r")
number_of_rows = read_and_evaluate_line(file)
number_of_columns = read_and_evaluate_line(file)
block_locations = read_and_evaluate_line(file)
ball_location = read_and_evaluate_line(file)
goal_location = read_and_evaluate_line(file)
file.close()
def read_and_evaluate_line(file):
line = file.readline()
data = eliminate_comment(line)
return eval(data)
def eliminate_comment(line):
"""Removes the # character (if there is one) and everything after it."""
hash_at = line.find("#")
if hash_at >= 0:
return line[:hash_at]
else:
return line
class Ricochet:
"""This defines the display for the game. To use this display,
create a "ricochet object" with
game = ricochet(number of rows, number of columns)
then call any or all of the methods
* game.place_ball(row, column)
* game.place_goal(row, column)
* game.place_blocks( a list of (row, column) tuples )
* game.set_path( a list of (row, column) tuples )
"""
def __init__(self, number_of_rows, number_of_columns):
"""This method is automatically called when you say
game = ricochet(number of rows, number of columns)
and should never be called explicitly. It contains a
few constants you may wish to modify.
"""
self.cell_size = min(width // (number_of_columns + 2),
height // (number_of_rows + 2))
self.x = self.cell_size # position of left edge of grid
self.y = self.cell_size # position of top edge of grid
self.rows = number_of_rows
self.columns = number_of_columns
self.block_locations = [] # to be filled in
self.path = [] # to be filled in
self.ball_x_y_position = (-1, -1) # to be replaced
self.goal_location = -1 # leave alone!
self.initial_delay = 60 # delay before ball starts to move
ellipseMode(CORNER)
strokeCap(ROUND)
def place_ball(self, location):
"""Specifies the initial location of the red ball."""
self.ball_x_y_position = self.row_column_to_x_y(location)
def place_goal(self, location):
"""Specifies the location of the goal cell (green X)."""
self.goal_location = location
def place_blocks(self, locations):
"""Given any number of (row, column) tuples, place blocks at
those locations. Previous blocks, if any, are forgotten.
"""
self.block_locations = list(locations)
def set_path(self, locations):
"""Given a list of (row, column) tuples, define a path
for the red ball to follow, starting from where it has been
placed initially. The ball will move to each location in
turn.
This method does NOT test whether the path is legal; it
will simply move the ball where it is told to.
"""
self.path = list(locations)
self.path_index = -1 # used to keep track of red ball moves
def move_ball(self):
"""Given a list of (row, column) tuples, define a path
for the red ball to follow, starting from its current
location. The ball will move to each location in turn.
This method does NOT test whether the path is legal; it
will simply move the ball where it is told to, even
diagonally, through blocks, or off the screen.
"""
if self.initial_delay > 0:
self.initial_delay -= 1
return # Pause before ball starts to move
if self.path_index == -1 :
self.path_index = 0
return # Just starting the path
if self.path_index >= len(self.path):
noLoop()
return # reached end of path
elif self.ball_x_y_position == \
self.row_column_to_x_y(self.path[self.path_index]):
self.path_index += 1
return # reached one location, ready to move to next location
else:
self.move_ball_toward(self.path[self.path_index])
return # moved slightly closer to next desired location
def draw_grid(self, rows, columns):
"""Draw a rows x columns grid starting at (x, y)."""
size = self.cell_size
x = size
y = size
stroke(0)
strokeWeight(1)
if rows > 0:
h_length = size * columns
v_length = size * rows
for i in range (0, rows + 1):
line(x, y + i * size, x + h_length, y + i * size)
for i in range (0, columns + 1):
line(x + i * size, y, x + i * size, y + v_length)
def draw_blocks(self):
"""Draws a black square at every location in block_locations."""
fill(0)
for location in self.block_locations:
(x, y) = self.row_column_to_x_y(location)
rect(x, y, self.cell_size, self.cell_size)
def draw_ball(self):
"""Draws the red ball at the position indicated by
ball_x_y_position, which is not necessarily exactly
within a single cell.
"""
fill(255, 0, 0)
noStroke()
(x, y) = self.ball_x_y_position
ellipse(x + 2, y + 2, self.cell_size - 3, self.cell_size - 3)
def draw_goal(self):
"""Draws a green X at goal_location."""
stroke(0, 255, 0)
strokeWeight(2)
(x, y) = self.row_column_to_x_y(self.goal_location)
line(x, y, x + self.cell_size, y + self.cell_size)
line(x, y + self.cell_size, x + self.cell_size, y)
def move_ball_toward(self, new_location):
"""Adjust the current (x, y) position of the red ball to be
slightly closer to the new location, given as (row, column)."""
(old_x, old_y) = self.ball_x_y_position
(new_x, new_y) = self.row_column_to_x_y(new_location)
self.ball_x_y_position = (self.toward(old_x, new_x),
self.toward(old_y, new_y))
def toward(self, frum, to): # "from" is a reserved word
"""Return one of the values frum-1, frum, or frum+1,
whichever is closer to 'to'."""
if frum < to: return frum + 1
elif frum > to: return frum - 1
else: return frum
def row_column_to_x_y(self, location):
"""Convert a (row, column) tuple to the (x, y) coordinates of
the top left corner of the cell at that location."""
(row, column) = location
return (self.x + column * self.cell_size, self.y + row * self.cell_size) |
496027764e253a16a16269652e8287bad5472268 | camilaffonseca/Learning_Python | /Prática/ex036.py | 669 | 4.1875 | 4 | # coding: utf-8
'''
Escreva um programa em Python que leia um número inteiro qualquer
e peça para o usuário escolher qual será a base de conversão:
1 para binário, 2 para octal e 3 para hexadecimal.
'''
numero = int(input('Digite um número inteiro: '))
base = input('''Escolha a base para conversão...
\n[1] Binário \n[2] Octal \n[3] Hexadecimal
\nSua opção > ''')
if base == '1':
conversão = bin(numero)
base = 'Binário'
elif base == '2':
conversão = oct(numero)
base = 'Octal'
else:
conversão = hex(numero)
base = 'Hexadecimal'
print(f'O número {numero} convertido para {base} fica {conversão}')
|
a91ac887afda4916573496a0f689ad38918b49f2 | prolo09/pari_2020 | /part2/ex5/ex5.py | 2,162 | 3.9375 | 4 | #!/usr/bin/env python
import readchar
listCharAsc = []
def printALLCharsUpTO():
print ("intreduza um carater :")
stop_char = readchar.readchar()
charInAscii = ord(stop_char) # ord serve para por em ascii
for x in range(32, charInAscii):
xChar = chr(x) # passa de ascii para o seu carater
listCharAsc.append(xChar)
# _______________ ex 4.b_____________________
def readAllUPTO():
print ("intreduza carater:")
intVariavel = readchar.readchar()
while intVariavel != 120:
intVariavel = readchar.readchar()
intVariavel = ord(intVariavel)
if intVariavel == 120:
break
else:
print ("volte a inserir:")
# ______________ex 4.c_______________________
def countNumberUPTO():
total_number = 0
total_other = 0
inputs = [] # crio a list de imputs
while True:
print ("intreduza carater:")
intVariavel = readchar.readchar()
inputs.append(intVariavel) # acrecenta varaiveis no input
# retiri o isnumeric pois so dava para python3 e nao tinha conseguido fazer isso anteriormente
intVariavel = ord(intVariavel)
if intVariavel != 120:
print ("intreduza o valor outra vez :")
else:
break
# para destingir se e numero ou nao
for input in inputs: # vai correndo as variaveis que tenho nas listas
if input.isdigit():
total_other = total_number + 1
else:
total_number = total_number + 1
print ("you entered " + str(total_number) + "numbers.")
print ("you entered " + str(total_other) + "others.")
# ex 5c
dict_other={}
for idx,input in enumerate(inputs): # o enumerate inumera as variavais para outra variavel que tinhamos
if not input.isdigit():
dict_other[idx]=input # add new key-value to dictianary
print ('dint_other '+ str(dict_other))
# ex 5c
# use de sort na lista e organiza sozinho as variaveis ...
def main():
printALLCharsUpTO()
print (listCharAsc)
readAllUPTO()
countNumberUPTO()
if __name__ == '__main__':
main()
|
4d4ea6eca9acb6ba0e19212d3ecf3d0474f20d99 | tmayphillips/DigitalCrafts-Assignments | /day08_text_editor.py | 615 | 3.90625 | 4 | with open('learning_python.txt', 'w') as file_object:
file_object.write("In Python you can create and use variables.\n")
file_object.write("In Python you can create classes.\n")
file_object.write("In Python you can do unit tests.\n")
file_object.write("In Python you can create and edit files.\n")
with open('learning_python.txt') as file_object:
contents = file_object.read()
print(contents)
with open('learning_python.txt') as file_object:
for line in file_object:
print(line)
with open('learning_python.txt') as file_object:
lines = file_object.readline()
print(lines) |
63d48fffd6364197ce1266ef2778b1b75a357eb3 | chrzhang/euler | /p050ConsecutivePrimeSum/p050.py | 2,127 | 3.6875 | 4 | import math
import time
"""
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
Author: Christopher Zhang
"""
def genPrimes(limit):
"Generates an array of indices containing whether or not they are prime up to and including a given limit using a Sieve of Eratosthenes"
primes = [1] * (limit + 1)
if (limit < 2):
print("Please enter a value that is at least 2.")
return
primes[0] = 0
primes[1] = 0
i = 2 # Start at 2
while (i <= math.sqrt(limit)): # A number will be prime if no factors up to its sqrt have been found that is not == 1
if (primes[i] == 1):
j = 2
while (i * j <= limit):
primes[i*j] = 0
j += 1
i += 1
return primes
start_time = time.time()
bound = 1000000
primalities = genPrimes(bound)
seqPrime = []
for x in range(0, bound):
if (primalities[x]): # For each one found
seqPrime.append(x)
total = 0
count = -1 # Currently unfound
indexFromStart = 0
while(indexFromStart < len(seqPrime)): # Go from ifs = 0 to ifs = # of primes
thisTotal = 0
indexAsStart = indexFromStart
while (indexAsStart < len(seqPrime)): # Go from current = ifs to current = # of primes
thisTotal += seqPrime[indexAsStart]
if (thisTotal > bound):
break # Have exceeded realm of possibility
elif (((indexAsStart - indexFromStart) > count) and (thisTotal > total) and (primalities[thisTotal])):
total = thisTotal # When a new answer has been found in the sum of those that remain (length greater, sum is prime, and is not already found)
count = indexAsStart - indexFromStart
indexAsStart += 1
indexFromStart += 1
print(total)
print ("Running Time:", time.time() - start_time, "seconds")
|
27b57390514e7d43677f29d20d1d439d0bd575cf | projectinnovatenewark/csx | /Students/Semester2/lessons/students/3_classes_and_beyond/18_access_modifiers/18_access_modifierstodo.py | 983 | 4.15625 | 4 | """
ToDo for 18_access_modifiers
"""
# TODO: Section 4
# Define a class called "User" that has the public instance attribute "username" and the private
# instance attribute "password". Then define a method within the "User" class called
# "check_password()" that will take an input with the question reading "What is the password?: ".
# The method should compare the input to the password defined in the instantiation of the "User"
# class. If the passwords match, then the method should print "The password entered is correct."
# If the passwords do not match, the method should print the statement "The password entered is
# incorrect."
# Next define an instantiation of the "User" class with "username" equal to "cool_coder" and
# password equal to "abcd1234!" and store it in the variable "user_1". Then call the
# "check_password()" method.
# Lastly, try to print the "password" variable directly. If you receive an error, consider the
# reasoning behind this output.
|
458476227113d539676d599a0754d6c7c8dd46a3 | miaviles/Data-Structures-Algorithms-Python | /linkedLists/right_shift.py | 2,375 | 4.0625 | 4 | """
Right Shift A Singly Linked List
Given the head of a singly linked list, rotate the list k steps to the right.
Example 1:
Input:
k = 2
1 -> 2 -> 3 -> 4 -> X
Output:
3 -> 4 -> 1 -> 2 -> X
Example 2:
Input:
k = 4
4 -> 1 -> 6 -> 7 -> X
Output:
4 -> 1 -> 6 -> 7 -> X
Constraints
k >= 0
"""
class Node:
def __init__(self, value, next):
self.value = value
self.next = next
from collections import deque
# https://wiki.python.org/moin/TimeComplexity
# rotate = O(k)
class NaiveSolution:
def rotateRight(self, head, k):
"""
Make use of collections.deque and the efficient O(k) rotate operation
Time : O(max(k, N)) deque rotate has time complexity of O(k)
Space : O(N)
"""
items = deque([head.value])
temp = head.next
while temp:
items.append(temp.value)
temp = temp.next
for _ in range(k):
items.rotate()
head = None
temp = head
for j in range(len(items)):
new_node = Node(items[j], None)
if head == None:
head = new_node
temp = head
else:
temp.next = new_node
temp = temp.next
return head
class OptimizedSolution:
def rotateRight(self, head, k):
"""
Approach
----
Example k = 2
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> None
Head becomes 5
1 -> 2 -> 3 -> 4 5 -> 6
5 -> 6 -> 1 -> 2 -> 3 -> 4 -> None
Time : O(N)
Space : O(1)
"""
# edge case
if k == 0:
return head
size_list = 0
temp = head
# get the size of the list O(N)
while temp:
size_list += 1
temp = temp.next
# O(k) find the new head
count = 0
temp = head
while count != size_list - k % size_list - 1:
count += 1
temp = temp.next
# change to tail
head_new_list = temp.next
temp.next = None
# reform the lists
temp = head_new_list
while temp.next != None:
temp = temp.next
temp.next = head
return head_new_list
s1 = NaiveSolution()
s2 = OptimizedSolution()
l = Node(1, Node(2, Node(3, Node(4, None))))
print(s2.rotateRight(l, 2))
|
27002ad6d683367124f023b14b446b929f042cc6 | umnstao/lintcode-practice | /bfs/tree(no need to check)/70.binaryTreeLevelTraversal.py | 812 | 3.828125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: buttom-up level order in a list of lists of integers
"""
def levelOrderBottom(self, root):
# write your code here
result = []
if not root:
return result
q = [root]
while q:
size = len(q)
level = []
for _ in range(size):
head = q.pop(0)
level.append(head.val)
if head.left:
q.append(head.left)
if head.right:
q.append(head.right)
result.insert(0,level)
return result
|
e8342235babeb31ed1b2600b6d5d731604812f16 | mariuszurbaniak/CodeWars | /nameInText.py | 145 | 3.890625 | 4 | def name_in_str(str, name):
it = iter(str.lower())
print(all(c in it for c in name.lower()))
name_in_str("Across the rivers", "chiis")
|
8955ac2f774c8bc3f74eff39de10b044a55987e9 | CollegeBoreal/INF1042-202-20H-02 | /P.Projets/300115140/b300115140.py | 1,450 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 14:21:40 2020
Conception d'un jeu dela tortue avec Python Turtle Graphics
@author: zacks
"""
import turtle
import random
zack = turtle.Turtle()
# Utilisation des variables
zack = turtle.Turtle()
zack.color("red")
zack.pensize(5)
zack.shape("turtle")
zack.forward(100)
zack.left(90)
zack.forward(100)
zack.left(90)
zack.forward(100)
zack.left(90)
zack.forward(100)
zack = turtle.Turtle()
zack.speed(5)
zack = turtle.Turtle()
zack.color("red", "blue") # le bleu est la couleur de remplissage
zack.width(5)
colors = ["red", "blue","green", "purple", "yellow", "orange", "black"]
for x in range(5):
randColor = random.randrange(0, len(colors))
rand1 = random.randrange(-300,300)
rand2 = random.randrange(-300,300)
zack.color(colors[randColor], colors[random.randrange(0, len(colors))])
zack.penup()
zack.setpos((rand1, rand2))
zack.pendown()
zack.begin_fill()
zack.circle(50)
zack.end_fill()
from turtle import Turtle
from turtle import Screen
screen = Screen()
t = Turtle("turtle")
def dragging(x, y):
t.ondrag(None)
t.setheading(t.towards(x, y))
t.goto(x, y)
t.ondrag(dragging)
def clickRight():
t.clear()
def main(): # fonction pour faire marcher le programme
turtle.listen()
t.ondrag(dragging) # permet de faire bouger la tortue
turtle.onscreenclick(clickRight, 3)
screen.mainloop()
main()
|
a3ad0a6233acf99fc8b0a18d5856b86637332748 | ksmdeepak/Leetcode | /Python Solutions/Rotate_Array_189.py | 685 | 3.53125 | 4 | class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
start =0
count =0
while count < len(nums):
current = start
prev = nums[start]
flag =0
while start!=current or flag==0:
flag+=1
nex = (current+k)%len(nums)
temp = nums[nex]
nums[nex] = prev
prev = temp
current = nex
count+=1
start+=1
|
e75926826748fcd818d1f7fa153ca42785a62fb2 | pengshishuaia/OA_TEST | /test_case/生成器和迭代器/生成器的应用.py | 853 | 4.03125 | 4 | '''
进程---》线程---》协程
生成器;generator
生成器一般应用在协程上面,意思就是生成器交替执行
定义生成器的方式:
1,通过列表推导式
g = (x for x in range(6))
2,函数+yield
def func():
。。。
yield 相当于return
g = func()
产生元素
1,next(generator) ---每次调用都会生产一个新的元素,如果元素产生完毕,再次调用的话就会产生异常
2,生成器自己的方法:
g.__next__()
g.send(value)
'''
def tarde1(i):
for i in range(10):
print('正在搬第{}快砖'.format(i))
yield
def tarde2(x):
for x in range(10):
print('正在听第{}首歌'.format(x))
yield
g1 = tarde1(5)
g2 = tarde2(5)
while True:
try:
g1.__next__()
g2.__next__()
except:
break
|
ade79fb0adaa2141143b383ed323a0873383a42f | erfannoury/new-eleusis | /Game.py | 11,448 | 3.65625 | 4 | """
Contains the Player and Scorer classes
"""
import random
from rule_functions import *
import phase2
class Player:
"""
The Player class which contains the logic of the New Eleusis game.
Parameters
----------
cards: list
The initial list of legal cards from the dealer which starts the game.
max_rule_constancy: int
The maximum number of turns where if the hypothesis set stays unchanged
then we can declare the game finished and return a rule.
"""
def __init__(self, cards, max_rule_constancy=5):
assert len(cards) == 3
self.board_state = []
for c in cards:
self.board_state.append((c, []))
self.hypothesis_set = []
self.applyAcceptedCard(cards[2])
self.hand = [generate_random_card() for i in range(14)]
self.max_rule_constancy = max_rule_constancy
self.constant_rule_count = 0
self.turn = 0
def boardState(self):
"""
This function returns the list of cards played so far
Returns
-------
board_state: list
The list describing the state of the game so far
"""
return self.board_state
def chooseCard(self):
"""
This function chooses which card to play next
Returns
-------
card: str
The next card to play
"""
prev = self.board_state[-1][0]
prev2 = self.board_state[-2][0]
random.shuffle(self.hand)
rule_tree = parse(combineListOfRules(self.hypothesis_set))
if self.turn % 2 == 0:
for cur in self.hand:
if rule_tree.evaluate([prev2, prev, cur]):
return cur
else:
for cur in self.hand:
if not rule_tree.evaluate([prev2, prev, cur]):
return cur
return random.choice(self.hand)
def applyAcceptedCard(self, current):
"""
This function adapts the rules for when a card is accepted
(if necessary)
Parameters
----------
current: str
The card that was accepted
"""
assert current == self.board_state[-1][0]
previous = self.board_state[-2][0]
previous2 = self.board_state[-3][0]
cards = [previous2, previous, current]
rule_changed = False
# first check to see if any of the rule sets accept this card
for rule_set in self.hypothesis_set:
if parse(combineRulesWithOperator(rule_set, 'and')).evaluate(
cards):
return
add_new_set = True
for rule_set in sorted(self.hypothesis_set, key=lambda rs: len(rs),
reverse=True):
if not any([parse(r).evaluate(cards) for r in rule_set]):
continue
else:
add_new_set = False
new_rule_set = []
for r in rule_set:
if parse(r).evaluate(cards):
new_rule_set.append(r)
if len(rule_set) != len(new_rule_set):
rule_changed = True
rule_set.clear()
for r in new_rule_set:
rule_set.append(r)
if add_new_set:
rule_changed = True
self.hypothesis_set.append(getRulesForSequence(cards))
new_hypothesis_set = []
for rule_set in self.hypothesis_set:
if len(rule_set) > 0:
new_hypothesis_set.append(rule_set)
self.hypothesis_set = new_hypothesis_set
if rule_changed:
self.constant_rule_count = 0
def applyRejectedCard(self, current):
"""
This function adapts the rules for when a card is rejected
(if necessary)
If a rule r1 (which is a disjunction of a number of predicates) accept
a cards sequence, then every predicate in rule r1 holds for the cards
sequence. Therefore, if we write r1 as p & q,
Parameters
----------
current: str
The card that was rejected
"""
assert current == self.board_state[-1][1][-1]
previous = self.board_state[-1][0]
previous2 = self.board_state[-2][0]
cards = [previous2, previous, current]
rule_changed = False
for rule_set in sorted(self.hypothesis_set, key=lambda rs: len(rs)):
if parse(
combineRulesWithOperator(rule_set, 'and')).evaluate(cards):
rule_changed = True
# all of the subrules were true for this cards, what should
# be done?
# Suppose the rule_set was p & q and the given rejected cards
# can be described by p & q & r & s. Now we search all card
# sequences that are only accepted by this rule_set and find
# the set of their properties, which becomes {p, q, r, t, u}.
# Now the updated rule_set should be p & q & !s, since s was
# not in the set of attributes that previous accepted card
# sequences had.
attr_set = set()
for i in range(len(self.board_state) - 2):
c_seq = list(
map(lambda c: c[0], self.board_state[i:i + 3]))
if not any([parse(
combineRulesWithOperator(rs, 'and')).evaluate(c_seq)
for rs in self.hypothesis_set if rs != rule_set]):
attr_set.update(getRulesForSequence(c_seq))
neg_rules = []
for r in getRulesForSequence(cards):
if (r not in rule_set) and (r not in attr_set):
neg_rules.append(r)
for r in neg_rules:
rule_set.append(negate_rule(r))
else:
# if the rule didn't accept the card, then there is no need
# to change the rule, we can leave it as is
continue
new_hypothesis_set = []
for rule_set in self.hypothesis_set:
if len(rule_set) > 0:
new_hypothesis_set.append(rule_set)
self.hypothesis_set = new_hypothesis_set
if rule_changed:
self.constant_rule_count = 0
def simplifyRules(self):
"""
This function gets rid of any redundant rules
"""
return combineListOfRules(self.hypothesis_set)
def update_card_to_boardstate(self, card, result):
"""
Update your board state with card based on the result
Parameters
----------
card: str
The card that was played
result: bool
Whether the dealer accepted the card or not
"""
self.turn += 1
self.constant_rule_count += 1
if result:
self.board_state.append((card, []))
self.applyAcceptedCard(card)
else:
self.board_state[-1][1].append(card)
self.applyRejectedCard(card)
def play(self):
"""
Either plays a card or returns a rule
Returns
-------
chosen: str
The next card to be played
OR
rule: str
The rule hypothesized so far
"""
if phase2.game_ended:
return combineListOfRules(self.hypothesis_set)
if self.constant_rule_count == self.max_rule_constancy:
phase2.game_ended = True
return combineListOfRules(self.hypothesis_set)
chosen = self.chooseCard()
self.hand.append(generate_random_card())
del self.hand[self.hand.index(chosen)]
return chosen
class Scorer:
"""
The Scorer class which implements a function that scores players
Parameters
----------
rule_expr: str
String representation of a rule
"""
def __init__(self, rule_expr):
self.setRule(rule_expr)
def rule(self):
"""
This function returns the true game rule to the user
Returns
-----------
true_rule: Tree
The rule tree that we have estimated so far in the game
"""
return self.true_rule
def setRule(self, rule_expr):
"""
This function sets a given rule for a game
Parameters
----------
rule_expr: str
String representation of a rule
"""
try:
self.true_rule = parse(rule_expr)
except:
raise ValueError("Invalid Rule")
def score(self, player, is_player):
"""
This function returns the score for a given Player
Parameters
----------
player: object
A Player object which implements the following functions:
* player.boardState()
Which returns the board state of the game as a list of
tuples
* player.play()
Which returns the final rule, because game_ended is set to
True
is_player: bool
Whether the given player ended the game or not
Returns
-------
score: int
Score of the game played for the given player
"""
print("Inside the score function")
score = 0
cardsPlayed = 0
boardState = player.boardState()
for play in boardState:
# look at legal plays
# +1 for every successful play over 20 cards and under 200 cards
cardsPlayed += 1
if cardsPlayed > 20:
score += 1
# look at illegal plays
# +2 for every unsuccessful play
for card in play[1]:
cardsPlayed += 1
score += 2
phase2.game_ended = True
guessedRule = player.play()
assert not is_card(guessedRule)
# Now check that the rule describes all of the cards played
describes = True
guessedTree = parse(guessedRule)
for i in range(2, len(boardState)):
if not guessedTree.evaluate(
[boardState[i - 2][0], boardState[i - 1][0],
boardState[i][0]]):
describes = False
for failedCard in boardState[i][1]:
if guessedTree.evaluate(
[boardState[i - 1][0], boardState[i][0],
failedCard]):
describes = False
if not describes:
# +30 for a rule that does not describe all cards on the board
score += 30
validReal = set(getAllValidSequences(self.true_rule))
validGuess = set(getAllValidSequences(guessedTree))
# the rules are the same
if len(validGuess ^ validReal) > 0:
# +15 for a rule that is not equivalent to the correct rule
score += 15
else:
# Each player that guesses the correct rule with few or no extra
# terms, receives an additional bonus of -75 points
score -= 75
if is_player:
# If the player that ended the game gives the correct rule,
# it receives an additional -25 points
score -= 25
return score
|
ae03842ad370c886f70585c3407726b5229f32cf | twinkle2002/Python | /altrnatvconstructor.py | 825 | 3.828125 | 4 | class Employee:
no_of_leaves = 8
def __init__(self,name,salary,role):
self.name = name
self.salary = salary
self.role = role
def printdetails(self):
return f"name is {self.name}. salary is {self.salary}. and role is {self.role}"
# classmethod
# def change_leaves(cls, newleaves):
# cls.no_of_leaves = newleaves
classmethod
def from_dash(cls, string):
# params = string.split("-")
# print(params)
# return cls(params[0],params[1],params[2])
return cls(*string.split("-"))
murat = Employee("Murat",4500,"Instructor")
ahaan = Employee("Ahaan",4554,"Student")
noel = Employee.from_dash("noel-456-student")
# murat.change_leaves(34)
# print(murat.printdetails())
# print(murat.no_of_leaves)
print(noel.salary)
# 57th vedio |
a9e4642163c21bbe5e1cde0ef11851f5659694fe | Protino/HackerRank | /Algorithms/Implementation/SherlockAndTheBeast.py | 177 | 3.75 | 4 | for _ in range(int(raw_input())):
y=int(raw_input())
z=y
while(z%3!=0):
z-=5
if(z<0):
print '-1'
else:
print z*'5'+(y-z)*'3'
|
ba14ab08a00494523afdb0b86e3e4c066b812908 | florekem/python_projekty | /codewars/codewars8.py | 824 | 3.734375 | 4 |
"""
pytania:
1. Dlaczego po apostrofie (lub innym znaku z poza alfabetu .title() podnosi do uppercase?
c = "'"
whereisit = [pos + 1 for pos, char in enumerate(words_upper) if char == c]
to jakbym zapisal to tak:
enum = enumerate(words_upper)
[x for x, char in enum if char == c] -> iterator
[x+1 for x,char in enum if char == c]
(x for x, char in enum if char == c) -> generator
rozpracowac to ^^
to co nizej w list comprehensions (rozwiazanie kogostam):
def toJadenCase(string):
return " ".join(w.capitalize() for w in string.split())
"""
def toJadenCase(string):
words_upper = string.split()
print(words_upper)
lista = []
for i in words_upper:
lista.append(i.capitalize())
out = " ".join(lista)
return out
toJadenCase("chuj dupa kurwa jeban'amac")
|
37abfd49c7d22d3e3443d08078e161087e82d7fa | Christy538/Hacktoberfest-2021 | /PYTHON/BFS.py | 621 | 4.125 | 4 | graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
|
51454b13d0e8f13c9aea938595ad25ec81e3c0de | JenySadadia/MIT-assignments-Python | /Assignment2/Exercise2.4.py | 650 | 4.03125 | 4 | ##Author : Group 4
##Assingnment 2
## --------------------Exercise 2.4.1--------------
import math
import random
def rand_divis_3():
number = random.randint(0,100)
print ("number: " +str(number))
if number%3 == 0:
return True
else:
return False
print rand_divis_3()
#---------------------------Exercise 2.4.2----------------------
print ("Random die print for three times")
def roll_dice(sides, dice):
while dice>0:
dice -= 1
print random.randint(1,sides)
return ("That's all!")
print (roll_dice(6,3))
print (roll_dice(4,4))
print (roll_dice(10,2))
|
6e7f66b357fe987e7f07b6fca47180a570211106 | DmitriiBaranovskii/learn-homework-1 | /3_for.py | 881 | 4.0625 | 4 | """
Домашнее задание №1
Цикл for: Оценки
* Создать список из словарей с оценками учеников разных классов
школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
* Посчитать и вывести средний балл по всей школе.
* Посчитать и вывести средний балл по каждому классу.
"""
import random
def main():
grades = [{'school_class': f'{school_class}a', 'scored':[random.randrange(1, 5, 1) for i in range(5)]} for school_class in range(5)]
school_average = {grade['school_class']: sum(grade['scored']) / len(grade['scored']) for grade in grades}
school_average['school_average'] = sum(school_average.values()) / len(school_average)
print(school_average)
if __name__ == "__main__":
main()
|
2fe992b1d202abf66d1aabb205981a65aec183d4 | kvijayenderreddy/march2020 | /userDefinedFunctions/function.py | 1,126 | 4.28125 | 4 | # list = [1,2,3,4,5]
def myName(name="Rayesa"):
print("My Name is", name)
# print("My Name is " + name)
# myName(list)
def listItertion(list):
for i in list:
print(i)
# listItertion(list)
def myNewName(name='Anjali'):
returnString = "My Name is" + name
print(returnString)
return returnString
# print(myNewName("Preeti"))
def ourNames(name1, name2, name3):
print("Class attendees:\n", name1, name2, name3)
# ourNames("Anjali", "Preeti", "Rayesa")
# ourNames(name2="Preeti", name1="Anjali", name3="Rayesa")
# Create a function which takes one parameter and will return the parameter value 3 times
def iterate3Times(text):
for i in range (3):
print (text)
# iterate3Times("Rayesa")
def my_func(value1, iterations):
print((value1+"\n") * iterations)
# for i in range(3):
# print (value1)
my_func("Test", 4)
# Create the function taking two parameters with first the string, and other the integer iteration count
# def value(name='ray'):
# for i in list:
# return("hello", name)
#
#
# print(value(1))
# print(value(2))
# print(value(3))
|
e21cd44fcf2235ecaf33ee5553b0654685c0f279 | michaelhuo/pcp | /98.py | 1,554 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def _isValidBST(root: TreeNode) -> (bool, int, int):
if not root:
return (True, None, None)
root_val = root.val
left_valid, left_min, left_max = _isValidBST(root.left)
if not left_valid:
return (False, None, None)
if left_min is None:
left_min = root_val
if left_max is None:
left_max = root_val
else:
if left_max >= root_val:
return (False, None, None)
else:
left_max = root_val
right_valid, right_min, right_max = _isValidBST(root.right)
if not right_valid:
return (False, None, None)
if right_min is None:
right_min = root_val
else:
if right_min <= root_val:
return (False, None, None)
else:
right_min = root_val
if right_max is None:
right_max = root_val
return (True, left_min, right_max)
if not root:
return True
(is_valid, left_val, right_val) = _isValidBST(root)
return is_valid
|
d26f0fd56aebfffba575a1799e5b8e109afa8726 | mason-larobina/projecteuler-py | /006/6.py | 715 | 3.90625 | 4 | #!/usr/bin/python
# Mason Larobina <mason.larobina@gmail.com>
# === Problem 6 ==============================================================
# The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
#
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 - 385 = 2640.
#
# Find the difference between the sum of the squares of the first one hundred
# natural numbers and the square of the sum.
# ============================================================================
print sum(range(101))**2 - sum(x**2 for x in range(101))
|
c9cd9aff0bf2935a85e1af761e37d0658aa0758f | MikeMinheere/1.3.1-Werken-met-condities | /game.py | 7,328 | 3.609375 | 4 | #Mike Minheere 99067548
import time
def path1():
print('je komt een verlaten dorp tegen, wat doe je?')
verlatenDorp = input('huizen doorzoeken (1) of doorlopen? (2) ')
if verlatenDorp == '1':
time.sleep(2)
print()
print('je gaat de huizen doorzoeken en je vind niet veel.')
time.sleep(2.5)
print('in het laatste huis dat je doorzoekt vind je wel een mes!')
time.sleep(2.5)
print('je gaat verder door het bos lopen totdat er ineens een wolf voor je neus staat!')
time.sleep(2.5)
print('gelukkig heb jij een mes gevonden! je steekt de wolf in zijn poot.')
time.sleep(2.5)
print('de wolf rent weg en, voor nu, ben je veilig.')
time.sleep(3)
print('je loopt verder en op een gegeven moment kom je een weg tegen.')
time.sleep(1)
weg = input('ga je naar links (1) of rechts? (2) ')
if weg == '1':
time.sleep(1)
print('je gaat naar links')
time.sleep(2.5)
print('je blijft lopen en lopen, maar je komt niks tegen.')
time.sleep(5)
print('je begint de hoop op te geven...')
time.sleep(5)
print('je word wakker in een ziekenhuis in een stad!')
time.sleep(2.5)
print('iemand had je aan de zijkant van de weg gevonden en meegenomen naar het ziekenhuis!')
time.sleep(4)
print()
print('YOU WIN!')
elif weg == '2':
time.sleep(1)
print('je vind een dode egel langs de weg')
time.sleep(2.5)
print('ga je de egel begraven?')
egel = input('ja (1) of nee (2)? ')
if egel == '1':
time.sleep(1)
print('je besluit de egel te begraven, maar de wolf van eerder kwam ineens uit de bosjes')
time.sleep(2)
print('je zag hem niet aankomen en hij beet jou in je nek')
time.sleep(4)
print()
print('YOU DIED')
elif egel == '2':
time.sleep(2)
print('je laat de egel wegrotten en loopt verder.')
time.sleep(4)
print('je blijft lopen en lopen, maar je komt niks tegen.')
time.sleep(5)
print('je begint de hoop op te geven...')
time.sleep(6)
print()
print("YOU DIED")
elif verlatenDorp == '2':
time.sleep(1.5)
print('je komt een wolf tegen en je hebt niks om jezelf te verdedigen')
print()
time.sleep(4)
print('YOU DIED')
def path2():
time.sleep(1.5)
print('je loopt een tijdje door een bos totdat je ineens een meer tegenkomt.')
time.sleep(2.5)
print('je ziet rechts van je een oude boot liggen, wat doe je?')
time.sleep(2.5)
meer = input('ga je over het meer varen (1) of om het meer heen? (2) ')
if meer == '2':
time.sleep(2.5)
print('je loopt verder langs het meer en geniet van het mooie uitzicht')
time.sleep(2.5)
print('het mooie bos word al gauw bergachtig.')
time.sleep(2.5)
print('je komt een ravijn tegen, wat doe je?')
time.sleep(2.5)
ravijn = input('klim je omhoog? (1) of loop je er doorheen? (2) ')
if ravijn == '1':
time.sleep(2.5)
print('je kan via de waterval omhoog (1), dat is minder steil maar wel nat. ')
time.sleep(1)
print('of je kan via een rotswand (2), die is steiler, maar wel droog. ')
klimmen = input('wat word het? ')
if klimmen == '1':
time.sleep(1)
print('je gaat langs de waterval omhoog klimmen.')
time.sleep(2.5)
print('tewijl je aan het klimmen bent, glij je uit en je valt op je hoofd')
time.sleep(4)
print()
print("YOU DIED")
elif klimmen == '2':
time.sleep(1)
print('je klimt omhoog en je komt zonder problemen boven.')
time.sleep(2.5)
print("eenmaal boven zie je in de verte 2 dorpen liggen.")
time.sleep(2.5)
dorp = input("naar welk dorp ga je toe? de linker (1) of de rechter? (2) ")
if dorp == '1':
time.sleep(2.5)
print()
path1()
elif dorp == '2':
time.sleep(2.5)
print('je loopt richting het dorp')
time.sleep(2.5)
print('je komt zonder problemen bij het dorp aan, en je overleeft')
time.sleep(4)
print()
print("YOU WIN!")
elif ravijn == '2':
time.sleep(1)
print("je besluit door het ravijn heen te lopen")
time.sleep(2.5)
print("tijdens het lopen hoor je ineens gerommel.")
time.sleep(2.5)
print("je kijkt boven je, en je ziet een hoop stenen op je af vallen.")
time.sleep(4)
print()
print("YOU DIED")
elif meer == '1':
time.sleep(2.5)
print('je sleept de boot het water op en je begint met varen.')
time.sleep(2.5)
print('eenmaal op het water, zie je iets verderop het meer.')
time.sleep(2.5)
monster = input('ga je er op af? (1) of ga je er omheen? (2) ')
if monster == '1':
time.sleep(2)
print('je besluit er op af te gaan.')
time.sleep(2.5)
print('eenmaal dichterbij realiseer je je dat het een groot monster is!')
time.sleep(2.5)
print("het kleine bootje maakt geen schijn van kans tegen het grote monster...")
time.sleep(4)
print()
print("YOU DIED")
elif monster == '2':
time.sleep(2.5)
print("je besluit om er omheen te varen.")
time.sleep(2.5)
print("tijdens dat je er omheen vaart, let je niet op. vervolgens vaar je over een scherpe steen en je boot begint te zinken")
time.sleep(2.5)
print("het water is erg koud.")
time.sleep(2.5)
print("eenmaal uit het water, is het veelste koud, en er is een grote kans op onderkoeling...")
time.sleep(4)
print()
print("YOU DIED")
loop = True
while loop == True:
print()
time.sleep(2.5)
print('-------------------------------------------------------------------------')
print('Hallo, u staat op het punt om met mijn spel "gestrand" te starten.')
print('In dit spel moet je beantwoorden met een cijfer.')
print("Druk op enter om te starten!")
input('-------------------------------------------------------------------------')
print()
time.sleep(2.5)
print("je bent gestrand midden in een bos, en jouw doel is om de beschaving te vinden. Succes!")
time.sleep(2.5)
print('Je komt een t-splitsing tegen en je kan 2 kanten op, welke kant kies je?')
tSplitsing = input('links (1) of rechts (2)? ')
if tSplitsing == '1':
path1()
elif tSplitsing == '2':
path2() |
c1e15fc34fabdd4339276cc4563c9644ccb2c8e7 | Meghashrestha/pythonassignment02 | /20.py | 771 | 4.0625 | 4 | # 20. Write a Python class to find the three elements that sum to zero
# from a list of n real numbers. Input array : [-25, -10, -7, -3, 2, 4, 8, 10] Output : [[-10, 2, 8], [-7, -3, 10]]
def three_element(arr, n):
found = True
for i in range(0, n - 2):
for j in range(i + 1, n - 1):
for k in range(j + 1, n):
if (arr[i] + arr[j] + arr[k] == 0):
print("[%d, %d, %d]" % (arr[i], arr[j], arr[k]))
found = True
if (found == False):
print(" not exist ")
arr = []
x = int(input("enter the number of item :"))
for i in range(0, x):
element = int(input("enter : "))
arr.append(element)
# arr = [0, -1, 2, -3, 1]
print(arr)
n = len(arr)
print(three_element(arr, n))
|
884920a2199ae56380b35c18414b185bb5ca2e24 | Indi44137/Functions | /Development 1.py | 481 | 4.125 | 4 | #Indi Knighton
#6/12/2014
#Development 1
hours = int(input("Please enter the amount of hours: "))
minutes = int(input("Please enter the amount of minutes here: "))
seconds = int(input("Please enter the amount of seconds here: "))
def calculate_seconds(hours, minutes, seconds):
hours = minutes * 60
minutes = seconds * 60
total_seconds = hours + minutes + seconds
print(total_seconds)
return total_seconds
calculate_seconds(hours, minutes, seconds)
|
4f62b4725401590f00361d0cb4c311fe538908c2 | mihirchakradeo/leetcreator | /main.py | 456 | 4.1875 | 4 | leet = {'a':'4','b':'13','c':'(','d':'[)','e':'3','f':'f','g':'6','h':'|-|','i':'|','j':'j',
'k':'|<','l':'1','m':'m','n':'/\/','o':'0','p':'|>','q':'q','r':'|2','s':'5','t':'7','u':'|_|','v':'\/',
'w':'w','x':'}{','y':'y','z':'2'}
def convertToLeet(inp):
a=[]
arr = inp.split(" ")
for word in arr:
for i in word:
a.append(leet[i])
a.append(" ")
print "LEET EQUIVALENT:"
print "".join(a)
inp = raw_input("Enter string: ")
convertToLeet(inp) |
aa6e5f8aaa4c218408472956b83a6ca07ba59fcb | anuroopmishra21/practice_codes_python | /binary_search_in_list.py | 351 | 3.65625 | 4 | l=list(map(int, input("Enter the list ").split(" ")))
n=int(input("Enter the element to be searched "))
c=0
low=0
high=len(l)-1
while low<=high:
mid=(low+high)//2
if n== l[mid]:
c=1
break
elif n<l[mid]:
high=mid-1
else:
low=mid+1
if c==1:
print("Element found")
else:
print("Element not found")
|
f113f8a1f4c7b50a7017ad3d6e64b76ec61a8d32 | chw3k5/philsGroup | /intoToPython.py | 6,586 | 4.25 | 4 | """
Comments - This is a multi-line comment
This is a brief introduction to python, written in Python 3
"""
# this is a single line comment
"""
The print state statement
"""
# simple example
print("Here is a simple print example.")
# compound example, the elements in the print statement are separated by commas ,
print("number ninety-nine:", 99, 'here is another string')
# the \n (newline) character. This charater is used print statements or other text is on multiple lines
print('\nThis newline character \n', "here is a 2nd line\n")
"""
Numbers - basic single value numbers Integers and floats.
"""
### integers (no decimal point)
anInt = 9
notherInt = 7
# ** is the power operator
print(anInt ** notherInt, ":: An example of the power operator")
# Tricky division
print(anInt / notherInt, " for new coders Interger division is a little tricky")
print("the result division with two integers is always an integer")
# The modulus operator
counter = 17
loopLen = 6
print("This modulus operation:", counter % 6, "it give the remainder.")
print("This how many times something can be divided", counter / loopLen, "it is another example of integer division.")
### float (floating point number, has a decimal point)
float1 = 55.8
float2 = 63.0
float3 = 1.4563e-122
# intuitive division.
print('\nintuitive division', float1 / float2, "Floats lead to the expected division.")
# is you do not know if a variable is a float or an int, or even something else you can use the type() function
print(type(float2), type(anInt))
# conversion to an integer
print(type(int(float1)), int(float1), int(round(float1)))
# conversion from an integer
print(type(float(anInt)), float(anInt))
# when used with an integer in math
print(float1 ** float2, float3, "\n")
"""
Strings
Strings can be groups of numbers or letters that are enclosed in quotes.
Single quotes '' or double "" quotes will both work. However, if you use an apostrophe '
Then you must enclose the apostrophe in double quotes to be be used in the string.
For Example:
stringVar = "This is Caleb's string, ain't it grand?"
"""
# single quotes
stringVar = 'This is Caleb'
print(stringVar)
# double quotes
stringVar = "This is Caleb 2"
print(stringVar)
stringVar = "This is Caleb's string, ain't it grand?"
print(stringVar)
# conversion to a number
aNumberString = '99'
print(int(aNumberString), float(aNumberString), type(aNumberString))
# concatenation of stings, use the + operator
print(stringVar + ' A number I like -> ', aNumberString, "\n")
# split method
dataExample = "Sometimes*data*is*delimited*with*strange*characters"
splitData = dataExample.split("*")
for datum in splitData:
print(datum, "is a split element from dataExample")
# replace method, sometimes you want to find and replace characters or stings within a string
print(dataExample.replace("*", "!!"))
"""
Tuples - pronounced 2-ple
These are a grouping of data in an immutable structure. Immutable means the length of the tuple
(I think of it as a container that is not allowed to change like and egg carton)
Tuples are enclosed in round brackets () and the values are separated by commas, the values in a tuple are
accessed using integers starting with 0 and then going 0, 1, 2,.... Access the last value in the tuple
starting with -1 and count backward as -1, -2, -3.
"""
# coordinates example
threeSpace = (99, 55, 8.7)
print(threeSpace)
### unpacking and packing
# unpack
x, y, z = threeSpace
print(x, y, z)
# and pack
nuSpace = (z, x, y)
print(nuSpace)
# calling a single value.
print(threeSpace[0], 'is the first value and', threeSpace[-1], "is the last value")
# Here is an example of a tuple made of a mixture of data types stings and floats.
bankInfo = ('Caleb', '0938583892', -88.8)
print(bankInfo, 'is my bank info')
# this is a number formating example, the formatting is based on "C"-code number formatting
name, bankAccountNum, balance = bankInfo
print("$" + str('%2.2f' % balance) + " is my balance")
# tuple of tuples, a tuple can be made of other tuples
tupOfTup = (threeSpace, bankInfo)
print(tupOfTup, '\n')
"""
Lists
These a grouping of data in an mutable structure. Use a list when your data is being collected or for any other
reason that its length might change.
(I think of lists as a train that can have cars added or subtracted at different stations along it journey)
Lists are enclosed in square brackets [] and the values are separated by commas, the values in a list are
accessed using integers starting with 0. Access that last value in the list starting with -1.
"""
# list example
basicList = ['rrrrrr', 5, 'rrrrrr']
print(basicList)
# the empty list
basicList = []
print(basicList)
# The append method
basicList = ['rrrrrr', 5, 'rrrrrr']
basicList.append('aString')
# add a single element to the end of a list
print(basicList)
# the extend method
diffList = [63498, "skejkg", 77777, ('he', 4)]
# concatenate 2 lists together.
basicList.extend(diffList)
print(basicList, '\n')
# list of tuples
tupleOne = (1, 2, 3)
tupleTwo = (4, 5, 6, 7)
tupleThree = (8, 9, 0)
listOfTuples = [tupleOne, tupleTwo, tupleThree, (11, 12)].append((13, 14))
# get the last tuple in the list
print(listOfTuples[4], "equivenently", listOfTuples[-1])
# get the 2nd element in the last tuple in the list
print(listOfTuples[-1][1])
"""
Dictionaries
A dictionary is a way to store data using key-value pairs. While a list or a tuple uses an integer to access
stored data, a dictionary value is assessed using a key, which can be an integer, string, float, or
even more complex data types, I have used some crazy keys.
Dictionaries are enclosed in curly brackets {} and have and use a colon : to link
key:value pairs. The key value pairs are separated by commas. To get a list of all the keys
in a given dictionary, use the .keys() method.
"""
# dictionary example
aDict = {'apple':'is a piece of red fruit'}
print(aDict['apple'])
# empty dictionary
aDict = {}
# add a key value pair
aDict['4'] = ' this is a string of stuff'
aDict['puppy'] = ' Here is my pup!'
aDict[7.7] = 'This key is a float'
print(aDict)
print(aDict[7.7])
# get all the keys for a dictionary
print(aDict.keys())
"""
The for loop
"""
# using the range function to make a counter
for aNumber in range(10):
print(aNumber)
# using a list
aList = ["Sing a song,", "If the sun refused to shine,", "I don't mind, I don't mind."]
for aLyric in aList:
print(aLyric)
# using enumerate
# with a break
# with an else
"""
the try statement
"""
"""
A definition
"""
|
d781dc0ed39f1ee55c98b5bd2fa38cb3a4bfc663 | GredziszewskiK/spoj | /prime_t.py | 407 | 3.765625 | 4 | # link do zadania
# https://pl.spoj.com/problems/PRIME_T/
from math import sqrt
from sys import stdout, stdin
def is_prime_number(number):
x = int(number)
y = sqrt(x)
if x < 2:
return 'NIE\n'
for n in range(2, int(y)+1):
if x % n == 0:
return 'NIE\n'
return 'TAK\n'
for i in range(int(stdin.readline())):
stdout.write(is_prime_number(stdin.readline()))
|
2a7a9663b472ca24e68dffaa908aed565c417d3a | WoodyLuo/PYTHON | /Lecture07/ex05_CircleWithPrivateRadius.py | 462 | 3.640625 | 4 | '''
Exercise05 - CircleWithPrivateRadius Functions.
Chung Yuan Christian University
written by Amy Zheng (the teaching assistant of Python Course_Summer Camp.)
'''
import math
class Circle:
def __init__(self, radius=1):
self.__radius = radius
def getRadius(self):
return self.__radius
def getPerimeter(self):
return 2 * self.__radius * math.pi
def getArea(self):
return self.__radius * self.__radius * math.pi
|
859e39398ddc0e4998680a13272e992252f42cfd | 1179069501/- | /4.16/demo/users/middleware.py | 572 | 3.6875 | 4 | #定义一个中间件用到的闭包
def my_decorator(func):
print('init')
def wrapper(request):
print('视图函数执行之前,调用的区域')
response = func(request)
print('视图函数调用之后,调用的函数')
return response
return wrapper
def my_decorator1(func):
print('init2')
def wrapper(request):
print('视图函数执行之前,调用的区域2')
response = func(request)
print('视图函数调用之后,调用的函数2')
return response
return wrapper |
ce2a183433226c291f139bcd8d65021dcfbdc227 | Kwpolska/adventofcode | /2015/14-reindeer-olympics.py | 1,398 | 3.59375 | 4 | #!/usr/bin/python3
class Reindeer(object):
# I feel like doing OOP today.
name = "Santa"
speed = 0
fly_time = 0
rest_time = 0
distance = 0
in_fly = 0
in_rest = 0
points = 0
def __init__(self, name, speed, fly_time, rest_time):
self.name = name
self.speed = int(speed)
self.fly_time = int(fly_time)
self.rest_time = int(rest_time)
self.in_fly = 0
self.in_rest = 0
self.distance = 0
self.points = 0
REINDEERS = {}
# Read in reindeers!
with open("14-input.txt") as fh:
for l in fh:
name, can, fly, speed, non_si_unit, for_, fly_time, seconds, but, then, must, rest, for_, rest_time, seconds = l.strip().split()
REINDEERS[name] = Reindeer(name, speed, fly_time, rest_time)
CURRENT_DISTANCE = {}
TIME = 0
while TIME < 2503:
for r in REINDEERS.values():
if r.in_fly < r.fly_time:
r.distance += r.speed
r.in_fly += 1
else:
r.in_rest += 1
if r.in_rest == r.rest_time:
r.in_fly = 0
r.in_rest = 0
for n, r in REINDEERS.items():
print(n, r.distance)
winner = max(REINDEERS.items(), key=lambda e: e[1].distance)
winner[1].points += 1
TIME += 1
RESULTS = sorted(REINDEERS.items(), key=lambda e: e[1].points)
for name, r in RESULTS:
print(name, r.distance, r.points)
|
2d2a7e90a9cdc787228df0e5126b3a78bdeb45cf | aschiedermeier/Programming-Essentials-in-Python | /Module_6/6.1.4.9.reflectInspect.py | 880 | 3.625 | 4 | # 6.1.4.9 OOP: Method
# Reflection and introspection
# The function named incIntsI() gets an object of any class,
# scans its contents in order to find all integer attributes with names starting with i,
# and increments them by one.
class MyClass: # define class
pass
obj = MyClass() # create object
obj.a = 1 # fill object with attributes
obj.b = 2
obj.i = 3
obj.ireal = 3.5
obj.integer = 4
obj.z = 5
def incIntsI(obj):
for name in obj.__dict__.keys(): # look for attribute names
if name.startswith('i'): # if name starts with 'i'
val = getattr(obj, name) # get current value
if isinstance(val, int): # check if the value is of type integer,
setattr(obj, name, val + 1) # increment the property's value
print(obj.__dict__)
incIntsI(obj)
print(obj.__dict__) # var '1' and 'integer' been incresed by 1
|
4a241dbbbb655be8c6a541c1ce86dc2117555319 | dongyingdepingguo/PTA | /pta_practice/PTA1038.py | 925 | 3.546875 | 4 | # !/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
1038 统计同成绩学生 (20 分)
本题要求读入 N 名学生的成绩,将获得某一给定分数的学生人数输出。
输入格式:
输入在第 1 行给出不超过 10**5 的正整数 N,即学生总人数。随后一行给出 N 名学生的百分制整数成绩,
中间以空格分隔。最后一行给出要查询的分数个数 K(不超过 N 的正整数),随后是 K 个分数,中间以空格分隔。
输出格式:
在一行中按查询顺序给出得分等于指定分数的学生人数,中间以空格分隔,但行末不得有多余空格。
输入样例:
10
60 75 90 55 75 99 82 90 75 50
3 75 90 88
输出样例:
3 2 0
"""
number = input()
re = input().split()
ch_re = input().split()[1:]
d_re = {i: 0 for i in ch_re}
for r in re:
if r in d_re:
d_re[r] += 1
print(' '.join([str(d_re[i]) for i in ch_re]))
|
70dbfdbeaa4a5914a5f9183e17dea0782d97782f | xinlongOB/python_docment | /面向对象/父类的私有属性和方法.py | 1,542 | 4.34375 | 4 | # 在父类定义的私有方法或属性 子类不能直接访问
"""
class A:
def __init__(self):
self.num1 = 100
self.__num2 = 200
def __test(self):
print("私有方法 %d %d" % self.num1,self.__num2)
class B(A):
def demo(self):
pass
#1、访问父类的私有属性
# print("访问父类的私有属性 %d" % self.__num2)
#2、调用父类的私有方法
#super().__test()
b = B()
print(b)
#在外界不能直接访问对象的私有属性/调用私有方法
print(b.num1)
#print(b.__num2)
b.demo()
"""
# 在父类定义的私有方法或属性 子类可以直接访问
# 子类可以通过间接的方式调用父类的私有方法和属性
class A:
def __init__(self):
self.num1 = 100
self.__num2 = 200
def __test(self):
print("私有方法 %d %d" % (self.num1, self.__num2))
def test(self):
print("父类的共有方法 %d" % self.__num2)
self.__test()
# self.__test()
class B(A):
def demo(self):
# 1、访问父类的私有属性
# print("访问父类的私有属性 %d" % self.__num2)
# 2、不可以调用父类的私有方法
# 3、访问父类的公有属性
print("子类方法 %d" % self.num1)
# 4、调用父类的公有方法
self.test()
# super().__test()
# b.test()
b = B()
# print(b)
# 在外界不能直接访问对象的私有属性/调用私有方法
print(b.num1)
# print(b.__num2)
b.demo()
|
e603f6094d8c34c90126d5f9c46f08b9aa91fc55 | saiteja6969/Gitam-2019 | /PYTHON2019 (1).py | 988 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
print("HELLO WORLD")
# In[4]:
print("hello")
# In[8]:
x=1
y=2
z=x+y
print(z)
# In[14]:
y=11
z=12
w=100
x=y*z*w
print("value of x is ",x)
# In[16]:
initialmarks=600
TotalMarks=900
percentage=(initialmarks/TotalMarks)*100
print(percentage)
# In[18]:
print(98)
# In[21]:
x=1
y=2
z=x+y
print(z)
# In[23]:
x=10
y=2
print(x*y)
print(x/y)
# In[30]:
x="abc"
print(x)
# In[35]:
print(1+2**3/4*5)
# In[36]:
print(2+5**6/4*8)
# In[37]:
x=2
r=(x<10)
print(r)
# In[39]:
r=(5<10)
print(r)
# In[40]:
r=(1000<10)
print(r)
# In[41]:
r=(10<=10)
print(r)
# In[42]:
r=(10>=10)
print(r)
# In[43]:
r=(10>=100)
print(r)
# In[45]:
r=(10==100)
print(r)
# In[46]:
print(10==100)
# In[48]:
print(100==100)
# In[49]:
r=(10<101) and (100==100)
print(r)
# In[51]:
r=(10<101) or (10==100)
print(r)
# In[53]:
x=True
r=not(x)
print(r)
# In[ ]:
# In[ ]:
# In[ ]:
|
773ce1d2a9975b48df7a742b84445952877392a7 | bentd/think-python | /14.5.2.py | 465 | 3.609375 | 4 |
def sed(pattern,replacement,file1,file2):
try:
file1=open('file1.txt','r')
file2=open('file2.txt','w')
for line in file1:
if pattern in line: file2.write(line.replace(pattern,replacement))
else: file2.write(line)
file1.close()
file2.close()
except IOError:
print 'Sorry! No such file or directory...\nPlease try again.'
|
805a828ae43db181206996bcba14d3edde27cfe8 | LiangFei90/PythonDataAnalysis | /Study/starCpy | 314 | 3.890625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon May 22 17:29:29 2017
@author: frank
题目:用*号输出字母C的图案。
"""
for i in range(12):
if i<2 or i>9:
print '**************'
elif i==2 or i==9:
print '**** **'
else:
print'****'
|
8c9c8211f6a733a8a2d88a7a096eb662d0e10bb6 | AntoniyaV/SoftUni-Exercises | /Fundamentals/01-Basic-Syntax-Conditional-Statements-and-Loops/09-easter-cozonacs.py | 553 | 3.703125 | 4 | budget = float(input())
flour_price = float(input())
eggs_price = 0.75 * flour_price
milk_price = (flour_price + (0.25 * flour_price)) / 4
cozonac_price = eggs_price + flour_price + milk_price
colored_eggs = 0
cozonac_count = 0
lost_eggs = 0
while budget > cozonac_price:
colored_eggs += 3
cozonac_count += 1
if cozonac_count % 3 == 0:
lost_eggs = cozonac_count - 2
colored_eggs -= lost_eggs
budget -= cozonac_price
print(f"You made {cozonac_count} cozonacs! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.") |
f28874928fedc481cf0d83f3f841495682a65a18 | hanqizheng/Algorithm | /Easy/JewelryAndStone.py | 871 | 3.90625 | 4 | """
给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
示例 1:
输入: J = "aA", S = "aAAbbbb"
输出: 3
示例 2:
输入: J = "z", S = "ZZ"
输出: 0
注意:
S 和 J 最多含有50个字母。
J 中的字符不重复。
"""
# 这道题就是考了一个count函数
class Solution:
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
n = 0
for i in J:
n += S.count(i)
return n
test = Solution()
j = 'aA'
s = 'abuisadAsda'
print test.numJewelsInStones(j, s)
|
2bf104bbb3c9a41d56921c47f4a8e0a02caaf7d7 | Sona1414/luminarpython | /flow controls/looping/forloop/demo.py | 198 | 4.09375 | 4 | #for loop
#initialisation --i
#condition---range(low,upp)
#upp-1 is executed
#increment can be mentioned in range function
for i in range(1,11,1):
print(i)
for i in range(1,11,2):
print(i) |
34f43bf294d27961b95985ae2b5f7faa15b74802 | 1170300523/code | /python/agriothm homework/Biscuit allocation.py | 453 | 3.53125 | 4 | # 贪心策略: 先满足贪婪因子小的孩子
def Biscuit_allocation():
k = 0
s = list(map(int, input("input s: ").split()))
f = list(map(int, input("input f: ").split()))
s = sorted(s)
f = sorted(f)
while len(s) and s[0]<f[-1]:
for j in f:
if j >= s[0]:
f.remove(j)
s.remove(s[0])
k += 1
break
return k
print(Biscuit_allocation())
|
0788092b33d91955c27ab4ea465aaaa739da0f7e | matchallenges/Portfolio | /2021/PythonScripts/leet_code_2.py | 821 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
str_list1 = [str(i) for i in l1]
str_list2 = [str(i) for i in l2]
l1_joined = ''.join(str_list1)
l2_joined = ''.join(str_list2)
l1_joined_int = int(l1_joined)
l2_joined_int = int(l2_joined)
sum_of_two_lists = l1_joined_int + l2_joined_int
string_of_final_number = str(sum_of_two_lists)
string_of_final_number_reversed = string_of_final_number[::-1]
answer = [int(i) for i in string_of_final_number_reversed]
return answer
solution = Solution()
print(solution.addTwoNumbers([2, 4, 3, 5, 6, 2, 3], [5, 6, 4])) |
0651c2a413ab40e73fb1e007e88cabc4e16496cf | Jane-Zhai/LeetCode | /easy_math_013_Roma2Int.py | 407 | 3.5 | 4 | class Solution:
def romanToInt(self, s):
"""
"""
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
ans = 0
for i in range(len(s)):
if i < len(s)-1 and dic[s[i]]<dic[s[i+1]]:
ans -= dic[s[i]]
else:
ans += dic[s[i]]
return ans
sol = Solution()
print(sol.romanToInt("LVIII")) |
5509c5336a4f6be517027aea952032b1717aa90a | onyonkaclifford/data-structures-and-algorithms | /data_structures/trees/avl_tree.py | 6,261 | 3.921875 | 4 | from binary_search_tree import BinarySearchTree
from tree import Tree
class AVLTree(BinarySearchTree):
"""An AVL tree is a binary search tree that is balanced. Whenever an item is inserted or deleted, the tree
rebalances itself. This ensures an a worst case search time of O(logn).
Instantiate an AVL tree object
>>> tree = AVLTree()
Insert an item to the tree
>>> tree.insert(5, 500)
>>> tree.insert(4, 400)
>>> tree.insert(6, 600)
>>> tree.insert(10, 10000)
Check if a tree is empty
>>> tree.is_empty()
False
>>> AVLTree().is_empty()
True
Get root position
>>> root = tree.get_root()
Get item corresponding to a certain position
>>> root.get_data()
(5, 500)
Check if a position is owned by some tree
>>> root.is_owned_by(tree)
True
>>> root.is_owned_by(AVLTree())
False
Get children of some position
>>> children = tree.get_children(root)
>>> [i.get_data() for i in children]
[(4, 400), (6, 600)]
Get left child of some position
>>> left_child = tree.get_left_child(root)
>>> left_child.get_data()
(4, 400)
Get right child of some position
>>> right_child = tree.get_right_child(root)
>>> right_child.get_data()
(6, 600)
Delete item from the tree
>>> position_to_delete = tree.get_right_child(right_child)
>>> tree.delete(position_to_delete)
Check if a position contains the root
>>> tree.is_root(root)
True
>>> tree.is_root(left_child)
False
Check if a position contains a leaf node
>>> tree.is_leaf(left_child)
True
>>> tree.is_leaf(root)
False
Get parent of some position
>>> tree.get_parent(left_child).get_data()
(5, 500)
>>> tree.get_parent(root) is None
True
Get siblings of some position
>>> siblings = tree.get_siblings(left_child)
>>> [i.get_data() for i in siblings]
[(6, 600)]
Get height of some position
>>> tree.get_height_of_node(left_child)
0
>>> tree.get_height_of_node(root)
1
Get height of tree
>>> tree.get_height_of_tree()
1
Get depth of some position
>>> tree.get_depth_of_node(left_child)
1
>>> tree.get_depth_of_node(root)
0
Get depth of tree
>>> tree.get_depth_of_tree()
1
Get level of some position
>>> tree.get_level_of_node(left_child)
2
>>> tree.get_level_of_node(root)
1
Get length of tree
>>> len(tree)
3
>>> len(AVLTree())
0
Get string reresentation of tree
>>> tree
5(4, 6)
>>> str(tree)
'5(4, 6)'
Get tree iterable
>>> tree_iterable = iter(tree)
>>> next(tree_iterable).get_data()
(5, 500)
Get next item of tree iterator
>>> next(tree).get_data()
(4, 400)
"""
def __init__(self):
super().__init__()
@staticmethod
def __rotate(node_to_move, root_node, parent, clockwise):
node_to_move.parent = parent
if parent is not None:
is_left_child = root_node.key < parent.key
if is_left_child:
parent.children[0] = node_to_move
else:
parent.children[1] = node_to_move
if clockwise:
node_to_move.children[1] = root_node
else:
node_to_move.children[0] = root_node
root_node.parent = node_to_move
def __get_balance(self, root_node):
if root_node is None:
return 0
left_height = (
0
if root_node.children[0] is None
else self.get_height_of_node(Tree._Position(self, root_node.children[0]))
)
right_height = (
0
if root_node.children[1] is None
else self.get_height_of_node(Tree._Position(self, root_node.children[1]))
)
return left_height - right_height
def __balance_tree(self):
def balance_tree(root_node):
parent = root_node.parent
left_child = root_node.children[0]
right_child = root_node.children[1]
if left_child is not None:
balance_tree(left_child)
if right_child is not None:
balance_tree(right_child)
balance = self.__get_balance(root_node)
if abs(balance <= 1):
return root_node
if balance > 0:
current = root_node.children[0]
right = current.children[1]
if right is None:
AVLTree.__rotate(current, root_node, parent, clockwise=True)
return current
else:
new_node = Tree._Node(
right.key, right.value, parent=parent, children=[current, None]
)
AVLTree.__rotate(new_node, root_node, parent, clockwise=True)
current.parent = new_node
self.delete(Tree._Position(self, right))
return new_node
else:
current = root_node.children[1]
left = current.children[0]
if left is None:
AVLTree.__rotate(current, root_node, parent, clockwise=False)
return current
else:
new_node = Tree._Node(
left.key, left.value, parent=parent, children=[None, current]
)
AVLTree.__rotate(new_node, root_node, parent, clockwise=False)
current.parent = new_node
self.delete(Tree._Position(self, left))
return new_node
self.__root = balance_tree(self._root)
def delete(self, position: Tree._Position):
super().delete(position)
self.__balance_tree()
def insert(self, key, value):
super().insert(key, value)
self.__balance_tree()
|
8c59200ffd5df27a6c3a77e41512f9fac5178c95 | Aplex2723/Introduccion-en-Python | /Clases y Objetos/POO.py | 929 | 4.15625 | 4 | '''Ejemplo de implementacion con programacion Estructurada'''
clientes = [
{'Nombre' : 'Hector', 'Apellido' : 'Costa Guzman', 'ine' : '111111111A'},
{'Nombre' : 'Pedro', 'Apellido' : 'Casillas Torres', 'ine' : '222222222B'}
]
def mostrar_clientes(clientes, ine):
for c in clientes:# le asignamos a c que buesque en clientes
if (ine == c['ine']):
print('{} {}'.format(c['Nombre'], c['Apellido']))
return
print("Cliente no encontrado")
print(mostrar_clientes(clientes, '111111111A'))
def borrar_cliente(clientes, ine):
for i,c in enumerate(clientes):# Asignamos a 'i' la numeracion de cliente
if (ine == c['ine']):
del(clientes[i])# Si no borramos el valor 'i' no se borra el diccionario
print(str(c), "> BORRADO")
return
print("Cliente no encontrado")
print(borrar_cliente(clientes, '222222222B'))
print(clientes) |
3a1cdff326a1b4b6748659272be79664bd4bb36d | Ayruahs/HuluHangmanChallenge | /Hangman.py | 3,150 | 3.640625 | 4 | """
The logic of my code is as follows: I first check for the most frequent letters in the hangman phrase.
After there is only one guess left, I use regular expressions to check for specific words from the
list of most used words provided by Google, which is recorded in the "count_1w.txt" text files.
"""
import json
import requests
import time
import re
from MostCommonWords import wordSet
winCount = 0
lossCount = 0
url = "http://gallows.hulu.com/play?code=sinha35@purdue.edu"
while True:
resp = requests.get(url=url)
data = resp.json()
print("Welcome to a new game of hangman!")
alive = 'ALIVE'
dead = 'DEAD'
free = 'FREE'
phrase = data['state']
TOKEN = data['token']
status = data['status']
guessesLeft = data['remaining_guesses']
letters = list("etaoinsrhldcumfpgwybvkxjqz")
guessedLetters = set()
for letter in letters:
if guessesLeft <2:
break
GUESS = letter
guessedLetters.add(letter)
gameUrl = "http://gallows.hulu.com/play?code=sinha35@purdue.edu&token=" + TOKEN + "&guess=" + GUESS
resp1 = requests.get(url=gameUrl)
data1 = resp1.json()
phrase = data1['state']
status = data1['status']
guessesLeft = data1['remaining_guesses']
while status == alive:
words = phrase.split()
wordsThatMatch = set()
for word in words:
if guessesLeft == 0:
break
indices = []
k = 0
if word.count('_') != 0:
regex = "^"
for letter in word:
if letter == "_":
indices.append(k)
regex += "[a-zA-Z]"
else:
regex += letter.lower()
k += 1
regex += "$"
if word.count('_') != 0:
for i in wordSet:
match = re.match(regex, i)
if match:
wordsThatMatch.add(match.string)
for w in wordsThatMatch:
#if w not in guessedWords:
# guessedWords.add(w)
for i in range(len(w)):
if i in indices:
GUESS = w[i]
if guessesLeft == 0:
break
gameUrl = "http://gallows.hulu.com/play?code=sinha35@purdue.edu&token=" + TOKEN + "&guess=" + GUESS
resp1 = requests.get(url=gameUrl)
data1 = resp1.json()
phrase = data1['state']
status = data1['status']
guessesLeft = data1['remaining_guesses']
if status == dead:
lossCount += 1
if status == free:
winCount += 1
print("The game is over!")
print("You have won: %d times\nand lost: %d times." %(winCount, lossCount))
print("Win Percentage is: %.4f%%" %(winCount / (winCount + lossCount) * 100))
print("The total number of games played is: %d\n\n\n" %(winCount + lossCount))
|
efd7cb48fe786a8b8948881d889e2b30a0fdcd4d | GustavoJatene/practice | /059.py | 1,032 | 3.953125 | 4 | sair = False
n1 = int(input("Digite o primeiro valor: "))
n2 = int(input("Digite o segundo valor: "))
opc = int
maior = n1
while not sair:
print("-" * 30)
print("[1] Para SOMAR\n[2] Para MULTIPLICAR\n[3] Para MAIOR\n[4] Para NOVOS NUMEROS\n[5] Para SAIR")
print("-" * 30)
opc = int(input("Digite a opção: "))
if opc == 1:
print("-" * 30)
print("A soma entre {} + {} é {}".format(n1,n2,n1+n2))
print("-"*30)
elif opc == 2:
print("-" * 30)
print("A multiplicação entre {} + {} é {}".format(n1, n2, n1 * n2))
print("-" * 30)
elif opc == 3:
print("-" * 30)
if n2 > maior:
maior = n2
print("O numero maior entre {} e {} é {}".format(n1, n2, maior))
print("-" * 30)
elif opc == 4:
print("-" * 30)
n1 = int(input("Digite um novo primeiro valor: "))
n2 = int(input("Digite um novo segundo valor: "))
print("-" * 30)
else:
print("Fazendo Logout")
sair = True |
69dae8eb1c8e3d63e74eaa0355e2f4fc6a83e964 | Panda0229/flasky | /04_request.py | 1,028 | 3.59375 | 4 | from flask import Flask, request
app = Flask(__name__)
# 接口 api
# 127.0.0.1:5000/index?city=shenzhen&country=china 问号后面的成为查询字符串(QueryString)
@app.route("/index", methods=["GET", "POST"])
def index():
# request中包含了前端发送过来的所有请求数据
# form和data是用来提取请求中的数据
# 通过request.form可以直接提取请求中的表单格式的数据,是一个类字典的对象
# 通过get方法只能拿到多个同名参数中的一个
name = request.form.get("name")
age = request.form.get("age")
# 通过getlist可以提取到表单中的重复部分
name_li = request.form.getlist("name")
# 如果请求体的数据不是表单格式(如json)格式,可以通过request.data获取
print("request.data: %s " % request.data)
# args是用来提取url中查询字符串的参数
city = request.args.get("city")
return "hello name=%s, age=%s, city=%s, name_li=%s" % (name, age, city, name_li)
if __name__ == "__main__":
app.run(debug=True)
|
c6a561bc50981ff655be602259e9afd936476b1a | parulc7/100-Days-of-NLP | /Day 1/re.py | 297 | 4.375 | 4 | # Matching Regular Expressions in a string
import re
words = ['Hello', 'this']
expression = '|'.join(words)
print(re.findall(expression, 'Hello world This is Parul', re.M))
# Reading from a file and splitting into strings
with open('test.txt') as f:
words = f.read().split()
print(words)
|
d127694ba04fb31705a229392c7e6db3605cce98 | geriwald/coding-exercises | /DailyCodingProblem/P03_serializeTree.py | 1,226 | 4.1875 | 4 | # Good morning! Here's your coding interview problem for today.
# This problem was asked by Google.
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string,
# and deserialize(s), which deserializes the string back into the tree.
# For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
# The following test should pass:
# node = Node('root', Node('left', Node('left.left')), Node('right'))
# assert deserialize(serialize(node)).left.left.val == 'left.left'
import json
class NodeEncoder(json.JSONEncoder):
def default(self,o):
return {'__{}__'.format(o.__class__.__name__): o.__dict__}
def NodeDecoder(o):
if '__Node__' in o:
n=Node(None)
n.__dict__.update(o['__Node__'])
return n
return o
def serialize(node):
return json.dumps(node,cls=NodeEncoder)
def deserialize(text):
return json.loads(text,object_hook=NodeDecoder)
# The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
|
03e403bac3c2e041c9dfacdc5c6604f534207072 | gurmehar98/PracticeProblems | /MaximumDepthOfN-aryTree.py | 899 | 3.625 | 4 | class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def maxDepth(self, root):
if root == None:
return 0
return(self._helper(root))
def _helper(self, root):
if root == None:
return 0
maxHeight = -float("inf")
if root.children != None:
for c in root.children:
height = self._helper(c)
if maxHeight < height:
maxHeight = height
if root.children == None or maxHeight == -float("inf"):
return 1
return (maxHeight + 1)
if __name__ == "__main__":
n2 = Node(2, None)
n4 = Node(4, None)
n5 = Node(5, None)
n6 = Node(6, None)
n3 = Node(3, [n5, n6])
n1 = Node(1, [n3, n2, n4])
s = Solution()
print(s.maxDepth(n1)) |
fb3f11bb3eafe33f7cb30e98c089d8806ed93b73 | yeonkyu-git/Algorithm | /백준/B_1427.py | 908 | 4.125 | 4 | def sorting (numbers):
if len(numbers) <= 1:
return numbers
mid = len(numbers) // 2
before_list = numbers[:mid]
after_list = numbers[mid:]
before_list = sorting(before_list)
after_list = sorting(after_list)
return merge(before_list, after_list)
def merge(left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left[1:]
else:
result.append(right[0])
right = right[1:]
elif len(left) > 0:
result.append(left[0])
left = left[1:]
elif len(right) > 0:
result.append(right[0])
right = right[1:]
return result
num = input()
list = list(map(int, num))
list = sorting(list)
print(''.join(map(str, list))) |
edcfc333d2d7a07a3915f282608bc4c75287fe3c | csula-students/cs4660-fall-2017-OnezEgo | /cs4660/graph/graph.py | 8,721 | 4 | 4 | """
graph module defines the knowledge representations files
A Graph has following methods:
* adjacent(node_1, node_2)
- returns true if node_1 and node_2 are directly connected or false otherwise
* neighbors(node)
- returns all nodes that is adjacency from node
* add_node(node)
- adds a new node to its internal data structure.
- returns true if the node is added and false if the node already exists
* remove_node
- remove a node from its internal data structure
- returns true if the node is removed and false if the node does not exist
* add_edge
- adds a new edge to its internal data structure
- returns true if the edge is added and false if the edge already existed
* remove_edge
- remove an edge from its internal data structure
- returns true if the edge is removed and false if the edge does not exist
"""
from io import open
from operator import itemgetter
def construct_graph_from_file(graph, file_path):
"""
TODO: read content from file_path, then add nodes and edges to graph object
note that grpah object will be either of AdjacencyList, AdjacencyMatrix or ObjectOriented
In example, you will need to do something similar to following:
1. add number of nodes to graph first (first line)
2. for each following line (from second line to last line), add them as edge to graph
3. return the graph
"""
input_file = open(file_path)
nodes = int(input_file.readline())
for i in range(0, nodes):
graph.add_node(Node(i))
for line in input_file:
split_line = line.split(':')
graph.add_edge(Edge(Node(int(split_line[0])), Node(int(split_line[1])), int(split_line[2])))
return graph
class Node(object):
"""Node represents basic unit of graph"""
def __init__(self, data):
self.data = data
def __str__(self):
return 'Node({})'.format(self.data)
def __repr__(self):
return 'Node({})'.format(self.data)
def __eq__(self, other_node):
return self.data == other_node.data
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.data)
class Edge(object):
"""Edge represents basic unit of graph connecting between two edges"""
def __init__(self, from_node, to_node, weight):
self.from_node = from_node
self.to_node = to_node
self.weight = weight
def __str__(self):
return 'Edge(from {}, to {}, weight {})'.format(self.from_node, self.to_node, self.weight)
def __repr__(self):
return 'Edge(from {}, to {}, weight {})'.format(self.from_node, self.to_node, self.weight)
def __eq__(self, other_node):
return self.from_node == other_node.from_node and self.to_node == other_node.to_node and self.weight == \
other_node.weight
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash((self.from_node, self.to_node, self.weight))
class AdjacencyList(object):
"""
AdjacencyList is one of the graph representation which uses adjacency list to
store nodes and edges
"""
def __init__(self):
# adjacencyList should be a dictonary of node to edges
self.adjacency_list = {}
def adjacent(self, node_1, node_2):
for edge in self.adjacency_list[node_1]:
if edge.to_node == node_2:
return True
return False
def neighbors(self, node):
neighbors_list = []
if node in self.adjacency_list:
for x in self.adjacency_list[node]:
neighbors_list.append(x.to_node)
return neighbors_list
def add_node(self, node):
if node not in self.adjacency_list:
self.adjacency_list[node] = []
return True
else:
return False
def remove_node(self, node):
if node in self.adjacency_list:
for x in self.adjacency_list.keys():
key_value = self.adjacency_list[x]
for y in key_value:
if y.to_node == node:
self.adjacency_list[x].remove(y)
self.adjacency_list.pop(node)
return True
else:
return False
def add_edge(self, edge):
for x in self.adjacency_list[edge.from_node]:
if x == edge:
return False
if self.adjacency_list[edge.from_node] == {}:
self.adjacency_list[edge.from_node] = edge
else:
self.adjacency_list[edge.from_node].append(edge)
return True
def remove_edge(self, edge):
if edge.from_node in self.adjacency_list:
if edge in self.adjacency_list[edge.from_node]:
self.adjacency_list[edge.from_node].remove(edge)
return True
else:
return False
class AdjacencyMatrix(object):
def __init__(self):
# adjacency_matrix should be a two dimensions array of numbers that
# represents how one node connects to another
self.adjacency_matrix = []
# in additional to the matrix, you will also need to store a list of Nodes
# as separate list of nodes
self.nodes = []
def adjacent(self, node_1, node_2):
if node_1 in self.nodes or node_2 in self.nodes:
if self.adjacency_matrix[self.__get_node_index(node_1)][self.__get_node_index(node_2)] != 0:
return True
return False
def neighbors(self, node):
neighbors_list = []
if node in self.nodes:
for x in range(0, len(self.adjacency_matrix[self.__get_node_index(node)])):
if self.adjacency_matrix[self.__get_node_index(node)][x] > 0:
neighbors_list.append(self.nodes[x])
return neighbors_list
def add_node(self, node):
if node not in self.nodes:
self.nodes.append(node)
self.adjacency_matrix.extend([[0] * len(self.nodes)])
for eachRow in self.adjacency_matrix:
eachRow.extend([0])
return True
return False
def remove_node(self, node):
if node in self.nodes:
index = self.__get_node_index(node)
self.nodes.remove(node)
for x in self.adjacency_matrix:
del x[index]
del self.adjacency_matrix[index]
return True
return False
def add_edge(self, edge):
if self.adjacency_matrix[self.__get_node_index(edge.from_node)][self.__get_node_index(edge.to_node)] == 0:
self.adjacency_matrix[self.__get_node_index(edge.from_node)][self.__get_node_index(edge.to_node)] = edge.weight
return True
return False
def remove_edge(self, edge):
if edge.from_node in self.nodes and edge.to_node in self.nodes:
if self.adjacency_matrix[self.__get_node_index(edge.from_node)][self.__get_node_index(edge.to_node)] > 0:
self.adjacency_matrix[self.__get_node_index(edge.from_node)][self.__get_node_index(edge.to_node)] = 0
return True
return False
def __get_node_index(self, node):
return self.nodes.index(node)
class ObjectOriented(object):
"""ObjectOriented defines the edges and nodes as both list"""
def __init__(self):
# implement your own list of edges and nodes
self.edges = []
self.nodes = []
def adjacent(self, node_1, node_2):
for edge in self.edges:
if edge.from_node == node_1 and edge.to_node == node_2:
return True
return False
def neighbors(self, node):
neighbors_list = []
for x in range(len(self.edges)):
if self.edges[x].from_node == node:
neighbors_list.append(self.edges[x].to_node)
return neighbors_list
def add_node(self, node):
if node not in self.nodes:
self.nodes.append(node)
return True
return False
def remove_node(self, node):
if node in self.nodes:
self.nodes.remove(node)
for x in self.edges:
if x.from_node == node or x.to_node == node:
self.remove_edge(x)
return True
return False
def add_edge(self, edge):
if edge not in self.edges:
self.edges.append(edge)
return True
return False
def remove_edge(self, edge):
if edge not in self.edges:
return False
self.edges.remove(edge)
return True
|
c199984b3de228c3c5ce68009fb5898aa94c7624 | vektorelpython24proje/temelbilgiler | /HUNKAR/OOP_/Generators.py | 227 | 3.609375 | 4 | import random as rnd
liste = [i for i in range(1000)]
def luckies(liste,count):
for i in range(count):
yield rnd.choice(liste)
for item in luckies(liste,3):
print(item)
print(rnd.sample(liste,3))
|
4786ad99401f82f44a763a25ca7714bc584c2aad | Gutu-Ivan/Bazele-programarii | /02.10.19/3.py | 250 | 3.96875 | 4 | a = input ("Введите основание:")
a = int(a)
b = input ("Введите основание:")
b = int(b)
h = input("Введите высоту:")
h = int(h)
print ("Площадь трапеции равна:", int(1/2*(a+b)*h)) |
543bb6b85e932e11b2ed087b78c69cb82e2d4af8 | qq122716072/ai_note | /numpy_demo/numpy02.py | 209 | 3.65625 | 4 | import numpy as np
a = np.array([1,2,3,4,5,6])
#变矩阵
b = a.reshape(3,2)
print(b)
print(np.sum(b, axis=1))
p = np.array([2,2])
print(p-b)
#距离计算 欧氏距离
print(np.sum((p-b)**2, axis=1)**0.5) |
d4988376f26201b5ffbd21b10dd9901426a6eef4 | brn016/cogs18 | /18 Projects/Project_k4carr_attempt_2018-12-12-11-27-27_SnakeWithExtraCredit/SnakeWithExtraCredit/my_module/functions.py | 7,716 | 3.75 | 4 |
# coding: utf-8
# In[ ]:
import turtle
import random
import os
from time import sleep
class food():
def __init__ (self, foodChar, terminal):
self.foodChar = foodChar
self.terminal = terminal
def foodShape(self):
shapes = ["arrow", "turtle", "circle", "triangle", "classic"]
food = random.choice(shapes)
return food
def foodColor(self):
colors = ["red", "blue", "green", "yellow", "orange", "purple"]
food = random.choice(colors)
return food
def foodStamp(self, foodChar):
stamp = self.foodChar.stamp
stamp
class snake(food):
def __init__ (self, foodChar, character, terminal):
super().__init__(foodChar, terminal)
self.foodChar = foodChar
self.character = character
self.terminal = terminal
def spawnSnake(self, character, terminal):
self.character.penup()
self.character.shape("square")
class controls(snake):
collisionCount = 0
lengthStep = 3
speedStep = 2
speedBrake = 32
def __init__ (self, foodChar, character, terminal):
super().__init__(foodChar, character, terminal)
self.foodChar = foodChar
self.character = character
self.terminal = terminal
def left(self):
if self.character.heading()!=0:
self.character.speed(0)
self.character.setheading(180)
self.character.speed(self.speedStep) #SPEED CONTROL
def right(self):
if self.character.heading()!=180:
self.character.speed(0)
self.character.setheading(0)
self.character.speed(self.speedStep) #SPEED CONTROL
def up(self):
if self.character.heading()!=270:
self.character.speed(0)
self.character.setheading(90)
self.character.speed(self.speedStep) #SPEED CONTROL
def down(self):
if self.character.heading()!=90:
self.character.speed(0)
self.character.setheading(270)
self.character.speed(self.speedStep) #SPEED CONTROL
def reset(self):
self.character.speed(0)
self.character.goto(0,0)
self.character.speed(self.speedStep)
def quit(self):
self.terminal.bye()
class playGame(controls):
sList = []
def __init__ (self, foodChar, character, terminal):
super().__init__(foodChar, character, terminal)
self.foodChar = foodChar
self.character = character
self.terminal = terminal
def insertFood(self, foodChar):
X = random.randrange(-self.terminal.screensize()[0]+60, self.terminal.screensize()[0]-60, 20)
Y = random.randrange(-self.terminal.screensize()[1]+60, self.terminal.screensize()[1]-60, 20)
foodPos = [X,Y]
self.foodChar.speed(0)
self.foodChar.penup()
self.foodChar.setpos(foodPos)
self.foodChar.shape(self.foodShape())
self.foodChar.color(self.foodColor())
self.foodStamp(self.foodChar)
def check_bounds(self):
if abs(self.character.position()[0]) >= abs(self.terminal.screensize()[0]-50):
self.character.speed(0)
self.character.hideturtle()
self.character.goto((self.character.position()[0]*-1),self.character.position()[1])
self.character.showturtle()
self.character.speed(self.speedStep) #SPEED CONTROL
if abs(self.character.position()[1]) >= abs(self.terminal.screensize()[1]-50):
self.character.speed(0)
self.character.hideturtle()
self.character.goto((self.character.position()[0]),self.character.position()[1]*-1)
self.character.showturtle()
self.character.speed(self.speedStep) #SPEED CONTROL
def snakePos(self, character):
return self.character.position()
def foodPos(self, foodChar):
return self.foodChar.position()
def collisionDetect(self, foodChar, character):
food = self.foodPos(self.foodChar)
snake = self.snakePos(self.character)
if round((food[0]),0) == round((snake[0]),0) and round((food[1]),0) == round((snake[1]),0):
self.terminal.delay(0)
self.character.speed(0)
self.foodChar.clearstamp(self.insertFood(foodChar))
self.collisionCounter()
self.lengthStepper()
self.speedStepper()
self.terminal.delay(self.speedBrake)
self.character.speed(self.speedStep)
def collisionCounter(self):
self.collisionCount += 1
return self.collisionCount
def lengthStepper(self):
if (self.collisionCount%2) == 0:
self.lengthStep += 3
def speedStepper(self):
if (self.collisionCount%10) == 0:
self.speedBrake -= 2
def gameOver (self):
sPosX = round((self.character.xcor()),0)
sPosY = round((self.character.ycor()),0)
sPos = (sPosX, sPosY)
if len(self.sList)>= self.lengthStep and sPos in self.sList: #This loop ends the game if the snake runs into itself
self.character.speed(0)
self.character.hideturtle()
self.character.goto(0,0)
for stamp in self.sList:
self.character.clearstamps(1)
self.character.write('Game Over', move=True, align="center", font=("Arial", 32, "bold"))
sleep(2)
self.terminal.bye()
def moveSnake(self, character, terminal):
self.spawnSnake(self.character, self.terminal)
while True:
try:
sPosX = round((self.character.xcor()),0)
sPosY = round((self.character.ycor()),0)
sPos = (sPosX, sPosY)
self.gameOver()
self.sList.append(sPos) #add the snake head position to the body
self.collisionDetect(self.foodChar, self.character) #clear and add new food when snake eats
self.character.speed(self.speedStep) #sets base speed of snake
self.terminal.delay(self.speedBrake) #set brake on speed of snake - used to increase speed
self.character.forward(20)
self.character.stamp()
if len(self.sList)>self.lengthStep: #LENGTH CONTROL
self.character.clearstamps(1)
del(self.sList[0])
self.check_bounds()
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).left, "Left")
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).right, "Right")
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).up, "Up")
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).down, "Down")
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).reset, "space")
self.terminal.onkey(controls(self.foodChar, self.character, self.terminal).quit, "q")
self.terminal.listen()
except:
os._exit(0)
def snakeGame():
random.seed()
turtle.setup(width=700, height=500, startx=0, starty=0)
window = turtle.Screen()
window.title("Hungry Python!")
window.bgcolor("lightgreen")
tess = turtle.Turtle()
snack = turtle.Turtle()
ssssnack = playGame(snack, tess, window)
ssssnack.insertFood(snack)
ssss = playGame(snack, tess, window)
ssss.moveSnake(tess, window)
window.mainloop()
|
770c6063732e81270a65e5e202c8c145a56e10cc | LinglingJ/Python | /DecryptFile.py | 1,345 | 3.609375 | 4 | #Given an encypted text try to decrypt
import os, sys
def main():
#Open input file and save into message
EncryptedFile = 'SomeCipherText.txt'
if not os.path.exists(EncryptedFile):
print('------------------------Could not find input file----------------------')
quit()
fileObj = open(EncryptedFile)
content = fileObj.read()
fileObj.close()
#Open output file
DecryptedFile = 'Decrypted.txt'
if not os.path.exists(DecryptedFile):
print('------------------------Could not find output file---------------------')
quit()
fileObj_Out = open(DecryptedFile,'w')
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
totalLetters = 0
thisList = []
translated = ''
#Setting the shift key and shifting the letters
#for key in range(1,26):
# count = 0
key = 18
for indexOne in range(0,len(content)-1):
if not SYMBOLS.find(content[indexOne]) == -1:
newIndex = SYMBOLS.find(content[indexOne]) + key
if newIndex>25:
newIndex -=26
translated = translated + SYMBOLS[newIndex]
else:
translated = translated + content[indexOne]
#Printing out the decrypted File.
fileObj_Out.write(translated)
fileObj_Out.close()
print('Done')
print('')
main()
|
c63b27dd013ec74ae6c1decee24d2804055432e0 | AaronLi/DNA-Codons | /levenshtein.py | 2,124 | 3.53125 | 4 | class Levenshtein:
alphabet = "abcdefghijklmnopqrstuvwxyz "
def __init__(self, **weight_dict):
self.w = dict(((letter, (7, 1, 6)) for letter in Levenshtein.alphabet + Levenshtein.alphabet.upper()))
if weight_dict:
self.w.update(weight_dict)
def get_distance(self, s, t):
"""
Levenshtein.get_distance(s, t) -> ldist
ldist is the Levenshtein distance between the strings
s and t.
For all i and j, dist[i,j] will contain the Levenshtein
distance between the first i characters of s and the
first j characters of t
weight_dict: keyword parameters setting the costs for characters,
the default value for a character will be 1
"""
rows = len(s) + 1
cols = len(t) + 1
dist = [[0 for i in range(cols)] for i in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for row in range(1, rows):
dist[row][0] = dist[row - 1][0] + self.w[s[row - 1]][0]
# target prefixes can be created from an empty source string
# by inserting the characters
for col in range(1, cols):
dist[0][col] = dist[0][col - 1] + self.w[t[col - 1]][1]
for col in range(1, cols):
for row in range(1, rows):
deletes = self.w[s[row - 1]][0]
inserts = self.w[t[col - 1]][1]
subs = max((self.w[s[row - 1]][2], self.w[t[col - 1]][2]))
if s[row - 1] == t[col - 1]:
subs = 0
else:
subs = subs
dist[row][col] = min(dist[row - 1][col] + deletes,
dist[row][col - 1] + inserts,
dist[row - 1][col - 1] + subs) # substitution
return dist[row][col]
if __name__ == "__main__":
levenshtein_engine = Levenshtein()
print(levenshtein_engine.get_distance("lycine", "lycane"))
print(levenshtein_engine.get_distance("guan", "leycein")) |
7de5eae167fa9cb5411abab797f4da5a65f16c99 | himma-civl/30daysofpython | /Day6_Practices.py | 1,132 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 9 00:33:38 2021
@author: yesye
"""
# Day 6 - 30DaysOfPython Challenge
# Practices
empty = ()
sisters = ('Ina', 'Rushia')
brothers = ('Angus', 'Izumi')
siblings = sisters + brothers
print('I have', len(siblings) , 'siblings.')
siblings = list(siblings)
siblings.append('Catdy')
siblings.append('Willman')
family_members = tuple(siblings)
print(family_members)
siblings = family_members[0:4]
parents = family_members[4:]
fruits = ('Apple', 'Banana', 'Mango', 'Kiwi')
vegetables = ('Cabbage', 'Peas', 'Lettuce', 'Spinach')
animal_products = ('Pork', 'Beef', 'Watame', 'Pekora')
food_stuff_tp = fruits + vegetables + animal_products
food_stuff_lt = list(food_stuff_tp)
length = len(food_stuff_tp)
if length % 2 == 0:
middle = food_stuff_tp[length // 2 - 1:length // 2 + 1]
else:
middle = food_stuff_tp[length // 2 - 1]
print(middle)
first_three = food_stuff_lt[0:3]
last_three = food_stuff_lt[-1:-4:-1]
del food_stuff_tp
nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden')
print('Estonia' in nordic_countries)
print('Iceland' in nordic_countries) |
9761e93381f85d1b47c1f4df86b1f8ce19e75fbc | ErlangZ/projecteuler | /36.py | 225 | 3.671875 | 4 | def is_bin_palindromes(x):
bstr = bin(x)[2:]
return bstr[::-1] == bstr
def is_int_palindromes(x):
s = str(x)
return s[::-1] == s
print sum([i for i in xrange(1000000) if is_int_palindromes(i) and is_bin_palindromes(i)])
|
20da3dfe4bd89485c26425353fb1867f82155cd6 | brandonjohnbaptiste/python-book-problems | /ch1-numbers/number_guess.py | 1,215 | 4.3125 | 4 | import random
# standard guessing game
def guessing_game():
rand_num = random.randint(0, 100)
# Loop until number found
while True:
guess = int(input('Enter Your Guess: '))
if guess == rand_num:
print(f'{guess} is the correct guess!')
break
elif guess < rand_num:
print('Guess too Low')
else:
print('Guess too High')
def guess_game_max_guess(max_guesses):
count = 0
rand_num = random.randint(0, 100)
# loop until the number is guessed or user runs out of guesses
while count < max_guesses:
guess = int(input('Enter Your Guess: '))
# TODO: check guesses are left, then run game logic
if guess == rand_num:
print(f'{guess} is the correct guess!')
break
elif guess < rand_num:
count += 1
print('Guess too Low')
print(f'You have {max_guesses - count} guesses left')
else:
count += 1
print('Guess too High')
print(f'You have {max_guesses - count} guesses left')
print('Maximum guesses reached you loose!')
if __name__ == '__main__':
guess_game_max_guess(3)
|
4508a8d9cb718b05baddd3bbed0b18d86555b618 | JoaoZati/ListaDeExerciciosPythonPro | /EstruturaDeRepeticao/Ex_43.py | 2,276 | 3.671875 | 4 | #%% 43 - Cardapio Lanchonete
"""
O cardápio de uma lanchonete é o seguinte:
Especificação Código Preço
Cachorro Quente 100 R$ 1,20
Bauru Simples 101 R$ 1,30
Bauru com ovo 102 R$ 1,50
Hambúrguer 103 R$ 1,20
Cheeseburguer 104 R$ 1,30
Refrigerante 105 R$ 1,00
Faça um programa que leia o código dos itens pedidos e as quantidades
desejadas. Calcule e mostre o valor a ser pago por item
(preço * quantidade) e o total geral do pedido. Considere que o cliente
deve informar quando o pedido deve ser encerrado.
"""
dic_codigo = {'100': 1.20,
'101': 1.30,
'102': 1.50,
'103': 1.20,
'104': 1.30,
'105': 1.00,}
dic_codigo_soma = {'100': 0,
'101': 0,
'102': 0,
'103': 0,
'104': 0,
'105': 0,}
dic_codigo_print = {'100': 'Cachorro Quente',
'101': 'Bauru Simples',
'102': 'Bauru com ovo',
'103': 'Hambúrguer',
'104': 'Cheeseburguer',
'105': 'Refrigerante',}
def imputcodigo(menssagem):
while True:
inp = input(menssagem).lower()
if inp not in dic_codigo.keys() and inp != 'end':
print('O codigo não consta no cardapio')
continue
return inp
def imputnumerocomloop_inteiro(mensagem):
while True:
try:
inp = int(input(mensagem))
if inp <= 0:
print('O numero tem que ser maior que zero')
continue
return inp
except ValueError:
print('Insira um numero inteiro')
while True:
codigo = imputcodigo('Digite o codigo do produto (digite "end" para sair): ')
if codigo == 'end':
break
quantidade = imputnumerocomloop_inteiro('Digite a quantidade do produto: ')
for key, value in dic_codigo.items():
if codigo == key:
dic_codigo_soma[key] += quantidade * value
total_pagar = 0
for key, value in dic_codigo_print.items():
total_pagar += dic_codigo_soma[key]
print(f'{key}: R$ {dic_codigo_soma[key]}')
print(f'Total: R$ {total_pagar}')
|
39ac5774d88f38099ea499447f80cceec55acca2 | fuenfundachtzig/Pythonkurs1 | /notebooks/source/solutions/titanic_chk.py | 433 | 3.71875 | 4 | import sqlite3
conn = sqlite3.connect('titanic.db')
curs = conn.cursor()
curs.execute('''SELECT * FROM titanic''')
# fetch all entries in 1 go
alld = curs.fetchall()
print(len(alld))
print(alld[0])
# (0, u'male', 22.0, 7.25, u'S', u'Third', u'man', None, u'Southampton')
# select entries 3rd class and male
sm3 = [ x[0] for x in alld if x[5]=='Third' and x[1]=='male' ]
# survival rate
print(float(sum(sm3))/len(sm3))
|
041bf343bca267524d8e46d80e1396a4af4b8b12 | Michaela192/ENGETO-Projekt2 | /Projekt_2.py | 4,506 | 3.671875 | 4 | import random
ODDELOVAC = 47 * '-'
#Program pozdraví užitele a vypíše úvodní text
print('Hi there!')
print(ODDELOVAC)
print('I´ve generated a random 4 digit number for you.')
print('Let´s play a bulls and cows game.')
print(ODDELOVAC)
#Program dále vytvoří tajné 4místné číslo (číslice musí být unikátní a nesmí začínat 0)
TAJNE_CISLO = []
TAJNE_CISLO_PRVNI = int((random.random() * 10000) / 1000)
if TAJNE_CISLO_PRVNI == 10:
TAJNE_CISLO_PRVNI = int(TAJNE_CISLO_PRVNI / 10)
TAJNE_CISLO.append(TAJNE_CISLO_PRVNI)
TAJNE_CISLO_DRUHE = int(random.random() * 9)
while TAJNE_CISLO_DRUHE == TAJNE_CISLO_PRVNI:
TAJNE_CISLO_DRUHE = int(random.random())
TAJNE_CISLO.append(TAJNE_CISLO_DRUHE)
TAJNE_CISLO_TRETI = int(random.random() * 9)
while TAJNE_CISLO_TRETI == TAJNE_CISLO_PRVNI or TAJNE_CISLO_TRETI == TAJNE_CISLO_DRUHE:
TAJNE_CISLO_TRETI = int(random.random())
TAJNE_CISLO.append(TAJNE_CISLO_TRETI)
TAJNE_CISLO_CTVRTE = int(random.random() * 9)
while TAJNE_CISLO_CTVRTE == TAJNE_CISLO_PRVNI or TAJNE_CISLO_CTVRTE == TAJNE_CISLO_DRUHE or TAJNE_CISLO_CTVRTE == TAJNE_CISLO_TRETI:
TAJNE_CISLO_CTVRTE = int(random.random())
TAJNE_CISLO.append(TAJNE_CISLO_CTVRTE)
POCET_POKUSU = 0
#Hráč hádá číslo. Program jej upozorní, pokud zadá číslo kratší nebo delší než 4 čísla, pokud bude obsahovat duplicity, začínat nulou, příp. obsahovat nečíselné znaky.
while TAJNE_CISLO:
VSTUP = input('Enter a number:')
VSTUP_FINAL = []
for ZNAK in VSTUP:
VSTUP_FINAL.append(ZNAK)
if len(VSTUP_FINAL) > 4 or len(VSTUP_FINAL) < 4:
print('Špatně, nezadal jste 4místné číslo.')
break
if VSTUP_FINAL[0] == VSTUP_FINAL[1] or VSTUP_FINAL[0] == VSTUP_FINAL[2] or VSTUP_FINAL[0] == VSTUP_FINAL[3] or VSTUP_FINAL[1] == VSTUP_FINAL[2] or VSTUP_FINAL[1] == VSTUP_FINAL[3] or VSTUP_FINAL[2] == VSTUP_FINAL[3]:
print('Špatně, zadal jste duplicitní čísla.')
break
if VSTUP_FINAL[0].isnumeric() and VSTUP_FINAL[1].isnumeric() and VSTUP_FINAL[2].isnumeric() and VSTUP_FINAL[3].isnumeric():
I = 0
else:
print('Špatně, zadal jste nečíselné znaky.')
break
#for ZNAK in VSTUP_FINAL:
# if ZNAK.isnumeric():
# continue
# else:
# print('Špatně, zadal jste nečíselné znaky.')
# break
VSTUP_FINAL[0] = int(VSTUP_FINAL[0])
VSTUP_FINAL[1] = int(VSTUP_FINAL[1])
VSTUP_FINAL[2] = int(VSTUP_FINAL[2])
VSTUP_FINAL[3] = int(VSTUP_FINAL[3])
#Program vyhodnotí tip uživatele. Program dále vypíše počet bull/ bulls (pokud uživatel uhodne jak číslo, tak jeho umístění), příp. cows/ cows (pokud uživatel uhodne
# pouze číslo, ale ne jeho umístění). Vrácené ohodnocení musí brát ohled na jednotné a množné číslo ve výstupu. Tedy 1 bull a 2 bulls (stejně pro cow/cows).
I = 0
VYSLEDEK = {'bulls': 0, 'cows': 0}
for ZNAK in TAJNE_CISLO:
I2 = 0
for ZNAK2 in VSTUP:
if int(ZNAK2) == int(ZNAK):
if I == I2:
VYSLEDEK['bulls'] += 1
else:
VYSLEDEK['cows'] += 1
I2 += 1
I += 1
if VYSLEDEK['bulls'] == 4:
POCET_POKUSU += 1
print("Correct, you've guessed the right number")
if POCET_POKUSU == 1:
print('in ', POCET_POKUSU, ' guess!', sep='')
else:
print('in ', POCET_POKUSU, ' guesses!', sep='')
print(ODDELOVAC)
if POCET_POKUSU == 1:
print("That's amazing.")
elif POCET_POKUSU == 2:
print("That's really very good.")
elif POCET_POKUSU == 3:
print("That's very good.")
elif POCET_POKUSU == 4:
print("That's average.")
else:
print("That's not so good.")
break
else:
POCET_POKUSU += 1
VYSLEDEK_BULLS = str(VYSLEDEK['bulls'])
VYSLEDEK_COWS = str(VYSLEDEK['cows'])
if VYSLEDEK['bulls'] == 0 or VYSLEDEK['bulls'] == 1:
VYSLEDEK_BULLS = VYSLEDEK_BULLS + ' bull'
elif VYSLEDEK['bulls'] > 1:
VYSLEDEK_BULLS = VYSLEDEK_BULLS + ' bulls'
if VYSLEDEK['cows'] == 0 or VYSLEDEK['cows'] == 1:
VYSLEDEK_COWS = VYSLEDEK_COWS + ' cow'
elif VYSLEDEK['cows'] > 1:
VYSLEDEK_COWS = VYSLEDEK_COWS + ' cows'
print(VYSLEDEK_BULLS, ', ', VYSLEDEK_COWS, sep='')
print(ODDELOVAC) |
6f0b494a2e71648f090de154e87063ce13114e84 | JDavid121/Script-Curso-Cisco-Python | /130 functions and arguments.py | 348 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 11:46:55 2020
@author: David
"""
# part 1
def myFunction(n):
print("I got", n)
n += 1
print("I have", n)
var = 1
myFunction(var)
print(var)
def myFunction(myList1):
print(myList1)
myList1 = [0, 1]
myList2 = [2, 3]
myFunction(myList2)
print(myList2) |
398c87f7cb322279c2a32c5dc0c0e53e79f0d020 | austin72905/python-lesson | /file_operation/file_operation.py | 1,350 | 4.21875 | 4 | ##文件(file)
#1. I/O (Input/Output)
#2. 操作文件的步驟
# (1) 打開文件
# (2) 對文件的操作( 讀、寫 ),然後保存
# (3) 關閉文件
##打開文件
#1. 語法 open(file)
#2. 參數 file : 路徑
#3. 返回值: 打開的文件(obj)
#4. 路徑用/ 取代\ ,或是 \\
## 讀取文件內容
#1. 語法 文件物件.read()
#2. 可將內容存成一個str
##關閉文件
#1. 語法 文件物件.close()
#2. 如果代碼執行完,文件會自動關閉,會自己是放掉資源,但如果下面還有代瑪,還是要自己關掉
##自動關閉
#1. with open(檔案路徑) as 文件物件:
#2. 對文件的操作只能在with 裡面,(會自動關閉)
#### code region ####
##打開文件
file_name="C:/Users/USER/Python/python_lesson/file_operation/demo.txt"
file_obj = open(file_name)
print(file_obj) #<_io.TextIOWrapper name='C:/Users/USER/Python/python_lesson/file_operation/demo.txt' mode='r' encoding='cp950'>
## 讀取文件內容
content = file_obj.read()
print(content)
##關閉文件
file_obj.close()
##自動關閉
#打該文件應該會報錯 FileNotFoundError: [Errno 2] No such file or directory: 'hello'
#試著捕獲錯誤
file_name1="hello"
try:
with open(file_name1) as file_obj1:
print(file_obj1.read())
except FileNotFoundError:
print(f"{file_name1}不存在~~") |
91558328185d9140b1a2b66e1f8c5b7cdc82a94b | andrejeller/Learning_Python_FromStart | /Exercicios/Fase_07_OperadoresAritimeticos/Exercicio_013.py | 343 | 3.8125 | 4 | """
Desafio 013
- Faça um algorítimo que leia o salário de um funcionário e mostre seu novo salário, com 15% de aumento.
"""
salario = float(input('Salario: '))
aumento = salario * 1.15 # jeito 1
aumento2 = salario + (salario * 15 / 100) # jeito 2
print('O novo valor do se salario com 15% de aumento é de R${:.2f}.'.format(aumento))
|
9f9d9c69b51d21f1c12cb8e6cfd40598ea718401 | Adison25/CS362-hw2 | /leapWithErrorHandling.py | 582 | 4.1875 | 4 | print("Program checking to see if a year is a leap year or not")
run = 1
while run == 1:
year = input("Please enter a year: ")
#check input
if year.isnumeric():
#if info is valid
if int(year) % 4 != 0:
print(str(year) + " is a common year")
elif int(year) % 100 != 0:
print(str(year) + " is a leap year")
elif int(year) % 400 != 0:
print(str(year) + " is a common year")
else:
print(str(year) + " is a leap year")
break
else:
print("Please enter an integer!\n") |
21953cb54cfc5bb3ad9312472bb873ea2f9dd60c | wolffam/CodingPractice | /Python/Fibonacci_recursive.py | 329 | 3.71875 | 4 | # Create fibonacci sequence based on input (list containing starting int) and stops before a provided max number
def fib(seq, max_num):
if len(seq) == 1:
seq.append(seq[0])
while seq[-1] + seq[-2] < max_num:
seq.append(seq[-1] + seq[-2])
fib(seq, max_num)
return seq
print(fib([1], 10000)) |
a76938022cd8ed5e991ab7d69a27b9bf0f25717b | QuantumNinja92/hackerrank | /intro to statistics/1/day1.py | 1,216 | 3.84375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from __future__ import division
N = int(raw_input())
S = raw_input()
As = S.split(" ")
for i in range(0, N):
As[i] = int(As[i])
def InsertionSort(Arr):
check = 0
n = len(Arr)
index = 0
while( check == 0):
if (Arr[index] != Arr[n-1]):
if(Arr[index] > Arr[index+1]):
swap = Arr[index+1]
Arr[index+1] = Arr[index]
Arr[index] = swap
index = 0
else:
index = index + 1
else:
check = 1
return Arr
def histogram(Arr):
D = dict()
for i in range(0, len(Arr)):
if( Arr[i] not in D):
D[Arr[i]] = 1
else:
D[Arr[i]] = D[Arr[i]] + 1
return D
def Mean(Arr):
sum = 0
for i in range(0, len(Arr)):
sum = sum + Arr[i]
mean = sum / len(Arr)
return mean
def Median(Arr):
if(len(Arr)%2 == 0):
Arr = InsertionSort(Arr)
sum = Arr[int((len(Arr)/2) - 1)] + Arr[int(len(Arr)/2)]
avg = sum / 2
return avg
def Mode(Dict):
print Mean(As)
print Median(As)
print histogram(As) |
e7f0208b24090c8a25f5372a415f6be335b456cd | povert/Programming | /python/装饰器实现单例/了解装饰器变量.py | 828 | 3.703125 | 4 | # 自定义一个容器,类,看容器会实例化几次
class Hodect():
def __init__(self,name):
self.li = list()
self.name = name
print(self.name+'容器实例化')
def __del__(self):
print(self.name+"容器删除")
def S(func):
h = Hodect('傅雨')
def wrap(*args,**kwargs):
if func not in h.li:
h.li.append(func)
print('%s装饰完毕'%(func.__name__))
return func(*args,**kwargs)
return wrap
@S
def func1():
print('func1')
@S
def func2():
print('func2')
@S
def func3():
print('func3')
@S
def func4():
print('func4')
def f():
print("ff")
if __name__=='__main__':
# 装饰器注释几次实例化几次,而且不论调用与否
func1()
func1()
func2()
func2()
func3()
func4()
S(f)
|
598dc1c6301f27ff5593ac193151b8f336961dd6 | I-will-miss-you/CodePython | /Curso em Video/Duvidas/d010.py | 607 | 3.625 | 4 | #Proposta 4:
#Escreva um programa para calcular o tempo de vida de um fumante. Pergunte a quantidade de cigarros fumados por dia e
# por quantos anos ele fumou. Considere que um fumante perde 10 minutos de vida a cada cigarro, calcule quantos dias
# de vida um fumante perderá. Exiba o total em dias.
qtdCigarros = int(input('Quantidade de cigarros fumados por dia: '))
qtdAnosFumou = int(input('Quantos anos ele fumou: '))
vidaPerdida = 10 * qtdCigarros * 365 * qtdAnosFumou #minutos perdidos
diasPerdidos = vidaPerdida / (24 * 60)
print("Você já perdeu {:.0f} dias de vida".format(diasPerdidos))
|
a7aeb9aaa6aa0c5cd21408873645ae636ababf34 | imatyukin/python | /PythonCrashCourse/chapter_09/exercise9_14.py | 913 | 3.734375 | 4 | #!/usr/bin/env python3
from random import randint
class Die():
def __init__(self, sides=6):
'''N-гранный кубик'''
self.sides = sides
def roll_die(self, throws):
'''Вывод случайного числа от 1 до количества сторон кубика с иммитацией количества бросков'''
nums = [randint(1, self.sides) for throw in range(0, throws)]
return print(', '.join(str(x) for x in nums))
cube = Die(6) # модель 6-гранного кубика
cube.roll_die(10) # имитация 10 бросков кубика
cube = Die(10) # модель 10-гранного кубика
cube.roll_die(10) # имитация 10 бросков кубика
cube = Die(20) # модель 20-гранного кубика
cube.roll_die(10) # имитация 10 бросков кубика |
5fda270a7bc285b564fa6890dcb309c125d641e3 | Taoge123/OptimizedLeetcode | /LeetcodeNew/python/LC_042.py | 1,363 | 3.765625 | 4 | """
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
In this case, 6 units of rain water (blue section) are being trapped.
Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
"""
class Solution:
def trap(self, height):
left, right = 0, len(height) - 1
leftMax, rightMax = 0, 0
res = 0
while left < right:
if height[left] < height[right]:
leftMax = max(height[left], leftMax)
res += leftMax - height[left]
left += 1
else:
rightMax = max(height[right], rightMax)
res += rightMax - height[right]
right -= 1
return res
class SolutionStack:
def trap(self, height) -> int:
stack = []
res = 0
for i in range(len(height)):
while stack and height[stack[-1]] < height[i]:
base = height[stack.pop()]
if not stack:
continue
# 看pop的左右边哪个小 - 刚pop出去的
h = min(height[stack[-1]], height[i]) - base
w = i - stack[-1] - 1
res += w * h
stack.append(i)
return res
height = [0,1,0,2,1,0,1,3,2,1,2,1]
a = Solution()
print(a.trap(height))
|
d10d970e4759e9330a4c64104150002b25409041 | aliumaev/PythonLesson | /Task#3.py | 440 | 3.75 | 4 | # Lesson #1
# 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369.
while True:
n = input("Please enter integer number n: ")
if n.isdigit():
n = int(n)
result = n+n*n+n*n*n
print(f"n+n*n+n*n*n = {n}+{n}*{n}+{n}*{n}*{n} = {result}")
break
|
cc761cec65900a54059da17b2f433b399675377d | tsmchoe/cs591_c2_assignment_6 | /problem_3/problem_3_test.py | 933 | 4.03125 | 4 | import unittest
from problem_3 import string_multiplication
class TestStringMethods(unittest.TestCase):
def test_string_multiplication(self):
self.assertEqual(string_multiplication('0','0'), '0', 'string_multiplication("0","0") should return "0"')
self.assertEqual(string_multiplication('12','6'), '18', 'string_multiplication("12","6") should return "18"')
self.assertNotEqual(string_multiplication('0','0'), 0, 'string_multiplication("0","0") should not return 0')
self.assertNotEqual(string_multiplication('12','6'), 18, 'string_multiplication("12","6") should not return 18')
self.assertEqual(string_multiplication('7598','1339130'), '1346728', 'string_multiplication("7598","1339130") should return "1346728"')
self.assertEqual(string_multiplication('503','30'), '533', 'string_multiplication("503","30") should return "533"')
if __name__ == '__main__':
unittest.main() |
0afbd9e73d731d26bdccdd56efd42f0787b48fc1 | AmauryOrtega/scripts-simulacion | /Binomial_Dados.py | 495 | 3.625 | 4 | import random
n_corridas = 50
n_lanzamientos = 51
P = 1.0/6.0
respuesta = 0.0 # Cuantas veces se obtuvieron 20 veces el numero 3 luego de n_lanzamientos
for corrida in range(n_corridas):
# INICIO Corrida
numero_3es = 0
for lanzamiento in range(n_lanzamientos):
R = random.uniform(0, 1)
if R < P:
numero_3es += 1.0
print("51 Lanzamientos con", numero_3es, "3es")
# FIN Corrida
# Conteo para probabilidad
if numero_3es == 20: respuesta += 1.0
print("P(X=20):", respuesta/n_corridas) |
a73c1e9bb149d6d68b750f41fc8f9e2e0742f3aa | aj2010adil/HackerRank-Python | /Print Function | 249 | 4.09375 | 4 | #!/bin/python
from __future__ import print_function
if __name__ == '__main__':
n = int(raw_input()) #taking input from user
for i in range(1,n+1):
print(i,end='') #end="" is used for printing the output in the same line
|
44e4a9c5c57a9e799d7933573cea95fb3501d884 | ivanakonatar/Homework04 | /zad6.py | 219 | 3.625 | 4 | #za dati broj vratiti listu pozicija na kojima se pojavljuje u proslijedjenom nizu
niz=[1,2,3,4,5,3,7,7]
broj=3
pozicije=[]
for i in range(len(niz)):
if niz[i] == broj:
pozicije.append(i)
print(pozicije) |
4eaa7c71f152841032f0e834e74e840476b1c0df | Gulnaz-Tabassum/hacktoberfest2021 | /Python/Factorials_of_large_numbers.py | 483 | 3.8125 | 4 | class Solution:
def factorial(self, N):
fact = 1
while(N>=1):
fact = fact * N
N = N-1
return str(fact)
if __name__ == '__main__':
t=int(input())
for _ in range(t):
N = int(input())
ob = Solution()
ans = ob.factorial(N)
for i in ans:
print(i,end="")
print()
# Input: N = 10
# Output: 3628800
# Explanation :
# 10! = 1*2*3*4*5*6*7*8*9*10 = 3628800
|
82318bae4d37238cb94a00b1f1d4af01d3692eb4 | arundaniel-kennedy/Cryptographic-Algorithms | /CNS-dany/diffie.py | 188 | 3.53125 | 4 |
p = int(input("Enter p"))
k = int(input("Enter k"))
a = int(input("Enter a"))
b = int(input("Enter b"))
c = (k**a)%p
d = (k**b)%p
ssk1 = (d**a)%p
ssk2 = (c**b)%p
print(ssk1,ssk2,c,d) |
a1fa9660bd5ae4d2d4614d5aa3a5ac1056cf242e | siokas/Python-Class1 | /project2/Motor.py | 221 | 3.625 | 4 | class Motor:
isBig = False
def __init__(self, port, isBig=False):
self.isBig = isBig
if isBig:
print(port + " MOTOR is big")
else:
print(port + " MOTOR is small")
|
9670c33ccf6ab9ce46680c31409fdd968584e639 | pengzhefu/LeetCodePython | /array/easy/q189.py | 2,133 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 09:47:18 2019
@author: pengz
"""
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
'''
def rotate(nums, k): ## written by my own, time complexity is O(n)
"""
Do not return anything, modify nums in-place instead.
"""
## this just like the right rotate, from the bottom to head,
## using reversal
def reversal(list1,start,end):
while start <= end:
tmp = list1[start]
list1[start] = list1[end]
list1[end] = tmp
start = start+1
end = end-1
times = k%len(nums)
reversal(nums,0,len(nums)-1)
reversal(nums,0,times-1)
reversal(nums,times,len(nums)-1)
#def reversal(list1,start,end):
# while start <= end:
# tmp = list1[start]
# list1[start] = list1[end]
# list1[end] = tmp
# start = start+1
# end = end-1
a = [1,2]
rotate(a,3)
def rotate1(nums, k): ## Time exceeded, O(n*k)
"""s
Do not return anything, modify nums in-place instead.
"""
## this just like the right rotate, from the bottom to head,
## using reversal
times = k%len(nums)
i = 1
while i <= times:
tmp = nums[-1]
for j in range(len(nums)-1,0,-1):
nums[j] = nums[j-1]
nums[0] = tmp
# print('换了一次')
# print(i)
i = i+1
#b = [1,2,3,4,5,6,7]
#rotate1(b,3) |
2c3b8adfa38c6e514bebd2061edf8475a30e3ae3 | JimmyRomero/AT06_API_Testing | /JimmyRomero/Python/Exam/Employee_commercial.py | 764 | 3.546875 | 4 | from Python.Exam.Person import Person
class EmployeeCommercial(Person):
def __init__(self, name, pieces, department, num):
super().__init__(name, pieces)
self.department = department
self.id = "CE-00" + str(num)
self.salary = 0
self.discount = 0
def get_id(self):
return self.id
def get_salary(self):
return self.pieces * 2.5
def get_discount(self):
return self.get_salary() * 12.5 / 100
def get_net_salary(self):
return self.get_salary() - self.get_discount()
def get_employee(self):
return "{}| {}| {}| {}| {}| {}".format(self.id, self.name, self.department, str(self.get_salary()), str(
self.get_discount()), str(self.get_net_salary()))
|
f23dd5bb31fd50a0c2877041d1220f8ac9168266 | escoffier/algorithm-py | /myList.py | 1,007 | 3.796875 | 4 | from typing import List
class MyList:
def __init__(self, parameter_list:List):
self.vaules = parameter_list
def __iter__(self):
print('MyList::__iter__')
return MyListIterator(self)
def length(self):
return len(self.vaules)
def at(self, i:int):
return self.vaules[i]
class MyListIterator:
def __init__(self, myList:MyList):
self.list = myList
self.index = 0
print('MyListIterator::__init__')
def __iter__(self):
print('__iter__()')
return self
def __next__(self):
if self.index < self.list.length():
print('__next__')
result = self.list.at(self.index)
self.index += 1
return result
raise StopIteration
if __name__ == "__main__":
list1 = [5,4, 1, 2,6,9]
list2 = MyList(list1)
for i in list2:
print(i)
print('###########')
ite = iter(list2)
for v in ite:
print(v)
# print(next(ite)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.