blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ebb48ef97e31747fd970e26e24d374e1e53b8a50 | codesurvivor/kyupy | /kyupy/circuit.py | 9,133 | 3.78125 | 4 | from collections import deque
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None] * (index + 1 - len(self)))
super().__setitem__(index, value)
class IndexList(list):
def __delitem__(self, index):
if index == len(self) - 1:
super().__delitem__(index)
else:
replacement = self.pop()
replacement.index = index
super().__setitem__(index, replacement)
class Node:
"""A Node is a named entity in a circuit (e.g. a gate, a standard cell,
a named signal, or a fan-out point) that has connections to other nodes.
Each node contains:
* `self.index`: a circuit-unique integer index.
* `self.kind`: a type describing its function (e.g. 'AND', 'NOR').
The type '__fork__' is special. It signifies a named signal
or a fan-out in the circuit. Any other type is considered a physical cell.
* `self.name`: a name. Names must be unique among all forks and all cells
in the circuit. However, a fork (`self.kind=='__fork__'`) and a cell with
the same name may coexist.
* `self.ins`: a list of input connections (objects of class `Line`)
* `self.outs`: a list of output connections (objects of class `Line`).
"""
def __init__(self, circuit, name, kind='__fork__'):
if kind == '__fork__':
if name in circuit.forks:
raise ValueError(f'fork of name {name} already exists.')
circuit.forks[name] = self
else:
if name in circuit.cells:
raise ValueError(f'cell of name {name} already exists.')
circuit.cells[name] = self
self.index = len(circuit.nodes)
circuit.nodes.append(self)
self.circuit = circuit
self.name = name
self.kind = kind
self.ins = GrowingList()
self.outs = GrowingList()
def __repr__(self):
ins = ' '.join([f'<{line.index}' if line is not None else '<None' for line in self.ins])
outs = ' '.join([f'>{line.index}' if line is not None else '>None' for line in self.outs])
return f'{self.index}:{self.kind}"{self.name}" {ins} {outs}'
def remove(self):
if self.circuit is not None:
del self.circuit.nodes[self.index]
if self.kind == '__fork__':
del self.circuit.forks[self.name]
else:
del self.circuit.cells[self.name]
self.circuit = None
class Line:
"""A Line is a directional 1:1 connection between two Nodes. It always
connects an output of a node (called `driver`) to an input of a node
(called `reader`) and has a circuit-unique index (`self.index`).
Furthermore, `self.driver_pin` and `self.reader_pin` are the
integer indices of the connected pins of the nodes. They always correspond
to the positions of the line in the connection lists of the nodes:
* `self.driver.outs[self.driver_pin] == self`
* `self.reader.ins[self.reader_pin] == self`
A Line always connects a single driver to a single reader. If a signal fans out to
multiple readers, a '__fork__' Node needs to be added.
"""
def __init__(self, circuit, driver, reader):
self.index = len(circuit.lines)
circuit.lines.append(self)
if type(driver) is Node:
self.driver = driver
self.driver_pin = len(driver.outs)
for pin, line in enumerate(driver.outs):
if line is None:
self.driver_pin = pin
break
else:
self.driver, self.driver_pin = driver
if type(reader) is Node:
self.reader = reader
self.reader_pin = len(reader.ins)
for pin, line in enumerate(reader.ins):
if line is None:
self.reader_pin = pin
break
else:
self.reader, self.reader_pin = reader
self.driver.outs[self.driver_pin] = self
self.reader.ins[self.reader_pin] = self
def remove(self):
circuit = None
if self.driver is not None:
self.driver.outs[self.driver_pin] = None
circuit = self.driver.circuit
if self.reader is not None:
self.reader.ins[self.reader_pin] = None
circuit = self.reader.circuit
if circuit is not None:
del circuit.lines[self.index]
self.driver = None
self.reader = None
def __repr__(self):
return f'{self.index}'
def __lt__(self, other):
return self.index < other.index
class Circuit:
"""A Circuit is a container for interconnected nodes and lines.
All contained lines have unique indices, so have all contained nodes.
These indices can be used to store additional data about nodes or lines
by allocating an array `my_data` of length `len(self.nodes)` and then
accessing it by `my_data[n.index]`. The indices may change iff lines or
nodes are removed from the circuit.
Nodes come in two flavors (cells and forks, see `Node`). The names of
these nodes are kept unique within these two flavors.
"""
def __init__(self, name=None):
self.name = name
self.nodes = IndexList()
self.lines = IndexList()
self.interface = GrowingList()
self.cells = {}
self.forks = {}
def get_or_add_fork(self, name):
return self.forks[name] if name in self.forks else Node(self, name)
def copy(self):
c = Circuit(self.name)
for node in self.nodes:
Node(c, node.name, node.kind)
for line in self.lines:
d = c.forks[line.driver.name] if line.driver.kind == '__fork__' else c.cells[line.driver.name]
r = c.forks[line.reader.name] if line.reader.kind == '__fork__' else c.cells[line.reader.name]
Line(c, (d, line.driver_pin), (r, line.reader_pin))
for node in self.interface:
if node.kind == '__fork__':
n = c.forks[node.name]
else:
n = c.cells[node.name]
c.interface.append(n)
return c
def dump(self):
header = f'{self.name}({",".join([str(n.index) for n in self.interface])})\n'
return header + '\n'.join([str(n) for n in self.nodes])
def __repr__(self):
name = f" '{self.name}'" if self.name else ''
return f'<Circuit{name} with {len(self.nodes)} nodes, {len(self.lines)} lines, {len(self.interface)} ports>'
def topological_order(self):
visit_count = [0] * len(self.nodes)
queue = deque(n for n in self.nodes if len(n.ins) == 0 or 'DFF' in n.kind)
while len(queue) > 0:
n = queue.popleft()
for line in n.outs:
if line is None: continue
succ = line.reader
visit_count[succ.index] += 1
if visit_count[succ.index] == len(succ.ins) and 'DFF' not in succ.kind:
queue.append(succ)
yield n
def topological_line_order(self):
for n in self.topological_order():
for line in n.outs:
if line is not None:
yield line
def reversed_topological_order(self):
visit_count = [0] * len(self.nodes)
queue = deque(n for n in self.nodes if len(n.outs) == 0 or 'DFF' in n.kind)
while len(queue) > 0:
n = queue.popleft()
for line in n.ins:
pred = line.driver
visit_count[pred.index] += 1
if visit_count[pred.index] == len(pred.outs) and 'DFF' not in pred.kind:
queue.append(pred)
yield n
def fanin(self, origin_nodes):
marks = [False] * len(self.nodes)
for n in origin_nodes:
marks[n.index] = True
for n in self.reversed_topological_order():
if not marks[n.index]:
for line in n.outs:
if line is not None:
marks[n.index] |= marks[line.reader.index]
if marks[n.index]:
yield n
def fanout_free_regions(self):
for stem in self.reversed_topological_order():
if len(stem.outs) == 1 and 'DFF' not in stem.kind: continue
region = []
if 'DFF' in stem.kind:
n = stem.ins[0]
if len(n.driver.outs) == 1 and 'DFF' not in n.driver.kind:
queue = deque([n.driver])
else:
queue = deque()
else:
queue = deque(n.driver for n in stem.ins
if len(n.driver.outs) == 1 and 'DFF' not in n.driver.kind)
while len(queue) > 0:
n = queue.popleft()
preds = [pred.driver for pred in n.ins
if len(pred.driver.outs) == 1 and 'DFF' not in pred.driver.kind]
queue.extend(preds)
region.append(n)
yield stem, region
|
d474c2ba8be218314f73b30b142e1b86613ed11d | TestID22/rip_nec0der | /BrainFuck.py | 2,056 | 3.53125 | 4 | def block(code):
opened = []
blocks = {}
for i in range(len(code)):
if code[i] == '[':
opened.append(i)
elif code[i] == ']':
blocks[i] = opened[-1]
blocks[opened.pop()] = i
return blocks
def parse(code):
return ''.join(c for c in code if c in '><+-.,[]')
def encode(data):
glyphs = len(set([c for c in data]))
number_of_bins = max(max([ord(c) for c in data]) // glyphs,1)
bins = [(i + 1) * number_of_bins for i in range(glyphs)]
code="+" * number_of_bins + "["
code+="".join([">"+("+"*(i+1)) for i in range(1,glyphs)])
code+="<"*(glyphs-1) + "-]"
code+="+" * number_of_bins
current_bin=0
for char in data:
new_bin=[abs(ord(char)-b)for b in bins].index(min([abs(ord(char)-b)for b in bins]))
appending_character=""
if new_bin-current_bin>0:
appending_character=">"
else:
appending_character="<"
code+=appending_character * abs(new_bin-current_bin)
if ord(char)-bins[new_bin]>0:
appending_character="+"
else:
appending_character="-"
code+=(appending_character * abs( ord(char)-bins[new_bin])) +"."
current_bin=new_bin
bins[new_bin]=ord(char)
return code
def run(code):
code = parse(code)
x = i = 0
bf = {0: 0}
blocks = block(code)
l = len(code)
r = ''
while i < l:
sym = code[i]
if sym == '>':
x += 1
bf.setdefault(x, 0)
elif sym == '<':
x -= 1
elif sym == '+':
bf[x] += 1
elif sym == '-':
bf[x] -= 1
elif sym == '.':
#print(chr(bf[x]), end='')
r += str(chr(bf[x]))
# elif sym == ',':
# bf[x] = int(input('Input: '))
elif sym == '[':
if not bf[x]: i = blocks[i]
elif sym == ']':
if bf[x]: i = blocks[i]
i += 1
return r |
c954b3d5067de813172f46d1ce5b610a5adc6317 | LL-Pengfei/cpbook-code | /ch2/vector_arraylist.py | 421 | 4.125 | 4 | def main():
arr = [7, 7, 7] # Initial value [7, 7, 7]
print("arr[2] = {}".format(arr[2])) # 7
for i in range(3):
arr[i] = i;
print("arr[2] = {}".format(arr[2])) # 2
# arr[5] = 5; # index out of range error generated as index 5 does not exist
# uncomment the line above to see the error
arr.append(5) # list will resize itself after appending
print("arr[3] = {}".format(arr[3])) # 5
main() |
9a19d8a9baea1b461e4db02364113fae3d367297 | guojiangwei/myLeetCode | /py/88.合并两个有序数组.py | 1,826 | 3.515625 | 4 | #
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# @lc code=start
class Solution:
# 将nums2拷贝给nums1
# 排序nums1
# 此方法有点取巧
# 32ms 97% 56% 13.4MB
def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
for i in range(m,len(nums1)):
nums1[i] = nums2[i-m]
nums1.sort()
# * 1,将nums1中的元素拷贝到临时数组
# * 2,用两个指针分别指向临时数组和数组二,谁的元素小就把谁拷贝到数组一,并移动指针
# * 3,根据指针位置判断临时数组和数组二剩余的元素,并全部拷贝到nums1
# 48ms 23% 71% 13.3MB
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
tmp = nums1[:]
i,j=0,0
while i<m and j<n:
if tmp[i] < nums2[j]:
nums1[i+j] = tmp[i]
i += 1
else:
nums1[i+j] = nums2[j]
j += 1
for i1 in range(i,m):
nums1[i1+j] = tmp[i1]
for i1 in range(j,n):
nums1[i1+i] = nums2[i1]
# * 1,题目以及假设nums1 长度有m+2
# * 2,将nums1的数字全部拷贝到数组尾部,nums1的前n个元素可以直接覆盖
# * 3,从nums1的第n个元素跟nums第一个元素开始比对
# 44ms 50% 94% 13.2MB
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
i,j = m-1,n-1
while j >=0 :
if i>= 0 and nums1[i] > nums2[j]:
nums1[i+j+1] = nums1[i]
i -= 1
else:
nums1[i+j+1] = nums2[j]
j -= 1
# @lc code=end
|
57c08dccb6e36f1116e3c23529459c8e15b83ef9 | jfblanchard/optical-calculations | /optical_calcs.py | 5,662 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
A module containing a number of functions used for performing common
optical calculations
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as const
import seaborn as sns
sns.set_style('whitegrid')
def diff_limited_spot(wavelength, f,D):
"""Compute the diffraction limited spot size achievable by a lens of
focal length f, wavelength lambda, and collimated input beam diameter D.
Units must match, and will return same in units.
Parameters
----------
wavelength : float
The wavelength in microns
f : float
The focal length of the lens
D: float
The diameter of the collimated input beam
Returns
-------
d: the diffraction limited spot size
"""
d = (4*wavelength*f)/(np.pi*D)
return d
def fnum(efl,diameter):
"""Compute the F-number from the efl and diameter. Both have to be the
same units.
Parameters
----------
efl : float
The focal length of the lens
diameter : float
The diameter of the input beam (in the same units as efl)
Returns
-------
fnum : float
The fnumber of the system
"""
fnum = efl/diameter
return fnum
def half_angle_from_NA(na, n=1,deg=True):
"""Compute the half angle of the cone of light from the NA value. From
the equation NA = n x sin(theta).
Parameters
----------
na : float
The numerical aperture
n : float (optional)
The index of the material. Default is 1.0 (air)
deg : bool (optional)
Return result in degrees or radians. Default is degrees.
Returns
-------
theta : float
The half angle of the cone of light in degrees
"""
if deg==True:
theta = np.rad2deg(np.arcsin(na/n))
else:
theta = np.arcsin(na/n)
return theta
def snells_law(n1,n2,theta1):
"""Compute the refracted ray angle (theta2) from index1,index2,
and angle in (theta1). Angle must be in the range -90 to 90 deg
Parameters
----------
n1 : float
Index of medium for the entering ray
n2 : float
Index of the medium the ray is entering into.
theta1 : float
Incident ray angle (degrees) measured from normal to the surface
Returns
-------
theta2 : float
The exiting angle of the ray after refraction (in degress),
measured from the surface normal.
"""
#need check for within -90 to 90 range, and handle it gracefully
theta1rad = np.deg2rad(theta1)
theta2rad = np.arcsin((n1/n2)*np.sin(theta1rad))
theta2 = np.rad2deg(theta2rad)
return theta2
def fresnel_refl(n1,n2,theta_i):
""" Compute the fresnel reflections at a dielectric surface with incident
index n1, and entering index n2, with incident angle theta_i (in radians).
Returns both the S and P polarized reflections.
"""
sterm1 = n1 * np.cos(theta_i)
sterm2 = n2*np.sqrt(1 - ((n1/n2)*np.sin(theta_i))**2)
Rs = ((sterm1 - sterm2)/(sterm1 + sterm2))**2
pterm1 = n2*np.cos(theta_i)
pterm2 = n1*np.sqrt(1 - ((n1/n2)*np.sin(theta_i))**2)
Rp = ((pterm2 - pterm1)/(pterm2 + pterm1))**2
#tested with 0 deg incidence, correct at 4% Reflection
#T = 1 - R
return Rs,Rp
def braggs_law():
"""Bragg's Law - unimplemented"""
pass
def irradiance(power,diameter,units='mm'):
"""Compute the irradiance (power per unit area 'W/cm*2') on a surface.
Parameters
----------
power : float
Power in watts
diameter : float
Spot size diameter in mm (default)
units : String (optinal)
units, valid = m,mm,um,nm
Returns
-------
irrad : float
The irradiance impinging on the surface in W/cm**2
"""
if units == 'mm':
d = .1*diameter
area = np.pi * d
irr = power/area
return irr
def newton_wedge_fringe_sep(alpha, wavelength):
"""Calculate the separation between fringes for an optical flat with angle
alpha."""
d = wavelength/(2*np.sin(alpha))
return d
def sag_depth(R,h):
""" Calculate sag depth of a shphere at height h. """
if np.abs(h) > np.abs(R):
print('height must be less than the raduis')
return
else:
theta = np.arcsin(h/R)
sag = R*(1-np.cos(theta))
return sag
def abbe_number(nd, nF, nC):
""" Compute the Abbe number (reciprocal dispersion). Using the visible F,
d, and C lines:
F(H): 486.1 nm
d(He): 587.6 nm
C(H): 656.3 nm
nd, nF, and nC are the refractive indicies at each of these three lines.
Todo: Alternately, select a glass type and compute these three n's.
"""
V = (nd - 1)/(nF - nC)
return V
if __name__ == "__main__":
#test some functions here
#test fresnel
theta = np.linspace(0,np.pi/2,100)
Rs,Rp = fresnel_refl(1,1.5,theta)
plt.figure()
plt.plot(np.rad2deg(theta),Rs, label = 'Rs')
plt.plot(np.rad2deg(theta),Rp, label = 'Rp')
plt.title('Fresenel Reflection vs. Angle of incidence')
plt.xlabel('Angle (deg)')
plt.ylabel('Reflection')
plt.legend()
plt.show()
|
147fc69a868a4dc3e73f317d70596f2a74cb4457 | xiaochenchen-PITT/CC150_Python | /Leetcode/Pascal's Triangle II.py | 488 | 3.5625 | 4 | class Solution:
# @return a list of integers
def getRow(self, rowIndex, pas = [1]):
'''hint: only O(N) extra space, meaning storing from 0th to nth lists is not allowed.'''
if len(pas)-1 == rowIndex:
return pas
next_pas = [1]
for i in range(0, len(pas)):
if i == len(pas)-1:
next_pas.append(1)
else:
next_pas.append(pas[i+1]+pas[i])
return self.getRow(rowIndex, next_pas)
|
fdb3b91793bf1541e2216b8f0384f6ee111983c4 | xiaochenchen-PITT/CC150_Python | /Leetcode/Search in Rotated Sorted Array_return boolean.py | 682 | 3.75 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
if len(A) < 3:
return True if target in A else False
mid = (len(A)-1) / 2
if A[0] < A[mid]: # left sorted
if target >= A[0] and target < A[mid]:
new_A = A[:mid+1]
else:
new_A = A[mid:]
else: # right sorted
if target > A[mid] and target <= A[-1]:
new_A = A[mid:]
else:
new_A = A[:mid+1]
return self.search(new_A, target)
s = Solution()
print s.search([1,3,5], 2) |
039e8c37b1c95e7659c109d2abbef9b697e7ca3d | xiaochenchen-PITT/CC150_Python | /Design_Patterns/Factory.py | 2,731 | 4.78125 | 5 | '''The essence of Factory Design Pattern is to "Define a factory creation
method(interface) for creating objects for different classes.
And the factory instance is to instantiate other class instances.
The Factory method lets a class defer instantiation to subclasses."
Key point of Factory Design Pattern is--
Only when inheritance is involved is factory method pattern.
'''
class Button(object):
"""class Button has 3 subclasses Image, Input and Flash."""
def __init__(self):
self.string = ''
def GetString(self):
return self.string
class Image(Button):
"""docstring for Image"""
def __init__(self):
self.string = 'string for Image.'
class Input(Button):
"""docstring for Input"""
def __init__(self):
self.string = 'string for Input.'
class Flash(Button):
"""docstring for Flash"""
def __init__(self):
self.string = 'string for Flash.'
class ButtonFactory:
"""ButtonFactory is the Factory class for Button, its instance is to
instantiate other button class instances"""
buttons = {'image': Image, 'input': Input, 'flash': Flash} # value is class
def create_button(self, typ):
return self.buttons[typ]() # () is for instantiating class !!!
# eg. s = Solution()
button_obj = ButtonFactory() # Factory instance is for instantiating other class
for b in button_obj.buttons:
print button_obj.create_button(b).GetString()
# print button_obj.buttons['image']
# print Flash
'''Another example/way for Factory design pattern.
Blackjack cards example.
'''
class CardFactory: # Factory class
def Newcard(self, rank, suit):
if rank == 1:
return ACE(rank, suit)
elif rank in [11, 12, 13]:
return FaceCard(rank, suit)
else:
return Card(rank, suit)
class Deck:
def __init__(self, ):
factory = CardFactory()
self.cards = [factory.Newcard(rank + 1, suit) for suit in ['Spade', 'Heart', 'Club', 'Diamond'] for rank in range(13)]
# Above is a huge list comprehesive!!
class Card:
"""Base class: Normal card"""
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
self.val = rank
def __str__(self):
return '{1} {0}'.format(self.rank, self.suit)
def GetSoftvalue(self):
return self.val
def GetHardvalue(self):
return self.val
class ACE(Card):
def __init__(self, rank, suit):
Card.__init__(self, rank, suit)
def __str__(self):
return '{1} {0}'.format('A', self.suit)
def GetSoftvalue(self):
return 11
def GetHardvalue(self):
return 1
class FaceCard(Card):
"""J, Q, K."""
def __init__(self, rank, suit):
Card.__init__(self, rank, suit)
self.val = 10
def __str__(self):
label = ('J', 'Q', 'K')[self.rank - 11]
return '{1} {0}'.format(label, self.suit)
deck = Deck()
for card in deck.cards:
print card
|
0d51133b3bdbcb43ffd745eeb543c357ff5a4faa | xiaochenchen-PITT/CC150_Python | /Design_Patterns/MVC.py | 2,175 | 4.03125 | 4 | import Tkinter as tk
class Observable:
"""class Observable defines the infrastructure of
model/view register and notification"""
def __init__(self, InitialValue = 0):
self.data = InitialValue
self.observer_list = []
def RegisterObserver(self, observer):
self.observer_list.append(observer)
def ObserverNotify(self):
for ov in self.observer_list:
ov.update(self.data)
def get(self):
return self.data
class Model(Observable):
"""Model extends its super class Observable and purely just functions"""
def __init__(self):
Observable.__init__(self)
def AddMoney(self, value):
self.data = self.get() + value
Observable.ObserverNotify(self)
def SubMoney(self, value):
self.data = self.get() - value
Observable.ObserverNotify(self)
class View(tk.Toplevel):
"""viewis the visual presentation of data"""
def __init__(self, master):
tk.Toplevel.__init__(self, master)
self.up_frame = tk.Frame(self)
self.up_frame.pack()
self.bottom_frame = tk.Frame(self)
self.bottom_frame.pack(side = 'bottom')
self.label = tk.Label(self.up_frame, text = 'My Money')
self.label.pack(side = 'left')
self.moneyDisplay = tk.Entry(self.up_frame, width = 8)
self.moneyDisplay.pack(side = 'left')
self.addButton = tk.Button(self.bottom_frame, text = 'Add', width = 8)
self.addButton.pack(side = 'left')
self.subButton = tk.Button(self.bottom_frame, text = 'Sub', width = 8)
self.subButton.pack(side = 'left')
def update(self, money):
self.moneyDisplay.delete(0, 'end')
self.moneyDisplay.insert('end', str(money))
class Controller:
"""Controller is the interconnection of model and view"""
def __init__(self, root):
self.model = Model()
self.view = View(root)
self.model.RegisterObserver(self.view)
self.view.addButton.config(command = self.AddMoney)
self.view.subButton.config(command = self.SubMoney)
self.MoneyChanged(self.model.get())
def AddMoney(self):
self.model.AddMoney(10)
def SubMoney(self):
self.model.SubMoney(10)
def MoneyChanged(self, money):
self.view.update(money)
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
whatever = Controller(root)
root.mainloop()
|
38d272cf81d92ed5616d14169f82118ee045f5be | xiaochenchen-PITT/CC150_Python | /cc150/c1.py | 6,214 | 3.9375 | 4 | '''1.1 Implement an algorithm to determine if a string has all unique character
What if you can not use additional data structures?'''
def solution(s):
# # for each in s:
# # if s.count(each) > 1:
# # return False
# # return True
# # if count()is not allowed,
# # then we can sort (quick or merge) the list and then compare the
# # adjacent element in the sorted list
# Quick Sort
def qsort(lst):
if len(lst) <= 1:
return lst
else:
pivot = lst[0]
less = [] # what if you can not use additional
equal = [] #data structure? -- In place quick sort
greater = []
for each in lst:
if each < pivot:
less.append(each)
elif each == pivot:
equal.append(each)
else:
greater.append(each)
return qsort(less) + equal + qsort(greater)
# In-place quick sort (NO additional space)
def partition(lst, left, right):
pivot = right
for i in xrange(left, right):
if lst[i] < lst[pivot]:
lst[i], lst[left] = lst[left],lst[i]
left += 1
lst[left], lst[right] = lst[right], lst[left]
return left
def inplace_qsort(lst, left, right):
if right > left:
new_pivot = partition(lst, left, right)
inplace_qsort(lst, left, new_pivot-1)
inplace_qsort(lst, new_pivot+1, right)
return lst
# Merge Sort
def msort(lst):
def merge(left, right):
merged_list = []
while left and right:
if left[0] <= right[0]:
merged_list.append(left.pop(0))
else:
merged_list.append(right.pop(0))
while left:
merged_list.append(left.pop(0))
while right:
merged_list.append(right.pop(0))
return merged_list
if len(lst) <= 1:
return lst
else:
middle_index = len(lst) / 2
left = msort(lst[:middle_index])
right = msort(lst[middle_index:])
return merge(left, right)
# sorted_list = qsort(list(s))
# sorted_list = inplace_qsort(list(s), 0, len(s)-1)
sorted_list = msort(list(s))
print sorted_list
for i in xrange(0, len(sorted_list)-1):
if sorted_list[i] == sorted_list[i+1]:
return False
return True
string = "af.sdvs"
print solution(string)
'''1.2 Write code to reverse a C-Style String
(C-String means including the null character at the end)'''
def solution(s):
return s[::-1]
string = "bdvir"
print solution(string)
'''1.3 Design an algorithm and write code to remove the duplicate characters
in a string without using any additional buffer
NOTE: One / two additional variables are fine An extra copy of the array is not
'''
def solution(a):
# In place quick sort the string and check the adjacent element
# and remove the same one.
if len(a) <= 1:
return a
def partition(a, left, right):
pivot = right
for i in xrange(left, right):
if a[i] < a[pivot]:
a[left], a[i] = a[i], a[left]
left += 1
a[left], a[right] = a[right], a[left]
return left
def inplace_qsort(a, left, right):
if right > left:
new_pivot = partition(a, left, right)
inplace_qsort(a, left, new_pivot-1)
inplace_qsort(a, new_pivot+1, right)
return a
sorted_list = inplace_qsort(a, 0, len(a)-1)
print sorted_list
i = 0
while i < len(sorted_list)-1: # Note: this is how you do when you
if sorted_list[i] == sorted_list[i+1]:# try to delete some elements from
sorted_list.pop(i) # the list (plz don't use for loop!!!)
continue
i += 1
return sorted_list
# l = [1,2,3,7,3,9,2,7]
l = [1,2,3,2]
print solution(l)
def solution(lst): #if not allowed to destroy the original order
i = 0
while i < len(lst):
j = i + 1
while j < len(lst):
if lst[i] == lst[j]:
lst.pop(j)
continue
j += 1
i += 1
return lst
s = 'davgdfverv'
print solution(list(s))
'''1.4 Write a method to tell if two strings are anagrams or not
eg. iceman vs cinema'''
def solution(s1,s2):
l1 = list(s1)
l2 = list(s2)
l1.sort() # Note: sort()method does not return anything!!!
l2.sort()
return l1 == l2
print solution('asd', 'dga')
'''1.5 write a method to replace all spaces in a string with "%20"
'''
def solution(s):
return '%20'.join(s.split(" "))
print solution('haha this is china')
'''1.6 Given an image represented by an NxN matrix,
where each pixel in the image is 4 bytes,
write a method to rotate the image by 90 degrees Can you do this in place?
'''
# not inplace
def solution(matrix):
if len(matrix) == 1:
return matrix
new_matrix = []
for i in xrange(0,len(matrix)):
row = []
for j in xrange(0,len(matrix[0])):
row.append(matrix[len(matrix)-1-j][i])
new_matrix.append(row)
return new_matrix
# inplace
def solution(matrix):
if len(matrix) < 2:
return matrix
# idea is reverse the matrix up side down and swap
matrix = matrix[::-1] # along the diagonal
print matrix
for i in xrange(0,len(matrix)): # Notice: just swap the upper half!
for j in xrange(i,len(matrix)):# Or you will get back
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return matrix
mat = [[1,2,3], [4,5,6], [7,8,9]]
mat = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
mat = [1]
print solution(mat)
"""1.7 Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column is set to 0
"""
def solution(matrix, M, N): # M: # of rows; N: # of cols
zero_list = []
for i in xrange(0, M):
for j in xrange(0, N):
if matrix[i][j] == 0:
zero_list.append([i, j])
print zero_list
for i_j_pair in zero_list:
for x in xrange(0, N):
matrix[i_j_pair[0]][x] = 0
for y in xrange(0, M):
matrix[y][i_j_pair[1]] = 0
return matrix
mat = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
print solution(mat, len(mat), len(mat[0]))
"""1.8 Assume you have a method isSubstring which checks
if one word is a substring of another. Given two strings,s1 and s2,
write code check if s2 is a rotation of s1 using only one call to isSubstring
(eg. 'waterbottle' is rotation of 'erbottlewat')
"""
def isSubstring(s1, s2): # wether s2 is sub of s1
for l in xrange(0, len(s1)):
for r in xrange(len(s1), 0, -1):
if s1[l:r] == s2:
return True
return False
def solution(s1, s2):
if len(s1) != len(s2) or len(s1) == 0:
return False
s1s1 = s1+s1
return isSubstring(s1s1, s2)
# s1 = 'waterbottle'
# s2 = 'erbottlewat'
s1 = ''
s2 = 'k'
print solution(s1, s2)
|
224ad7e01779ebc872a2c4c65be799ab0518094f | xiaochenchen-PITT/CC150_Python | /Leetcode/Merge Sorted Array.py | 686 | 3.609375 | 4 | class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
'''Note: A is actually [1, 3, 6, placeholder, placeholder], m = 3
B is [2, 5], n = 2
So avoid using len(A) and len(B), use m and n with incre/decre.
And avoid using append() and extend()'''
if n == 0:
return
pa = 0
pb = 0
while n - pb > 0:
if pa > m-1:
for i in range(pb, n):
A[pa] = B[i]
pa += 1
m += n
break
if B[pb] >= A[pa]:
pa += 1
else:
A.insert(pa, B[pb])
pb += 1
m += 1
return |
6ce064242cb40428e52917203518b1291ceeb0e5 | emetowinner/python-challenges | /Phase-1/Python Basic 2/Day-26.py | 2,807 | 4.5625 | 5 | '''
1. Write a Python program to count the number of arguments in a given function.
Sample Output:
0
1
2
3
4
1
2. Write a Python program to compute cumulative sum of numbers of a given list.
Note: Cumulative sum = sum of itself + all previous numbers in the said list.
Sample Output:
[10, 30, 60, 100, 150, 210, 217]
[1, 3, 6, 10, 15]
[0, 1, 3, 6, 10, 15]
3. Write a Python program to find the middle character(s) of a given string. If the length of the string is odd return the middle character and return the middle two characters if the string length is even.
Sample Output:
th
H
av
4. Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers.
Sample Output:
30
20
6
5. Write a Python program to check whether every even index contains an even number and every odd index contains odd number of a given list.
Sample Output:
True
False
True
6. Write a Python program to check whether a given number is a narcissistic number or not.
If you are a reader of Greek mythology, then you are probably familiar with Narcissus. He was a hunter of exceptional beauty that he died because he was unable to leave a pool after falling in love with his own reflection. That's why I keep myself away from pools these days (kidding).
In mathematics, he has kins by the name of narcissistic numbers - numbers that can't get enough of themselves. In particular, they are numbers that are the sum of their digits when raised to the power of the number of digits.
For example, 371 is a narcissistic number; it has three digits, and if we cube each digits 33 + 73 + 13 the sum is 371. Other 3-digit narcissistic numbers are
153 = 13 + 53 + 33
370 = 33 + 73 + 03
407 = 43 + 03 + 73.
There are also 4-digit narcissistic numbers, some of which are 1634, 8208, 9474 since
1634 = 14+64+34+44
8208 = 84+24+04+84
9474 = 94+44+74+44
It has been proven that there are only 88 narcissistic numbers (in the decimal system) and that the largest of which is
115,132,219,018,763,992,565,095,597,973,971,522,401
has 39 digits.
Ref.: //https://bit.ly/2qNYxo2
Sample Output:
True
True
True
False
True
True
True
False
7. Write a Python program to find the highest and lowest number from a given string of space separated integers.
Sample Output:
(77, 0)
(0, -77)
(0, 0)
8. Write a Python program to check whether a sequence of numbers has an increasing trend or not.
Sample Output:
True
False
False
True
False
9. Write a Python program to find the position of the second occurrence of a given string in another given string. If there is no such string return -1.
Sample Output:
-1
31
10. Write a Python program to compute the sum of all items of a given array of integers where each integer is multiplied by its index. Return 0 if there is no number.
Sample Output:
20
-20
0
'''
|
48449d264326a4508b0f111d19a6f5832155485d | emetowinner/python-challenges | /Phase-1/Python Basic 2/Day-28.py | 2,740 | 4.375 | 4 | '''
1. Write a Python program to check whether two given circles (given center (x,y) and radius) are intersecting. Return true for intersecting otherwise false.
Sample Output:
True
False
2. Write a Python program to compute the digit distance between two integers.
The digit distance between two numbers is the absolute value of the difference of those numbers.
For example, the distance between 3 and -3 on the number line given by the |3 - (-3) | = |3 + 3 | = 6 units
Digit distance of 123 and 256 is
Since |1 - 2| + |2 - 5| + |3 - 6| = 1 + 3 + 3 = 7
Sample Output:
7
6
1
11
3. Write a Python program to reverse all the words which have even length.
Sample Output:
7
6
1
11
4. Write a Python program to print letters from the English alphabet from a-z and A-Z.
Sample Output:
Alphabet from a-z:
a b c d e f g h i j k l m n o p q r s t u v w x y z
Alphabet from A-Z:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
5. Write a Python program to generate and prints a list of numbers from 1 to 10.
Sample Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
['1', '2', '3', '4', '5', '6', '7', '8', '9']
6. Write a Python program to identify nonprime numbers between 1 to 100 (integers). Print the nonprime numbers.
Sample Output:
Nonprime numbers between 1 to 100:
4
6
8
9
10
..
96
98
99
100
7. Write a Python program to make a request to a web page, and test the status code, also display the html code of the specified web page.
Sample Output:
Web page status: <Response [200]>
HTML code of the above web page:
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
8. In multiprocessing, processes are spawned by creating a Process object. Write a Python program to show the individual process IDs (parent process, process id etc.) involved.
Sample Output:
Main line
module name: __main__
parent process: 23967
process id: 27986
function f
module name: __main__
parent process: 27986
process id: 27987
hello bob
9. Write a Python program to check if two given numbers are coprime or not. Return True if two numbers are coprime otherwise return false.
Sample Output:
True
True
False
False
10. Write a Python program to calculate Euclid's totient function of a given integer. Use a primitive method to calculate Euclid's totient function.
Sample Output:
4
8
20
'''
|
c04ddba01766923e3e435d0f5eee406a99d29e17 | Osraj/Tic-Tac-Toe_Game | /Main.py | 3,822 | 3.953125 | 4 | # Tic-Tac-Toe game in Python with simple AI
board = [' ' for x in range(10)]
def insertLetter(letter, pos):
board[pos] = letter
def spaceIsFree(pos):
return (board[pos] == ' ')
def printBoard(board=board):
# print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
# print(' | |')
print('-----------')
# print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
# print(' | |')
print('-----------')
# print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
# print(' | |')
def isWinner(bo, le):
horizontal_win = ( ( (bo[1] == le) and (bo[2] == le) and (bo[3] == le) ) or
( (bo[4] == le) and (bo[5] == le) and (bo[6] == le) ) or
( (bo[7] == le) and (bo[8] == le) and (bo[9] == le) ) )
vertical_win = ( ( (bo[1] == le) and (bo[4] == le) and (bo[7] == le) ) or
( (bo[2] == le) and (bo[5] == le) and (bo[8] == le) ) or
( (bo[3] == le) and (bo[6] == le) and (bo[9] == le) ) )
diagonal_win = ( ( (bo[1] == le) and (bo[5] == le) and (bo[9] == le) ) or
( (bo[3] == le) and (bo[5] == le) and (bo[7] == le) ) )
return (horizontal_win or vertical_win or diagonal_win)
def playerMove():
run = True
while run:
move = input(f"Please select a position to place an (X) (1-9): ")
try:
move = int(move)
if ( (move > 0) and (move < 10) ):
if spaceIsFree(move):
run = False
insertLetter('X', move)
else:
print("Sorry, this space is occupied")
else:
print("Please type a number within the range (1-9)")
except:
print("what you wrote isn't a number between 1 and 9. Please try again ")
def compMove():
possible_moves = [x for x, letter in enumerate(board) if (letter == ' ' and x != 0)]
move = 0
for let in ['O', 'X']:
for i in possible_moves:
board_copy = board[:]
board_copy[i] = let
if isWinner(board_copy, let):
move = i
return move
corners_open = []
for i in possible_moves:
if i in [1, 3, 7, 9]:
corners_open.append(i)
if len(corners_open) > 0:
move = selectRandom(corners_open)
return move
if 5 in possible_moves:
move = 5
return move
corners_open = []
for i in possible_moves:
if i in [2, 4, 6, 8]:
corners_open.append(i)
if len(corners_open) > 0:
move = selectRandom(corners_open)
return move
def selectRandom(li):
import random
ln = len(li)
r = random.randrange(0,ln)
return li[r]
def isBoardFull(board):
return not(board.count(' ') > 1)
def main():
print ("Welcome to Tic-Tac-Toe")
printBoard()
while not(isBoardFull(board)):
if not(isWinner(board, 'O')):
playerMove()
printBoard()
else:
print("Sorry, the bot won this time!")
break
if not(isWinner(board, 'X')):
move = compMove()
if move == 0:
print("Tie Game!")
else:
insertLetter('O', move)
print (f"Computer places an (O) in position {move}")
printBoard()
else:
print("You won this time!, Well Done!")
break
if isBoardFull(board):
print("Tie Game!")
run_game = True
while run_game:
answer = input("Do you want to play Tic-Tac-Toe?[yes/no] ")
if answer == "yes":
main()
else:
print("I hope you had fun ^^")
run_game = False
|
d8a9bd9a1f48d42de21a646dc5b51ec262ef3c07 | Bloodika/AdventOfCode2020 | /Day3/3.py | 847 | 3.953125 | 4 | def slopes(tree_map, right, down):
index, row, tree_counter = 0, 0, 0
text_length = len(tree_map[0])
while row != len(tree_map) - 1:
index += right
row += down
if index >= text_length:
index = index - text_length
position = tree_map[row][index]
if position == "#":
tree_counter += 1
print(tree_counter)
return tree_counter
def main():
with open("3.txt", "r") as f:
lines = f.readlines()
tree_map = []
for line in lines:
tree_map.append(line.strip())
final_answer = 0
final_answer += slopes(tree_map, 1, 1)
final_answer *= slopes(tree_map, 3, 1)
final_answer *= slopes(tree_map, 5, 1)
final_answer *= slopes(tree_map, 7, 1)
final_answer *= slopes(tree_map, 1, 2)
print(final_answer)
main()
|
01c8736466d21a74a166999bacededf7f81eeb03 | airmax11/seleniumPy | /Teclado/start.py | 513 | 4.0625 | 4 | class Bookshelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"There are {len(self.books)} books."
class Book:
def __init__(self, name, amount):
self.name = name
self.amount = amount
def __str__(self):
return f"Book name is {self.name} and amount is {self.amount}"
book1 = Book("Harry", 100)
book2 = Book("Germiona", 20)
print(book1)
print(book2)
bookshell = Bookshelf(book1, book2)
print(bookshell.books)
print(bookshell) |
73b3d4ea858146efa6fa0c26b0e4130d1448c2ea | juanman2/mlpy | /notebook/api_data_wrangling_mini_project.py | 3,435 | 3.828125 | 4 | #!/usr/bin/env python
# coding: utf-8
# This exercise will require you to pull some data from the Qunadl API. Qaundl is currently the most widely used aggregator of financial market data.
# As a first step, you will need to register a free account on the http://www.quandl.com website.
# After you register, you will be provided with a unique API key, that you should store:
# In[ ]:
# In[51]:
# First, import the relevant modules
import requests
import json
import time
import sys
import matplotlib.pyplot as plt
# In[52]:
# Now, call the Quandl API and pull out a small sample of the data (only one day) to get a glimpse
# into the JSON structure that will be returned
URL="https://www.quandl.com/api/v3/datasets/CFTC/0233CV_FO_L_ALL_CR.json?api_key={:s}&".format(key)
parameters = {'start_date': '2020-01-01', 'end_date':'2020-12-31'}
response = requests.get(URL, params=parameters)
if response.status_code != 200:
raise Exception("Response was code " + str(response.status_code))
responseStr = response.text
data = json.loads(response.text)
print(data['dataset'].keys())
type(data['dataset']['data'])
print(len(data['dataset']['data']))
print(len(data['dataset']))
# In[53]:
# Inspect the JSON structure of the object you created, and take note of how nested it is,
# as well as the overall structure
# These are your tasks for this mini project:
#
# 1. Collect data from the Franfurt Stock Exchange, for the ticker AFX_X, for the whole year 2017 (keep in mind that the date format is YYYY-MM-DD).
# 2. Convert the returned JSON object into a Python dictionary.
# 3. Calculate what the highest and lowest opening prices were for the stock in this period.
# 4. What was the largest change in any one day (based on High and Low price)?
# 5. What was the largest change between any two days (based on Closing Price)?
# 6. What was the average daily trading volume during this year?
# 7. (Optional) What was the median trading volume during this year. (Note: you may need to implement your own function for calculating the median.)
# In[54]:
smin = sys.float_info.max
lmin = sys.float_info.max
dmin = sys.float_info.max
smax = 0.0
lmax = 0.0
dmax = 0.0
dsum = 0.0
dlist = []
for d in data['dataset']['data']:
smin = min(smin, d[2])
smax = max(smax, d[2])
lmin = min(lmin, d[1])
lmax = max(lmax, d[1])
dif = abs(d[1]-d[2])
dmax = max(dmax, dif)
dmin = min(dmin, dif)
dsum += dif
dlist.append(dif)
print(d[0], d[1], d[2])
ave_dif = dsum / len(data['dataset']['data'])
print("Max long in 2020 was: {:.2f}".format(lmax))
print("Min long in 2020 was: {:.2f}".format(lmin))
print("Max short in 2020 was: {:.2f}".format(smax))
print("Min short in 2020 was: {:.2f}".format(smin))
print("Max differential in 2020 was: {:.2f}".format(dmax))
print("Min differential in 2020 was: {:.2f}".format(dmin))
print("Ave differential in 2020 was: {:.2f}".format(ave_dif))
print(len(dlist))
# In[67]:
def median(dlist):
for i in dlist:
print("{:.2f}".format(i))
if len(dlist)%2 == 0: # even
h = int(len(dlist)/2)
return (dlist[h-1]+dlist[h])/2
else:
return (dlist[int(len(dlist)/2) + 1])
median_d = median(sorted(dlist))
median_d
# In[68]:
print("Median differential is {:.2f}".format(median_d))
# In[58]:
plt.plot(dlist)
plt.xlabel("2020 (months)")
plt.ylabel("differential")
plt.show()
# In[ ]:
|
c0233475b282a3a4f41a5829905d9fcd1fd0fa69 | lmiguelgarcia/Frubana | /ejercicio2.py | 4,002 | 3.84375 | 4 | import numpy as np
class TreeNode:
"""Clase para crear los nodos del arbol
Atributos
----------
val : int
valor del nodo
left : TreeNode
nodo hijo a la izquieda
right : TreeNode
nodo hijo a la derecha
root : TreeNode
nodo padre
is_leaf : Boolean
indica si es una hoja(nodo final)
"""
def __init__(self, x):
"""
x : int
numero correspondiente al nodo
"""
self.val = x
self.left = None
self.right = None
self.root = None
self.is_leaf = True
def add_node(self,node):
"""Metodo para adicionar nodo hijo
-se indica que ya no es una hoja
-se valida si se adiciona a la rama izquierda o derecha
Parameters:
node: TreeNode
Nodo hijo
"""
self.is_leaf = False
node.root=self
if self.left == None:
self.left = node
else:
self.right = node
def path(node, k):
"""Metodo para encontrar la ruta de un nodo a otro, se valida si el nodo2 esta en los hijos(lef,right)
Parameters:
node: TreeNode
Nodo1 root
K: int
valor del nodo2 a buscar en la ruta
Returns:
list
lista de los nodos de la ruta de (n1 a n2)
"""
if not node:
return []
if node.val == k:
return [node.val]
res = path(node.left, k)
if res:
return [node.val] + res
res = path(node.right, k)
if res:
return [node.val] + res
return []
def nodes_path(node, k):
"""Metodo para encontrar los nodos de la ruta entre node1 y node2
Parameters:
node: TreeNode
Nodo1
K: int
valor del nodo2 a buscar en la ruta
Returns:
list
lista de los nodos de la ruta de (n1 a n2)
"""
# si no es un nodo hoja, se busca la ruta a partir de ese nodo
if not node.is_leaf :
res = path(node,k)
if res:
return res
# se itera nuevamente con el nodo padre para buscar la ruta
res = nodes_path(node.root,k)
if res:
return [node.val] + res
return []
def sum_unique_colors(nodes,colors):
"""Metodo para encontrar los nodos de la ruta entre node1 y node2
Parameters:
nodes: list
nodos de la ruta entre node1 y node2
colors: list
colores correspondientes a cada nodo
Returns:
int
suma de colores unicos
"""
colors_nodes=[colors[x-1] for x in nodes]
return len(set( colors_nodes ))
# en esta seccion se toman los parametros de entrada del usuario para construir el arbol
M = int(input())
x = [None] * M
colors = [int(x) for x in input().split()]
for i in range(0, M-1):
node1, node2 = map(int, input().split(' '))
index1=int(node1)-1
index2=int(node2)-1
if x[index1] == None:
x[index1] = TreeNode(node1)
if x[index2] == None:
x[index2] = TreeNode(node2)
x[index1].add_node(x[index2])
# en esta seccion se crea un matrix para guardar la suma de las rutas entre nodos (Node 0-Node n)
a = np.zeros(shape=(M,M))
np.fill_diagonal(a, 1)
for j in range(0, M):
summ=0
for i in range(0, M):
if a[j][i] == 0:
node1=x[j]
node2=x[i]
nodes=nodes_path(node1, node2.val)
summ=sum_unique_colors(nodes,colors)
a[j][i] = summ
a[i][j] = summ
print("Resumen sumatoria")
print (a)
print("Suma nodos:")
print (a.sum(axis=1))
|
6ece47524c7619b649fd02a684262c06eac17f53 | Megha2122000/python3 | /3.py | 361 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 19 15:30:29 2021
@author: Comp
"""
# Python program to print positive Numbers in a List
# list of numbers
list1 = [-12 , -7 , 5 ,64 , -14]
# iterating each number in list
for num in list1:
# checking condition
if num >= 0:
print(num, end = " ") |
ccad48e6c0098ebc9f19b8218034baada0a18a53 | sushrest/machine-learning-intro | /decisiontree.py | 1,455 | 4.4375 | 4 | # scikit-learn Machine Learning Library in python
# Environment Python Tensorflow
# Following example demonstrates a basic Machine Learning examples using
# Supervised Learning by making use of Decision Tree Classifier and its fit algorithm to predict whether the given
# features belong to Apple or Orange
from sklearn import tree
# Preparing data for the decision tree classifier
# features as an input for classifier
features = [
[140, 1], #140 as weight in grams and 1 as Bumpy surface and 0 as Smooth surface
[130, 1],
[150, 0],
[170, 0]
]
# labels as an output for classifier
labels = [0, 0, 1, 1] # 0 as an apple and 1 as orange
print 'Marking features type to Int by'
print '1 as Smooth and 0 as Bumpy and 0 as Apple and 1 as Orange'
print ' '
# Initializing a classifier this can be treated as an empty box of Rule.
clf = tree.DecisionTreeClassifier()
print '.'
print '.'
print 'Learning algorithm is just a procedure that creates classifier such as DecisionTree.'
print '.'
print '.'
print ' '
print 'Calling a built-in algorithm called fit from DecisionTreeClassifier Object '
print '.'
print ' '
print 'Think of fit being a synonym for Fine Pattern and Data'
print '.'
print ' '
clf = clf.fit(features, labels)
print 'Now lets Predict'
print '1'
print '2.. and '
print 'BAAAM !!'
print 'Predicting a fruit which is 160g and Bumpy = 0 '
print clf.predict([[160,0]])
print 'If 0 its Apple and if 1 its Orange' |
95c41253866a25394ad1c99a3ea2e66580e4f340 | InonBr/python_JS_react | /python_fundamentals/function.py | 170 | 4.0625 | 4 | def double(x):
return x*2
print(double(3))
def multiply(a, b):
result = a * b
print("the result of a * b")
return result
result = multiply(2, 3)
print(result)
|
048c443d33c916c112433ae0358e5b66b1d2ec5c | statco19/doit_pyalgo | /ch3/ssearch_test1.py | 418 | 3.796875 | 4 | from ssearch_while import seq_search
print("Finding a float.")
print("Caurtion: the program quits when 'End' entered")
number = 0
x = []
while True:
s = input(f'x[{number}]: ')
if s == "End":
break
x.append(float(s))
number += 1
ky = float(input("What to search?: "))
idx = seq_search(x,ky)
if idx == -1:
print("No such an element")
else:
print(f"The element is at x[{idx}]")
|
1ed4644c963103b0bb9acc9f5e86fc4b3820321c | statco19/doit_pyalgo | /ch6/quick_sort1.py | 466 | 3.90625 | 4 | def qsort(a, left, right): # left = 0, right = n-1
n = len(a)
pl = left
pr = right
x = a[(left+right)//2]
while pl <= pr:
while a[pl] < x: pl += 1
while a[pr] > x: pr -= 1
if pl <= pr:
a[pl], a[pr] = a[pr], a[pl]
pl += 1
pr -= 1
if left < pr: qsort(a, left, pr)
if right > pl: qsort(a, pl, right)
return a
def quick_sort(a):
return qsort(a, 0, len(a)-1)
if __name__ == "__main__":
a = [5,8,4,2,6,1,3,9,7]
print(quick_sort(a))
|
078583a747845399770de5ca3d4228d66f3ffb3c | statco19/doit_pyalgo | /ch6/quick_sort2.py | 1,071 | 3.828125 | 4 | # choosing a pivot
def sort3(a, idx1, idx2, idx3):
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
if a[idx3] < a[idx2]: a[idx2], a[idx3] = a[idx3], a[idx2]
if a[idx2] < a[idx1]: a[idx1], a[idx2] = a[idx2], a[idx1]
return idx2
# insertion sort
def insertion_sort(a, left, right):
for i in range(left+1, right+1):
j=i
tmp = a[i]
while j>0 and a[j-1] > tmp:
a[j] = a[j-1]
j-=1
a[j] = tmp
return a
# quick sort
def qsort(a, left, right):
if right - left + 1 < 9:
insertion_sort(a, left, right)
else:
pl = left
pr = right
m = sort3(a, pl, (pl+pr)//2, pr)
# the index of a mid-value
x = a[m]
a[m],a[pr-1] = a[pr-1], a[m]
pl += 1
pr -= 2
while pl <= pr:
while a[pl] < x: pl += 1
while a[pr] > x: pr -= 1
if pl <= pr:
a[pl], a[pr] = a[pr], a[pl]
pl += 1
pr -= 1
if left < pr: qsort(a, left, pr)
if pl < right: qsort(a, pl, right)
return a
def quick_sort(a):
return qsort(a, 0, len(a)-1)
if __name__ == "__main__":
a = [5,8,4,2,6,1,3,9,7,0,3,5]
print(quick_sort(a))
|
eff1131fddbee28b9b4a2c9f7f32ca1a1c38bd94 | statco19/doit_pyalgo | /ch4/fixed_stack_test.py | 1,406 | 3.71875 | 4 | from enum import Enum
from fixed_stack import FixedStack
Menu = Enum("Menu",['push','pop','peek','find','dump','quit'])
def select_menu() -> Menu:
s = [f'({m.value}){m.name}' for m in Menu]
while True:
print(*s, sep = ' ', end = '')
n = int(input(': '))
if 1 <= n <= len(Menu):
return Menu(n)
s = FixedStack(64)
while True:
print(f'The number of data: {len(s)} / {s.capacity}')
menu = select_menu()
if menu == Menu.push:
x = int(input('Enter data: '))
try:
s.push(x)
except FixedStack.Full:
print("The stack is full.")
elif menu == Menu.pop:
try:
x = s.pop()
print(f'The popped datum is {x}.')
except FixedStack.Empty:
print("The stack is empty.")
elif menu == Menu.peek:
try:
x = s.peek()
print(f'The peeked data are {x}.')
except FixedStack.Empty:
print("The stack is empty.")
elif menu == Menu.find:
x = int(input("Enter data to find: "))
if x in s:
print(f"The stack has found {s.count(x)} data(datum), its head's indice is {s.find(x)}.")
else:
print("Cannot find the data")
elif menu == Menu.dump:
s.dump()
else:
break
|
27248e5f2992f91b95a1071696682cb0123cc34b | ajm188/coursework | /eecs440/pa3/logistic_regression.py | 5,481 | 3.609375 | 4 | # -*- coding: utf8 -*-
"""
The Logistic Regression Classifier
"""
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.linalg
import numpy.random
import scipy
import scipy.optimize
import stats
from folds import get_folds
def sigmoid(x):
"""
Computes the sigmoid of x.
If x is an ndarray, computes the sigmoid element-wise.
"""
return (np.exp(-x) + 1) ** (-1)
def objective_func(w_and_b, X, y, _lambda):
"""
The objective function we are trying to minimize for logistic regression.
"""
w, b = w_and_b[0:-1], w_and_b[-1]
s = sigmoid(y * (np.dot(X, w) + b))
return _lambda * 0.5 * (np.linalg.norm(w) ** 2) + np.sum(np.log(s ** (-1)))
def gradient(w_and_b, X, y, _lambda):
"""
Gradient of the objective function we are trying to minimize for logistic
regression.
"""
w, b = w_and_b[0:-1], w_and_b[-1]
s = sigmoid((-y) * (np.dot(X, w) + b))
del_common = (-y) * s
del_w = (_lambda * w) + np.sum(del_common[:, np.newaxis] * X, axis=0)
del_b = np.sum(del_common)
return np.concatenate([del_w, [del_b]])
def random_weights(dimensions, r):
"""
Returns an ndarray with the given dimensions, where each value is between
r[0] and r[1].
"""
lower, upper = r
size = upper - lower
offset = lower
return np.random.rand(*dimensions) * size + offset
class LogisticRegression(object):
def __init__(self, schema=None, **kwargs):
"""
Constructs a logistic regression classifier
@param lambda : Regularisation constant parameter
"""
self.schema = schema
self.nominals = {}
self._lambda = kwargs.pop('lambda')
def fit(self, X, y):
"""
Fit a classifier to X and y. Performs parameter tuning for the choice
of λ.
"""
self._lambda = self.tune(X, y, [0, 0.001, 0.01, 0.1, 1, 10, 100])
print('Chose {} for λ'.format(self._lambda))
self._fit(X, y)
def _fit(self, X, y):
"""
Helper routine that fits X and y according to whatever self._lambda is.
"""
np.seterr(over='ignore', divide='ignore')
self._enable_unnominalization(X)
X = self.unnominalize(X)
self.means = np.mean(X, axis=0)
self.stddevs = np.std(X, axis=0)
X = self.normalize(X)
res = scipy.optimize.minimize(
objective_func,
np.zeros(len(X[0]) + 1),
method='BFGS',
jac=gradient,
args=(X, y, self._lambda),
options={
'maxiter': 2000,
},
)
self.w, self.b = res.x[0:-1], res.x[-1]
def tune(self, X, y, lambda_range):
"""
Perform internal cross-fold validation to find the λ which maximizes
AUC.
"""
folds = get_folds(X, y, 5)
AUCs = []
for _lambda in lambda_range:
sm = stats.StatisticsManager()
for train_X, train_y, test_X, test_y in folds:
kwargs = {'schema': self.schema, 'lambda': _lambda}
classifier = LogisticRegression(**kwargs)
classifier._fit(train_X, train_y)
preds = classifier.predict(test_X)
probs = classifier.predict_proba(test_X)
sm.add_fold(test_y, preds, probs, 0)
A = sm.get_statistic('auc', pooled=True)
AUCs.append(A)
return lambda_range[np.argmax(AUCs)]
def normalize(self, X):
"""
Normalizes X according to a set of means and standard deviations.
"""
return (X - self.means) / self.stddevs
def _enable_unnominalization(self, X):
"""
Sets up an instance variable that will be used later to transform
discretely-valued attributes into continuous attributes.
"""
for i, _ in enumerate(self.schema.feature_names):
if self.schema.is_nominal(i):
self.nominals[i] = \
dict([(float(v), j)
for j, v in enumerate(self.schema.nominal_values[i])])
def unnominalize(self, X):
"""
Transforms X from discretely-valued to continuous attributes.
"""
D = np.empty_like(X)
for i, _ in enumerate(self.schema.feature_names):
X_C = X[:, i]
if self.schema.is_nominal(i):
nom = self.nominals[i]
for n, c in nom.iteritems():
D[:, i][np.where(X_C == n)[0]] = c
else:
D[:, i] = X_C
return D
def predict(self, X):
"""
Makes predictions about X.
Returns 1 if (w dot x) + b > 0 and -1 otherwise for each x in X.
"""
np.seterr(over='ignore')
X = self.normalize(self.unnominalize(X))
predictions = np.dot(X, self.w) + self.b
predictions[np.where(predictions > 0)[0]] = 1
predictions[np.where(predictions < 0)[0]] = -1
return predictions
def predict_proba(self, X):
"""
Returns p(y=1|x) for each x in X.
"""
np.seterr(over='ignore', divide='ignore')
X = self.normalize(self.unnominalize(X))
dot_prods = -(np.dot(X, self.w[:, np.newaxis]) + self.b)
frac = ((np.exp(dot_prods) + 1) ** (-1)).reshape(dot_prods.shape[0],)
frac[np.where(frac == np.inf)[0]] = 1
return frac
|
b0d5b1f2fa14e151645767ef1bc5e002a4d29476 | jdalton92/cs50x | /pset7/similarities/helpers.py | 813 | 3.53125 | 4 | from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
a_line = set(a.split("\n"))
b_line = set(b.split("\n"))
return list(a_line & b_line)
def sentences(a, b):
"""Return sentences in both a and b"""
a_sentence = set(sent_tokenize(a))
b_sentence = set(sent_tokenize(b))
return list(a_sentence & b_sentence)
def substring_split(string, n):
"""Return a list of substrings of length n"""
substrings = []
for i in range(len(string) - n + 1):
substrings.append(string[i:i + n])
return substrings
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
a_substring = set(substring_split(a, n))
b_substring = set(substring_split(b, n))
return list(a_substring & b_substring) |
07f17fd5c38fd55a2e8cc668e853e15ebdcb5c73 | poio90/perceptron-multicapa | /cargar_datos.py | 1,722 | 3.59375 | 4 | import pandas as pd
import numpy as np
def cargar_datos(path:str):
"""
dado el path, retorna una tupla con= un numpy.narray primer array filas, segundo array valores de las columnas
con= numpy.narray donde solo tiene valores de la ultima columna del dataset.
"""
data_set_diabetes = pd.read_csv(path)
data = data_set_diabetes.to_numpy()
#numpy.ndarray
respuestas = data[:, -1]
respuestas = respuestas[:, np.newaxis]
data = data[:, :-1]
# Prueba de que anda normalizar
# prueba = np.array([[23,0.1,1000],[54,0.7,2000],[42,0.4,1444]])
# print("shape prueba"+str(prueba.shape))
# np.random.shuffle(prueba)
# print("prueba")
# normalizar(prueba)
# print(np.array_str(prueba, precision=2, suppress_small=True))
normalizar(data)
return data, respuestas
def normalizar(data):
"""Dado los datos normalizara las columnas con la ecuacion (x-min)/(max-min)
prueba = np.array([[23,0.1,1000],[54,0.7,2000]])
para prueba[0][0]=23 -> (23-23)/(54-23)
para prueba[0][1]=0.1 -> (0.1-0.1)/(0.7-0.1)
"""
for i in range(len(data[0])):
minimo, maximo = buscar_min_max_a_traves_de_columnas(data, i)
for instancia in data:
instancia[i] = (instancia[i] - minimo)/(maximo - minimo)
def buscar_min_max_a_traves_de_columnas(array_de_arrays, posicion):
"""Dado un array de array, reccorrera la posicion x de cada uno buscando el minimo."""
minimo = array_de_arrays[0][posicion]
maximo = minimo
for array in array_de_arrays:
value = array[posicion]
if value < minimo:
minimo = value
elif value > maximo:
maximo = value
return minimo, maximo
|
edb5a32cde65084ef08906bd501682cc57d37d31 | poio90/perceptron-multicapa | /entrenamiento.py | 2,369 | 3.640625 | 4 | import numpy as np
def entrenar(red_neuronal, Entrada, Respuesta, funcion_costo, tasa_aprendizaje=0.05, entrenar=True):
"""Si entrenar esta en true, se obtiene los resultados del forward_pass, luego se hace el proceso de backpropagation
donde se calculan los deltas, y luego con esto se realiza el aprendizaje por el desenso de gradiente"""
# Forward pass, meter la entrada, y guardar la respuesta predicha.
out = forward_pass(red_neuronal=red_neuronal, Entrada=Entrada)
if entrenar:
# backward pass
deltas = []
# se comienza a recorrer desde la ultima capa
for indice in reversed(range(0, len(red_neuronal))):
z = out[indice+1][0]
a = out[indice+1][1]
if indice == len(red_neuronal)-1:
# calcular deltas ultima capa
deltas.insert(0, funcion_costo[1](
a, Respuesta) * red_neuronal[indice].funcion_activacion[1](a))
else:
# calcular deltas respecto de capa previa
deltas.insert(
0, deltas[0] @ _W.T * red_neuronal[indice].funcion_activacion[1](a))
_W = red_neuronal[indice].W
# ajustar pesos y bias por el metodo del gradient descent
red_neuronal[indice].B = red_neuronal[indice].B - \
np.mean(deltas[0], axis=0, keepdims=True) * tasa_aprendizaje
red_neuronal[indice].W = red_neuronal[indice].W - \
out[indice][1].T @ deltas[0] * tasa_aprendizaje
return out[-1][1]
def forward_pass(red_neuronal, Entrada):
out = [(None, Entrada)]
for indice, layer in enumerate(red_neuronal):
# Multiplicacion matricial de el vector entrada por el vector de pesos de la primera capa, y se le suma los bias de la primera capa
z = out[-1][1] @ red_neuronal[indice].W + red_neuronal[indice].B
# salida de la funcion de activacion
a = red_neuronal[indice].funcion_activacion[0](z)
# guardamos para despues hacer backpropagation
out.append((z, a))
return out
def eta_adaptativo(tasa_aprendizaje, error, last_error, a, b):
if(error - last_error > 0):
tasa_aprendizaje = tasa_aprendizaje - b * tasa_aprendizaje
elif(error - last_error < 0):
tasa_aprendizaje = tasa_aprendizaje + a
return tasa_aprendizaje
|
958b94f5966c36f1895d6c183d3cf7459c45a4ad | Sakhiyev/Web-Development | /Web Development/Lab7/informatics/2-ссылка/bolshe.py | 108 | 3.734375 | 4 | a=int(input())
b=int(input())
if(a>b):
print(a)
elif(a==b):
print("Oni ravny")
else:
print(b)
|
8604d0ef3683a455d7281e5139cae4080e5b28d0 | mdmuneerhasan/python | /Hackeblock/test.py | 97 | 3.6875 | 4 | lst = [(1, 2), (2, 2), (3, 2)]
print(lst[1][0])
for i in range(0,3):
print(lst[i])
i+=1 |
3dbaa10acd3bb6edd33d7d86afc4b795da5ef098 | rishgoyell/VisProgGen | /token_file.py | 1,445 | 3.609375 | 4 | '''
This file contains the definitions of tokens required
to tokenize the program
'''
import ply.lex as lex
def build_lexer(debug_mode=True, optimize_mode=False):
tokens = [
'IDENTIFIER',
'UNION',
'INTERSECTION',
'DIFFERENCE',
'INTEGER'
]
literals = "(),"
# t_token = value
def t_UNION(t):
r'\+'
return t
def t_INTERSECTION(t):
r'\*'
return t
def t_DIFFERENCE(t):
r'-'
return t
def t_IDENTIFIER(t):
r'c|t|s'
return t
def t_INTEGER(t):
r'[0-9](_?[0-9]+)*([Ee](\+)?[0-9](_?[0-9]+)*)?'
t.value = int(float(t.value.replace("_","")))
return t
'''
The following rule are taken form ply tutorial for easier debugging.
source : http://www.dabeaz.com/ply/ply.html#ply_nn4
'''
# Define a rule so we can track line numbers
def t_newline(t):
r'\n'
t.lexer.lineno += len(t.value)
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
t_ignore_COMMENT = r'%.*'
# Error handling rule
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
if debug_mode:
return [tokens, lex.lex(debug=1)]
elif optimize_mode:
return [tokens, lex.lex(optimize=1)] # disables error checking
else:
return [tokens, lex.lex()]
|
d7c34077050555f47e8e1988e1a49b2f27fdc4b2 | inwk6312winter2019/openbookfinal-arjanchauhan87 | /task1B.py | 197 | 3.625 | 4 | def count_the_article():
mylist = ["a", "the", "at", "run", "to","and","are","or","for","an","this"]
for x, word in enumerate(mylist):
for i, subwords in enumerate(word):
print i
|
e5a138e01d5f8068025cffb859ae3324fe73a456 | alimohammad0816/algorithms | /rotate.py | 163 | 3.546875 | 4 | def rotate(s, k):
duble_s = s + s
if k <= len(s):
return duble_s[k:k+len(s)]
else:
return duble_s[k-len(s):k]
print(rotate("ali", 5)) |
84d6cd6702409ee551f0383a14bf3b4b64aa9af2 | alimohammad0816/algorithms | /buy_sell_stock.py | 339 | 3.578125 | 4 | """
buy-sell stock
[7, 1, 5, 3, 6, 4] ==> 5
[9, 7, 6, 4, 3, 1] ==> 0
"""
def max_profit(prices):
cur_max, final_max = 0, 0
for i in range(1, len(prices)):
cur_max = max(0, cur_max + prices[i] - prices[i - 1])
final_max = max(cur_max, final_max)
return final_max
max_profit([7, 1, 5, 3, 6, 4])
|
6c9bf76c320d9c711c254c6c6c057ecb3abae949 | POA-WHU/POA-spiders | /src/base/base_url_manager.py | 2,389 | 3.5 | 4 | """
BaseURLManager定义文件
"""
from threading import Thread
from abc import ABC, abstractmethod
from base.utilities import Logger
class BaseURLManager(ABC):
"""
从目录页获取文章URL,为Spider提供待爬取的URL
"""
def __init__(self, start_page=1, end_page=-1):
"""
初始化
注意:每个目录页包含多个url
:param start_page:开始目录页码
:param end_page:结束目录页码, 默认为无穷
"""
self._logger = Logger(self.__class__.__name__)
self.start_page = start_page
self.end_page = end_page
# url队列
self.queue = list()
# 工作状态
self.is_working = False
@property
def is_empty(self) -> bool:
"""
:return: URL队列是否为空
"""
return len(self.queue) == 0
def new_url(self):
"""
:return: 队首url
"""
if self.is_empty:
self._logger.warning('Get url from an empty queue.')
return None
else:
return self.queue.pop(0)
def run(self):
"""
新开线程爬取可用url,不影响主线程运行
:return:
"""
self.is_working = True
self._logger.debug('Started running')
Thread(target=self._gather_urls, daemon=True).start()
def _gather_urls(self):
"""
私有方法,不可被外部调用
:return:
"""
# 记录当前正在爬取的目录页
page_cnt = self.start_page
while page_cnt != self.end_page:
self._logger.debug(f'Parsing page {page_cnt}')
page_cnt += 1
# 解析目录页,获取文档url
try:
urls = self.parse(page_cnt)
except Exception as e:
self._logger.error(e)
continue
# 返回空列表,说明已到达无效目录页,退出循环
if len(urls) == 0:
break
# 将文档url存入队列
for i in urls:
self.queue.append(i)
self.is_working = False
self._logger.debug('Done')
@abstractmethod
def parse(self, page_cnt) -> list:
"""
:param page_cnt: 页码
:return: 文档url列表
"""
pass
|
fc97aa36a7e1b41c72b120769e49972655d38f3f | RatnadeepYSVS/Algorithms | /Smallest Positive missing number .py | 1,578 | 3.890625 | 4 | """
Question:You are given an array arr[] of N integers including 0.
The task is to find the smallest positive number missing from the array.
Example 1:
Input:
N = 5
arr[] = {1,2,3,4,5}
Output: 6
Explanation: Smallest positive missing number is 6.
Example 2:
Input:
N = 5
arr[] = {0,-10,1,3,-20}
Output: 2
Explanation: Smallest positive missing number is 2.
Your Task:
The task is to complete the function missingNumber() which returns the smallest positive missing number in the array.
Expected Time Complexity: O(NLogN).
Constraints:
1 <= N <= 106
-106 <= arr[i] <= 106
Approach:
step 1:we can filter the given array in a way that it should contain only positive elements(excluding 0).
step 2:sort the resultant array.
step 3:loop over the array to find the missing element."""
def findMissingElement(arr,n):
res=-1
arr=list(filter(lambda x:x>0,arr))
arr.sort()
arr.insert(0,0)#adding 0 to the array such that we can find minimum missing element
#print(arr)
if len(arr)>0:
for i in range(len(arr)-1):
if arr[i+1]-arr[i]>1:#difference between two consecutive elements should be <=1.
res=arr[i]+1
break
if res==-1:
res=arr[-1]+1
else:#if length of the array containing positive elements in 0 then the minimum missing element is 1
res=1
return res
n=int(input())
l=list(map(int,input().split()))
print(findMissingElement(l,n))
#Code is contributed by bsandeep137
|
ccc3abda28abe8e4719c043e55fe47fe3e9f7b53 | fight741/DaVinciCode | /main.py | 435 | 4.15625 | 4 | import numpy as np
start = input("start from : ")
end = input("end with : ")
number = int(np.random.randint(int(start), int(end)+1))
g = int(input("Input your guess here : "))
while g != number:
if g > number:
print("The number is smaller")
g = int(input("Give another guess : "))
else:
print("The number is bigger")
g = int(input("Give another guess : "))
print("HOOORAY! That's correct!")
|
ad1a43b054cdacf6c3db89e33a389df16df0b7da | abhishekshinde2104/Coursera_Guided_Projects | /Image Data Augmentation with Keras/project.py | 5,435 | 3.625 | 4 | #IMPORTING LIBRARIES
#%matplotlib inline
import os
import numpy as np
import tensorflow as tf
from PIL import Image
from matplotlib import pyplot as plt
print('Using TensorFlow', tf.__version__)
#ROTATION
#This class has lot of functions for data augmentation and we can also do data normalisation with it
generator = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=40)
#this rotation_range = 40 means our image can be rotated randomly between -40 to +40 with the generator object
image_path = 'images/train/cat/cat.jpg'
plt.imshow(plt.imread(image_path));
#flow_from_directory goes into all folders
x, y = next(generator.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#You see the image of size 256x256 and theres sort of an angle
#WIDTH AND HEIGHT SHIFTS
#we can shift the pixels along the horizontal and vertical axis
#we can set this range with tuple or list
#we are explicitly giving the possible values in the list
generator_1 = tf.keras.preprocessing.image.ImageDataGenerator(
width_shift_range=[-100,-50,0,50,100],
height_shift_range=[-50,0,50])
#3this code goes in all the images in the specified folder and applies the generator object and its parameters to it
x, y = next(generator_1.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#BRIGHTNESS
generator_2 = tf.keras.preprocessing.image.ImageDataGenerator(brightness_range=(0.5,2))
#this tuple gives the range instead of explicitly giving the values like a list
x, y = next(generator_2.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#SHEAR TRANSFORMATION
generator_3 = tf.keras.preprocessing.image.ImageDataGenerator(shear_range=40)
#just like rotation shear is also in degrees
#in shear transformation the bottom coordinates are intact while the top coordinates can move in the shear_range degree
x, y = next(generator_3.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#ZOOM
generator_4 = tf.keras.preprocessing.image.ImageDataGenerator(zoom_range=0.5)
x, y = next(generator_4.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#CHANNEL SHIFT
generator_5 = tf.keras.preprocessing.image.ImageDataGenerator(channel_shift_range=100)
#this shifts the channel value of any rgb channel in range -100 to 100
x, y = next(generator_5.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
print(x.mean())#this calculates mean of all pixels in the image
#np.array(Image.open(image_path).mean())
#mean value of original image
#FLIPS
generator_6 = tf.keras.preprocessing.image.ImageDataGenerator(vertical_flip=True,horizontal_flip=True)
x, y = next(generator_6.flow_from_directory('images', batch_size=1))
plt.imshow(x[0].astype('uint8'));
#NORMALISATION
#1)FEATURE-WISE
#Nomalisation can be either featuewise or samplewise
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
generator_7 = tf.keras.preprocessing.image.ImageDataGenerator(
featurewise_center=True, # all values will be updated mean value will be reduced
featurewise_std_normalization=True
)
generator_7.fit(x_train)#this here is done to save the changes made by the generator
x, y = next(generator_7.flow(x_train, y_train, batch_size=1))
print(x.mean(), x.std(), y)#0.058420304 0.59477633 [[5]]
print(x_train.mean())#around 120.707565
#2)SAMPLE-WISE
#here we dont need to fit it to x_train and no need to calculate the std,mean as sampling is done
generator_8 = tf.keras.preprocessing.image.ImageDataGenerator(
samplewise_center=True,
samplewise_std_normalization=True
)
x, y = next(generator_8.flow(x_train, y_train, batch_size=1))
print(x.mean(), x.std(), y)#-1.9868216e-08 0.99999994 [[3]] ,
#RESCALING AND PREPROCESSING FUNCTION
generator_9 = tf.keras.preprocessing.image.ImageDataGenerator(
rescale=1.,
preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input
)
#1 way to do normalisation as well with rescale
#preprocessing fucntion take a 3-D Numpy array and returns that only
#just give parameters and it will be applied to every image generated by the generator
x, y = next(generator_9.flow(x_train, y_train, batch_size=1))
print(x.mean(), x.std(), y)#-0.26615605 0.47240233 [[2]]
#TRAINING OUR MODEL
generator_10 = tf.keras.preprocessing.image.ImageDataGenerator(
preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input,
horizontal_flip=True,
rotation_range=20
)
#Model
#pass list of layers in the sequential class
#1st layer a 3d to 2d tensor
model=tf.keras.models.Sequential([
tf.keras.applications.mobilenet_v2.MobileNetV2(
include_top=False, input_shape=(32,32,3),#shape of all the images in the dataset,
pooling='avg'
),
tf.keras.layers.Dense(10,activation='softmax')
])
model.compile(loss='sparse_categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
#loss is set that as we dont use OneHotEncoder and our values will be from 0-9
#using the flow method we can create a data iterator on our image and u pass that iterator as it is in model.fit
_=model.fit(generator_10.flow(x_train,y_train,batch_size=32),
epochs=1,steps_per_epoch=10)
|
41de36d6f7b3d3daaa24450d1b6e0fa6c97fa431 | antonvsdata/walking_dinner | /src/reader.py | 3,379 | 3.953125 | 4 | import csv
from participant import Participant
import sys
class Reader:
"""
Reader class for the .csv files
Currently, a minimum number of 18 participants is required
"""
def __init__(self, file, delimiter=","):
self.file = file
self.delimiter = delimiter
def check_header(self, hdr, location):
"""
Checks that the header of the file (column names) looks OK, exits if not
:param hdr: the header as list of strings
:param location: whether location will be used to create pairs
:return: None
"""
hdr_ok = True
if hdr[0] != "Name":
hdr_ok = False
print("First column is not called 'Name'")
if hdr[1] != "Contact":
hdr_ok = False
print("Second column is not called 'Contact'")
if hdr[2] != "Diet":
hdr_ok = False
print("Third column is not called 'Diet'")
if location:
if len(hdr) < 4:
hdr_ok = False
print("Too few columns!")
elif hdr[3] != "Location":
hdr_ok = False
print("Fourth column is not called 'Location'")
else:
if len(hdr) > 3:
if hdr[3] == "Location":
print("Note that location is not used for pairing, you can turn the feature on"
" by using the -l or --location flag")
if not hdr_ok:
print("Please check the input file")
sys.exit()
def read_by_location(self):
"""
Read the file and create Participant objects
Group participants into 3 groups based on location
- far
- near
- inda (because they are in da hood, sorry, 'in' is reserved)
:return: dict with 3 fields, each holding a list of Participant objects
"""
far = []
near = []
inda = []
with open(self.file) as csv_file:
rdr = csv.reader(csv_file, delimiter=self.delimiter)
hdr = next(rdr, None)
self.check_header(hdr, location=True)
for row in rdr:
if row[3] == "Far":
far.append(Participant(row[0], row[1], row[2]))
elif row[3] == "Near":
near.append(Participant(row[0], row[1], row[2]))
else:
inda.append(Participant(row[0], row[1], row[2]))
if (len(inda) + len(far) + len(near)) < 18:
print("Currently you need to have at least 18 participants!")
sys.exit()
participants = {"near": near, "far": far, "inda": inda}
return participants
def read_simple(self):
"""
Read the file and create Participant objects without grouping
:return: list of Participant objects
"""
participants = []
with open(self.file) as csv_file:
rdr = csv.reader(csv_file, delimiter=self.delimiter)
hdr = next(rdr, None)
self.check_header(hdr, location=False)
for row in rdr:
participants.append(Participant(row[0], row[1], row[2]))
if len(participants) < 18:
print("Currently you need to have at least 18 participants!")
sys.exit()
return participants
|
cb07bb7e8a75906f636c5b57a9aeb65b564cb89d | SidG404/Course-Work | /OPEN SOURCE/WEEK 4/2.py | 230 | 3.5625 | 4 | import numpy as np
user_input=int(input())
n=user_input
list=[]
while(n!=0):
m=n%10
n=n/10
list.append(m)
list.reverse()
numpy_array=np.array(list)
numpy_array.sort()
numpy_array=numpy_array[::-1]
print(numpy_array)
|
1f603a12707aad4eb77a203c707541b159b0a116 | JavierPacheco1601/StructuredProgramming-2A- | /funtions_intro.py | 1,337 | 4.03125 | 4 | from sys import argv as ag
def addToNumbers( number1, number2 ):
print('StartProgram: addToNumbers executed...\n')
result = number1+number2
return result
answer = False
def isEven( aNumber ):
if( aNumber%2 == 0 ):
return True
# print("it's even" )
else:
return False
# print("it is odd!")
## isPrime
if __name__ == "__main__":
# print(f' La suma de dos numeros = { addToNumbers( int(ag[1] ), int(ag[2]) ) } ')
n1 = int( input( 'Dame numero 1:\t' ) )
n2 = int( input('Dame numero 2:\t'))
# print( f' La suma de dos numeros = { addToNumbers( n1, n2 ) } ' )
# answer = isEven( addToNumbers( n1, n2) )
if( isEven( addToNumbers( n1, n2) ) ):
print( f'N1: "{n1}" and N2: "{n2}" are your lucky numbers!' )
else:
print( f'N1: "{n1}" and N2: "{n2}" are NOT your lucky numbers!' )
# if( isPrime( n3 ) ):
# print("n3 is prime")
# else:
# print("n3 is not prime")
# if( isPrime( n4 ) ):
# print("n4 is prime")
# else:
# print("n4 is not prime") |
e1e57f1b0ef3b9715575a6cea092f052695cefb2 | guyutza/myproject | /Yuze Gu Python Program/mapquest_client.py | 1,560 | 3.53125 | 4 | # Yuze Gu
import mapquest_api
import mapquest_classes_output
class MapQuestError(Exception):
pass
class RouteNotFoundError(Exception):
pass
def input_places() -> list:
'''let user input the locations and orders'''
places_num = int(input())
if places_num < 2:
raise MapQuestError
else:
place_list = []
for n in range(places_num):
place_list.append(input())
return place_list
def output_results() -> list:
'''get which output the user wants'''
result_num = int(input())
if result_num > 5:
raise MapQuestError
else:
outputs = []
for n in range(result_num):
outputs.append(input())
return outputs
def main():
'''main program'''
try:
places = input_places()
outputs = output_results()
make_url = mapquest_api.build_route_search_url(places)
result = mapquest_api.download_result(make_url)
if result['info']['statuscode'] != 0:
raise RouteNotFoundError
else:
output_lists = mapquest_classes_output.display_results(outputs)
print()
mapquest_classes_output.run_mapquests(output_lists, result)
print()
print('Directions Courtesy of MapQuest; Map Data Copyright OpenStreetMap Contributors.')
except RouteNotFoundError:
print()
print('NO ROUTE FOUND')
except:
print()
print('MAPQUEST ERROR')
if __name__ == '__main__':
main()
|
e1056968cd13a605ae4f0ff2cf1b2c3bb7d4459f | wolwemaan/katis | /foxsay.py | 257 | 3.5625 | 4 | def runtest(c):
while True:
j = [str(i) for i in input().split()]
if j[0] == "what":
print (" ".join(c))
return
else:
c = [value for value in c if value != j[-1]]
for n in range(0, int(input())):
runtest([str(i) for i in input().split()])
|
d61ea57024a9f16d89a6f12979fe6d8050209785 | ArkhipovNikita/Breakout | /objects/board.py | 878 | 3.53125 | 4 | import pygame
import random
from helps import Common, width, height
from base_classes import *
class Board(pygame.sprite.Sprite, GameObject):
"""
Class describing behavior of board object
Class inherits GameObject class
Attributes:
step step of moving by key
"""
def __init__(self, filename):
pygame.sprite.Sprite.__init__(self)
GameObject.__init__(self, filename)
self.rect.x = width / 2 - self.width / 2
self.rect.y = height - self.height - 15
self.step = 20
def update(self):
"""
Update coordinate of a board
"""
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and self.right + self.step <= width:
self.rect.x += self.step
elif keys[pygame.K_LEFT] and self.left - self.step >= 0 :
self.rect.x -= self.step
|
ce4538035bd10d46defe36ca39677409fad124a8 | AndresMontenegroArguello/UTC | /2020/Logica y Algoritmos/Tareas/Tarea 2/Extras/Python/Tarea 2.1 - Colones.py | 626 | 4.34375 | 4 | # Introducción
print("Logica y Algoritmos")
print("Andres Montenegro")
print("02/Febrero/2020")
print("Tarea 2.1")
print("Colones")
print("**********")
# Definición de variables
# Python es de tipado dinámico por lo que no es necesario declarar antes de asignar valor a las variables
# Ingreso de datos por el usuario
print("Ingrese la cantidad de Colones que posee Pepe: ")
Pepe = float(input())
# Procesamiento de datos
Juan = Pepe / 2
Ana = (Juan + Pepe) / 2
# Presentación de resultados
print("Pepe posee " + str(Pepe) + " Colones")
print("Juan posee " + str(Juan) + " Colones")
print("Ana posee " + str(Ana) + " Colones")
|
5e5d9fe7b10d00f927162e2b39c6eedaa4cb8538 | vijayprathap/PassCheck | /pass.py | 3,288 | 3.9375 | 4 | import re
import random
num_check = re.compile(r"[0-9]")
upp_case = re.compile(r"[A-Z]")
spl_char = set('`~!@#$%^&*()-_=+{[}]|\;:"\'<,>.?/')
#checks if the given password has atleast 6 characters
def sixLetter(password):
if len(password) >= 6:
return True
else:
return False
#checks if the given password has a number
def hasNumber(password):
val = num_check.search(password)
return bool(val)
#checks if the given password has a upper case character
def hasUpper(password):
val = upp_case.search(password)
return bool(val)
#checks if the given password has a spl character
def hasSplChar(password):
if any((c in spl_char) for c in password):
return True
else:
return False
#checks if a character in password is not repeated more than twice
def notSameChar(password):
ismore=False
for i in password:
count=0
for j in range(password.index(i)+1,len(password)):
if i is password[j]:
count+=1
c=password[j]
if count>1:
ismore=True
if ismore:
print 'character %s is repeated more than twice' % c
return False
else:
return True
#checks if the given password is weak or strong
def isWeakPassword(password):
if not sixLetters or not number or not hasUpperCase or not splChar or sameChar:
print "\nThe given password is not good enough"
return True
else:
print "\nThe given password is strong enough"
return False
#inserts a random number in the password string
def putNumber(password):
randindex = random.randint(0,len(password)-1)
randnum = random.randint(0,9)
newpass = password[:randindex] + str(randnum) + password[randindex:]
return newpass
#changes a random character to uppercase
def makeCaps(password):
randindex = random.randint(0,len(password)-1)
c=password[randindex]
while c.isdigit() or c in spl_char:
randindex = random.randint(0,len(password)-1)
c=password[randindex]
newpass = password[:randindex]+password[randindex].upper()+password[randindex+1:]
return newpass
#inserts a spl character randomly
def putSymbol(password):
randindex = random.randint(0,len(password)-1)
symbol=''.join(random.sample(spl_char,1))
newpass = password[:randindex] + symbol + password[randindex:]
return newpass
#gives information about your password
def genReport(password):
print "\nThe given password has six characters: %s" %sixLetters
print "\nThe given password has a number: %s" %number
print "\nThe given password has an uppercase character: %s" %hasUpperCase
print "\nThe given password has a special character: %s" %splChar
print "\nThe given password has a character repeated more than twice: %s" %sameChar
#gives you secure password
def fixPassword(password):
if not number:
password=putNumber(password)
if not hasUpperCase:
password=makeCaps(password)
if not splChar:
password=putSymbol(password)
st = "\nThe suggested password is %s" %password
return st
while True:
print "Password should be atleast 6 characters\n"
password = raw_input("Enter your password: ")
if sixLetter(password) and notSameChar(password):
break
sixLetters=sixLetter(password)
number = hasNumber(password)
hasUpperCase = hasUpper(password)
splChar = hasSplChar(password)
sameChar = not notSameChar(password)
genReport(password)
if isWeakPassword(password):
print fixPassword(password)
|
8bb4ef10fa5bb4e81806cdb797e2a7d857854f37 | mbeliogl/simple_ciphers | /Caesar/caesar.py | 2,137 | 4.375 | 4 |
import sys
# using caesar cipher to encrypy a string
def caesarEncrypt(plainText, numShift):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = []
cipherText = ''
plainText = plainText.lower()
# the for loop ensures we are looping around
for i in range(len(alphabet)):
if i + numShift >= 27:
key.append(alphabet[i + numShift - 27])
else:
key.append(alphabet[i+numShift])
# shifting each character n spaces
for i in range(len(plainText)):
cipherText = cipherText + key[alphabet.find(plainText[i])]
return cipherText
# decrypting the string by reversing the caesarEncrypt() method
def caesarDecrypt(cipherText, numberShift):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
key = []
plainText = ''
for i in range(len(alphabet)):
if i + numberShift >= 27:
key.append(alphabet[i + numberShift - 27])
else:
key.append(alphabet[i + numberShift])
for i in range(len(cipherText)):
plainText = plainText + alphabet[key.index(cipherText[i])]
return plainText
# breaking using brute force approach
def caesarBreak(cipherText):
guess = 1
for i in range(27):
print('Guess ' + str(guess) + ': ' + caesarDecrypt(cipherText, i))
guess = guess + 1
# driver
def main():
task_list = ['encrypt', 'decrypt', 'break']
task = input(f"Please choose the task type {task_list} : ")
if task == task_list[0]:
msg = input("Enter the string to encrypt: ")
key = int(input("Enter the key (how many letters to shift): "))
key = key % 27
encrypted_msg = caesarEncrypt(msg, key)
print(f"Your encrypted message: {encrypted_msg}")
if task == task_list[1]:
msg = input("Enter the string to decrypt: ")
key = int(input("Enter the key (how many letters to shift): "))
key = key % 27
decrypted_msg = caesarDecrypt(msg, key)
print(f"\nYour encrypted message: {decrypted_msg}")
if task == task_list[2]:
msg = input("Enter the string break: ")
caesarBreak(msg)
main()
|
4f481795b00a24195be24d735f5a05e9fa8f5055 | Yoatn/codewars.com | /Largest 5 digit number in a series.py | 1,000 | 3.796875 | 4 | # --------------------------------------------------
# Programm by Yoatn
#
# Start date 04.01.2018 19:47
# End date 04.01.2017 20:07
#
# Description:
#In the following 6 digit number:
# 283910
# 91 is the greatest sequence of 2 digits.
#
# In the following 10 digit number:
#
# 1234567890
# 67890 is the greatest sequence of 5 digits.
#
# Complete the solution so that it returns
# the largest five digit number found within
# the number given. The number will be passed
# in as a string of only digits. It should
# return a five digit integer. The number
# passed may be as large as 1000 digits.
#
# Adapted from ProjectEuler.net
# --------------------------------------------------
def solution(digits):
return max(int(digits[i:i + 5]) for i in range(len(digits)))
# StrIn = '1234567898765'
# BufferList = [0]
# for i in range(len(StrIn)):
# number = int(StrIn[0 + i:5 + i])
# if number > BufferList[0]:
# BufferList[0] = number
print(solution('1234567898765')) |
83a808d35782977e2ea92f9ed105d73f7d61f443 | strendley/CS3600 | /pa02/bin_otp.py | 2,466 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 19:47:56 2019
@author: stbrb@mst.edu
"""
import sys
def main():
keyFile = sys.argv[1] #grab all inputs
keyNum = sys.argv[2]
inFile = sys.argv[3]
outFile = sys.argv[4]
convertedString = convertInput(inFile) #convert the input file into binary
binaryString = getOtpKey(keyFile, keyNum) #grab the otpkey corresponding to keynum
XORString= XOR(convertedString, binaryString) #perform XOR on strings
translated = ASCII(XORString) #translate XOR'd string into ASCII
f = open(outFile, "w") #write the encrypted message to the outfile
f.write(translated)
f.close()
def convertInput(inFile):
f = open(inFile, mode='r', encoding='utf-8-sig') #read in the input file
inf = f.read()
f.close()
#if encoding, the length may be greater than 256 because of newline char???
if len(inf) > 256:
for letter in inf: #if there are any newline characters, remove them
if letter == '\n':
inf = inf.replace('\n', '')
#convert the string into binary
converted = ' '.join('{0:08b}'.format(ord(i), 'b') for i in inf)
#remove all spaces from the string
converted = converted.replace(' ', '')
return converted
def getOtpKey(keyFile, keyNum):
#read in the keyfile
f = open(keyFile, "r")
key = f.read()
f.close()
#check how the user inputs the keynum
intKeyNum = int(keyNum)
#add 0's to the front for consistency with the keyfile
if intKeyNum < 10:
num = '00' + str(intKeyNum)
elif intKeyNum < 100:
num = '0' + str(intKeyNum)
else:
num = keyNum
#grab the otpkey corresponding to the keynum
otp = key[key.find(num) + 4 : key.find(num) + 2052]
return otp
def XOR(convertedString, binaryString):
#convert the strings into ints and XOR them
result = int(convertedString, 2) ^ int(binaryString, 2)
#convert/format the result back into binary string
XORString = bin(result)[2:].zfill(len(convertedString))
return XORString
def ASCII(XORString):
translated = ''
for i in range(0,len(XORString),8): #from the start to the finish, every 8 chars
translated += chr(int(XORString[i:i+8],2)) #convert the 8-bit string into ascci
#print(translated)
return translated
if __name__ == '__main__':
main() |
8178b51bf3c1385ae1aa3c4fa1684e535be6357e | suay1936/suay1936-cmis-cs2 | /countup.py | 190 | 3.65625 | 4 | def countup(n):
if n >= 10:
print "Blast off"
else:
print n
countup(n + 1)
def main():
countup(0)
countup(1)
countup(-20)
return
main()
|
bbe8a937b2109cc02dcc2059d87a1e505b4bbc13 | suay1936/suay1936-cmis-cs2 | /simpleprogram.py | 1,702 | 3.921875 | 4 | # simpleprogram: currency conversion
import math
def baht_to_dollar(dollar1):
dollar1 = dollar1 / 35.63
def baht_to_pound(pound1):
pound1 = pound1 / 50.94
def dollar_to_baht(baht1):
baht1 = baht1 * 35.63
def dollar_to_pound(pound2):
pound2 = pound2 * 0.70
def pound_to_baht(baht2):
baht2 = baht2 * 50.94
def pound_to_dollar(dollar2):
dollar2 = dollar2 * 1.44
def total_baht(baht1, baht2):
return baht1 + baht2
def total_dollar(dollar1, dollar2):
return dollar1 + dollar2
def total_pound(pound1, pound2):
return pound1 + pound2
def printing(baht3, dollar3, pound3):
will_print = """ I now have {} baht, {} dollars, and {} pounds. """.format(baht3, dollar3, pound3)
return will_print
def main():
#input section
#baht to dollars and pounds
dollar1 = raw_input("How much money do you have in baht?: ")
pound1 = raw_input("Go do something with your money, how much money do you have in baht now?: ")
# dollars to baht and pounds
baht1 = raw_input("How much money do you have in dollars?: ")
pound2 = raw_input("Go do something with your money, how much money do you have in dollars now?: ")
# pound to baht and dollars
baht2 = raw_input("How much money do you have in pounds?: ")
dollar2 = raw_input("Go do something with your money, how much money do you have in pounds now?: ")
#processsing?
baht3 = total_baht(float(baht1), float(baht2))
dollar3 = total_dollar(float(dollar1), float(dollar2))
pound3 = total_pound(float(pound1), float(pound2))
will_print = printing(baht3, dollar3, pound3)
print will_print
#werk werk werk
main()
|
791db67ad389cdc6364342f60d73e9556877c0d3 | suay1936/suay1936-cmis-cs2 | /oneguess.py | 1,053 | 4.09375 | 4 | # What is the minimum number? 5
# What is the maximum number? 10
# I'm thinking of a number from 5 to 10.
# What do you think it is?: 7
# The target was 9.
# Your guess was 7.
# That's under by 2.
#need to use the if an comparison
# interval comparison
import random
import math
#adjust lines with def, check the if
def sub(guess, target):
return guess - target
def sub(guess, target):
return target - guess
def condition(guessTarget):
if (guess) > (target):
print "That's over by"
return sub(int(guess), int(target))
elif int(guess) < int(target):
print "That's under by"
return sub(int(target), int(guess))
else
print "That's amazing! Someone's a lucky soul today!"
def main():
minNumber = int(raw_input("What is the minimum number? "))
maxNumber = int(raw_input("What is the maximum number? "))
print "I'm thinking of a number from"
myNumberGuess = int(raw_input("What do you think it is?: "))
main()
|
89e0b00936b4f58aaa57beb6545c6f9e6008b48f | tmrd993/pythonchallenge | /ch6.py | 809 | 3.625 | 4 | from zipfile import ZipFile
zip = ZipFile('ch6.zip', 'r');
print(zip.getinfo('90052.txt').comment);
pathPrefix = 'ch6/';
fileType = '.txt';
filename = "90052";
fileContents = open(pathPrefix + filename + fileType, "r").read();
filename = fileContents[fileContents.index('is') + 3:];
print(str(zip.getinfo(filename + fileType).comment)[2], end=""); # print the first character
while 'nothing is' in fileContents:
fileContents = open(pathPrefix + filename + fileType, "r").read();
if('comments' in fileContents):
break;
filename = fileContents[fileContents.index('is') + 3:];
output = str(zip.getinfo(filename + fileType).comment);
output = output[2:output.index('\'', 2)] # strip quotation marks
if output == '\\n':
print();
else:
print(output, end='');
|
f62be8e37d8707398922cd9a310a8670fb7a5527 | JohnnyHowe/slow-engine | /display/camera.py | 869 | 3.546875 | 4 | from slowEngine.vector2 import Vector2
class Camera:
""" Camera class.
Uses singleton pattern.
Deals with game/world display things.
"""
# Singleton things
_instance = None
@staticmethod
def get_instance():
if Camera._instance is None:
Camera()
return Camera._instance
def __init__(self):
if Camera._instance is not None:
print("Camera instance already made.")
else:
self.on_startup()
Camera._instance = self
@staticmethod
def init():
Camera.get_instance()
# Camera help
zoom = None # How many pixels on screen? (min of height and width)
position = None
def on_startup(self):
""" When the singleton is first initialized, this is called. """
self.zoom = 10
self.position = Vector2(0, 0)
|
4d969849727d7b049825d2dcf47db14b7dd16a67 | AndrewBowerman/example_projects | /Python/oopRectangle.py | 1,745 | 4.5625 | 5 | """ oopRectangle.py
intro to OOP by building a Rectangle class that demonstrates
inheritance and polymorphism.
"""
def main():
print ("Rectangle a:")
a = Rectangle(5, 7)
print ("area: {}".format(a.area))
print ("perimeter: {}".format(a.perimeter))
print ("")
print ("Rectangle b:")
b = Rectangle()
b.width = 10
b.height = 20
print (b.getStats())
# start of my code
# create a base class with a constructor to inherit into rectangle class
class Progenitor(object):
def __init__(self, height = 10, width = 10):
object.__init__(self)
self.setHeight(height)
self.setWidth(width)
# lets get down to business
# to defeat the huns
class Rectangle(Progenitor):
#METHODS
#constructor is imported from progenitor
#setters for width and height
def setWidth (self, width):
self.__width = width
def setHeight (self, height):
self.__height = height
def setArea (self):
return getArea()
# getters return area and perimeter
def getArea (self):
return (self.__height * self.__width)
def getPerimeter (self):
return ((self.__height + self.__width) * 2)
# getter for all rectangle stats
def getStats (self):
print("width: {}".format(self.__width))
print("height: {}".format(self.__height))
print("area: {}".format(self.__area))
print("perimeter: {}".format(perimeter))
#ATTRIBUTES
width = property(fset = setWidth)
height = property(fset = setHeight)
area = property(fset = setArea, fget = getArea)
perimeter = property(fget = getPerimeter)
main()
|
35e90299fb38758fadf25e5a037bb62e618d47e3 | countone/exercism-python | /beer_song.py | 842 | 3.96875 | 4 | def recite(start, take=1):
song=[]
while take>0:
if start==0:
song.append('No more bottles of beer on the wall, no more bottles of beer.')
song.append('Go to the store and buy some more, 99 bottles of beer on the wall.')
elif start==1:
song.append('1 bottle of beer on the wall, 1 bottle of beer.')
song.append('Take it down and pass it around, no more bottles of beer on the wall.')
else:
song.append(str(start)+' bottles of beer on the wall, '+str(start)+ ' bottles of beer.')
if start==2:
song.append('Take one down and pass it around, 1 bottle of beer on the wall.')
else:
song.append('Take one down and pass it around, '+str(start-1)+' bottles of beer on the wall.')
if take!=1:
song.append('')
start-=1
take-=1
return song
|
63aa75a90f9b31c9959afd8eb59807253efabdbc | countone/exercism-python | /diamond.py | 620 | 3.90625 | 4 | from string import ascii_uppercase as UPPER
def make_diamond(letter):
diamond=[]
for i in range(UPPER.index(letter)+1):
if i==0:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
else:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(i*2-1)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
for i in range(UPPER.index(letter)-1,-1,-1):
if i==0:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
else:
diamond.append((UPPER.index(letter)-i)*' '+UPPER[i]+(i*2-1)*' '+UPPER[i]+(UPPER.index(letter)-i)*' ')
return '\n'.join(diamond)+'\n'
|
f637572b76b214df0d5f99698c7194e5d3ce92b9 | countone/exercism-python | /allergies.py | 895 | 3.90625 | 4 | class Allergies(object):
def __init__(self, score):
self.score=score
def is_allergic_to(self, item):
return (item in self.lst)
@property
def lst(self):
allergy_list=[]
temp_score=self.score%256
while temp_score>0:
if temp_score>=128:
temp_score-=128
allergy_list.append('cats')
elif temp_score>=64:
temp_score-=64
allergy_list.append('pollen')
elif temp_score>=32:
temp_score-=32
allergy_list.append('chocolate')
elif temp_score>=16:
temp_score-=16
allergy_list.append('tomatoes')
elif temp_score>=8:
temp_score-=8
allergy_list.append('strawberries')
elif temp_score>=4:
temp_score-=4
allergy_list.append('shellfish')
elif temp_score>=2:
temp_score-=2
allergy_list.append('peanuts')
elif temp_score>=1:
temp_score-=1
allergy_list.append('eggs')
return allergy_list[::-1]
|
59475aaeebbd95938a0ff08294533c03c59392e1 | countone/exercism-python | /clock.py | 873 | 3.921875 | 4 | class Clock(object):
def __init__(self, hour, minute):
hour+=minute//60
self.minute=minute%60
self.hour=hour%24
def __repr__(self):
if len(str(self.hour))==1 and len(str(self.minute))==1:
return '0'+str(self.hour)+':'+'0'+str(self.minute)
elif len(str(self.hour))==1 and len(str(self.minute))==2:
return '0'+str(self.hour)+':'+str(self.minute)
elif len(str(self.hour))==2 and len(str(self.minute))==1:
return str(self.hour)+':'+'0'+str(self.minute)
else:
return str(self.hour)+':'+str(self.minute)
def __eq__(self, other):
return self.minute== other.minute and other.hour==self.hour
def __add__(self, minutes):
return Clock(self.hour,self.minute+minutes)
def __sub__(self, minutes):
return Clock(self.hour,self.minute-minutes)
|
900f7d0045824991014ba4760bcd06867f3c4fbd | countone/exercism-python | /custom_set.py | 1,401 | 3.71875 | 4 | class CustomSet(object):
def __init__(self, elements=[]):
self.elements=set(elements)
def isempty(self):
return not self.elements
def __contains__(self, element):
return element in self.elements
def issubset(self, other):
return self.elements <=other.elements
def isdisjoint(self, other):
for value in list(self.elements):
if value in other.elements:
return False
else:
return True
def __eq__(self, other):
return self.elements==other.elements
def add(self, element):
self.elements=list(self.elements)
self.elements.append(element)
self.elements=set(self.elements)
def intersection(self, other):
intersection=[]
for value in self.elements:
if value in other.elements:
intersection.append(value)
return CustomSet(intersection)
def __sub__(self,other):
return self.difference(other)
def difference(self, other):
difference=list(self.elements)
for value in other.elements:
if value in self.elements:
difference.remove(value)
return CustomSet(difference)
def __add__(self,other):
return self.union(other)
def union(self, other):
return CustomSet(list(self.elements)+list(other.elements)) |
ff473968b091617a36adeabd52181a0b9c6fd27f | yuzhengDL/MSAN | /vocab.py | 1,213 | 3.578125 | 4 | """
Constructing and loading dictionaries
"""
import numpy
from collections import OrderedDict
from collections import Counter
def build_dictionary(text):
"""
Build a dictionary
text: list of sentences (pre-tokenized)
"""
counter = Counter()
captions = []
for s in text:
tokenized_captions = []
s = s.lower()
tokenized_captions.extend(s.split())
#tokenized_captions.append("</s>")
captions.append(tokenized_captions)
for cc in captions:
counter.update(cc)
print("Total words:", len(counter))
word_counts = [x for x in counter.items() if x[1] >= 3]
word_counts.sort(key=lambda x:x[1], reverse=True)
print("Words in vocabulary:", len(word_counts))
reverse_vocab = [x[0] for x in word_counts]
worddict = OrderedDict([(x, y+2) for (y,x) in enumerate(reverse_vocab)])
worddict['<eos>'] = 0
worddict['UNK'] = 1
wordcount = OrderedDict(word_counts)
return worddict, word_counts
def load_dictionary(loc):
"""
Load a dictionary
"""
with open(loc, 'rb') as f:
worddict = pkl.load(f)
return worddict
def save_dictionary(worddict, wordcount, loc):
"""
Save a dictionary to the specified location
"""
with open(loc, 'wb') as f:
pkl.dump(worddict, f)
pkl.dump(wordcount, f)
|
eb32a71508ff54d97244320b409274f2a06e4253 | singhankur7/Python | /classes ass.py | 3,623 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 22:53:14 2019
@author: Ankur Singh
"""
"""
Python is easy : Homework assignment #9
Classes
"""
# creating a class
class Vehicle:
def __init__(self, make, model, year, wt, TSM, NM): #declaring class attributes
self.make = make
self.model = model
self.year = year
self.weight =wt
self.TripsSinceMaintenance = TSM
self.NeedsMaintenance = NM
def getMake(self): #getter
return self.make #function used to get the value
def setMake(self, make): #setter
self.make = make #function used to set the value
def getModel(self):
return self.model
def setModel(self):
self.model = model
def getYear(self):
return self.year
def setYear(self):
self.year = year
def getWeight(self):
return self.weight
def setWeight(self,wt):
self.weight = wt
Vhcl = Vehicle("make", "model", "year", "wt", 0, False)
#child class is created which will inherit the properties of their parent class
class Cars(Vehicle):
def __init__(self, make, model, year, wt, TSM, NM, isDriving):
Vehicle.__init__(self, make, model, year, wt,TSM, NM)
self.isdriving = isDriving
def Drive(self):
self.isDriving = True
def Stop(self):
self.isDriving = False
def Repair(self):
self.TripsSinceMaintenance = 0
self.NeedsMaintenance = False
def Switching(self):
if self.isDriving == True:
self.TripsSinceMaintenance = 0
else:
self.TripsSinceMaintenance = self.TripsSinceMaintenance + 1
if self.TripsSinceMaintenance > 100:
self.NM = True
car1 = Cars("Lamborghini", "Huracan", 2018, 1450, 0, False, True)
car2 = Cars("Aston Martin", "DB11", 2017, 1800, 150, True, False)
car3 = Cars("Ferrari", "GTC4Lusso", 2016, 1700, 70, False, False)
car1.Drive()
car1.Stop()
car1.Drive()
car1.Drive()
car1.Stop()
car1.Switching()
car2.Drive()
car2.Stop()
car2.Drive()
car2.Drive()
car2.Stop()
car2.Switching()
car3.Drive()
car3.Stop()
car3.Drive()
car3.Drive()
car3.Stop()
car3.Switching()
car1.Repair()
print("Make : "+car1.make)
print("Model : "+car1.model)
print("Year : "+str(car1.year))
print("Weight : "+str(car1.weight))
print("TripsSinceMaintenance : "+str(car1.TripsSinceMaintenance))
print("NeedsMaintenance : "+str(car1.NeedsMaintenance)+"\n")
print("Make : "+car2.make)
print("Model : "+car2.model)
print("Year : "+str(car2.year))
print("Weight : "+str(car2.weight))
print("TripsSinceMaintenance : "+str(car2.TripsSinceMaintenance))
print("NeedsMaintenance : "+str(car2.NeedsMaintenance)+"\n")
print("Make : "+car3.make)
print("Model : "+car3.model)
print("Year : "+str(car3.year))
print("Weight : "+str(car3.weight))
print("TripsSinceMaintenance : "+str(car3.TripsSinceMaintenance))
print("NeedsMaintenance : "+str(car3.NeedsMaintenance)+"\n")
|
6f7d33585fac28efdcbd848c65e489bb71044b0b | singhankur7/Python | /advanced loops.py | 2,306 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 9 23:48:15 2019
@author: New
"""
"""
Python is easy: Homework assignment #6
Advanced Loops
"""
# for the maximum width(columns) and maximum height(rows) that my playing board can take
# This was achieved by trial and error
# Defining the function which takes two inputs - rows and columns
def playingBoard(rows,columns):
if rows<=15 and columns<=15: #declaring the number of rows and columns
for r in range(1,rows): #loop for the rows
if r % 2 == 0: #checking the rows if it is even or not
for c in range(1,columns): #loop for the columns
if c % 2 == 1: #checking the columns for odd
print(" ",end=" ") #printing for even row and odd column
else:
print("$$",end=" ") #printing for even row and even column
else:
for c in range(1,columns):
if c % 2 == 1:
print("$$",end=" ") #printing for odd row and odd column
else:
print(" ",end=" ") #printing for odd row and even column
print(" ")
return True
else:
return False
op = playingBoard(6,8) #calling the function and passing the value
if op == True:
print("True : playing board is created successfully")
else:
print("False : number of rows and columns exceeds the limit")
print(" ")
print("check maximum width and height of playing board")
print(" ")
op = playingBoard(11,14) #calling the function and passing the value
if op == True:
print("True : playing board is created successfully")
else:
print("False : number of rows and columns exceeds the limit")
print(" ")
print("check maximum width and height of playing board")
print(" ")
op = playingBoard(16,18) #calling the function and passing the value
if op == True:
print("True : playing board is created successfully")
else:
print("False : number of rows and columns exceeds the limit")
|
d05538641aeebe5475ec7d5b83c4bab4d6a77296 | NadiaAlmutlak/Intro-Python | /Desktop/IntroPython/Midterm/Midterm Practice/baseball.py | 2,490 | 3.71875 | 4 | # in the case the csv is provided this code can be directly applicable by just changing the csv name
import csv
comparator_ops = ["min", "max"] # these operators give us the different mathmatical function labels we may use
math_ops = ["sum", "avg"]
valid_op_names = comparator_ops + math_ops # if another label is inserted and not part of the valid op lists,
# it will result in errors
def evaluate_sheet(column_name, op_name, fn="data.csv"): # you can change the csv file input here
result = None
try:
with open(fn, "r") as d: # reads our data file
cr = csv.reader(d, delimiter=",")
op_index = valid_op_names.index(op_name) # provides the valid ops within this function
c_index = None
count = 0
for r in cr:
# print(r)
if c_index is None:
c_index = r.index(column_name)
else:
count = count + 1
v = r[c_index]
if op_name in comparator_ops:
if result is None:
result = v
else:
if op_name == 'max' and v > result:
result = v
elif op_name == 'min' and v < result:
result = v
else:
if result is None:
result = 0
result = result + float(v)
if op_name == 'avg':
result = result / count
d.close()
except ValueError as v:
print(type(v), v)
result = None
except FileNotFoundError as fe:
print(type(fe), fe)
result = None
except UnicodeError as ue:
print(type(ue), ue)
result = None
except TypeError as te:
print(type(te), te)
result = None
except ValueError as ve:
result = None
print(type(ve), ve)
return result
#Test cases
print("h,max = ", evaluate_sheet('h', 'max'))
print("h,max = ", evaluate_sheet('playerid', 'max'))
print("h,max = ", evaluate_sheet('h', 'sum'))
print("h,max = ", evaluate_sheet('playerid', 'max', 'foo.bar'))
print("yearid,max = ", evaluate_sheet('yearid', 'min'))
print("hr,min = ", evaluate_sheet('hr', 'min'))
print("hr,sum = ", evaluate_sheet('hr', 'sum'))
print("hr,avg = ", evaluate_sheet('hr', 'avg'))
|
5bae9f98d4a044f24784506c634426868a01ae77 | Kenoro1/pop | /3.py | 690 | 4.09375 | 4 | months = int(input('Введите месяц ввиде целого числа: '))
winter = [12, 1, 2]
spring = [3, 4, 5]
summer = [6, 7, 8]
autumn = [9, 10, 11]
if months in winter:
print('Зима')
if months in spring:
print('Весна')
if months in summer:
print('Лето')
if months in autumn:
print('Осень')
# ----------------------homework_3(2var)_____________________
months = int(input('Введите месяц ввиде целого числа: '))
dict_months = {
[12, 1, 2]:'Зима',
[3, 4, 5]:'Весна',
[6, 7, 8]:'Лето',
[9, 10, 11]:'Осень'
}
if months in dict_months.keys():
print(dict_months.values())
|
47e5298eb88a8cb40827b8a0ed5745e0dbcbb74a | sagarneeli/coding-challenges | /Other/cube.py | 805 | 4.0625 | 4 | """
Question:
You have 15 six-sided blocks.
These are cubes with a letter (or a blank space) on each face.
Each block can have a different set of letters.
For instance, one block may have A E I O U _ on its faces;
another block may have A B C D E E.
Write a function that takes as input a 15 character message
and the 15 blocks and returns a new ordering of the blocks
that can spell out the message.
0 1 2
Input - blocks = [['A', 'B', 'C', ''], ['X', 'Y', 'Z'], ['P', 'R', 'S']], message = 'SYB'
Output - (new ordering of block) = [2, 1, 0]
0 1 2
Input - blocks = [['A', 'B', 'C'], ['C', 'Y', 'Z'], ['P', 'R', 'S']], message = 'CAR'
Output - (new ordering of block) = [1, 0, 2]
""" |
3c72263a7c1a33651b5ab20d448b57a0810160dc | sagarneeli/coding-challenges | /Arrays/spiral_order.py | 1,028 | 4.0625 | 4 |
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Game plan
1. Keep 4 pointers top, bottom, left, right
2. Start from the first row and iterate over the columns, top = 0, left += 1
3. Once you read the end, Keey the column constant and start incrementing the row. left = len(matrix) and top += 1
4. Once you reach the bottom, right -= 1, bottom = len(matrix)
5. Last step - top -= 1, left = 0
-
"""
def spiralOrder(matrix):
result = []
if len(matrix) == 0:
return []
top = 0
bottom = 0
left = 0
right = 0
while left <= len(matrix) or right >= 0:
for i in range(len(matrix)):
result.append(matrix[top][left])
left += 1
top += 1
isBottom = True
if isBottom:
for i in range(len(matrix)):
result.append(matrix[top][left])
left += 1
|
b6b9a578c524fa372d4adf93096d3a5c29b5c5d0 | sagarneeli/coding-challenges | /Linked List/evaluate_expression.py | 2,583 | 4.59375 | 5 | # Python3 program to evaluate a given
# expression where tokens are
# separated by space.
# Function to find precedence
# of operators.
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
# Function to perform arithmetic
# operations.
def applyOp(a, b, op):
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a // b
# Function that returns value of
# expression after evaluation.
def evaluate(tokens):
# stack to store integer values.
values = []
# stack to store operators.
ops = []
i = 0
while i < len(tokens):
# Current token is a whitespace,
# skip it.
if tokens[i] == ' ':
i += 1
continue
# Current token is an opening
# brace, push it to 'ops'
elif tokens[i] == '(':
ops.append(tokens[i])
# Current token is a number, push
# it to stack for numbers.
elif tokens[i].isdigit():
val = 0
# There may be more than one
# digits in the number.
while (i < len(tokens) and tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
i += 1
values.append(val)
# Closing brace encountered,
# solve entire brace.
elif tokens[i] == ')':
while len(ops) != 0 and ops[-1] != '(':
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# pop opening brace.
ops.pop()
# Current token is an operator.
else:
# While top of 'ops' has same or
# greater precedence to current
# token, which is an operator.
# Apply operator on top of 'ops'
# to top two elements in values stack.
while (len(ops) != 0 and
precedence(ops[-1]) >= precedence(tokens[i])):
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Push current token to 'ops'.
ops.append(tokens[i])
i += 1
# Entire expression has been parsed
# at this point, apply remaining ops
# to remaining values.
print(values)
print(ops)
while len(ops) != 0:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
print(val2)
print(val1)
print(ops)
values.append(applyOp(val1, val2, op))
# Top of 'values' contains result,
# return it.
return values[-1]
# Driver Code
# print(evaluate("10 + 2 * 6"))
# print(evaluate("100 * 2 + 12"))
print(evaluate("(1+(4+5+2)-3)+(6+8)"))
# print(evaluate("3 + 2 * 2"))
# This code is contributed
# by Rituraj Jain |
eccee14c4a5a92446a898f2c1a668b4036122070 | hehao9/Mushroom | /sqlite3_help.py | 3,193 | 3.71875 | 4 | import sqlite3
class Sqlite3DB:
def __init__(self, db_name=None):
self.conn = sqlite3.connect(db_name if db_name else 'system.db')
self.cursor = self.conn.cursor()
def create_table(self, table_name: str, field_list: list):
"""
创建表格
:param table_name: 表名
:param field_list: 字段列表,例如:["name","age","gender"]
:return:
"""
fields = ",".join([field + " TEXT" for field in field_list])
sql = f"CREATE TABLE {table_name} ({fields});"
self.cursor.execute(sql)
self.conn.commit()
def insert_data(self, table_name: str, data):
"""
插入数据,根据传入的数据类型进行判断,自动选者插入方式
:param table_name: 表名
:param data: 要插入的数据
:return:
"""
if isinstance(data, list):
for item in data:
keys = ",".join(list(item.keys()))
values = ",".join([f"'{x}'" for x in list(item.values())])
sql = f"INSERT INTO {table_name} ({keys}) VALUES ({values});"
self.cursor.execute(sql)
elif isinstance(data, dict):
keys = ",".join(list(data.keys()))
values = ",".join([f"'{x}'" for x in list(data.values())])
sql = f"INSERT INTO {table_name} ({keys}) VALUES ({values});"
self.cursor.execute(sql)
self.conn.commit()
def query_data(self, sql: str) -> list:
"""
查询数据
:param sql: 要查询的sql语句
:return:
"""
results = []
self.cursor.execute(sql)
cols = [desc[0] for desc in self.cursor.description]
for row in self.cursor.fetchall():
data = {}
for i, col in enumerate(cols):
data[col] = row[i]
results.append(data)
return results
def execute(self, sql: str):
"""
查询数据
:param sql: 要执行的sql语句
:return:
"""
self.cursor.execute(sql)
self.conn.commit()
def close(self):
"""
关闭数据库连接
:return:
"""
self.cursor.close()
self.conn.close()
if __name__ == '__main__':
db = Sqlite3DB()
# db.create_table('song_play_list', ['visitor_id', 'song_id', 'song_name', 'song_singer', 'song_album',
# 'song_duration', 'song_platform', 'song_album_id', 'song_hash'])
# db.insert_data("song_play_list", {'visitor_id': '93900461f5b249e998e9ce7128d47021', 'song_id': '190072',
# 'song_name': '黄昏', 'song_singer': '周传雄', 'song_album': '忘记 transfer',
# 'song_duration': '05:44', 'song_platform': 'netease-cloud',
# 'song_album_id': '', 'song_hash': ''})
# db.execute('delete from song_play_list where song_id = "190072"')
# db.execute('drop table song_play_list')
print(db.query_data("select * from song_play_list where visitor_id = '93900461f5b249e998e9ce7128d47021'"))
db.close()
|
b408fbae9bcbcdcc49651da01f35bfffb92f7b6d | AntoineMau/N-Puzzle | /utils.py | 1,086 | 3.828125 | 4 | def error(index_error):
list_error = {
'Bad file': 'Error: Bad file',
'Unsolvable': 'Error: Puzzle is unsolvable',
'Under size': 'Error: Size must be ≥ 3',
'Under shuffle': 'Error: Number of shuffle must be ≥ 0',
}
print(list_error[index_error])
exit(1)
def swap(data, i1, i2):
data[i1], data[i2] = data[i2], data[i1]
return tuple(data)
def next_move(data, size):
index = data.index(0)
l = list()
col, line = index%size, int(index/size)
if line != 0:
l.append(swap(list(data), index, index-size))
if line != size-1:
l.append(swap(list(data), index, index+size))
if col != 0:
l.append(swap(list(data), index, index-1))
if col != size-1:
l.append(swap(list(data), index, index+1))
return l
def make_goal(size):
cycle = {(1, 0): (0, 1), (0, 1): (-1, 0), (-1, 0): (0, -1), (0, -1): (1, 0)}
total_size = size**2
goal = [0] * total_size
x, y, ix, iy = 0, 0, 1, 0
for i in range(1, total_size):
if (x+ix == size or y+iy == size or goal[x + ix + (y+iy)*size] != 0):
ix, iy = cycle[(ix, iy)]
goal[x + y*size] = i
x += ix
y += iy
return goal
|
668cf41a649c6771f2b239253ef5449fb70f6487 | lesnerd/weary_traveler | /loaders/csv_steps_array_loader.py | 895 | 3.625 | 4 | import pandas
import pandas as pd
class CSVStepsArrayLoader(object):
@staticmethod
def load(file_path):
try:
df = pd.read_csv(file_path, sep=',', header=None, skip_blank_lines=True).dropna()
except pandas.errors.EmptyDataError:
raise pandas.errors.EmptyDataError('No data to read.')
if df.empty:
raise IOError('The file is empty.')
return df.values[0].astype(int).tolist()
"""
df = pd.read_csv(file_path, usecols=[1], sep=',')
if df.empty:
raise IOError('The file is empty.')
print(df.values.astype(int).tolist())
return df.iloc[:,0].tolist()
with open(file_path) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
row = [int(row[1]) for row in csv_reader]
return row
""" |
6cbceeafb452648885a2cda8a579f917f96265be | dianalow/deeplearning | /softmax.py | 900 | 3.53125 | 4 | """Softmax."""
import numpy as np
scores = np.array([3.0, 1.0, 0.2])
# scores = np.array([[1, 2, 3, 6],
# [2, 4, 5, 6],
# [3, 8, 7, 6]])
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
#pass # TODO: Compute and return softmax(x)
values = np.exp(x);
return values/np.sum(values,axis=0)
"""
long method
if len(np.shape(values))>1 :
values_t = np.transpose(values)
for i in xrange(len(values_t):
values_t[i]=values_t[i]/np.sum(values_t[i])
return(np.transpose(values_t))
else:
return values/np.sum(values)
"""
print(softmax(scores))
# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
plt.plot(x, softmax(scores).T, linewidth=2)
plt.show()
|
0a1a0f66af66feb4ee13899192bc64ef2d66f018 | sy-li/ICB_EX7 | /ex7_sli.py | 1,791 | 4.375 | 4 | # This script is for Exercise 7 by Shuyue Li
# Q1
import pandas as pd
def odd(df):
'''
This function is aimed to return the add rows of a pandas dataframe
df should be a pandas dataframe
'''
nrow = df.shape[0]
odds = pd.DataFrame()
for i in range(1,nrow):
if i%2 == 0:
continue
else:
odds = odds.append(df.iloc[i,:])
return odds
# test data
iris = pd.read_csv("iris.csv", delimiter = ",")
print odd(iris)
# Q2
def ct_sp(data,species):
'''
This function is aimed to return the number of observations for a given
species included in the data set
data should be a pandas dataframe; species should be a string
'''
sp = data.loc[data['Species']==species]
return sp.shape[0]
# test data
iris = pd.read_csv("iris.csv", delimiter = ",")
print ct_sp(iris,"setosa")
def select_sepal(data,width):
'''
This function is used to return a dataframe for flowers with Sepal.Width
greater than a value specified by the function user
data is a pandas dataframe; width is specified width
'''
if width > data["Sepal.Width"].max():
print "Invalid value: larger than maximum width"
else:
select = data.loc[data['Sepal.Width'] > width]
return select
# test data
iris = pd.read_csv("iris.csv", delimiter = ",")
print select_sepal(iris,3.5)
def extract_species(data,species):
'''
This function is used to select a given species and save to a csv file
data should be a pandas dataframe; species should be a string
'''
sp = data.loc[data['Species']==species]
file_name = str(species) + ".csv"
sp.to_csv(file_name, sep=',')
# test data
iris = pd.read_csv("iris.csv", delimiter = ",")
extract_species(iris,"setosa") |
d6ba9957ecd45606826386e031558efca3474a0b | jtanium/turbo-garbanzo | /vehicle_prices.py | 888 | 3.609375 | 4 | import numpy as np
def predict(X, w):
return np.matmul(X, w)
def loss(X, Y, w):
return np.average((predict(X, w) - Y) ** 2)
def gradient(X, Y, w):
return 2 * np.matmul(X.T, (predict(X, w) -Y)) / X.shape[0]
def train(X, Y, iterations, lr):
w = np.zeros((X.shape[1], 1))
for i in range(iterations):
if i % 1000 == 0:
print("Iteration %4d => Loss: %.15f" % (i, loss(X, Y, w)))
w -= gradient(X, Y, w) * lr
return w
dataset = np.loadtxt("car_details_v3.csv", delimiter=",", skiprows=1) #, unpack=True)
y = dataset[:, -1]
dataset = dataset[:, :-1]
X = np.column_stack((np.ones(dataset[:, 0].size), dataset))
Y = y.reshape(-1, 1)
w = train(X, Y, iterations=1000000, lr=0.0000000001)
print("\nWeights: %s" % w.T)
print("\nA few predictions:")
for i in range(5):
print("X[%d] -> %.4f (label: %d)" % (i, predict(X[i], w), Y[i]))
|
70a613a86f90ab97397f9c29797b220793428aa4 | 44746/Lists | /Caesar.py | 652 | 4.03125 | 4 | def input1():
message = input("Please enter the message: ")
cora = input("Is the message in caesar or english? c or e: ")
if cora == "c":
shift = -3
else:
shift = 3
return message,shift
def process(message,shift):
list1 = list(message)
list2 = []
for index in range(len(message)):
character = list1[index]
index= index+1
ascii_character = ord(character)
caesar = ascii_character + shift
character = chr(caesar)
list2.append(character)
print(list2)
def main():
message,shift= input1()
process(message,shift)
main()
|
385567e7cf206dc047dd799ac28615e9c49525e2 | 44746/Lists | /bubble sort1.py | 405 | 3.734375 | 4 |
list1= []
item = '1'
while item!= "0":
item=input("Please add an item to a list: ")
if item!= "0":
list1.append(item)
no_swaps=False
while no_swaps != True:
no_swaps= True
for count in range (len(list1)-1):
if list1[count]> list1[count+1]:
no_swaps = False
list1[count+1],list1[count] = list1[count],list1[count+1]
print(list1)
|
63cf9296c1b57a4e5999d3a077cbdde4bef9fc0c | danu0/Particle_Electric_Field | /run_electron_rk4_1.py | 1,253 | 3.515625 | 4 | from electron_rk4_1 import *
import numpy as np
import matplotlib.pyplot as plt
Ex = 0 #
Ey = 0 #
B = 1e-4 #
t0 = 0.0 # initial time
dt = 1e-9 # integration time step
tmax= 1e-6 # end of integration
x0=0.0 # initial x position
y0=0.0 # initial y position
vx0=100 # initial speed along the x axis
vy0=0.0 # initial speed along the y axis
ode = ElectronRK4([x0, y0, vx0, vy0], dt, t0, Ex, Ey, B)
ode.iterate(tmax)
plt.xlabel("x", fontsize=22) # Set horizontal (x) figure label to "x"
plt.ylabel("y", fontsize=22) # Set vertical (y) figure label to "y"
plt.axis('equal') # The x and y scales are identical. To see a circle
ode.plot(2, 1, "g*") # plot y(x) using green stars
#plt.savefig("5_4_c_1.pdf")
plt.show()
plt.xlabel("t", fontsize=22) # Set horizontal (x) figure label to "t"
plt.ylabel("x", fontsize=22) # Set vertical (y) figure label to "x"
ode.plot(1, 0, "b-") # plot x(t) in blue
#plt.savefig("5_4_c_2.pdf")
plt.show()
plt.xlabel("t", fontsize=22) # Set horizontal (x) figure label to "t"
plt.ylabel("y", fontsize=22) # Set vertical (y) figure label to "y"
ode.plot(2, 0, "r-") # plot y(t) in red
#plt.savefig("5_4_c_3.pdf")
plt.show()
|
c24b76b40773bcde6356d5ba2f951cdd3eea5d94 | io-ma/Zed-Shaw-s-books | /lmpthw/ex4_args/sys_argv.py | 1,302 | 4.4375 | 4 | """
This is a program that encodes any text using the ROT13 cipher.
You need 2 files in the same dir with this script: text.txt and result.txt. Write your text in text.txt, run the script and you will get the encoded version in result.txt.
Usage:
sys_argv.py -i <text.txt> -o <result.txt>
"""
import sys, codecs
for arg in sys.argv[1:]:
arg_pos = sys.argv[1:].index(arg) + 1
if arg in ["-h", "--help", "-i", "--input", "-o", "--output"]:
if arg == "-h" or arg == "--help":
v = __doc__
print(v)
elif arg == "-i" or arg == "--input":
ifile = sys.argv[arg_pos + 1]
text = ifile
elif arg == "-o" or arg == "--output":
ofile = sys.argv[arg_pos +1]
result = ofile
else:
print("""You need an input and an output file. Type -h for more info.""")
class Encode(object):
def encode_txt(self):
""" This function encodes the text """
txt = open(text)
read = txt.read()
encoded = codecs.encode(read, 'rot_13')
target = open(result, 'w')
target.write(encoded)
target.close()
def main():
encode = Encode()
encode.encode_txt()
print("Succes! Your file is encoded.")
if __name__ == "__main__":
main()
|
4a0b6ac25992d4fe863ab606b9bba7ac76c2f803 | io-ma/Zed-Shaw-s-books | /lpthw/ex45/diver.py | 609 | 3.703125 | 4 | class Diver(object):
""" Main diver class """
def __init__(self, diver_name):
""" Initialize diver class """
self.name = diver_name
self.choices = {
'instructor_name': 'x',
'cave_name': 'y',
'equipment': []
}
self.points = None
def set_instructor(self, instructor_name):
self.choices['instructor_name'] = instructor_name
def set_cave(self, cave_name):
self.choices['cave_name'] = cave_name
def set_equipment(self, equipment_choices):
self.choices['equipment'] = equipment_choices
|
964a73303ef9c60790a12e94a0315b7dce610afb | io-ma/Zed-Shaw-s-books | /lpthw/ex4/ex4_sd3.py | 813 | 3.78125 | 4 | # cars is 100
cars = 100
# space_in_a_car is 4.0
space_in_a_car = 4.0
# drivers is 30
drivers = 30
# passengers is 90
passengers = 90
# cars_not_driven is cars - drivers
cars_not_driven = cars - drivers
# cars_driven is drivers
cars_driven = drivers
# carpool_capacity is cars_driven * space_in_a_car
carpool_capacity = cars_driven * space_in_a_car
# average_passengers_per_car is passengers / cars_driven
average_passengers_per_car = passengers / cars_driven
print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available.")
print("There will be", cars_not_driven, "empty cars today.")
print("We can transport", carpool_capacity, "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car,
"in each car.") |
fce87c3bacfa0a2b794f793c5c8bc62d35015784 | io-ma/Zed-Shaw-s-books | /lmpthw/ex13_sll/sll.py | 4,858 | 3.953125 | 4 | class SingleLinkedListNode(object):
def __init__(self, value, nxt):
self.value = value
self.next = nxt
def __repr__(self):
nval = self.next and self.next.value or None
return f"[{self.value}:{repr(nval)}]"
class SingleLinkedList(object):
def __init__(self):
self.begin = None
self.end = None
def push(self, obj):
"""Appends a new value on the end of the list."""
new_node = SingleLinkedListNode(obj, None)
print("new node:", new_node)
if self.begin == None:
self.begin = new_node
self.end = self.begin
else:
self.end.next = new_node
self.end = new_node
print(self.begin, self.end)
def pop(self):
"""Removes the last item and returns it."""
if self.end == None:
return None
elif self.end == self.begin:
new_node = self.begin
self.end = self.begin = None
return new_node.value
else:
new_node = self.begin
while new_node.next != self.end:
new_node = new_node.next
#assert self.end != new_node
self.end = new_node
return new_node.next.value
def shift(self, obj):
"""Another name for push."""
new_node = SingleLinkedListNode(obj, None)
print("new node:", new_node)
if self.end == None:
self.begin = new_node
self.end = self.begin
else:
new_node.next = self.begin
self.begin = new_node
print(f"self.begin is:{self.begin} self.begin.next is: {self.begin.next}")
def unshift(self):
"""Removes the first item and returns it."""
if self.begin == None:
return None
elif self.begin == self.end:
new_node = self.begin
self.begin = self.end = None
return new_node.value
else:
value = self.begin.value
self.begin = self.begin.next
return value
def remove(self, obj):
"""Finds a matching item and removes it from the list."""
temp = self.begin
if temp is not None:
if temp.value == obj:
self.begin = temp.next
temp = None
return
while temp is not None:
if temp.value == obj:
break
prev = temp
temp = temp.next
if temp == None:
return
# Unlink the node from linked list
prev.next = temp.next
temp = None
def first(self):
"""Returns a reference to the first item, does not remove."""
return self.begin.value
def last(self):
"""Returns a reference to the last item, does not remove."""
return self.end.value
def count(self):
"""Counts the number of elements in the list."""
new_node = self.begin
count = 0
while new_node:
count += 1
new_node = new_node.next
return count
def get(self, index):
"""Get the value at index."""
nr = self.count()
count = 0
if nr == 0:
return None
elif index > nr:
return "Error"
else:
node = self.begin
while node:
if nr == index:
return node.value
else:
node = node.next
count += 1
def shift(self, obj):
"""Another name for push."""
def dump(self, mark):
"""Debugging function that dumps the contents of the list."""
pass
colors = SingleLinkedList()
'''colors.push("blue")
colors.push("yellow")
colors.push("red")
colors.push("pink")
colors.push("orange")
print(">>>>> start shifting <<<<<")
print("colors count:", colors.count())
colors.shift("blue")
print(f"shift colors begin: {colors.begin}, colors end: {colors.end}")
print("colors count:", colors.count())
colors.shift("yellow")
print(f"shift colors begin: {colors.begin}, colors 2: {colors.begin}, colors end: {colors.end}")
print("colors count:", colors.count())
colors.shift("pink")
print(f"shift colors begin: {colors.begin}, colors end: {colors.end}")
print("colors count:", colors.count())
print("colors pop:", colors.pop())
print(f"colors begin: {colors.begin}, colors 2: {colors.begin.next}, colors end: {colors.end}")
print("colors count:", colors.count())
print("colors pop:", colors.pop())
print(f"colors begin: {colors.begin}, colors 2: {colors.begin.next}, colors end: {colors.end}")
print("colors count:", colors.count())
print("colors pop:", colors.pop())
print(f"colors begin: {colors.begin}")
print("colors count:", colors.count())
'''
#colors.unshift()
#colors.unshift()
|
cdf3e69d108a22b4f439d7f3891be6180e5eff39 | io-ma/Zed-Shaw-s-books | /lpthw/ex7/ex7_sd1.py | 834 | 4.09375 | 4 | # prints a string
print("Mary had a little lamb.")
# prints a string that contains another string
print("Its fleece was white as {}.".format('snow'))
# prints a string
print("And everywhere that Mary went.")
# prints 10 times .
print("." * 10) # what'd that do?
# sets end1 to C
end1 = "C"
# sets end2 to h
end2 = "h"
# sets end3 to e
end3 = "e"
# sets end4 to e
end4 = "e"
# sets end5 to s
end5 = "s"
# sets end6 to e
end6 = "e"
# sets end7 to B
end7 = "B"
# sets end8 to u
end8 = "u"
# sets end9 to r
end9 = "r"
# sets end10 to g
end10 = "g"
# sets end11 to e
end11 = "e"
# sets end12 to r
end12 = "r"
# concatenates 6 variables, assigns a space to end and prints everything
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
# concatenates 6 variables and prints everything
print(end7 + end8 + end9 + end10 + end11 + end12)
|
87753a54526f92bd132822cfaada8b03ed2f2bbf | io-ma/Zed-Shaw-s-books | /lmpthw/ex4_args/arg_parse.py | 1,078 | 4.09375 | 4 | import argparse
import codecs
import os
def write_result(args, encoded):
""" Write result to the output file """
result = args['text'][:-4] + '_1.txt'
with open(result, 'w') as target:
target.write(encoded)
target.close()
print("Success! Your file is encoded.")
def encode(args):
""" Read the input file and encode it"""
with open(args['text']) as text:
txt= text.read()
encoded = codecs.encode(txt, 'rot_13')
write_result(args, encoded)
def get_parser():
parser= argparse.ArgumentParser(description="""
This is a program that encodes any text using the ROT13 cipher.
""")
parser.add_argument('text', type=str, help='name of the input file')
return parser
def run_parser():
parser= get_parser()
args= vars(parser.parse_args())
if not os.path.exists(args['text']):
print("You need a text file, try again.")
return
encode(args)
if __name__ == "__main__":
run_parser()
|
e015f0925ccb831ef32e805bd81fff3db46668f6 | io-ma/Zed-Shaw-s-books | /lpthw/ex19/ex19_sd1.py | 1,485 | 4.34375 | 4 | # define a function called cheese_and_crackers that takes
# cheese_count and boxes_of_crackers as arguments
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# prints a string that has cheese_count in it
print(f"You have {cheese_count} cheeses!")
# prints a string that has boxes_of_crackers in it
print(f"You have {boxes_of_crackers} boxes of crackers!")
# prints a string
print("Man that's enough for a party!")
# prints a string and a newline
print("Get a blanket.\n")
# prints we can give the function numbers directly
print("We can just give the function numbers directly:")
# gives cheese_and_crackers function 20 and 30 as arguments and calls it
cheese_and_crackers(20, 30)
# prints we can use variables as arguments
print("OR, we can use variables from our script:")
# assigns 10 to a variable amount_of_cheese
amount_of_cheese = 10
# assigns 50 to a variable amount_of_crackers
amount_of_crackers = 50
# calls cheese_and_crackers function with variables as arguments
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# prints we can have math inside too
print("We can even do math inside too:")
# calls cheese_and_crackers giving it math as arguments
cheese_and_crackers(10 + 20, 5 + 6)
# prints we can combine variables and math
print("And we can combine the two, variables and math:")
# calls cheese_and_crackers with variables and math as arguments
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) |
6d61170cc9b78518126f5608a298b0126de37c4e | io-ma/Zed-Shaw-s-books | /lpthw/ex33/ex33_sd5.py | 255 | 3.75 | 4 | def range_func(incr, up_limit):
numbers = []
numbers = range(incr, up_limit)
for number in numbers:
print(f"The number is {number}")
print("The numbers: ")
for number in numbers:
print(number)
range_func(1, 6) |
9b4c2f669637b9726c9c442467bd0a670b1f1fc2 | InnaMisovetc/algorithm_training | /yandex_algorithm_training/contest1/A-conditioner.py | 554 | 3.71875 | 4 | def temp_after_one_hour(t_room, t_cond, mode):
if mode == 'fan':
return t_room
elif mode == 'auto':
return t_cond
elif mode == 'freeze':
if t_cond < t_room:
return t_cond
else:
return t_room
elif mode == 'heat':
if t_cond > t_room:
return t_cond
else:
return t_room
def main():
t_room, t_cond = map(int, input().split(' '))
mode = input()
print(temp_after_one_hour(t_room, t_cond, mode))
if __name__ == '__main__':
main()
|
007b26928ae2db9fa19beb5691406d392af147f3 | blakfeld/Data-Structures-and-Algoritms-Practice | /Python/sorts/util.py | 717 | 4.09375 | 4 | """
util.py -- Common functions to be used by various sorting algorithms.
"""
import random
def swap(l, i, j):
"""
Swap the index i with the index j in list l.
Args:
l (list): list to perform the operation on.
i (int): left side index to swap.
j (int): Right side index to swap.
Returns:
list
"""
l[i], l[j] = l[j], l[i]
return l
def generate_list_of_random_numbers(length):
"""
Generate a list of random numbers.
Args:
length (int): The length of the list.
Returns:
list
"""
rand_nums = []
for i in xrange(0, length):
rand_nums.append(random.randrange(0, 99))
return rand_nums
|
a6da253639d8ca65b62444ec6bc60545c11d2501 | blakfeld/Data-Structures-and-Algoritms-Practice | /Python/general/binary_search_rotated_array.py | 1,661 | 4.34375 | 4 | #!/usr/bin/env python
"""
binary_search_rotated_array.py
Author: Corwin Brown <blakfeld@gmail.com>
"""
from __future__ import print_function
import sys
import utils
def binary_search(list_to_search, num_to_find):
"""
Perform a Binary Search on a rotated array of ints.
Args:
list_to_search (list): The list to search.
num_to_find (int): The int to search for.
Returns:
tuple: (index, value)
"""
first = 0
last = len(list_to_search) - 1
while first <= last:
mid = (first + last) // 2
if list_to_search[mid] == num_to_find:
return mid, list_to_search[mid]
# Is first half sorted?
if list_to_search[first] <= list_to_search[mid]:
# If first and mid are less than num_to_find, Search the
# first half, else search the second half.
if all([list_to_search[first] <= num_to_find,
list_to_search[mid] >= num_to_find]):
last = mid - 1
else:
first = mid + 1
# If the second half is sorted.
else:
# If last and mid are less than num_to_find, Search the
# second half, else search the first half.
if all([list_to_search[mid] <= num_to_find,
list_to_search[last] <= num_to_find]):
first = mid + 1
else:
last = mid - 1
return None, None
def main():
"""
Main.
"""
list_to_search = utils.rotate_list(sorted(utils.get_unique_random_list()), 10)
print(binary_search(list_to_search, 30))
if __name__ == '__main__':
sys.exit(main())
|
38bb553b4974f0df84ce9704955c61d32abfb54c | L200170159/prak_asd | /Modul 2/latOOP3.py | 473 | 3.765625 | 4 | class Manusia(object):
""" class ' manusia' dengan inisiasi 'nama' """
keadaan="lapar"
def __init__(self,nama):
self.nama=nama
def ucapkanSalam(self):
print "salaam, namaku",self.nama
def makan(self,s):
print "saya baru makan",s
self.keadaan="kenyang"
def olahraga(self,k):
print "saya baru saja makan",k
self.keadaan="lapar"
def mengalikanDenganDua(self,a):
return n*2
|
e6d34c8f7107ce16aacb7791b215e97bf60ea0d5 | ChanakaUOMIT/Machine-learning-basic | /matPlotlib-basic/bar-basic.py | 351 | 3.65625 | 4 | import matplotlib.pyplot as plt
from matplotlib import style
style.use('bmh')
x = [2, 4, 6]
y = [3, 6, 9]
x2 = [4, 8, 12]
y2 = [5, 10, 15]
x3 = [6, 12, 18]
y3 = [12, 24, 36]
plt.bar(x, y)
plt.bar(x2, y2)
plt.bar(x3, y3)
plt.title("Test")
plt.xlabel("Test x values")
plt.ylabel("Test y values")
plt.show()
print("----------------------------")
|
cc61c9f756d546638241c8213e5f371390693519 | strawhatRick/python_learning | /list_slice.py | 280 | 3.53125 | 4 | rainbow = ["red", "orange", "green", "yellow", "blue", "black", "white", "aqua", "purple", "pink"]
del rainbow[5:8]
rainbow[2:4] = ["yellow", "green"]
rainbow[4:5] = ["blue", "indigo"]
rainbow[-2:] = "violet"
rainbow[-6:] = ["".join(rainbow[-6:])]
for i in rainbow:
print (i)
|
b60d9a557323fc63fb093135624b57d7b596657e | martireg/bmat | /app/utils/csv_manipulation.py | 966 | 3.546875 | 4 | import csv
from typing import Union, IO, List, Dict, Generator, Iterable, ByteString, Optional
def process_csv(file: Union[IO, str, List[str], bytes]):
if isinstance(file, bytes):
file = file.decode()
if isinstance(file, str):
file = file.splitlines()
return csv.DictReader(file, delimiter=",", quotechar="|")
def stream_csv_from_dicts(
data: List[Dict], keys: Iterable, separator: Optional[str] = None
) -> Generator[ByteString, None, None]:
if not data:
yield b""
return
if separator is None:
separator = ","
yield separator.join(keys).encode()
yield b"\n"
for i, obj in enumerate(data):
items = (
"|".join(item)
if isinstance(item := obj.get(key, ""), list)
else str(item if item is not None else "")
for key in keys
)
yield separator.join(items).encode()
if i < len(data) - 1:
yield b"\n"
|
1578f0742d7e2e04bc8fd65c13ee0418612cacea | Braingains/Python-loop-lists | /start_code/task_list.py | 2,342 | 3.859375 | 4 | #chickens = [
# { "name": "Margaret", "age": 2, "eggs": 0 },
# { "name": "Hetty", "age": 1, "eggs": 2 },
# { "name": "Henrietta", "age": 3, "eggs": 1 },
# { "name": "Audrey", "age": 2, "eggs": 0 },
# { "name": "Mabel", "age": 5, "eggs": 1 },
#def find_chicken_by_name( list, chicken_name ):
# for chicken in list:
# if chicken["name"] == chicken_name:
# return chicken
# else:
# return "Not found"
tasks = [
{ "description": "Wash Dishes", "completed": False, "time_taken": 10 },
{ "description": "Clean Windows", "completed": False, "time_taken": 15 },
{ "description": "Make Dinner", "completed": True, "time_taken": 30 },
{ "description": "Feed Cat", "completed": False, "time_taken": 5 },
{ "description": "Walk Dog", "completed": True, "time_taken": 60 },
]
#if task == False:
# for key value in completed():
# print task("status"+key)
1 Print a list of uncompleted tasks
def uncompleted_tasks(tasks):
incomplete_tasks=[]
for task in tasks:
if task["completed"] == False:
incomplete_tasks.append(task)
return incomplete_tasks
# print (uncompleted_tasks(tasks))
#2 Print a list of completed tasks
def completed_tasks(tasks):
complete_tasks=[]
for task in tasks:
if task["completed"] == True:
complete_tasks.append(task)
return complete_tasks
print (completed_tasks(tasks))
#3 Print a list of all the task decriptions
def task_descriptions(task):
description_list =[]
for task in tasks:
description_list.append(task)
return description_list
print(task_descriptions(task))
#4 Print a list of tasks where time taken is at least a given time
# def uncompleted_tasks( tasks, uncompleted ):
# for tasks in list:
# if chicken["name"] == chicken_name:
# return chicken
# else:
# return "Not found"
# def find_chicken_by_name( list, chicken_name ):
# for chicken in list:
# if chicken["name"] == chicken_name:
# return chicken
# else:
# return "Not found"
#for task in tasks:
# if completed == false:
# task =
#res = True
#for ele in test_dict:
# if not test_dict[ele]:
# res = False
# break
#for key, value in task():
# print(key, 'is the key for the value', value) |
a56c0c46f1810e8540a5aaf4dc5e538cc0a80bf5 | Himani1010/loop | /manjula_pettren_2_elif.py | 378 | 3.59375 | 4 | i=1
while i<=4:
j=1
while j<=7:
if (i==1 and(j==1 or j==2 or j==3 or j==5 or j==6 or j==7)):
print(" ",end=" ")
elif(i==2 and(j==1 or j==2 or j==6 or j==7)):
print(" ",end=" ")
elif(i==3 and(j==1 or j==7)):
print(" ",end=" ")
else:
print("*",end=" ")
j=j+1
print()
i=i+1 |
0c6d4979aad84d3ca6c087e5d2980f81ba8739c6 | Himani1010/loop | /q2_to_100.py | 79 | 3.8125 | 4 | i=20
while i<=100:
if i%2==0:
print(i ,"divisible by 2")
i=i+1
|
399d2aa8119607ceabe1c096b798d86ec5fa4a44 | Himani1010/loop | /counter_question_5.py | 130 | 4 | 4 | i=0
sum=0
n=int(input("enter a number"))
while i<n:
n_1=int(input("enter a number"))
sum=sum+n_1
print(sum)
i=i+1
|
cec8a1091bad0447be52deefeda0174293bfefd0 | matyh/PracticePython | /17 Decode A Web Page.py | 451 | 3.796875 | 4 | """
Use the BeautifulSoup and requests Python packages to print out a list of
all the article titles on the New York Times homepage (http://www.nytimes.com/)
"""
import requests
from bs4 import BeautifulSoup
url = "http://www.nytimes.com/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
articles = soup.find_all("h2", attrs={"class": "story-heading"})
# print articles
for article in articles:
print article.text.strip()
|
66eca7571cc7335686f71ff78987c7560833432a | katharinepires/cursodepython | /basicos_conceitos.py | 6,159 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Conceitos básicos:
# In[1]:
X = 10
Y = 25
soma = X + Y #soma recebe x + y, esse é o jeito correto de ler
print("O resultado da adição entre", X, "e", Y, 'é igual a', soma)
# In[2]:
100%2
# In[3]:
100%3
# ### Variáveis numéricas:
# - *int* => significa números inteiros
# - *float* => significa números de ponto flutuantes: 1.28
# - *complex* => significa números complexos: 4j
# In[4]:
inteiro = 20
flutuante = 14.06
complexo = 4j + 5
print("O resultado de",inteiro, "+", 50, "é igual a:",inteiro + 50)
print("O resultado de",flutuante, "+", 0.99, "é igual a:",flutuante + 0.99)
print("O resultado de",complexo,"+ (20 - 2j + 3) é igual a:",complexo + 20 - 2j + 3)
# ### Variáveis tipo lógico:
# Também conhecidas como boleanas
# - *true*
# - *false*
# In[5]:
chuva = True
nao_chuva = False
print(chuva)
print(nao_chuva)
# In[6]:
p = 14
k = 6
print("p é diferente de k:", p != k)
print("p é igual a k:", p == k)
print("p é maior ou igual a k:", p >= k)
print("p é menor ou igual a k:",p <= k)
print("p é maior que k:",p > k)
print("p é menor que k:",p < k)
# In[7]:
a = True
b = False
print("negativo de a é:",not a)
print("negativo de b é:",not b)
# In[8]:
c = not True
d = not False
print("c é:",c)
print("d é:",d)
# In[9]:
log1 = (p < k)
log2 = (p == k)
log3 = (p >= k)
log4 = (p != k)
print(log1 and log2) #ambos tem que ser atendidos
print(log3 and log4)
print(log3 or log2) #pelo menos um tem que atender a solicitação
print(log1 or log4)
# ordem das variáveis lógicas: ``not``, `and`, `or`.
# ### Variáveis tipo string:
# Variáveis com caracteres, textos
# In[10]:
frase = "Olá, quero muito um emprego."
len(frase)
# Para acessar a posição de cada caractere, basta usar o índice:
# In[11]:
frase[3]
# In[12]:
frase[10]
# In[13]:
frase[20]
# Python é uma liguaguem de tipagem forte
# In[14]:
a = 10
f = "Roi, Letícia, né?!"
soma = a + f
print("O resultado é:",soma)
# In[15]:
soma = str(a) + f
print("O resultado depois de transfromado em string é:",soma)
# ### Entrada de dados:
# In[16]:
input("Informe o teu nome: ")
# In[17]:
idade = input("Digite a sua idade: ")
print(f"IDADE:{idade}")
# In[18]:
nome = input("Informe o teu nome: ")
print("NOME:",nome)
# In[19]:
resp = input("Quanto é 1 + 1?\n"
"a) 11\n"
"b) 2\n"
"c) 1,1\n"
"d) 1\n"
"RESPOSTA: ")
# In[20]:
ano = 2021
nascimento = int(input("Digite o ano de seu nascimento: "))
idade = ano - nascimento
print("Então sua idade é",idade,"anos!")
# In[21]:
ano = int(input("Digite o ano desejado: "))
nascimento = int(input("Digite o ano de seu nascimento: "))
idade = ano - nascimento
print("Então em",ano,"sua idade será",idade,"anos!")
# In[22]:
juros = float(input("Digite a taxa de juros: "))
emprestimo = float(input("Digite o valor a ser emprestado: "))
fv = (1 + (juros/100)) * emprestimo
print("Então no vencimento você pagará",fv)
# ### Mais sobre `strings`:
# In[23]:
a = "Olá, meu nome é "
b = "Katharine Pires. E o seu?"
concat = a + b
print(concat)
# In[24]:
c = "agua "
multi = c * 5
print(multi)
# ### Composição ou Interpolação:
# Combinar e colocar `strings` e até dados dentro de outra `string`
# - *%s* => string
# - *%d* => inteiro
# - *%f* => real
# - *%%* => porcentagem
# In[25]:
cinema = "Bela Vista"
frase = "Vamos ao %s assistir Mulher Maravilha" % cinema
print(frase)
# In[26]:
pagar = 150
frase = "Passe no Bootcamp e tive que pagar %d para a matrícula" % pagar
print(frase)
# In[27]:
taxa = 2.0
frase = "O copom deve se reunir e manter a SELIC em %.2f%% ao ano" % taxa
print(frase)
# In[28]:
frase = 'Fomos ao {} e pagamos mais de R${} só em comida, isso é culta da SELIC a {} ao ano!'.format(cinema, pagar, taxa)
print(frase)
# In[29]:
frase = "Estou pensando em comprar um {1} novo porque o nosso já está ruim".format('carro','moto','casa')
print(frase)
# In[30]:
f"paguei R${pagar} de matrícula!"
# In[31]:
f"Fui ao {cinema} com minha amiga!"
# Fatiamento de `string`: string[x:y:z] onde **x** é o incício da posição, **y** é o fim da posição e o **z** é o salto
# In[32]:
frase[2:11:2]
# In[33]:
frase[5:16]
# In[34]:
frase[:]
# In[35]:
frase[::-1]
# In[36]:
frase.index('c')
# In[37]:
frase[18]
# In[38]:
frase.index('moto')
# In[39]:
frase[29]
# Achando um email:
# In[40]:
email = "katharinepires@outlook.com"
print(email.index('.com'))
# In[41]:
print(email.index('@'))
# In[42]:
arroba = email.index('@')
print("NOME DE USUÁRIO: ",email[0:arroba])
# In[43]:
ponto = email.index('.')
print('O provedor de email é: ',email[arroba+1:ponto]) #+1 para não sair o @
# In[44]:
outro = "kkathy1999.kp@gmail.com"
usuario, provedor = outro.split('@')
print('Nome de usuário:',usuario)
print('Provedor:',provedor)
# In[45]:
ponto = provedor.index('.')
print('Nome de usuário:',usuario)
print('Provedor:',provedor[:ponto])
# #### Desafios:
# 1º - Valor da compra
# In[46]:
valor = float(input('Qual valor mensal da parcela: '))
parcela = int(input('Em qauntas parcelas serão: '))
total = valor * parcela
print(f'O valor total da compra é: {total:,.2f}')
# 2º - Comparar Strings
# In[47]:
texto1 = "Pizza de Queijo"
texto2 = "Pizza de Frango com Requeijão"
print('O tamanho do primeiro texto é:',len(texto1))
print('O tamanho do segundo texto é:',len(texto2))
# In[48]:
print('Os textos possuem as mesmas quantidades de caracetres?',len(texto1) == len(texto2))
print('Os textos são iguais?',texto1 == texto2)
# 3º - Árvore de natal
# In[49]:
print(" "*10 + "x")
print(" "*10 + "X")
print(" "*9 + "X"*3)
print(" "*8 + "X"*5)
print(" "*7 + "X"*7)
print(" "*6 + "X"*9)
print(" "*5 + "X"*11)
print(" "*4 + "X"*13)
print(" "*3 + "X"*15)
print(" "*9 + "X"*3)
print(" "*9 + "X"*3)
print(" "*9 + "X"*3)
# In[50]:
salario = float(input("Digite o seu slário: "))
aumento = float(input("Digite o valor do aumento: "))
fv = (1 + (aumento/100)) * salario
print(f"Seu salário com o aumento de {aumento}% será de R${fv:,.2f}")
|
9196d5de7e76fab9792b793fd62806e13d1ff153 | kparmar20/ProjectEuler | /Q6.py | 453 | 3.765625 | 4 | def sum_of_square(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x**2)
return sum(list_out)
def square_of_sum(min_int, max_int):
list_out=[]
for x in range(min_int, max_int+1):
list_out.append(x)
return sum(list_out)
#sum of squares
#print(sum_of_square(1,100))
#square of the sum
#print((square_of_sum(1,100))**2)
print(((square_of_sum(1,100))**2)-sum_of_square(1,100))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.