blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c9f8feb5dceca65df1e800cdf743dd417983e1d3 | candyer/codechef | /September Challenge 2018/MAGICHF/MAGICHF.py | 950 | 3.59375 | 4 | # https://www.codechef.com/SEPT18B/problems/MAGICHF
#######################
###### solution 1 #####
#######################
def solve(n, x, s, actions):
boxes = [False] * (n + 1)
boxes[x] = True
res = x
for a, b in actions:
if boxes[a]:
boxes[a], boxes[b] = boxes[b], boxes[a]
res = b
elif boxes[b]:
boxes[a], boxes[b] = boxes[b], boxes[a]
res = a
return res
#######################
###### solution 2 #####
#######################
def solve(n, x, s, actions):
res = x
for a, b in actions:
if a == res:
res = b
elif b == res:
res = a
return res
if __name__ == '__main__':
t = int(raw_input())
for _ in range(t):
n, x, s = map(int, raw_input().split())
actions = []
for i in range(s):
a, b = map(int, raw_input().split())
actions.append((a, b))
print solve(n, x, s, actions)
assert solve(5, 2, 4, [(4, 2), (3, 4), (3, 2), (1, 2)]) == 1
assert solve(5, 1, 3, [(1, 2), (3, 4), (2, 1)]) == 1
|
2bc16f43539e10dd76edfafd8c81deb868a8b15d | Kwasniok/Cards | /core/owning.py | 721 | 3.921875 | 4 | from abc import abstractmethod
class Owner:
@abstractmethod
def __init__(self):
pass
class Owned:
@abstractmethod
def __init__(self, owner):
self._owner = None
self.change_owner(owner)
def get_owner(self):
return self._owner
def change_owner(self, owner):
if not isinstance(owner, Owner):
raise (
TypeError(
"Cannot change owner of "
+ str(self)
+ " due to invalid owner "
+ str(owner)
+ " (must be a "
+ str(Owner)
+ ")."
)
)
self._owner = owner
|
877fece738080ab8437571be6664d2c0f50445a7 | gitjcart/python | /clinic.py | 1,256 | 4.09375 | 4 | # clinic.py
def clinic():
print "you've been chosen to represent the break lounge!"
print "pick a number between 1-10"
answer = raw_input("!!! ").lower()
if answer == "1" or answer == "one":
print "was your number %s!?" %(answer)
elif answer == "2" or answer == "two":
print "was your number %s!?" %(answer)
elif answer == "3" or answer == "three":
print "was your number %s!?" %(answer)
elif answer == "4" or answer == "four":
print "was your number %s!?" %(answer)
elif answer == "5" or answer == "five":
print "was your number %s!?" %(answer)
elif answer == "6" or answer == "six":
print "was your number %s!?" %(answer)
elif answer == "7" or answer == "seven":
print "was your number %s!?" %(answer)
elif answer == "8" or answer == "eight":
print "was your number %s!?" %(answer)
elif answer == "9" or answer == "nine":
print "was your number %s!?" %(answer)
elif answer == "10" or answer == "ten":
print "was your number %s!?" %(answer)
else:
print "you didn't pick a number! Try again.."
clinic()
clinic()
# inserted to see how it feels
# took it out and re inserted it, to see how it felt again. |
f9145c857320988897d3e8861d551d872cde2358 | ericskim/redax | /redax/spaces.py | 19,871 | 3.796875 | 4 | r"""
Nomenclature:
bv = Bit vector \n
box = \n
point = element of set \n
cover = \n
grid = a countable set of points embedded in continuous space \n
"""
import itertools
import math
from abc import abstractmethod
from typing import Iterable, Tuple
from dataclasses import dataclass, InitVar, field
import numpy as np
from redax.utils.bv import bv2pred, bvwindow, bvwindowgray, BitVector, int2bv, bv2int, bintogray, graytobin, increment_bv, bv_interval
class OutOfDomainError(Exception):
"""
Exception raisen whenever a concrete value assumes a value that has no
corresponding discrete encoding
For example, a continuous interval [0,1] partitioned into two discrete bins
and encoded with a single bit cannot encode the points -1.4 or 3.
"""
pass
# TODO: Composite spaces combined through + and *.
@dataclass(frozen=True)
class SymbolicSet(object):
"""Abstract class for representing a concrete underlying space and handling translation to symbolic encodings."""
pass
@dataclass(frozen=True)
class DiscreteSet(SymbolicSet):
r"""Discrete set abstract class."""
num_vals : int
@property
def num_bits(self):
return math.ceil(math.log2(self.num_vals))
@property
def bounds(self) -> Tuple[float, float]:
return (0, self.num_vals-1)
def pt2bv(self, point) -> BitVector:
assert point < self.num_vals
return int2bv(point, self.num_bits)
def abs_space(self, mgr, name: str):
"""
Return the predicate of the discrete set abstract space.
Parameters
----------
mgr: bdd
manager
name: str
BDD variable name, e.g. "x" for names "x_1", "x_2", etc.
"""
left_bv = int2bv(0, self.num_bits)
right_bv = int2bv(self.num_vals-1,self.num_bits)
bvs = bv_interval(left_bv, right_bv)
boxbdd = mgr.false
for i in map(lambda x: bv2pred(mgr, name, x), bvs):
boxbdd |= i
return boxbdd
def conc2pred(self, mgr, name: str, concrete):
"""
Translate from a concrete value to a the associated predicate.
Parameters
----------
mgr (dd mgr):
name:
concrete:
Returns
-------
bdd:
"""
assert concrete >= 0 and concrete < self.num_vals
bv = int2bv(concrete, self.num_bits)
return bv2pred(mgr, name, bv)
def bv2conc(self, bv: BitVector) -> int:
"""
Converts a bitvector into a concrete grid point
"""
return bv2int(bv)
def conc_iter(self):
return range(self.num_vals)
@dataclass(frozen=True)
class EmbeddedGrid(DiscreteSet):
"""
A discrete grid of points embedded in continuous space.
Parameters
----------
num_vals : int
Number of points in the grid
left : float
Left point (inclusive)
right : float
Right point (inclusive)
Example
-------
EmbeddedGrid(4,-2,2) corresponds with points [-2, -2/3, 2/3, 2]
"""
lb: float
ub: float
periodic: bool = False
def __post_init__(self):
if self.num_vals <= 0:
raise ValueError("Grid must have at least one point")
if self.lb > self.ub:
raise ValueError("Left point is greater than right")
if self.num_vals == 1 and self.lb != self.ub:
raise ValueError("Single point but left and right are not equal")
@property
def pts(self):
if self.periodic:
right = self.ub - (self.ub-self.lb)/self.num_vals
return np.linspace(self.lb, right, self.num_vals)
else:
return np.linspace(self.lb, self.ub, self.num_vals)
def width(self):
return self.ub - self.lb
def _wrap(self, val):
return self.lb + (val - self.lb) % self.width()
def find_nearest_index(self, array, value) -> int:
if self.periodic:
value = self._wrap(value)
idx = np.searchsorted(array, value, side="left")
if self.periodic and idx in (self.num_vals, self.num_vals-1):
right = self.ub - self.width()/self.num_vals
if math.fabs(value - self.width() - self.lb) < math.fabs(value - right):
return 0
if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
return idx-1
else:
return idx
def pt2index(self, pt: float, snap=False) -> int:
"""
Parameters
----------
pt : float
Continuous point to be converted into a bitvector
snap : bool
Snaps pt to the nearest discrete point with preference towards greater point. Otherwise requires exact equality.
Returns
-------
int
"""
if snap:
return self.find_nearest_index(self.pts, pt)
elif pt in self.pts:
return np.searchsorted(self.pts, pt)
else:
raise ValueError("Cannot find an exact match without snapping")
def conc2pred(self, mgr, name: str, concrete, snap=True):
"""
Translate from a concrete value to a the associated predicate.
Parameters
----------
mgr (dd mgr):
name:
concrete:
snap:
Returns
-------
bdd:
"""
bv = int2bv(self.pt2index(concrete, snap), self.num_bits)
return bv2pred(mgr, name, bv)
def conc_iter(self) -> Iterable:
"""Iterable of points."""
return self.pts
def bv2conc(self, bv: BitVector) -> float:
"""Converts a bitvector into a concrete grid point."""
return self.pts[bv2int(bv)]
@dataclass(frozen=True)
class ContinuousCover(SymbolicSet):
"""
Continuous Interval
"""
lb: float
ub: float
def __post_init__(self):
assert self.ub - self.lb >= 0.0, "Upper bound is smaller than lower bound"
@property
def bounds(self) -> Tuple[float, float]:
return (self.lb, self.ub)
def width(self) -> float:
return self.ub - self.lb
def conc_space(self) -> Tuple[float, float]:
"""Concrete space."""
return self.bounds
@dataclass(frozen=True)
class DynamicCover(ContinuousCover):
"""
Dynamically covers the space with a variable number of bits.
Number of covers is always a power of two.
"""
periodic: bool = False
def _wrap(self, point: float):
"""Helper function for periodic intervals."""
if point == self.ub:
return point
width = self.ub - self.lb
return ((point - self.lb) % width) + self.lb
def abs_space(self, mgr, name:str):
"""
Returns the predicate of the abstract space
"""
return mgr.true
def pt2bv(self, point: float, nbits: int, tol=0.0):
"""
Continuous point to a bitvector
Parameters
----------
point : float
Continuous point
nbits : int
Number of bits to encode
Returns
-------
Tuple of bools:
Left-most element is most significant bit. Encoding is the standard binary encoding or gray code.
"""
assert isinstance(nbits, int)
if self.periodic:
point = self._wrap(point)
index = self.pt2index(point, nbits, alignleft=True)
if self.periodic:
index = bintogray(index)
return int2bv(index, nbits)
def pt2index(self, point: float, nbits: int, alignleft=True, tol=0.0) -> int:
"""Convert a floating point into an integer index of the cover the point lies in."""
assert isinstance(nbits, int)
if self.periodic:
point = self._wrap(point)
if point > self.ub + tol:
raise OutOfDomainError("Point {0} exceepds upper bound {1}".format(point, self.ub+tol))
if point < self.lb - tol:
raise OutOfDomainError("Point {0} exceepds lower bound {1}".format(point, self.lb-tol))
bucket_fraction = 2**nbits * (point - self.lb) / (self.ub - self.lb)
index = math.floor(bucket_fraction) if alignleft else math.ceil(bucket_fraction)
# Catch numerical errors when point == self.ub
# if alignleft is True and index >= 2**nbits:
# index = (2**nbits) - 1
return index
def pt2bdd(self, mgr, name, pt: float, nbits: int):
return bv2pred(mgr, name, self.pt2bv(pt, nbits))
def bv2conc(self, bv: BitVector) -> Tuple[float, float]:
nbits = len(bv)
if nbits == 0:
return (self.lb, self.ub)
index = bv2int(bv)
if self.periodic:
index = graytobin(index)
eps = (self.ub - self.lb) / (2**nbits)
left = self.lb + index * eps
right = self.lb + (index+1) * eps
return (left, right)
def pt2box(self, point: float, nbits: int):
return self.bv2conc(self.pt2bv(point, nbits=nbits))
def box2bvs(self, box, nbits: int, innerapprox=False, tol=.0000001):
"""
Returns a list of bitvectors corresponding to a box
Parameters
----------
box (2-tuple): Left and right floating points
nbits (int): Number of bits
innerapprox:
tol: Numerical tolerance
"""
left, right = box
assert tol >= 0 and tol <= 1, "Tolerance is not 0 <= tol <= 1"
eps = (self.ub - self.lb) / (2**nbits)
abs_tol = eps * tol
# TODO: Check for out of bounds error here!
if innerapprox:
# Inner approximations move in the box
left_bv = self.pt2bv(left - abs_tol, nbits, tol=abs_tol)
right_bv = self.pt2bv(right + abs_tol, nbits, tol=abs_tol)
if left_bv == right_bv: # In same box e.g. [.4,.6] <= [0,1]
return []
left_bv = increment_bv(left_bv, 1, self.periodic, saturate=True)
if left_bv == right_bv: # Adjacent boxes [.4,.6] overlaps [0,.5] and [.5,1]
return []
right_bv = increment_bv(right_bv, -1, self.periodic, saturate=True)
else:
left_bv = self.pt2bv(left - abs_tol, nbits=nbits, tol=abs_tol)
right_bv = self.pt2bv(right + abs_tol, nbits=nbits, tol=abs_tol)
if not self.periodic and (left_bv > right_bv):
raise ValueError("{0}: {1}\n{2}: {3}".format(left, left_bv, right, right_bv))
return bv_interval(left_bv, right_bv, self.periodic)
def box2indexwindow(self, box, nbits: int, innerapprox=False, tol=.0000001):
"""
Returns
-------
None or Tuple:
None if the index window is empty and (left, right) index tuple otherwise
"""
left, right = box
assert tol >= 0 and tol <= 1, "Tolerance is not 0 <= tol <= 1"
eps = (self.ub - self.lb) / (2**nbits)
abs_tol = eps * tol
if nbits == 0 and self.periodic:
return None if innerapprox else (0, 0)
if self.periodic:
left = self._wrap(left)
right = self._wrap(right)
# If true, then the XORs flip the usual value
flip = True if self.periodic and right < left else False
if innerapprox:
leftidx = self.pt2index(left, nbits, alignleft=False)
rightidx = self.pt2index(right, nbits, alignleft=True)
# Left and right were in the same bin. Return empty window!
if self.periodic is False and leftidx >= rightidx:
return None
if self.periodic is True and not flip and leftidx >= rightidx:
return None
# Left boundary is near the upper value, right boundary is near lower value
if flip and leftidx == (2**nbits) and rightidx == 0:
return None
else:
leftidx = self.pt2index(left, nbits, alignleft=True)
rightidx = self.pt2index(right, nbits, alignleft=False)
if flip and (leftidx + 1) == rightidx:
return (leftidx + 1) % (2**nbits), (rightidx-1) % (2**nbits)
if flip and leftidx == (2**nbits) and rightidx == 0:
return (0,(2**nbits)-1)
# Weird off by one errors happen.
rightidx = (rightidx - 1) % (2**nbits)
leftidx = leftidx % (2**nbits)
return leftidx, rightidx
def conc2pred(self, mgr, name: str, box, nbits: int, innerapprox=False, tol=.00001):
"""
Concrete box [float, float] to a predicate.
"""
predbox = mgr.false
window = self.box2indexwindow(box, nbits, innerapprox, tol)
if window == None:
return predbox
leftidx, rightidx = window
if self.periodic:
for bv in bvwindowgray(leftidx, rightidx, nbits):
predbox |= bv2pred(mgr, name, bv)
else:
for bv in bvwindow(leftidx, rightidx, nbits):
predbox |= bv2pred(mgr, name, bv)
return predbox
def conc_iter(self, nbits: int):
"""
Generator for iterating over the space with fixed precision
Yields
------
Tuple:
(left, right) box of floats
"""
i = 0
while(i < 2**nbits):
yield self.bv2conc(int2bv(i, nbits))
i += 1
def quantizer(self, nbits: int):
"""
Create a quantizer function for inputs and outputs.
TODO: Figure out how to generate quantizers without circular imports.
Returns
-------
Tuple: (Callable, Callable)
"""
raise NotImplementedError
@dataclass(frozen=True)
class FixedCover(ContinuousCover):
"""
There are some assignments to bits that are not valid for this set
Fixed number of "bins"
Parameters
----------
lb: float
Lower bound
ub: float
Upper bound
bins: int
Number of bins
periodic: bool, default False
If true, cover loops around so lb and ub represent the same point
Examples
--------
FixedCover(2, 10, 4, False) corresponds to the four bins
[2, 4] [4,6] [6,8] [8,10]
"""
bins: int
periodic: bool = False
def __post_init__(self):
assert self.bins > 0
def _wrap(self, point: float):
"""Helper function for periodic intervals."""
if point == self.ub:
return point
width = self.ub - self.lb
return ((point - self.lb) % width) + self.lb
@property
def num_bits(self):
return math.ceil(math.log2(self.bins))
def __repr__(self):
s = "FixedCover({0}, {1}, bins = {2}, periodic={3})".format(self.lb, self.ub, self.bins, self.periodic)
return s
def abs_space(self, mgr, name: str):
"""Return the predicate of the fixed cover abstract space."""
left_bv = int2bv(0, self.num_bits)
right_bv = int2bv(self.bins - 1, self.num_bits)
bvs = bv_interval(left_bv, right_bv)
boxbdd = mgr.false
for i in map(lambda x: bv2pred(mgr, name, x), bvs):
boxbdd |= i
return boxbdd
@property
def binwidth(self):
return (self.ub-self.lb) / self.bins
def dividers(self, nbits: int):
raise NotImplementedError
def pt2box(self, point: float):
return self.bv2conc(self.pt2bv(point))
def pt2bv(self, point: float, tol=0.0):
"""
Map a point to bitvector corresponding to the bin that contains it.
"""
index = self.pt2index(point, tol)
return int2bv(index, self.num_bits)
def pt2index(self, point: float, alignleft=True, tol=0.0) -> int:
if self.periodic:
point = self._wrap(point)
assert point <= self.ub + tol and point >= self.lb - tol
# index = int(((point - self.lb) / (self.ub - self.lb)) * self.bins)
bucket_fraction = ((point - self.lb) / (self.ub - self.lb)) * self.bins
index = math.floor(bucket_fraction) if alignleft else math.ceil(bucket_fraction)
# Catch numerical errors when point == self.ub
# if index >= self.bins:
# index = self.bins - 1
return index
def bv2conc(self, bv: BitVector) -> Tuple[float, float]:
if len(bv) == 0:
return (self.lb, self.ub)
left = self.lb
left += bv2int(bv) * self.binwidth
right = left + self.binwidth
return (left, right)
def box2bvs(self, box, innerapprox=False, tol=.0000001):
left, right = box
eps = self.binwidth
abs_tol = eps * tol
# assert left <= right
left = self.pt2index(left - abs_tol)
right = self.pt2index(right + abs_tol)
if innerapprox:
# Inner approximations move in the box
if left == right or left == right - 1:
return []
if self.periodic and left == self.bins-1 and right == 0:
return []
else:
left = (left + 1) % self.bins
right = (right - 1) % self.bins
left_bv = int2bv(left, self.num_bits)
right_bv = int2bv(right, self.num_bits)
if self.periodic and left > right:
zero_bv = int2bv(0, self.num_bits)
max_bv = int2bv(self.bins-1, self.num_bits)
return itertools.chain(bv_interval(zero_bv, right_bv),
bv_interval(left_bv, max_bv))
else:
return bv_interval(left_bv, right_bv)
def box2indexwindow(self, box, innerapprox=False, tol=.00001):
left, right = box
if self.bins == 1 and self.periodic:
return None if innerapprox else (0, 0)
if self.periodic:
left = self._wrap(left)
right = self._wrap(right)
flip = True if self.periodic and right < left else False
if innerapprox:
leftidx = self.pt2index(left, alignleft=False)
rightidx = self.pt2index(right, alignleft=True)
# Left and right were in the same bin. Return empty window!
if self.periodic is False and leftidx >= rightidx:
return None
if self.periodic is True and not flip and leftidx >= rightidx:
return None
# Left boundary is near the upper value, right boundary is near lower value
if flip and leftidx == self.bins and rightidx == 0:
return None
else:
leftidx = self.pt2index(left, alignleft=True)
rightidx = self.pt2index(right, alignleft=False)
# Contained in same interval but bloating
if flip and (leftidx + 1) == rightidx:
return (leftidx + 1) % self.bins, (rightidx-1) % self.bins
if flip and leftidx == self.bins and rightidx == 0:
return (0, self.bins-1) # Entire interval
rightidx = (rightidx - 1) % self.bins
leftidx = leftidx % self.bins
return leftidx, rightidx
def conc2pred(self, mgr, name: str, box, innerapprox=False, tol=.00001):
predbox = mgr.false
window = self.box2indexwindow(box, innerapprox, tol)
if window is None:
return predbox
leftidx, rightidx = window
if leftidx > rightidx:
for bv in bvwindow(leftidx, self.bins-1, self.num_bits):
predbox |= bv2pred(mgr, name, bv)
for bv in bvwindow(0, rightidx, self.num_bits):
predbox |= bv2pred(mgr, name, bv)
else:
for bv in bvwindow(leftidx, rightidx, self.num_bits):
predbox |= bv2pred(mgr, name, bv)
return predbox
|
ce7ef68e60b7f780ecac42666f8a9f553aa9f10f | fatih-iver/Intro-to-Relational-Databases | /Select Where.py | 275 | 3.6875 | 4 | # The query below finds the names and birthdates of all the gorillas.
#
# Modify it to make it find the names of all the animals that are not
# gorillas and not named 'Max'.
#
QUERY = '''
select name from animals where not (species = 'gorilla' or name = 'Max');
''' |
ede469d19908b74e2228406fbeafe13dde9e47d8 | RobertMusser/Avent-of-Code | /2019/08/one.py | 1,791 | 3.546875 | 4 | # dumps orbits into list
def file_reader(file_name):
with open(file_name) as file_pointer:
while True:
line = file_pointer.read()
if not line:
break
raw_data = line[0:(len(line)-2)] # strips \n\n from end of line
print(raw_data)
return raw_data
# stealing populating method from: https://www.ict.social/python/basics/multidimensional-lists-in-python
def data_processor(raw_data):
counter = 0
clean_data = []
while True:
layer = []
for _ in range(6):
line = []
for _ in range(25):
if counter == len(raw_data):
return clean_data
line.append(int(raw_data[counter]))
counter += 1
layer.append(line)
clean_data.append(layer)
# counts zeros in layers and returns layer with fewest zeros
# would have been simpler and more idiomatic to use .count
def zero_counter(data):
answer = [9999999999, 'ERROR'] # [0]: lowest number of zeros, [1]: layer with that number of zeros
for layer in data:
zeros = 0 # lol
for line in range(6):
for x in layer[line]:
if x == 0:
zeros += 1
if zeros < answer[0]:
answer[0] = zeros
answer[1] = layer
# formats layer conveniently
real_answer = []
for line in answer[1]:
for x in range(25):
real_answer.append(line[x])
return real_answer
# main program
data = file_reader('input.txt') # change file name here!
data = data_processor(data)
layer = zero_counter(data)
# https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item
#print((layer.count(1))*(layer.count(2)))
|
fa65c84253e99d411c94cb6463cac4b24ea9d0e2 | tmu-nlp/100knock2017 | /Shi-ma/chapter01/knock02.py | 147 | 3.5625 | 4 | str1 = 'パトカー'
str2 = 'タクシー'
str_ans = ''
for i in range(len(str1)):
str_ans += str1[i]
str_ans += str2[i]
print(str_ans)
|
4a110205ff6777bf3a8b66b7c48cbd95e0ee0256 | mo-dt/PythonDataScienceCookbook | /ch 2/Recipe_1c.py | 649 | 3.953125 | 4 |
# Alternate ways of creating arrays
# 1. Leverage np.arange to create numpy array
import numpy as np
from Display_Shape import display_shape
created_array = np.arange(1,10,dtype=float)
display_shape(created_array)
# 2. Using np.linspace to create numpy array
created_array = np.linspace(1,10)
display_shape(created_array)
# 3. Create numpy arrays in using np.logspace
created_array = np.logspace(1,10,base=10.0)
display_shape(created_array)
# Specify step size in arange while creating
# an array. This is where it is different
# from np.linspace
created_array = np.arange(1,10,2,dtype=int)
display_shape(created_array)
|
556769551dca2921d2a1df940e62088bf323821b | Stevenzzz1996/MLLCV | /Leetcode/链表/1019. 链表中的下一个更大节点.py | 744 | 3.515625 | 4 | #!usr/bin/env python
# -*- coding:utf-8 -*-
# author: sfhong2020 time:2020/5/8 21:38
# 输入:[1,7,5,1,9,2,5,1]
# 输出:[7,9,9,9,0,5,0,0]
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
nums = []
node = head
while node:
nums.append(node.val)
node = node.next
stack = []
stack_loc = []
res = [0] * len(nums)
for i in range(len(nums)):
while stack and stack[-1] < nums[i]:
res[stack_loc[-1]] = nums[i]
stack.pop()
stack_loc.pop()
stack.append(nums[i])
stack_loc.append(i)
return res
import numpy as np
print(np.random.random((10,2))) |
879760525cbf51add321e1755a23f021acf92a5c | thamtommy/COMP4Coursework | /Implementation/CLI/create_tables.py | 3,099 | 3.921875 | 4 | import sqlite3
def create_table(db_name,table_name,sql):
with sqlite3.connect(db_name) as db:
cursor = db.cursor()
cursor.execute("select name from sqlite_master where name=?",(table_name,))
result = cursor.fetchall()
keep_table = True
if len(result) == 1:
response = input("The table {0} already exists, do you wish to recreate it (y/n): ".format(table_name))
if response == 'y':
keep_table = False
print("The {0} table will be recreated - all existing data will be lost".format(table_name))
cursor.execute("drop table if exists {0}".format(table_name))
db.commit()
else:
print("The existing table was kept")
else:
keep_table = False
if not keep_table:
cursor.execute(sql)
db.commit()
def Type():
sql = """create table ItemType
(ItemTypeID integer,
Type text,
primary key(ItemTypeID))"""
create_table(db_name,"ItemType",sql)
def Booking():
sql = """create table Booking
(BookingID integer,
FirstName text,
LastName text,
TelephoneNo text,
BookingTime text,
BookingDate text,
primary key(BookingID))"""
create_table(db_name,"Booking",sql)
def OrderID():
sql = """create table Orders
(OrderID integer,
TotalDrinkPrice real,
TotalDishPrice real,
TotalPrice real,
primary key(OrderID))"""
create_table(db_name,"Orders",sql)
def MenuID():
sql = """create table Menu
(MenuID integer,
MenuItem text,
ItemPrice real,
ItemTypeID integer,
primary key(MenuID),
foreign key(ItemTypeID) references ItemType(ItemTypeID)
on update cascade on delete cascade)"""
create_table(db_name,"Menu",sql)
def OrderItemID():
sql = """create table Ordered_Items
(OrderItemID integer,
OrderID integer,
MenuID integer,
Quantity integer,
primary key(OrderItemID),
foreign key(OrderID) references Orders(OrderID),
foreign key(MenuID) references Menu(MenuID))"""
create_table(db_name,"Ordered_Items",sql)
def CustomerID():
sql = """create table Customer
(CustomerID integer,
BookingID integer,
OrderID integer,
NumberOfPeople integer,
Date text,
Time text,
TableNumber integer,
primary key(CustomerID),
foreign key(BookingID) references Booking(BookingID),
foreign key(OrderID) references Orders(OrderID))"""
create_table(db_name,"Customer",sql)
if __name__ == "__main__":
db_name = "restaurant.db"
Type()
Booking()
OrderID()
MenuID()
OrderItemID()
CustomerID()
|
977a3354315bbf102ba45d7dd0334d15353202e2 | chicory-gyj/JustDoDo | /pre_test/except.py | 333 | 3.890625 | 4 | #!/usr/bin/python
try:
x=input('enter the first number:')
y=input('enter the second number:')
print x/y
except (ZeroDivisionError,TypeError,NameError),e:
print e
print 'ddd'
try:
x=input('enter the first number:')
y=input('enter the second number:')
print x/y
except:
print 'Someting must be wrong'
|
ec1b00a48b23ee6443ad0780db5589fb93877565 | Da1anna/Data-Structed-and-Algorithm_python | /leetcode/其它题型/递归/第N个泰波那契树数.py | 1,203 | 3.703125 | 4 | '''
泰波那契序列 Tn 定义如下:
T0 = 0, T1 = 1, T2 = 1, 且在 n >= 0 的条件下 Tn+3 = Tn + Tn+1 + Tn+2
给你整数 n,请返回第 n 个泰波那契数 Tn 的值。
示例 1:
输入:n = 4
输出:4
解释:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
示例 2:
输入:n = 25
输出:1389537
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
#记忆化递归
def tribonacci_1(self, n: int) -> int:
T = [0 for _ in range(n+1)]
T[1],T[2] = 1,1
def helper(n,T) -> int:
if n == 0:
return 0
if T[n]:
return T[n]
T[n] = helper(n-3,T) + helper(n-2,T) + helper(n-1,T)
return T[n]
return helper(n,T)
#自底向上动态规划
def tribonacci_2(self, n: int) -> int:
if n < 3:
return 1 if n else 0
x,y,z = 0,1,1
for i in range(3,n+1):
x,y,z = y,z,x+y+z
return z
#测试
res = Solution().tribonacci_2(25)
print(res) |
5881b602039ea8c20e829f13bf024fd66d37a63d | dastous/HackerRank | /The HackerRank Interview Preparation Kit/Search/03. Pairs | 744 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the pairs function below.
def pairs(k, arr):
count =0
# Sort array elements
arr.sort()
l =0
r=0
while r<n:
if arr[r]-arr[l]==k:
count+=1
l+=1
r+=1
# arr[r] - arr[l] < sum
elif arr[r]-arr[l]>k:
l+=1
else:
r+=1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nk = input().split()
n = int(nk[0])
k = int(nk[1])
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
fptr.write(str(result) + '\n')
fptr.close()
|
f615243921d1285495ef15e2625b921a0b92ad28 | JJong0416/Algorithm | /Programmers/2Level/StackQueue/Printer/minki.py | 580 | 3.609375 | 4 | def solution(priorities, location):
answer = 0
printCount = 0
while len(priorities) != 0:
first_item = priorities.pop(0)
check = False
for item in priorities:
if item > first_item:
check = True
if check:
priorities.append(first_item)
if location == 0:
location += len(priorities)
else:
printCount += 1;
if location == 0:
answer = printCount
break
location -= 1;
return answer |
1a2bafe0b9a1c16cf521fd25077cc43aa6ca9103 | Vidhyalakshmi-sekar/LetsUpgrade_PythonAssignment | /primeNumber.py | 442 | 4.15625 | 4 | # getting number as input
input_number = int(input('Please enter a number: '))
if input_number > 1:
for num in range(2, input_number):
if input_number % num == 0:
print('The number {} is not a prime number'.format(input_number))
break
else:
print('The number {} is a prime number'.format(input_number))
else:
print('The number {} is not a prime number'.format(input_number))
|
0034a3442023cbae28e4cdd84f9389cda61b9730 | KedraMichal/python-lab | /lab5/shape_classes.py | 3,173 | 3.8125 | 4 | def is_number(number):
try:
float(number)
return True
except:
return False
class Vector_2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector_2D(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
return self + other
def __str__(self):
return "[" + str(self.x) + ", " + str(self.y) + "]"
class Shape:
color = ["black", "white", "red", "green", "blue", "cyan", "magenta", "yellow"]
def __init__(self, name, *size):
self.name = name
self.spot = Vector_2D(0, 0)
self.angle = 0
self.size = [float(i) for i in size]
self.border_color = "black"
self.background_color = "white"
def set_background_color(self, color):
if color in Shape.color:
self.background_color = color
else:
print("Color is not available")
def set_border_color(self, color):
if color in Shape.color:
self.border_color = color
else:
print("Color is not available")
def move(self, x, y):
if is_number(x) and is_number(y):
self.spot += Vector_2D(x, y)
def rotate(self, degrees):
if is_number(degrees):
self.angle += degrees
while self.angle > 360:
self.angle -= 360
else:
print('Degrees must be a float')
def scale(self, ratio):
if is_number(ratio):
if ratio != 0:
self.size = [i * ratio for i in self.size]
else:
print("Ratio cant be 0!")
else:
print('Ratio must be a float')
def __str__(self):
return "name: {}, border color: {}, background color: {}, angle: {} degrees, spot: {}, size: {}".format(self.name, self.border_color,
self.background_color, self.angle, self.spot, self.size)
class Circle(Shape):
def __init__(self, name, *size):
super().__init__(name, *size)
if len(size) != 1:
raise ValueError
def __str__(self):
return "Figure: circle, " + super().__str__()
class Square(Shape):
def __init__(self, name, *size):
super().__init__(name, *size)
if len(size) != 1:
raise ValueError
def __str__(self):
return "Figure: square, " + super().__str__()
class Triangle(Shape):
def __init__(self, name, *size):
super().__init__(name, *size)
if len(size) != 3:
raise ValueError
if self.size[0] + self.size[1] <= self.size[2] or self.size[1] + self.size[2] <= self.size[0] or self.size[0] + self.size[2] <= self.size[1]:
raise ValueError
def __str__(self):
return "Figure: triangle, " + super().__str__()
class Rectangle(Shape):
def __init__(self, name, *size):
super().__init__(name, *size)
if len(size) != 2:
raise ValueError
def __str__(self):
return "Figure: rectangle, " + super().__str__()
|
6f6d772b5e18173f88b051de5b8121aa37661f4a | fruitynoodles/Python_Examples | /numpy_matplotlib/curvefit.py | 458 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as pl
#set up noisy data set based on quadratic
datax = np.arange(0,10,0.5)
datay =(0.8-0.4*np.random.rand(np.size(datax)))*datax**2
# generate fitted polynomial
pfit = np.polyfit(datax,datay,3)
#generate polynomial x-y data
fitx = np.linspace(np.min(datax),np.max(datax),100)
fity = np.polyval(pfit,fitx)
#plot everything
pl.plot(datax,datay,'r.')
pl.plot(fitx,fity,'g-')
pl.legend(["data","polyfit"])
pl.show()
|
b0131a522cf297b9dc92b9080e16fa22d6f2e3e3 | dbridenbeck/recordexpungPDX | /src/backend/expungeservice/database/database.py | 2,645 | 3.53125 | 4 | """Database module"""
import logging
import psycopg2
import psycopg2.extras
import os
class Database(object):
"""Database connection class.
Example usage:
import os
password = os.environ['POSTGRES_PASSWORD']
from expungeservice.database import database
# Get a connection.
db = database.Database(host='db', port='5432', name='record_expunge',
username='postgres', password=password)
# Run a query.
query = 'SELECT * FROM users;'
db.cursor.execute(query, ())
# Get the results.
rows = db.cursor.fetchall()
# Examine the results.
print(rows)
[row._asdict() for row in rows]
"""
def __init__(self, host, port, name, username, password):
"""Opens a connection to the database."""
self._host = host
self._port = port
self._name = name
self._username = username
self._conn = None
self._cursor = None
try:
self._conn = psycopg2.connect(host=host, port=port, dbname=name, user=username, password=password)
self._cursor = self._conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
self._cursor.execute("""SET search_path TO {},public""".format(self._name))
except psycopg2.OperationalError as e:
logging.error(e)
raise e
psycopg2.extras.register_uuid()
@property
def host(self):
"""Returns database host."""
return self._host
@property
def port(self):
"""Returns database port."""
return self._port
@property
def name(self):
"""Returns database name."""
return self._name
@property
def username(self):
"""Returns database username."""
return self._username
@property
def connection(self):
"""Returns database connection."""
return self._conn
@property
def cursor(self):
"""Returns connection cursor."""
return self._cursor
def close_connection(self):
"""Closes the connection."""
if self._cursor is not None:
self._cursor.close()
if self._conn is not None:
self._conn.close()
def __str__(self):
s = """Host: {}
Port: {}
Name: {}
Username: {}""".format(
self.host, self.port, self.name, self.username
)
return s
def get_database():
host = os.environ["PGHOST"]
port = int(os.environ["PGPORT"])
name = os.environ["PGDATABASE"]
username = os.environ["PGUSER"]
password = os.environ["PGPASSWORD"]
return Database(host=host, port=port, name=name, username=username, password=password)
|
7d526de5d58f3be976dee9ec24b39fa85fb03ac0 | kvombatkere/Enigma-Machine | /Rotorset.py | 7,970 | 3.515625 | 4 | #Karan Vombatkere
#German Enigma Machine
#October 2017
from string import *
import numpy as np
Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#function to create a dictionary with letters and their indices
#Use this to return the index of a letter (a = 0, .., z = 25)
def genDictionary():
letter_index_pairs = []
for indx, char in enumerate(Letters):
letter_index_pairs.append([char, indx])
Indx_Dict = dict(letter_index_pairs)
print("Generated Letter Dictionary!")
return Indx_Dict
#Call the function to create a global dictionary
Char_Indices = genDictionary()
#Enigma Rotor Configurations
Rotor1 = ['E','K','M','F','L','G','D','Q','V','Z','N','T','O','W','Y','H','X','U','S','P','A','I','B','R','C','J']
Rotor2 = ['A','J','D','K','S','I','R','U','X','B','L','H','W','T','M','C','Q','G','Z','N','P','Y','F','V','O','E']
Rotor3 = ['B','D','F','H','J','L','C','P','R','T','X','V','Z','N','Y','E','I','W','G','A','K','M','U','S','Q','O']
Rotor4 = ['E','S','O','V','P','Z','J','A','Y','Q','U','I','R','H','X','L','N','F','T','G','K','D','C','M','W','B']
Rotor5 = ['V','Z','B','R','G','I','T','Y','U','P','S','D','N','H','L','X','A','W','M','J','Q','O','F','E','C','K']
Rotor6 = ['J','P','G','V','O','U','M','F','Y','Q','B','E','N','H','Z','R','D','K','A','S','X','L','I','C','T','W']
Rotor7 = ['N','Z','J','H','G','R','C','X','M','Y','S','W','B','O','U','F','A','I','V','L','P','E','K','Q','D','T']
Rotor8 = ['F','K','Q','H','T','L','X','O','C','B','J','S','P','D','Z','R','A','M','E','W','N','I','U','Y','G','V']
#Set of All Rotors
Enigma_Rotors = [Rotor1, Rotor2, Rotor3, Rotor4, Rotor5, Rotor6, Rotor7, Rotor8]
#Class to implement Rotors
#Rotor is Initialized with a list of letters as given and can rotate the pointer to keep track of the position
class Rotor:
'Implement a Rotor for the Enigma Machine'
rotorPos = 0
def __init__(self, rotorPermutation, pos):
self.rotorPermutation = list(rotorPermutation)
self.rotatebyN(pos)
self.rotorPos = pos
self.origPos = 0
self.rotateFlag = False #All rotors are configured to NOT rotate initially
#print("Rotor Configuration:\n", self.rotorPermutation)
#Function to rotate the rotor by a specified initial rotation, n
def rotatebyN(self, n):
for i in range(n):
self.rotate()
#Function to rotate the rotor once
def rotate(self):
self.rotorPos += 1 #keep track of positions
self.rotorPos = self.rotorPos % 26
#shift all elements in rotorPermutation one space to the right
rotatedRotor = []
for i in range(len(self.rotorPermutation)):
rotatedRotor.append(self.rotorPermutation[(i-1)%26])
#increment each character by 1
self.rotorPermutation = [Letters[((Char_Indices[ch]) +1)%26] for indx, ch in enumerate(list(rotatedRotor))]
#print(self.rotorPermutation)
#display the Details of the rotor and its current location
def displayRotor(self):
print("Rotor Configuration:", self.rotorPermutation)
print("Rotor Position:", self.rotorPos, "\nRotor Original Position:", self.origPos)
#take a character as input and return its rotated ciphertext character
#rotate rotor after encrypting automatically
def outputRotated(self, charX):
#Rotate the rotor if the flag is set to true
if(self.rotateFlag):
self.rotate()
X_index = Char_Indices[charX]
rotatedChar = self.rotorPermutation[X_index]
return rotatedChar
def outputRotatedRev(self, charX):
X_index = getIndex(charX, self.rotorPermutation)
rotatedCharRev = Letters[X_index]
return rotatedCharRev
#Class to Implement a Set of Rotors along with the reflector
#Customized to build a 3-Rotor Set and Fastest moving rotor is closest to Plugboard
#Both the parameters in the init uniquely identify the rotor element of the key
class RotorSet(Rotor, Reflector):
'Implements a Rotor Set for a 3-Rotor Enigma Machine'
#useRotors is a list that has the index of the rotor to be used from Enigma_Rotors
#(Rotor1 = 0, Rotor2 = 1, ..., Rotor8 = 7)
#rotorPositions is list with the initial position of the rotors being used
#both the above lists are in order of closest to plugboard to furthest in terms of their rotor set position
def __init__(self, useRotors, rotorPositions, reflectNum): #Instantiates the rotor set
self.R1 = Rotor(Enigma_Rotors[useRotors[0]], rotorPositions[0]) #Rotor R1 to be placed nearest the plugboard
self.R2 = Rotor(Enigma_Rotors[useRotors[1]], rotorPositions[1])
self.R3 = Rotor(Enigma_Rotors[useRotors[2]], rotorPositions[2])
#Instantiate correct reflector
self.Reflector1 = Reflector(reflectNum)
print("\nInitialized Enigma 3-Rotor Set with Plugboard Successfully")
#self.R1.displayRotor()
#self.R2.displayRotor()
#self.R3.displayRotor()
print("-------------------------------------------------------------------------------------------------------")
#funtion to display the state of the rotor positions
def displayRotorState(self):
print("Current RotorState:", self.R1.rotorPos, self.R2.rotorPos, self.R3.rotorPos)
#Encrypt text as per the rotor settings and spin rotors as per the gearing
#Each rotor takes the output of the previous rotor as its input
#The reflector and backward path has also been accomodated
def encryptText(self, textArray):
rotorSet_out = []
#Only set rotate flag for R1=True since it must rotate every turn
self.R1.rotateFlag = True
#Traverse the array with characters once
for indx, letter in enumerate(textArray):
#self.displayRotorState() #Check Rotorstate
#R1 always encrypts the letter and rotates
R1out = self.R1.outputRotated(letter)
'''
#Test just one rotor + reflector
refOut = self.Reflector1.outputReflected(R1out)
R1outrev = self.R1.outputRotatedRev(refOut)
print("Letter Path:", letter, " ->", R1out, " ->", refOut, " ->"
, R1outrev)
'''
#R2 is configured to rotate every time R1 completes a cycle, except first index
if(self.R1.rotorPos == ((self.R1.origPos)%26) and indx != 0 ):
self.R2.rotateFlag = True
R2out = self.R2.outputRotated(R1out)
#R3 is configured to rotate every time R3 completes a cycle, except first cycle
if(self.R2.rotorPos == ((self.R2.origPos)%26) and self.R2.rotateFlag and indx > 26):
self.R3.rotateFlag = True
R3out = self.R3.outputRotated(R2out)
#Pass through reflector
reflectedOut = self.Reflector1.outputReflected(R3out)
#Pass through R3 again
R3out_rev = self.R3.outputRotatedRev(reflectedOut)
self.R3.rotateFlag = False #Rotate flag must stay false as default
#Pass through R2 again
R2out_rev = self.R2.outputRotatedRev(R3out_rev)
self.R2.rotateFlag = False #Rotate flag must be set to false as default
R1out_rev = self.R1.outputRotatedRev(R2out_rev)
#print path of letter:
#print("Letter Path:", letter, " ->", R1out, " ->", R2out, " ->", R3out, " ->", reflectedOut, " ->"
#, R3out_rev, " ->", R2out_rev, " ->", R1out_rev)
#The character stored in R1out_rev is the final result of rotors + reflector
rotorSet_out.append(R1out_rev)
return rotorSet_out
|
9758932f9f5ff8b7fd148cd62983aa083b14e434 | mihaivalentistoica/Python-Fundamentals | /Curs4/Exercitii_singuri.py | 1,805 | 3.578125 | 4 | '''
1. Creati clasa Animal cu 2 atribute private(mangled): nume si varsta. La initiere se dau valori default.
Sa se creeze getteri si setteri pentru ambele campuri.
Creati cel putin 2 obiecte si testati proprietatile create.
'''
class Animal:
def __init__(self):
self.__nume = None
self.__varsta = None
@property
def nume(self):
return self.__nume
@nume.setter
def nume(self, nume_in):
self.__nume = nume_in
def get_varsta(self):
return self.__varsta
def set_varsta(self, varsta_in):
self.__varsta = varsta_in
pisica = Animal() # cream cele 2 obiecte pisca si animal
caine = Animal()
pisica.nume = 'Pisica'
pisica.set_varsta(0.1)
caine.nume = 'Caine'
caine.set_varsta(3)
print(f'Animalul {pisica.nume} are o varsta de {pisica.get_varsta()}')
print(f'Animalul {caine.nume} are o varsta de {caine.get_varsta()}')
'''
2. Creati o clasa caine cu 2 atribute statice publice si 2 atribute de instanta protejate.
Faceti modificarea variabilelor din exteriorul clasei pentru 2 instante.
'''
'''
3. Creati o clasa Animal cu 1 atribut public nume si 1 atribut privat varsta.
Creati getteri si setteri pentru variabila privata.
Sa se verifice in cadrul setter-ului daca valoarea transmisa este pozitiva.
Daca valoarea nu este corecta, se afiseaza un mesaj corespunzator si nu se efectueaza atribuirea.
Sa se creeze 1 obiect(instanta) de tip animal si inca unul ce este o copie a primului( prin referinta).
Sa se modifice campurile celui de-al doilea obiect si sa se verifice modificarile aparute in cadrul ambelor obiecte create.
Sa se repete procedeul cu o alta copie a obiectului, de aceeasta data utilizandu-se 'deepcopy'.
'''
class Animal:
def __init__(self):
self.__nume = None
self.__varsta = None
|
c9ac60eeeb2e14534883034e6e6a7d6e8ad5235a | amandashotts/Pig-Latin-Translator | /piglatintranslator.py | 370 | 3.796875 | 4 | # A fun pig-latin translator.
pyg = 'ay'
original = input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = ('%s%s%s' % (word, first, pyg))
new_word = new_word[1: len(new_word)]
print(new_word)
else:
print('Error! Try again without spaces, numbers, or characters.') |
51d1dc5ddb4dd6e324206c6d39f7fd0b7f9c916d | cpeixin/leetcode-bbbbrent | /queen/circular_queue.py | 842 | 3.921875 | 4 | class circular_queue():
def __init__(self, size):
self.array = []
self.head = 0
self.tail = 0
self.size = size
def enqueue(self, value):
"""入队判满"""
if (self.tail + 1) % self.size == self.head:
return False
self.array.append(value)
"""入队,尾节点下标变化"""
self.tail = (self.tail + 1) % self.size
return True
def dequeue(self):
"""出队判空"""
if self.head != self.tail:
item = self.array[self.head]
"""出队,头节点下标变化"""
self.head = (self.head + 1) % self.size
return item
if __name__ == '__main__':
q = circular_queue(5)
for i in range(5):
q.enqueue(i)
q.dequeue()
q.dequeue()
q.enqueue(1)
print(q) |
04db0b6af5dc527281784edc380602b0b3fa23cb | Upasna4/Training | /op.py | 688 | 3.78125 | 4 | import os
print(os.getcwd()) #current working dir
path=os.getcwd() #gives current working dir
print(path)
loc=__file__
print(loc) #to check puri location
print(os.getcwd())
os.chdir("C:\\Users\\hp\\desktop") #to change loc of rest of the files which will be made later(first method using double backslash)
print(os.getcwd())
os.chdir("C:/Users/hp/desktop") #second method using frontslash
print(os.getcwd())
path=os.getcwd()
os.chdir("C:/Users/hp/desktop")
print(os.getcwd())
os.chdir(path) #third method if we have chngd loc n we want our loc back we store our orig loc in a var then we pas that var we get orig loc
print(os.getcwd())
|
c33612d749548f5bb305f301ea52624c57dafda4 | mayelespino/code | /LEARN/python/sorting/my-merge-sort-01.py | 727 | 3.640625 | 4 | from random import randint
listOfRandomInts = []
for x in xrange(1,10):
listOfRandomInts.append(randint(0,99))
def mergeSort(listToSort):
if len(listToSort) <= 1:
return listToSort
halfPoint = len(listToSort) / 2
left = mergeSort(listToSort[:halfPoint])
right = mergeSort(listToSort[halfPoint:])
result = []
while len(left) > 0 and len(right) > 0:
if left[0] > right[0]:
result.append(right.pop(0))
else:
result.append(left.pop(0))
if len(left) > 0:
result.extend(mergeSort(left))
else:
result.extend(mergeSort(right))
return result
print listOfRandomInts
sortedList = mergeSort(listOfRandomInts)
print sortedList |
63077f16d214292959d862163c4b07b8449cb9f4 | jerkuebler/Pathfinding | /main.py | 764 | 3.765625 | 4 | # Meant to demonstrate a simple pathfinding algorithm with recursion
import pygame
import grid
pygame.init()
pygame.display.set_caption('Pathfinding')
grid = grid.Grid()
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
grid.screen.fill(BLACK)
clock = pygame.time.Clock()
done = False
start_node = grid.nodes[0]
visited_nodes = [grid.nodes[0]]
while not done:
pygame.display.update()
for node in grid.nodes:
node.update()
for path in grid.paths:
path.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if len(visited_nodes) < len(grid.nodes):
start_node, visited_nodes = grid.traverse(start_node, visited_nodes)
clock.tick(1)
|
513d2ef278bfc9a41f945a64f93dda78b040c61b | cssd2019/mutationplanner | /mutationplanner/read_fasta.py | 526 | 3.515625 | 4 | from Bio import SeqIO, Seq
def read_fasta(file_path):
""" Reads a fasta file and converts it into a dictionary
:param file_path (string): path of the fasta file to read
:return: a dictionary of fasta records
"""
seq_dict = {}
for sequence in SeqIO.parse(file_path, "fasta"): #
s = str(sequence.seq)
seq_dict[sequence.id] = s
return seq_dict
if __name__ == "__main__":
fasta_file_path = "./data/test.fasta"
fasta_dict = read_fasta(fasta_file_path)
print(fasta_dict)
|
fd05729b587e18a1d80b8491cb5a47a07a645e14 | viniciusbonito/CeV-Python-Exercicios | /Mundo 1/ex017.py | 374 | 3.96875 | 4 | #crie um programa que peça os cumprimentos dos catetos adjacente e oposto de um triângulo retângulo e calcule
#a hipotenusa
import math
oposto = float(input('Informe o comprimento do cateto oposto: '))
adjacente = float(input('Informe o comprimento do cateto adjacente: '))
hipotenusa = math.hypot(oposto, adjacente)
print('A hipotenusa é {:.2f}'.format(hipotenusa))
|
80556910787d27ff185989190cfc3b5cdd51a7f9 | Alekseevnaa11/practicum_1 | /52.py | 1,003 | 3.765625 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: 52.py
Автор: 2020 © Д.П. Юткина, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 04/12/2020
Дата последней модификации: 04/12/2020
Описание: Решение задачи 52 практикума № 1
#версия Python: 3.8
"""
"""
Заданы M строк символов, которые вводятся с клавиатуры.
Из заданных строк, каждая из которых представляет одно слово,
составить одну длинную строку, разделяя слова пробелами.
"""
M = int(input("Введите количество строк: "))
x = []
for i in range(0, M):
print("Введите строку:", end=' ')
x.append(input())
print(' '.join(x))
|
f65b20df3c85f9a7aea170a4375a06b542c2725f | aniGevorgyan/python | /sixth.py | 1,053 | 3.671875 | 4 | #! usr/bin/python3.6
# 1.
number = int(input("Type number: "))
word = input("Type word: ")
list = []
for i in range(number):
s = input("Sentence here: ")
list.append("%d : %d" %(i, s.count(word)))
print("\n".join(list))
# 2.
number2 = int(input("Type number: "))
list2 = []
for i in range(number2):
s = input("Sentence here: ")
list2.append(s)
list2 = list2[::-1]
print("\n".join(list2))
#3.
sentence = "Mary and Samantha arrived at the bus station early but waited until noon for the bus."
list = sentence.split()
w = input("Word here: ")
while(w != 'End'):
if(w.isdigit()):
print(list[int(w)])
w = input("Word here: ")
else: break
print("Finish")
#4.
sentence = "Mary and Samantha arrived at the bus station early but waited until noon for the bus."
list = sentence.split()
w = input("Word here: ")
while(w != 'End'):
if(w.isdigit()):
if('a' in list[int(w)]):
print("Yes")
else:
print("No")
w = input("Word here: ")
else: break
print("Finish") |
5341b02d3dda6deefda46454bba47ddfa51a40d9 | jpardike/lists_ranges | /main.py | 2,586 | 4.25 | 4 | # --------------------- LISTS & RANGES
# Lists are mutable (changeable)
# Lists can contain similar types of data
fruits = ['apple', 'banana', 'pear', 'grapes']
# Get Length
# fruits.length
# print(len(fruits))
# Accessing Elements
first_fruit = fruits[0]
last_fruit = fruits[-2]
# Adding Elements
fruits.insert(len(fruits), 'peach')
fruits.append('coconut')
fruits.extend(['nectarine', 'orange'])
# Change Values
# fruits[0] = 'apple'
# Deleting Values
# del fruits[0] # removes index position, does not return a value
# fruits.pop(1) # pop will take an optional index
# fruits.remove('peach') # remove wil remove the first element that matches the argument passed
# fruits.clear()
# print(fruits)
# ----------------- ITERATION
# for fruit in fruits:
# print(fruit)
# for i, fruit in enumerate(fruits):
# print(f"{i} - fruit")
# -------------- COMPREHENSIONS
nums = [1, 2, 3, 4, 5]
doubled_nums = []
for num in nums:
doubled_nums.append(num * 2)
# Doubled Nums Comprehension
doubled_nums_comp = [num *2 for num in nums]
even_nums = []
for num in nums:
if num % 2 == 0:
even_nums.append(num)
# Even Nums Comprehension
even_nums_comp = [num for num in nums if num % 2 ==0]
# print(even_nums_comp)
words = ['what', 'hump']
uppercase_words_comp = [word.upper() for word in words]
# print(uppercase_words_comp)
# -------------------- TUPLES
# Tuples are immutable (cannot change values)
colors = ('red', 'blue', 'purple')
colors2 = 'green', 'orange', 'yellow'
colors3 = 'polka-dot', # use a hanging comma to create a single item tuple
# blue = colors[1] # unpacking values
red, blue, purple = colors
# colors[1] = 'Blue' # Tuples do not support assignment or reassignment
# The len() method also works on tuples
# print(type(colors3))
# -------------- Iterating on Tuples
# for color in colors:
# print(color)
# print(colors.index('blue'))
# ----------------------- RANGES
# Range returns a list of integers from start val to stop val, non-inclusive of stop val
# for number in range(11, 0, -1):
# print(number)
# const people = 'john'
# const people2 = people
# people = ['kevin']
# Memory
# | people | 00x234 | 00x234 |
# | people2 | 00x234 | 00x234 |
# HEAP
# | people | 00x234 | 00x234 |
# const people2 = people
# ------------------------ SLICES
# Slice takes start and stop vals (non-inclusive)
name = 'Alexandria'
copy = name[:]
nickname = name[0:4]
name = 'bob'
first_two_colors = colors[0:2]
last_two_colors = colors[1:3]
# copy/clone
colors_copy = colors[:]
print(colors_copy) |
7dcf2e243d29ccb080e57088fb637dea20ea9850 | sinhdev/python-demo | /basic-programming/loops/for-loop.py | 319 | 4.53125 | 5 | #!/usr/bin/python
for letter in 'Python': # First Example
print('Current Letter :' + letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print('Current fruit: ' + fruit)
for index in range(len(fruits)):
print('Current fruit :' + fruits[index])
print("Good bye!") |
1009bade5f94183511a64795a317e4edf44762d8 | warisamin25/Game | /Games.py | 2,068 | 3.90625 | 4 | import Mood
from sys import exit
from random import randint
def main():
while True:
#input1 = input("> What's your current mood? (Happy/Angry/Stressed/Sad): " ).lower()
if set_mood == "happy":
setting = Mood.Happy()
break
elif mood == "angry":
setting = Mood.Angry()
break
elif mood == "stressed":
setting = Mood.Stressed()
break
elif mood == "sad":
setting = Mood.Sad()
break
#else:
#nput1 = print ("Invalid input! Please enter Happy, Angry, Stressed or Sad only!\n> ")
def calc(setting):
return setting.stability * (setting.HMULT/setting.SMULT) * 100/randint(5, 10)
def RPG():
if mood == "happy":
print ("100% stability achieved!")
else:
print(f"Your mental stability is: {round(calc(mood), 2)}%.")
def FPS():
if mood == "angry":
print ("100% stability achieved!")
else:
print(f"Your mental stability is: {round(calc(mood), 2)}%.")
def PnC():
if mood == "stressed":
print ("100% stability achieved!")
else:
print(f"Your mental stability is: {round(calc(mood), 2)}%.")
def Sim():
if mood == "sad":
print ("100% stability achieved!")
else:
print(f"Your mental stability is: {round(calc(mood), 2)}%.")
while True:
#input2 = input("> What game do you want to play?\nRPG/FPS/PnC/Sim?: ").lower()
if set_games == "rpg":
RPG()
break
elif games == "fps":
FPS()
break
elif games == "pnc":
PnC()
break
elif games == "sim":
Sim()
break
#else:
#input2 = print("Please choose from the option!")
main() |
10f2cc80d44941a24f64b4ad63e7cebe3bea7d99 | fuburning/lstm_intent | /tensorgou/utils/txtutils.py | 1,291 | 3.53125 | 4 | """
"""
import re, string
import unicodedata
def cleanline(txt):
return txt.strip('\n')
def to_lowercase(text):
return text.lower().strip()
def remove_all_punctuations(text):
regex = re.compile('[%s]' % re.escape(string.punctuation))
text = regex.sub(' ', text).strip()
return " ".join(text.split()).strip()
def remove_basic_punctuations(text):
text = text.replace('.','')
text = text.replace(',','')
text = text.replace('?','')
text = text.replace('!','')
text = text.replace(';','')
text = text.replace('-',' ')
return text.strip()
def remove_spaced_single_punctuations(text):
wds = text.split()
return " ".join([w for w in wds if len(w)>1 or re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', w).strip() != '']).strip()
def space_out_punctuations(text):
return re.sub(r"([\w\s]+|[^\w\s]+)\s*", r"\1 ", text).strip()
def remove_numbers(text):
return re.sub(r' \d+ ',' ', text).strip()
def replace_numbers(text):
return re.sub(r' \d+ ',' *#NUMBER#* ', text).strip()
def replace_accents(text):
text = text.decode('utf-8')
text = unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
text = text.replace('-LRB-','(')
text = text.replace('-RRB-',')')
return text.strip() |
d0da81523e9ee782e803d9e8b9368865bd87e8de | muadz-mr/python-censor-program | /main.py | 318 | 3.78125 | 4 | watchWords = ["apple", "head", "example", "bend"]
message = input("What do you want to say? : ")
for word in watchWords:
censoredWord = "*"*len(word)
if word in message:
msgWord = word
approvedMessage = message.replace(msgWord, censoredWord)
message = approvedMessage
print(message) |
437ecd0a67cdc1dca2da6e6b32f95aafa585585a | priyapriyam/loop_question | /ankita.py | 62 | 3.578125 | 4 | list=[4,9,8,7,6,3,3]
i=1
while i<len(list):
i=i+1
print(i) |
08e707d07ba2775c5796412cd6603096cacbb310 | osnaldy/Python-StartingOut | /chapter13/g_c_d.py | 235 | 3.765625 | 4 | def main():
num1 = int(raw_input("Enter the first number: "))
num2 = int(raw_input("Enter the second number: "))
print gdc(num1, num2)
def gdc(x, y):
if x % y == 0:
return y
return gdc(x, x % y)
main() |
b647da93a9e0d9db30453d8eaaff4c5f9fdee6dc | pk026/competative_pragramming | /Flattening_a_Linked_List.py | 1,254 | 4.3125 | 4 | # Flattening a Linked List
# Given a linked list where every node represents a linked list and contains two pointers of its type:
# (i) Pointer to next node in the main list (we call it ‘right’ pointer in below code)
# (ii) Pointer to a linked list where this node is head (we call it ‘down’ pointer in below code).
# All linked lists are sorted. See the following example
class Node:
def __init__(self, data):
self.data = data
self.right = None
self.down = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data, v_head):
new_node = Node(data)
new_node.right = self.head
self.head = new_node
new_node.down = v_head
v_head = new_node
def merge_node(node_a, node_b):
if node_a is None:
return node_b
if node_b is None:
return node_a
result = Node()
if node_a.data < node_b.data:
result = node_a
result.down = merge_node(node_a.down, node_b)
else:
result = node_b
result.down = merge_node(node_a, node_b.down)
return result
def flatten(root):
if (root is None) or (root.right is None):
return root
return merge_node(root, flatten(root.right)) |
515dfe102a97b9c68ed07b3a7b8bf81c1a39bc02 | Arina-prog/Python_homeworks | /homework_9/task_9_1.py | 2,603 | 4.1875 | 4 | # *Create a class for representing book with some attributes (author, owner, pages, price, current page)
# # and behavior (change owner, increase price, change current page), create several books and perform operations on them
# * Создайте класс для представления книги с некоторыми атрибутами (автор, владелец, страницы, цена, текущая страница) и
# поведением (сменить владельца, увеличить цену, изменить текущую страницу), создать несколько книг и выполнить с ними
# операции
class Book:
"""this is class of Book"""
def __init__(self, author, ower, page, price, new_page):
self.author = author
self.ower = ower
self.page = page
self.price = price
self.new_page = new_page
def change_ower(self, ower):
self.ower = ower
def increase_price(self, price=125):
self.price += price
def current_page(self, page=25):
if self.new_page + page < self.page:
self.new_page += page
else:
self.new_page = "<<end book>>"
return self.new_page
def show(self):
print("Book author is " + self.author, "\n", "Book ower is " + self.ower, "\n", "Book page " + str(self.page),
"\n", "Book price " + str(self.price), "\n", "Book current page " + str(self.new_page), "\n")
# ##############class book t ########
t = Book("sheqspir", "Dianna", 468, 7500, 365)
t.show()
print("_______change ower___________")
t.change_ower("Narek")
t.show()
print("_________increase price_____________")
t.increase_price(600)
t.show()
print("________courrent_page__________")
t.current_page(350)
t.show()
print("/////////////////")
################ book1###########
book1 = Book("M.Gosh", "Anna", 865, 6980, 140)
book1.show()
print("_______change ower____book1_______")
book1.change_ower("Inga")
book1.show()
print("_________increase price_____book1________")
book1.increase_price(1200)
book1.show()
print("________courrent_page____book1______")
book1.current_page(126)
book1.show()
print("/////////////////")
################ book2###########
book2 = Book("A. Dyuma", "Nvard", 755, 10000, 36)
book2.show()
print("_______change ower____book2_______")
book2.change_ower("Lena")
book2.show()
print("_________increase price_____book2________")
book2.increase_price(500)
book2.show()
print("________courrent_page____book2______")
book2.current_page(110)
book2.show()
print("/////////////////")
|
a4784c49e1ef5e7ba0ec24154650e7c3bbb9f678 | dandoan1/CIS-2348-python | /Homework 2/7.25.py | 1,792 | 3.84375 | 4 | # Dan Doan 1986920
# first function will return the amount of times each of the variable was used.
def exact_change(user_total):
remaining = user_total
dol = 0
qua = 0
dim = 0
nic = 0
pen = 0
while remaining > 100 or remaining == 100:
remaining -= 100
dol += 1
while remaining > 25 or remaining == 25:
remaining -= 25
qua += 1
while remaining > 10 or remaining == 10:
remaining -= 10
dim += 1
while remaining > 5 or remaining == 5:
remaining -= 5
nic += 1
while remaining > 1 or remaining == 1:
remaining -= 1
pen += 1
return dol, qua, dim, nic, pen
# the rest checks for if there is no change or if it is more than 1 in the variables then it will add the plural version
# of the word then print them out
if __name__ == "__main__":
input_val = int(input())
if input_val == 0 or input_val < 0:
print("no change")
num_dollars, num_quarters, num_dimes, num_nickels, num_pennies = exact_change(input_val)
if num_dollars == 0:
pass
elif num_dollars == 1:
print(num_dollars, "dollar")
else:
print(num_dollars, "dollars")
if num_quarters == 0:
pass
elif num_quarters == 1:
print(num_quarters, "quarter")
else:
print(num_quarters, "quarters")
if num_dimes == 0:
pass
elif num_dimes == 1:
print(num_dimes, "dime")
else:
print(num_dimes, "dimes")
if num_nickels == 0:
pass
elif num_nickels == 1:
print(num_nickels, "nickel")
else:
print(num_nickels, "nickels")
if num_pennies == 0:
pass
elif num_pennies == 1:
print(num_pennies, "penny")
else:
print(num_pennies, "pennies")
|
9b2d0d052ccba8adceda379d6b501ad03c971718 | ghorutest/GeekBrains | /lesson-02/2. switch_pairs_in_list.py | 567 | 3.9375 | 4 | list_main = input ('Введите спиок через запятую\n').split(',')
list_before = list(list_main)
list_len = len(list_main)
even = True if (list_len % 2) == 0 else False
if not even:
list_len = list_len - 1
print (f'Нечётная длина, игнорируем последний элемент \'{list_main[list_len]}\'\n')
for pair in range(0, list_len, 2):
tmp = list_main[pair]
list_main[pair] = list_main[pair + 1]
list_main[pair + 1] = tmp
pair += 1
print (f'До: {list_before}\nПосле: {list_main}')
|
6c5a4f0e7daa901fae21bdfd8809227166e2d450 | marcinplata/advent-of-code-2017 | /day_02.py | 2,912 | 4.4375 | 4 | """
--- Day 2: Corruption Checksum ---
As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be
idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to display
an hourglass cursor!"
The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right
track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the
largest value and the smallest value; the checksum is the sum of all of these differences.
For example, given the following spreadsheet:
5 1 9 5
7 5 3
2 4 6 8
The first row's largest and smallest values are 9 and 1, and their difference is 8.
The second row's largest and smallest values are 7 and 3, and their difference is 4.
The third row's difference is 6.
In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18
What is the checksum for the spreadsheet in your puzzle input?
"""
def read_file(path):
rows = []
with open(path) as file:
for line in file:
line = line[:-1] if line[-1] == '\n' else line
numbers = list(map(lambda x: int(x), line.split("\t")))
rows.append(numbers)
return rows
def checksum(rows):
return sum(max(row) - min(row) for row in rows)
rows = read_file("tests/day_02_test")
print(checksum(rows))
"""
--- Part Two ---
"Great work; looks like we're on the right track after all. Here's a star for your effort." However, the program
seems a little worried. Can programs be worried?
"Based on what we're seeing, it looks like all the User wanted is some information about the evenly divisible values
in the spreadsheet. Unfortunately, none of us are equipped for that kind of calculation - most of us specialize in
bitwise operations."
It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is,
where the result of the division operation is a whole number. They would like you to find those numbers on each line,
divide them, and add up each line's result.
For example, given the following spreadsheet:
5 9 2 8
9 4 7 3
3 8 6 5
In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
In the second row, the two numbers are 9 and 3; the result is 3.
In the third row, the result is 2.
In this example, the sum of the results would be 4 + 3 + 2 = 9.
What is the sum of each row's result in your puzzle input?
"""
def checksum(rows):
sum = 0
for row in rows:
pairs = [(x, y) for i, x in enumerate(row) for y in row[i+1:]]
pairs = list(map(lambda x: (x[1], x[0]) if x[0] < x[1] else x, pairs))
pairs = list(filter(lambda x: x[0] % x[1] == 0, pairs))
x, y = pairs[0]
sum = sum + x//y
return sum
print(checksum(rows))
|
cf957384e33cdc36cab2e2391733797d55b28419 | balajichander/tvr-tech | /cal.py | 611 | 4.125 | 4 | def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("selecion operation.")
print("1.add")
print("2.subtract")
print("3.multiply")
print("4.divide")
choice=input("enter choice(1/2/3/4):")
num1=int(input("enter first number:")
num2=int(input("enter second number:")
if choice=='1':
print(num1,"+",num2,"=",add(num1,num2))
elif choice=='2':
print(num1,"-",num2,"=",subtract(num1,num2))
elif choice=='3':
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice=='4':
print(num1,"/",num2,"=",divide(num1,num2))
else:
print("invalid input")
|
e281a6c2e97163336c6dd784a3e11699223d1c74 | havardnyboe/ProgModX | /2019/37/Oppgave 3.1-3.6.py/Oppgave 3.7.py | 508 | 3.5 | 4 | #Lag et program som løser andregradslikningen 𝑎𝑥^2+𝑏𝑥+𝑐=0, ved å ta 𝑎,𝑏 𝑜𝑔 𝑐 som input.
a = float(input("Skriv inn en verdi for a: "))
b = float(input("Skriv inn en verdi for b: "))
c = float(input("Skriv inn en verdi for c: "))
if (b**2) - (4*a*c) == 0:
en_losning = -b/(2*a)
print(en_losning)
elif (b**2 - 4*a*c) > 0:
x_1 = (-b + (b**2 + 4*a*c)**(1/2))/(2*a)
x_2 = (-b + (b**2 - 4*a*c)**(1/2))/(2*a)
print(x_1, "V", x_2)
else:
print("Likningen har ingen løsning")
|
0dbd7e796c295585d5d8df1d8912f15acc046ab1 | geomstats/geomstats | /examples/plot_kmeans_manifolds.py | 3,583 | 3.734375 | 4 | """Run K-means on manifolds for K=2 and Plot the results.
Two random clusters are generated in separate regions of the
manifold. Then K-means is applied using the metric of the manifold.
The points are represented with two distinct colors. For the moment
the example works on the Poincaré Ball and the Hypersphere.
Computed means are marked as green stars.
"""
import logging
import os
import matplotlib.pyplot as plt
import geomstats.backend as gs
import geomstats.visualization as visualization
from geomstats.geometry.hypersphere import Hypersphere
from geomstats.geometry.poincare_ball import PoincareBall
from geomstats.learning.kmeans import RiemannianKMeans
def kmean_poincare_ball():
"""Run K-means on the Poincare ball."""
n_samples = 20
dim = 2
n_clusters = 2
manifold = PoincareBall(dim=dim)
cluster_1 = gs.random.uniform(low=0.5, high=0.6, size=(n_samples, dim))
cluster_2 = gs.random.uniform(low=0, high=-0.2, size=(n_samples, dim))
data = gs.concatenate((cluster_1, cluster_2), axis=0)
kmeans = RiemannianKMeans(manifold, n_clusters=n_clusters, init="random")
kmeans.fit(X=data)
centroids = kmeans.centroids_
labels = kmeans.labels_
plt.figure(1)
colors = ["red", "blue"]
ax = visualization.plot(
data,
space="H2_poincare_disk",
marker=".",
color="black",
coords_type=manifold.default_coords_type,
)
for i in range(n_clusters):
ax = visualization.plot(
data[labels == i],
ax=ax,
space="H2_poincare_disk",
marker=".",
color=colors[i],
coords_type=manifold.default_coords_type,
)
ax = visualization.plot(
centroids,
ax=ax,
space="H2_poincare_disk",
marker="*",
color="green",
s=100,
coords_type=manifold.default_coords_type,
)
ax.set_title("Kmeans on Poincaré Ball Manifold")
return plt
def kmean_hypersphere():
"""Run K-means on the sphere."""
n_samples = 50
dim = 2
n_clusters = 2
manifold = Hypersphere(dim)
# Generate data on north pole
cluster_1 = manifold.random_von_mises_fisher(kappa=50, n_samples=n_samples)
# Generate data on south pole
cluster_2 = manifold.random_von_mises_fisher(kappa=50, n_samples=n_samples)
cluster_2 = -cluster_2
data = gs.concatenate((cluster_1, cluster_2), axis=0)
kmeans = RiemannianKMeans(manifold, n_clusters, tol=1e-3)
kmeans.fit(data)
centroids = kmeans.centroids_
labels = kmeans.labels_
plt.figure(2)
colors = ["red", "blue"]
ax = visualization.plot(data, space="S2", marker=".", color="black")
for i in range(n_clusters):
if len(data[labels == i]) > 0:
ax = visualization.plot(
points=data[labels == i], ax=ax, space="S2", marker=".", color=colors[i]
)
ax = visualization.plot(
centroids, ax=ax, space="S2", marker="*", s=200, color="green"
)
ax.set_title("Kmeans on the sphere")
return plt
def main():
"""Run K-means on the Poincare ball and the sphere."""
kmean_poincare_ball()
plots = kmean_hypersphere()
plots.show()
if __name__ == "__main__":
if os.environ.get("GEOMSTATS_BACKEND", "numpy") != "numpy":
logging.info(
"Examples with visualizations are only implemented "
"with numpy backend.\n"
"To change backend, write: "
"export GEOMSTATS_BACKEND = 'numpy'."
)
else:
main()
|
2f71a9f1278fde929186c42723a05f2689fab860 | dmitryzhurkovsky/stepik | /python_profiling/example1.py | 275 | 3.75 | 4 | class Iterator():
def __init__(self):
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i <= 5:
self.i += 1
return 0
else:
raise StopIteration
x = Iterator()
print(x[2]) |
9c13ab78e2d74469b219d534db07f0c3124eb184 | panxman/Python-Apps | /Computer-Vision/face_detector.py | 618 | 3.546875 | 4 | import cv2
# Load Cascade
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# Load Image
img = cv2.imread("Path/to/image.jpg")
# Image to Grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the face
faces = face_cascade.detectMultiScale(gray_img,
scaleFactor=1.1,
minNeighbors=5)
# Draw the rectangles
for x, y, w, h in faces:
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
# Show colored image
cv2.imshow("Face", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
66f0f81fd22daa5f9ab32292c252d161493f0aa3 | mandyedi/coding-challenge-solutions | /cstutoringcenter-com/programming96.py | 206 | 3.59375 | 4 | import itertools
s = ""
numbers = []
for i in itertools.permutations([1, 2, 3, 4, 5, 6, 7, 8, 9]):
for j in i:
s += str(j)
numbers.append(s)
#for i in numbers:
#i[0:
s = "hello"
print s[0:2] |
7cde210322d0ee49ae710ed2c4b6f67427857f25 | tongchangbin/python | /zdy.py | 133 | 3.84375 | 4 | #自定义函数
x = input('请输入数字:')
x = int(x)
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(x)) |
3591e84a817e1c6139b41b57aa970e5a2cfc1129 | WeiyangZhang/deep-learning-tutorial-with-chainer | /src/02_mnist_mlp/train_mnist_1_minimum.py | 4,803 | 3.90625 | 4 | """
Very simple implementation for MNIST training code with Chainer using
Multi Layer Perceptron (MLP) model
This code is to explain the basic of training procedure.
"""
from __future__ import print_function
import time
import os
import numpy as np
import six
import chainer
import chainer.functions as F
import chainer.links as L
from chainer import cuda
from chainer import serializers
class MLP(chainer.Chain):
"""Neural Network definition, Multi Layer Perceptron"""
def __init__(self, n_units, n_out):
super(MLP, self).__init__()
with self.init_scope():
# the size of the inputs to each layer will be inferred when `None`
self.l1 = L.Linear(None, n_units) # n_in -> n_units
self.l2 = L.Linear(None, n_units) # n_units -> n_units
self.l3 = L.Linear(None, n_out) # n_units -> n_out
def __call__(self, x):
h1 = F.relu(self.l1(x))
h2 = F.relu(self.l2(h1))
y = self.l3(h2)
return y
class SoftmaxClassifier(chainer.Chain):
"""Classifier is for calculating loss, from predictor's output.
predictor is a model that predicts the probability of each label.
"""
def __init__(self, predictor):
super(SoftmaxClassifier, self).__init__()
with self.init_scope():
self.predictor = predictor
def __call__(self, x, t):
y = self.predictor(x)
self.loss = F.softmax_cross_entropy(y, t)
self.accuracy = F.accuracy(y, t)
return self.loss
def main():
# Configuration setting
gpu = -1 # GPU ID to be used for calculation. -1 indicates to use only CPU.
batchsize = 100 # Minibatch size for training
epoch = 20 # Number of training epoch
out = 'result/1' # Directory to save the results
unit = 50 # Number of hidden layer units, try incresing this value and see if how accuracy changes.
print('GPU: {}'.format(gpu))
print('# unit: {}'.format(unit))
print('# Minibatch-size: {}'.format(batchsize))
print('# epoch: {}'.format(epoch))
print('out directory: {}'.format(out))
# Set up a neural network to train
model = MLP(unit, 10)
# Classifier will calculate classification loss, based on the output of model
classifier_model = SoftmaxClassifier(model)
if gpu >= 0:
chainer.cuda.get_device(gpu).use() # Make a specified GPU current
classifier_model.to_gpu() # Copy the model to the GPU
xp = np if gpu < 0 else cuda.cupy
# Setup an optimizer
optimizer = chainer.optimizers.Adam()
optimizer.setup(classifier_model)
# Load the MNIST dataset
train, test = chainer.datasets.get_mnist()
n_epoch = epoch
N = len(train) # training data size
N_test = len(test) # test data size
# Learning loop
for epoch in range(1, n_epoch + 1):
print('epoch', epoch)
# training
perm = np.random.permutation(N)
sum_accuracy = 0
sum_loss = 0
start = time.time()
for i in six.moves.range(0, N, batchsize):
x = chainer.Variable(xp.asarray(train[perm[i:i + batchsize]][0]))
t = chainer.Variable(xp.asarray(train[perm[i:i + batchsize]][1]))
# Pass the loss function (Classifier defines it) and its arguments
optimizer.update(classifier_model, x, t)
sum_loss += float(classifier_model.loss.data) * len(t.data)
sum_accuracy += float(classifier_model.accuracy.data) * len(t.data)
end = time.time()
elapsed_time = end - start
throughput = N / elapsed_time
print('train mean loss={}, accuracy={}, throughput={} images/sec'.format(
sum_loss / N, sum_accuracy / N, throughput))
# evaluation
sum_accuracy = 0
sum_loss = 0
for i in six.moves.range(0, N_test, batchsize):
index = np.asarray(list(range(i, i + batchsize)))
x = chainer.Variable(xp.asarray(test[index][0]))
t = chainer.Variable(xp.asarray(test[index][1]))
loss = classifier_model(x, t)
sum_loss += float(loss.data) * len(t.data)
sum_accuracy += float(classifier_model.accuracy.data) * len(t.data)
print('test mean loss={}, accuracy={}'.format(
sum_loss / N_test, sum_accuracy / N_test))
# Save the model and the optimizer
if not os.path.exists(out):
os.makedirs(out)
print('save the model')
serializers.save_npz('{}/classifier_mlp.model'.format(out), classifier_model)
serializers.save_npz('{}/mlp.model'.format(out), model)
print('save the optimizer')
serializers.save_npz('{}/mlp.state'.format(out), optimizer)
if __name__ == '__main__':
main()
|
e48e5e40effd77a87c23ea484aae07c2ee66e0b3 | qq854051086/46-Simple-Python-Exercises-Solutions | /problem_16_alternative.py | 325 | 3.984375 | 4 | '''
Write a function filter_long_words()that takes
a list of words and an integer
n and returns the list of words that are longer than n
'''
def filter_long_words(word_list,n):
return [word for word in word_list if len(word)>n]
word_list = ['abc','defgh','pqrstuvw','','abdghtfd']
print(filter_long_words(word_list,5))
|
9eaaf545663fb60629706113b23267f9c771c1d4 | ImGoroshik/all-tasks | /masiv2.py | 211 | 3.625 | 4 | import random
list = [random.randint(3, 15) for j in range(random.randint(3, 15))]
summ = 0
a = 0
for a in range(len(list)):
if list[a] % 3 == 0 and list[a] % 2 == 1:
summ = list[a]
print(list)
print(summ)
|
738bda0ccb17983a4e3e39517315185c7e2bacf4 | jmstratton/python-challenge | /PyBank/main.py | 2,857 | 4.3125 | 4 | # create a Python script that analyzes the records to calculate each of the following:
# The total number of months included in the dataset
# The total amount of revenue gained over the entire period
# The average change in revenue between months over the entire period
# The greatest increase in revenue (date and amount) over the entire period
# The greatest decrease in revenue (date and amount) over the entire period
#
import os
import csv
# Have the user select which version of the file to use
filename = input ('Please select which version you would like to analize (i.e budget_data_1.csv): ')
# Define Lists and Variables to be calculated
months = []
rev_changes = []
monthcounter = 0
total_revenue = 0
this_month_rev = 0
last_month_rev = 0
rev_change = 0
# open csv file
PyBankData = os.path.join('raw_data', filename)
with open(PyBankData, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
next (csvreader)
#REVENUE - Gather monthly changes in revenue
for row in csvreader:
monthcounter = monthcounter + 1
months.append(row[0])
this_month_rev = int(row[1])
total_revenue = total_revenue + this_month_rev
if monthcounter > 1:
rev_change = this_month_rev - last_month_rev
rev_changes.append(rev_change)
last_month_rev = this_month_rev
#REVENUE CONT'D - Analyze the monthly result
Sum_of_revenue_changes = sum(rev_changes) #Add all the revenue changes
average_change = Sum_of_revenue_changes / (monthcounter - 1) #Finds the average change
max_change = max(rev_changes)
min_change = min(rev_changes)
max_monthly_index = rev_changes.index(max_change)
min_monthly_index = rev_changes.index(min_change)
max_month = months[max_monthly_index]
min_month = months[min_monthly_index]
#print results
print('Financial Analysis')
print('---------------------------------------------')
print(f'Total Months: {monthcounter}')
print(f'Total Revenue: ${total_revenue}')
print(f'Average Revenue Change: ${average_change}')
print(f'Greatest Increase in Revenue: {max_month} (${max_change})')
print(f'Greatest Decrease in Revenue: {min_month} (${min_change})')
PyBankText_path = os.path.join ('raw_data', 'Budget_Data_ANALYSIS-CHANGE ME')
#NOTE: ***THIS FILE WILL BE OVERWRITTEN, RENAME THE FILE FOR FUTURE USE!!!!!***
with open(PyBankText_path, 'w') as newfile:
newfile.write('Financial Analysis \n')
newfile.write('---------------------------------------------\n')
newfile.write(f'Total Months:{monthcounter}' + '\n')
newfile.write(f'Total Revenue: ${total_revenue}' + '\n')
newfile.write(f'Average Revenue Change: ${average_change}' + '\n')
newfile.write(f'Greatest Increase in Revenue: {max_month} (${max_change})' + '\n')
newfile.write(f'Greatest Decrease in Revenue: {min_month} (${min_change})' + '\n') |
bd4364047b82fedd7ee90635067a6c7c20f57e59 | joebigjoe/Hadoop | /Spark快速大数据分析/第 3 章 RDD 编程/Python OOP Basic/classTest2.py | 724 | 4.0625 | 4 | #_name
#__name
##__name__
# __init__ is the self defined methods by python, normally it has special purpose
# __init__ is to initialize the instance of a class
# __main__ is to show the start poin of a program.
# nomally it is for override
class Person:
def __init__(self):
self._name = "Joey" # this is just a conversion for private member, just a convension
self.name = "Aria" # normal
self.__name = "Jria" # name mangling, for when differet class has same name, so we can indentify nane add a class name as a namespace
self.__lol = "HAHAHAHAHA"
person1 = Person()
print(person1.name)
print(person1._name)
#print(dir(person1))
print(person1._Person__name)
print(person1._Person__lol) |
46967699118df771c18826d0a4624f3a731f1b78 | andersongfs/Programming | /URI/URI-1091.py | 488 | 3.734375 | 4 | # -*- coding: utf-8 -*-
while True:
qtd_casa = int(raw_input())
if(qtd_casa == 0):
break
x_ponto, y_ponto = map(int, raw_input().split())
for i in range(qtd_casa):
x_casa, y_casa = map(int, raw_input().split())
if(x_casa > x_ponto and y_casa > y_ponto):
print "NE"
elif(x_casa > x_ponto and y_casa < y_ponto):
print "SE"
elif(x_casa < x_ponto and y_casa > y_ponto):
print "NO"
elif(x_casa < x_ponto and y_casa < y_ponto):
print "SO"
else:
print "divisa"
|
e3dce270f41a5505135a8eadbce8e3aba2716923 | kuchunbk/PythonBasic | /2_String/String_Sample/Sample/string_ex43.py | 594 | 4.09375 | 4 | '''Question:
Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.
'''
# Python code:
area = 1256.66
volume = 1254.725
decimals = 2
print("The area of the rectangle is {0:.{1}f}cm\u00b2".format(area, decimals))
decimals = 3
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
'''Output sample:
The area of the rectangle is 1256.66cm²
The volume of the cylinder is 1254.725cm³
''' |
4784097591055b420d9da1df8a650782095d4d57 | Amrutha26/100DaysOfCode | /Week2/Day13/Duplicate Character.py | 1,382 | 3.6875 | 4 | '''
Duplicate Character
Tina is given a string
S which contains the first letter of all the student names in her class. She got a curiosity to check how many people have their names starting from the same alphabet.
So given a string S, she decided to write a code that finds out the count of characters that occur more than once in the string.
Input format
The first line contains an integer T, denoting the number of test cases.
Each test case consists of a string S containing only lowercase characters.
Output format
For each test case on a new line, print the output in the format character=count. If multiple characters have more than one count, print all of them separated by space, in alphabetical order.
In case no such character is present print −1.
Constraints
1<=T<=7
1<=|S|<=10^7, where |S| denotes length of string S.
Time limit
1 second
Example
Input
3
prepbytes
java
algorithm
Output
e=2 p=2
a=2
−1
Sample test case explanation
In the first string character p is occuring 2 times and character e is occuring 2 times.
Printing them in alphabetical order we get,
e=2 p=2
'''
import collections
t=int(input())
for i in range(t):
s=input()
results = collections.Counter(s)
flag=1
for key in sorted(results):
if(results[key]>1):
flag=0
print(key,end="=")
print(results[key],end=" ")
if(flag):
print("-1",end="")
print() |
b39f0c8d5713d59b15ca0c9905ecfbc60de4b3ce | u19046500/280201055 | /lab4/factorial.py | 107 | 4.03125 | 4 | n = int(input("Enter the number:"))
sum_ = 1
for i in range(1, n+1):
sum_ = sum_ * i
print("n! =", sum_)
|
cf7c7dd390ce758150f031d9cd4f9f2c092535c4 | erik-bordac/snake_neural_network | /classes/snakeClass.py | 1,048 | 3.890625 | 4 |
class Snake():
def __init__(self):
self.body = [{"x": 5, "y":5}, {"x": 4, "y":5}, {"x": 3, "y":5},]
self.direction = "right"
self.ate = False
self.moves_left = 400
def move(self):
"""
Moves the snake in self.direction
If snake ate apple in this iteration, prevents removing last block
return None
"""
if self.direction == "right":
head = self.body[0]
self.body.insert(0, {"x": head["x"]+1, "y": head["y"]})
elif self.direction == "up":
head = self.body[0]
self.body.insert(0, {"x": head["x"], "y": head["y"]-1})
elif self.direction == "left":
head = self.body[0]
self.body.insert(0, {"x": head["x"]-1, "y": head["y"]})
elif self.direction == "down":
head = self.body[0]
self.body.insert(0, {"x": head["x"], "y": head["y"]+1})
if not self.ate:
del self.body[-1]
self.ate = False
self.moves_left -= 1
|
84feca3a9f4db7181a67df5d99a2df30bbaf6ce2 | nurhalfiansilayar/pgame | /pgame-16092/praktikum6.2.py | 226 | 3.8125 | 4 | batas='*'*30
x = 0
while (x < 5):
x = x+ + 1
x += 1
print ("Praktikum 6 no.", x)
a = 0
while a < 6:
print (" no a == ", a)
if a == 3:
break
a +=1
b = 0
while b < 6:
b += 1
if b == 3:
print("B == ",b)
print(b)
|
88a91b1e4fb86498a0e47eda6a6fe17a5d2c26aa | Kiranc44/DSA-Project | /bankhash.py | 4,920 | 3.734375 | 4 | from banklinkedlist import LinkedList
from bankqueue import Queue
import datetime
stint=0
def h(v):
return int(v)%10
class hashtable:
def __init__(self):
self.T=[None for i in range(0,10)]
def chained_insert(self,a,ln):
k=h(a)
if(self.T[k]==None):
self.T[k]=LinkedList()
self.T[k].head=ln
else:
p=self.T[k].head
while (p.next is not None):
p=p.next
p.next=ln
def chained_search(self,a):
k=h(a)
if(self.T[k]==None):
return False
else:
p=self.T[k].head
while(p is not None):
if(a==p.key):
return p
p=p.next
return False
def chained_delete(self,a):
k=h(a)
p=self.T[k].head
while p!=None:
if(a!=p.key):
z=p
p=p.key
else:
z.next=p.next
def createAC(self):
global stint
stint=stint+1
#print("To create a new zero balance savings account do : ")
newNode=ListNodell(stint)
newNode.name=input("Enter the account holders name : ")
newNode.Address=input("Enter the Address of the account holder : ")
newNode.phno=input("Enter the phone number account holder : ")
self.chained_insert(stint,newNode)
self.acc_pass(stint)
def show(self):
for i in range(0,len(self.T)):
if self.T[i]!=None:
self.T[i].print()
def transactions(self,k):
x=int(input("Enter 1 to withdraw and 2 to deposite"))
date = datetime.datetime.now()
date=date.strftime("%Y-%m-%d %H:%M")
if(x==1 and self.balance!=0):
print("Please deposite amount..!")
a=int(input("Enter the amount to withdraw"))
account=self.chained_search(k)
account.balance=account.balance-a
account.qu.enqueue(date,"W",a,account.balance)
#elif(x==1 and self.balance==0):
# print("Please deposite your money...!")
elif(x==2):
a=int(input("Enter the amount to deposite"))
account=self.chained_search(k)
account.balance=account.balance+a
account.qu.enqueue(date,"D",a,account.balance)
def passbookdisplay(self,k):
account1=self.chained_search(k)
print('DATE | TRANSACTION | AMOUNT | BALANCE')
account1.qu.dequeue()
#def loanIssue(self,K):
# person=
def acc_pass(self,k):
k=h(k)
account=self.chained_search(k)
if(account.password==None):
q=input("Enter a new password")
l=input("Confirm password")
if(q==l):
account.password=q
else:
while True:
q=input("Enter your password")
if account.password==q:
a=input("Enter a new password")
b=input("Confirm password")
if a==b:
account.password=a
print("Password changhed sucessfully!")
return
else:
print("Enter correct password or account no")
def loanIssue():
pass
class ListNodell:
def __init__(self,k=None):
self.key=k
self.next=None
self.qu=Queue()
self.phno=None
self.balance=0
self.Address=None
self.name=None
self.Loan=None
self.password=None
def main():
"""h=hashtable()
h.createAC()
h.createAC()
h.show()
print(h.chained_search(1))
h.transactions(1)
h.transactions(1)
h.passbookdisplay(1)"""
h=hashtable()
date = datetime.datetime.now()
date=date.strftime("%Y-%m-%d %H:%M")
print("Enter 1:Coustomer")
print("Enter 2:Staff")
q=int(input("Enter ur choice:"))
if(q==1):
print("Enter 1:Login")
print("Enter 2:createAC")
print("Enter 3:Loan")
z=int(input("Enter your option"))
if(z==1):
accno=int(input("Enter your Acc.No"))
passwrd=input("Enter your password")
if(self.T[k].password!=passwrd):
print("Wrong account no. or password")#shd go back to first statement
else:
print("Enter 1 for transactions")
print("Enter 2 for checking balance")
print("Enter 3 for printing passbook")
print("Enter 4 for changing password")
m=int(input("Enter your option"))
if(m==1):
h.transactions(accno)
elif(m==2):
print("Your current balance is: ",h[accno].balance," as of:",date)
elif(m==3):
h.passbookdisplay(accno)
elif(m==4):
h.acc_pass(accno)
elif(z==2):
h.createAC()
if __name__ == '__main__':
main()
|
ea01165b8a27e783181912d103cef78b638aaeb5 | Weless/leetcode | /python/general/1022. 从根到叶的二进制数之和.py | 521 | 3.5625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
def dfs(root,path):
if root:
path += str(root.val)
if not root.left and not root.right:
res.append(path)
dfs(root.left,path)
dfs(root.right,path)
res = []
dfs(root,'')
return sum([int(item,2) for item in res]) |
fb7df606223d91e294d9b599ad27e6d88058dac7 | ShivamGupta-08/Oh-Soldier-Prettify-My-Folder | /Oh-Soldier-Prettify-My-Folder.py | 1,648 | 4.375 | 4 | import os
def File_Reader(file_read):
with open(file_read) as e:
read = e.read()
s = read.split("\n")
return s
def Folder_Prettifer(path, file, format):
"""This function prettify your folder by -
1 - Capitalizing the first letter of the files not folder expect the file names you have entered in the dictionary file.
2 - Renaming the files by whole numbers of particular format you have entered. """
os.chdir(path)
s = File_Reader(file)
list = os.listdir(path)
list_of_files = [ele for ele in list if os.path.isfile(ele) if ele != file]
for ele in s:
list_of_files.remove(ele)
for count, filename in enumerate(list_of_files):
dst = filename.capitalize()
src = path + "/" + filename
dst = path + "/" + dst
os.rename(src, dst)
list_of_files_format = [ele for ele in list if os.path.isfile(ele) if ele != file if ele.endswith(format)]
for count, filename in enumerate(list_of_files_format):
dst = str(count)+"."+format
src = path + "/" + filename
dst = path + "/" + dst
os.rename(src, dst)
print("Your folder is now prettify")
if __name__ == '__main__':
print("WELCOME TO "" Oh Soldier Prettify My Folder """)
print("Enter the path of your folder:")
folder = input()
print("Enter the name of your dictionary file:")
Dictionary_file = input()
print("Enter the file format (without ""."") you want to name them in numerically order: ")
exe = input()
#input your folder path , Dictionary file and the format like this
Folder_Prettifer(folder,Dictionary_file, exe)
|
10e5829568952762fab910c6a43d4c77a1cf2542 | Herna7liela/New | /list4.py | 404 | 4.28125 | 4 | # Write a program that asks the user to enter a number from 1 to 12 and
# prints out the name of the corresponding month.
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
#months = [January, February, March, April, May, June, July, August, September, October, November, December]
number = int(input("Enter a number between 1 to 12: "))
print (months[number]) |
10c7332d57801a828f1c1261d143866fcfe7567e | admud/matplotlibPython | /practice1.py | 243 | 3.59375 | 4 | import matplotlib.pyplot as plt
x = [1,2,3]
y= [5,4,7]
x2 = [1,2,3]
y2 = [10,11,12]
plt.plot(x,y,label = "First")
plt.plot(x2,y2,label = "Second")
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('cool graph')
plt.legend()
plt.show()
|
445aef32fe8b18831ddcb186e4422afbe42696b4 | KHP-Informatics/RADAR-scripts | /radar/preprocess/filters.py | 3,609 | 3.828125 | 4 | #!/usr/bin/env python3
import pandas as pd
from scipy import signal
def butterworth(arr, cutoff, freq, order=5, ftype='highpass'):
""" butterworth filters the array through a two-pass butterworth filter.
Parameters
__________
arr: list or numpy.array
The timeseries array on which the filter is applied
cutoff: scalar or len-2 sequence
The critical frequencies for the Butterworth filter. The point at
which the gain drops to 1/sqrt(2) of the passband. Must be length-2
sequence for a bandpass filter giving [low, high]. Or else the scalar
cutoff frequency for either a low-pass' or 'highpass' filter.
freq: float
The frequency (Hz) of the input array
ftype: {'highpass', 'lowpass', 'bandpass'}
The filter type. Default is 'highpass'
"""
nyq = 0.5 * freq
b, a = signal.butter(order, cutoff/nyq, ftype)
return signal.filtfilt(b, a, arr)
def accel_linear(accel_array, freq):
""" acceleration_gravity runs a filter on the input array(s) to remove the
gravitational component and return linear acceleration. Uses a two-pass
Butterworth filter with cutoff = 0.5Hz, order=5
Parameters
__________
accel_array : list(s) or numpy array(s)
The acceleration data that the filter will be applied to. Can be single
or multiple vectors. Each dimension is treated as a seperate
accelerometer vector. Vectors should be in rows for numpy arrays but
columns for pandas DataFrames
freq: float
The frequency (Hz) of the accelerometer
Returns
_______
linear_accel: type(accel_array)
The linear acceleration as predicted by the highpass filter
"""
if accel_array.ndim > 1:
linear_accel = accel_array.copy()
if isinstance(accel_array, pd.DataFrame):
for col in linear_accel:
linear_accel[col] = butterworth(linear_accel[col], cutoff=0.5,
freq=freq, ftype='highpass')
else:
for arr in linear_accel:
arr = butterworth(arr, cutoff=0.5, freq=freq, ftype='highpass')
else:
linear_accel = butterworth(accel_array, cutoff=0.5, freq=freq,
ftype='highpass')
return linear_accel
def accel_gravity(accel_array, freq):
""" accel_gravity runs a filter on the input array(s) to extract
the gravitational component. Uses a two-pass Butterworth filter with
cutoff = 0.5Hz, order=5
Parameters
__________
accel_array : list(s) or numpy array(s)
The acceleration data that the filter will be applied to. Can be single
or multiple vectors. Each dimension is treated as a seperate
accelerometer vector. Vectors should be in rows for numpy arrays but
columns for pandas DataFrames
freq: float
The frequency (Hz) of the accelerometer
Returns
_______
gravity: type(accel_array)
The gravity as predicted by the lowpass filter
"""
if accel_array.ndim > 1:
gravity = accel_array.copy()
if isinstance(accel_array, pd.DataFrame):
for col in gravity:
gravity[col] = butterworth(gravity[col], cutoff=0.5,
freq=freq, ftype='lowpass')
else:
for arr in gravity:
arr = butterworth(arr, cutoff=0.5, freq=freq, ftype='lowpass')
else:
gravity = butterworth(accel_array, cutoff=0.5, freq=freq,
ftype='lowpass')
return gravity
|
eb0767677a68b68a8a0b350eb0393e757d598c8b | beejjorgensen/bgpython | /source/examples/ex_refval.py | 190 | 3.84375 | 4 | a = [1, 2, 3]
#b = a # Copies reference to same list
b = a.copy() # Makes a new list
#b = list(a) # Also makes a new list
#b = a[:] # Also makes a new list
b[0] = 99
print(a[0])
|
51608c728ad02bc139b9fdb6e746bc63ec86d9c4 | geekpradd/Project-Euler | /problem2.py | 242 | 3.515625 | 4 | __author__ = 'Pradipta'
def fibo():
s=[]
a,b=1,2
while a<4000001:
s.append(a)
s.append(b)
a=a+b
b=b+a
return s
def main():
total=sum([x for x in fibo() if not x%2])
print(total)
main() |
05256e312ec693dbaa1e7b30871f44532f2bf686 | stemlatina/SI507--HW03--MariluD | /magic_eight.py | 2,228 | 3.921875 | 4 | #<<<<<<< HEAD
import random
class Magic8:
def __init__(self, question):
self.question = question
pass
def ask_question(self, question):
question_list = []
q = self.question
question_list.append(q)
pass
def pick_random_ans(self):
#List from Wiki: https://en.wikipedia.org/wiki/Magic_8-Ball
rand_list = ["It is certain", "It is decidedly so","Without a doubt", "Yes - definitely","You may rely on it", "As I see it, yes", "Most likely", "Outlook good","Yes", "Signs point to yes", "Reply hazy, try again", "Ask again later", "Better not tell you now","Cannot predict now","Concentrate and ask again", "Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"]
rand_item = random.choice(rand_list)
r = str(rand_item)
return r
q = Magic8(input("What is your question? : "))
print(q.pick_random_ans())
#=======
# SI 507 Fall 2019
# Homework 3 - Magic 8-Ball Code & Git Tutorial
# Worked on by: Marilu D. and Alison S.
import random
class Magic8:
def __init__(self, question):
self.question = question
pass
def ask_question(self, question):
question_list = []
q = self.question
question_list.append(q)
pass
def pick_random_ans(self):
#List from Wiki: https://en.wikipedia.org/wiki/Magic_8-Ball
rand_list = ["It is certain", "It is decidedly so","Without a doubt", "Yes - definitely","You may rely on it", "As I see it, yes", "Most likely", "Outlook good","Yes", "Signs point to yes", "Reply hazy, try again", "Ask again later", "Better not tell you now","Cannot predict now","Concentrate and ask again", "Don't count on it","My reply is no","My sources say no","Outlook not so good","Very doubtful"]
rand_item = random.choice(rand_list)
r = str(rand_item)
return r
def check_for_question(self, question):
question = self.question
q = question[-1:]
r = self.pick_random_ans()
if q == "?":
return print("The Magic 8 ball says: " + r)
else:
return print("I'm sorry, I can only answer questions. Please enter a question.")
q = Magic8(input("What is your question? : "))
qq = q.question
q.check_for_question(qq)
#>>>>>>> check_question
|
8b3b5da037a838d1d98c4fe3db8eb4f79db642e3 | jpchato/data-structures-and-algorithms-python | /challenges/insertion_sort/test_insertion_sort.py | 628 | 3.765625 | 4 | from insertion_sort import insertion_sort
def test_insertion_sort():
array_one = [5, 26, 9, 4, 3]
actual = insertion_sort(array_one)
expected = [3, 4, 5, 9, 26]
assert actual == expected
def test_negative_insertion_sort():
array_two = [-1, 2, 7, -100, 42]
actual = insertion_sort(array_two)
expected = [-100, -1, 2, 7, 42]
assert actual == expected
def test_duplicates_insertion_sort():
array_three = [4, 1, 2, 2, 4, -23, -100, 1]
actual = insertion_sort(array_three)
expected = [-100, -23, 1, 1, 2, 2, 4, 4]
assert actual == expected
# print(insertion_sort([5, 26, 9, 4, 3])) |
a94cd29932db2f2586d321d60ed9a552f050127b | Jeff-ust/D002-2019 | /L1/Q4.py | 214 | 4.03125 | 4 | yr = int(input("Please input the year."))
if (yr%4 == 0) and (yr%100 != 0):
print("Yes, it is a leap year.")
elif (yr%400 == 0):
print("Yes, it is a leap year.")
else:
print("No, it is not a leap year.")
|
c301f134ea191e2f29cb56b41d00aa1baea7a5fe | singh7h/GeekforGeek | /Basic/Array.py | 465 | 3.921875 | 4 |
"""Sum of array"""
def _sum(arr):
return sum(arr)
def splitarr(arr, d):
for i in range(d):
new_arr = arr
x = arr.pop(0)
new_arr.append(x)
print(new_arr)
def largest(arr, d):
large = arr[0]
for i in range(0, d):
if arr[i] > large:
large = arr[i]
print(large)
if __name__ == '__main__':
arr = [6, 2, 3, 4, 5,90,88]
# splitarr(arr, 2)
n = len(arr)
largest(arr, n)
|
3612c0d1e059a647cf5e08c5c9b20fc5bdaf3a99 | Celsoliv/Orientacao-Objetos | /OrientacaoObjeto01.py | 1,347 | 4.34375 | 4 | # Criando nossa 1ª Classe em Python
# Sempre que você quiser criar uma classe, você vai fazer:
#
# class Nome_Classe:
#
# Dentro da classe, você vai criar a "função" (método) __init__
# Esse método é quem define o que acontece quando você cria uma instância da Classe
#
# Vamos ver um exemplo para ficar mais claro, com o caso da Televisão que a gente vinha comentando
#classes
class TV: #criar uma classe
cor = 'preta' #atributo fixo criado para a classe TV
def __init__(self, tamanho): #atributos, sempre inicia com __init__ / tamanho virou atributo para escolher
self.ligada = False
self.tamanho = tamanho #tamanho é uma variavel
self.canal = "Netflix"
self.volume = 10
def mudar_canal(self, novo_canal): #metodo da minha classe TV, novo_canal é um parametro
self.canal = novo_canal
print('Canal alterado para {}'.format(novo_canal))
#programa
# para criar uma TV eu preciso passar os parametro que escolhi no __init__
tv_sala = TV(tamanho=55) #cria a tv da sala com a classe TV / Criando uma instancia da TV / recebendo todos os atributos
tv_quarto = TV(tamanho=50)
tv_sala.quarto = 'verde'
tv_sala.mudar_canal("Globo") #aqui coloca o novo_canal que é o parametro
tv_quarto.mudar_canal('Youtube')
print(tv_sala.canal)
print(tv_quarto.canal)
print(tv_sala.cor) |
2fa6d7a3e3b5e409f383e1c6da83fd421148fc42 | sukhesai/algorithms_and_data_structures | /learning docs/testt1.py | 181 | 3.609375 | 4 | import math
x = 0
for y in range(1,50):
for i in range(1,y+1):
#print(i,math.floor(i*math.sqrt(2))-i)
x += math.floor(i*math.sqrt(2))
print((2*x)/(y*(y+1)))
|
81a11b12218b61c724d09fc3aa759f13734893fb | staufferl16/Programming112 | /evaluator.py | 2,374 | 3.5 | 4 | """
Author: Leigh Stauffer
File: evaluator.py
Project 10
"""
from tokens import Token
from scanner import Scanner
from linkedstack import LinkedStack
class Evaluator(object):
"""Evaluator for postfix expressions.
Assumes that the input is a syntactically correct
sequence of tokens."""
def __init__(self, scanner):
"""Sets the initial state of the evaluator."""
self._operandStack = LinkedStack()
self._scanner = scanner
def evaluate(self):
"""Returns the value of the postfix expression."""
for currentToken in self._scanner:
if currentToken.getType() == Token.INT:
self._operandStack.push(currentToken)
elif currentToken.isOperator():
right = self._operandStack.pop()
left = self._operandStack.pop()
result = Token(self._computeValue(currentToken,
left.getValue(),
right.getValue()))
self._operandStack.push(result)
result = self._operandStack.pop()
return result.getValue();
def _computeValue(self, op, value1, value2):
"""Utility routine to compute a value."""
result = 0
theType = op.getType()
if theType == Token.PLUS:
result = value1 + value2
elif theType == Token.MINUS:
result = value1 - value2
elif theType == Token.MUL:
result = value1 * value2
elif theType == Token.REMDR:
result = value1 % value2
elif theType == Token.EXPO:
result = value1 ** value2
elif theType == Token.DIV:
if value2 == 0:
raise ZeroDivisionError("Attempt to divide by 0")
else:
result = value1 // value2
return result
def main():
"""Tester function for the evaluator."""
while True:
sourceStr = input("Enter a postfix expression: ")
if sourceStr == "": break
try:
evaluator = Evaluator(Scanner(sourceStr))
print("The value is", evaluator.evaluate())
except Exception as e:
print("Exception:", str(e))
if __name__ == '__main__':
main()
|
99985d96503ee8b998b736e3bb4aece9b3498293 | claraqqqq/l_e_e_t | /139_word_break.py | 1,679 | 4.03125 | 4 | # Word Break
# Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
# For example, given
# s = "leetcode",
# dict = ["leet", "code"].
# Return true because "leetcode" can be segmented as "leet code".
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
"""
Dynamic programming:
Dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems.
It is applicable to problems exhibiting the properties of overlapping subproblems[1] and optimal substructure.
In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine
the solutions of the subproblems to reach an overall solution,
Often when using a more naive method, many of the subproblems are generated and solved many times.
The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations:
once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution
is needed, it is simply looked up.
"""
length = len(s)
rcrd = [False for dummy_idx in range(length+1)]
rcrd[0] = True
for break_idx in range(1, length+1):
for tmp_break_idx in range(break_idx):
if rcrd[tmp_break_idx] == True and \
s[tmp_break_idx : break_idx] in dict:
rcrd[break_idx] = True
break
return rcrd[-1]
|
e6000854575fdf45dcf4e37ebe08d0f5fab5430b | TheRealSnuffles/Python-HW | /Boolean.py | 333 | 4.0625 | 4 | test1=float(input('What was your 1st test score?'))
test2=float(input('What was your 2nd test score?'))
test3=float(input('What was your 3rd test score?'))
HIGH_SCORE=95
average=(test1+test2+test3)/3
print('The average score is', average)
if average >= HIGH_SCORE:
print('Congratulations!')
print('that is a great average!')
|
3d4a0f9e37d593bd33e81134633cb428d0bb645f | CatchTheDog/python_crash_course | /src/chapter_4/logical_control_2.py | 310 | 3.96875 | 4 | car = 'subaru'
print("Is car == 'subaru'? I predict True!")
print(car == 'subaru')
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding "+ requested_topping)
print("\n\tFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?") |
244ccff77fdb9b214a04334627cf12b67c4ff50b | lovisgod/TravisCI_With_Python | /work.py | 301 | 4 | 4 | def is_prime (number):
if number in (0,1):
return False
if number < 0:
return False
""" return true if the *number* is prime"""
for element in range(2, number):
if number % element == 0:
return False
return True
is_prime(5) |
f6bcf54bacf17a73e0f1701aa68ea1e33db1f972 | renan-lab/python-study | /part1/exercicios/aula13/ex7.py | 653 | 3.90625 | 4 | #num = int(input('Digite um número: '))
#div = 0
#for c in range(2, num):
# if num % c == 0:
# div += 1
#
#if div > 0 or num == 1:
# print('{} não é um número primo.'.format(num))
#else:
# print('{} é um número primo.'.format(num))
#código melhorado:
num = int(input('Digite um número: '))
div = 0
for c in range(1, num+1):
if num % c == 0:
print('\033[32m', end='')
div += 1
else:
print('\033[31m', end='')
print(c, end=' ')
print('\n\033[0;0mO número {} foi divisível {} vezes'.format(num, div))
if div == 2:
print('E por isso ele É PRIMO!')
else:
print('E por isso ele NÃO É PRIMO!')
|
d2fb92783986b0850745955c8a271706717f8b6d | mbyrd314/cryptopals | /set1_challenge7.py | 1,613 | 3.609375 | 4 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
def decrypt_aes_ecb1(ciphertext, key):
"""
Implementation of AES ECB mode decryption using the Python cryptography library
Args:
ciphertext (bytes): The ciphertext message to be decrypted
key (bytes): The AES secret key
Returns:
msg (bytes): The decrypted version of the ciphertext input
"""
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
decryptor = cipher.decryptor()
msg = decryptor.update(ciphertext) + decryptor.finalize()
return msg
def decrypt_aes_ecb2(ciphertext, key):
"""
Implementation of AES ECB mode decryption using the Python Crypto library
Args:
ciphertext (bytes): The ciphertext message to be decrypted
key (bytes): The AES secret key
Returns:
msg (bytes): The decrypted version of the ciphertext input
"""
aes = AES.new(key, AES.MODE_ECB)
msg = aes.decrypt(ciphertext)
return msg
if __name__ == '__main__':
"""
Tests both of the above AES ECB mode decryption functions on the encrypted
text file with known key.
"""
with open('set1_challenge7.txt', 'r') as f:
ciphertext = b64decode(f.read())
key = b'YELLOW SUBMARINE'
msg = decrypt_aes_ecb1(ciphertext, key)
print(msg.decode())
assert(decrypt_aes_ecb1(ciphertext, key)==decrypt_aes_ecb2(ciphertext,key))
|
8162e759a06dfe2f82be1edfe4b67e8addbbef42 | krishnakpatel/Summer2017 | /graphv5.py | 5,262 | 3.640625 | 4 |
#add functionality: modifying values
import matplotlib.pyplot as plt
import networkx as nx
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring
# as soon as the program loads
circ = nx.MultiDiGraph()
node_num = 1
key = 0
def click(type):
circ.add_node(node_num)
circ.add_node(node_num+1)
# print(What is it's value?)
circ.add_edge(node_num, (node_num+1),key=key+1,type=type)
node_num += 2
key += 1
# click on a resistor
def resistor():
click('r')
# click on an inductor
def inductor():
click('i')
# click on a capacitor
def capacitor():
click('c')
#two components dragged together(ends join together)
def join(edge1, edge2):
old_node = edge2[0]
edge2[0] = edge1[1]
to_change = circ.edges(old_node)
for edge in to_change:
edge[0] = edge1[1]
circ.remove_edge(old_node)
# figure out which node is the last node of edge1
#edge1[1]
# figure out which node is the first node of edge2
#edge2[0]
# change edge2's first node to the last node of edge1
# find any other edges connected to edge2's start
# change all of them to the edge1's last node
# delete the first node of edge2
# two components dragged apart (ends split) the one being dragged MUST be edge2
def split(stationary, dragged):
# figure which node they have in common
if stationary[1] == dragged[0]:
dragged[0] = node_num+1
node_num += 1
return
elif stationary[0] == dragged[1]:
dragged[1] = node_num+1
node_num += 1
# if it's edge2's first node
# change edge2's first node to num_node+1
# num_node++
# if it's edge2's second node
# change edge2's second node to num_node+1
# num_node++
# delete a component
def delete(edge):
start = circ.edges(edge[0])
end = circ.edges(edge[1])
if not start:
if not end:
circ.remove_node(edge[0])
circ.remove_node(edge[1])
circ.remove_edge(edge)
# check that it has start & end nodes that no other nodes are connected to
# remove edge
# remove start & end nodes
for x in range(1,8):
circ.add_node(x)
circ.add_edges_from([(1, 2, {'type': 'r', 'value': 25}), (1, 2, {'type': 'r', 'value': 50}), (1, 5, {'type': 'r', 'value': 77}), (1, 3,{'type': 'r', 'value': 85}),(2, 7,{'type': 'r', 'value': 63}), (6, 7,{'type': 'r', 'value': 50}), (3, 4,{'type': 'r', 'value': 200}), (4, 5,{'type': 'r', 'value': 100}), (4, 6,{'type': 'r', 'value': 85})])
# CTRL + S/click on save
def save():
# added functionality to ask for file name (Save As...)
file = open('test.xml','wb')
root = Element('circuit')
document = ElementTree(root)
nodes = SubElement(root, 'max_node_num')
nodes.text = str(node_num)
edges_list = SubElement(root,'edges_list')
edges = circ.edge
for start, dicts in edges.items():
if bool(dicts):
s = SubElement(edges_list, 'start', {'at': str(start)})
for end, keys in dicts.items():
e = SubElement(s, 'end', {'at': str(end)})
string = ''
for key, data in keys.items():
for t, v in data.items():
if not isinstance(v, str):
v = str(v)
string += v
string += ' '
e.text = string
#list = [e for e in circuit.edges_iter(data=True)]
#for elem in list:
#edge = SubElement(edges_list, 'edge', {'data':elem})
# print(tostring(file, encoding='UTF-8', xml_declaration=True))
# print(tostring(root, encoding='UTF-8'))
document.write(file, encoding='UTF-8', xml_declaration=True)
#print(prettify(root))
#file.write(tostring(root))
file.close()
save()
circ.clear()
# open from saved file
# read in selected HML file use ElemenTree HML parser call create_graph
def open_saved(file_name):
file = open(file_name, 'rb')
tree = ElementTree()
tree.parse(file)
# root = tree.getroot()
# for child in root:
# print(child.tag, child.attrib)
#tree = ET.parse(file_name)
root = tree.getroot()
node_num = root.findtext('max_node_num')
for start in root.find('edges_list'):
node1 = start.attrib['at']
for end in start:
node2 = end.attrib['at']
edges_str = ''.join(end.itertext())
edges = edges_str.split( )
if bool(edges):
first = edges[0]
sec = edges[1:]
circ.add_edges_from([(node1, node2, {'type': first, 'value': sec})])
# l = l.replace('\\', '')
# result = bytes(l, "utf-8").decode("unicode_escape")
#result = l.translate({ord('\\'):None})
#circuit.add_edges_from(result)
# print(node_num)
# print(tostring(root))
# print(root.tag)
# for child in root:
# print(child.tag)
# for c in child:
# print(c.tag, c.attrib)
open_saved('test.xml')
pos = nx.random_layout(circ)
nx.draw_networkx_nodes(circ,pos,node_size=700)
nx.draw_networkx_edges(circ,pos,width=1.0)
nx.draw_networkx_labels(circ,pos)
# show graph
plt.show()
|
02b6d600fa101af2f04bd6b59e11fca1c18c8775 | gerrycfchang/leetcode-python | /google/Abbr/valid_word_abbreviation.py | 1,343 | 4 | 4 | """
Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.
A string such as "word" contains only the following valid abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".
"""
class Solution(object):
def validWordAbbreviation(self, word, abbr):
"""
:type word: str
:type abbr: str
:rtype: bool
"""
num = index = 0
for w in abbr:
if w.isdigit():
num = num * 10 + int(w)
if num > len(word):
return False
else:
index = num + index
num = 0
if index > len(word) or word[index] != w:
return False
index += 1
return index == len(word)
if __name__ == '__main__':
sol = Solution()
assert (sol.validWordAbbreviation('word','w2d') == True)
assert (sol.validWordAbbreviation('word', '3d') == True)
assert (sol.validWordAbbreviation('word', '10d') == False)
assert (sol.validWordAbbreviation('word', 'w1xd') == False)
|
a72522154e3dba483f66be75baf4d2da023fa7a6 | Engy-22/BaseballSync | /src/utilities/stringify_list.py | 313 | 3.5625 | 4 | def stringify_list(given_list):
if len(given_list) > 1:
low = str(given_list[0])
high = str(given_list[-1])
if len(given_list) != 2:
return 's ' + low + '-' + high
else:
return 's ' + low + ' & ' + high
else:
return ' ' + str(given_list[0])
|
ca3cb64788663f8024317fd9fc0f08c7c627b422 | programmingkids/python-level1 | /chapter06/work10.py | 91 | 3.53125 | 4 | num = 10
if :
print("5以上です")
else :
print("5より小さいです")
|
e2c9d337b566b8bb9334ae3959fadd56846b4b85 | Xiaowei66/UNSW_COMP9021_S2 | /assignment1_q4.py | 3,501 | 3.796875 | 4 | # import related functions
import os.path
import sys
try:
filename = input('Please enter the name of the file you want to get data from: ')
if not os.path.exists(filename):
print('Sorry, there is no such file.')
sys.exit()
except ValueError:
print('Sorry, there is no such file. ')
sys.exit()
# read the content of this file
with open(filename) as tunnel_input:
original_tunnel_sequence = tunnel_input.readlines()
# remove the '/n' in the original list
tunnel_sequence = []
for i in original_tunnel_sequence:
if not i == '\n':
tunnel_sequence.append(i)
#print(tunnel_sequence)
# identify how many lines this file have
#print('11111')
#print(len(tunnel_sequence))
if not len(tunnel_sequence) == 2:
print('Sorry, input file does not store valid data.')
sys.exit()
line1_sequence_tunnel = (tunnel_sequence[0]).split()
line2_sequence_tunnel = (tunnel_sequence[1]).split()
#print(line1_sequence_tunnel)
#print(line2_sequence_tunnel)
# identify the number of integers in two line is the same
# identify at least two integers
if len(line1_sequence_tunnel) != len(line2_sequence_tunnel) or len(line1_sequence_tunnel) < 2 :
print('Sorry, input file does not store valid data.')
sys.exit()
# identify the elements are all integers
for i in line2_sequence_tunnel + line2_sequence_tunnel:
if not i.isdigit():
print('Sorry, input file does not store valid data.')
sys.exit()
# identify line1[i] > line2[i]
# connected_sequence_tunnel = line1_sequence_tunnel + line2_sequence_tunnel
# for i in range(len(line2_sequence_tunnel)):
# if int(connected_sequence_tunnel[i]) < int(connected_sequence_tunnel[i+len(line2_sequence_tunnel)]):
# print('Sorry, input file does not store valid data.')
# sys.exit()
s1 = []
for i in line1_sequence_tunnel:
s1.append(int(i))
s2 = []
for i in line2_sequence_tunnel:
s2.append(int(i))
#print(s1)
#print(s2)
# identify line1[i] > line2[i]
for i in range(len(s1)):
if s1[i] <= s2[i]:
print('Sorry, input file does not store valid data.')
sys.exit()
def get_gap_list_in_s1s2(x):
gap = []
for i in range(s2[x],s1[x]):
gap.append(i)
return gap
#print('gap')
#print(get_gap_list_in_s1s2(0))
def get_index_when_tunnel_stop(element_in_gap,column):
for i in range(column + 1,len(s1)):
if element_in_gap < s1[i] and element_in_gap >= s2[i]:
if i == len(s1) - 1:
return len(s1)
continue
else:
return i
#print('i')
#print(get_index_when_tunnel_stop(6,0))
#print('i2')
#print(get_index_when_tunnel_stop(6,1))
#print('i3')
#print(get_index_when_tunnel_stop(6,10))
def all_get_index_when_tunnel_stop(column):
answer = []
for x in get_gap_list_in_s1s2(column):
answer.append(get_index_when_tunnel_stop(x,column))
return answer
# print(all_get_index_when_tunnel_stop(14))
all_distance = []
for column in range(len(s1)):
for e in all_get_index_when_tunnel_stop(column):
if e:
all_distance.append(str(e-column))
#print(get_gap_list_in_s1s2(2))
#print(all_get_index_when_tunnel_stop(2))
#print(all_distance)
#print(max(all_get_index_when_tunnel_stop(0)))
#print(max(all_distance))
print(f'From the west, one can see into the tunnel over a distance of {max(all_get_index_when_tunnel_stop(0))}.')
print(f'Inside the tunnel, one can see into the tunnel over a maximum distance of {max(all_distance)}.')
|
7b68a911b0858991b4e903ebb05e949fac93c0ba | thraddash/python_tut | /14_ojbect_oriented_programming/oop_golden.py | 479 | 3.90625 | 4 | #!/usr/bin/env python
# Class
# Global variable
restaurant_name = '7 Eleven'
restaurant_owner = 'Seven'
def restaurant_details(): #function
print(restaurant_name, restaurant_owner)
def another_restaurant(): #local variable
restaurant_address = 'Bogra'
print(restaurant_name, restaurant_owner)
print(restaurant_address)
restaurant_details()
another_restaurant()
# Syntax
'''
class ClassName(ParentClass): #inherit
class variables
instance methods
'''
|
d8d3aa87552863e71e5c60e0ac6ad2eb819e2af6 | roshanrobotics/python-program | /triangle.py | 282 | 4.15625 | 4 | a=float(input("Enter the first side: "))
b=float(input("Enter the second side: "))
c=float(input("Enter the third side: "))
if(a==b and a==c):
print("Equilateral triangle")
elif(a==b or a==c or b==c):
print("Isosceles triangle")
else:
print("Scalene triangle")
|
c152330bc581d592d7f4bccd2a940bf95ebfc7a2 | withinfinitedegreesoffreedom/datastructures-algorithms | /stacks-queues/stack_of_plates.py | 1,844 | 3.84375 | 4 | import unittest
class SetOfStacks:
def __init__(self,stack_capacity):
self.stack_capacity = stack_capacity
self.list = []
self.acting_stack = 1
def push(self, data):
self.list.append(data)
self.acting_stack = (self.length() // self.stack_capacity) + 1
return True
def pop(self):
if not self.is_Empty():
item = self.list.pop()
self.acting_stack = (self.length() // self.stack_capacity) + 1
return item
else:
raise IndexError("Empty stack")
def popAt(self, stack_num):
if stack_num == self.acting_stack:
return self.pop()
elif stack_num < self.acting_stack:
idx = (stack_num-1) * self.stack_capacity + (self.stack_capacity - 1)
item = self.list.pop(idx)
self.acting_stack = (self.length() // self.stack_capacity) + 1
return item
elif stack_num > self.acting_stack:
raise IndexError("Requested stack doesn't exist")
elif stack_num == 0:
raise ValueError("Stack number has to be > 0")
def length(self):
return len(self.list)
def is_Empty(self):
return self.length() == 0
class Test(unittest.TestCase):
def setUp(self):
self.stacks = SetOfStacks(4)
def test_setofstacks(self):
l = [1,2,3,4,5,6,7,8,9]
for item in l:
self.stacks.push(item)
self.assertEqual(self.stacks.acting_stack, (len(self.stacks.list)//self.stacks.stack_capacity)+1)
self.assertEqual(self.stacks.pop(), 9)
self.assertEqual(self.stacks.popAt(1), 4)
self.assertTrue(self.stacks.push(11))
#print(self.stacks.list)
self.assertEqual(self.stacks.popAt(2), 11)
if __name__=="__main__":
unittest.main() |
2e5c76ea8a3b5c3fca75619d1761ef5c8bda693a | mathvolcano/leetcode | /0082_deleteDuplicates.py | 1,001 | 3.5 | 4 | """
82. Remove Duplicates from Sorted List II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if (not head) or (not head.next): return head
result = ListNode(0)
result.next = head
no_dups = result
ahead = result.next
# Check if the next value is distinct and iterate
while no_dups.next:
# Advance ahead to last dup
while ahead.next and (no_dups.next.val == ahead.next.val):
ahead = ahead.next
# If different nodes then advance
if no_dups.next == ahead:
ahead = ahead.next
no_dups = no_dups.next
else: # step to same next node
no_dups.next = ahead.next
return result.next
|
e28d1ee207e754bdd522165718622637424c2dd1 | armstrong019/coding_n_project | /Jiuzhang_practice/subsets2.py | 659 | 3.734375 | 4 |
class Solution:
"""
@param nums: A set of numbers
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, nums):
nums.sort()
self.nums = nums
self.res = []
self.dfs(0, [])
return self.res
def dfs(self, index, combination):
if combination not in self.res:
self.res.append(list(combination))
# if index==len(nums): # there is no difference adding this sentence
# return
for i in range(index, len(self.nums)):
combination.append(self.nums[i])
self.dfs(i + 1, combination)
combination.pop()
|
2781caeb906a73e6dd3db0330d43409a0775d3bb | rifoolaw/techcamp-raspi | /PiCameraMenuTkS/pcmtks_exec.py | 1,530 | 3.984375 | 4 | print "Importing stuff..."
import time
import picamera
import pcmtks
print "done. Welcome to PiCamera Menu!\n\n"
while True:
print "Welcome to the PiCamera Menu! With this, you can take photos and more with your PiCamera!"
print "To make it work, use the commands down here."
print "PreviewIt: displays what PiCamera sees for 10 seconds."
print "PreviewTake: displays what PiCamera sees for 5 seconds, and then takes a photo."
print "PiTakeScale: Preview, take a photo and scale it basing on user preference!"
print "RecordMe: Want to take a video? This is for you! (videos are in 640 * 480)"
what = raw_input("")
if what == "PreviewIt":
pcmtks.PreviewIt()
elif what == "PreviewTake":
destination = raw_input("We'll save the file in the Downloads folder. How you you want to call your file? ")
pcmtks.PreviewTake(destination)
elif what == "PiTakeScale":
destination = raw_input("We'll save the file in the Downloads folder. How you you want to call your file? ")
scale = raw_input("The image should be scaled by?")
if scale.type() == float or scale.type() == int:
pcmtks.PiTakeScale(destination, scale)
else:
print "You insterted a string instead of a number on scale!"
elif what == "RecordMe":
destination = raw_input("We'll save the file in the Downloads folder. How you you want to call your file? ")
leng = raw_input("How long should your video be?")
RecordMe(destination, leng) |
4256e77254d38cdca7e3402146b32e586ca7adad | ulyssesorz/data-structures | /tree/二叉平衡树AVL.py | 6,893 | 4 | 4 | class Queue: #用于层次遍历
def __init__(self):
self.data = []
self.head = 0
self.tail = 0
def isEmpty(self):
return self.head == self.tail
def push(self,data):
self.data.append(data)
self.tail = self.tail + 1
def pop(self):
temp = self.data[self.head]
self.head = self.head + 1
return temp
def count(self):
return self.tail - self.head
def print(self):
print(self.data)
print("**************")
print(self.data[self.head:self.tail])
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
self.height=1
def getdata(self):
return self.data
def getleft(self):
return self.left
def getright(self):
return self.right
def getheight(self):
return self.height
def setdata(self,data):
self.data = data
return
def setleft(self,left):
self.left = left
return
def setright(self,right):
self.right=right
return
def setheight(self,height):
self.height=height
return
def getheight(node):
if node is None:
return 0
return node.getheight()
def max(a,b):
return a if a>b else b
def leftrotation(node):
ret=node.getleft()
node.setleft(ret.getright())
ret.setright(node)
h1=max(getheight(node.getleft()),getheight(node.getright()))+1
node.setheight(h1)
h2=max(getheight(ret.getleft()),getheight(ret.getright()))+1
ret.setheight(h2)
return ret
def rightrotation(node):
ret=node.getright()
node.setright(ret.getleft())
ret.setleft(node)
h1=max(getheight(node.getleft()),getheight(node.getright()))+1
node.setheight(h1)
h2=max(getheight(ret.getleft()),getheight(ret.getright()))+1
ret.setheight(h2)
return ret
def rlrotation(node): #子树左旋,根右旋
node.setleft(rightrotation(node.getleft()))
return leftrotation(node)
def lrrotation(node):
node.setright(leftrotation(node.getright()))
return rightrotation(node)
def insert(node,data):
if node is None:
return Node(data)
if data < node.getdata():
node.setleft(insert(node.getleft(),data))
if getheight(node.getleft())-getheight(node.getright())==2:
if data<node.getleft().getdata(): #通过和根节点的左右子节点比较大小,得出新节点在左(右)子节点的左部分还是右部分
node=leftrotation(node)
else:
node=rlrotation(node)
r"""
第一种情况:图2,F在B的左部分,直接右旋即可,第二种情况,图1,F在B右部分,执行rl
A A
/ \ / \
B C B C
/ \ / \
D E D E
\ /
F F
"""
else:
node.setright(insert(node.getright(),data))
if getheight(node.getright())-getheight(node.getleft())==2:
if data<node.getright().getdata():
node=lrrotation(node)
else:
node=rightrotation(node)
h=max(getheight(node.getleft()),getheight(node.getright()))+1
node.setheight(h)
return node
def getmin(node):
while node.getleft() is not None:
node=node.getleft()
return node.getdata()
def delete(node,data):
if data==node.getdata():
if node.getleft() is not None and node.getright() is not None: #这组if-else用于删除相应节点,并保持搜索二叉树的特点,但未必平衡
temp=getmin(node.getright())
node.setdata(temp)
node.setright(delete(node.getright(),temp))
elif node.getleft() is not None:
node=node.getleft()
else:
node=node.getright()
elif data>node.getdata():
if node.getright() is None:
return node
else:
node.setright(delete(node.getright(),data))
else:
if node.getleft() is None:
return node
else:
node.setleft(delete(node.getleft(),data))
if node is None: #这组if-else用于维持二叉树平衡,原理和insert相同
return node
elif getheight(node.getleft())-getheight(node.getright())==2:
if getheight(node.getleft().getleft())>getheight(node.getleft().getright()):
node=leftrotation(node)
else:
node=rlrotation(node)
elif getheight(node.getleft())-getheight(node.getright())==-2:
if getheight(node.getright().getleft())>getheight(node.getright().getright()):
node=lrrotation(node)
else:
node=rightrotation(node)
h=max(getheight(node.getleft()),getheight(node.getright()))+1
node.setheight(h)
return node
class AVLtree:
def __init__(self):
self.root=None
def length(self):
return getheight(self.root)
def isempty(self):
return self.length()==0
def insert(self,data):
self.root=insert(self.root,data)
def delete(self,data):
if self.root is None:
print('Empty tree')
else:
self.root=delete(self.root,data)
def traversal(self): #层次遍历,以树状输出
q = Queue()
q.push(self.root)
layer = self.length()
if layer == 0:
return
cnt = 0
while not q.isEmpty():
node = q.pop()
space = " " * int(pow(2, layer - 1))
print(space, end="")
if node is None:
print("*", end="")
q.push(None)
q.push(None)
else:
print(node.getdata(), end="")
q.push(node.getleft())
q.push(node.getright())
print(space, end="")
cnt = cnt + 1
for i in range(100):
if cnt == pow(2, i) - 1:
layer = layer - 1
if layer == 0:
print()
print("*************************************")
return
print()
break
print()
print("*************************************")
return
if __name__ == "__main__":
t = AVLtree()
list=[144,32,6,78,45,43]
for i in list:
t.insert(i)
t.traversal()
t.insert(2)
t.insert(1)
t.traversal()
t.delete(144)
t.traversal()
|
ad8378973c531ef5ac0d45afc90507ec09b20c45 | kennycaiguo/Heima-Python-2018 | /00-2017/基础班/设计蛋糕店类-工厂模式.py | 726 | 3.9375 | 4 | #coding=utf-8
class Cake(object):
def __init__(self,taste="默认"):
self.taste = taste
class AppleCake(object):
def __init__(self,taste="苹果味"):
self.taste = taste
class BananaCake(object):
def __init__(self,taste="香蕉味"):
self.taste = taste
class CakeKitchen(object):
def createCake(self, taste):
if taste == "苹果":
cake= AppleCake()
elif taste == "香蕉":
cake = BananaCake()
elif taste == "默认":
cake = Cake()
return cake
class CakeStore(object):
def __init__(self):
self.kitchen = CakeKitchen()
def taste(self,taste):
cake = self.kitchen.createCake(taste)
print("-----味道:%s-----"%cake.taste)
a = CakeStore()
a.taste("苹果")
a.taste("香蕉")
a.taste("默认") |
d41f5482258ede8a2a517ebb5c153555825a2bc6 | VerstraeteBert/algos-ds | /test/vraag4/src/isbn/168.py | 1,412 | 3.515625 | 4 | def isISBN_13(code):
if type(code) is not str:
return False
if len(code) != 13:
return False
try:
oneven = 0
i = 0
while i < 11:
oneven += int(code[i])
i += 2
even = 0
i = 1
while i < 12:
even += int(code[i])
i += 2
if int(code[12]) == (10-(oneven + 3*even)%10)%10:
return True
return False
except ValueError:
return False
def overzicht(lijst):
f = 0
en = 0
fr = 0
ru = 0
du = 0
ch = 0
jap = 0
ov = 0
for el in lijst:
if not isISBN_13(el):
f += 1
elif int(el[0:3]) != 978 and int(el[0:3]) != 979:
f += 1
else:
land = int(el[3])
if land == 0 or land == 1:
en += 1
elif land == 2:
fr += 1
elif land == 3:
du += 1
elif land == 4:
jap += 1
elif land == 5:
ru += 1
elif land == 7:
ch += 1
else:
ov += 1
print('Engelstalige landen:', en)
print('Franstalige landen:', fr)
print('Duitstalige landen:', du)
print('Japan:', jap)
print('Russischtalige landen:', ru)
print('China:', ch)
print('Overige landen:', ov)
print('Fouten:', f) |
8699c0036e3bb634217d09f0f93ec6ab18fd7ea3 | BohanHsu/developer | /python/classes/classInheritance.py | 756 | 4.40625 | 4 | # in this file we study inheritance in python
#define the super class ClassA
class ClassA:
def doing(self):
print('I\'m class A')
class ClassB(ClassA):
def doing(self):
print('I\'m class B')
class ClassC:
def __init__(self,a):
self.a = a
def getA(self):
return self.a
class ClassD(ClassC):
def __init__(self):
pass
# method override in derived class
a1 = ClassA()
b1 = ClassB()
a1.doing()
b1.doing()
# calling super class's method in derived class
ClassA.doing(b1)
# if super class only provide a initialize method with one arguments.
# and derived class not calling this method explicitly, what will happen?
d1 = ClassD()
print(d1.getA())
# AttributeError: 'ClassD' object has no attribute 'a'
# 'a' is dynamic declared!!!!!
|
549c511ebc159d13b651c525560db6c9e0db9cd4 | zcarc/algorithm | /Programmers/level1/소수 만들기_라이브러리.py | 401 | 3.734375 | 4 | import itertools
def solution(nums):
nums = list(itertools.combinations(nums, 3))
def is_prime(n):
for i in range(2, int(n ** (1 / 2)) + 1):
if n % i == 0:
return False
return True
answer = 0
for e in nums:
if is_prime(sum(e)):
answer += 1
return answer
print(solution([1,2,3,4]))
print(solution([1,2,7,6,4])) |
a7c55eb5e0b255baa0cb69574914bfa59d348808 | pedro-puerta/PYTHON-2021-01 | /exemplos POO 3.py | 799 | 3.640625 | 4 | '''
Criar uma classe Aluno
- Atributos: ra, nome, email, lista de notas.
- Métodos: inserir_nota, calcular_media
'''
class Aluno:
def __init__(self, ra, nome, email): # construtor
# atributos
self.ra = ra
self.nome = nome
self.email = email
self.lista_notas = [] # inicializa com uma lista vazia
# Métodos
def inserir_nota(self, nota):
self.lista_notas.append(nota)
def calcular_media(self):
media = sum(self.lista_notas) / len(self.lista_notas)
return media
# cria objeto
aluno1 = Aluno(1111111, 'Paulo', 'paulo@email.com')
# insere notas
aluno1.inserir_nota(9.5)
aluno1.inserir_nota(7)
aluno1.inserir_nota(8.5)
# calcula a media
print('Média: ', aluno1.calcular_media())
|
0f50cef78a3fce80dc1bff474a59ae2dc4942af8 | jonathan-taylor/formula | /formula/sympy_utils.py | 1,764 | 3.703125 | 4 | import sympy
def getparams(expression):
""" Return the parameters of an expression that are not Term
instances but are instances of sympy.Symbol.
Examples
--------
>>> x, y, z = [Term(l) for l in 'xyz']
>>> f = Formula([x,y,z])
>>> getparams(f)
[]
>>> f.mean
_b0*x + _b1*y + _b2*z
>>> getparams(f.mean)
[_b0, _b1, _b2]
>>>
>>> th = sympy.Symbol('theta')
>>> f.mean*sympy.exp(th)
(_b0*x + _b1*y + _b2*z)*exp(theta)
>>> getparams(f.mean*sympy.exp(th))
[theta, _b0, _b1, _b2]
"""
atoms = set([])
expression = np.array(expression)
if expression.shape == ():
expression = expression.reshape((1,))
if expression.ndim > 1:
expression = expression.reshape((np.product(expression.shape),))
for term in expression:
atoms = atoms.union(sympy.sympify(term).atoms())
params = []
for atom in atoms:
if isinstance(atom, sympy.Symbol) and not is_term(atom):
params.append(atom)
params.sort()
return params
def getterms(expression):
""" Return the all instances of Term in an expression.
Examples
--------
>>> x, y, z = [Term(l) for l in 'xyz']
>>> f = Formula([x,y,z])
>>> getterms(f)
[x, y, z]
>>> getterms(f.mean)
[x, y, z]
"""
atoms = set([])
expression = np.array(expression)
if expression.shape == ():
expression = expression.reshape((1,))
if expression.ndim > 1:
expression = expression.reshape((np.product(expression.shape),))
for e in expression:
atoms = atoms.union(e.atoms())
terms = []
for atom in atoms:
if is_term(atom):
terms.append(atom)
terms.sort()
return terms
|
45c9941345fe881d7ea0c55f1f2b0aada207b4a7 | JGraff2821/JuniorDesign | /interviewQ3.py | 1,257 | 4.21875 | 4 | from random import uniform
from typing import Tuple
# Function gives a random coordinate within a circle of radius one.
def random_coordinate() -> Tuple[float, float]:
return uniform(0, 1), uniform(0, 1)
def calculate_pi(number_of_points: int):
# Variable to track in/out of circle.
points_in_circle: int = 0
for point in range(number_of_points):
# Find a point, within the given quadrant
new_point = random_coordinate()
# Check to see if that point is within the circle.
# This is done by using the distance formula (in circle if distance is less than equal one)
in_circle = new_point[0] * new_point[0] + new_point[1] * new_point[1] <= 1
# Keep track of which points are in, which are out.
if in_circle:
points_in_circle += 1
# Points in divided by the total points is an estimate of the area of the quarter circle divided by the area of
# the quadrant (in/total) estimates to (PI/4 *r^2)/(r^2) **Side length of square is r.
points_in_over_total: float = points_in_circle/number_of_points
# from algebra, PI estimates to 4(in/out)
pi: float = 4*points_in_over_total
return pi
if __name__ == '__main__':
print(calculate_pi(10000000))
|
7ae7fb7bff259c14a2e51e4c819b6b5ea8636287 | nicehiro/LeetCode | /divide.py | 930 | 3.640625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
prefix = 1
if (dividend < 0 and divisor > 0) or\
(dividend > 0 and divisor < 0):
prefix = -1
dividend = abs(dividend)
divisor = abs(divisor)
res = 0
while dividend >= divisor:
r, dividend = self.divide_iter(dividend, divisor)
res += r
if prefix < 0:
res = ~res + 1
if res < - 2 ** 31:
return - 2 ** 31
if res > 2 ** 31 - 1:
return 2 ** 31 - 1
return res
def divide_iter(self, dividend, divisor):
res = 0
i = 1
while dividend >= divisor:
res += i
dividend -= divisor
divisor += divisor
i += i
return res, dividend
if __name__ == '__main__':
s = Solution()
print(s.divide(-10, 1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.