blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
1cdb8b5bc45783cb17c1365884d9f5a18db94e2f | raghuprasadks/sindhi-python-aug-2021 | /day7/3-assignment.py | 379 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
1. Create a class called Product
having attributes
code,name,desc,manu,price
having following methods
addProduct(self,code,name,desc,manu,price)
displayProduct(self)
return product attributes
2. show the product having maximum price
3. show all products of a specific manufacturer
4. search for a specific product
"""
|
211301423c62e1082b0bc261be6f7fcca5e9189d | raghuprasadks/sindhi-python-aug-2021 | /day9/1-createtable.py | 303 | 3.59375 | 4 | import sqlite3
conn = sqlite3.connect('olympicsdb.db')
conn.execute('''
CREATE TABLE if not exists olympics (
location TEXT,
year INTEGER,
country TEXT,
gold INTEGER,
silver INTEGER,
bronze INTEGER,
total INTEGER
)
'''
)
print('table created successfully')
conn.close()
|
839946a7d28885e51edacabbd322e58eef806004 | raghuprasadks/sindhi-python-aug-2021 | /day8/2-filemanagement.py | 714 | 4.09375 | 4 | """
File management
Modes
w - write mode - existing content will be deleted
a - content gets added to the existing file
r - read content of a file
"""
file=open("olympics.txt","w")
file.write("Olympics 2020 was held in japan \n")
file.write("More than 170 countries participated in it")
file.close()
file=open("olympics.txt","w")
file.write("US came first followed by china \n")
file.close()
file=open("olympics.txt","a")
file.write("\n India performed well compared to previous olympics \n")
file.close()
file=open("olympics.txt","r")
info = file.read()
print(info)
file.close()
'''
reading line by line
'''
file=open("olympics.txt","r")
info = file.readlines()
for i in info:
print(i)
file.close()
|
7823d45c55eedbfeda27499fb09e0a528313165b | raghuprasadks/sindhi-python-aug-2021 | /day4/1-listdemo.py | 615 | 4.0625 | 4 | """
List -
Dynamic array
It allows duplicate values
It maintains the order of insertion
Elements can be accessed using index
"""
runs =[10,40,50,60]
print('runs -list ',runs)
print('runs -list - data type ',type(runs))
#<class 'list'>
print("list length ",len(runs))
'''
Adding an element
'''
runs.append(35)
print("after append ",runs)
'''
update an existing element
'''
runs[0]=15
print("after update ",runs)
'''
delete
'''
del runs[1]
print('after deletion ',runs)
'''
delete the list
'''
#del runs
#print('after deletion --',runs)
'''
find element at index 2
'''
print('element at index 2 ',runs[2])
|
517b57af6476e831869f798356ab0e7c57c0be3d | Nav-31/Zest-to-Conquer | /Hackerrank/Problem Solving/DiagonalDiff.py | 416 | 3.671875 | 4 |
def diff(n,ar):
s1=0;s2=0
for i in range(n):
s1=s1+ar[i][i]
s2=s2+ar[i][n-1-i]
d=abs(s1-s2)
return d
n=int(input("Enter the size of matrix:"))
ar=[]
for i in range(n):
a=map(int,input().split()) #Enter 3 numbers per line
p=list(a)
ar.append(p)
print(diff(n,ar))
|
f7e5eeb733fe6521f57a9e47bf2fd96e87e1494c | Nav-31/Zest-to-Conquer | /Hackerrank/Problem Solving/UthopianTree.py | 254 | 3.75 | 4 | def uthopianTree(n):
h=1
for i in range(1,n+1):
if(i%2!=0):
h=h*2
else:
h=h+1
return h
tc=int(input("Enter d no. of TestCases:"))
for i in range(tc):
n=int(input())
print(uthopianTree(n))
|
4d9e426e1ff609fb3dd95fb8f42df70221da55e4 | neelitummala/swarmrouting | /Point.py | 730 | 3.640625 | 4 | import math
import numpy as np
class Point:
def __init__(self, x, y):
# x and y are integers
self.__x = x
self.__y = y
def getX(self):
return self.__x
def getY(self):
return self.__y
def distanceToPoint(self, other_point):
dx = self.__x - other_point.getX()
dy = self.__y - other_point.getY()
return math.hypot(dx, dy)
def __str__(self):
return "(" + str(self.__x) + "," + str(self.__y) + ")"
def __repr__(self):
return "Point(" + str(self.__x) + "," + str(self.__y) + ")"
def __eq__(self, other):
return (self.__x == other.getX()) and (self.__y == other.getY()) |
6c0e983ee912c4df1cd54aba6d832f74b1b46d88 | suliemanmeq/MCSA | /regression.py | 2,460 | 3.65625 | 4 | print(__doc__)
# Code source: Jaques Grobler
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]
# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
# Make predictions using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)
# print diabetes_y_pred
# The coefficients
print('Coefficients: \n', regr.coef_)
print('Intercept: \n', regr.intercept_)
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
# from sklearn import datasets
# from sklearn import linear_model
# import numpy as np
# import matplotlib.pyplot as plt
# diabetes = datasets.load_diabetes()
# diabetes_X_train = diabetes.data[:-20]
# diabetes_X_test = diabetes.data[-20:]
# diabetes_y_train = diabetes.target[:-20]
# diabetes_y_test = diabetes.target[-20:]
# print dir(datasets.load_diabetes())
# regr = linear_model.LinearRegression()
# print regr.fit(diabetes_X_train, diabetes_y_train)
# # LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
# print np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2)
# print regr.score(diabetes_X_test, diabetes_y_test)
# print len(diabetes.data)
# plt.scatter(diabetes_X_test, diabetes_y_test, color ='black')
# plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue', linewidth=3)
# plt.xticks(())
# plt.yticks(())
# plt.show()
# # iris = datasets.load_iris()
# # iris_X = iris.data
# # iris_y = iris.target
# # np.unique(iris_y)
# # print iris_X
# # print iris_y
|
b320d9d84c7377bd3d2ac6b959b8b8798016da69 | asaidomar/euler-project | /problem_27.py | 2,992 | 3.546875 | 4 | # -*- coding: utf-8; -*-
#
# 2019-05-31
def primes_formula(a, b, n):
return n ** 2 + a * n + b
def get_primes(limit):
candidates = set(range(2, limit))
for i in range(2, limit):
candidates.difference_update({i * n for n in range(i, limit)})
return candidates
def primes_below(end):
if end < 2:
return []
lng = (end // 2) - 1
primes = [True] * lng
for i in range(int(lng ** 0.5)):
if primes[i]:
for j in range(2 * i * (i + 3) + 3, lng, 2 * i + 3):
primes[j] = False
return [2] + [i * 2 + 3 for i, j in enumerate(primes) if j]
def is_prime(n):
for i in range(2, (abs(n) // 2) + 1):
if n % i == 0:
return False
return True
def process():
candidate_a = 0
candidate_b = 0
max_len = 0
primes = list(get_primes(1000))
result = dict()
max_computed = list()
for a in range(-999, 1000, 2):
for b in primes:
# a + b must be even
if (a + b) % 2 == 1:
continue
computed_primes = list()
n = 0
while True:
candidate_prime = primes_formula(a, b, n)
if not is_prime(candidate_prime):
result[(a, b)] = computed_primes
if len(computed_primes) > max_len:
max_len = len(computed_primes)
candidate_a, candidate_b = a, b
max_computed = computed_primes
break
else:
computed_primes.append(candidate_prime)
n += 1
return candidate_a, candidate_b, max_computed
def main():
a, b, mac_c = process()
return a, b, mac_c
def main2():
# from https://www.lucaswillems.com/fr/articles/53/project-euler-27-solution-python
def primes_below(end):
if end < 2:
return []
lng = (end // 2) - 1
primes = [True] * lng
for i in range(int(lng ** 0.5)):
if primes[i]:
for j in range(2 * i * (i + 3) + 3, lng, 2 * i + 3):
primes[j] = False
return [2] + [i * 2 + 3 for i, j in enumerate(primes) if j]
# Obtention de la liste des nombres premiers inférieurs à 1000
primes = primes_below(1000)
longest = 0
# b prend successivement la valeur des différents nombres premiers
for b in primes:
# a prend successivement la valeur de tous les nombres impairs de -999 à 2
for a in range(-999, 1000, 2):
image = b
n = 0
# Calcul du nombre consécutif de nombres premiers
while is_prime(image):
n += 1
image = n ** 2 + a * n + b
if n > longest:
longest = n
resultat = a * b
return resultat
if __name__ == '__main__':
print(main())
# print(list(primes_formula(1, 41, i) for i in range(0, 40)))
|
27d96e595a2cb0560c0c22c075244e3dbd61ef88 | asaidomar/euler-project | /problem_31.py | 989 | 3.796875 | 4 | # -*- coding: utf-8; -*-
#
# 2019-06-02
tree = [1, 2, 5, 10, 20, 50, 100]
count = 0
# credit https://medium.com/@jschapir/coinsum-algorithm-for-dummies-e3f73394bc11
def coinsum(total):
count = 0
def make_change(current_total):
nonlocal count
if current_total == total:
count += 1
# print(count)
return
if current_total > total:
return
for c in tree:
make_change(current_total + c)
make_change(0)
return count
def _walk(index=0, sum_=0, path=None, ):
global count
path = path or []
new_sum_ = sum_ + tree[index]
path.append(index)
if new_sum_ == 200:
path = list()
count += 1
if new_sum_ > 200:
return
for j in range(index, len(tree)):
_walk(index=j, sum_=new_sum_, path=path)
return count
def main():
return _walk()
def main2():
return coinsum(200)
if __name__ == '__main__':
print(main2())
|
c16a82ce52dada89b2470f62bdd9d5ec3fab42e1 | asaidomar/euler-project | /problem_14.py | 755 | 3.75 | 4 | import math
memoize_dict = {}
def step(start):
if start % 2 == 0:
start = int(start / 2)
else:
start = 3 * start + 1
return start
def is_power_of_two(number):
value = math.log(number, 2)
return math.floor(value) == math.ceil(value)
def cycle_len(start):
c = 1
while start > 1:
start = step(start)
if is_power_of_two(start):
c += math.log(start, 2)
return c + 1
c += 1
return c
def main(end):
j = 0
max_l = 0
for i in range(2, end):
length = cycle_len(i)
# print(i, length)
if length > max_l:
max_l = length
j = i
return max_l, j
if __name__ == '__main__':
print(main(1_000_000))
|
9bc6d0914b96d338ebfb8436fec4d9561968b1c0 | Pogorelov-Y/python-project-lvl1 | /brain_games/games/brain_gcd.py | 946 | 3.890625 | 4 | import random
from fractions import gcd
def make_data():
"""Make two random natural numbers"""
number1 = random.randint(1, 100)
number2 = random.randint(1, 100)
return {
"number1": number1,
"number2": number2,
}
def get_number1(data):
"""Return random natural numbers"""
return data["number1"]
def get_number2(data):
"""Return other random natural numbers"""
return data["number2"]
def great_divisor(data):
"""Return the largest common divisor"""
result = gcd(get_number1(data), get_number2(data))
return str(result)
def question(data):
"""Form a string of two random numbers"""
return "{} {}".format(get_number1(data),
get_number2(data))
GAME_RULES = 'Find the greatest common divisor of given numbers.\n'
def round():
"""Form a question and answer string"""
data = make_data()
return question(data), great_divisor(data)
|
3df5b1c94a03d38aa3313e0e118dbfc6176afa28 | babint/AoC-2020 | /05/part2.py | 1,303 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
import re
seats = []
rows = 128
cols = 8
def caluate_id(row, col):
return (row) * 8 + (col)
def calculate_seat(instructions, rows, cols):
# Seat set
plane_rows = list(range(0, rows))
plane_cols = list(range(0, cols))
# halve the seat set based on instruction
for instr in instructions:
if (instr == 'F'):
plane_rows = plane_rows[:len(plane_rows)//2]
elif(instr == 'B'):
plane_rows = plane_rows[(len(plane_rows)//2):]
elif(instr == 'L'):
plane_cols = plane_cols[:(len(plane_cols)//2)]
elif(instr == 'R'):
plane_cols = plane_cols[(len(plane_cols)//2):]
else:
print(f'bad instruction: {instr}')
# Build Seat data from whats left
seat = {
'id': caluate_id(plane_rows[0], plane_cols[0]),
'row': plane_rows[0],
'col': plane_cols[0]
}
return seat
# Usage
if len(sys.argv) != 2:
print("usage: part2.py input.txt")
exit(1)
# Read File + Calculate Seat
with open(sys.argv[1]) as f:
line = f.read().splitlines()
for instructions in line:
seat = calculate_seat(instructions, rows, cols)
seats.append(int(seat['id'])) # Track seat and ids
# Find missing Seat id
missing = 0
seats.sort()
for i in range(seats[0],seats[-1]):
if (i in seats): continue
missing = i # found missing
break
# Answer
print(f'{missing}')
|
0be5483f9dc0a3a9b03dacd612fa84a2786449be | babint/AoC-2020 | /01/part1.py | 636 | 3.921875 | 4 | #!/usr/bin/env python3
import sys
numbers = []
found = -1
# Usage
if len(sys.argv) != 2:
print("usage: part1.py input.txt")
exit(1)
# Read File + Get Numbers
with open(sys.argv[1]) as f:
data = f.read().splitlines()
for num in data:
numbers.append(int(num))
# Start
for i, num1 in enumerate(numbers):
if (found > -1): break
for j, num2 in enumerate(numbers):
#print(f'i: {i} num: {num1} j: {j} num2: {num2}')
# don't attempt to sum itself
if (i == j): break
# don't attempt if we are done
if (found > -1): break
# Match?
if ((num1 + num2) == 2020):
found = (num1 * num2)
# Answer
print(f"{found}"); |
5b2e58bb92df6134906050ca74148d5c52f893de | ArturSargsyans/Trees | /BST.py | 1,845 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
class BST:
def __init__(self):
self.root = None
def __str__(self):
if self.root == None:
return "empty"
else:
return str(self.root.data)
def addNode(self, node):
if self.root == None:
self.root = node
else:
self.addToCorrectParent(node, self.root)
def addToCorrectParent(self, node, curr_root):
if node.data < curr_root.data:
if curr_root.left == None:
curr_root.left = node
else:
self.addToCorrectParent(node, curr_root.left)
elif node.data > curr_root.data:
if curr_root.right == None:
curr_root.right = node
else:
self.addToCorrectParent(node,curr_root.right)
else:
print("value has been skipped")
pass
def PreorderList(self, currentroot, list):
if currentroot != None:
list.append(currentroot.data)
list = self.PreorderList(currentroot.left, list)
list = self.PreorderList(currentroot.right, list)
return list
def PreorderPrint(self):
print(self.PreorderList(self.root, []))
def main():
myBST = BST()
Node1 = Node(50)
Node2 = Node(20)
Node3 = Node(3)
Node4 = Node(34)
Node5 = Node(7)
Node6 = Node(99)
Node7 = Node(25)
Node8 = Node(6)
myBST.addNode(Node1)
myBST.addNode(Node2)
myBST.addNode(Node3)
myBST.addNode(Node4)
myBST.addNode(Node5)
myBST.addNode(Node6)
myBST.addNode(Node7)
myBST.addNode(Node8)
myBST.PreorderPrint()
main() |
c5333727d54b5cb7edff94608ffb009a29e6b5f4 | nikita5119/python-experiments | /cw1/robot.py | 1,125 | 4.625 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be:
# 2
position=[0,0]
while True:
a= input("enter the direction and steps :")
if not a:
break
direction, steps= a.split(' ')
steps=int(steps)
if (direction== "up"):
position[0]= position[0]+steps
elif (direction=="down"):
position[0]=position[0]-steps
if (direction=="right"):
position[1]=position[1]+steps
elif (direction=="left"):
position[1]=position[1]-steps
print(position)
distance=(position[0]**2+position[1]**2)**(1/2)
print(distance) |
6e468bf7c8d0d37233ee7577645e1d8712b83474 | TameImp/compound_interest_app | /test_calc.py | 929 | 4.125 | 4 | '''
this programme test the compound interest calculator
'''
from calc import monthly_compounding
def test_tautology():
assert 3 == 3
#test that investing no money generates no returns
def test_zeros():
#initialise some user inputs
initial = 0
monthly = 0
years = 0
annual_rate = 0
#calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 0
def test_cash():
initial = 1000
monthly = 100
years = 10
annual_rate = 0
#calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 13000
def test_rate():
initial = 1000
monthly = 100
years = 2/12
annual_rate = 12
# calculate a final sum
final_sum = monthly_compounding(initial, monthly, years, annual_rate)
#test out
assert final_sum == 1221.1
|
908b570380df3572cb18391937b7a8cdfc733dff | vurpo/e-resepti | /models.py | 2,218 | 3.890625 | 4 | """
This module contains the classes that represent the recipe book and recipe, used in the application.
"""
class RecipeBook:
"""
Represents a recipe book (collection of recipes)
"""
def __init__(self, recipes):
self.recipes = recipes
@classmethod
def from_json_list(cls, recipebook):
"""
Create a RecipeBook from a list deserialized from a JSON array
"""
recipes = [Recipe.from_json_dict(recipe) for recipe in recipebook]
return cls(recipes)
def to_json_list(self):
"""
Return a list that represents the JSON representation of the recipe book
"""
return [recipe.to_json_dict() for recipe in self.recipes]
class Recipe:
"""
Represents a recipe (with name, ingredients, and instructions for how to cook)
"""
def __init__(self, name, ingredients, instructions):
self.name = name
self.ingredients = ingredients
self.instructions = instructions
@classmethod
def from_json_dict(cls, recipe):
"""
Create a Recipe from a dict deserialized from a JSON object
"""
return cls(recipe['name'], recipe['ingredients'], recipe['instructions'])
def to_json_dict(self):
"""
Return a dict that represents the JSON representation of the recipe
"""
return {"name":self.name, "ingredients":self.ingredients, "instructions":self.instructions}
def has_ingredient(self, ingredient_string):
"""
Check if recipe matches ingredient string
"""
for ingredient in self.ingredients:
if ingredient_string.lower() in ingredient['name'].lower():
return True
return False
def prettyprint(self):
"""
Pretty print recipe for console output
"""
out = ""
out += "{}\n".format(self.name)
out += "{}\n\n".format("="*len(self.name))
out += "Ingredients:\n"
for ingredient in self.ingredients:
out += " * {} {} {}\n".format(ingredient['amount'], ingredient['unit'], ingredient['name'])
out += "\n"
out += "{}".format(self.instructions)
return out
|
2325c94dd4abf0c95ab0b4cc39dc1fb80156eaa4 | eliezeravihail/heap | /simple_use_heapsort.py | 306 | 3.765625 | 4 | import heap as H
def heapSort(arr):
heap = H.heap()
for i in arr:
heap.push(i)
for i in range(len(arr)):
arr[len(arr)-1-i] = heap.popMax()
"""#use:
x= [23,2,454,6,8787,3]
heapSort(x)
print(x)
#======== output: =============
[2, 3, 6, 23, 454, 8787]
"""
|
1f7e272130cff2ed0494cde01bd77119fef2164a | xjtushilei/python_dots_game | /factory.py | 4,605 | 3.875 | 4 | """Factory classes for Dots & Co game
While quite concise, the purpose of these classes is to manage creation of instances (of dots, etc.). By having a
class managing this process, hooking into and extending this process becomes quite simple (through inheritance). This
allows for interesting things to be done, such as rigging a factory to ensure a game can be played a certain way.
"""
#
# /-------------\
# / \
# / \
# / \
# | XXXX XXXX |
# | XXXX XXXX |
# | XXX XXX |
# \ X /
# --\ XXX /--
# | | XXX | |
# | | | |
# | I I I I I I I |
# | I I I I I I |
# \ /
# -- --
# \-------/
# XXX XXX
# XXXXX XXXXX
# XXXXXXXXX XXXXXXXXXX
# XXXXX XXXXX
# XXXXXXX
# XXXXX XXXXX
# XXXXXXXXX XXXXXXXXXX
# XXXXX XXXXX
# XXX XXX
# **************
# * BEWARE!! *
# **************
# All ye who enter here:
# Most of the code in this module
# is twisted beyond belief!
# Tread carefully
# If you think you understand it,
# You Don't,
# So Look Again
#
from abc import ABC, abstractmethod
from cell import Cell, VoidCell
from dot import AbstractKindlessDot
__author__ = "Benjamin Martin and Brae Webb"
__copyright__ = "Copyright 2017, The University of Queensland"
__license__ = "MIT"
__version__ = "1.1.1"
class AbstractFactory(ABC):
"""Abstract factory"""
@abstractmethod
def generate(self, position):
"""(*) Abstract method to return a new instance
Parameters:
position (tuple<int, int>) The (row, column) position of the dot
"""
raise NotImplementedError
class WeightedFactory(AbstractFactory):
"""Factory to generate instances based upon WeightedSelector value"""
def __init__(self, selector, constructor):
"""Constructor
Parameters:
selector (WeightedSelector): The weighted selector to choose from
constructor (WeightedSelector): A weighted selector to choose
the constructor class from
"""
self._selector = selector
self._constructor = constructor
def generate(self, position):
"""(*) Generates a new instance"""
constructor = self._constructor.choose()
return constructor(self._selector.choose())
class CellFactory(AbstractFactory):
"""A basic factory for grid cells determined by a set of dead cells
Generates a VoidCell for every position in dead cells, otherwise Cell
"""
def __init__(self, dead_cells=None):
"""
Constructor
Parameters:
dead_cells (set<tuple<int, int>>): Set of cells that are disabled (i.e. VoidCells)
"""
if dead_cells is None:
dead_cells = set()
self._dead_cells = dead_cells
def generate(self, position):
"""(*) Generates a new dot"""
return Cell(None) if position not in self._dead_cells else VoidCell()
class DotFactory(AbstractFactory):
"""Factory to generate dot instances"""
def __init__(self, selector, constructor):
"""Constructor
Parameters:
selector (WeightedSelector): The weighted selector to choose from
constructor (WeightedSelector): A weighted selector to choose
the constructor class from
"""
self._selector = selector
self._constructor = constructor
def generate(self, position):
"""(*) Generates a new dot"""
constructor = self._constructor.choose()
if issubclass(constructor, AbstractKindlessDot):
return constructor()
return constructor(self._selector.choose())
|
5c6905ae0f3d93a0f4f21be897c926faa79f275e | ocaballeror/AdventOfCode2018 | /6/sol1.py | 1,138 | 3.796875 | 4 | from collections import defaultdict
from common import manhattan
from common import all_points
from common import start_x, end_x, start_y, end_y
def nearest_point(coord):
nearest = None
smallest = float('inf')
duplicate = False
for point in all_points:
distance = manhattan(point, coord)
if distance == smallest:
duplicate = True
elif distance < smallest:
duplicate = False
smallest = distance
nearest = point
return nearest if not duplicate else None
def is_finite(point):
x, y = point
left = start_x, y
right = end_x, y
up = x, start_y
down = x, end_y
for test in (left, right, up, down):
if nearest_point(test) == point:
return False
return True
def part1():
valid_points = [p for p in all_points if is_finite(p)]
area = defaultdict(int)
for y in range(start_y, end_y):
for x in range(start_x, end_x):
nearest = nearest_point((x, y))
if nearest in valid_points:
area[nearest] += 1
return max(area.values())
print(part1())
|
4ee50f47fa7f3ecdb44b1e62be1bc645df218490 | ocaballeror/AdventOfCode2018 | /13/sol1.py | 1,368 | 3.921875 | 4 | """
DAY 13
The map is represented as an array, containing all the track pieces, using
their original character representation, with a few exceptions:
1. The carts are removed from the map and stored in a separate array.
# 2. Empty space is replace by an empty string for easier conversion to bool.
3. Empty space at the end is removed.
The carts are stored as an array of tuples in the format:
(y_position, x_position, direction, last_turn)
Where the direction is one of the four characters used to represent the cart in
the original example, and last_turn is an integer representing the action taken
in the last crossroad. 0 means it will turn left the next time, 1 straight and
2 left.
The y position is stored first so that we can use the carts array as a heap,
and get the upper most cart in an efficient way.
"""
import time
from common import draw
from common import simulate
from common import parse_input
def run(tracks, carts):
while True:
draw(tracks, carts)
carts, collisions = simulate(tracks, carts)
if collisions:
return collisions
time.sleep(.05)
if __name__ == '__main__':
tracks, carts = parse_input()
collision = run(tracks, carts)
draw(tracks, carts, collision)
if len(collision) == 1:
collision = list(collision)[0]
print('Collision at', collision)
|
615539c38a067d3e739360dd6b4c1e8241281286 | timush-a/praxise | /test_regexp.py | 1,127 | 3.5625 | 4 | from regexp import SimpleMathematicalOperationsCalculator as Calculator
one_variable = 'a-=1a+=1a+=10a+=a'
three_variables = 'a=1a=+1a=-1a=ba=b+100a=b-100b+=10b+=+10b+=-10b+=bb+=b+100' \
'b+=b-100c-=101c-=+101c-=-101c-=bc-=b+101c-=b-101'
raw_data = 'saf nahu haou fhj sf,aa134%...jfbak fa sd fb+=as;2kl5klskdfsjglknc+=a + 100' \
'jakjgasf/..klsjgl naemfa-=1000'
class TestCalculator:
def test_case_empty(self):
test_case = Calculator('', {'a': 0, 'b': 0, 'c': 0})
assert test_case.calculate() == {'a': 0, 'b': 0, 'c': 0}
def test_case_with_one_variable(self):
test_case = Calculator(one_variable, {'a': 1, 'b': 2, 'c': 3})
assert test_case.calculate() == {'a': 22, 'b': 2, 'c': 3}
def test_case_with_three_variables(self):
test_case = Calculator(three_variables, {'a': 1, 'b': 2, 'c': 3})
assert test_case.calculate() == {"a": -98, "b": 196, "c": -686}
def test_case_raw_data(self):
test_case = Calculator(raw_data, {'a': 100, 'b': -1, 'c': 88})
assert test_case.calculate() == {'a': -900, 'b': 99, 'c': 188}
|
b78774d35a8f939c8ef3ea6511adb463a1a5996b | zhaoyang6943/Python_JiChu | /day06/01 可变不可变类型.py | 1,191 | 3.6875 | 4 | # 可变不可变类型,进行区分
"""
整形、浮点型、字符串、列表、字典、布尔
"""
# 可变类型:值改变、id不变,证明改的是原汁,证明原值是可以被改变的
# 不可变类型:值改变,id不变,证明是产生的是新的值,压根没有改变原值,证明原值是不可以被修改的
# 2. 验证
# 2.1 int是不可变类型
x=10
print(id(x))
x=11 # 产生新增
print(id(x))
# 2.2 float是不可变类型
y=10.5
print(id(y))
y=11.5 # 产生新增
print(id(y))
# 2.3 str是不可变类型
z="123asd"
print(id(z))
z="456qwe" # 产生新增
print(id(z))
# 2.4 list是可变类型
l = ["111","222","333"]
print(id(l))
l[0] = "aaaaaaa"
print(l)
print(id(l))
# 2.5 dict是可变类型
di = {"k1":111,"k2":222}
print(id(di))
di['k1'] = 333333333
print(di)
print(id(di))
# 2.6 bool类型
# 不可变
"""
关于字典补充:
定义:{}内用逗号分隔开,key:value
其中 value 可以是任意类型
但是 key 必须是不可变类型
"""
di1={
'k1':1111,
123:2.11,
123.1:'saas123阿萨德~!@#¥',
'k4':[123,456.789,[123],"123",{"k1":123}],
'k5':{'1':123}
}
print(di1[123.1]) |
3cd051bbb49fc8bed3359a5c4bfedb2b8d8d5667 | DMfananddu/Kristina-s | /courser.py | 3,117 | 3.671875 | 4 | from random import randint, random, choice
class Course(object):
"""
Курс - набор уроков (от 4 до 16) по определенной Тематике;
Тематика - одна из списка тематик
Урок - объект, имеющий след. характеристики:
Номер в курсе
Тип урока:
Видео (долгое, среднее, короткое)
Текст (долгий, средний, короткий)
Тест с ограничением по времени (долгий, средний, короткий)
Длительность полного изучения:
У Короткого: от 5 минут до 20 минут
У Среднего: от 30 минут до 50 минут
У Длинного: от 60 минут до 120 минут
Сложность обработки для системы:
У Текста: 1
У Видео: 2
У Теста: 3
"""
def __init__(self, name='', duration=0):
self.theme = self.choice_theme()
self.name = self.choice_name('data/'+self.theme+'course_names.txt')
self.lessons_count = randint(4, 16)
self.lesson_duraion_type = randint(0, 2)
self.lessons = self.create_lessons()
self.type = 'Course'
def choice_theme(self, filename='themes.txt'):
with open(filename, 'r', encoding='utf-8') as reader:
course_themes_list = []
for theme in reader:
course_themes_list.append(theme.strip('\n'))
return choice(course_themes_list)
def choice_name(self, filename):
with open(filename, 'r', encoding='utf-8') as reader:
course_names_list = []
for course in reader:
course_names_list.append(course.strip('\n'))
return choice(course_names_list)
def create_lessons(self):
types = ['text', 'video', 'quiz']
tmp_lessons = []
for i in range(self.lessons_count):
difficulty = randint(0, 4)
if difficulty == 4:
difficulty = 2
elif difficulty == 0:
difficulty = 0
else:
difficulty = 1
tmp_lessons.append({
'number': i+1,
'type': types[difficulty],
'difficulty': difficulty+2,
'duration': self.duration()
})
return tmp_lessons
def duration(self):
duration = 0
if self.lesson_duraion_type == 0:
duration = randint(5, 20)
elif self.lesson_duraion_type == 1:
duration = randint(30, 50)
else:
duration = randint(60, 120)
return duration
def __repr__(self):
return f' type: {self.type} | theme: {self.theme} | name: {self.name} | lessons_count: {self.lessons_count} | lesson_duraion_type: {self.lesson_duraion_type}\n'
if __name__ == '__main__':
print('courser.py') |
a39844f0165749d52821e3ce256af15dc90f833c | gruve-p/haitech | /programming/python/combinatorics/bellnumber/bell.py | 799 | 3.5625 | 4 | #!/usr/bin/env python
#binomial coefficient
def ksub(n,k):
if k<=0 or k==n:
return 1
elif k<0 or n<0 or k>n:
return 1
else:
return (ksub(n-1,k-1)+ksub(n-1,k))
#how many ways to partition [n] into k cells
#each cell are mutex and their union is [n]
def stirling(n,k):
if n==k:
return 1
elif k==0 or k>n:
return 0
else:
return k*stirling(n-1,k) + stirling(n-1,k-1)
#bell number
#how many way to parition [n]
#into any number of cells
def bell(n):
bn=1
if n>1:
bn=0
for j in range(0,n+1):
bn=bn+stirling(n,j)
return bn
#bell recursive formula
def bellRecur(n):
sum=0
if n==0 or n==1: return 1
for i in xrange(1,n+1):
sum+= ksub(n-1,i-1)*bellRecur(n-i)
return sum
|
490a659e150f79c7557abe84b440425ba81ca395 | Sbeir/Python_SQLite_Exam | /esame_ufs01/Biblio/create_table.py | 4,110 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 19 16:45:19 2021
@author: RobertoFormenti
"""
import sqlite3
from sqlite3 import Error
#connette al file biblio.sqlite se esiste se no lo crea
conn = sqlite3.Connection('file:biblio.sqlite?mode=rwc', uri=True)
def create_table(conn, create_table_sql): #funzione che crea le tabelle
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def table(): #struttura database sql e poi avvia funzione create_table
sql_create_autore_table = """CREATE TABLE IF NOT EXISTS autore (
nome varchar(255) NOT NULL,
cognome varchar(255) NOT NULL,
anno integer NOT NULL,
note text,
id integer PRIMARY KEY
);"""
sql_create_libro_table = """ CREATE TABLE IF NOT EXISTS libro (
isbn integer PRIMARY KEY,
titolo varchar(255) NOT NULL,
lingua varchar(255) NOT NULL,
anno integer NOT NULL,
editore varchar(255) NOT NULL,
pagine integer NOT NULL,
categoria int NOT NULL,
copie integer NOT NULL,
autore integer NOT NULL,
FOREIGN KEY (autore) REFERENCES autore (id),
FOREIGN KEY (categoria) REFERENCES categoria (id)
); """
sql_create_utente_table = """CREATE TABLE IF NOT EXISTS utente (
nome varchar(255) NOT NULL,
cognome varchar(255) NOT NULL,
anno_reg date NOT NULL,
telefono integer NOT NULL,
tessera integer PRIMARY KEY,
nprest integer NOT NULL
);"""
sql_create_prestito_table = """CREATE TABLE IF NOT EXISTS prestito (
isbn integer,
id integer PRIMARY KEY,
tessera integer NOT NULL,
data_iniz date NOT NULL,
data_fine date NOT NULL,
stato integer NOT NULL,
data_consegna date,
FOREIGN KEY (tessera) REFERENCES utente (tessera),
FOREIGN KEY (isbn) REFERENCES libro (isbn)
);"""
sql_create_categoria_table = """CREATE TABLE IF NOT EXISTS categoria (
id integr PRIMARY KEY,
nome varchar(255) not null
);"""
# create a database connection
conn = sqlite3.Connection('file:biblio.sqlite?mode=rwc', uri=True)
# create tables
if conn is not None:
create_table(conn, sql_create_autore_table)
create_table(conn, sql_create_libro_table)
create_table(conn, sql_create_utente_table)
create_table(conn, sql_create_prestito_table)
create_table(conn, sql_create_categoria_table)
else:
print("Error! cannot create the database connection.")
conn.close()
if __name__ == '__main__':
table() |
e0ee6d13b199a167c7cf72672876ff5d4b6e1b99 | LuisPereda/Learning_Python | /Chapter03/excercise1.py | 420 | 4.1875 | 4 | # This program parses a url
url = "http://www.flyingbear.co/our-story.html#:~:text=Flying%20Bear%20is%20a%20NYC,best%20rate%20in%20the%20city."
url_list = url.split("/") # Parsing begins at character (/)
domain_name = url_list[2] # Dictates at which character number parsing begins
print (domain_name.replace("www.","")) # Deletes a specific character or string of characters and replaces them with desired input
|
78b34f6a6d9a9048ee5a35146749f9a6c4440875 | LuisPereda/Learning_Python | /Chapter10/default_dict_example4.py | 206 | 3.515625 | 4 | from collections import defaultdict
game = defaultdict(int)
list1 = ['cricket', 'badminton', 'hockey' 'rugby', 'golf', 'baseball' , 'football']
for each in list1:
game[each]= game[each]+1
print game |
40a6ece982e5369eaed63f84061c204f53023ce4 | stoneape314/AdventOfCode2019 | /2019_day2_pt2_intcode.py | 5,469 | 3.546875 | 4 | '''
Advent of Code 2019, Day 2, Pt2
An encoding problem with list input of ints that's an analogy for
assembly language.
Intcode programs work in blocks of 4 numbers at a time, with 3 commands
1: tells you to take the numbers at the indices of the next two numbers,
add them, then place the result at the 3rd index
2: tells you to take the numbers at the indices of the next two numbers,
multiply them, then place the result at the 3rd index
99: tells you end of program
Pt2 asks you to find values for memory addresses 1 & 2 so that the value
at memory address 0 is 19690720
'''
FILENAME = "2019_day2_input.txt"
# both these file read implementations are overkill for a list of strictly numbers separated by commas
# but I was playing around with the different read methods
with open(FILENAME,"r") as f:
codeList = []
# reading in file line by line as list of strings. each string is split into a list
for line in f:
codeList.extend(line.strip("\n").replace(" ","").split(","))
codeList = [int(num) for num in codeList if num.isdigit()]
with open(FILENAME,"r") as f:
codeList2 = []
# using try/except because iterator will throw a StopIteration when it is done and next called
try:
while True:
# next calls each line in file object that is split into list and iterated per element
codeList2.extend(int(num) for num in next(f).strip("\n").replace(" ","").split(",") if num.isdigit())
except:
pass
# reads in file character by character and throws everything in a list
with open(FILENAME,"r") as f:
codeList3 = []
char = f.read(1)
while char:
codeList3.append(char)
char = f.read(1)
def opCode(feed):
feed_copy = feed.copy()
#!!!! When you do enumerate stepwise the index still only goes up by 1. You need to multiply by
#your factor.
for i,x in enumerate(feed_copy[::4]):
# Operation 1: sum the numbers found at the next 2 locations put in location indexed by 4th
if x == 1:
# print(feed_copy[4*i+3],feed_copy[feed_copy[4*i+1]],"+",feed_copy[feed_copy[4*i+2]])
feed_copy[feed_copy[4*i+3]] = feed_copy[feed_copy[4*i+1]] + feed_copy[feed_copy[4*i+2]]
# Operation 2: multiply the numbers found at next 2 locations put in location indexed by 4th
elif x == 2:
# print(feed_copy[4*i+3],feed_copy[feed_copy[4*i+1]],"*",feed_copy[feed_copy[4*i+2]])
feed_copy[feed_copy[4*i+3]] = feed_copy[feed_copy[4*i+1]] * feed_copy[feed_copy[4*i+2]]
# Operation 99: end of program
elif x == 99:
break
# other numbers meant something went wrong
else:
print("error in processing")
break
return feed_copy
def trial(feed):
feed_copy = feed.copy()
# trying some initial values to see how the system reacts. linear? inverse?
# because values at mem locations 1&2 are just added, order doesn't matter
# both the values are integers beween 0 & 99, inclusive
#
# response seems to be linear somewhere below summed value of 160. let's try
# with a bisector test approach
# We want values at mem location 0 to be 19690720
TARGET = 19690720
# verification of opCode via known values test
feed_copy[1] = 12
feed_copy[2] = 2
ret_copy = opCode(feed_copy)
print("Value at memlocation 0 is 4138658:",ret_copy[0] == 4138658)
next_input = (14,14,198)
while True:
# calculated next suggested total input at memloc 1&2
next_input = bisector(next_input[0],next_input[1],next_input[2], ret_copy[0], TARGET)
feed_copy = feed.copy()
feed_copy[1] = next_input[0] // 2
feed_copy[2] = next_input[0] - feed_copy[1]
print("New inputs:",feed_copy[1],feed_copy[2])
ret_copy = opCode(feed_copy)
print("1st:",feed_copy[1]," 2nd:",feed_copy[2]," 0th:", ret_copy[0])
print(ret_copy[0] - TARGET)
if abs(ret_copy[0] - TARGET) <= 20:
break
return
def brute_force(feed):
feed_copy = feed.copy()
# can't find a solution with bisector method (get a value within 8 though)
# just going to number crunch instead
TARGET = 19690720
# verification of opCode via known values test
feed_copy[1] = 12
feed_copy[2] = 2
ret_copy = opCode(feed_copy)
print("Value at memlocation 0 is 4138658:",ret_copy[0] == 4138658)
for i in range(100):
for j in range(100):
feed_copy = feed.copy()
feed_copy[1] = i
feed_copy[2] = j
ret_copy = opCode(feed_copy)
if ret_copy[0] == TARGET:
print("Solution! Found @ memcode1:",feed_copy[1]," and memcode2:",feed_copy[2])
return
def bisector(prev_test, lower_bound, upper_bound, prev_result, targ_value):
# this bisector test assumes linear response, especially since it'll weight
# next test value accordingly
#
# input: all ints
# output: int
if prev_result < targ_value:
lower_bound = max(prev_test,0)
elif prev_result > targ_value:
upper_bound = min(prev_test,198)
new_test = int((upper_bound + lower_bound)/2)
return (new_test,lower_bound, upper_bound)
|
1c33398ed7c5a35041c81e9ba808d38fb603ef25 | pombreda/anacrolix | /various/project-euler/problem1.py | 116 | 3.75 | 4 | #!/usr/bin/env python
sum = 0
for n in xrange(1, 1000):
if not n % 3 or not n % 5:
print n
sum += n
print sum
|
796d95af7e23bc1727f7e0ae171d7dbf559f825d | pombreda/anacrolix | /university/pymd/demos/tictac.py | 3,756 | 3.84375 | 4 | ## 3-D tictactoe Ruth Chabay 2000/05
from visual import *
from tictacdat import *
scene.width=600
scene.height=600
scene.title="3D TicTacToe: 4 in a row"
# draw board
yo=2.
base=grid (n=4, ds=1, gridcolor=(1,1,1))
base.pos=base.pos+vector(-0.5, -2., -0.5)
base.radius=0.02
second=grid(n=4, ds=1)
second.pos=second.pos+vector(-0.5, -1., -0.5)
third=grid(n=4, ds=1)
third.pos=third.pos+vector(-0.5, 0, -0.5)
top=grid(n=4, ds=1)
top.pos=top.pos+vector(-0.5, 1., -0.5)
# get list of winning combinations
wins=win()
print "****************************************"
print "Drag ball up starting from bottom grid."
print "Release to deposit ball in a square."
print "****************************************"
print " "
# make sliders
bars={}
balls={}
for x in arange(-2, 2,1):
for z in arange(-2, 2,1):
cyl=cylinder(pos=(x,-2,z), axis=(0,3,0), radius=0.05, visible=0)
bars[(x,-yo,z)]=cyl
# set reasonable viewing angle
scene.center=(-.5,0,-.5)
scene.forward = (0,-0.05,-1)
scene.autoscale=0
nballs=0
visbar=None
red=(1,0,0)
blue=(.3,.3,1)
bcolor=red
point=None
won=None
while len(balls) < 4*4*4:
while 1:
if scene.mouse.events:
p = scene.mouse.getevent()
if p.drag:
point=p.project(normal=(0,1,0),d=-yo) # 'None' if not in plane
break
# chose valid square
if not (point==None):
point=(round(point[0]), round(point[1]), round(point[2]))
if not (visbar==None): visbar.visible=0
if not (bars.has_key(point)):
continue
visbar=bars[point]
visbar.visible=1
nballs=nballs+1
b=sphere(pos=point, radius=0.3, color=bcolor)
while not scene.mouse.events:
y=scene.mouse.pos.y
if y > 1.: y=1.
if y < -yo: y=-yo
b.y=y
scene.mouse.getevent() # get rid of drop depositing ball
bpoint=(round(b.x), round(b.y), round(b.z))
if not(balls.has_key(bpoint)): # not already a ball there
b.pos=bpoint
balls[bpoint]=b
if bcolor==red: bcolor=blue
else:bcolor=red
else: ## already a ball there, so abort
b.visible=0
visbar.visible=0
visbar=None
# check for four in a row
for a in wins:
a0=balls.has_key(a[0])
a1=balls.has_key(a[1])
a2=balls.has_key(a[2])
a3=balls.has_key(a[3])
if a0 and a1 and a2 and a3:
ccolor=balls[a[0]].color
if balls[a[1]].color==balls[a[2]].color==balls[a[3]].color==ccolor:
won=ccolor
print " "
if ccolor==red:
print "***********"
print " Red wins!"
print "***********"
else:
print "***********"
print " Blue wins!"
print "***********"
for flash in arange(0,5):
balls[a[0]].color=(1,1,1)
balls[a[1]].color=(1,1,1)
balls[a[2]].color=(1,1,1)
balls[a[3]].color=(1,1,1)
rate(10)
balls[a[0]].color=ccolor
balls[a[1]].color=ccolor
balls[a[2]].color=ccolor
balls[a[3]].color=ccolor
rate(10)
break
if not (won==None):
break
print "game over"
|
c592d1c17eb39b646b8a144249a27e521f86b56a | ColeB2/Snake | /snakeObject.py | 4,776 | 3.75 | 4 | '''
snakeObject.py - Main class for snake and food objects
'''
import math
import pygame as pg
from pygame.locals import *
from pyVariables import *
import random
'''SNAKE CLASS'''
class Snake():
def __init__(self, x=START_X, y=START_Y):
self.x = x
self.y = y
self.eaten = 0
self.position = [[self.x, self.y],
[self.x-SCALE, self.y],
[self.x-(2*SCALE), self.y]]
self.head = [self.x, self.y]
self.UP = 'up'
self.DOWN = 'down'
self.RIGHT = 'right'
self.LEFT = 'left'
self.previous_direction = self.RIGHT
self.direction = self.RIGHT
self.color = SNAKE_COLOR
def snake_move(self):
if self.direction == self.RIGHT:
self.head[0] += SCALE
elif self.direction == self.LEFT:
self.head[0] -= SCALE
elif self.direction == self.DOWN:
self.head[1] += SCALE
elif self.direction == self.UP:
self.head[1] -= SCALE
else:
pass
self.previous_direction = self.direction
self.position.insert(0, list(self.head))
self.position.pop()
def move(self, event):
'''Sets movement direction based on key press (WASD/ARROW controls)'''
if (event.key == pg.K_a or event.key == K_LEFT) and \
self.previous_direction != self.RIGHT:
self.direction = self.LEFT
elif (event.key == pg.K_d or event.key == K_RIGHT) and \
self.previous_direction != self.LEFT:
self.direction = self.RIGHT
elif (event.key == pg.K_w or event.key == K_UP) and \
self.previous_direction != self.DOWN:
self.direction = self.UP
elif (event.key == pg.K_s or event.key == K_DOWN) and \
self.previous_direction != self.UP:
self.direction = self.DOWN
else:
self.direction = self.direction
def crash(self):
'''Checks to see if the snake has crashed'''
if self.head[0] < LEFT_BOUND_X or self.head[0] > RIGHT_BOUND_X or \
self.head[1] < TOP_BOUND_Y or self.head[1] > BOTTOM_BOUND_Y:
return True
elif [self.head[0],self.head[1]] in self.position[2:]:
return True
else:
return False
def draw(self, screen):
for position in self.position:
pg.draw.rect(screen, self.color,
(position[0], position[1],SCALE-1,SCALE-1))
def eat(self, apple_pos, screen):
'''
If snake head, collides with apple, increment score,
create new apple and increase size of snake
'''
if self.head[0] == apple_pos.x and self.head[1] == apple_pos.y:
self.eaten += 1
'''add new piece to head'''
self.position.insert(0, list(self.head))
'''adds 3 pieces to tail'''
for i in range(3):
self.y = -50 #So that GREEN square doesn't appear on screen
self.position.append([self.x - (len(self.position)+1 * SCALE),
self.y - (len(self.position)+1 * SCALE)])
apple_pos.new_food(screen, self.position)
return True
class Food():
def __init__(self):
'''initialize x, y values of the 1st piece of food'''
self.x = int()
self.y = int()
self.first_food()
self.possible_food_location = []
def draw(self, screen):
'''Draws the initial/starting piece of food on the screen'''
pg.draw.rect(screen, FOOD_COLOR, (self.x, self.y,SCALE-1,SCALE-1))
def new_food(self, screen, snake_location):
'''Sets x, y of food based on open board locations'''
self.calculate_possible_location(snake_location)
self.x, self.y = random.choice(self.possible_food_location)
self.draw(screen)
def first_food(self):
'''Create random location for the 1st food, away from top left corner'''
x = random.randint((LEFT_BOUND_X + (6*SCALE)), RIGHT_BOUND_X)
y = random.randint((TOP_BOUND_Y + (6*SCALE)), BOTTOM_BOUND_Y)
self.x = math.floor((x/SCALE)) * SCALE
self.y = math.floor((y/SCALE)) * SCALE
def calculate_possible_location(self, snake_location):
'''Calcualate board locations that doesn't contain the snake'''
self.possible_food_location = []
for i in range(LEFT_BOUND_X, RIGHT_BOUND_X, SCALE):
for j in range(TOP_BOUND_Y, BOTTOM_BOUND_Y, SCALE):
if [i,j] not in snake_location:
self.possible_food_location.append([i,j])
|
52062e9097e26c678d957bf732615e1138d08de2 | OsnovaDT/Grokking-Algorithms | /k_nearest_neighbours_algorithm.py | 2,888 | 3.796875 | 4 | '''Code for task in chapter 10'''
from collections import namedtuple
from math import sqrt
def get_the_most_similar_parameter(
parameter, other_parameters):
'''Get the most similar parameter'''
# The most similar parameter and his difference with parameter's values
the_most_similar_parameter = None, float('inf')
for another_parameter, another_parameter_values in other_parameters.items():
parameter_and_another_parameter_values = zip(
parameter, another_parameter_values
)
difference_between_parameters_values = sqrt(sum([
(values[0] - values[1]) ** 2 for values in parameter_and_another_parameter_values
]))
# If difference between parameter values less than current smallest difference
if difference_between_parameters_values < the_most_similar_parameter[1]:
the_most_similar_parameter = another_parameter, difference_between_parameters_values
# Name of the most similar parameter
return the_most_similar_parameter[0]
def get_k_most_similar_parameters(parameter, other_parameters, k=1):
'''Get k most similar parameters for the parameter'''
other_parameters_copy = other_parameters.copy()
k_most_similar_parameters = []
while k:
the_most_similar_parameter = get_the_most_similar_parameter(
parameter, other_parameters_copy
)
k_most_similar_parameters.append(the_most_similar_parameter)
other_parameters_copy.pop(the_most_similar_parameter)
k -= 1
return k_most_similar_parameters
def main():
'''Run function get_the_most_similar_parameter'''
# Task 1 - Classification
UserRating = namedtuple(
'UserRating',
[
'Comedy',
'Action_movie',
'Drama',
'Horror',
'Melodrama'
]
)
current_user_ratings = UserRating(3, 4, 4, 1, 4)
other_users_ratings = {
'Justin': UserRating(4, 3, 5, 1, 5),
'Morpheus': UserRating(2, 5, 1, 3, 1),
}
print(get_the_most_similar_parameter(
current_user_ratings, other_users_ratings
))
# Task 2 - Regression
DayCondition = namedtuple(
'DayCondition',
[
'Weather',
'IsHoliday',
'ThereIsSportGame',
]
)
today_condition = DayCondition(4, 1, 0)
other_days_conditions = {
'A': DayCondition(5, 1, 0),
'B': DayCondition(3, 1, 1),
'C': DayCondition(1, 1, 0),
'D': DayCondition(4, 0, 1),
'E': DayCondition(4, 0, 0),
'F': DayCondition(2, 0, 0),
}
print(get_k_most_similar_parameters(
today_condition, other_days_conditions, 4
))
print(get_k_most_similar_parameters(
today_condition, other_days_conditions, 4
))
if __name__ == '__main__':
main()
|
b412d0a61cf0122d340d79c6ea076c61c814549e | OsnovaDT/Grokking-Algorithms | /chapter_9.py | 4,136 | 4.21875 | 4 | '''Code for tasks from chapter 9'''
from collections import namedtuple
ThingForGrab = namedtuple(
'Thing_for_grab',
['weight', 'price']
)
def print_prices_matrix(prices, subjects_names):
'''Prints prices in a beautiful way with their string's names'''
max_len_for_name_in_string_names = len(max(
subjects_names,
key=len
))
# Matrix elements
print(prices)
for string_index, string in enumerate(prices):
indent = max_len_for_name_in_string_names - \
len(subjects_names[string_index])
print(subjects_names[string_index], ' ' * indent, string)
def get_max_price_for_grab(things, max_backpack_size):
'''Get max possible price fot all the things we can grab'''
# Set prices to zero
prices = [
[0 for _ in range(max_backpack_size)] for _ in things
]
names_of_things_for_grab = list(things.keys())
# For each string in prices matrix
for str_index, string in enumerate(prices):
current_thing = things[
names_of_things_for_grab[str_index]
]
current_thing_weight = current_thing[0]
current_thing_price = current_thing[1]
# For each element in the string
for element_index in range(len(string)):
# If the thing doesn't fit in the backpack
if (element_index + 1) < current_thing_weight:
# The price = zero
prices[str_index][element_index] = 0
# If the thing fits in the backpack
else:
# If the string is first
if str_index == 0:
# The price = price for current thing
prices[str_index][element_index] = current_thing_price
# If the string is NOT first
else:
current_price_for_this_weight = \
prices[str_index - 1][element_index]
remaining_weight = element_index - current_thing_weight
if remaining_weight < 0:
remaining_weight = 0
price_for_remaining_weight = \
prices[str_index - 1][remaining_weight]
another_price = current_thing_price + price_for_remaining_weight
if current_price_for_this_weight > another_price:
prices[str_index][element_index] = current_price_for_this_weight
else:
prices[str_index][element_index] = another_price
# return prices
return prices[len(things) - 1][max_backpack_size - 1]
def get_most_similar_word(user_word, similar_words):
'''Get most similar word on the user's word'''
coincidence_for_similar_words = {}
for similar_word in similar_words:
letters_for_words = list(zip(similar_word, user_word))
number_of_coincidence = 0
for similar_word_letter, user_word_letter in letters_for_words:
if similar_word_letter == user_word_letter:
number_of_coincidence += 1
coincidence_for_similar_words[similar_word] = number_of_coincidence
return max(
list(coincidence_for_similar_words.items()),
key=lambda word_and_coincidence: word_and_coincidence[1]
)[0]
def main():
'''Apply function get_max_price_for_grab'''
# Task 1
things_for_grab = {
'Recorder': ThingForGrab(4, 3_000),
'Laptop': ThingForGrab(3, 2_000),
'Guitar': ThingForGrab(1, 1_500),
# 'Iphone': ThingForGrab(1, 2_000),
# 'MP-3': ThingForGrab(1, 1_000),
}
max_backpack_size = 4
# It'll works if change last string for function get_max_price_for_grab
# print_prices_matrix(
# get_max_price_for_grab(things_for_grab, max_backpack_size),
# [name for name in things_for_grab]
# )
print(get_max_price_for_grab(things_for_grab, max_backpack_size))
# Task 2
user_word = 'hish'
similar_words = ['fish', 'vista']
print(get_most_similar_word(user_word, similar_words))
if __name__ == '__main__':
main()
|
06863f77ce80ac75a5c43e30b31efd91b81fefd8 | FernnandoSussmann/PyCalculator | /Operation.py | 1,879 | 3.953125 | 4 | class Operation(object):
def __init__(self,operation_type, value1, value2, result):
self.operation_type = operation_type
self.value1 = value1
self.value2 = value2
self.result = result
def get_operation_type(self):
return self.operation_type
def get_value1(self):
return self.value1
def get_value2(self):
return self.value2
def get_result(self):
return self.result
def set_operation_type(self, operation_type):
self.operation_type = operation_type
def set_value1(self, value1):
self.value1 = value1
def set_value2(self, value2):
self.value2 = value2
def set_result(self, result):
self.result = result
def sum_values(self):
return self.get_value1() + self.get_value2()
def subtract_values(self):
return self.get_value1() - self.get_value2()
def multiply_values(self):
return self.get_value1() * self.get_value2()
def divide_values(self):
return self.get_value1() / self.get_value2()
def power_of_value1_by_value2(self):
return self.get_value1() ** self.get_value2()
def root_of_value1_by_value2(self):
return self.get_value1() ** (1/self.get_value2())
def derivative_of_value1_by_value2(self):
result = self.get_value1() * self.get_value2()
return result
def integral_of_value1_by_value2(self):
result = self.get_value1() / (self.get_value2() + 1)
return result
def adjust_value2(self):
if (self.get_operation_type() == 7):
self.set_value2(self.get_value2() - 1)
elif (self.get_operation_type() == 8):
self.set_value2(self.get_value2() + 1)
def __str__(self):
if self.get_operation_type() in range(1,7):
return str(self.get_result())
elif self.get_operation_type() in (7,8):
return "\n" + str(self.get_result()) + "x^" + str(self.get_value2()) + "\n"
else:
return "Invalid Operation"
|
9448f1cc26fecc85c8b5f39ac8b029e66021f394 | popposs/ProjectEuler | /q36/q36.py | 702 | 3.671875 | 4 | import timeit
def to_binary(n):
return "{0:b}".format(n)
def digits(n):
return map(int, str(n))
def is_palindromic(n):
d = digits(n)
length = len(d)
end = int(length / 2) + (length % 2 == 0)
for i in xrange(end):
if d[i] != d[length - i - 1]:
return False
d = digits(to_binary(n))
length = len(d)
end = int(length / 2) + (length % 2 == 0)
for i in xrange(end):
if d[i] != d[length - i - 1]:
return False
return True
start = timeit.default_timer()
total = 0
for i in xrange(1000000):
if is_palindromic(i):
total += i
print total
stop = timeit.default_timer()
print 'Time:', stop - start
|
43cfed3d199b536a9450f4021ddc18b15e2bbdfa | itisdhiraj/Simple-Chatty-Bot | /Problems/Very odd/task.py | 110 | 3.71875 | 4 | a = int(input())
b = int(input())
result = a // b
if result % 2 == 0:
print(False)
else:
print(True)
|
5663034bdb0f71931aeb1112d91972beb8442bb2 | mannaf/Python_docs | /Chapter 9/Object_Methods.py | 204 | 3.6875 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfun(self):
print("Hello my Name is " + self.name)
p1 = Person("Johan", 36)
p1.myfun()
|
e1934bcda23f7563d1cb6e220901682f0ce7c881 | mannaf/Python_docs | /Chapter 9/inheritance_add_prop.py | 391 | 3.828125 | 4 | class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.greaduationyear = year
x = Student("mannaf", "Abde", 2020)
print(x.greaduationyear)
|
9aa73c6303a6ea7fe63841bc56352f020b73be05 | SuperCowPowers/zat | /zat/utils/file_storage.py | 5,197 | 3.640625 | 4 | """FileStorage class for storing/retrieving bytes to/from persistant storage
Methods:
- store(key, bytes): Takes a bytes object as input
- get(key): Returns a bytes object
"""
import os
try:
import pyarrow # noqa F401
_HAVE_PYARROW = True
except ImportError:
print('pyarrow not found, $ pip install pyarrow for more tests...')
_HAVE_PYARROW = False
class FileStorage(object):
"""FileStorage class for storing/retrieving bytes to/from persistant storage
Methods:
- store(key, bytes): Takes a bytes object as input
- get(key): Returns a bytes object
"""
def __init__(self):
"""FileStorage Initialization"""
self.tmp_dir = '/tmp/zat_file_storage'
os.makedirs(self.tmp_dir, exist_ok=True)
def store(self, key, bytes_buffer):
"""Store the buffer with the associated key"""
# Write the temporary file
try:
filename = self.compute_filename(key)
tempfile = filename + '.tmp'
with open(tempfile, 'wb') as fp:
fp.write(bytes_buffer)
os.rename(tempfile, filename)
except (PermissionError, IOError):
msg = 'FileStorage: could not write to disk!'
print(msg)
raise IOError(msg)
def get(self, key):
"""Retrieve the buffer associated with the given key"""
# Now see if we can read it off disk (it may have been removed/expired)
try:
filename = self.compute_filename(key)
print('FileStorage: Returning bytes for: {:s}'.format(key))
with open(filename, 'rb') as fp:
return fp.read()
except IOError:
print('Could not read file for key: {:s}'.format(key))
return None
def compute_filename(self, key):
# Compute the temporary file name
return os.path.join(self.tmp_dir, key)
def stored_files(self):
return [os.path.join(self.tmp_dir, name) for name in os.listdir(self.tmp_dir)]
@property
def size(self):
"""Return size of the query/dataframe store"""
return len(self.stored_files())
def clear(self):
"""Clear the query/dataframe store"""
for filename in self.stored_files():
try:
os.unlink(filename)
except IOError:
print('Could not delete: {:s}'.format(filename))
def dump(self):
"""Dump the cache key/values (for debugging)"""
for filename in self.stored_files():
print(filename)
def test():
"""Test for the FileStorage class"""
import json
from io import BytesIO
import pandas as pd
# Create some data
data1 = {'foo': [1, 2, 1, 1, 2, 3], 'name': ['bob', 'bob', 'sue', 'sue', 'jim', 'jim']}
data2 = {'count': [8, 9, 8, 8, 8, 9], 'name': ['joe', 'sal', 'joe', 'sal', 'joe', 'sal']}
my_storage = FileStorage()
my_storage.clear()
# Serialize the data
bytes1 = json.dumps(data1).encode('utf-8')
bytes2 = json.dumps(data2).encode('utf-8')
# Test storage
my_storage.store('data1_key', bytes1)
my_storage.store('data2_key', bytes2)
# Make sure size is working
assert my_storage.size == 2
# Try grabbing a key that doesn't exist
assert my_storage.get('no key') is None
# Dump the storage
my_storage.dump()
# Retrieve the stored data
r_data1 = json.loads(my_storage.get('data1_key'))
r_data2 = json.loads(my_storage.get('data2_key'))
assert r_data1 == data1
assert r_data2 == data2
# Delete our key value entries
my_storage.clear()
assert my_storage.size == 0
# Dump the cache
my_storage.dump()
# Now run all the same tests with dataframes (only if pyarrow available)
if _HAVE_PYARROW:
# Helper methods
def dataframe_to_bytes(df):
bytes_buffer = BytesIO()
df.to_parquet(bytes_buffer)
return bytes_buffer.getvalue()
def dataframe_from_bytes(df_bytes):
return pd.read_parquet(BytesIO(df_bytes))
# Create the a dataframe and a DataStore class
df1 = pd.DataFrame(data={'foo': [1, 2, 1, 1, 2, 3], 'name': ['bob', 'bob', 'sue', 'sue', 'jim', 'jim']})
df2 = pd.DataFrame(data={'count': [8, 9, 8, 8, 8, 9], 'name': ['joe', 'sal', 'joe', 'sal', 'joe', 'sal']})
my_storage.clear()
# Serialize the dataframes
df1_bytes = dataframe_to_bytes(df1)
df2_bytes = dataframe_to_bytes(df2)
# Test storage
my_storage.store('df1_key', df1_bytes)
my_storage.store('df2_key', df2_bytes)
# Make sure size is working
assert my_storage.size == 2
# Dump the cache
my_storage.dump()
# Retrieve the cached dataframes
r_df1 = dataframe_from_bytes(my_storage.get('df1_key'))
r_df2 = dataframe_from_bytes(my_storage.get('df2_key'))
assert r_df1.equals(df1)
assert r_df2.equals(df2)
# Delete our key value entries
my_storage.clear()
assert my_storage.size == 0
if __name__ == '__main__':
# Run the test
test()
|
7230c582168abaff0ca797c95cf8c5a5cb7756be | saunders-jake/EaglePing | /eagleping.py | 2,703 | 3.546875 | 4 | from pythonping import ping
from time import sleep, localtime, strftime
import sys, time
print("##########################")
print("........EAGLE PING........")
print("##########################")
print(" Made by: Jake Saunders ")
print("##########################\n")
logpath = "output.txt" #Path to your desired output file.
packettotal = 2 #Determines the amount of packets to be sent per address, per ping "round" (I recommend 2)
while True:
try:
pingint = int(input("Enter ping interval(seconds): ")) #Takes user input for the amount of time between rounds of pings
if pingint <= 0:
print("Please enter a positive integer.") #Verifies that user input is not a negative number.
else:
break #Breaks the loop, input has been completely verifed and saved to the pingint variable.
except(ValueError):
print("Please enter a positive integer.") #Verifies that user input doesn't include any non-numeric characters
while True:
try:
ipct = int(input("\nEnter amount of addresses: ")) #Takes user input for the desired amount of addresses to be pinged.
if ipct <= 0:
print("Please enter a positive integer.") #Verifies that user input is not a negative number.
else:
break #Breaks the loop, input has been completely verifed and saved to the ipct variable.
except(ValueError):
print("Please enter a positive integer.") #Verifies that user input doesn't include any non-numeric characters
iplst = []
for i in range(0,ipct):
z = input("Address {}: ".format(str(i+1))) #Takes user input for the ip/domain to be pinged.
iplst.append(z) #Appends above ip/domain to iplst
log = open(logpath, 'a+') #Opens/Creates temp.txt in append mode.
roundcounter = 0
print("")
while True:
try:
for q in range(len(iplst)):
response = ping(iplst[q],verbose=True,count=packettotal) #Iterates though the iplst list, pinging each address x amount of times (determined by packtettotal), and displays output to terminal.
roundcounter += 1
for i in range(packettotal):
if "Reply from" not in str(response._responses[i]):
timestamp = strftime("%d %b %Y %H:%M:%S", localtime()) #Creates the timestamp used in the log
log.write("{} {} {} Round: {}\n".format(timestamp, iplst[q], response._responses[q], roundcounter))
print("Round {} complete".format(roundcounter))
time.sleep(pingint-.5) #Pauses the program for x amount of seconds (determined by the user input from pingint) between rounds of pings.
except KeyboardInterrupt:
break #Makes the program quit once the user hits the proper break key
print("\nCompleted {} rounds".format(roundcounter))
print("Quitting program...\n")
sys.exit()
|
4efdb253e77e395072a91db9407b4896a5121edb | chintanvijan/Data-Structures | /python/stack.py | 1,028 | 4.09375 | 4 | class node:
def __init__(self,dataval):
self.dataval=dataval
self.nextval = None
class stack:
def __init__(self):
self.headval = None
def push(self,dataval):
if self.headval == None:
self.headval = node(dataval)
else :
t = self.headval
self.headval = node(dataval)
self.headval.nextval = t
def pop(self):
if self.headval==None:
print("Stack is Empty! Can't pop")
else:
self.headval = self.headval.nextval
def traverse(self):
val = self.headval
while val is not None:
print(val.dataval)
val = val.nextval
st = stack()
ch = 'y'
while ch=='y':
print("Enter 1 to push elements into stack")
print("Enter 2 to pop elements from stack")
print("Enter 3 to traverse stack")
inp = int(input())
if inp == 1:
dataval = input("Enter data to be inserted into stack:")
st.push(dataval)
print("Push Successfull!")
if inp == 2:
st.pop()
print("Pop Successfull!")
if inp == 3:
st.traverse()
ch = input("Want to continue?(y/n)")
|
6ea1039b8aabd3cf03922cbd6cbb81c9eb7fbbe5 | ordros/Euler | /problem12.py | 573 | 3.640625 | 4 | from math import sqrt, ceil
def count_divisors(N):
fact = 1
j = 0
max = ceil(sqrt(N))
if N >= 3:
while N!=1 and N%2==0:
j += 1
N /= 2
i = 3
fact *=(j+1)
j = 0
while N!=1 and i<=max:
while N!=1 and N%i==0:
j += 1
N /= i
fact *=(j+1)
i += 2
j = 0
if N > max:
fact *=2
return fact
i = 0
j = 1
while 1:
i += j
j += 1
if count_divisors(i) >= 500:
print i
break
|
3fedb6049e642132bc3d056ff6c1631bbcd282fe | CA2528357431/python-note-re | /07/main.py | 902 | 3.78125 | 4 | import re
#零宽断言
#即可修饰匹配内容前后的内容,又可以修饰要匹配的内容
a='word wow woawo wo w wasting aworow walling arrrw'
x=re.compile(r'\b\w+(?=ing\b)')#匹配 \b\w+ 此\w+后方必须是ing\b
xx=x.findall(a)
print(xx)
#正预测零宽断言,对后续部分的要求
# 形式为(?=结构)
x=re.compile(r'(?<=\bwo)\w+\b')#匹配 \w+\b 而且\w+前方必须是\bwo
xx=x.findall(a)
print(xx)
#正回顾零宽断言,对之前部分的修饰
# 形式为(?<=结构)
x=re.compile(r'\b(?!w)\w+\b')#匹配 \b\w+ 此\w+第一个必须不是w
xx=x.findall(a)
print(xx)
#负预测零宽断言,对后续部分的要求
# 形式为(?!结构)
x=re.compile(r'\b\w{2}(?<!o)\w+\b')#匹配 \w{2}\w+ 而且\w{2}第二个前方第一个字符不是o
xx=x.findall(a)
print(xx)
#负回顾零宽断言,对之前部分的修饰
# 形式为(?<!结构)
|
cca792b806acb6de02f602c55746873161c513b3 | witters9516/CSC-221 | /Examples/m2_vowel_finder.py | 648 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 25 12:16:24 2017
@author: norrisa
"""
def findVowels(word):
vowels = ['a', 'e', 'i', 'o', 'u']
found = []
for letter in word:
if letter in vowels:
print(letter)
def findVowelsV2(word):
vowels = ['a', 'e', 'i', 'o', 'u']
found = []
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print('Found vowels: ',end='')
for vowel in found:
print(vowel,end=',')
print()
def testFindVowels():
word = input('Provide a word to search for vowels: ')
findVowels(word) |
57ca2c5a050d5194c1ba7e935c81ccd0a888d501 | witters9516/CSC-221 | /test.py | 1,562 | 3.78125 | 4 | def main():
title = 'a clash of KINGS'
minor_words = 'a an the of'
officialTitle = title_case(title, minor_words)
print(officialTitle)
def title_case(title, minor_words):
# print(title)
titleWordList = list()
minorWordList = list()
officialTitle = ""
if title != '':
print("Yorgy Shmorgy!")
titleWordList = title.split(' ')
print(titleWordList)
minorWordList = minor_words.split(' ')
print(minorWordList)
#for i in titleWordList:
#titleWordList[i].lowercase()
#print(titleWordList[i])
count1 = 0
for item in titleWordList:
count1 += 1
print("Count1 = " + str(count1))
count2 = 0
for item in minorWordList:
count2 += 1
print("Count2 = " + str(count2))
for item in range(0, count1, 1):
for item2 in range(0, count2, 1):
print(titleWordList[item] + " : " + minorWordList[item2])
if titleWordList[item] == minorWordList[item2]:
if item == 0:
officialTitle += titleWordList[item].title() + " "
else:
titleWordList[item] == minorWordList[item2]
officialTitle += titleWordList[item] + " "
else:
if item == (count1 -1):
officialTitle += titleWordList[item].title()
else:
officialTitle += titleWordList[item].title() + " "
return officialTitle
main()
|
260d5caa5d4ea343e7d356ab693761dd99f0677f | zilongxuan001/LearnPythonhandbook | /ex201012_20201012.py | 244 | 3.859375 | 4 | number = int(input())
num = len("Hello World")
HW =("Hello World")
j = 0
if number == 0:
print("Hello World")
elif number > 0:
while j < num:
print(HW[j:j+2])
j +=2
else:
for i in "Hello World":
print(i)
|
7e38dc101f8ef9007499f15cc251ce89984123f3 | zilongxuan001/LearnPythonhandbook | /single_20201106.py | 3,781 | 3.609375 | 4 | import turtle,time
def drawGap():
turtle.penup()
turtle.fd(5)
def drawLine(draw): # 处理单个行
drawGap()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawGap()
turtle.right(90)
def drawDigit(digit): # 处理单个字符
drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,6,8] else drawLine(False)
turtle.left(90) # 从中间一横开始,画4个横后,就需要直着前进一部分。
drawLine(True) if digit in [0,4,6,8,9] else drawLine(False)
drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False)
drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
turtle.left(180)
turtle.penup()
turtle.fd(20)
def drawDate(date): # 将日期分解为单个字符。
turtle.pencolor("red")
for i in date: # 循环取出每个数字
if i == "-":
turtle.write('年', font=("Arial",18,"bold"))
turtle.pencolor("green")
turtle.fd(40)
elif i == "=":
turtle.write('月', font=("Arail",18,"normal"))
turtle.pencolor("green")
turtle.fd(40)
elif i == "+":
turtle.write('日', font=('Arail',18,'italic'))
else:
drawDigit(eval(i))
def main(): # 建设画布,获得日期
turtle.setup(800, 350, 200, 200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
turtle.speed(100)
drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))
turtle.hideturtle()
turtle.done()
main()
#犯的错误:
#1. 第31行turtle.pencolor("red") 多了':',修改方法:去掉':'
#2. 第34、38、42行的font前的“,”错了,为中文标号,改成英文","
#3. 第26行“turle.left(180)”拼写错了,改为“turtle.left(180)”
#4. 第18行“drawLine(True) if digit in [0,2,3,5,6,8,9] else drawline(False)”的“drawline”拼写错误,应为“drawLine”
# 原理:
# 7段数码管是个8字形,每次海龟画线都从中间一段横线开始,不断右转,或直线,每段横线画出线,或者不画出线。
#
# main()控制所有函数:
# 1.设置画布大小,并移动海龟到合适位置。
# 2.其次设置笔触大小
# 3.根据时间画七段管。设置时间显示的格式,并获得时间,调用drawDate()函数,根据时间格式画七段管。
# 4.隐藏海龟,并在画布上停留。
#
# drawDate()控制所有日期:
# 1.根据时间的格式区分出“年”、“月”、“日”,设置颜色,并写出来,再右移动。
# 2.drawDigit()写年月日的数字。
#
# drawDigit()中控制单个数字:
# 1. 调用drawLine(),根据每个数字的不同,画出每个数字来。
# 2. 画完每个数字后,调整方向,并右移一段时间。
#
# drawLine()中控制每一横:
# 1. 调用drawGap()形成横与横之间的缝隙
# 2. 根据drawDigit()控制海龟是否抬起还放下。
# 3. 画横。如果海龟抬起,则无痕迹,如果海龟放下,则留下一横。
# 4. 调用drawGap()形成横与横之间的缝隙
# 5. 右转90度。
# 点评:
# 该代码的函数环环相套,从获得日期,循环取出,分解为单个字符,最后具体到每一横。是自顶向下设计,分解目标
# 新学内容:
# 单行写if...else行数,格式 <执行命令> if <判断条件> else <执行命令>
# turtle.pendown() if draw else turtle.penup()
#
# 海龟直接写文字,turtle.write(),通过font()调整文字的字体,大小和正常(normal, 加粗Bold,斜体italic)
# turtle.write('年', font=("Arial",18,"normal"))
|
274f872cd115a67a51d260296ba6f97189b23d10 | zilongxuan001/LearnPythonhandbook | /forElse_20200922.py | 115 | 3.703125 | 4 | # forElse
for c in "PYTHON":
if c == "T":
continue
print(c, end="")
else:
print("正常退出") |
c7f9d7a7c4f6a8343014e75a01570c46ed2e32eb | zilongxuan001/LearnPythonhandbook | /circles_20200917.py | 333 | 3.671875 | 4 | # circles
import turtle as t
t.pencolor("pink")
t.left(90)
def main():
for i in range(10):
t.circle(10,360)
t.penup()
t.fd(20)
t.pendown()
t.penup()
t.right(180)
t.fd(200)
t.left(90)
t.fd(20)
t.left(90)
t.pendown()
for i in range(10):
main()
t.done()
|
dba14cc9b716dcedab90012a8b47257f05fe47e7 | zilongxuan001/LearnPythonhandbook | /ex16_01_20200902.py | 613 | 3.765625 | 4 | from sys import argv
script, filename = argv
print("Let's open the file:")
target= open(filename, 'r+')
print("Let's erase the content.")
target.truncate()
print("Let's write something")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
print("Let's close the file.")
target.close()
file= open(filename, 'r')
readFile = file.read()
# 游标移动到第一行,否则读取的是空。
file.seek(0,0)
readFileLine = file.readline()
print(readFile)
print(readFileLine)
|
0f59c8d732fd9bedc415c135a372acc743d5d961 | zilongxuan001/LearnPythonhandbook | /ex13_02_20200831.py | 156 | 3.65625 | 4 | from sys import argv
a,x,y,z = argv
print(f"the first is {x}")
print(f"the second is {y}")
print(f"the third is {z}")
print(input("What you want is ")) |
fdad515316880c87f37637b0c1d7ff37a4e833da | L200170122/prak_ASD_D | /Modul_6/partisi.py | 1,033 | 3.734375 | 4 | def partisi(A, awal, akhir):
nilaiPivot = A[awal]
penandaKiri = awal
penandaKanan = akhir
selesai = False
while not selesai:
while penandaKiri <= penandaKanan and A[penandaKiri] <= nilaiPivot:
pendanaKiri = penandaKiri + 1
while A[penandaKanan] >= nilaiPivot and penandaKanan >= penandaKiri:
penandaKanan = penandaKanan - 1
if penandaKanan < penandaKiri:
selesai = True
else:
temp = A[penandaKiri]
A[awal] = A[penandaKanan]
A[penandaKanan] = temp
temp = A[awal]
A[awal] = A[penandaKanan]
A[penandaKanan] = temp
return penandaKanan
def quickSort(A):
quickSortBantu(A, 0, len(A) - 1)
def quickSortBantu(A, awal, akhir):
if awal < akhir:
titikBelah = partisi(A, awal, akhir)
quickSortBantu(A, awal, titikBelah - 1)
quickSortBantu(A, titikBelah + 1, akhir)
alist = [1,4,3,2,6,8,7]
quickSort(alist)
print(quickSort)
|
82a1ab1412c029fe3b789e1b67909ed731cf910e | NickLuGithub/school_homework | /Python/期中考/b10702057-期中考2.py | 930 | 3.515625 | 4 | import time
import random
list1 = ['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']
op = input("請輸入Y開始遊戲")
print(list1)
t0 = time.time()
while op == 'y' or op == 'Y':
for i in range(0, 10):
k = random.randrange(0, 26)
print(list1[k])
for l in range(3):
a = input("請輸入前一個字母")
if (list1[k] == 'a' and a == '0'):
break
elif ((a in list1) == True):
if ((list1.index(a)) == (list1.index(list1[k])) - 1):
break
else:
print("錯誤 ", end = "")
else:
print("不要鬧了!")
op = 'end'
break
else:
t1 = time.time()
print("總共猜10次,您總空花了%f秒" %(t1 - t0))
op = 'end'
|
61e27a466ee3a9d70062faf23f32d2a5ec427c7c | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習3-1-1.py | 1,755 | 4.15625 | 4 | print("第一題");
print(1 == True);
print(1 == False);
print();
print(0 == True);
print(0 == False);
print();
print(0.01 == True);
print(0.01 == False);
print();
print((1, 2) == True);
print((1, 2) == False);
print();
print((0, 0) == True);
print((0, 0) == False);
print();
print('string' == True);
print('string' == False);
print();
print('0' == True);
print('0' == False);
print();
print('' == True);
print('' == False);
print();
print([0, 0] == True);
print([0, 0] == False);
print();
print({0} == True);
print({0} == False);
print();
print({} == True);
print({} == False);
print();
print("第二題");
x = True;
y = False;
print(x == True);
print(x == False);
print();
print(y == True);
print(y == False);
print();
print(x and y == True);
print(x and y == False);
print();
print(x or y == True);
print(x or y == False);
print();
print(x + y== True);
print(x + y== False);
print();
print(x - y== True);
print(x - y== False);
print();
print(x * y== True);
print(x * y== False);
print();
print(y / x== True);
print(y / x == False);
print();
print("第三題");
inx = input("輸入X")
if inx == "True":
x = True
if inx == "False":
x = False
iny = input("輸入Y")
if iny == "True":
y = True
if iny == "False":
y = False
print(x == True);
print(x == False);
print();
print(y == True);
print(y == False);
print();
print(x and y == True);
print(x and y == False);
print();
print(x or y == True);
print(x or y == False);
print();
print(x + y== True);
print(x + y== False);
print();
print(x - y== True);
print(x - y== False);
print();
print(x * y== True);
print(x * y== False);
print();
print(y / x== True);
print(y / x == False);
print(); |
d6aead41f21280a466324b5ec51c9c86a57c35e6 | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習7-1.py | 802 | 4.15625 | 4 | print("1")
list1 = [1,2,3,4]
a = [5, 6, 7, 8]
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("2")
list1 = [1,2,3,4]
a = 'test'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("3")
list1 = [1,2,3,4]
a = ['a', 'b', 'c']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("4")
list1 = [1,2,3,4]
a = '阿貓'
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("5")
list1 = [1,2,3,4]
a = ['阿貓', '阿狗']
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1)
print("6")
list1 = [1,2,3,4]
a = 0
list1.append(a)
print(list1)
list1 = [1,2,3,4]
list1.extend(a)
print(list1) |
2e424f94449de9f18669616d112303960228afe4 | NickLuGithub/school_homework | /Python/課堂練習/b10702057-課堂練習6-1.py | 138 | 3.59375 | 4 | a = "天增歲月人增肉,春滿乾坤福滿身"
for i in a:
if ( i == ","):
print(' ');
else:
print(i); |
9aff0ff67604c76da2cec2fe4ea16c7ac7f889d9 | kaushik246/python-concepts | /src/arg_parse.py | 658 | 3.578125 | 4 | # arg_parse.py
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
parser.add_argument('-arg1', '--argument1' , action="store", required=True, help='Help for option X')
group = parser.add_mutually_exclusive_group()
group.add_argument('-arg2', '--argument2', help='Help for option Y', default=False)
group.add_argument('-arg3', '--argument3', help='Help for option Z', default=10)
print(parser.parse_args())
return parser.parse_args()
if __name__ == '__main__':
get_args() |
8a3dde8254a203250f68e450a793fc43f8b9ccad | JaredQR/CruceroPorElCaribe-Programacion2 | /modulo.py | 6,568 | 3.5625 | 4 | #PUERTOS#
def anadirpuertos():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
puer=input("Ingrese el puerto :" )
pai=input("Ingrese el pais : ")
os.system('cls')
cursor=con.cursor()
cursor.execute("insert into TABPUERTOS(puertos, pais) values ('"+puer+"','"+pai+"')")
con.commit()
con.close()
def salir():
import sys, os
print("Decidio SALIR")
sys.exit()
def verpuertos():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABPUERTOS")
print()
print ("\t Cod \t Puerto \t Ubicacion")
print("********************************************************************")
for TABPUERTOS in cursor:
verpuer='\t'+str(TABPUERTOS[0])+'\t'+" "+str(TABPUERTOS[1])+'\t'+'\t'+str(TABPUERTOS[2])
print(str(verpuer))
con.close
print()
def modificarpuerto():
import sys, os, sqlite3
llave=[]
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABPUERTOS")
print()
print ("\t Cod \t Puerto \t Ubicacion")
print("********************************************************************")
for TABPUERTOS in cursor:
llave.append(TABPUERTOS)
verpuer='\t'+str(TABPUERTOS[0])+'\t'+" "+str(TABPUERTOS[1])+'\t'+'\t'+str(TABPUERTOS[2])
print(str(verpuer))
print("")
cod=input("Ingrese el codigo del puerto que desea modificar :")
for TABPUERTOS in llave:
if int(TABPUERTOS[0]==int(cod)):
P1=TABPUERTOS[1]
P2=TABPUERTOS[2]
encontrado=True
break
P1=input("Digite el nuevo puerto"+P1+":")
P2=input("Digite el nuevo lugar"+P2+":")
sql="update TABPUERTOS set puertos='"+P1+"', pais='"+P2+"' where Cod="+cod
cursor.execute(sql)
con.commit()
con.close()
os.system("cls")
print("El producto a sido modificado")
def sacarpuerto():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABPUERTOS")
print("Aqui puedes eliminar los puertos")
print()
print ("\t Cod \t Puerto \t Ubicacion")
print("********************************************************************")
for TABPUERTOS in cursor:
verpuer='\t'+str(TABPUERTOS[0])+'\t'+" "+str(TABPUERTOS[1])+'\t'+'\t'+str(TABPUERTOS[2])
print(str(verpuer))
print("")
cod=input("Ingrese el codigo que desea eliminar :")
sql="delete from TABPUERTOS where Cod="+cod
cursor.execute(sql)
con.commit()
con.close()
os.system('cls')
print("Elimino un puerto ")
##################################################################################################
#Categorias y precios #
def anadircategoria():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
categ=input("Ingrese la categoria :" )
TB=input("Ingrese el precio de la temporada baja : ")
TM=input("Ingrese el precio de la temporada media : ")
TA=input("Ingrese el precio de la temporada alta : ")
os.system('cls')
cursor=con.cursor()
cursor.execute("insert into TABCATEGORIAS(categoria, tempbaja, tempmed, tempalta) values ('"+categ+"','"+TB+"','"+TM+"','"+TA+"')")
con.commit()
con.close()
def vercategoria():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABCATEGORIAS")
print()
print ("\t Cod \t Categoria \t TempBaja \t TempMed \t TempAlta")
print("********************************************************************")
for TABCATEGORIAS in cursor:
vercategorias='\t'+str(TABCATEGORIAS[0])+'\t'+" "+str(TABCATEGORIAS[1])+'\t'+" "+str(TABCATEGORIAS[2])+'\t'+" "+str(TABCATEGORIAS[3])+'\t'+str(TABCATEGORIAS[4])
print(str(vercategorias))
con.close
print()
def modificarcategoria():
import sys, os, sqlite3
llave=[]
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABCATEGORIAS")
print()
print ("\t Cod \t Categoria \t TempBaja \t TempMed \t TempAlta")
print("********************************************************************")
for TABCATEGORIAS in cursor:
llave.append(TABCATEGORIAS)
vercategorias='\t'+str(TABCATEGORIAS[0])+'\t'+" "+str(TABCATEGORIAS[1])+'\t'+" "+str(TABCATEGORIAS[2])+'\t'+" "+str(TABCATEGORIAS[3])+'\t'+str(TABCATEGORIAS[4])
print(str(vercategorias))
print("")
cod=input("Ingrese el codigo del puerto que desea modificar :")
for TABCATEGORIAS in llave:
if int(TABCATEGORIAS[0]==int(cod)):
C1=TABCATEGORIAS[1]
Cbaja=TABCATEGORIAS[2]
Cmed=TABCATEGORIAS[3]
Calta=TABCATEGORIAS[4]
jared=True
break
C1=input("Digite la nueva categoria "+C1+":")
Cbaja=input("Digite el precio de temporada baja "+str(Cbaja)+":")
Cmed=input("Digite el nuevo precio de temporada media "+str(Cmed)+":")
Calta=input("Digite el nuevo precio de temporada alta "+str(Calta)+":")
sql="update TABCATEGORIAS set categoria='"+C1+"', tempbaja='"+Cbaja+"' , tempmed='"+Cmed+"' , tempalta='"+Calta+"' where Cod="+cod
cursor.execute(sql)
con.commit()
con.close()
os.system("cls")
print("El producto a sido modificado")
def sacarcategoria():
import sys, os, sqlite3
con = sqlite3.connect('DISENHO.s3db')
cursor=con.cursor()
cursor.execute("select * from TABCATEGORIAS")
print("Aqui puedes eliminar los puertos")
print()
print ("\t Cod \t Categoria \t TempBaja \t TempMed \t TempAlta")
print("********************************************************************")
for TABCATEGORIAS in cursor:
vercategorias='\t'+str(TABCATEGORIAS[0])+'\t'+" "+str(TABCATEGORIAS[1])+'\t'+" "+str(TABCATEGORIAS[2])+'\t'+" "+str(TABCATEGORIAS[3])+'\t'+str(TABCATEGORIAS[4])
print(str(vercategorias))
print("")
cod=input("Ingrese el codigo que desea eliminar :")
sql="delete from TABCATEGORIAS where Cod="+cod
cursor.execute(sql)
con.commit()
con.close()
os.system('cls')
print("Elimino un puerto ")
|
b17b98417dd5426278864a106cb22b7f7b2ba0ec | JNewberry/Lists | /List Rev 2.py | 351 | 3.953125 | 4 | #John Newberry
#
#List Rev 2
name_list = []
order = 0
for count in range(6):
order + 1
name = input("Please input a name: ")
name_list.append(name)
print(name_list)
while 1:
print("Please input the names you wish to view")
view = int(input("From: "))
end_view = int(input("To: "))
print(name_list[view:end_view])
|
b6cb4e5b3387f132abd793de8a7c79d719bef2e2 | aspcodenet/iot_StefanIfLabbar | /PythonLabbarIf/Labb6.py | 239 | 3.828125 | 4 |
age = int(input("Ange ålder"))
if age >=1980 and age < 1990:
print("Du är född på 1980-talet")
elif age >=1990 and age < 2000:
print("Du är född på 1990-talet")
else:
print("Du är inte född på 1990 eller 1980-talen") |
58de770241c64ab5294eac22884c104814b61bd4 | mfligiel/Capstone_Text_Mining | /capstone_text_mining/graph_viz.py | 1,043 | 3.75 | 4 |
import networkx as nx
from matplotlib import pyplot as plt
def graphviz(graph, edgecolor='grey', nodecolor='purple'):
"""
Parameters
----------
graph : graph object
A graph object prepared by the graphprep function
edgecolor : string
Optional color selection for visualization
nodecolor : string
Optional color selection for visualization
Returns
-------
A visualization of keywords.
"""
fig, ax = plt.subplots(figsize=(10, 8))
pos = nx.spring_layout(graph, k=2)
# Plot networks
nx.draw_networkx(graph, pos,
font_size=16,
width=3,
edge_color=edgecolor,
node_color=nodecolor,
with_labels = False,
ax=ax)
# Create offset labels
for key, value in pos.items():
x, y = value[0]+.135, value[1]+.045
ax.text(x, y,
s=key,
bbox=dict(facecolor='red', alpha=0.25),
horizontalalignment='center', fontsize=13)
plt.show()
|
a898631d48a06defcbdad0a66c6d9cd4d6f96e3b | jwon/adventofcode | /2021/12/p1.py | 1,062 | 3.75 | 4 | from pprint import pprint
caves = {}
with open('input.txt') as f:
for line in f:
cave, connected_to = line.strip().split('-')
if cave in caves:
caves[cave].add(connected_to)
else:
caves[cave] = {connected_to}
if connected_to in caves:
caves[connected_to].add(cave)
else:
caves[connected_to] = {cave}
pprint(caves)
def traverse(current_cave, path=None, cannot_visit_again=None):
cannot_visit_again = set() if cannot_visit_again is None else set(cannot_visit_again)
path = [] if path is None else list(path)
path.append(current_cave)
if current_cave.islower():
cannot_visit_again.add(current_cave)
if current_cave == 'end':
print(f'FOUND PATH: {path}')
return 1
potential_caves = caves[current_cave] - cannot_visit_again
if potential_caves != set():
return sum(traverse(cave, path=path, cannot_visit_again=cannot_visit_again) for cave in potential_caves)
else:
return 0
print(traverse('start'))
|
3edc431c6167d5f8715dccc885d4cb5ba81e4e9b | iubica/tickerscrape | /scrape/web.py | 2,654 | 3.515625 | 4 | """
Routines for caching web queries
"""
import requests
from bs4 import BeautifulSoup
import pandas as pd
import six
_web_cache = dict()
def get_web_page(url, force):
"""
Gets a web page from the web, or from the local cache, in case it is cached.
Arguments:
url - the URL to retrieve
force - if True, overwrite the cache
Return value:
The contents of the web page
"""
if force or (url not in _web_cache):
r = requests.get(url)
_web_cache[url] = r.content
return _web_cache[url]
def get_web_page_table(url, force, table_idx):
"""
Gets a web page table in DataFrame format
Arguments:
url - the URL to retrieve
force - if True, overwrite the cache
table_idx - the index of the table
Return value:
The DataFrame associated to the table
"""
# Get the page
web_page = get_web_page(url, force)
# Parse the contents
soup = BeautifulSoup(web_page, 'lxml')
# List of all tables
tables = soup.find_all('table')
# Specific tables
table = tables[table_idx]
# Get the number of rows and columns
row_count = len(table.find_all('tr'))
column_count = 0
for row in table.find_all('tr'):
column_idx = len(row.find_all('th')) + len(row.find_all('td'))
if column_count < column_idx:
column_count = column_idx
#print("row_count = %s, column_count = %s"%(row_count, column_count))
df = pd.DataFrame(columns = range(column_count),
index = range(row_count))
row_idx = 0
for row in table.find_all('tr'):
column_idx = 0
columns = row.find_all('th') + row.find_all('td')
for column in columns:
column_text = column.get_text()
#print("row_idx %d, cloumn_idx %d, text %s" % (row_idx, column_idx, column_text))
df.iat[row_idx, column_idx] = column_text
column_idx += 1
row_idx += 1
return df
def dataframe_promote_1st_row_and_column_as_labels(df):
"""
Moves the DataFrame first row as column labels, and the first column
as row labels.
Arguments:
df - the DataFrame
Returns: the updated Dataframe
"""
table_name = df.at[0, 0].strip()
df.at[0, 0] = "_"
# Promote 1st row as column labels
transform = lambda x: x.strip() if isinstance(x, six.string_types) else x
df.columns = df.iloc[0].map(transform)
df = df[1:]
# Promote 1st column as new index
df2 = df.set_index("_")
df = df2
df.index.name = table_name
return df
if __name__ == "__main__":
pass
|
13e937ebfdb6866b60dc3aa4f3b96b8d4744e07c | confar/algorithms_stepik | /course_1_algorithms/dynamic/calculator.py | 1,067 | 3.796875 | 4 | import math
from collections import deque
def calculate_steps_from_number_to_one(number):
operation_list = deque([number])
step_list = [0] + [math.inf for _ in range(number)]
prev_list = [math.inf for _ in range(number)]
if number != 1:
for num in range(1, number):
for value in (num * 3, num * 2, num + 1):
if value <= number and step_list[num - 1] + 1 < step_list[value - 1]:
step_list[value - 1] = step_list[num - 1] + 1
prev_list[value - 1] = num
while number > 1:
new_elem = prev_list[number-1]
operation_list.appendleft(new_elem)
number = new_elem
return len(operation_list) - 1, list(operation_list)
def main():
assert calculate_steps_from_number_to_one(1) == (0, [1])
assert calculate_steps_from_number_to_one(5) == (3, [1, 2, 4, 5])
assert (calculate_steps_from_number_to_one(96234) == (
14, [1, 3, 9, 10, 11, 22, 66, 198, 594, 1782, 5346, 16038, 16039, 32078, 96234]))
if __name__ == '__main__':
main()
|
9c645cb9fc290a59f8cf438c7e96deb994303992 | confar/algorithms_stepik | /course_2_data_structures/hash_tables/chaining_hashmap.py | 4,172 | 3.625 | 4 | import io
from functools import partial
from typing import List
class NotFound(Exception):
pass
class ListElem:
def __init__(self, value: str) -> None:
self.value = value
self.next = None
class LinkedList:
def __init__(self) -> None:
self.head = None
self.size = 0
def __bool__(self) -> bool:
return bool(self.head)
def find(self, string: str) -> ListElem:
elem = self.head
if self.is_empty():
raise NotFound
while elem.value != string:
if elem.next:
elem = elem.next
else:
raise NotFound
return elem
def is_empty(self) -> bool:
return not self.size
def add(self, string: str) -> None:
elem = ListElem(value=string)
if not self.head:
self.head = elem
else:
current_head = self.head
self.head = elem
self.head.next = current_head
self.size += 1
def remove(self, string: str) -> None:
if self.is_empty():
return
elem = self.head
if elem.value == string:
self.head = elem.next
self.size -= 1
elif elem.next:
while elem.next and elem.next.value != string:
elem = elem.next
if elem.next:
removed_value_next = elem.next.next
elem.next = removed_value_next
self.size -= 1
def get_values(self) -> List[str]:
out = []
elem = self.head
for _ in range(self.size):
out.append(elem.value)
elem = elem.next
return out
class HashTable:
def __init__(self, size: int) -> None:
self.array = [LinkedList() for _ in range(size)]
self.size = size
def add(self, string: str) -> None:
hash = self.get_hash(string)
lst = self.array[hash]
try:
lst.find(string)
except NotFound:
self.array[hash].add(string)
def remove(self, string: str) -> None:
hash = self.get_hash(string)
lst = self.array[hash]
lst.remove(string)
def get_hash(self, string: str) -> int:
return sum((ord(char) * 263 ** idx) for idx, char in enumerate(string)) % 1_000_000_007 % self.size
def get_by_index(self, index: str) -> str:
index = int(index)
lst = self.array[index]
if lst:
return ' '.join(lst.get_values())
return ''
def search(self, string: str) -> str:
hash = self.get_hash(string)
lst = self.array[hash]
try:
lst.find(string)
return 'yes'
except NotFound:
return 'no'
def get_method(operation, hash_table, argument):
method_map = {
'add': partial(hash_table.add, string=argument),
'del': partial(hash_table.remove, string=argument),
'find': partial(hash_table.search, string=argument),
'check': partial(hash_table.get_by_index, index=argument)
}
return method_map[operation]
def main(str_buffer):
hashmap_size = int(next(str_buffer))
operations_count = int(next(str_buffer))
hashtable = HashTable(hashmap_size)
out = []
for i in range(operations_count):
operation, argument = next(str_buffer).split()
func = get_method(operation, hashtable, argument)
if operation in ('find', 'check'):
out.append(func())
else:
func()
return out
tst1 = io.StringIO('''5
12
add world
add HellO
check 4
find World
find world
del world
check 4
del HellO
add luck
add GooD
check 2
del good''')
tst2 = io.StringIO('''4
8
add test
add test
find test
del test
find test
find Test
add Test
find Test''')
tst3 = io.StringIO('''3
12
check 0
find help
add help
add del
add add
find add
find del
del del
find del
check 0
check 1
check 2''')
if __name__ == '__main__':
assert main(tst1) == ['HellO world', 'no', 'yes', 'HellO', 'GooD luck']
assert main(tst2) == ['yes', 'no', 'no', 'yes']
assert main(tst3) == ['', 'no', 'yes', 'yes', 'no', '', 'add help', '']
|
a4e06672b939e6fe8c2769c5fcc1e8670f774b1e | confar/algorithms_stepik | /course_1_algorithms/dynamic/editing_distance.py | 1,255 | 3.5 | 4 | import math
def diff(char1, char2):
return 1 if char1 != char2 else 0
def _edit_distance(distance, i, j, str1, str2):
if distance[i][j] == math.inf:
if i == 0:
distance[i][j] = j
elif j == 0:
distance[i][j] = i
else:
insert = _edit_distance(distance, i, j - 1, str1, str2) + 1
delete = _edit_distance(distance, i - 1, j, str1, str2) + 1
substitute = _edit_distance(distance, i - 1, j - 1, str1, str2) + diff(str1[i-1], str2[j-1])
distance[i][j] = min(insert, delete, substitute)
return distance[i][j]
def edit_distance(str1, str2):
rows = len(str1) + 1
cols = len(str2) + 1
distance = [[math.inf for _ in range(cols)] for _ in range(rows)]
for i in range(1, rows):
for k in range(1, cols):
distance[i][0] = i
distance[0][k] = k
for i in range(rows):
for j in range(cols):
_edit_distance(distance, i, j, str1, str2)
result = distance[len(str1)][len(str2)]
print(result)
return result
if __name__ == '__main__':
assert edit_distance('ab', 'ab') == 0
assert edit_distance('short', 'ports') == 3
assert edit_distance('editing', 'distance') == 5
|
2e9b857a824c9da9b12923a39882047606052698 | cristhianfdx/console-crud-python | /console-crud.py | 10,958 | 3.515625 | 4 | # -*- coding=utf-8 -*-
'''
@author: Cristhian Alexander Forero
'''
import sqlite3
import os
import re
db_name = 'students.db'
def print_menu():
print('''
OPERACIONES BÁSICAS CON SQLITE
1. Crear Base de Datos.
2. Crear tabla.
3. Insertar datos en la tabla.
4. Consultar todos los registros de la tabla.
5. Eliminar tabla.
6. Actualizar registro de la tabla.
7. Buscar un registro.
8. Eliminar un registro.
9. Restaurar tabla eliminada.
10. Salir.
''')
def create_database():
if is_database_exists():
print('{} ya existe! :/'.format(db_name))
else:
connection = sqlite3.connect(db_name)
connection.close()
print('{} se creó correctamente •ᴗ•'.format(db_name))
def create_table():
query = '''
CREATE TABLE estudiante (
doc INT UNIQUE,
nombre VARCHAR(40),
fecha DATE,
genero VARCHAR(1)
)
'''
if are_valid_rules(create_table=True):
execute_query(query)
print('''La tabla ha sido creada •ᴗ• con la siguiente estructura:
{}'''.format(query))
def insert_data_table():
save_table_data()
def get_all_data():
if not are_valid_rules(): return
query = 'SELECT * FROM estudiante'
result = execute_query(query).fetchall()
if result:
print('\nRegistros:')
print('--------------------------------------')
for row in result:
print(row)
print('--------------------------------------')
else:
print('La tabla no tiene registros :(')
def drop_table():
if not are_valid_rules(): return
question = get_input_question('eliminar la tabla')
if is_run_again(question):
print('La tabla no fue eliminada :)')
return
save_table_backup()
result = execute_query(query='DROP TABLE estudiante')
if result is not None:
print('La tabla ha sido eliminada :(')
print('Se ha guardado una copia de la tabla estudiante :)')
def update_one():
save_table_data(is_editable=True)
def find_one():
while True:
if not are_valid_rules(): break
option = get_find_option()
if option == '1':
document_number = int(input('\nIngrese el número de documento: '))
result = get_by_field_and_parameter('doc', parameter=document_number)
if result: print('Resultado: {}'.format(result))
elif option == '2':
name = get_insert_name()
result = get_by_field_and_parameter('nombre', parameter=name)
if result: print('Resultado: {}'.format(result))
elif option == '3':
date = get_valid_date()
result = get_by_field_and_parameter('fecha', parameter=date)
if result: print('Resultado: {}'.format(result))
elif option == '4': return
else: print('Opción incorrecta.')
question = get_input_question('buscar otro registro')
if is_run_again(question): break
def delete_one():
if not are_valid_rules(): return
print('Buscar usuario por número de documento.\n')
document_number = int(input('\nIngrese el número de documento: '))
student = get_by_field_and_parameter(field='doc', parameter=document_number)
if student is None: return
print('Usuario encontrado:\n', student, '\n')
question = get_input_question('eliminar el registro')
if not is_run_again(question):
execute_query(query='DELETE FROM estudiante WHERE doc=?', parameters=(student[0],))
print('Se ha eliminado el registro :(')
else:
print('No se ha eliminado el registro :)')
def restore_table():
question = get_input_question('generar el backup')
if is_run_again(question):
print('No se ha restaurado la tabla :( \n')
return
if is_table_exists(is_main=False):
execute_query(query='DROP TABLE IF EXISTS estudiante')
execute_query(query='CREATE TABLE estudiante AS SELECT * FROM backup')
print('Se ha restaurado la tabla estudiante :) \n')
execute_query('DROP TABLE IF EXISTS backup')
print('La tabla de respaldo ha sido eliminada :/ \n')
else:
print('No existe copia de respaldo :( \n')
def save_table_data(is_editable=False):
while True:
data = None
query = ''
if not are_valid_rules(): break
if is_editable:
data = get_valid_save_data(is_editable=True)
query = '''
UPDATE estudiante
SET doc=?, nombre=?, fecha=?, genero=?
WHERE doc=?
'''
else:
data = get_valid_save_data()
query = 'INSERT INTO estudiante VALUES (?,?,?,?)'
if data is None: break
result = execute_query(query=query, parameters=data)
if result is not None: print('\nRegistro guardado correctamente •ᴗ•')
action = 'guardar' if not is_editable else 'actualizar'
question = get_input_question('{} más registros'.format(action))
if is_run_again(question): break
def save_table_backup():
execute_query('DROP TABLE IF EXISTS backup')
execute_query('CREATE TABLE backup AS SELECT * FROM estudiante')
def get_selected_option(option):
options = {
'1' : 'create_database',
'2' : 'create_table',
'3' : 'insert_data_table',
'4' : 'get_all_data',
'5' : 'drop_table',
'6' : 'update_one',
'7' : 'find_one',
'8' : 'delete_one',
'9' : 'restore_table'
}
return options.get(option)
def get_valid_save_data(is_editable=False):
student = None
data = ()
if is_editable:
print('Se encuentra en el modo de edición de datos.\n')
print('Buscar usuario por número de documento.\n')
document_number = int(input('Ingrese el número de documento: '))
student = get_by_field_and_parameter(field='doc', parameter=document_number)
if student is None: return
print('Usuario encontrado:\n', student, '\n')
question = get_input_question('actualizar el nombre')
name = get_insert_name() if not is_run_again(question) else student[1]
question = get_input_question('actualizar la fecha')
date = get_valid_date() if not is_run_again(question) else student[2]
question = get_input_question('actualizar el género')
gender = get_valid_gender() if not is_run_again(question) else student[3]
data = (document_number, name, date, gender,) + (document_number,)
else:
print('Por favor ingrese los datos.\n')
document_number = get_valid_document_number()
name = get_insert_name()
date = get_valid_date()
gender = get_valid_gender()
data = (document_number, name, date, gender,)
return data
def function_execute():
while True:
option = input('Ingrese la opción deseada: ')
func_name = get_selected_option(option)
if func_name is not None:
globals()[func_name]()
else:
if option == '10':
print('(ʘ‿ʘ)╯ Bye....')
break
print('Opción incorrecta.')
input_value = get_input_question('ejecutar otra operación')
if is_run_again(input_value):
print('Bye....')
break
print_menu()
def execute_query(query, parameters=()):
with sqlite3.connect(db_name) as connection:
cursor = connection.cursor()
result = cursor.execute(query, parameters)
connection.commit()
return result
def are_valid_rules(create_table=False):
is_valid = True
if not is_database_exists():
print('La base de datos no existe :(')
return
if not is_table_exists() and not create_table:
print('La tabla estudiante no existe : (')
return
if create_table and is_table_exists():
print('La tabla estudiante ya existe : (')
return
return is_valid
def is_database_exists():
return os.path.isfile(db_name)
def is_table_exists(is_main=True):
if not is_database_exists():
print('La base de datos no existe :(')
return
table_name = 'estudiante' if is_main else 'backup'
return execute_query('''SELECT count(name) FROM sqlite_master WHERE type='table' AND name=?''',
parameters=(table_name,)).fetchone()[0] == 1
def get_valid_document_number():
input_document_number_message = 'Ingrese el número de documento: '
document_number = int(input(input_document_number_message))
query = 'SELECT * FROM estudiante WHERE doc=?'.format(document_number)
student = execute_query(query, (document_number,)).fetchone()
while student is not None:
print('Ya existe un usuario con ese número de documento.')
document_number = int(input(input_document_number_message))
student = get_by_field_and_parameter(field='doc', parameter=document_number)
return document_number
def get_by_field_and_parameter(field, parameter):
if are_valid_rules():
query = ''
result = None
if field == 'nombre':
query = "SELECT * FROM estudiante WHERE {} LIKE ?".format(field)
result = execute_query(query, ('%'+parameter+'%',))
else:
query = 'SELECT * FROM estudiante WHERE {} =?'.format(field)
result = execute_query(query, (parameter,))
data = result.fetchone()
if data is None:
print('No se encuentra el usuario por el parámetro {} :('.format(parameter))
else:
return data
def get_input_question(message):
return input('\n¿Desea {}? s/n: '.format(message))
def is_run_again(option=''):
return option.lower() != 's'
def get_insert_name():
return input('Ingrese el nombre: ').upper()
def get_valid_date():
input_date_message = 'Ingrese la fecha (DD/MM/AAAA): '
date_regex = r'^\d{1,2}\/\d{1,2}\/\d{4}$'
date = input(input_date_message)
while not re.match(date_regex, date):
print('Formato de fecha inválido.')
date = input(input_date_message)
return date
def get_valid_gender():
input_gender_message = 'Ingrese género (m/f/otro): '
gender = input(input_gender_message)
while is_valid_gender(gender):
print('Formato de género inválido.')
gender = input(input_gender_message)
return gender.upper()
def is_valid_gender(gender):
return not gender == 'm' and not gender == 'f' and not gender == 'otro'
def get_find_option():
return input('''
BÚSQUEDA DE REGISTROS
1. Buscar por número de documento.
2. Buscar por nombre
3. Buscar por fecha.
4. Cancelar
Ingrese la opción deseada: ''')
def run():
print_menu()
function_execute()
if __name__ == '__main__':
run()
|
64ab234863beaabbd6ca3b5ae30c84256c109736 | pmjonesg/FaceTracker | /Algorithms/webcam.py | 1,150 | 3.734375 | 4 | # This script performs face recognition and draws a green box around a detected face.
import cv2
import sys
# The argument this script takes is a haarcascade.xml file which contains face parameters to be recognized.
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
# Start the capture
video_capture = cv2.VideoCapture(0)
count = 10
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
if not ret: continue
# Analyze 1 out of 40 frames
if(count % 40 == 0):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(10, 10),
#flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
count += 1
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
|
652e5bd306bdaceec9f79d87234d5e74a08fa232 | Fir-lat/Fir-lat.github.io | /caidingke.py | 2,018 | 3.953125 | 4 | #猜丁壳
#导入库
from random import randint
#游戏介绍
def introduce():
print("这是一个石头剪刀布的游戏")
print("请点击开始进行游戏")
print("每赢一局分数加一,采取五局三胜制")
#获取输入
def got():
f = True
print("请输入“石头”或“剪刀”或“布”")
while f:
x = 0
n = str(input())
if n in ["石头"]:
x = 1
f = False
elif n in ["剪刀"]:
x = 2
f = False
elif n in ["布"]:
x = 3
f = False
else:
print("您的输入不符合规范")
print("请再输一遍")
f = True
return x
#产生随机手势
def create():
y = randint(1,3)
if y == 1:
print("石头")
elif y == 2:
print("剪刀")
else:
print("布")
return y
#比较大小
def compare(x,y,a,b):
if x == y:
print("你们打平了".center(9,"-"))
elif x == 1 and y == 3:
print("你输了".center(10,"-"))
elif x < y :
print("你赢了".center(10,"-"))
a += 1
elif x == 3 and y == 1:
print("你赢了".center(10,"-"))
a += 1
else:
b += 1
print("你输了".center(10,"-"))
return a,b
#主函数
def main():
a,b =0,0
introduce()
for i in range(5):
x = got()
y = create()
a ,b = compare(x,y,a,b)
if a == 3 or b == 3:
break
print("你的最终得分为:{}\n电脑的最终得分为:{}".format(a,b))
if a > b:
print("你获得了最终的胜利")
elif a < b:
print("你输掉了这场游戏")
else:
print("你们最终打平了")
print("游戏结束".center(10,"#"))
#递归
def again():
main()
t = 1
print("你想要再玩一遍吗?")
j = str(input())
if j in ["不想"]:
t = 0
else:
t = 1
if t == 1:
again()
else:
return
again() |
8d9d4c73894c0a436707cfc316938de3c8805f78 | Fir-lat/Fir-lat.github.io | /chengji.py | 154 | 3.703125 | 4 | print('小明上学期成绩:')
a = int(input())
print('小明这学期成绩:')
b = int(input())
c = (a/b+1.0)*10
print('成绩提升百分点=%.1f%%'%c) |
db8073a8a852d31b0f7536dd9061b36416b689f2 | BursacPetar/GIS_programiranje_Domaci_zadatak | /GIS_programiranje_Vezba_br_2/GISP_Vezba_br_2_Zadatak_br_1_PetarBursac1540-16.py | 370 | 3.703125 | 4 | # Kodiranje skripta
# -*- coding: utf-8 -*-
# Zadatak br. 1
# niz = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# napisati program koji racuna sumu parnih elemenata niza
niz = input("Unesite niz u obliku: [x,x1,x2,...]")
suma_parnih = 0
for i in niz:
if i % 2 == 0:
suma_parnih = suma_parnih + i
print "Suma parnih elemenata niza je jednaka: ", suma_parnih
|
2fb46cfcde3579f8c17dad8ece07131a06ae8391 | Rekahani/tugas-praktikum5-6 | /lab2.py | 486 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 4 19:09:11 2020
@author: LENOVO i5
"""
a = eval (input("masukan nilai a: "))
b = eval (input("masukan nilai b: "))
hasil = a+b
print ("variable a = ",a)
print ("variable b = ",b)
print ("hasil penggabungan %d & %d = %d" % (a, b, hasil))
#konversi nilai variable
print ("KONVERSI NILAI VARIABLE")
a = int(a)
b = int(b)
print("hasil penjumlahan {1}+{0}=%d".format(a,b) % (a+b))
print("hasil penjumlahan {1}/{0}=%d".format(a,b) % (a/b))
|
d080eeac24b1847b2d0725a3175dce9ce2329680 | MaxHills/demo-git-conflict | /uobioinfo/main.py | 728 | 3.515625 | 4 | import argparse
def say_something(phrase): # ... I'm giving up on you.
"""Change this however you'd like!"""
print("testphrase1")
print(phrase)
print("testphrase2")
# --- Don't change anything below this line -------
def cli():
"""Command line interface"""
parser = argparse.ArgumentParser(
description="Demo for bioinformatics and genomics program at UO.")
parser.add_argument('phrase', help="What should I say?")
args = parser.parse_args()
main(args.phrase)
def main(phrase):
"""Main function to execute"""
print("\nHello, Bioinformatics and genomics program at UO:")
say_something(phrase)
print("\n")
if __name__ == "__main__":
main("Hello, World!")
|
11c90dbbfebfaaf74e1296a9378a1c40083e2f08 | orbital23/tensorflow-example | /playground-1/data_generator.py | 406 | 3.75 | 4 | import random
import math
def generate(numPoints):
result = []
for i in range(0, numPoints):
x = random.uniform(-6,6)
y = random.uniform(-6,6)
color = 1 if distance((0,0), (x,y)) < 3 else 0
result.append((x,y,color))
return result
def distance(pointFrom, pointTo):
diff = (pointTo[0] - pointFrom[0], pointTo[1] - pointFrom[1])
return math.sqrt(diff[0]*diff[0]+diff[1]*diff[1])
|
5e2c3645f39f57c882205c19014fe1142e836716 | Orenjonas/school_projects | /python/python_scripts/test_complex.py | 1,887 | 3.890625 | 4 | import math as m
from complex import *
def test_add():
"""
Test addition for Complex with Complex, complex, int and float
"""
z = Complex(1, -2)
w = Complex(1, 1)
assert (z + w) == Complex(2, -1)
assert (z + (1+1j)) == Complex(2, -1)
assert (z + 2) == Complex(3, -2)
assert (z + 2.0) == Complex(3, -2)
def test_sub():
"""
Test subtraction for Complex with Complex, complex, int and float
"""
z = Complex(1, -2)
w = Complex(1, 1)
assert (z - w) == Complex(0, -3)
assert (z - (1+1j)) == Complex(0, -3)
assert (z - 2) == Complex(-1, -2)
assert (z - 2.0) == Complex(-1, -2)
def test_conjugate():
z = Complex(1, -2)
assert z.conjugate() == Complex(1, 2)
def test_modulus():
a = 1
b = -2
z = Complex(a, b)
assert z.modulus() == m.sqrt(a + b**2)
def test_string():
z = Complex(1, -2)
assert str(z) == "(1-2i)"
def test_mul():
"""
(1-2i)*(2+2i) = 2 + 2i - 4i + 4
= 6 - 2i
"""
z = Complex(1, -2)
v = Complex(2, 2)
assert z*v == Complex(6, -2)
assert v*z == z*v
assert z*2 == Complex(2, -4)
assert z*2.0 == Complex(2, -4)
assert z*(2+2j) == v*z
def test_radd():
z = Complex(1, -2)
w = Complex(1, 1)
assert ((1+1j) + z) == Complex(2, -1)
assert (2 + z) == Complex(3, -2)
assert (2.0 + z) == Complex(3, -2)
def test_rsub():
z = Complex(1, -2)
w = Complex(1, 1)
assert ((1+1j) - z) == Complex(0, 3)
assert (2 - z) == Complex(1, 2)
assert (2.0 - z) == Complex(1, 2)
def test_rmul():
z = Complex(1, -2)
v = Complex(2, 2)
assert 2*z == Complex(2, -4)
assert 2.0*z == Complex(2, -4)
assert (2+2j)*z == z*v
def test_eq():
z = Complex(1, -2)
w = Complex(0, 1)
assert ( z == z and not z == w )
|
cd45d4f6b4705211c862908dfdc2256cf5380237 | smkell/adventofcode | /2016/day3/day3py/day3.py | 1,455 | 3.953125 | 4 | """Python Solution of Day 3 of the `Advent of Code <http://adventofcode.com/2016/day/3>`
"""
import sys
def valid_triangle(sides):
"""Return true if the given sides specify a valid triangle."""
return ((sides[0] + sides[1] > sides[2]) and
(sides[1] + sides[2] > sides[0]) and
(sides[0] + sides[2] > sides[1]))
def part1(lines):
"""Process the lines using the requirements of Part 1"""
print 'Part 1'
print '------'
accum = 0
for line in lines:
sides = [int(x) for x in line.split()]
if valid_triangle(sides):
accum = accum + 1
print 'Number of valid triangles: {0}'.format(accum)
print ''
def part2(lines):
"""Process the lines using the requirements of Part 2"""
print 'Part 2'
print '------'
accum = 0
cols = [[], [], []]
for line in lines:
sides = [int(x) for x in line.split()]
for i, side in enumerate(sides):
cols[i].append(side)
accum = 0
for col in cols:
for page in range(0, len(col) / 3):
start = page * 3
end = start + 3
triangle = col[start:end]
if valid_triangle(triangle):
accum = accum + 1
print 'Number of valid triangles: {0}'.format(accum)
print ''
def main():
"""Main entry point."""
lines = sys.stdin.readlines()
part1(lines)
part2(lines)
if __name__ == '__main__':
main()
|
8c90dd545d83437d8dc4be1a985779827851b7d2 | ydPro-G/Flask | /4_request,session,cookie,response/requrst_2.py | 889 | 3.578125 | 4 |
# 一个完整的HTTP请求,包含客户端的Request,服务端的Response,会话Session等
# 在Flask中使用这些内建对象:request,session,cookie
# 请求对象Request
from flask import request
from flask import Flask
app = Flask(__name__)
@ app.route('/login',methods=['POST','GET'])
def login():
if request.method == 'POST': # request中的method变量可以获取当前请求的方法
if request.form['user'] == 'admin': # from变量是一个字典,可以获取Post请求表单中的内容
return 'Admin login successfully!'
else:
return 'No such user!'
title = request.args.get('title','Default') # 获取get请求url中的参数,该函数的第二个参数是默认值,当url不存在时,则返回默认值
return render_template('login.html',title=title)
if __name__ == '__main__':
app.run()
|
510bb83032b4a31bb0e78773f72ba4f18a86f6b2 | NIshant-Hegde/Data-Science | /Spam_classifier_using _naive_bayes/Spam_classifier_using_Naive_Bayes.py | 3,469 | 3.875 | 4 | #Importing libraries
import os #To navigate between directories and files
import io #For file manipulation and management
from pandas import DataFrame #To create dataframes to visualize data
import pandas as pd #For data visualisations
from sklearn .feature_extraction.text import CountVectorizer #To count words in a given file
from sklearn.naive_bayes import MultinomialNB #To implement Naive_Bayes_Classifier
from sklearn.metrics import accuracy_score, precision_score, f1_score
#Reading data and creating a dataframe
data = pd.read_csv(path/emails.csv)
data = DataFrame(data) #Creating a dataframe
data.head() #Printing the first five rows of the dataframe
print(data.shape) #Printing the shape of the dataframe
#Preprocessing
data.drop_duplicates(inplace = True) #Deleting duplicates from the dataframe
print(data.shape) #Checking if the duplicates have been removed by printing out the shape
data['text'] = data['text'].map(lambda text: text[8:]) #Since every text message starts with 'SUBJECT', deleting that word
#in every text row
print(data['text']) # Checking the new dataframe/text column
from sklearn.model_selection import train_test_split #Splitting the dataset into train and test
X_train, X_test, Y_train, Y_test = train_test_split(data['text'], data['spam'], test_size = 0.2, random_state = 10)
#Building the model
vectorizer = CountVectorizer() #Using the CountVectorizer() to count the frequency of every word
counts = vectorizer.fit_transform(X_train) #Counting the frequency and storing them in a list called counts
targets = Y_train #Creating targets for the classifier
classifier = MultinomialNB() #Creating the classifier model
classifier.fit(counts, targets) #Training the classifier
def test_func(predictions): #A function to predict the emails
pred_class = []
for preds in predictions:
if preds == 1:
pred_class.append("spam")
else:
pred_class.append("ham")
return pred_class #returns a email consisting of predictions
#Testing
examples = ["congralutions! you've won a $100000", "Dear Sir, Will you be free tomorrow? This is to ask you regarding a meeting."]
example_counts = vectorizer.transform(examples)
predictions = classifier.predict(example_counts)
print(test_func(predictions))
#Model evaluation
X_test_counts = vectorizer.transform(X_test)
X_test_counts.shape
preds = classifier.predict(X_test_counts)
acc = accuracy_score(Y_test, preds)
precision = precision_score(Y_test, preds)
f1 = f1_score(Y_test, preds)
acc = acc * 100
precision = precision * 100
print("Mean accuracy: {} \nPrecision: {} \nF1_score: {}".format(acc, precision, f1))
|
a51e999f87254fb12a0dbb2b84184fa6de6260a9 | MrComputingHound/pylot_python_belt_exam | /app/models/User.py | 3,683 | 3.546875 | 4 | """
Sample Model File
A Model should be in charge of communicating with the Database.
Define specific model method that query the database for information.
Then call upon these model method in your controller.
Create a model using this template.
"""
from system.core.model import Model
import re
class User(Model):
def __init__(self):
super(User, self).__init__()
def create_user(self, info):
EMAIL_REGEX = re.compile(r'^[a-za-z0-9\.\+_-]+@[a-za-z0-9\._-]+\.[a-za-z]*$')
errors = []
if not info['name']:
errors.append('Name cannot be blank')
elif len(info['name']) < 2:
errors.append('Name must be at least 2 characters long')
elif not info['name'].isalpha():
errors.append("Name must be letters only.")
if not info['alias']:
errors.append('Alias cannot be blank')
elif len(info['alias']) < 2:
errors.append('Alias must be at least 2 characters long')
elif not info['alias'].isalpha():
errors.append("Alias must be letters only.")
if not info['email']:
errors.append('Email cannot be blank')
elif not EMAIL_REGEX.match(info['email']):
errors.append('Email format must be valid!')
if not info['password']:
errors.append('Password cannot be blank')
elif len(info['password']) < 8:
errors.append('Password must be at least 8 characters long')
elif info['password'] != info['p_con']:
errors.append('Password and confirmation must match!')
if errors:
return {"status": False, "errors": errors}
else:
password = info['password']
hashed_pw = self.bcrypt.generate_password_hash(password)
query = "INSERT INTO users (name, alias, email, pw_hash, birthdate) VALUES (:name, :alias, :email, :pw_hash, :birthdate)"
data = {'name': info['name'], 'alias': info['alias'], 'email': info['email'], 'pw_hash': hashed_pw, 'birthdate': info['birthdate']}
self.db.query_db(query, data)
return {"status": True}
def login_user(self, info):
password = info['password']
user_query = "SELECT * FROM users WHERE email = :email LIMIT 1"
user_data = {'email': info['email']}
user = self.db.query_db(user_query, user_data)
if user:
if self.bcrypt.check_password_hash(user[0]['pw_hash'], password):
return True
return False
def get_alias(self, info):
user_query = "SELECT alias FROM users WHERE email = :email LIMIT 1"
user_data = {'email': info['email']}
return self.db.query_db(user_query, user_data)
"""
Below is an example of a model method that queries the database for all users in a fictitious application
Every model has access to the "self.db.query_db" method which allows you to interact with the database
def get_users(self):
query = "SELECT * from users"
return self.db.query_db(query)
def get_user(self):
query = "SELECT * from users where id = :id"
data = {'id': 1}
return self.db.get_one(query, data)
def add_message(self):
sql = "INSERT into messages (message, created_at, users_id) values(:message, NOW(), :users_id)"
data = {'message': 'awesome bro', 'users_id': 1}
self.db.query_db(sql, data)
return True
def grab_messages(self):
query = "SELECT * from messages where users_id = :user_id"
data = {'user_id':1}
return self.db.query_db(query, data)
""" |
f8b8f879cccda263a09997fb5132ab52fa827e4a | liuduanyang/Python | /廖大python教程笔记/jichu.py | 1,733 | 4.3125 | 4 | # python编程基础
a = 100
if a >= 0:
print(a)
else:
print(-a)
# 当语句以冒号:结尾时,缩进的语句视为代码块(相当于{}内的语句)
# Python程序是大小写敏感的
# 数据类型和变量
'''
数据类型:整数
浮点数
字符串('' 或 ""括起来的文本)
"I'm OK"包含的字符是I,',m,空格,O,K这6个字符
'I\'m \"OK\"!' 表示的字符串内容是:I'm "OK"!
布尔值(在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过布尔运算计算出来)
>>> True
True
>>> False
False
>>> 3 > 2
True
>>> 3 > 5
False
>>> True and True
True
>>> True and False
False
>>> False and False
False
>>> 5 > 3 and 3 > 1
True
>>> not True
False
>>> not False
True
>>> not 1 > 2
True
or 的就不写了
空值 空值是Python里一个特殊的值,用None表示
'''
# 转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
# Python还允许用r''表示''内部的字符串默认不转义 >>> print(r'\\\t\\') 输出:\\\t\\
'''
>>> print('''line1
... line2
... line3''')
line1
line2
line3
'''
# 变量
#同一个变量可以反复赋值,而且可以是不同类型的变量
# 常量
# 常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:PI = 3.14159265359
# 其实常量也是变量,可以改变值
# 除法
# 用/得到的值是浮点数
# 用//得到的值是整数(只取结果的整数部分)
# 取余
10 % 3
#得 1
|
1d6cafab3bfee249b8ab0ab04ab0cd94e5b5d506 | liuduanyang/Python | /廖大python教程笔记/fanhuihanshu.py | 3,364 | 3.703125 | 4 | # 返回函数
# 把函数作为结果值返回
# 返回一个求和函数
def lazy_sum(*args):
def sum():
ax=0
for i in args:
ax=ax+i
return ax
return sum
f=lazy_sum(1,3,5,7,9)
print(f())
# 25
# 解析:当我们调用lazy_sum(1,3,5,7,9)时 返回的sum sum指向具体的函数 赋值给f的也就是sum
# 当我们调用f 即f() 时也就是调用sum得到25 也就是说返回一个函数 并不立即执行这个
# 函数,只有调用时才执行
'''
f是函数(指向函数变量)
>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function lazy_sum.<locals>.sum at 0x101c6ed90>
'''
'''
在这个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部
函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回
的函数中,这种称为“闭包(Closure)”的程序结构拥有极大的威力
'''
# 当我们调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数,两个或多个函数也不相同
'''
>>> f1 = lazy_sum(1, 3, 5, 7, 9)
>>> f2 = lazy_sum(1, 3, 5, 7, 9)
>>> f1==f2
False
'''
# 闭包
'''
在上个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部
函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回
的函数中,这种称为“闭包(Closure)”
'''
# 当一个函数返回了一个函数后,其内部的局部变量还被新函数引用
# 返回的函数并没有立刻执行,而是直到调用才执行
# 闭包例子
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1()) # 9
print(f2()) # 9
print(f3()) # 9
'''
count()被调用后 执行的过程:先将[]赋值给fs 然后进入for循环,然后在fs列表的末尾插入函数f
这里的f相当于返回值 即return f 这里出现一个闭包 照此步骤 重复循环三次 返回fs列表
此时的fs列表为[f,f,f] 因为返回的是函数f 并非函数调用f()
将count函数的返回值赋值给f1 f2 f3 即 f1=f f2=f f3=f 但fn与f fn与fm之间都不相等
在执行f1() f2() f3()时 由于他们共享父函数 count的变量和参数 所以f函数内的i为3
所以f1() f2() f3()的执行的结果都是9
'''
# 返回闭包时牢记的一点就是:返回函数不要引用任何循环变量,或者后续会发生变化的变量
# 否则就会和上例一样, 与预期结果不同
# 对上例改进 得到1,4,9
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i))
return fs
f1, f2, f3 = count()
print(f1()) # 1
print(f2()) # 4
print(f3()) # 9
'''
与上例不同 多了函数f 本例中有两个闭包 一个是count函数内 f是闭包 另一个是 f函数内函数g
是闭包 当执行三次循环是 f内的参数分别为1,2,3 由于g是f的闭包 所以g的变量与f的值相同
所以g内的变量j分别为1,2,3 所以结果分别为1,4,9
'''
# 一个函数可以返回一个计算结果,也可以返回一个函数。
# 返回一个函数时,牢记该函数并未执行,返回函数中不要引用任何可能会变化的变量 |
ff6f55f92091a43f543d07553876fde61b780da8 | liuduanyang/Python | /廖大python教程笔记/diedai.py | 1,360 | 4.3125 | 4 | # 迭代 (Iteration)
# 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代
# Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上 比如dict、字符串、
# 或者一些我们自定义的数据类型
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
# b
# a
# c
# 因为字典存储是无序的 所以每次得到的顺序可能会不同
# for key in d 迭代key-value的key
# for value in d.values() 迭代value
# for k, v in d.items() 迭代key-value
for value in d.values():
print(value)
for k, v in d.items():
print(k)
print(v)
# 对字符串进行迭代
for num in 'Liuduanyang':
print(num)
# 通过collections模块的Iterable类型判断一个对象是否是可迭代对象
from collections import Iterable
print(isinstance('abc', Iterable))
# True
print(isinstance([1,2,3], Iterable))
# True
print(isinstance(123, Iterable))
# False
# 可通过某个个例来判断该数据类型是否是可迭代对象
# 如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一
# 个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身
for i, value in enumerate(['A', 'B', 'C']):
print(i, value)
# 0 A
# 1 B
# 2 C |
57cf0f1364b7d4d2c0c3f3b8a8c869be4f7a261a | liuduanyang/Python | /廖大python教程笔记/dict.py | 2,204 | 4.28125 | 4 | # 字典
# Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)
# 存储,具有极快的查找速度。这种查找速度都非常快,不会随着字典大小的增加而变慢
d={'Michael':95,'Bob':75,'Tracy':85}
print(d['Michael'])
# 95
# 除了上述初始化方法外,还可以通过key来放入数据
d['Adam']=67
print(d['Adam'])
print(d)
# 67
# {'Adam': 67, 'Michael': 95, 'Bob': 75, 'Tracy': 85}
# 一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉
d['Adam']=67
d['Adam']=99
print(d['Adam'])
# 99
# 通过in判断key是否存在
print('Tracy' in d)
# True
# 通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
print(d.get('Bob'))
# 75
print(d.get('Mary'))
# None
# 返回None的时候Python的交互式命令行不显示结果
print(d.get('Mary',0))
# 0
# Mary不在时返回0 如果不指定0 则返回None且在交互命令行不显示
# 删除一个key,用pop(key)方法,对应的value也会从dict中删除
d.pop('Bob')
print(d)
#{'Michael': 95, 'Tracy': 85, 'Adam': 99}
# dict内部存放的顺序和key放入的顺序是没有关系的
'''
和list比较,dict有以下几个特点:
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。
所以,dict是用空间来换取时间的一种方法。
dict可以用在需要高速查找的很多地方,在Python代码中几乎无处不在,正确使用dict非常重要,需要牢记的
第一条就是dict的key必须是不可变对象。
这是因为dict根据key来计算value的存储位置,如果每次计算相同的key得出的结果不同,那dict内部就完全混
乱了。这个通过key计算位置的算法称为哈希算法(Hash)。
要保证hash的正确性,作为key的对象就不能变。在Python中,字符串、整数等都是不可变的,因此,可以放心
地作为key。而list是可变的,就不能作为key
''' |
7b8b186ef4337434ab97a55d9687452f909add16 | nbtvu/Data-Structure---Python-Implementation | /BinarySearchTrees/SplayTree.py | 4,908 | 3.796875 | 4 | from collections import deque
class Node(object):
def __init__(self, val):
self.val = val
self.parents = None
self.left = None
self.right = None
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self.val)
class SplayTree(object):
def __init__(self):
self.root = None
def find_val(self, val):
cur_node = self.root
while cur_node and cur_node.val != val:
if val > cur_node.val:
cur_node = cur_node.right
else:
cur_node = cur_node.left
return self._splay(cur_node)
def predecessor(self, val, subtree_root=None):
if subtree_root:
cur_node = subtree_root
else:
cur_node = self.root
res = None
while cur_node:
if cur_node.val < val:
res = cur_node
cur_node = cur_node.right
else:
cur_node = cur_node.left
return self._splay(res)
def successor(self, val, subtree_root=None):
if subtree_root:
cur_node = subtree_root
else:
cur_node = self.root
res = None
while cur_node:
if cur_node.val > val:
res = cur_node
cur_node = cur_node.left
else:
cur_node = cur_node.right
return self._splay(res)
def insert_val(self, val):
if not self.root:
self.root = Node(val)
return self.root
cur_node = self.root
while cur_node:
if cur_node.val == val:
break
if cur_node.val > val:
if cur_node.left:
cur_node = cur_node.left
else:
cur_node.left = Node(val)
cur_node.left.parents = cur_node
cur_node = cur_node.left
break
else:
if cur_node.right:
cur_node = cur_node.right
else:
cur_node.right = Node(val)
cur_node.right.parents = cur_node
cur_node = cur_node.right
break
return self._splay(cur_node)
def delete_val(self, val):
val_node = self.find_val(val)
if not val_node:
return None
if not self.root.left:
if not self.root.right:
# root has no children
self.root = None
else:
# root has only right child
self.root = self.root.right
self.root.parents = None
else:
if not self.root.right:
# root has only left child
self.root = self.root.left
self.root.parents = None
else:
# root has 2 children
right_child = self.root.right
self.root = self.root.left
self.root.parents = None
self.predecessor(right_child.parents.val)
self.root.right = right_child
right_child.parents = self.root
return val_node
def display(self):
if not self.root:
print "Empty Tree"
return
cur_level = 0
max_level = cur_level
queue = deque()
queue.append((self.root, cur_level))
cur_list = []
while queue:
node, level = queue.popleft()
if level != cur_level:
if level > max_level:
break
print cur_list
cur_list = []
cur_level = level
cur_list.append(node)
if node:
queue.append((node.left, level+1))
queue.append((node.right, level+1))
max_level = level+1
else:
queue.append((None, level+1))
queue.append((None, level+1))
def _splay(self, node):
if not node:
return None
pa = node.parents
while pa:
grandpa = pa.parents
if grandpa:
if pa == grandpa.right and node == pa.left:
# right - left
self._right_rotate(pa)
self._left_rotate(grandpa)
elif pa == grandpa.left and node == pa.right:
# left - right
self._left_rotate(pa)
self._right_rotate(grandpa)
elif pa == grandpa.left and node == pa.left:
# left - left
self._right_rotate(grandpa)
self._right_rotate(pa)
else:
# right - right
self._left_rotate(grandpa)
self._left_rotate(pa)
else:
if node == pa.left:
self._right_rotate(pa)
else:
self._left_rotate(pa)
pa = node.parents
self.root = node
return self.root
def _left_rotate(self, node):
tmp = node.right
node.right = tmp.left
if node.right:
node.right.parents = node
tmp.parents = node.parents
tmp.left = node
node.parents = tmp
if tmp.parents:
if tmp.parents.left == node:
tmp.parents.left = tmp
else:
tmp.parents.right = tmp
def _right_rotate(self, node):
tmp = node.left
node.left = tmp.right
if node.left:
node.left.parents = node
tmp.parents = node.parents
tmp.right = node
node.parents = tmp
if tmp.parents:
if tmp.parents.left == node:
tmp.parents.left = tmp
else:
tmp.parents.right = tmp
splay_tree = SplayTree()
a = [9, 1, 8, 23, 14, 17, 2, 4, 9, 98, 33, 24, 12, 31, 33, 4, 22]
for val in a:
splay_tree.insert_val(val)
splay_tree.display()
print splay_tree.find_val(9)
print splay_tree.find_val(32)
print splay_tree.find_val(22)
print splay_tree.delete_val(22)
print splay_tree.find_val(22)
print splay_tree.delete_val(17)
print splay_tree.delete_val(3)
print splay_tree.delete_val(4)
print splay_tree.find_val(33)
print splay_tree.delete_val(33)
print splay_tree.find_val(33)
print splay_tree.insert_val(33)
splay_tree.display()
print splay_tree.find_val(33)
|
b5bfd66f6760cb0cfd08db20638eeb4e2e1965cb | nbtvu/Data-Structure---Python-Implementation | /how_to_read_a_matrix_from_console.py | 374 | 3.796875 | 4 | #read matrix of size MxN
m, n = map(int, raw_input("Input the matrix size (row, column): ").split())
print "Input the matrix elements (row by row): "
a = [None] * m
for i in range(m):
a[i] = map(int, raw_input().split())
#print out the matrix
print "Print out the matrix:"
for i in range(m):
line = ""
for j in range(n):
line += str(a[i][j])
line += " "
print line
|
21b2c42a45579c3481867264ac4493c9e7f13e10 | tor1414/python_programs | /131_h1_validate_sudoku_solutions.py | 2,353 | 3.96875 | 4 | """
Victoria Lynn Hagan
Victoria014
1/30/2014
Homework 1 - CSC 131
Program that uses 2D lists to verify whether or not a Sudoku solution is valid
"""
def checkLst(lst):
"""returns True if lst (may represent row, column or a block) has the values 1 to 9"""
#replace pass by the necessary code
a = []
for value in lst:
if value not in a:
a.append(value)
else:
return False
def isValid(grid):
"""returns True if solution is valid and False otherwise"""
#verify that every row has the numbers from 1 to 9
#your code goes here
for row in range(len(grid)):
if checkLst(grid[row]) == False:
return False
#verify that every column has the numbers from 1 to 9
#your code goes here
for row in range(len(grid)):
lst = []
for column in range(len(grid[0])):
lst.append(grid[row][column])
if checkLst(lst) == False:
return False
#verify that every 3-by-3 box has the numbers from 1 to 9
#Boxes will be processed in a left to right, top to bottom order
startRow = 0 #row coordinate of starting cell in a 3-by-3 box
startColumn = 0 #column coordinate of starting cell in a 3-by-3 box
for boxNumber in range(0, 9):
currentBox = []
for row in range(startRow, startRow + 3):
for column in range(startColumn, startColumn + 3):
currentBox.append(grid[row][column])
#display(currentBox)
if checkLst(currentBox) == False:
return False
startColumn += 3 #time to move to the next box
if startColumn == 9: #time to move to the next row of boxes
startColumn = 0
startRow += 3
#if here, then solution must have passed all verification
return True
def main():
file_names_list = ["sudokuSample.txt"]
for file_name in file_names_list:
grid = [] #to store solution read from file
f = open(file_name)
for line in f:
line = line.split()
line = map(int, line) # convert strings to integres
grid.append(line)
if isValid(grid):
print "valid solution"
else:
print "invalid solution"
main()
|
900588802461bb57362293cb8118e4710704ee4c | IbroCalculus/Python-Tkinter-Codes-Snippets | /x/window_Size.py | 593 | 3.53125 | 4 | import tkinter as tk
root = tk.Tk()
root.title("This is my template")
root.config(bg='#123456')
root.resizable(width=True, height=True)
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#x+y offset
#root.geometry("400x200+800+200")
root.geometry("%dx%d+%d+%d" % (screen_width, screen_height, 200, 300))
label = tk.Label(root, text='This is a text', bg='red',
activebackground='blue', bd=10)
label.pack()
label2 = tk.Label(root, text="This is another text", activeforeground='yellow', relief='solid', bd=10)
label2.pack()
root.mainloop()
|
3a305255401e86963c00825ded481ca48ed93084 | sonyashkapa/Sonya-Shkapa | /gener.py | 7,012 | 4.21875 | 4 | """ This module contains methods and a function for tokenizing a string of characters
"""
import unicodedata
def making_array(str):
""" This function divides a string in a list of alphabetical substrings."""
i = 0
# set the array, in which each element will be the alphabetical chain
data = []
if str == '':
return []
# loop that goes through each character in a string
for i, c in enumerate(str):
# checking if the character is an alphabetical char
if str[i].isalpha():
# if the character is an alphabetical char
# then we check it's index and the previous element
if (i > 0) and (str[i-1].isalpha()):
continue
else:
# we remember the index of the first char in the alphabetical chain
nomer1 = i
else:
# if the character is not char, we check it's index and the previous character
if (i > 0) and (str[i-1].isalpha()):
# if it's the last char in the alphabetical chain
# then we add this chain to the array
data.append(str[nomer1:i])
# checking the last character in our string, whether it is letter or not
# if the last character was alphabetic
# then the cycle does not meet non-alphabetic one to save the last alphabetic chain
if str[i].isalpha():
data.append(str[nomer1:i+1])
return(data)
class Tokenizator(object):
""" This class uses the method to divide a string in a list of alphabetical substrings."""
def tokenize(self,str):
""" This method divides a string in the array of alphabetical substrings."""
i = 0
data = []
if str == '':
return []
# loop that goes through each character in a string
for i, c in enumerate(str):
# checking if the character is an alphabetical char
if str[i].isalpha():
# if the character is an alphabetical char
# then we check it's index and the previous element
if (i > 0) and (str[i-1].isalpha()):
continue
else:
# we remember the index of the first char in the alphabetical chain
nomer1 = i
else:
# if the character is not char, we check it's index and the previous character
if (i > 0) and (str[i-1].isalpha()):
# if it's the last char in the alphabetical chain
# then we add this chain to the array
data.append(str[nomer1:i])
# checking the last character in our string, whether it is letter or not
# if the last character was alphabetic
# then the cycle does not meet non-alphabetic one to save the last alphabetic chain
if str[i].isalpha():
data.append(str[nomer1:i+1])
return(data)
@staticmethod
def defcategory(char):
""" This method is used for determining 4 categories """
if char.isalpha():
category = 'alpha'
elif char.isdigit():
category = 'digit'
elif char.isspace():
category = 'space'
elif unicodedata.category(char)[0] == 'P':
category = 'punct'
else:
category = 'unknown'
return category
def tokenize_cat(self, str):
"""
This method adds token, its category,
index of first and last char of substring in initial string
"""
data2 = []
if len(str) == 0:
return []
else:
# loop that goes through each character in a string
for i, c in enumerate(str):
category = Tokenizator.defcategory(c)
if i == 0:
index = i
prevcat = category
# check if we didn't reach the last character of the string
else:
if (i+1) < len(str):
# we compare categories of current and next characters
# if they differ, so we have reached the last characters of the category
if category != prevcat:
token = str[index:i]
t = Token(token, prevcat, index, i)
data2.append(t)
index = i
prevcat = category
# check the last character in the string
token = str[index:]
i = i + 1
t = Token(token, category, index, i)
data2.append(t)
return data2
def gen_tokenize_cat(str):
"""
This method yiels tokens and category
"""
if len(str) == 0:
return
else:
# loop that goes through each character in a string
for i, c in enumerate(str):
category = Tokenizator.defcategory(c)
if i == 0:
index = i
prevcat = category
# check if we didn't reach the last character of the string
else:
if (i+1) < len(str):
# we compare categories of current and next characters
# if they differ, so we have reached the last characters of the category
if category != prevcat:
token = str[index:i]
t = Token(token, prevcat, index, i)
yield t
index = i
prevcat = category
# check the last character in the string
token = str[index:]
i = i + 1
t = Token(token, category, index, i)
yield t
def gen_gen(self,str):
""" This method is used for determining 2 categories """
for token in self.gen_tokenize_cat(str):
if token.category == 'alpha' or token.category == 'digit' :
yield token
class Token(object):
"""
Class representing information about the token
Token type,first and last indexes in original string
"""
def __init__(self, t, categ, frstind, lstind):
self.firstindex = frstind
self.lastindex = lstind
self.token = t
self.category = categ
def __repr__(self):
""" Method of building printable outcome """
return ' ' + self.token + ' is ' + self.category + ' located from ' + str(self.firstindex) + ' index to ' + str(self.lastindex) + ' index.' + '\n'
def main():
t = Tokenizator()
str = 'мама 2!'
print(t.tokenize_cat(str))
if __name__ == '__main__':
main()
|
36cacd0e4052782976eca85781b5fda9a4894256 | alexwaweru/graduate_algotithms | /dynamic_programming/change_maker.py | 986 | 3.828125 | 4 | """
@Author: Alex Waweru
"""
import timeit
def dynamic_programming_change_maker(coin_value_list, change, min_coins, coins_used):
for cents in range(change+1):
coin_count = cents
new_coin = 1
for j in [c for c in coin_value_list if c <= cents]:
if min_coins[cents-j] + 1 < coin_count:
coin_count = min_coins[cents-j]+1
new_coin = j
min_coins[cents] = coin_count
coins_used[cents] = new_coin
return min_coins[change]
# compute dynamic time
def dynamic_time():
SETUP_CODE = "from __main__ import dynamic_programming_change_maker"
TEST_CODE = "dynamic_programming_change_maker([1,5,10,21,25],63,[0]*64, [0]*64)"
# timeit.repeat statement
times = timeit.repeat(
setup = SETUP_CODE,
stmt=TEST_CODE,
repeat=3,
number=1
)
# printing minimum exec. time
print('dynamic time complexity: {}'.format(min(times)))
if __name__ == "__main__":
dynamic_time() |
b3862bd1d09ec45f919afbd45d1ef61b1abb6d41 | yyj7647261/gittest | /day02-2-zuoye.py | 630 | 3.5625 | 4 | # 递归函数列出所有文件 使用os.listdir 列出目录内容 os.isfile 检测是否是文件
# 练习找出单个目录中的最大文件
# 练习找出目录树中的最大文件
import os
file=os.listdir() #列出所有文件
# print (type(file))
# print ("当前目录所有文件:"+str(file)) #累出当前目录中的全部文件
# #os.path.getsize(name) 获取文件大小
maxV = -float('inf') #正无穷:float("inf"); 负无穷:float("-inf")
for a in file:
f=os.path.getsize(a)
#print ("文件"+a+"大小是"+str(f))
if f > maxV:
maxV =f
print("最大的文件大小是"+str(maxV)) |
eac14658b397d716e836dc38952b6fad36039e36 | azh4r/online-sorting-algorithms | /LargestValues/DataFile.py | 1,520 | 3.75 | 4 | # Class with functions to get handle to a file and
# to read in a file.
# Update: This should also take in number of lines to read
# and return also that file has ended.
class DataFile:
def get_handle(file_location):
in_file = open(file_location, "r")
return in_file
# method to convert a segment of txt file into dict
# returning the segment in dict and the position in the file
# and whether it reached the end of file or not.
def read_file(file_handle, lines_to_read, offset):
end_of_file = False
file_dict = {}
count = 0
file_handle.seek(offset)
while count < lines_to_read and not end_of_file:
line = file_handle.readline().strip()
if line == '':
end_of_file = True
break
(key, val) = line.split()
file_dict[key] = int(val)
count +=1
offset = file_handle.tell()
if end_of_file:
file_handle.close()
return (file_dict, offset, end_of_file)
# Function to take a dict object and write it to a text file.
# this should also take in a file suffix like 'out', 1, 2, to append to file name written
# update: changing this to take filename but append with txt.
def write_file(sorted_dict,file_name):
# print("write file")
with open('{}.txt'.format(str(file_name)), 'w') as f:
for key,value in sorted_dict.items():
f.write("%s %s\n" % (key,value))
|
76f4172c5d391106c5ac528a89aa84fc1f8cfab0 | dkaniu/Denis-Kaniu-Dojo-Project | /room.py | 1,850 | 3.640625 | 4 | """
Room Allocation System
Usage:
room.py create_room <room_name> <room_type>...
room.py add_person <person_name> <emp_type>...
room.py print_room <room_name>
room.py print_allocations [-o=filename]
room.py print_unallocated [-o=filename]
room.py reallocate_person <person_identifier> <new_room_name
room.py load_people
room.py save_state [--db=sqlite_database]
room.py load_state <sqlite_database>
Options:
-h --help Show help info.
"""
from docopt import docopt
from person import Person
class Room:
add_people = []
room_names = []
room_size = 0
def __init__(self):
pass
def create_room(self, room_type, room_name):
self.room_type = room_type
self.room_name = room_name
Room.room_names.append(room_name)
if room_type == 'office':
Room.room_size = 6
elif room_type == 'livingspace':
Room.room_size = 4
else:
Room.room_size = 0
print("{} {} has been successfully created!".format( self.room_type, room_name))
def add_person(self, person_name, emp_type):
self.person_name = person_name
self.emp_type = emp_type
self.person = Person(person_name, emp_type, choice='Y')
Room.add_people.append(self.person_name)
print("{} {} has been successfully added! ".format(person_name, emp_type))
class LivingSpace(Room):
def __init__(self):
#initializes the LivingSpace sub class
pass
class Office(Room):
def __init__(self):
#initializes the Office sub class
pass
if __name__ == '__main__':
arguments = docopt(__doc__, version='Denis-Kaniu-Dojo-Allocation v_0')
Room().create_room(arguments['<room_type>'], arguments['<room_name>'])
Room().add_person(arguments['<person_name>'], arguments['<emp_type>'])
|
d8fd909cb070443842cf901dd363efa7b0dda23d | prachichouksey/Array-1 | /238_Product_Except_Self.py | 2,634 | 3.75 | 4 | # Leetcode problem link : https://leetcode.com/problems/product-of-array-except-self
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
'''
Basic approach => Traverse from left to right first and store product of element to left for each index in an array. Traverse from right to left in next loop and save the product of elements to the right for each index in another array. Take product of the two arrays to get the answer array and return as response. This will take extra space O(n).
Optimized approach => Traverse from left to right and take a temperay variable intialized to 1. Add temp variable to the array. Multiply temp variable to current nums (to maintain product to the left for next element). Add the new product to next index and again multiply current product with current nums.
Start traversing from right to left and intialize the temp variable to 1 again. Multiply the current product with the currentindex of output array (output array will have product of elements to the right on first traversal).
Multiply product with current nums ( to maintain product to the right for next element while traversing to the left).
At the end output array will contain at each index the product of all elements except self
'''
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# edge case when nums is empty
if not nums or len(nums) == 0:
return [0]
# initialize temp product variable
product = 1
# intialize output array
output = [None] * len(nums)
# traverse through the array for calculating the left product
for i,num in enumerate(nums):
# add product calculated so far to the next index
output[i] = product
# multiply current num for the product to the left for next element
product *= num
# intialize temp variable again for product to the right
product = 1
# traverse from right to left
for i in range(len(nums)-1,-1,-1):
# multiplying with existing value of output array will give product of all elements to the right of current element with all elements to the left
output[i] = output[i] * product
# multiply current element for the next index
product *= nums[i]
# final result is multiplication of left and right computations
return output
|
9a915e306d84c786fd2290dc3180535c5773cafb | schase15/cs-module-project-iterative-sorting | /src/searching/searching.py | 1,967 | 4.375 | 4 | # Linear and Binary Search assignment
def linear_search(arr, target):
# Go through each value starting at the front
# Check to see if it is equal to the target
# Return index value if it is
# Return -1 if not found in the array`
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
# If the target is in the array, return the index value
# If the target is not in the array, return -1
def binary_search(arr, target):
# Set first and last index values
first = 0
last = len(arr) -1
# What is our looping criteria? What tells us to stop looping
# If we see that the index position has gone past the end of the list we stop
# If the value from the array is equal to the target, we stop
while first <= last:
# Compare the target element to the midpoint of the array
# Calculate the index of the midpoint
mid = (first + last) //2 # The double slash rounds down
# If the midpoint element matches our target, return the midpoint index
if target == arr[mid]:
return mid
# If the midpoint value is not equal to the target, decide to go higher or lower
if target < arr[mid]:
# If target is less than the midpoint, toss all values greater than the midpoint
# Do this by moving the search boundary high point down to one below the midpoint
last = mid -1
if target > arr[mid]:
# If target is greater than the midpoint, toss all values less than the midpoint
# Move the search boundary low point up to one above the midpoint
first = mid + 1
# Repeat this loop unitl the end of the array has been reached
# When the mid index has surpassed the length of the list
# If target is not found in the list, return -1
return -1
|
24b9e0ca714e29c6bc0dc6e6ffff1b3204b877d7 | kthvg5/CS5200 | /Knights_Tour/dfs.py | 1,505 | 3.6875 | 4 | # Don't use odd libraries
# Open tour gets partial credit
# Not testing anything bigger than 8x8
import sys
import copy
import stack
class Node(object):
def __init__(self, neighbors, used):
self.neighbors = neighbors
self.used = used
def dfs(graph, path):
parent = path.top()
# print "parent = ", parent
moves = graph[parent].neighbors
if path.size() == len(graph):
if path.data[0] in moves:
print "found one!"
return True
else:
return False
else:
for move in moves:
if graph[move].used is False:
graph[move].used = True
path.push(move)
if dfs(graph, path):
return True
else:
graph[move].used = False
path.pop()
def main():
n = int(sys.argv[1])
moves = [(2, -1), (2, 1), (1, 2), (-1, 2), (-1, -2), (1, -2), (-2, 1), (-2, -1)]
graph = dict()
node_moves = set()
path = stack.Stack()
for i in range(0, n):
for j in range(0, n):
for move in moves:
if 0 <= i + move[0] < n and 0 <= j + move[1] < n:
node_moves.add((i + move[0], j + move[1]))
graph[(i, j)] = (Node(copy.deepcopy(node_moves), False))
node_moves = set()
graph[(n/2, n/2)].used = True
path.push((n/2, n/2))
dfs(graph, path)
path.print_stack()
if __name__ == "__main__":
main()
|
6d8c58321442d9390bb3b8a0e7beaa39621906b6 | dolevp/prime_numbers | /utils.py | 205 | 3.90625 | 4 | def two_or_odd_numbers_between(start, end):
if start == 2:
return [2, *range(3, end + 1, 2)]
range_start = start + 1 if start % 2 == 0 else start
return range(range_start, end + 1, 2)
|
f1679bebaaf3107cc013a30839c45746444bc44b | nzsnapshot/MyTimeLine | /1-2 Months/tutorial/Test Discord Code.py | 854 | 3.5625 | 4 | import importlib
def get_all_candidates(ballots):
'''(list)->list
Given a list of strings, a list of lists, a list of dictionaries, or a
mix of all three, this function returns all the unique strings in this
list and its nested contents.
([{'GREEN':3, 'NDP':5}, {'NDP':2, 'LIBERAL':4},['CPC', 'NDP'], 'BLOC'])
['GREEN', 'NDP', 'LIBERAL', 'CPC', 'BLOC']
([['GREEN', 'NDP'], 'BLOC'])
['GREEN', 'NDP','BLOC']
([{'GREEN':3, 'NDP':5}, {'NDP':2, 'LIBERAL':4}])
['GREEN', 'NDP','LIBERAL']
'''
new_list = []
for e in ballots:
if type(e) is dict:
new_list.extend(get_all_candidates(e))
if type(e) is dict:
new_list.append(e.keys())
elif type(e) is dict:
new_list.append(e)
return new_list
print(new_list)
get_all_candidates(ballots) |
34d610751d4a8d69513f394ae0f53ed178f4fb95 | nzsnapshot/MyTimeLine | /2-3 Months/non-tutorial projects/rockpaperscissors.py | 5,096 | 3.875 | 4 | import random
import time
SLEEP_BETWEEN_ACTIONS = 0.5
def checkRules(user):
print('This is a game of Rock, Paper and Scissors')
print('')
userRules = input('Do you know the rules of the game? ')
time.sleep(SLEEP_BETWEEN_ACTIONS)
var = userRules.lower()
if var == 'yes':
straightinto = print(f"Okay lets get straight into the game {user}")
print('')
elif var == 'no':
print('')
insert = print('Insert rules here')
elif var != 'yes' or 'no':
fuck = input('Fuckwit, its a yes or no question stupid fucking nigger: ')
def user():
player = input('Please enter your username: ')
print('')
return player
def startGame():
player1 = user()
options = ['Rock', 'Paper', 'Scissors']
time.sleep(SLEEP_BETWEEN_ACTIONS)
checkRules(player1)
compScore = 0
playerScore = 0
print('Type Quit to quit at anytime: ')
print('')
while True:
try:
usersChoice = int(input('Please select from the following: 1:ROCK 2:PAPER 3:SCISSORS '))
compChoice = random.choice(options)
except ValueError:
print('Fucking Shit Game NIgger')
if usersChoice == 1 and compChoice == 'Scissors':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... 'ROCK'")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU WIN!')
time.sleep(SLEEP_BETWEEN_ACTIONS)
playerScore += 1
print(f"Your score is now {playerScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 1 and compChoice == 'Paper':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... ROCK")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU LOSE SHITTER!')
compScore += 1
print(f"Computers score is now {compScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 1 and compChoice == 'Scissors':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... ROCK")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('It is a draw')
elif usersChoice == 2 and compChoice == 'Scissors':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... PAPER")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU LOSE SHITTER!')
compScore += 1
print(f"Computers score is now {compScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 2 and compChoice == 'Rock':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... PAPER")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU WIN!')
playerScore += 1
print(f"Your score is now {compScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 2 and compChoice == 'Paper':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... PAPER")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('It is a draw')
elif usersChoice == 3 and compChoice == 'Rock':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... Scissors")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU LOSE SHITTER!')
compScore += 1
print(f"Computers score is now {compScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 3 and compChoice == 'Paper':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... Scissors")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('YOU WIN!')
playerScore += 1
print(f"Your score is now {compScore}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
elif usersChoice == 3 and compChoice == 'Scissors':
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"You have choosen... Scissors")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(f"The Computer has choosen... {compChoice}")
time.sleep(SLEEP_BETWEEN_ACTIONS)
print('It is a draw')
startGame()
|
Subsets and Splits