blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
aa48d363e35894f3ff0479b8f04188f98e06c898 | sururuu/TIL | /Baekjoon_Algorithm/14496_그대,그머가 되어.py | 648 | 3.8125 | 4 | import heapq
INF = float('inf')
def dijkstra(a,b):
distance = [INF] * (n+1)
distance[a] = 0
q = []
heapq.heappush(q,[0,a])
while q:
dis,idx = heapq.heappop(q)
if idx == b:
return distance[b]
for k in graph[idx]:
if dis + 1 < distance[k]:
distance[k] = dis + 1
heapq.heappush(q,[distance[k],k])
return -1
a,b = map(int,input().split())
n,m = map(int,input().split())
graph = [[] for _ in range(n+1)]
for i in range(m):
s,e = map(int,input().split())
graph[s].append(e)
graph[e].append(s)
print(dijkstra(a,b)) |
5539d7df9d444008e030b596dc0668a513425ae5 | AlexanderOnbysh/edu | /bachelor/generators.py | 3,744 | 3.765625 | 4 | # yield and yield from difference
# yield
def bottom():
return (yield 42)
def middle():
return (yield bottom())
def top():
return (yield middle())
>> gen = top()
>> next(gen)
<generator object middle at 0x10478cb48>
# ----------------------
# yield from
# is roughly equivalent to
# ***
# for x in iterator:
# yield x
# ***
def bottom():
return (yield 42)
def middle():
return (yield from bottom())
def top():
return (yield from middle())
>> gen = top()
>> next(gen)
42
# ----------------------
# yield from not iterable
def test():
yield from 10
>> gen = test()
>> next(gen)
TypeError: 'int' object is not iterable
# ----------------------
# yield from iterable object
def test():
yield from [1, 2]
>> gen = test()
>> next(gen)
1
>> next(gen)
2
>> next(gen)
StopIteration:
# throw method in generators
# gen.throw(exception, value, traceback)
def test():
while True:
try:
t = yield
print(t)
except Exception as e:
print('Exception:', e)
>> gen = test()
>> next(gen)
>> gen.send(10)
10
>> gen.send(12)
12
>> gen.throw(TypeError, 18)
Exception: 18
# g.close() send GeneratorExit to GeneratorExit
def close(self):
try:
self.throw(GeneratorExit)
except (GeneratorExit, StopIteration):
pass
else:
raise RuntimeError("generator ignored GeneratorExit")
# Other exceptions are not caught
# async
# Parallel async
# asyncio.gather put all tasks in event loop
import asyncio
async def bottom(name, sleep):
await asyncio.sleep(sleep)
print(f"I'm bottom {name}")
return 42
async def middle(name, sleep):
print(f"I'm middle {name}")
await bottom(name, sleep)
async def top(name, sleep):
print(f"I'm top {name}")
await middle(name, sleep)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(top('first', 3),
top('second', 2),
top('third', 1)
))
I'm top first
I'm middle first
I'm top third
I'm middle third
I'm top second
I'm middle second
# sleep for 3 seconds
I'm bottom third
I'm bottom second
I'm bottom first
# If we call corutine that call other corutine
# then task will be added sequatially to event loop
# and no parallelism happens
async def run():
names = ['first', 'second', 'third']
times = [3, 2, 1]
for name, time in zip(names, times):
await top(name, time)
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
I'm top first
I'm middle first
# sleep for 3 seconds
I'm bottom first
I'm top second
I'm middle second
# sleep for 2 seconds
I'm bottom second
I'm top third
I'm middle third
# sleep for 1 seconds
I'm bottom third
# Create tasks from futures and put
# them to event loop
# await results from each task
async def run():
loop = asyncio.get_event_loop()
names = ['first', 'second', 'third']
times = [3, 2, 1]
tasks = []
for name, time in zip(names, times):
t = loop.create_task(top(name, time))
tasks.append(t)
await asyncio.gather(*tasks)
# equvalet to
# for task in tasks:
# await task
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
I'm top first
I'm middle first
I'm top second
I'm middle second
I'm top third
I'm middle third
# sleep for 1 seconds
I'm bottom third
# sleep for 1 seconds
I'm bottom second
# sleep for 1 seconds
I'm bottom first
# Call later
def hey_hey(n):
print(n)
def hey():
print('Hey!')
loop = asyncio.get_event_loop()
loop.call_later(10, lambda: hey_hey(42))
loop = asyncio.get_event_loop()
loop.call_later(20, hey)
# 20 seconds
Hey
# 10 seconds
42
|
f1fd2535b2414f329f57dc856b2cb89621e07b5f | terrence85561/leetcode | /python/Array/LC238_productExceptSelf.py | 1,074 | 3.65625 | 4 | def productExceptSelf(self, nums: List[int]) -> List[int]:
# imagine when looping from left to right, in a certain view, we can only know the product of the values on the left
# in order to knnow the product of values on the right from this view, just loop from right to left again
# space O(1)
# rtn = [1] * len(nums)
# prod = 1
# for i in range(len(nums)):
# rtn[i] *= prod
# prod *= nums[i]
# prod = 1
# for i in range(len(nums)-1, -1, -1):
# rtn[i] *= prod
# prod *= nums[i]
# return rtn
# space O(n)
left = [0] * len(nums)
right = [0] * len(nums)
left[0] = 1
right[-1] = 1
for i in range(1, len(nums)):
left[i] = left[i-1] * nums[i-1]
for i in range(len(nums)-2, -1, -1):
right[i] = right[i+1] * nums[i+1]
rtn = [left[i] * right[i] for i in range(len(nums))]
return rtn
|
1cdf33060a02674b34fcfa37c133f44c8fceb115 | samuelluo/practice | /recursive_staircase/recursive_staircase.py | 709 | 3.6875 | 4 | def num_ways_1(N):
if N == 1: return 1 # 1 way: [1]
if N == 2: return 2 # 2 ways: [1+1, 2]
return num_ways_1(N-1) + num_ways_1(N-2) # take one step from N-1, or 2 steps from N-2
def num_ways_2(N):
if N in [0, 1]: return 1
ways = [1, 1]
for i in range(2, N+1):
ways.append(ways[i-1] + ways[i-2])
return ways[N]
def num_ways_3(N, X):
if N == 0: return 1
ways = [1]
for i in range(1, N+1):
ways_i = 0
for j in X:
if i-j >= 0:
ways_i += ways[i-j]
ways.append(ways_i)
return ways[N]
N = 3
print(num_ways_1(N))
print(num_ways_2(N))
X = [2,4]
print(num_ways_3(N, X))
X = [1,2,3]
print(num_ways_3(N, X)) |
17c66e0b79d2b9be178fbfbb08a88b2014f0f96e | AlexandrSech/Z49-TMS | /students/Volodzko/Task_4/task_4_1.py | 499 | 4.25 | 4 | """
Дан список целых чисел.Создать новый список,
каждый элемент которого равен исходному элементу умноженному на -2
"""
# Способ 1
my_list = [2, 5, 3, 8, 7, 9]
my_list2 = list()
i = 0
while i < len(my_list):
my_list2.append(my_list[i]*(-2))
i+=1
print(my_list2)
# Способ 2
my_list3 = [2, 5, 3, 8, 7, 9]
my_list4 = list()
for i in my_list3:
my_list4.append(i*(-2))
print(my_list4)
|
8d8f833866058a6e5a9461adf96f9c61e374af35 | hanameee/Algorithm | /Leetcode/파이썬 알고리즘 인터뷰/6_문자열조작/src/most-common-word.py | 689 | 3.515625 | 4 | from collections import Counter
def solution(paragraph, banned):
paragraph = paragraph.lower()
filtered_paragraph = ""
buf = ""
for char in paragraph:
if char.isalpha():
filtered_paragraph += char
continue
filtered_paragraph += " "
arr = list(map(lambda x: x.lower(), filtered_paragraph.split()))
filtered_arr = []
for item in arr:
if item not in banned:
filtered_arr.append(item)
c = Counter(filtered_arr)
return c.most_common(1)[0][0]
print(
solution("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))
print(
solution(
"a, a, a, a, b,b,b,c, c", ["a"]))
|
e2bc2e2be278d14ce48392a61e172b0b629476a9 | tuestudy/ipsc | /2011/A/haru.py | 527 | 3.765625 | 4 |
game_table = {
'scissors': ['Spock', 'rock'],
'paper': ['scissors', 'lizard'],
'rock': ['paper', 'Spock'],
'lizard': ['rock', 'scissors'],
'Spock': ['lizard', 'paper']
};
def main():
t = input()
result = []
for _ in range(t):
x = raw_input()
if len(result) > 0 and result[-1] == game_table[x][0]:
result.append(game_table[x][1])
else:
result.append(game_table[x][0])
for x in result:
print x
if __name__ == '__main__':
main()
|
fc4d16b3f454905c3773d52c059ed190f86528af | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Functions/lab/2_calculations.py | 395 | 4.15625 | 4 | def calculation(operator, n1, n2):
if operator == 'multiply':
result = n1 * n2
elif operator == "divide":
result = n1 // n2
elif operator == "add":
result = n1 + n2
elif operator == "subtract":
result = n1 - n2
return result
command = input()
num1 = int(input())
num2 = int(input())
print(calculation(command, num1, num2))
|
3fddd6c9c907b25ddc50b0f7ab15fee756a39e46 | ikhwan1366/Datacamp | /Data Engineer with Python Track/13. Building Data Engineering Pipelines in Python/Chapter/01. Ingesting Data/07-Communicating with an API.py | 3,921 | 4.40625 | 4 | '''
Communicating with an API
Before diving into this third lesson’s concepts, make sure you remember how URLs are constructed and how to interact with web APIs, from the prerequisite course Importing Data in Python, Part 2.
The marketing team you are collaborating with has been scraping several websites for customer reviews on consumer products. The dataset is only exposed to you through an internal REST API. You would like to add that data in its entirety to the data lake and store it in a convenient way, say csv. While the data is available over the company’s internal network, you still need to supply the API key that the marketing team has created for your exploration use case: api_key: scientist007.
For technical reasons, the endpoint has been made available to you on localhost:5000. You can “browse” to it, using the well-known requests module, by calling requests.get(SOME_URL). You can authenticate to the API using your API key. Simply fill in the template URL <endpoint>/<api_key>/.
Instructions 1/3
35 XP
- Fill in the correct API key.
- Create the URL of the web API by completing the template URL above. You need to pass the endpoint first and then the API key.
- Use that URL in the call to requests.get() so that you may see what more the API can tell you about itself.
'''
endpoint = "http://localhost:5000"
# Fill in the correct API key
api_key = "scientist007"
# Create the web API’s URL
authenticated_endpoint = "{}/{}".format(endpoint, api_key)
# Get the web API’s reply to the endpoint
api_response = requests.get(authenticated_endpoint).json()
pprint.pprint(api_response)
'''
Instructions 2/3
35 XP
- Take a look at the output in the console from the previous step. Notice that it is a list of endpoints, each containing a description of the content found at the endpoint and the template for the URL to access it. The template can be filled in, like you did in the previous step.
Complete the URL that should give you back a list of all shops that were scraped by the marketing team.
'''
endpoint = "http://localhost:5000"
# Fill in the correct API key
api_key = "scientist007"
# Create the web API’s URL
authenticated_endpoint = "{}/{}".format(endpoint, api_key)
# Get the web API’s reply to the endpoint
api_response = requests.get(authenticated_endpoint).json()
pprint.pprint(api_response)
# Create the API’s endpoint for the shops
shops_endpoint = "{}/{}/{}/{}".format(endpoint,
api_key, "diaper/api/v1.0", "shops")
shops = requests.get(shops_endpoint).json()
print(shops)
'''
Instructions 3/3
30 XP
Take a look at the output in the console from the previous step. The shops variable contains the list of all shops known by the web API.
From the shops variable, find the one that starts with the letter “D”. Use it in the second (templated) url that was shown by the call to pprint.pprint(api_response), to list the items of this specific shop. You must use the appropriate url endpoint, combined with the http://localhost:5000, similar to how you completed the previous step.
'''
endpoint = "http://localhost:5000"
# Fill in the correct API key
api_key = "scientist007"
# Create the web API’s URL
authenticated_endpoint = "{}/{}".format(endpoint, api_key)
# Get the web API’s reply to the endpoint
api_response = requests.get(authenticated_endpoint).json()
pprint.pprint(api_response)
# Create the API’s endpoint for the shops
shops_endpoint = "{}/{}/{}/{}".format(endpoint,
api_key, "diaper/api/v1.0", "shops")
shops = requests.get(shops_endpoint).json()
print(shops)
# Create the API’s endpoint for items of the shop starting with a "D"
items_of_specific_shop_URL = "{}/{}/{}/{}/{}".format(
endpoint, api_key, "diaper/api/v1.0", "items", "DM")
products_of_shop = requests.get(items_of_specific_shop_URL).json()
pprint.pprint(products_of_shop)
|
86087bacc41b3926b4de98e25b0f687436a54c9f | sumitvarun/pythonprograms | /inheritance baseclass.py | 210 | 3.609375 | 4 | class Rectangle():
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
|
43f5c68c8a9adfc9b590557baabc15843e390dfb | renebentes/Python4Zumbis | /Exercícios/Lista I/questao08.py | 117 | 3.875 | 4 | f = int(input('Informe a temperatura em Fahrenheit: '))
print('Temperatura em Celsius: %5.2f' % ((f - 32) * 5 / 9))
|
ec22cf8fcd82e0f0e62bb3b4c9e78af01f99a352 | enordlund/CS325 | /Homework 3/h3q4d.py | 4,362 | 3.5625 | 4 | #!/usr/bin/python
from collections import namedtuple
import numpy as np
# item type for code clarity
Item = namedtuple("Item", "weight value")
def constructItemArrayBottomUp():
# opening data file
f = open("data.txt")
# initializing empty array for items
itemArray = [Item(0,0)]
for line in f.readlines():
if " " in line:
# creating item for array from populated line
dataList = [int(i) for i in line.split(" ")]
# first is weight, second is value
item = Item(dataList[0], dataList[1])
itemArray.append(item)
return itemArray
def constructItemArrayTopDown():
# opening data file
f = open("data.txt")
# initializing empty array for items
itemArray = []
for line in f.readlines():
if " " in line:
# creating item for array from populated line
dataList = [int(i) for i in line.split(" ")]
# first is weight, second is value
item = Item(dataList[0], dataList[1])
itemArray.append(item)
return itemArray
def emptyTable(items, capacity):
#getting dimensions for table B
rows = len(items)
# columns is capacity + 1
columns = capacity + 1
# creating empty array for output
table = [[0]*columns]*rows
return table
# creating array of items from the data file
itemsBU = constructItemArrayBottomUp()
table = emptyTable(itemsBU, 6)
#print(table)
def optimalKnapsackBenefitBottomUp(items, capacity):
# print("bottom up")
itemCount = len(items)
itemIndex = 0
npTable = np.array([])
while itemIndex < itemCount:
capacityIndex = 0
item = items[itemIndex]
valuesRow = []
# print(table)
maxValue = 0
while capacityIndex <= capacity:
# print("Item index:")
# print(itemIndex)
# print("Capacity index:")
# print(capacityIndex)
# print("Item weight:")
# print(item.weight)
value = 0
if itemIndex is 0:
value = 0
elif capacityIndex is 0:
value = 0
elif item.weight <= capacityIndex:
# print("item weight <= capacity index")
# print("table[itemIndex - 1][capacityIndex]:")
# print(table[itemIndex-1][capacityIndex])
# print("table[itemIndex - 1][capacityIndex - item.weight] + item.value: ")
# print(table[itemIndex-1][capacityIndex - item.weight] + item.value)
value = max([table[itemIndex-1][capacityIndex], table[itemIndex-1][capacityIndex - item.weight] + item.value])
else:
# print("item weight > capacity index")
value = table[itemIndex - 1][capacityIndex]
# print("value:")
# print(value)
if value > maxValue:
maxValue = value
valuesRow.append(value)
capacityIndex += 1
# print("valuesRow: ")
print(valuesRow)
table[itemIndex] = valuesRow
# npTable = np.append(npTable, valuesRow)
itemIndex += 1
# print(npTable)
print'Optimal benefit: ',
print maxValue
optimalKnapsackBenefitBottomUp(itemsBU, 6)
#print(table)
def optimalKnapsackBenefitTopDown(items, itemsMaxIndex, capacity):
# print("top down")
item = items[itemsMaxIndex]
if (itemsMaxIndex < 0) or (itemsMaxIndex >= items.count):
outcome = 0
#table[capacity][itemsMaxIndex] = outcome
print("item ", itemsMaxIndex + 1, ", capacity ", capacity, "benefit: ", outcome)
#print(outcome)
return outcome
elif item.weight > capacity:
outcome = optimalKnapsackBenefitTopDown(items, itemsMaxIndex - 1, capacity)
#table[capacity][itemsMaxIndex] = outcome
print("item ", itemsMaxIndex + 1, ", capacity ", capacity, "benefit: ", outcome)
#print(outcome)
return outcome
else:
outcome = max([optimalKnapsackBenefitTopDown(items, itemsMaxIndex - 1, capacity), optimalKnapsackBenefitTopDown(items, itemsMaxIndex - 1, capacity - item.weight) + item.value])
#table[capacity][itemsMaxIndex] = outcome
print("item ", itemsMaxIndex + 1, ", capacity ", capacity, "benefit: ", outcome)
#print(outcome)
return outcome
#itemsTD = constructItemArrayTopDown()
##
### calculating optimal benefit
##print("Subsets:")
#print("top down")
#benefit = optimalKnapsackBenefitTopDown(itemsTD, 4, 6)
##
### printing outcome
#print("Optimal benefit:")
#print(benefit)
#testTable = emptyTable(itemsBU, 6)
#
#print(testTable)
#
#newRow = testTable[1]
#
#print(newRow)
#
##newRow[2] = 1
#
#print(newRow)
#
#testTable[1] = [2, 3]
#
#testTable[1][0] = testTable[0][3]
#
#testTable[0][3] = 5
#
#print(newRow)
#
##print(testTable[1])
#
#print(testTable) |
1e3298652853c8aa9aace93ffb3862e680e57041 | mmveres/pythonProject18_09_2021 | /lesson02/cycle/task_cycle.py | 465 | 3.65625 | 4 | def print_inc_value(start=0, end=100, delta=1):
i = start
while i < end:
print(i)
i = i + delta
def print_dec_value(start, end, delta):
i = start
while i >= end:
print(i)
i = i - delta
def print_power_value(x = 2,n = 10):
i = 0
xn = 1;
while i < n:
xn *= x
i += 1
print(xn)
def get_power_value(x = 2, n = 10):
xn = 1;
for i in range(n):
xn *= x
return xn
|
5837be02bf4ec3da8e84480cf1f0abdce6dbc5b3 | NeelShah18/googletensorflow | /operation.py | 1,559 | 4.28125 | 4 | import tensorflow as tf
#Defining constant using tensorflow object
a = tf.constant(2)
b = tf.constant(3)
'''
Open tensorflow session and perform the task, Here we use "with" open the tensorflow because with will close the session automatically so we dont need to remember to close
each sessiona fter starting it. We can use those constatn variable as python variable and perform the task or we can use tensorflow inbuild function to perform mathematical task.
Bdw launching the session means define basic graph!!!!
'''
with tf.Session() as sess:
print("A is %i"%sess.run(a))
print("B is %i"%sess.run(b))
print("Addition is: %i"%sess.run(a+b))
print("Multiplication is: %i"%sess.run(a*b))
'''
Here, placeholder works like input of the graph. Means it defines what will be input for current runing session
'''
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a,b)
mul = tf.multiply(a,b)
'''
As we can see a and b is now placeholder means input for current runing session.
'''
with tf.Session() as sess:
print("Addition: %i"%sess.run(add, feed_dict={a:10, b:15}))
print("Multiplication: %i"%sess.run(mul, feed_dict={a:5, b:6}))
'''
Creating two constatn matrix m1=1*2 and m2=2*1
'''
m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.], [2.]])
#Deafult function of tensorflow to do matrix multiplication. Here object is created name prod which perform matrix multiplication of m1 and m2
prod = tf.matmul(m1,m2)
#This session print the muatrix multiplication
with tf.Session() as sess:
result = sess.run(prod)
print(result)
|
4ebcd7c1b2489942f7c533b821ce7654d09163ff | Natebeta/Tannenbaum | /Tannenbaum.py | 795 | 3.53125 | 4 | # Autor: Aman
# Tannenbaum
#Version 1
#Variablen
l = int(input("Eingabe: "))
sterne = "**"
stern = "*"
sterne_anzahl = 0
loop = 0
out = "*"
var1 = l
FILLER1 = ""
FILLER = ' '
def stamm():
var2 = l//4
countFILLER = len(FILLER1)
for loop in range(0, var2):
print(str((" " * (countFILLER - var2 // 2)) + (stern * var2)))
while loop<l:
var1 = var1 -1
if loop==0:
FILLER1 = FILLER * var1
print(FILLER * var1 + "W")
else:
while sterne_anzahl<loop:
out = out + sterne
sterne_anzahl = sterne_anzahl + 1
if(loop%3 == 0):
print(FILLER * (var1 - 1) + "I" + out + "I")
else:
print(FILLER * var1 + out)
loop =loop + 1
stamm()
|
9b74583fc3edbc72b8cf0ab7fab9000626a3d6c3 | oneMoreTime1357/selfteaching-python-camp | /19100101/Shawn/mymodule/stats_word.py | 1,001 | 3.578125 | 4 | #d9 excercise
import collections
import re
#英文字频统计
def stats_text_en(text_en,count):
if type(text_en) == str:
entext = re.sub("[^A-Za-z]", " ", text_en.strip())
enList = entext.split()
return collections.Counter(enList).most_common(count)
else:
raise ValueError ('it is not str')
#汉字词频统计
def stats_text_cn(text_cn,count):
if type(text_cn) == str:
cntext = re.findall(u'[\u4e00-\u9fff]+', text_cn.strip())
newString = ''.join(cntext)
return collections.Counter(newString).most_common(count)
else:
raise ValueError ('it is not str')
# 合并英汉词频统计 '''
def stats_text(text_en_cn,count_en_cn) :
if type(text_en_cn) == str:
return (stats_text_en(text_en_cn,count_en_cn)+stats_text_cn(text_en_cn,count_en_cn))
else :
raise ValueError('it is not str')
|
271694984dbdf95ef138b363e511e06405505618 | Raragyay/Snake | /snake/solver/path.py | 8,473 | 3.734375 | 4 | # coding=utf-8
"""
Definitions for PathSolver class, which is the path-finder for Greedy and Hamilton..
Exported methods in PathSolver are longest path to tail and shortest path to food.
"""
import random
import sys
from collections import deque
from snake.map import PointType, Direc
from snake.solver.base import BaseSolver
class _TableCell:
def __init__(self):
self.reset()
def __str__(self):
return '{dist: {} parent:{} visit:{}}'.format(self.dist, str(self.parent), self.visit)
__repr__ = __str__
def reset(self):
"""
Reset the table cell.
:return:
"""
self.parent = None
self.dist = sys.maxsize
self.visit = False
class PathSolver(BaseSolver):
"""
This is a helper class that contains two important algorithms:
1. Shortest path from the head to a certain point.
2. Longest path from the head to a certain point.
Each of the solvers contains a PathSolver which helps compute the tedious tasks, which the solvers then interpret.
"""
def __init__(self, snake):
super().__init__(snake)
self.__table = [[_TableCell() for _ in range(snake.map.num_cols)] for _ in range(snake.map.num_rows)]
@property
def table(self):
"""
:return: Table. Used for Hamiltonian Cycle.
"""
return self.__table
def shortest_path_to_food(self):
"""
:return: A deque of directions to go in to get the shortest path to food.
"""
return self.path_to(self.map.food, 'shortest')
def longest_path_to_tail(self):
"""
:return: A deque of directions to go in to get the longest path to the tail.
Used for hamiltonian cycle and greedy snake running away.
"""
return self.path_to(self.snake.tail(), 'longest')
def path_to(self, des, path_type):
"""
This is a helper function that temporarily sets the point of the destination to empty.
This is done so that it will be considered by the path_finding_algorithms, which only add points to the queue
if they are empty.
:param des: The destination of the path of type Pos.
:param path_type: Either shortest or longest. Switches between method shortest_path_to and longest_path_to.
:return: A deque of directions. Each direction is an enum Direc.
"""
original_type = self.map.point(des).type
self.map.point(des).type = PointType.EMPTY
path = deque()
if path_type == 'shortest':
path = self.shortest_path_to(des)
elif path_type == 'longest':
path = self.longest_path_to(des)
self.map.point(des).type = original_type
return path
def shortest_path_to(self, des):
"""
Find the shortest path from the snake's head to the destination.
This is a BFS implementation for snake.
:param des: The destination position on the map of type Pos.
:return: A deque of instructions(directions) for the snake.
"""
self.__reset_table()
head = self.snake.head()
self.__table[head.x][head.y].dist = 0
queue = deque()
queue.append(head)
while queue:
cur = queue.popleft()
if cur == des:
return self.__build_path(head, des)
if cur == head:
first_direc = self.snake.direc
else:
first_direc = self.__table[cur.x][cur.y].parent.direction_to(cur)
adjacents = cur.all_adj()
random.shuffle(adjacents)
# Arrange the order of traverse to make the path as straight as possible.
for i, pos in enumerate(adjacents):
if first_direc == cur.direction_to(pos):
adjacents[0], adjacents[i] = adjacents[i], adjacents[0]
break
for pos in adjacents:
if self.__is_valid(pos):
adj_cell = self.__table[pos.x][pos.y]
if adj_cell.dist == sys.maxsize: # If it hasn't been visited yet
adj_cell.parent = cur
adj_cell.dist = self.__table[cur.x][cur.y].dist + 1
queue.append(pos)
return deque()
def longest_path_to(self, des):
"""
Find the longest path from the snake's head to the destination.
This is done by getting the shortest path,
then extending the path by pushing it out.
:param des: THe destination position on the map of type Pos.
:return: A deque of instructions(directions) for the snake.
"""
path = self.shortest_path_to(des)
if not path: # If you can't even get there, then return an empty deque.
return deque()
self.__reset_table() # Ensure idempotency.
cur = head = self.snake.head()
# Set all positions on the shortest path to visited.
self.__table[cur.x][cur.y].visit = True
for direc in path:
cur = cur.adj(direc)
self.__table[cur.x][cur.y].visit = True
idx, cur = 0, head
while True:
cur_direc = path[idx]
nxt = cur.adj(cur_direc)
tests = []
# We create a next because we need to push out two "blocks" at once.
# How this works is the algorithm checks two adjacent points,
# and sees if they can be pushed out in the opposite direction.
if cur_direc == Direc.LEFT or cur_direc == Direc.RIGHT:
tests = [Direc.UP, Direc.DOWN]
# Then we can try extending the path up or down.
elif cur_direc == Direc.UP or cur_direc == Direc.DOWN:
tests = [Direc.LEFT, Direc.RIGHT]
# If the direction is moving up, then we try pushing it out sideways..
extended = False
for test_direc in tests:
cur_test = cur.adj(test_direc)
nxt_test = nxt.adj(test_direc)
if self.__is_valid(cur_test) and self.__is_valid(nxt_test):
self.__table[cur_test.x][cur_test.y].visit = True
self.__table[nxt_test.x][nxt_test.y].visit = True
path.insert(idx, test_direc) # We will insert that anti-shortcut into the path.
path.insert(idx + 2, Direc.opposite(test_direc)) # What goes out must eventually come back.
extended = True # This tells the algorithm to continue checking that same point.
break
if not extended: # If there was no pushing out the path, then continue to the next point.
cur = nxt
idx += 1
if idx >= len(path):
# Once all points have been checked, then break out of the loop and return the path.
break
return path
def __reset_table(self):
"""
Reset the table for a new round of testing.
This is done by calling the reset function for each cell,
which deletes their parents (shocking, I know), and sets their visit to false.
:return: Void.
"""
for row in self.__table:
for col in row:
col.reset()
def __build_path(self, src, des):
"""
Build a path from the source from the destination, using the records of parent.
:param src: The starting point. Usually the snake's head.
:param des: The destination. Usually the food for Greedy,
and the snake's tail for Hamiltonian Cycle.
:return: A path of deque, tracing the path to get there. Each item in the deque is a Direc.
"""
path = deque()
tmp = des
while tmp != src:
parent = self.__table[tmp.x][tmp.y].parent
path.appendleft(parent.direction_to(tmp))
tmp = parent
return path
def __is_valid(self, pos):
"""
This function checks if that point is valid.
The two conditions that it checks is if the point has been visited before,
and if it is safe, aka within the boundaries of the map and not a snake body.
:param pos: A position of type Pos.
:return: A boolean value, depending on if that position is valid or not.
"""
return not self.__table[pos.x][pos.y].visit and self.map.is_safe(pos)
|
de9562fe2357209d34bcec2a78619162b6f146c7 | songaiwen/information_29_01 | /7.爬虫/day3/4.re方法2.py | 567 | 3.609375 | 4 | """
正则表达式:
"""
import re
if __name__ == '__main__':
str_one = 'abc123'
str_two = '456'
pattern = re.compile('^\d+$')
# 1.match 从头开始 匹配一次
result = pattern.match(str_one)
print(result)
# 2.search 从任意位置
result = pattern.search(str_one)
print(result)
#3.findall 返回list
str_two = 'afdsdafsfsdfsdsdsd'
pattern = re.compile('s')
result = pattern.findall(str_two)
#4.finditer 返回iter
result = pattern.finditer(str_two)
# for res in result:
print(result) |
71d43d633f889b07ecb97317cef581abbba59273 | xizhang77/LeetCode | /Math/357-count-numbers-with-unique-digits.py | 642 | 3.953125 | 4 | # -*- coding: utf-8 -*-
'''
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
excluding 11,22,33,44,55,66,77,88,99
'''
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
ans = 10
factor = 9
for i in range(n-1):
factor = factor * (9-i)
ans += factor
return ans |
8a7f5a0c4362f69e5289170081277f6d0433f8e3 | dcheung15/Python | /ecs102/Hw/KGtoPound.py | 929 | 3.625 | 4 | #Doung Lan Cheung
#KGtoPound.py
#kilograms to pounds
from graphics import *
def main():
win=GraphWin("Kilograms to Pounds Converter",400,600)
win.setBackground("light blue")
win.setCoords(0,0,4,6)
#make fake button for conversion
button=Rectangle(Point(1,1.5),Point(3,.5))
button.setFill("grey")
buttonLabel=Text(Point(2,1),"Click to Calculate")
button.draw(win)
buttonLabel.draw(win)
#draw weight in kilograms
Text(Point(1,5.7),"Weight in pounds").draw(win)
lbs = 0
lbdisplay=Text(Point(1,5.5),str(lbs))
lbdisplay.draw(win)
#display text entry box for entering weight in kilograms
Text(Point(3.3,5.7),"Weight in Kg").draw(win)
KgBox=Entry(Point(3,5.5),10)
KgBox.setText("0.0")
KgBox.draw(win)
#calculate kilograms to pounds
win.getMouse()
kg=float(KgBox.getText())
pounds= kg/0.453592
lbdisplay.setText(str(pounds))
main() |
ac63da86a9d8fe6a81ecc0e70a5d1240c425acae | suecharo/ToudaiInshi | /2014_summer/question_3.py | 341 | 3.859375 | 4 | # coding: utf-8
import math
def question_3():
ans = 0
s_0 = 25 * math.sqrt(3)
for i in range(3):
if i == 0:
ans += s_0
else:
tri_num = 3 * (4 ** (i - 1))
s_i = s_0 * ((1 / 9) ** i)
ans += s_i * tri_num
print(ans)
if __name__ == "__main__":
question_3()
|
480259fdfe4386648ebd370f07554924b7afeb50 | vkumar62/practice | /leetcode/229_majority_element.py | 762 | 3.734375 | 4 | from collections import defaultdict
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
counts = defaultdict(int)
for n in nums:
counts[n] += 1
if len(counts) == 3:
for c in list(counts.keys()):
counts[c] -= 1
if counts[c] == 0:
del counts[c]
for c in counts:
counts[c] = 0
for n in nums:
if n in counts:
counts[n] += 1
return [x for x in counts if counts[x] > len(nums)//3]
import pdb
pdb.set_trace()
nums = [1,2]
print(Solution().majorityElement(nums))
|
24d0475a05be00049fa4d88053b4398307a94281 | josepmg/trabalhoRedes1 | /model/tabuleiro.py | 3,582 | 3.65625 | 4 | import random
import sys
from main.utils import Utils
class Tabuleiro:
#construtor da classe Tabuleiro que ja cria um tabuleiro novo
def __init__(self, dim):
#dimensoes do tabuleiro
self.dimension = dim
#numero de pecas
self.nPieces = dim**2
# numero de pares
self.pairs = dim * 2
# numero de pares encontrados
self.discoveredPairs = 0
#valores do tabuleiro
self.values = []
#como o tabuleiro pe apresentado para o jogador
self.display = []
# inicializa o array de valores
for i in range(0, dim):
linha = []
for j in range(0, dim):
linha.append(0)
self.values.append(linha)
# inicializa o array de display
for i in range(0, dim):
linha = []
for j in range(0, dim):
linha.append('?')
self.display.append(linha)
# Cria um array com todas as posicoes disponiveis
# Facilita a atribuicao inical de valores (aleatorios)
availabePositions = []
for i in range(0, dim):
for j in range(0, dim):
availabePositions.append((i, j))
# Varre todas as pecas que serao colocadas no
# tabuleiro e posiciona cada par de pecas iguais
# em posicoes aleatorias.
for j in range(0, dim // 2):
for i in range(1, dim + 1):
# Sorteio da posicao da segunda peca com valor 'i'
maximo = len(availabePositions)
indiceAleatorio = random.randint(0, maximo - 1)
rI, rJ = availabePositions.pop(indiceAleatorio)
self.values[rI][rJ] = -i
# Sorteio da posicao da segunda peca com valor 'i'
maximo = len(availabePositions)
indiceAleatorio = random.randint(0, maximo - 1)
rI, rJ = availabePositions.pop(indiceAleatorio)
self.values[rI][rJ] = -i
def getDimen(self):
return self.dimension
def getNPieces(self):
return self.nPieces
def getNumPairs(self):
return self.pairs
def discoverPair(self):
self.discoveredPairs += 1
def getDiscoveredPairs(self):
return self.discoveredPairs
def revealPiece(self, i, j):
#caso a peca da posicao i j ainda nao tenha sido esoclhida ou retirada do jogo
if (self.display[i][j] == '?' and self.values[i][j] < 0):
#array do display mostra o valor da peca
self.display[i][j] = self.values[i][j]
#array da peca passa a conter o numero POSITIVO, indicando que esta escolhido
self.values[i][j] = -self.values[i][j]
return self.values[i][j]
# Caso a peça já tenha sido escolhida ou removida, retorna 0 como código de erro
return 0
def hidePiece(self, i, j):
#caso a peca da posicao i j ainda tenha sido esoclhida e nao tenha sido retirada do jogo
if self.display[i][j] != '?' and self.display[i][j] != '-' and self.values > 0:
#array do display recebe interrogacao
self.display[i][j] = '?'
#array da peca passa a conter o numero NEGATIVO, indicando que nao esta escolhido
self.values[i][j] = -self.values[i][j]
return True
else:
return False
def removePiece(self, i, j):
if self.display[i][j] == '-':
return False
else:
self.display[i][j] = '-'
return True
|
8379ebe3e66656e4b7e0484543ba4af27ef7f559 | LiangZZZ123/algorithm_python | /2/02_linked_list.py | 876 | 3.890625 | 4 | class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __repr__(self):
return '<Node: value: {}, next={}>'.format(self.value, self.next)
class LinkedList():
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.tailnode = None
self.length = 0
def __len__(self):
return self.length
def append(self, value):
if self.maxsize is not None and len(self) >= self.maxsize:
raise Exception('full')
node = Node(value)
tailnode = self.tailnode
if tailnode is None:
self.root.next = node
else:
tailnode.next = node
self.tailnode = node
self.length += 1
def appendleft(self, value):
if self.maxsize is not None and le
|
702f77c704b9bbef0168fa956aa906d2a017472c | solareenlo/python_practice | /03_制御フローとコード構造/none.py | 763 | 4.15625 | 4 | """This is a test program."""
is_empty: object = None
print(is_empty) # None と表示
if is_empty == None:
print('None!') # None! と表示
if is_empty is None:
print('None!') # None! と表示
if is_empty is not None:
print('None!') # 何も表示されない
print(1 == True) # True と表示 objectとしてTrueかどうかを判定
print(1 is True) # False と表示 objectの中身が同じかどうかを判定
print(True == True) # True と表示
print(True is True) # True と表示
print(None == None) # True と表示
print(None is None) # True と表示
# 何が言いたい方というと, isやis notはNoneであるかどうかを判定する時によく使われるということ
# Noneとは空のobjectですよ. という意味
|
7f544e07dc56f4ee89de2d780cf029d5846b2f0c | arthurPignet/privacy-preserving-titanic-challenge | /src/features/build_features.py | 3,766 | 3.65625 | 4 | import logging
import pandas as pd
from sklearn.preprocessing import LabelEncoder
DATA_PATH = "../../data/raw/"
WRITE_PATH = "../../data/processed/"
def data_import(path=DATA_PATH):
""""
This function import the raw data from .csv files to pandas. It aims for 2 files, named train.csv and test.csv
Parameter
-----------
path : path of the directory where the two .csv files are stored
Returns
------------
tuple : (pandas_df: train_set, pandas_df: test_set)
"""
logger = logging.getLogger(__name__)
logger.info('loading the data into memory (pandas df)')
raw_train_set_df = pd.read_csv(path + "train.csv")
raw_test_set_df = pd.read_csv(path + "test.csv")
logger.info('Done')
return raw_train_set_df, raw_test_set_df
def processing(raw_train_df, raw_test_df, isSaved=False, write_path=WRITE_PATH):
"""
process the raw data, filling empty values, generating some features
For commentary about this processing,
see the notebook entitled processing in the directory
titanic-data
:parameter
------------
train_df : dataframe with train_df data
preprocessed_test_df : dataframe with test data
(Optional) isSaved : boolean, if True the output data will be stored in the write_path
(Optional) write_path : if isSaved, path where the output dataframe will be saved, in csv format.
:returns
----------
processed_train_df : train data set, after data completion, data scaling, and feature engineering.
processed_test_df : test data set, after data completion, data scaling, and feature engineering.
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data')
data_df = pd.concat([raw_train_df, raw_test_df], sort=True).reset_index(drop=True)
data_df.Embarked = data_df.Embarked.fillna('S')
data_df["Age"] = data_df.groupby(['Sex', 'Pclass', 'Embarked'])["Age"].apply(lambda x: x.fillna(x.median()))
data_df.Fare = data_df.Fare.fillna(data_df.groupby(['Pclass', 'Parch']).median().Fare[3][0])
data_df['Deck'] = data_df.Cabin.fillna('M').apply(lambda x: str(x)[0])
data_df['Family_Size'] = data_df['SibSp'] + data_df['Parch'] + 1
data_df['Title'] = data_df.Name.str.split(',', expand=True)[1].str.split('.', expand=True)[0].str.replace(" ", "")
data_df['Title'] = data_df['Title'].replace(
['Lady', 'theCountess', 'Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
data_df['Title'] = data_df['Title'].replace('Mlle', 'Miss')
data_df['Title'] = data_df['Title'].replace('Ms', 'Miss')
data_df['Title'] = data_df['Title'].replace('Mme', 'Mrs')
categorical_col = ["Pclass", 'Embarked', 'SibSp', 'Deck', "Title"]
data_df.Sex = LabelEncoder.fit_transform(data_df.Sex, data_df.Sex)
for col in categorical_col:
dummies = pd.get_dummies(data_df[col], prefix=col)
data_df = pd.concat([data_df, dummies], axis=1)
data_df = data_df.drop(col, axis=1)
data_df.drop(['Name', 'Cabin', 'Ticket', 'PassengerId'], axis='columns', inplace=True)
col_to_reg = ['Age', 'Fare', 'Family_Size']
for col in col_to_reg:
data_df[col] = (data_df[col] - data_df[col].mean()) / data_df[col].std()
processed_train_df = data_df.iloc[:raw_train_df.shape[0]]
processed_test_df = data_df.iloc[raw_train_df.shape[0]:].drop('Survived', axis=1)
logger.info('Done')
if isSaved:
processed_train_df.to_csv(write_path + "processed_train.csv")
processed_test_df.to_csv(write_path + "processed_test.csv")
return processed_train_df, processed_test_df
if __name__ == "__main__":
train_df, test_df = data_import()
processing(train_df, test_df, isSaved=True)
|
9aa6a675e4cf57571729a07154a7124ca4489734 | zhangambit/486finalproject | /commentCompile.py | 3,390 | 3.6875 | 4 | import json
import os
""" This module defines methods and a class to take a Reddit archive and create a representation of who replied to whom."""
class Person:
def __init__(self, ID):
self.ID = ID
self.replies = dict() # The number of replies & to whom this person has made.
self.parents = list() # Links to comments that were replied to by other people, or that the Person replied to.
self.commentsMade = 0
self.commentsRecieved = 0
def addReply(self, repliedTo):
if repliedTo in self.replies:
self.replies[repliedTo] += 1
else:
self.replies[repliedTo] = 1
def __str__(self):
str = "/u/%s replied to:" % (self.ID)
for k in self.replies:
str += "\n /u/%s : %d" % (k, self.replies[k])
return str
"""A recursive function that traverses the comment tree"""
def readComment(DB, tree, author, authorData, permalink):
# The author is the person who the 'current' person replied to;
# that is, this function adds a reply to all the children of that comment
link = permalink + authorData["id"] # reddit.com/r/subreddit/comments/threadID/threadname/commentID>
DB[author].parents.append(link);
for reply in tree:
if not reply["kind"] == "t1":
continue
current = reply["data"]["author"]
if not current in DB:
DB[current] = Person(current)
DB[current].addReply(author)
DB[current].parents.append(link);
if len(reply["data"]["replies"]) > 0:
readComment(DB, reply["data"]["replies"]["data"]["children"], current, reply["data"], permalink)
"""This is the function to call.
DB is a dict() of People. filename is a string that represents a path to the json file. parseJSON() must be called once for each json file."""
def parseJSON(DB, filename):
with open(filename, 'r') as jsonfile:
rawdata = jsonfile.read()
data = json.loads(rawdata)
OP = data[0]["data"]["children"][0]["data"]["author"]
permalink = data[0]["data"]["children"][0]["data"]["permalink"]
if not OP in DB:
DB[OP] = Person(OP);
for rep in data[1]["data"]["children"]:
if not rep["kind"] == "t1" or rep["kind"] == "Listing":
continue
author = rep["data"]["author"]
if not author in DB:
DB[author] = Person(author)
DB[author].addReply(OP)
if len(rep["data"]["replies"]) > 0:
replies = rep["data"]["replies"]["data"]["children"]
readComment(DB, replies, rep["data"]["author"], rep["data"], permalink)
incomingReplies = dict()
for key in DB:
DB[key].commentsMade = len(DB[key].replies);
# Compile a list of how many times each person recieved a reply.
for person in DB[key].replies:
if not person in incomingReplies:
incomingReplies[person] = DB[key].replies[person]
else:
incomingReplies[person] += DB[key].replies[person]
# May cause a problem with people only recieving a reply.
for person in incomingReplies:
if not person in DB:
buffer = Person(person)
buffer.commentsRecieved = incomingReplies[person]
DB[person] = buffer
else:
DB[person].commentsRecieved = incomingReplies[person]
|
74a78ec1bd536ca71138ef203d2cb244b4ff5ee4 | abhishekreddy1206/spoj | /nextpali.py | 904 | 3.53125 | 4 | output = []
cases = input()
def next_higher(K):
if all(digit == '9' for digit in K):
return int(K) + 2
L = len(K)
left = K[:L/2]
center = L % 2 and K[L/2] or ""
right = left[::-1]
P = left + center + right
if P > K:
return P
if center and center != '9':
center = chr(ord(center) + 1)
return left + center + right
elif center:
center = '0'
left = list(left)
digits_left = len(left)
while digits_left:
idx = digits_left - 1
if left[idx] == '9':
left[idx] = '0'
digits_left = digits_left - 1
else:
left[idx] = chr(ord(left[idx]) + 1)
break
left = "".join(left)
right = left[::-1]
return left + center + right
for i in range(0,cases):
z = raw_input()
output.append(next_higher(z))
for i in range(0,cases):
print output[i] |
b0c65894f67a4ee168f84e472fd3f8bf1afe0ad7 | Wormandrade/Trabajo02 | /eje_p1_06.py | 448 | 4.28125 | 4 | #Utilizando la función range() y la conversión a listas genera las siguientes listas dinámicamente:
print("========================")
print("\tEJERCICIO 06")
print("========================")
print("\nListas dinamicas\n")
def listas(inicio, fin, salto):
num_lista = []
for num in range(inicio, fin+1,salto):
num_lista.append(num)
print(num_lista)
listas(0,10,1)
listas(-10,0,1)
listas(0,20,2)
listas(-19,0,2)
listas(0,50,5) |
24e028b3eb783c36f9f165d13dc5dcb2f69fe80a | kubos777/cursoSemestralPython | /Tareas/SolucionesTarea3/tarea3P5.py | 391 | 4.46875 | 4 | #################################################################################################
# Tarea 3 , Problema 1
# Escriba un programa de Python que acepta una palabra del usuario y la invierte.
#################################################################################################
palabra=input("Escribe una palabra: ")
print("Tu palabra al revés es: ",palabra[::-1])
|
1f8544b2fb33c90483c87d84492e9493abca7281 | WilliamSampaio/ExerciciosPython | /exerc26/26.py | 235 | 4.03125 | 4 | import os
num1 = float(input('digite o numero 1: '))
num2 = float(input('digite o numero 2: '))
num3 = float(input('digite o numero 3: '))
num=[num1,num2,num3]
print(*sorted(num,reverse=True), sep=', ')
os.system('pause') |
6b3c8e282e6881deab73a5912304c843df4f1558 | jorgemauricio/INIFAP_Course | /ejercicios/ej_26_groupDataFrames.py | 1,412 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 17 16:17:25 2017
@author: jorgemauricio
"""
# librerias
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
# crear un dataframe
dframe = DataFrame({'k1':['X','X','Y','Y','Z'],
'k2':['alpha','beta','alpha','beta','alpha'],
'dataset1':np.random.randn(5),
'dataset2':np.random.randn(5)})
# desplegar
dframe
# tomamos la columan dataset1 y lo agrupamos con la llave k1
group1 = dframe['dataset1'].groupby(dframe['k1'])
# desplegar el objecto
group1
# ahora podemos realizar operaciones en este objeto
group1.mean()
# podemos utilizar los nombres de las columnas para generar las llaves de los grupos
dframe.groupby('k1').mean()
# o multiples columnas
dframe.groupby(['k1','k2']).mean()
# podemos saber el tamaño del grupo con el metodo .size()
dframe.groupby(['k1']).size()
# podemos iterar entre los grupos
# por ejemplo:
for name,group in dframe.groupby('k1'):
print ("This is the %s group" %name)
print (group)
print ('\n')
# utilizando multiples llaves
for (k1,k2) , group in dframe.groupby(['k1','k2']):
print ("Key1 = %s Key2 = %s" %(k1,k2))
print (group)
print ('\n')
# se puede generar un diccionario de la informacion
group_dict = dict(list(dframe.groupby('k1')))
# desplegar el grupo con una 'X'
group_dict['X'] |
b900505abbd54b33687bd1af9c58d8e00443d541 | chintu0019/DCU-CA146-2021 | /CA146-test/markers/line-plot.py/line-plot.py | 1,218 | 4.09375 | 4 | #!/usr/bin/env python
import sys
n = 20
x1 = float(sys.argv[1])
y1 = float(sys.argv[2])
x2 = float(sys.argv[3])
y2 = float(sys.argv[4])
m = (y2 - y1) / (x2 - x1)
c = y1 - m * x1
def should_plot(x, y):
if x < x1 and x < x2: # Too far left.
return False
if x1 < x and x2 < x: # Too far right.
return False
if y < y1 and y < y2: # Too far down.
return False
if y1 < y and y2 < y: # Too far up.
return False
# These are just two formulations of the line formula:
#
# y = mx + c
# x = (y-c) / m (equivalent)
#
# The first form draws lines well if the line is closer to horizontal.
# The second form draws lines well if they are closer to vertical.
# int() rounds down. By adding 0.5, we get the nearest integer value.
return x == int((y - c) / m + 0.5) or y == int(m * x + c + 0.5)
# Print header line.
print " " + "-" * n
i = 0
while i < n:
y = n - i - 1
output = []
x = 0
while x < n:
if should_plot(x, y):
output.append("*")
else:
output.append(" ")
x = x + 1
# Build and print the current line.
print "|" + "".join(output) + "|"
i = i + 1
# Print footer line.
print " " + "-" * n
|
175d4fa4a648aa25846e0deb97033d1d7aac617a | MHM18/hm18 | /hmpro/zhangxiyang/homework/greatestcommondivisor.py | 367 | 3.953125 | 4 | a = input("输入第一个数字")
b = input("输入第二个数字")
a = int(a)
b = int(b)
def greatestcommondivisor(a, b):
if a > b:
smaller = b
else:
smaller = a
for i in range(1,smaller+1):
if((a % i == 0) and (b % i == 0)):
greatestcommondivisor = i
return greatestcommondivisor
print(greatestcommondivisor(a,b))
|
1e930f51d398c6692fe6fa8f3a8cb45695e3e274 | EOT123/AllEOT123Projects | /All Python Files Directory/Year2Tutorials/2018_08_21_screen_events001.py | 633 | 3.625 | 4 | import turtle # imports the turtle library
import random # imports the rankdom library
scr = turtle.Screen() # goes into turtle library and calls screen function
trt = turtle.Turtle() # creates turtle
def little_draw():
scr.tracer(10, 0)
myx = random.randrange(-360, 360)
myy = random.randrange(-360, 360)
randsize = random.randrange(50, 100)
trt.goto(myx, myy) # sends turtle to random x and y
trt.begin_fill()
trt.circle(randsize)
trt.end_fill()
scr.listen() # readies screen events
scr.update() # refreshes the screen
scr.onkey(little_draw, "a")
scr.mainloop() # keeps screen looping
|
4596c63bccd721402e76b45a41eeb9622803bc51 | sodaWar/MyPythonProject | /PycharmProjects/testPython/test_transmit_data.py | 822 | 3.78125 | 4 | # -*- coding:utf-8 -*-
a = 1
def changeInteger(a):
a = a+1
return a
print(changeInteger(a))
print(a)
b = [1,2,3]
def changeList(b):
b[1] = b[1] + 1
return b
print(changeList(b))
print(b)
# 第一个函数传的变量是整数变量,函数对变量进行操作,但是不会影响原来的变量,因为
# 对于基本数据类型的变量,变量传递给函数后,函数会在内存中复制一个新的变量,从而不影响原来的变量。(我们称此为值传递)
# 第二个函数传的变量是表,函数对表进行操作后,原来的表会发生变化,因为
# 对于表来说,表传递给函数的是一个指针,指针指向序列在内存中的位置,在函数中对表的操作将在原有内存中进行,
# 从而影响原有变量。 (我们称此为指针传递)
|
8ab2cd8ddbc86f6b1d5e1b261d69c6e82c5fab13 | panthercoding/Summer_Lecture6 | /flatEarth.py | 1,843 | 4.21875 | 4 | import numpy as np
""" helper function to calculate arc cosine given radians """
def arccosine(theta):
return np.arccos(theta)
class Point3D():
def __init__(self,x,y,z):
""" delete the below and finish the constructor method """
pass
def EuclideanDistance(self,other):
""" calculate the Euclidean distance between two points
and returns it (delete the below) """
return(0)
def greatCircleDistance(self,other):
""" calculate the great-circle distance between two points
located on a sphere centered at (0,0,0); formula on handout.
Return this great-circle distance.
make sure to calculate the distance of each point to origin,
and set r equal to the larger distance should they differ
(approximates distance for non-spheroid planet)"""
return(0)
""" prewritten method to print out a 3D coordinate """
def __str__(self):
return "<{},{},{}>".format(self.x,self.y,self.z)
def main():
Point1 = Point3D(-40,30,-20)
Point2 = Point3D(20,-30,40)
distance_Euclid = Point1.EuclideanDisatnce(Point2)
distance_GC = Point1.greatCircleDistance(Point2)
print("The Euclidean distance between {} and {} is equal to {}".format(Point1,Point2,distance_Euclid))
print("The great circle distance between {} and {} is equal to {}".format(Point1,Point2,distance_GC))
""" create some new points and try looking at a real life globe to model and estimate,
to the best of your mathematical dexterity, the 3D locations of certain cities
on the earth and calculate the great-circle (NOT EUCLIDEAN) distance and print it out
for reference, the radius of the aerth is approximately 4000 miles and you can presume
that the Earth has a fullty spheroid shape (actually an oblate spheroid)
if you are a flat earther, ignore this exercise all together"""
main() |
9225c73be056d7922353e44c38e64011be1e02e2 | MaryamNajafian/Tea_TF2.0 | /rnn_shapes.py | 2,701 | 3.625 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Input, Dense, Flatten, SimpleRNN
from tensorflow.keras.optimizers import SGD, Adam
from tensorflow.keras.models import Model
"""
RNN for Time series prediction:
It did not perform as autoregressive linear model
This is because RNN has too many parameters and hence flexibility
Linear regression:
* input shape: 2D array: NxT, output-shape: NxK
* i = Input(shape=(T,)) # input layer of shape T
* model.predict(x.reshape(1, -1))[0, 0]
RNN:
* input shape:3D array: NxTxD or NxTx1, output shape: NxK
* i = Input(shape=(T, D))
* i = Input(shape=(T,1)) # input layer of shape T if D=1
* model.predict(x.reshape(1, T, 1))[0, 0] because #samples=1, #feature dimensions=1 length=T
Unlike auto-regressive linear model which expects a a 2D array: an NxT array
The vanilla RNN model addresses time series problem using a 3D array of NxTxD
Keep track of the data shapes in RNN
1-load the data (for RNN data shape: NxTxD)
2-build/instantiate the model
3-train the model
4-evaluate the model
5-make predictions on unseen test data
"""
#%% Make some data
"""
Things you should automatically know and have memorized
N = number of samples
T = sequence length
D = number of input features
M = number of hidden units
K = number of output units
"""
N = 1
T = 10
D = 3
K = 2
X = np.random.randn(N, T, D)
#%% Make an RNN
M = 5 # number of hidden units
i = Input(shape=(T, D))
x = SimpleRNN(units=M)(i) # in RNNs default activation is not None it is tanh
x = Dense(units=K)(x)
model = Model(i,x)
#%% Get the output
Yhat = model.predict(X)
print(Yhat)
#%% See if we can replicate this output
# Get the weights first
model.summary()
# See what's returned
print(model.layers[1].get_weights())
#%% Check their shapes
# Should make sense
# First output is input > hidden
# Second output is hidden > hidden
# Third output is bias term (vector of length M)
a, b, c = model.layers[1].get_weights()
print(a.shape, b.shape, c.shape)
#%%
Wx, Wh, bh = model.layers[1].get_weights()
# Wx is (DxM), Wh is MxM, bh is is a (M,) and
# Wo and bo are assigned to output layer
Wo, bo = model.layers[2].get_weights()
#%% manual RNN calculation gives us same results as Yhat in simpleRNN
h_last = np.zeros(M) # initial hidden state
x = X[0] # the one and only sample
Yhats = [] # where we store the outputs
for t in range(T):
h = np.tanh(x[t].dot(Wx) + h_last.dot(Wh) + bh)
y = h.dot(Wo) + bo # we only care about this value on the last iteration
Yhats.append(y)
# important: assign h to h_last
h_last = h
# print the final output
print(Yhats[-1])
|
fcadee1c22eb8f77971a8c35320976f142918e2a | LiXiang02140105/Python_code | /8_returnfunc_bibao.py | 1,075 | 3.84375 | 4 | '''
返回函数
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
闭包的知识
也就是直接早
实际上,是因为在Python中,函数名 f 只是一个变量,相当于C中的指针,指向的是函数 f() 的存储位置
而,之后通过 是使用 f 还是 f()来知道是得到函数的地址还是函数计算之后的值
strip()
'''
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
print("f : ",f,f())
fs.append(f)
print("fs[{}]".format(i-1),fs[i-1])
return fs
def count1():
fs = []
for i in range(1, 4):
def f1():
return i*i
print("f1 : ",f1,f1())
fs.append(f1())
print("fs1[{}]".format(i-1),fs[i-1])
return fs
if __name__ == "__main__":
f1,f2,f3 = count()
f4,f5,f6 = count1()
print("f1 : ",f1,f1())
print("f2 : ",f2,f2())
print("f3 : ",f3,f3())
print("--------------")
print("f4 : ",f4)
print("f5 : ",f5)
print("f6 : ",f6)
|
c61b9df745407de1b3dd840e5aac9d32aa71cd06 | anishverma2/MyLearning | /MyLearning/Files/json_imports.py | 852 | 4.28125 | 4 | import json
'''
json data is very much like a dictionary
the json library help us to convert the json data to a dictionary easily
'''
file = open('friends_json.txt', 'r')
file_contents = json.load(file) #read files and turns it to a dictionary
file.close()
print(file_contents)
print(file_contents['friends'][0])
cars = [
{'make': 'Ford', 'model': 'fiesta'},
{'make': 'Ford', 'model': 'Focus'}
]
file = open('cars_json.txt', 'w')
json.dump(cars, file)
file.close()
my_json_string = '[{"name": "Alfa Romeo", "released": 1950}]'
incorrect_car = json.loads(my_json_string) #loads is used to read a json string into a dictionary
print(incorrect_car[0]['name'])
correct_car = json.dumps(incorrect_car) #dumps is used to load a dictionary as a string
print(type(correct_car)) #json allows us to use list or dictionary, not tuples |
544a636c28ce4f336313bfb80a95c2a66000d472 | freekdh/advent-of-code-2020 | /advent_of_code_2020/day9/solve.py | 1,704 | 3.828125 | 4 | import re
from itertools import combinations
def get_input_data(path_to_input_data):
with open(path_to_input_data) as input_file:
return list(map(int, input_file.read().splitlines()))
def is_the_sum_of_two_of_the_n_numbers(focal_number, n_numbers):
return any(
number1 + number2 == focal_number
for number1, number2 in combinations(n_numbers, 2)
)
def get_window_iterator(list_of_data, window_size):
return zip(*(list_of_data[n:] for n in range(window_size)))
def main():
input_data = get_input_data("advent_of_code_2020/day9/input.txt")
preamble = 25
result_part1 = next(
focal_numbers[-1]
for focal_numbers in get_window_iterator(
list_of_data=input_data, window_size=preamble + 1
)
if not is_the_sum_of_two_of_the_n_numbers(
focal_number=focal_numbers[-1], n_numbers=focal_numbers[:-1]
)
)
print(
f"{result_part1} is the first number that is not the sum of two of the {preamble} preamble numbers before"
)
for windows_size in range(2, len(input_data)):
try:
window_part2 = next(
window
for window in get_window_iterator(
list_of_data=input_data, window_size=windows_size
)
if sum(window) == result_part1
)
break
except StopIteration:
pass
print(
f"{min(window_part2) + max(window_part2)} is the sum of the smallest and largest number in the continguous range"
)
# TODO: should be able to do this more efficiently using previous evaluations
if __name__ == "__main__":
main() |
20249785b5439cba743d03f3c34f89b480bce47b | egorkravchenko13/python_homework | /Lab1/1.py | 788 | 3.734375 | 4 | import re
re_integer = re.compile("^\d*$")
def validator_1(pattern, promt):
a_value = input(promt)
while not bool(pattern.match(a_value)):
a_value = input(promt)
return a_value
def validator_2(prompt):
number = float(validator_1(re_integer, prompt))
return number
import math
num1 = validator_2("введите сторону a: ")
num2 = validator_2("введите сторону b: ")
num3 = validator_2("введите сторону c: ")
res2 = math.acos((num1*num1+num2*num2-num3*num3)/(2*num1*num2))
res1 = math.acos((num1*num1+num3*num3-num2*num2)/(2*num1*num3))
res3 = math.acos((num2*num2+num3*num3-num1*num1)/(2*num2*num3))
print("A: ", res1, math.degrees(res1))
print("B: ", res2, math.degrees(res2))
print("C: ", res3, math.degrees(res3)) |
116a700351d64f09dceb06c125cf969c806ea72d | KARABERNOUmohamedislem/First-Python-experience | /printing.py | 78 | 3.625 | 4 | print ("winter is coming")
age=input("hhfisod ")
age=int(age)*4
print (age) |
df27b442a9ecdfcb57a57ddf0341382743baad83 | iFission/Linear-Algebra | /rref.py | 1,616 | 4 | 4 | # finds the rref form of a matrix
from pprint import pprint # to print matrix row by row
# initialise a mxn matrix with 0s
def initialise(m,n):
zero_matrix = [[0 for x in range(n)] for y in range(m)]
return zero_matrix
def assign_matrix(matrix): # len(matrix) = row, len(matrix[0])= column
for x in range(len(matrix)):
for y in range(len(matrix[0])):
matrix[x][y] = float(input()) # pprint prints in separate rows in float, not int to allow for decimal places
return matrix
# reduces the input row matrix by making the first number 1
#def reduceRow(rowMatrix, r, y):
# rrow = []
# rrow.append(rowMatrix[r][y]/rowMatrix[r][r])
# return rrow
if __name__ == '__main__':
m, n = input("Enter m x n matrix, separated by space: ").split() # splits the output into 2 numbers
m, n = [int(x) for x in [m, n]] # list comprehension, converts to int
matrix = initialise(m,n)
matrix = assign_matrix(matrix)
pprint(matrix)
for r in range(m): # number of times matrix must be reduced / round
pprint(matrix)
# print("matrix is",matrix)
tempMatrix =[]
rrow=[]
for y in range(n):
# print("r is", r, "y is", y, "matrix[",r,"][",y,"] is", matrix[r][y], "matrix[",r,"][",r,"] is", matrix[r][r])
tempMatrix.append(matrix[r][y]/matrix[r][r])
rrow.append(tempMatrix)
# print("rrow is",rrow)
for x in range(m):
if x is not r:
# print("x is",x)
rrrow =[]
for y in range(n):
rrrow.append(matrix[x][y]-matrix[x][r]*rrow[0][y])
# print("rrrow is",rrrow)
rrow.append(rrrow)
matrix = []
matrix = rrow
matrix.reverse() # reverse the order of the matrix
pprint(matrix) |
de4e74ee1086c2afd01139bd6976e6163d4556f7 | salvadb23/SPD1.2 | /superheroes.py | 4,704 | 3.765625 | 4 | class Hero:
def __init__(self, name, starting_health=100):
self.name = name
self.starting_health = starting_health
self.current_health = starting_health
self.abilities = list()
self.armors = list()
self.deaths = 0
self.kills = 0
def add_ability(self, ability):
self.abilities.append(ability)
def attack(self):
sum = 0
for ability in self.abilities
sum += ability.attack()
return sum
def take_damage(self, damage):
self.current_health = self.current_health - damage
'''
This method should update self.current_health
with the damage that is passed in.
'''
def is_alive(self):
if self.current_health > 0:
return true
else
return false
'''
This function will
return true if the hero is alive
or false if they are not.
'''
def fight(self, opponent):
'''
Runs a loop to attack the opponent until someone dies.
'''
pass
def defend(self):
defense = 0
if self.current_health == 0
return 0
else:
for armor in self.armors
defense += armor.defend()
return defense
'''
This method should run the defend method on each piece of armor and calculate the total defense.
If the hero's health is 0, the hero is out of play and should return 0 defense points.
'''
pass
def take_damage(self, damage_amt):
'''
Refactor this method to use the new defend method and to update the number of deaths if the hero dies in the attack.
'''
pass
def add_kill(self, num_kills):
self.kills += num_kills
'''
This method should add the number of kills to self.kills
'''
pass
def fight(self, opponent):
'''
Refactor this method to update the number of kills the hero has when the opponent dies.
'''
pass
class Ability:
def __init__(self, name, max_damage):
self.name = name
self.max_damage = max_damage
def attack(self):
random_attack = random.randint(0, self.max_damage)
return random_attack
'''
Return a random attack value
between 0 and max_damage.
'''
class Weapon(Ability):
def attack(self):
random_attack_weapon = random.randint()
return random.randint(self.max_damage /2, self.max_damage)
"""
This method should should return a random value
between one half to the full attack power of the weapon.
Hint: The attack power is inherited.
"""
class Team:
def init(self, team_name):
'''Instantiate resources.'''
self.name = team_name
self.heroes = list()
def add_hero(self, Hero):
self.heroes.append(Hero)
'''Add Hero object to heroes list.'''
def remove_hero(self, name):
for hero in self.heroes:
if hero.name == name:
self.heroes.remove(hero)
else:
return 0
'''
Remove hero from heroes list.
If Hero isn't found return 0.
'''
def view_all_heroes(self):
for hero in self.heroes
print hero
'''Print out all heroes to the console.'''
pass
def attack(self, other_team):
'''
This function should randomly select a living hero from each team and have them fight until one or both teams have no surviving heroes.
Hint: Use the fight method in the Hero class.
'''
pass
def revive_heroes(self, health=100):
for hero in self.heroes:
hero.current_health = health
'''
This method should reset all heroes health to their
original starting value.
'''
pass
def stats(self):
'''
This method should print the ratio of kills/deaths for each member of the team to the screen.
This data must be output to the console.
'''
pass
class Armor:
def __init__(self, name, max_block):
'''Instantiate name and defense strength.'''
self.name = name
self.max_block = max_block
def block(self):
return random.randint(0, self.max_block)
'''
Return a random value between 0 and the
initialized max_block strength.
'''
pass
if __name__ == "__main__":
# If you run this file from the terminal
# this block is executed.
pass |
1a76675c23c150918b8657926d3ef00af9483e2b | daem-uni/dagdim-lab-informatica | /lab3/e3.py | 522 | 4.21875 | 4 | s = input("Inserire una stringa: ")
if s.isalpha():
print("La stringa contiene solo lettere.")
if s.isupper():
print("La stringa contiene solo lettere maiuscole.")
if s.islower():
print("La stringa contiene solo lettere minuscole.")
if s.isdigit():
print("La stringa contiene solo numeri.")
if s.isalnum():
print("La stringa contiene solo lettere e numeri.")
if s[0].isupper():
print("La stringa inizia con una lettera maiuscola.")
if s.endswith("."):
print("La stringa termina con un punto.") |
2ac30b1f7b133b60482faba41b5cb69529872515 | suhassrivats/Data-Structures-And-Algorithms-Implementation | /Problems/Leetcode/733_FloodFill.py | 1,764 | 3.703125 | 4 | class Solution:
def floodFill(self, image: List[List[int]], sr: int,
sc: int, newColor: int) -> List[List[int]]:
"""
Time Complexity:
=> O(M x N) // length of (rows * col) (OR)
=> O(n) // n is the number of pixels in the image
Space Complexity:
Input Space: O(n)
Auxiliary Space: O(n) size of the implicit call stack when calling dfs.
"""
# If newColor is the same as the starting_pixel, then there is nothing
# to do. Simply return the image as it is.
if newColor == image[sr][sc]:
return image
# Get values for rows, cols and starting_pixel
rows = len(image)
cols = len(image[0])
starting_pixel = image[sr][sc]
# DFS call
self.dfs(image, sr, sc, newColor, rows, cols, starting_pixel)
return image
def dfs(self, image, sr, sc, newColor, rows, cols, starting_pixel):
# Handle boundary cases
if sr < 0 or sr >= rows or sc < 0 or sc >= cols:
return
# If adjacent elements are not same as the starting_pixel
elif image[sr][sc] != starting_pixel:
return
# Update the pixel value to newColor
image[sr][sc] = newColor
# Check all its adjacent elements. Note that pixel value will be updated
# only if the adjacent values are same the starting_pixel value
self.dfs(image, sr-1, sc, newColor, rows, cols, starting_pixel) # Top
self.dfs(image, sr+1, sc, newColor, rows, cols, starting_pixel) # Bottom
self.dfs(image, sr, sc-1, newColor, rows, cols, starting_pixel) # Left
self.dfs(image, sr, sc+1, newColor, rows, cols, starting_pixel) # Right
|
8be81da05fb147528a6829c154b8e3e078b2cf3b | paranoidandryd/pyyyy | /ex14.py | 795 | 3.78125 | 4 | from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s! So good to see you." % user_name
print "How are you doing, %s? Are you doing well or poorly?" % user_name
status = raw_input(prompt)
if(status == "well"):
print "I'm so glad to hear that %s." % user_name
elif(status == "poorly"):
print "I'm so sorry to hear that %s." % user_name
else:
print "idk wat to say to that"
print "Where would you prefer to be right now %s?" % user_name
where = raw_input(prompt)
if(where=="home"):
print "omg me too"
else:
print "Oh, cool"
print "And what would you prefer to be doing?"
what = raw_input(prompt)
if(what=="sleeping"):
print "ughhh u killin me, me too!"
else:
print "Hm, sounds nice."
print """
I wish we were in %r doing %r too, %r.
""" % (where, what, user_name) |
a2ac5c856a1a5661a1d61202f4aa3140197e48cf | betaBison/learn-to-care | /covid.py | 2,568 | 3.9375 | 4 | ########################################################################
# Author(s): D. Knowles
# Date: 26 Jul 2021
# Desc: working with COVID-19 dataset
########################################################################
# import python modules that will be used in the code
import pandas as pd
import matplotlib.pyplot as plt
# file location of the CSV file
file_location = "./data/covid19.csv"
# read the CSV into a pandas dataframe object
df = pd.read_csv(file_location)
# print shape of dataframe
num_rows, num_cols = df.shape
print("Successfully imported ", num_rows, " rows and ",
num_cols, " columns and data.\n")
# print out all possible column headers
for col in df.columns:
# print(col)
pass
# get single column (series) of data from the dataframe
deaths = df["deaths_covid"]
# display number of deaths greater than 1000
num_large_deaths = sum(deaths > 1000)
# print the number of large deaths and largest death count
print("There were ", num_large_deaths, " reports of deaths >1000, "
"the largest of which was ", int(deaths.max()), ".")
# for plotting we will remove the outliers
df = df[df["deaths_covid"] < 1000]
# calculate the percentage of hospitals understaffed and
# add new column to dataframe
df["percent_understaffed"] = df["critical_staffing_shortage_today_yes"]\
/(df["critical_staffing_shortage_today_no"] \
+ df["critical_staffing_shortage_today_yes"])
# create histogram of the newly created dataframe column
df.hist(column="percent_understaffed", bins = 50)
# create new dataframes based on the percent of reporting hospitals
# that are understaffed
poorly_staffed = df[df["percent_understaffed"] >= 0.2]
well_staffed = df[df["percent_understaffed"] < 0.2]
# create a new figure that contains 1 row and 2 columns of subplots
fig, axes = plt.subplots(1,2)
# for the subplot at index 0, set the title
axes[0].title.set_text("well staffed")
# graph deaths vs. bed utilization for a well staffed hospital
well_staffed.plot.scatter(x = "inpatient_beds_utilization",
y = "deaths_covid",
c = "blue",
ax=axes[0])
# for the subplot at index 1, set the title
axes[1].title.set_text("poorly staffed")
# graph deaths vs. bed utilization for a poorly staffed hospital
poorly_staffed.plot.scatter(x = "inpatient_beds_utilization",
y = "deaths_covid",
c = "red",
ax=axes[1])
# have to include this line to show the plots and pause to view
plt.show()
|
8c3009e149d0786bc1c690185c23229df1bde0ad | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4058/codes/1602_842.py | 121 | 3.765625 | 4 | a=int(input("Digite um numero:"))
b=a//1000
b1= a%1000
c=b1//100
c1=b1%100
d=c1//10
d1=c1%10
e=d1//1
x=b+c+d+e
print(x)
|
9b7d6db0790265c9987c27de5693fd51ce57353c | ShramanJain/Computer-Society | /Basic/Check if A String is Palindrome or Not/SolutionByShraman.py | 188 | 3.609375 | 4 | def palin(str):
l = len(str)
n = int(l/2)
for i in range(1, n):
if str[i] != str[l - i - 1]:
return 'No'
return 'Yes'
str = input()
print(palin(str))
|
c96d84ed695de83fa9c4ce7bf9b41789ef335499 | joshualan/Notes | /python_notes/modules.py | 2,456 | 3.703125 | 4 | # Modules are one of the best and most natural ways to structure your code.
# They are an abstraction layer, which means we can separate code into parts
# that have related functionality or data. They're pretty easy to grasp, which
# means that it's also really easy to screw up.
# Here's some things that we should try to avoid:
# 1. Messy, circular dependencies. If class Spaceship needs to import Scotty
# to implement Spaceship.hullIntegrity() and Scotty needs to import Spaceship
# to answer Scotty.isHappy(), then it's a circular dependency.
#
# 2. Relying too much on global state or context. These can be changed by
# literally anything! Try to explicitly pass things that we depend on.
#
# 3. Spaghetti code. This means that our program has complicated flow,
# redundant code, and basically not understandable.
#
# 4. Ravioli code. This means we have a lot of very similar code in a lot
# of places. In an overzealous attempt to encapsulate and loosely couple code,
# foo() calls 5 other functions to access bar when once can import bar instead.
# Remember kids: simple > complex > complicated
# Now for example, let's use the collections's defaultdict as an example
import collections *
names = defaultdict(int)
# This means the interpreter will look for collections.py in the current path
# and throw an ImportError exception if iti doesn't exist. It also runs any
# top level statements in collections.py However, this example is bad
# though. Is defaultdict() part of collections? Is it a local function? This
# made code hard to read and blurred the lines between dependencies.
from collections import defaultdict
names = defaultdict(int)
# This is slightly better. It shows where defaultdict is coming from.
import collections
names = collections.defaultdict(int)
# This is pretty good. Though the from example was pretty terse, dozens of
# similar from mod import func will make it hard to read. This example
# makes it pretty clear where defaultdict is coming from, no matter how
# many imports.
# Packages are simply modules++. A directory is considered a package if it
# contains an __init__.py. This file's top-level statements will be ran when
# we try to import the package. For example, import pack.modu means we're gonna
# look for a directory called pack, run __init__.py's top level statements,
# find modu.py and run its top-level statements. __init__.py is good for keeping
# all package-wide definitions together.
|
6a0e5c1b2d83ec7a9691f601d9d792231254b1cd | jadeliu/interview_prep | /epi4.11_zip_single_list.py | 1,139 | 3.84375 | 4 | __author__ = 'qiong'
# epi 4.11
# start time 8:55 pm
# initial trial end time 10:15 pm
# initial trial time complexity O(n^2)
# space complexity O(1)? recursive O(n)?
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def zip_list(head):
if not head:
return None
n = 0
l1 = head
while l1:
n += 1
l1 = l1.next
return zip_list_helper(head, n)
def zip_list_helper(head, n):
print 'entering helper with n=%d'%n
if n==1 or n==2:
return head
l1 = head.next
if n==3:
head.next = l1.next
head.next.next = l1
l1.next = None
return head
l2 = head.next
r1 = head
r2 = None
count = n
while count>2:
r1 = r1.next
count -= 1
print 'r1=%d'%r1.val
r2 = r1.next
r1.next = None
l1.next = r2
r2.next = l2
l2 = zip_list_helper(l2, n-2)
return head
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
zip_list(a)
temp = a
while temp:
print temp.val
temp = temp.next
|
2b649ae8084d2266f8d55f18ec1b8aba0b58c303 | ccsreenidhin/Practice_Anand_Python_Problems | /Learning_python_AnandPython/Module/problem7.py | 564 | 4.09375 | 4 | #Problem 7: Write a function make_slug that takes a name converts it into a slug. A slug is a string where spaces and special characters are replaced by a hyphen, typically used to create blog post URL from post title. It should also make sure there are no more than one hyphen in any place and there are no hyphens at the biginning and end of the slug.
import re
def mkslug(s):
string = re.findall('\w+', s)
li = '-'.join(string)
return li
print(mkslug("hello world"))
print(mkslug("hello world!"))
print(mkslug(" --hello world--"))
|
06861a40e95ba77314c85f9b11fc66af889b41e4 | vijaymaddukuri/python_repo | /training/time_conversion.py | 413 | 3.84375 | 4 | def timeConversion(time):
if time[-2:] == "AM" and int(time[0:2]) < 12:
convTime = time[:-2]
elif time[-2:] == "AM" and int(time[0:2])==12:
convTime = '00' + time[2:8]
elif time[-2:] == "PM" and int(time[0:2])==12:
convTime = time[:-2]
else:
convTime = str(int(time[:2]) + 12) + time[2:8]
return convTime
convTime = timeConversion('12:40:22AM')
print(convTime) |
3cf083705d272ace6fa7e53109253cccb1170761 | ineed-coffee/PS_source_code | /LeetCode/17. Letter Combinations of a Phone Number(Medium).py | 713 | 3.53125 | 4 | class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dig2ch = {
"2":["a","b","c"],
"3":["d","e","f"],
"4":["g","h","i"],
"5":["j","k","l"],
"6":["m","n","o"],
"7":["p","q","r","s"],
"8":["t","u","v"],
"9":["w","x","y","z"]
}
answer=[]
for dig in digits:
if not answer:
for letter in dig2ch[dig]:
answer.append(letter)
else:
tmp=[]
for letter in dig2ch[dig]:
tmp+=[ch+letter for ch in answer]
answer=tmp
return answer
|
06193a95d64778b5d61cb5a48d57898fb86f190e | rimzimt/Trees-2 | /44_post_inorder.py | 1,290 | 3.828125 | 4 | # S30 Big N Problem #44 {Medium}
# LC pproblem - 106
# Recursive approach
# Construct Binary Tree from Inorder and Postorder Traversal
# Time Complexity : O(nlogn) n=no. of nodes in the tree
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
return self.helper(len(postorder)-1,0,len(inorder)-1,inorder,postorder)
def helper(self,postroot,instart,inend,inorder,postorder):
if postroot<0 or instart>inend:
return None
for i in range(instart,inend+1,1):
if inorder[i]==postorder[postroot]:
iindex=i
break
root=TreeNode(postorder[postroot])
root.left=self.helper(postroot-(inend-iindex)-1,instart,iindex-1,inorder,postorder)
root.right=self.helper(postroot-1,iindex+1,inend,inorder,postorder)
return root
|
7d59f1e6e06f9ef56d9a917db3612624ccd00693 | valvesss/ratata-crypto | /ratata.py | 2,247 | 3.8125 | 4 | class Ratata(object):
def __init__(self, desc, owner, amount):
self.desc = desc
self.owner = owner
self.amount = amount
self.payers = []
print("#1 Ratata created. Owner: {0} | Description: {1} | Amount: $ {2}".format(owner.name,desc,amount))
def assignLeader(self, leader):
self.leader = leader
print("Leader assigned for #1 Ratata: {0}".format(leader.name))
def addPayer(self, payer):
self.payers.append(payer)
print("Payer added for #1 Ratata: {0}".format(payer.name))
def validatePayersBalance(self):
paymentParticipants = 1 + len(self.payers)
self.splittedAmount = self.amount / paymentParticipants
# Leader
if self.leader.balance >= self.splittedAmount:
# Payers
for payer in self.payers:
if payer.balance < self.splittedAmount:
print("Ratata #1 error, payer {0} have not enough balance".format(payer.name))
return False
else:
print("Ratata #1 error, leader {0} have not enough balance".format(self.leader.name))
return False
print("Ratata #1 validated, all payers have enough balance")
return True
def transferWealth(self):
# Leader
self.leader.balance -= self.splittedAmount
self.owner.balance += self.splittedAmount
# Payers
for payer in self.payers:
payer.balance -= self.splittedAmount
self.owner.balance += self.splittedAmount
class User(object):
def __init__(self, name, balance):
self.name = name
self.balance = balance
## MOCK
# Create Users
users = []
users_name = ["Jon", "Mike", "Bob"]
balance = 80
for user in users_name:
users.append(User(user, balance))
for i in range(len(users)):
print("{0}'s balance: $ {1}".format(users[i].name,users[i].balance))
# Create Ratata
desc = "Table 10"
owner = users[0]
amount = 162
ratata = Ratata(desc, owner, amount)
ratata.assignLeader(users[1])
ratata.addPayer(users[2])
if ratata.validatePayersBalance():
ratata.transferWealth()
for i in range(len(users)):
print("{0}'s balance: $ {1}".format(users[i].name,users[i].balance))
|
2726ac64e3386ff62ce007e8ddda3dcf82fc947f | phamhung3589/LearnPython | /sorting/insertion_sort.py | 391 | 4.25 | 4 | def insertion(arr):
n = len(arr)
for i in range(1, n):
tmp = arr[i]
j = i-1
while j >= 0 and arr[j] > tmp:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = tmp
if __name__ == "__main__":
arr = [4, 3, 2, 10, 12, 1, 5, 6]
print("the array before sorting: \n", arr)
insertion(arr)
print("the array after sorting: \n", arr)
|
9c6dde5286c9d240ed926332c7c9fcca796128ad | Alexanderklau/Algorithm | /Everyday_alg/2021/01/2021_01_11/find-minimum-in-rotated-sorted-array-ii.py | 630 | 3.640625 | 4 | # coding: utf-8
__author__ = 'Yemilice_lau'
"""
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
注意数组中可能存在重复的元素。
示例 1:
输入: [1,3,5]
输出: 1
示例 2:
输入: [2,2,2,0,1]
输出: 0
"""
nums = [1,3,5]
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] < nums[right]:
right = mid
elif nums[mid] > nums[right]:
left = mid + 1
else:
right -= 1
print(nums[left]) |
8cf765d877bb5d7655550639418a963529c87340 | romf90/python-3-tasks | /python task1.py | 435 | 3.6875 | 4 | import numpy as np
def task1():
print ("Task 1:")
a=np.array([[2,2],[1,1],[3,2]])
b=np.array([[1,2,2],[2,1,2]])
c=np.zeros((a.shape[0],b.shape[1]), dtype=int)
size=c.shape
for row in range(size[0]):
for column in range(size[1]):
for mul in range(a.shape[1]):
c[row][column] += a[row][mul]*b[mul][column]
print (c)
if __name__ == "__main__":
task1() |
f7e4bad89403e4012e198214f81daa8a0a6c646a | Farhad16/Python | /Data Structure/List/zip.py | 268 | 4.25 | 4 | list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
# combine a list into a one list with a single tuple
x = list(zip(list1, list2))
print(x)
# zip can also add single character with the list as it takes a string which is iterable
y = list(zip("abcd", list1, list2))
print(y)
|
f71bed373178d0353a97ee6ce54b494798732369 | youngkey89/MDASO1 | /HW3/HW3A1.py | 2,077 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Define function
def f(x):
return np.exp(x)
x0 = 1
h_value = np.logspace(-15, 1, 17)
# Analytical Result
def df1_ana(x):
"first derivative"
return np.exp(x)
def df2_ana(x):
"second derivative"
return np.exp(x)
def df1_ff(x0, h):
'first derivative using Finite forward-difference approximation'
return (f(x0 + h) - f(x0))/h
def df1_cf(x0, h):
'first derivative using Finite center-difference approximation'
return (f(x0 + h) - f(x0-h))/(2*h)
def df1_com(x0, h):
'first derivative using complex step approximation'
return np.imag(f(x0 + 1j*h))/h
def df2_so(x0, h):
'second derivative using second order finite difference approximation'
return (f(x0 + h) - 2*f(x0) + f(x0 - h))/(h**2)
def df2_com(x0, h):
'second derivative using second order finite difference approximation'
return (2/(h**2))*(f(x0) - np.real(f(x0 + 1j*h)))
def error(dy, dy_ana):
'error calculation'
return abs(dy - dy_ana)/dy_ana
#First derivative calculation
dy11 = df1_ff(x0, h_value)
dy12 = df1_cf(x0, h_value)
dy13 = df1_com(x0, h_value)
dy1_ana = df1_ana(x0)
er11 = error(dy11, dy1_ana)
er12 = error(dy12, dy1_ana)
er13 = error(dy13, dy1_ana)
#Second derivative calculation
dy21 = df2_so(x0, h_value)
dy22 = df2_com(x0, h_value)
dy2_ana = df2_ana(x0)
er21 = error(dy21, dy2_ana)
er22 = error(dy22, dy2_ana)
plt.figure(1)
plt.plot(h_value, er11, 'b--', label='forward')
plt.plot(h_value, er12, 'r--', label='center')
plt.plot(h_value, er13, 'g--', label='complex')
plt.xscale("log")
plt.yscale("log")
plt.xlabel("pertubation step size")
plt.ylabel("error")
plt.title("first derivative approximation")
plt.legend()
plt.figure(2)
plt.plot(h_value, er21, 'b--', label='second order')
plt.plot(h_value, er22, 'r--', label='complex')
plt.xscale("log")
plt.yscale("log")
plt.xlabel("pertubation step size")
plt.ylabel("error")
plt.title("second derivative approximation")
plt.legend()
plt.show()
|
ac304ad1ae256b1e3ba1de3fc2ac672cedde5e32 | Samothrace-Shaddam/expense_tracker | /help_page.py | 920 | 3.59375 | 4 | '''
Contains help files for the program, if you're looking for the README,
go to the README.
'''
def main_help():
help_text = '''
Press the keys shown on the menu and hit enter to control different parts
of the program. Selections are not case sensitive. (Entering 'E' or 'e'
will both take you to the Enter menu.)
Enter 'q' from the main menu to quit the program. All data is saved at
entry time.
Specific control help can be found in the help (h) file of each
sub-console.
'''
print(help_text)
def enter_help():
help_text = '''
From the enter console, you can add expenses to your database.
In the current version, you must "initiate" a week before you can add
information to a day in that week. After initiating, go to (D) to
enter expenses. Data is saved after answering (N) no to the enter more
expenses prompt. If you have made a mistake, you can (C) cancel at this
time.
'''
print(help_text) |
5a9a74cb5f1e05caa878d0e2ceef29aee20af5f7 | devitasari/intro-python | /string.py | 729 | 4.09375 | 4 | #Let's Form a Sentence
word = "JavaScript"
second = "is"
third = "awesome"
fourth = "and"
fifth = "I"
sixth = "love"
seventh = "it!"
print word,second,third,fourth,fifth,sixth,seventh
#Index Accessing -1 by 1
word = 'wow JavaScript is so cool'
exampleFirstWord = word[0:3]
secondWord = word[4:14]
thirdWord = word[15:17]
fourthWord = word[18:20]
fifthWord = word[21:25]
print "First Word:", exampleFirstWord, "jumlah karakter:", len(exampleFirstWord)
print "Second Word:", secondWord, "jumlah karakter:", len(secondWord)
print "Third Word:", thirdWord, "jumlah karakter:", len(thirdWord)
print "Fourth Word:", fourthWord, "jumlah karakter:", len(fourthWord)
print "Fifth Word:", fifthWord, "jumlah karakter:", len(fifthWord)
|
0b0c3359f60549ce08245d9f9131a1917b6573d0 | Bigpig4396/Multi-Agent-Reinforcement-Learning-Environment | /env_Rescue/Python2/maze.py | 15,084 | 3.78125 | 4 | #! /usr/bin/env python3
'''
Random Maze Generator
Makes use of a radomized version of Kruskal's Minimum Spanning Tree (MST)
algorithm to generate a randomized mazes!
@author: Paul Miller (github.com/138paulmiller)
'''
import numpy as np
import os, sys, random, time, threading
# defined in disjointSet.py
import disjointSet as ds
class Maze:
# static variables
# Directions to move the player.
# Note, up and down are reversed (visual up and down not grid coordinates)
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1,0)
def __init__(self, width, height, seed, symbols, scaling):
'''
Default constructor to create an widthXheight maze
@params
width(int) : number of columns
height(int) : number of rows
seed(float) : number to seed RNG
symbols(dict) : used to modify maze symbols and colors
settings{
start, end, start_color, end_color, : start and end symbols and colors
wall_v, wall_h, wall_c, wall_color, : vertical,horizontal and corner wall symbols and colors
head, tail, head_color, tail_color : player head and trail symbols and colors
*_bg_color, : substitute _color with bg_color to set background colors
@return
Maze : constructed object
'''
assert width > 0; assert height > 0
self.init_symbols(symbols)
self.time_taken = False
self.timer_thread = None
self.is_moving = True # used as a semaphore for the update time thread
self.width = width
self.height = height
self.seed = seed
self.scaling = scaling
self.path = [] # current path taken
self.player = (0,0) # players position
# self.items = [(x,y)] #TODO?? Add a list of possible items to collect for points?
# Creates 2-D array of cells(unique keys)
# Grid is 2-D, and the unique ids are sequential, i
# so uses a 2-D to 1-D mapping
# to get the key since row+col is not unique for all rows and columns
# E.g.
# width = 5
# 1-D Mapping vs Naive
# grid[2][3] = 5*2+3 = 13 vs 2+3 = 6
# grid[3][2] = 5*3+2 = 17 vs 3+2 = 6 X Not unique!
# use 2D list comprehensions to avoid iterating twice
self.grid = [[(width*row + col) \
for row in range(0,height)]\
for col in range(0, width)]
# portals[key] = {keys of neighbors}
self.portals = {}
# generate the maze by using a kruskals algorithm
self.kruskalize()
def __repr__(self):
'''
Allows for print(maze)
@params
None
@return
String : Ascii representation of the Maze
'''
return self.to_str()
def to_str(self):
'''
Defines the string representation of the maze.
@return
Maze : constructed object
'''
s=''
for col in range(0, self.width):
s+=self.wall_c + self.wall_h
s+=self.wall_c+'\n'
# wall if region not the same
for row in range(0,self.height):
# draw S for start if at (0,0)
if row == 0:
s+=self.wall_v + self.start
else:
s+=self.wall_v + self.empty
# draw | if no portal between [row][col] and [row][col-1]
for col in range(1, self.width):
# if theres a portal between cell and left cell
if self.grid[col-1][row] in self.portals[self.grid[col][row]]:
# if portal remove wall
c = self.empty
else:
# if not portal draw vertical wall
c = self.wall_v
# if at [width-1][height-1] draw end marker or cell
if row == self.height-1 and col == self.width-1:
c += self.end
else: # draw cell
c += self.empty
s += c
s+=self.wall_v +'\n'
# draw - if not portal between [row][col] and [row+1][col]
for col in range(0, self.width):
# if edge above (visually below)
c =self.wall_h
key = self.grid[col][row]
# if not at last row, and theres a portal between cell and above cell
if row+1 < self.height and self.grid[col][row+1] in self.portals[key]:
c = self.empty
s+=self.wall_c + c
s+=self.wall_c +'\n'
s+=self.empty
return s
def to_np(self):
s = np.zeros((2*self.height+1, 2*self.width+1), dtype=np.int)
print(s.shape)
for col in range(0, 2*self.width+1):
s[0][col] = 1
for row in range(0, self.height):
s[2*row + 1][0] = 1
s[2*row + 1][1] = 0
for col in range(1, self.width):
if self.grid[col-1][row] in self.portals[self.grid[col][row]]:
# if portal remove wall
s[2*row+1][2*col] = 0
else:
# if not portal draw vertical wall
s[2*row+1][2*col] = 1
# if at [width-1][height-1] draw end marker or cell
if row == self.height-1 and col == self.width-1:
s[2*row+1][2*col+1] = 0
s[2*row+1][2*self.width] = 1
for col in range(0, self.width):
# if edge above (visually below)
c = 1
key = self.grid[col][row]
# if not at last row, and theres a portal between cell and above cell
if row+1 < self.height and self.grid[col][row+1] in self.portals[key]:
c = 0
s[2*row+2][2*col] = 1
if c == 1:
s[2 * row + 2][2 * col + 1] = 1
else:
s[2 * row + 2][2 * col + 1] = 0
s[2*row+2][-1] = 1
return s
def scale(self, map_np):
new_map_np = np.zeros((self.scaling * map_np.shape[0], self.scaling * map_np.shape[1]))
for i in range(map_np.shape[0]):
for j in range(map_np.shape[1]):
if map_np[i][j] == 1:
for k in range(self.scaling):
for l in range(self.scaling):
new_map_np[self.scaling * i + k][self.scaling * j + l] = 1
else:
for k in range(self.scaling):
for l in range(self.scaling):
new_map_np[self.scaling * i + k][self.scaling * j + l] = 0
return new_map_np
def portals_str(self):
'''
Returns a string containing a list of all portal coordinates
'''
i = 1
s = 'Portal Coordinates\n'
for key, portals in self.portals.items():
for near in portals.keys():
# print the cell ids
s += '%-015s' % (str((key, near)))
# draw 5 portals coordinates per line
if i % 5 == 0:
s+='\n'
i+=1
return s
def init_symbols(self, symbols):
#get symbol colors _color + bg_color
start_color = symbols['start_color'] if 'start_color' in symbols else ''
start_bg_color = symbols['start_bg_color'] if 'start_bg_color' in symbols else ''
end_color = symbols['end_color'] if 'end_color' in symbols else ''
end_bg_color = symbols['end_bg_color'] if 'end_bg_color' in symbols else ''
wall_color = symbols['wall_color'] if 'wall_color' in symbols else ''
wall_bg_color=symbols['wall_bg_color'] if 'wall_bg_color' in symbols else''
head_color = symbols['head_color'] if 'head_color' in symbols else ''
head_bg_color=symbols['head_bg_color'] if 'head_bg_color' in symbols else ''
tail_color = symbols['tail_color'] if 'tail_color' in symbols else ''
tail_bg_color = symbols['tail_bg_color'] if 'tail_bg_color' in symbols else ''
empty_color = symbols['empty_color'] if 'empty_color' in symbols else ''
# symbol colors
self.start = start_bg_color + start_color + symbols['start']
self.end = end_bg_color + end_color + symbols['end'] + empty_color
self.wall_h = wall_bg_color + wall_color + symbols['wall_h']
self.wall_v = wall_bg_color + wall_color + symbols['wall_v']
self.wall_c = wall_bg_color + wall_color + symbols['wall_c']
self.head = head_bg_color + head_color + symbols['head']
self.tail = tail_bg_color + tail_color + symbols['tail']
self.empty = empty_color+' '
def kruskalize(self):
'''
Kruskal's algorithm, except when grabbing the next available edge,
order is randomized.
Uses a disjoint set to create a set of keys.
Then for each edge seen, the key for each cell is used to determine
whether or not the the keys are in the same set.
If they are not, then the two sets each key belongs to are unioned.
Each set represents a region on the maze, this finishes until all
keys are reachable (MST definition) or rather all keys are unioned into
single set.
@params
None
@return
None
'''
# edge = ((row1, col1), (row2, col2)) such that grid[row][col] = key
edges_ordered = [ ]
# First add all neighboring edges into a list
for row in range(0, self.height):
for col in range(0, self.width):
cell = (col, row)
left_cell = (col-1, row)
down_cell = (col, row-1)
near = []
# if not a boundary cell, add edge, else ignore
if col > 0:
near.append((left_cell, cell))
if row > 0:
near.append( (down_cell, cell))
edges_ordered.extend(near)
# seed the random value
random.seed(self.seed)
edges = []
# shuffle the ordered edges randomly into a new list
while len(edges_ordered) > 0:
# randomly pop an edge
edges.append(edges_ordered.pop(random.randint(0,len(edges_ordered))-1))
disjoint_set = ds.DisjointSet()
for row in range(0, self.height):
for col in range(0,self.width):
# the key is the cells unique id
key = self.grid[col][row]
# create the singleton
disjoint_set.make_set(key)
# intialize the keys portal dict
self.portals[key] = {}
edge_count = 0
# eulers formula e = v-1, so the
# minimum required edges is v for a connected graph!
# each cell is identified by its key, and each key is a vertex on the MST
key_count = self.grid[self.width-1][self.height-1] # last key
while edge_count < key_count:
# get next edge ((row1, col1), (row2,col2))
edge = edges.pop()
# get the sets for each vertex in the edge
key_a = self.grid[edge[0][0]][edge[0][1]]
key_b = self.grid[edge[1][0]][edge[1][1]]
set_a = disjoint_set.find(key_a)
set_b = disjoint_set.find(key_b)
# if they are not in the same set they are not in the
# same region in the maze
if set_a != set_b:
# add the portal between the cells,
# graph is undirected and will search
# [a][b] or [b][a]
edge_count+=1
self.portals[key_a][key_b] = True
self.portals[key_b][key_a] = True
disjoint_set.union(set_a, set_b)
def move(self, direction):
'''
Used to indicate of the player has completed the maze
@params
direction((int, int)) : Direction to move player
@return
None
'''
assert(direction in [self.LEFT, self.RIGHT, self.UP, self.DOWN])
# if new move is the same as last move pop from path onto player
new_move = (self.player[0]+direction[0],\
self.player[1]+direction[1])
valid = False
# if new move is not within grid
if new_move[0] < 0 or new_move[0] >= self.width or\
new_move[1] < 0 or new_move[1] >= self.height:
return valid
player_key = self.width*self.player[1] + self.player[0]
move_key = self.width*new_move[1] + new_move[0]
#if theres a portal between player and newmove
if move_key in self.portals[player_key]:
self.is_moving = True
#'\033[%d;%dH' % (y x)# move cursor to y, x
head = '\033[%d;%dH' % (new_move[1]*2+2, new_move[0]*2+2) + self.head
# uncolor edge between (edge is between newmove and player)
edge = '\033[%d;%dH' % (self.player[1]*2+(new_move[1]-self.player[1])+2,\
self.player[0]*2+(new_move[0]-self.player[0])+2)
tail = '\033[%d;%dH' % (self.player[1]*2+2, self.player[0]*2+2)
end = '\033[%d;%dH' % ((self.height)*2+2, 0) +self.empty
# if new move is backtracking to last move then sets player pos to top of path and remove path top
if len(self.path) > 0 and new_move == self.path[-1]:
# move cursor to player and color tail, move cursor to player and color empty
self.player = self.path.pop()
# move cursor to player and color tail, move cursor to player and color empty
# uncolor edge between and remove tail
edge += self.empty
tail += self.empty
valid = False # moved back
# else move progresses path, draws forward and adds move to path
else:
self.path.append(self.player)
self.player = new_move
#move cursor to position to draw if ANSI
# color edge between and color tail
edge += self.tail
tail += self.tail
valid = True # successfully moved forward between portals
# use write and flush to ensure buffer is emptied completely to avoid flicker
sys.stdout.write(head+edge+tail+end)
sys.stdout.flush()
self.is_moving = False
return valid
def solve(self, position=(0,0)):
''' Uses backtracking to solve maze'''
if self.is_done():
return True
for direction in [self.LEFT, self.RIGHT, self.UP, self.DOWN]:
# try a move, move will return false if no portal of backward progress
if self.move(direction):
# after move, set new test position to be current player position
if self.solve(self.player):
return True
# if position changed
if position != self.player:
# move back from towards previos position
self.move((position[0]-self.player[0], position[1]-self.player[1]))
return False
def heuristic_solve(self, position=(0,0), depth=0, lookahead=10):
''' Use backtracking with iterative deepening to solve maze with a distance or randomized choice heuristic'''
if self.is_done():
return True
if depth > 0:
directions = [self.LEFT, self.RIGHT, self.UP, self.DOWN]
# sort by distance towards the end dist 0 is closest so ascending order
#heuristic
directions.sort(
#get manhatten distance
#key=lambda direction: (self.width-self.player[0]+direction[0]-1+self.height-self.player[1]+direction[1]-1)/2.0
#random
key=lambda direction: random.random()
)
for direction in directions:
# try a move, move will return false if no portal of backward progress
if self.move(direction):
# after move, set new test position to be current player position
if self.heuristic_solve(self.player, depth-1,lookahead):
return True
# if position changed
if position != self.player:
# move back from towards previos position
self.move((position[0]-self.player[0], position[1]-self.player[1]))
return False
else:
return self.heuristic_solve(self.player, lookahead, lookahead+1)
def start_timer(self):
self.is_moving = False
self.timer_thread = threading.Thread(target=self.timer_job)
self.timer_thread.start()
def kill_timer(self):
self.player = (self.width-1, self.height-1)
if self.timer_thread != None:
self.timer_thread.join()
def end_timer(self):
self.kill_timer()
return self.time_taken
def timer_job(self):
start_time = time.time()
# your code
# prints the current time at the bottom of the maze
while not self.is_done():
# if not currently writing move, print time at bottom
if not self.is_moving:
time_elapsed = time.time() - start_time
# delay on the update rate (only update every 10th of a second)
if time_elapsed -self.time_taken > 0.01:
self.time_taken = time_elapsed
# use write and flush to ensure buffer is emptied completely to avoid flicker
sys.stdout.write('\033[%d;%dHTime:%.2f' % (self.height*2+2, 0, self.time_taken))
sys.stdout.flush()
self.time_taken = time.time() - start_time
def is_done(self):
'''
Used to indicate of the player has completed the maze
@params
None
@return
True if player has reached the end
'''
return self.player == (self.width-1, self.height-1)
|
473d274ac4afc18690d37c1a01402a284305fe4d | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/M_Sunday/lesson08/circle.py | 2,110 | 3.875 | 4 | #!/usr/bin/python
from math import pi
class Circle(object):
@staticmethod
def entry_check(the__radius):
if isinstance(the__radius, (str, list, tuple, dict)):
raise TypeError("Radius/Diameter entry must be a single, positive, and "
"non-string value")
else:
if the__radius < 0:
raise ValueError("Radius/Diameter must be greater than 0")
else:
return the__radius
def __init__(self, the_radius):
self._radius = self.entry_check(the_radius)
def __repr__(self):
return "Circle({})".format(self._radius)
def __str__(self):
return "Circle with radius: {0:.6f}".format(float(self._radius))
def __add__(self, other):
new_circle = self._radius + other._radius
return Circle(new_circle)
def __rmul__(self, other):
new_circle = self._radius * other
return Circle(new_circle)
def __mul__(self, other):
new_circle = self._radius * other
return Circle(new_circle)
def __lt__(self, other):
return self._radius < other._radius
def __gt__(self, other):
return self._radius > other._radius
def __eq__(self, other):
return self._radius == other._radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, the_radius):
self._radius = self.entry_check(the_radius)
@property
def diameter(self):
return self._radius * 2.0
@diameter.setter
def diameter(self, diam):
self._radius = self.entry_check(diam) / 2.0
@property
def area(self):
return pi * self._radius**2
@classmethod
def from_diameter(cls, dia):
if isinstance(dia, (str, list, tuple, dict)):
raise TypeError("Diameter entry must be a single, positive, and "
"non-string value")
else:
if dia < 0:
raise ValueError("Diameter must be greater than 0")
else:
return cls(dia / 2.0)
|
04eeedfceeeac5d24380d683751509b495df5109 | TorpidCoder/Python | /PythonCourse/DataStructure/stacksBasics.py | 682 | 3.875 | 4 | __author__ = "ResearchInMotion"
class Stacks:
def __init__(self):
self.stack =[]
# pushing the element
def push(self,data):
return self.stack.insert(0,data)
# check if emepty
def isempty(self):
return self.stack == []
# pop the data
def pop(self):
if self.isempty():
return "Stack empty"
return self.stack.pop(0)
# check the data
def peek(self):
return self.stack[0]
# size of the data
def size(self):
return len(self.stack)
s1 = Stacks()
s1.push("sahil")
s1.push("nikki")
print(s1.peek())
print(s1.size())
print(s1.pop())
print(s1.pop())
print(s1.pop())
|
b71992fd3ffdc65a812bd5f440e01efc36602706 | v-profits/python_lessons | /1.9.py | 627 | 3.875 | 4 | s = 'C:\d\new'
print(s)
s = 'C:\d\\new'
print(s)
s = r'C:\d\new'
print(s)
s = 'Ry''thon'
print(s)
s = 'Ry'+'thon'
print(s)
s1 = 'Hello, '
s2 = 'world!'
s = s1 + s2
print(s)
name = 'John'
age = 20
print('My name is ' + name + " I'm " + str(age))
print("hi "*5)
s = 'Hello world!'
print(s[0]) # H
print(s[-1]) # !
print(s[-12]) # H
# s[0] = 'h' # нельзя изменить символ
s = 'Hello world!'
print(s[0:12]) # Hello world!
print(s[-1]) # !
print(s[0:5]) # Hello
print(s[:5]) # Hello
print(s[6:]) # world!
print(s[::2]) # Hlowrd
print(s[::-1]) # !dlrow olleH
print(s[:5] + s[6:]) # Helloworld! |
b4ec35a2c62bbdb036cff0e06bd29714cf3d8a9b | josesandino/Python-con-JS-2021-Polotic-Misiones | /Clase 3/Ejercicios/ejercicio2.py | 300 | 4 | 4 | #Escribe un programa Python que acepte 5 números decimales del usuario.
a = float(input("Escribe un número: "))
b = float(input("Escribe un número: "))
c = float(input("Escribe un número: "))
d = float(input("Escribe un número: "))
e = float(input("Escribe un número: "))
print(a, b, c, d, e) |
44a0a8c90a6ac14b092ff4c946e4c663beb87d46 | alulec/CYPAlexisCC | /libro/programa1_10.py | 259 | 3.734375 | 4 | # programa que calcula la base y superficie de un rectangulo
bas= int(input("cuanto mide la base: "))
alt= int(input("cuanto mide la altura: "))
sup= alt * bas
per= (2* alt) + (2* bas)
print("la superficies es de {} y su perimetro es de {}".format(sup,per))
|
e9ce77c99c7f142632513b50f8b9467c22f3dd14 | Dyndyn/python | /lab12.1.py | 1,646 | 4 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import math
class Point:
def __new__(cls, x=0, y=0):
inst = object.__new__(Point)
inst.x = x
inst.y = y
return inst
def __str__(self) -> str:
return "Point(x = {}, y = {})".format(self.x, self.y)
def diff_length(self, point) -> float:
return math.sqrt((self.x - point.x) ** 2 + (self.y - point.y) ** 2)
class Triangle:
def __new__(cls, a=Point(), b=Point(), c=Point()):
inst = object.__new__(Triangle)
inst.a = a
inst.b = b
inst.c = c
return inst
def __str__(self) -> str:
return "Triangle(a = {}, b = {}, c = {})".format(self.a, self.b, self.c)
def is_valid(self) -> bool:
x = self.a.diff_length(self.b)
y = self.a.diff_length(self.c)
z = self.b.diff_length(self.c)
return x + y > z and x + z > y and y + z > x
def perimeter(self) -> float:
x = self.a.diff_length(self.b)
y = self.a.diff_length(self.c)
z = self.b.diff_length(self.c)
return x + y + z
def square(self) -> float:
x = self.a.diff_length(self.b)
y = self.a.diff_length(self.c)
z = self.b.diff_length(self.c)
p = (x + y + z) / 2
return math.sqrt((p - x) * (p - y) * (p - z) * p)
point1 = Point(3,4)
point2 = Point()
print("{} - {} = {}".format(point1, point2, point1.diff_length(point2)))
a = Point()
b = Point(3, 0)
c = Point(0, 4)
triangle = Triangle(a,b,c)
print("is valid = {}".format(triangle.is_valid()))
print("perimeter = {}, square = {}".format(triangle.perimeter(), triangle.square()))
|
aaf4f8e342468f48551fe8b86d404c0f0fa7bccd | mayartmal/puche | /range_loop.py | 181 | 3.8125 | 4 | friends = ['kot', 'bot', 'mot']
congrats = 'Happy NY, '
for friend in friends:
print(congrats + friend)
print()
for i in range(len(friends)):
print(congrats + friends[i])
|
55c6739feb85462395d553cddb44a43304143cd2 | shreyasabharwal/Data-Structures-and-Algorithms | /Sorting/10.3SearchInRotatedArray.py | 1,870 | 4.1875 | 4 | '''10.3 Search in Rotated Array: Given a sorted array of n integers that has been rotated an unknown
number of times, write code to find an element in the array. You may assume that the array was
originally sorted in increasing order.
EXAMPLE
Input: find 5 in [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
Output: 8 (the index of 5 in the array)
'''
def searchArray(arr, num):
return searchRotatedArray(arr, 0, len(arr)-1, num)
def searchRotatedArray(arr, left, right, num):
mid = (left+right)//2
if num == arr[mid]:
return mid
if right < left:
return -1
if arr[left] < arr[mid]: # left is sorted in increasing order
if num > arr[left] and num < arr[mid]:
# search left side
return searchRotatedArray(arr, left, mid-1, num)
else:
# search right side
return searchRotatedArray(arr, mid+1, right, num)
elif arr[mid] < arr[right]: # right is sorted in increasing order
if num > arr[mid] and num < arr[right]:
# search right side
return searchRotatedArray(arr, mid+1, right, num)
else:
# search left side
return searchRotatedArray(arr, left, mid-1, num)
# if left and middle are identical, eg: [2, 2, 2, 3, 4, 2]
elif arr[mid] == arr[left]:
if arr[mid] != arr[right]: # search right if right!=left
return searchRotatedArray(arr, mid+1, right, num)
else:
# search both sides
index = searchRotatedArray(arr, left, mid-1, num)
if index == -1:
return searchRotatedArray(arr, mid+1, right, num)
else:
return index
return -1
if __name__ == "__main__":
#arr = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14]
arr = [2, 2, 2, 3, 4, 2]
num = 4
print(searchArray(arr, num))
|
c681600100cb54002bc05b4aeac6fadc6258197f | lxyshuai/leetcode | /82. Remove Duplicates from Sorted List II.py | 1,052 | 3.78125 | 4 | """
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
cur = head
pre = dummy
while cur:
next = cur.next
count = 1
while next:
if next.val == cur.val:
count += 1
next = next.next
else:
break
if count == 1:
pre = cur
cur = cur.next
else:
pre.next = next
cur = next
return dummy.next
|
9f1eae7fa7ca133c710468cd572b1c5252489824 | palenic/Automata | /my_fsa.py | 8,318 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""Finite state automata
Provides the Fsa class to configure and run finite state automata (FSA)
and a parser function to parse .txt files into a Fsa object.
"""
class Fsa:
"""
Create and use a finite state automata object.
Attributes
----------
states : list of string
the states of the automaton.
transitions : dict
a dictionary with tuples (start_state, input) as keys and
(end_state, output) as value describing the allowed transitions.
current_state : string
the current state of the automaton (initialized as initial_state when run_fsa is called).
initial_state : string
the initial state of the automaton.
final_states : list of string
the final states of the automaton.
out : list of string
the output generated by the execution (initialized as an empty list when run_fsa is called).
name : string
a nickname for the automaton. The default is "".
"""
def __init__(self,name=""):
"""
Initialize empty automaton.
Parameters
----------
name : string, optional
A nickname for the automaton. The default is "".
Returns
-------
None.
"""
self.states = []
self.transitions = {}
self.current_state = None
self.initial_state = None
self.final_states = []
self.out = []
self.name = name
def define_start(self, start_state):
"""
Set starting state for the automaton.
Parameters
----------
start_state : string
The start state. Must be part of the allowed states (states attribute).
Returns
-------
None.
"""
if start_state not in self.states:
print(start_state, "is not part of the automaton allowed states, so it can't be used as initial state")
else:
self.initial_state = start_state
def define_end(self, end_states):
"""
Set final state/s for the automaton.
Parameters
----------
end_states : list of strings
A list of allowed end states. Must be part of the allowed
states (states attribute). Can also be of length 1.
Returns
-------
None.
"""
for i in end_states:
if i not in self.states:
print(i, "is not part of the automaton allowed states, so it can't be used as final state")
else:
self.final_states.append(i)
def add_states(self, states):
"""
Add a list of states to the automaton.
Parameters
----------
states : list of strings
A list of allowed states for the automaton. Can also be of length 1.
Returns
-------
None.
"""
for i in states:
self.add_state(i)
def add_state(self, state):
"""
Add a single state to the automaton.
Parameters
----------
state : string
A single state for the automaton.
Returns
-------
None.
"""
self.states.append(state)
def add_transition(self, start, inp, end, out):
"""
Add a transition between two states to the automaton. If an invalid
transition is given it will not be added to the automaton.
Parameters
----------
start : string
The first state. Must be part of the allowed states (states attribute).
inp : string
The input that triggers the transition.
end : string
The next state. Must be part of the allowed states (states attribute).
out : string
What to write in the output (for transducers). If empty,
nothing will be written.
Returns
-------
None.
"""
#(init, input): final)
if start not in self.states or end not in self.states:
print("Invalid start or end state")
else:
self.transitions[(start,inp)] = (end, out)
def check_automaton(self):
"""
Helper function for run_fsa and my_pda.run_pda. Check that the
automaton has a start state, one or more final states and one or
more transitions.
Returns
-------
bool
True if all conditions are respected, False otherwise.
"""
if self.initial_state is None:
print("Please provide an initial state")
return False
elif self.final_states == []:
print("Please provide one or more final states")
return False
elif self.transitions == {}:
print("Please provide one or more transitions")
return False
else:
return True
def run_fsa(self, inp = None):
"""
Runs automaton on the provided input string. Ends if the automaton
does not have a start state, one or more final states and one or
more transitions, or if no input is given.
Parameters
----------
inp : TYPE, optional
DESCRIPTION. The default is None.
Returns
-------
int
-2 if the automaton is invalid or no input is given;
-1 if input was not accepted by the automaton;
0 if input was accepted.
"""
if self.check_automaton() == False:
print("Invalid automaton")
return -2
if inp is None:
print("Please provide an input string")
return -2
print("Running automaton",self.name,"on input: ", inp)
self.current_state = self.initial_state
self.out=[]
i = 0
L = len(inp)
#print(self.out)
while i<L:
cmd = inp[i]
try:
current_tr = self.transitions[(self.current_state, cmd)]
i += 1
except KeyError:
#print("No transition is defined for state and input tuple: ", e)
break
#print(self.transitions[(self.current_state, cmd)])
self.current_state = current_tr[0]
self.out.append(current_tr[1])
#print(self.out)
print("the final state is: ",self.current_state)
print("output: ", "".join(self.out))
if (self.current_state in self.final_states) and (i == L):
print("The automaton accepts this string")
return 0
else:
print("The automaton does not accept this string")
return -1
def from_txt_helper(automaton, file):
"""
Helper function for fsa_from_txt and my_pda.pda_from_txt
"""
with open(file) as f:
states = f.readline().strip()
states = states.split(",")
#print(states)
automaton.add_states(states)
start = f.readline().strip()
automaton.define_start(start)
end = f.readline().strip().split(",")
automaton.define_end(end)
return automaton
def fsa_from_txt(file, name=""):
"""
Builds a FSA from a configuration file in txt format, structured
as follows:
first line: all the states separates by commas
second line: initial state
third line: final states separated by commas
following lines: transitions with format:
start_state,input,end_state,output
IMPORTANT: spaces are not stripped
Parameters
----------
file : string
path to the .txt file.
name : string, optional
Nickname for the automaton. The default is "".
Returns
-------
automaton : Fsa
An object of class Fsa containing the automaton specified by the
states and transitions in the configuration file.
"""
automaton = Fsa(name)
automaton = from_txt_helper(automaton, file)
with open(file) as f:
for line in f.readlines()[3:]:
tr = line.strip().split(",")
automaton.add_transition(tr[0],tr[1],tr[2],tr[3])
return automaton
|
e4522cf8b50b4061e52798a4114df4e39896a8bb | chuckinator0/Projects | /scripts/BST_value.py | 2,715 | 4.125 | 4 | '''
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL.
For example,
Given the tree:
4
/ \
2 7
/ \
1 3
And the value to search: 2
You should return this subtree:
2
/ \
1 3
In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Reminder that a binary search tree is one where all values in the left subtree are less than the value of the current node,
# and all values in the right subtree are greater.
def searchBST(root,val):
'''
root: TreeNode object, root of the binary search tree
val: integer, the value we are looking for
output: return the node whose value is val. If no such node exits, return None
'''
stack = []
node = root
while node or stack:
# Traverse down the left side of the tree as much as possible, checking
# each node against the target value. Eventually, we reach a leaf and set
# node to None
while node:
if node.val == val:
return node
stack.append(node)
node = node.left
# At this point, we went past a leaf to None, so we step back to the leaf
node = stack.pop()
# Take a step to the right and then go back to the while loop to check nodes
# to the left as much as possible
node = node.right
# If we have survived to this point, it means we have traversed the whole tree
# and not found a node with the target value, so we return None
return None
## Here's a recursive implementation!
def searchBSTrecursive(root,val):
'''
root: TreeNode object, root of the binary search tree
val: integer, the value we are looking for
output: return the node whose value is val. If no such node exits, return None
'''
# if we have gone to a None node, then we have traversed a subtree that was supposed
# to contain the target value but failed to find it
if root is None:
return None
# if this node has the target value, return this node
if root.val == val:
return root
# if this node's value is greater than the target value, then
# the target value is either in the left subtree or it doesn't exist
if root.val > val:
return searchBSTrecursive(root.left,val)
# if this node's value is less than target, then the target value must be
# in the right subtree or doesn't exist
else:
return searchBSTrecursive(root.right,val)
|
b2e73437f39016dde1abbe8e3a1beb2ecb18a1e7 | SerhiiD/sudoku | /sudoku.py | 5,998 | 3.765625 | 4 | import random
class Board:
def __init__(self, size):
self.__size = size
self.__backstep_count = 0
self.__pointer = [0, 0]
self.__board = []
for rowi in range(self.__size ** 2):
self.__board.append([])
for columni in range(self.__size ** 2):
self.__board[rowi].append(0)
# self.__board[rowi].append(-1)
self.__free_numbers = []
for squarei in range(self.__size ** 2):
self.__free_numbers.append([])
# Генерация случайных чисел для квадрата
while len(self.__free_numbers[squarei]) < self.__size ** 2:
random_number = random.randrange(1, self.__size ** 2 + 1)
if random_number not in self.__free_numbers[squarei]:
self.__free_numbers[squarei].append(random_number)
def __str__(self):
s = ''
for row in self.__board:
for cell in row:
s += str(cell) + '\t'
s += '\n'
return s
def __check_number(self, number, row, column):
# Проверка по горизонтали
for i in range(len(self.__board[row])):
if self.__board[row][i] == number:
return False
# Проверка по вертикали
for i in range(len(self.__board)):
if self.__board[i][column] == number:
return False
# # Проверка в квадрате
# row_start = row//self.__size*self.__size
# column_start = column//self.__size *self.__size
#
# for rowi in range(row_start, row_start + self.__size):
# for columni in range(column_start, column_start + self.__size):
# if self.__board[rowi][columni] == number:
# return False
return True
def __pop_number_for_square(self, square_number):
if len(self.__free_numbers[square_number]) > 0:
return self.__free_numbers[square_number].pop()
def __put_number_for_square(self, square_number, number):
if len(self.__free_numbers[square_number]) >= 0:
self.__free_numbers[square_number].insert(0, number)
def __move_pointer_forward(self):
# Последняя ячейка на доске
if self.__pointer[0] == self.__size ** 2 - 1 and self.__pointer[1] == self.__size ** 2 - 1:
return False
if self.__pointer[1] < self.__size ** 2 - 1:
# Перейти к следующей колонке
self.__pointer[1] += 1
else:
# Перейти к следующей строке
self.__pointer[0] += 1
self.__pointer[1] = 0
return True
def __move_pointer_backward(self):
# Первая ячейка на доске
if self.__pointer[0] == 0 and self.__pointer[1] == 0:
return False
if self.__pointer[1] > 0:
# Перейти к предыдущей колонке
self.__pointer[1] -= 1
else:
# Перейти к предыдущей строке
self.__pointer[0] -= 1
self.__pointer[1] = self.__size ** 2 - 1
return True
def __step_forward(self):
square_number = ((self.__pointer[0] // self.__size) * self.__size) + (self.__pointer[1] // self.__size)
for attempt in range(len(self.__free_numbers[square_number])):
number = self.__pop_number_for_square(square_number)
if self.__check_number(number, self.__pointer[0], self.__pointer[1]):
self.__board[self.__pointer[0]][self.__pointer[1]] = number
self.__move_pointer_forward()
return True
else:
self.__put_number_for_square(square_number, number)
return False
def __step_backward(self):
if not self.__move_pointer_backward():
return False
square_number = ((self.__pointer[0] // self.__size) * self.__size) + (self.__pointer[1] // self.__size)
self.__put_number_for_square(square_number, self.__board[self.__pointer[0]][self.__pointer[1]])
self.__board[self.__pointer[0]][self.__pointer[1]] = 0
return True
def generate_board(self):
while self.__pointer[0] < self.__size ** 2 and self.__pointer[1] < self.__size ** 2:
# print(self.__pointer[0]*10+self.__pointer[1], (self.__size ** 2)*(self.__size ** 2))
# print(self.__pointer)
if not self.__step_forward():
stop_point = self.__pointer[:]
backstep_count = 1
while self.__board[stop_point[0]][stop_point[1]] == 0:
for i in range(backstep_count):
self.__step_backward()
for i in range(backstep_count + 1):
self.__step_forward()
backstep_count += 1
if backstep_count == self.__size ** 2 * self.__size ** 2:
print(backstep_count)
print(self.__free_numbers)
return
# print(backstep_count, str(self), sep='\n')
# for r in self.__free_numbers:
# print(r)
#
# self.__pointer = [self.__size**2-1, self.__size**2-1]
# while self.__step_backward():
# print()
#
# for r in self.__free_numbers:
# print(r)
def make_sudoku(size):
board = Board(size)
board.generate_board()
# print(board)
make_sudoku(3)
# for size in range(1, 42):
# start = time.time()
# make_sudoku(size)
# end = time.time()
# print(size, end - start, sep=': ')
|
7e189e936e27cf000597125a7eec80284f27f949 | EllyChanYiLing/github | /password entry.py | 233 | 3.984375 | 4 | password = 'a123456'
i = 3
while True:
pwd = input('Please input password:')
if pwd == password:
print('Correct Assess!')
break
else:
i = i - 1
print('Wrong Password! You still have ', i, 'chances')
if i ==0:
break |
72ab5f3c18b55166d12c235791d046b7b8b490a8 | doudou1234/MachineLearningAlgorithm | /python/Clustering/KMeansClustering.py | 6,506 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2017-02-13 09:03:42
# @Last Modified by: WuLC
# @Last Modified time: 2017-02-15 20:54:58
# Clustering with KMeans algorithm
import random
from math import sqrt
from PIL import Image,ImageDraw
from GetData import read_data
def pearson(v1,v2):
"""use pearson coeffcient to caculate the distance between two vectors
Args:
v1 (list): values of vector1
v2 (list): values of vector2
Returns:
(flaot):1 - pearson coeffcient, the smaller, the more similar
"""
# Simple sums
sum1=sum(v1)
sum2=sum(v2)
# Sums of the squares
sum1Sq=sum([pow(v,2) for v in v1])
sum2Sq=sum([pow(v,2) for v in v2])
# Sum of the products
pSum=sum([v1[i]*v2[i] for i in xrange(len(v1))])
# Calculate r (Pearson score)
num=pSum-(sum1*sum2/len(v1))
den=sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1)))
if den==0: return 0
return 1.0-num/den
def kMeans(blog_data, distance = pearson, k = 5):
m, n = len(blog_data), len(blog_data[0])
max_value = [0 for i in xrange(n)]
min_value = [0 for i in xrange(n)]
for i in xrange(m):
for j in xrange(n):
max_value[j] = max(max_value[j], blog_data[i][j])
min_value[j] = min(min_value[j], blog_data[i][j])
# initial random clusters
clusters = []
for i in xrange(k):
clusters.append([min_value[j] + random.random()*(max_value[j] - min_value[j]) for j in xrange(n)])
count = 0
previous_cluster_nodes = None
while True:
count += 1
print 'iteration count %s'%count
curr_cluster_nodes = [[] for i in xrange(k)]
for i in xrange(m):
closest_distance = distance(blog_data[i], clusters[0])
cluster = 0
for j in xrange(1, k):
d = distance(blog_data[i], clusters[j])
if closest_distance > d:
closest_distance = d
cluster = j
curr_cluster_nodes[cluster].append(i)
if curr_cluster_nodes == previous_cluster_nodes:
break
previous_cluster_nodes = curr_cluster_nodes
# modify the core of each cluster
for i in xrange(k):
tmp = [0 for _ in xrange(n)]
for node in curr_cluster_nodes[i]:
for j in xrange(n):
tmp[j] += blog_data[node][j]
clusters[i] = [float(tmp[j])/len(curr_cluster_nodes) for j in xrange(n)]
return clusters, curr_cluster_nodes
def scale_dowm(blog_data,distance=pearson,rate=0.01):
"""transform data in multiple-dimentional to two-dimentional
Args:
data (list[list[]]): blog data in the form of a two-dimentional matrix
distance (TYPE, optional): standark to caculate similarity between two vectors
rate (float, optional): rate to move the position of the nodes
Returns:
list[list[]]: position of nodes in a two dimentional coordinate
"""
n=len(blog_data)
# The real distances between every pair of items
real_list=[[distance(blog_data[i],blog_data[j]) for j in xrange(n)]
for i in xrange(n)]
# Randomly initialize the starting points of the locations in 2D
loc=[[random.random(), random.random()] for i in xrange(n)]
fake_list=[[0.0 for j in xrange(n)] for i in xrange(n)]
lasterror=None
for m in range(0,1000):
# Find projected distances
for i in range(n):
for j in range(n):
fake_list[i][j]=sqrt(sum([pow(loc[i][x]-loc[j][x],2)
for x in xrange(len(loc[i]))]))
# Move points
grad=[[0.0,0.0] for i in range(n)]
totalerror=0
for k in range(n):
for j in range(n):
if j==k or real_list[j][k] == 0: continue # acoid the case when real_list[j][k] == 0.0
# The error is percent difference between the distances
error_term=(fake_list[j][k]-real_list[j][k])/real_list[j][k]
# Each point needs to be moved away from or towards the other
# point in proportion to how much error it has
grad[k][0] += ((loc[k][0]-loc[j][0])/fake_list[j][k])*error_term
grad[k][1] += ((loc[k][1]-loc[j][1])/fake_list[j][k])*error_term
# Keep track of the total error
totalerror+=abs(error_term)
# print 'curr error {0}'.format(totalerror)
# If the answer got worse by moving the points, we are done
if lasterror and lasterror<totalerror: break
lasterror=totalerror
# Move each of the points by the learning rate times the gradient
for k in range(n):
loc[k][0] -= rate*grad[k][0]
loc[k][1] -= rate*grad[k][1]
return loc
def draw_clusters(blog_data, clusters, cluster_nodes, blog_names, jpeg_path = 'Clustering_data/mds2d.jpg'):
"""draw the result of KMeans clustering
Args:
blog_data (list[list]): blog data that had been transfromed into two-dimentional form
clusters (list[list]): center of clusters that had been transfromed into two-dimentional form
cluster_nodes (list[list]): nodes of each cluster
blog_names (list[str]): blog name corresponding to each node
jpeg_path (str, optional): path of the photo to be stored
Returns:
None
"""
img=Image.new('RGB',(2000,2000),(255,255,255))
draw=ImageDraw.Draw(img)
for i in xrange(len(clusters)):
for node in cluster_nodes[i]:
c_x,c_y = (clusters[i][0] + 0.5)*1000, (clusters[i][1] + 0.5)*1000
x, y =(blog_data[node][0]+0.5)*1000, (blog_data[node][1]+0.5)*1000
draw.line((c_x, c_y, x, y),fill=(255,0,0))
draw.text((x,y),blog_names[node],(0,0,0))
img.save(jpeg_path ,'JPEG')
if __name__ == '__main__':
cluster_num = 4
col_names, blog_names, blog_data = read_data('Clustering_data/data')
clusters, cluster_nodes = kMeans(blog_data, k = cluster_num)
for i in xrange(len(cluster_nodes)):
print '=============cluster %s==========='%i
for node in cluster_nodes[i]:
print blog_names[node]
scaled_data = scale_dowm(blog_data + clusters)
scaled_blog_data = scaled_data[:len(blog_data)]
scaled_clusters = scaled_data[len(blog_data):]
draw_clusters(scaled_blog_data, scaled_clusters, cluster_nodes, blog_names)
|
5683495e9a591b9701b392d2a701c40a738c79e4 | asavpatel92/algorithms | /sorting/MergeSort.py | 1,879 | 3.890625 | 4 | #===============================================================================
# implementation of mergesort
#===============================================================================
from math import floor
import random
#===============================================================================
# Takes in an array that has two sorted subarrays,
# from [startIndex..joinIndex] and [joinIndex+1..endIndex], and merges the array
#===============================================================================
def merge(array, startIndex, endIndex, joinIndex):
lowHalf = []
highHalf = []
k = startIndex
i = 0
j = 0
while ( k <= joinIndex):
lowHalf.append(array[k])
i += 1
k += 1
while ( k <= endIndex):
highHalf.append(array[k])
j += 1
k += 1
k = startIndex
i = 0
j = 0
while( i < len(lowHalf) and j< len(highHalf)):
if ( lowHalf[i] < highHalf[j]):
array[k] = lowHalf[i]
i += 1
else:
array[k] = highHalf[j]
j += 1
k += 1
while ( i < len(lowHalf)):
array[k] = lowHalf[i]
i += 1
k += 1
while ( j < len(highHalf)):
array[k] = highHalf[j]
j += 1
k += 1
#Takes in an array and recursively merge sorts it
def mergeSort(array, startIndex, endIndex):
if ( startIndex < endIndex):
midPoint = int(floor((startIndex + endIndex)/ 2))
mergeSort(array, startIndex, midPoint)
mergeSort(array, midPoint + 1, endIndex)
merge(array, startIndex, endIndex, midPoint)
def main():
n = 10
array = [random.randint(0, 100) for _ in range(n)]
print "Unsorted array is: ", array
mergeSort(array, 0, len(array) - 1)
print "Sorted array is: ", array
if __name__ == '__main__':
main() |
301a042f0f35cc7c0561027a66fca5e7b71624b7 | asmitrofanov74/Final-python-project-with-GUI | /Database.py | 2,273 | 3.5 | 4 | import sqlite3
from tkinter.messagebox import _show
def submit(*get_data):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("""INSERT INTO Users (User_name , Password , First_name , Last_name , Age , Address, City , Gender )
VALUES(?,?,?,?,?,?,?,?);""",
*get_data)
conn.commit()
conn.close()
def login(username, password):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
sql = "SELECT * FROM Users WHERE User_name = ? and Password = ?"
c.execute(sql, (username, password))
result = c.fetchall()
conn.commit()
conn.close()
return result
def check_user(username):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("SELECT * FROM Users WHERE User_name = ? ;", [username])
result = c.fetchall()
conn.commit()
conn.close()
return result
def get_records(sql="select * from users where User_name = _rowid_"):
conn = sqlite3.connect('pythonsqlite.db')
records = conn.cursor().execute(sql).fetchall()
conn.commit()
conn.close()
if len(records) == 0:
_show('Message', 'No data in records!')
return records
def confirm(*get_data):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("""INSERT INTO Appointments (User_ID , Appointment_date , Appointment_time , Doctor )
VALUES(?,?,?,?);""",
*get_data)
conn.commit()
conn.close()
def check_availability(date, time, doctor):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("SELECT Doctor FROM Appointments WHERE Appointment_date = ? AND Appointment_time = ? "
"AND Doctor =? "
, (date, time, doctor))
result = c.fetchall()
conn.commit()
conn.close()
return result
def check_app(date, time, user_id):
conn = sqlite3.connect('pythonsqlite.db')
c = conn.cursor()
c.execute("SELECT User_ID FROM Appointments WHERE Appointment_date = ? AND Appointment_time = ? "
"AND User_ID =? "
, (date, time, user_id))
result = c.fetchall()
conn.commit()
conn.close()
return result
|
bd551b1735ba0376dcd71a0b4f1413835c93c8b1 | ElleSowulewski/CIT228 | /Chapter10/learning_python.py | 537 | 4.0625 | 4 | filename = "Chapter10/learning_python.txt"
with open(filename) as textFile:
myText = textFile.read()
# From read()
print(myText)
# From for loop
with open(filename) as textFile:
for line in textFile:
print(line)
# From readlines() as list
with open(filename) as textFile:
myText = textFile.readlines()
for line in myText:
print(line)
#------------------------------------------
with open(filename) as textFile:
for line in textFile:
print(line.replace("Python", "C#"))
|
728911b303a41e4d0ef3f56ae47c954fbee40c34 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/CCSt130/lesson01/front_back.py | 688 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 2019
@author: Chuck Stevens :: CCSt130
"""
test_string = "Watermelon"
def front_back(str):
# Find length of the string and assign it to a variable
index = (len(test_string)-1)
print("\nWe're going to swap the first and last characters of our string.")
# Display string passed to the function
print("\nOur string is: '%s' " % (test_string))
# Concatenate the last char with the middle chars and the first char
var_swap = test_string[index]+test_string[1:(index-1)]+test_string[0]
# Display result on screen
print("\nThe result is: '%s' " % (var_swap))
front_back(test_string)
|
3ec8dba014d8ef19ec057a7855168eaf233bf5f3 | learnMyHobby/func-dict-while-for-python | /for/pattern.py | 344 | 3.984375 | 4 |
# F
# F F F
# F F F F F
# F F F F F F
# F F F F F F F F F
# F F F F F F F F F F F
current = "f"
stop = 2
rows = 6 # Number of rows to print numbers
for i in range(rows):
for j in range(1, stop):
print(current , end=' ')
print("")
stop += 2
|
cbbf8a818af7b40a6219fe7c451f626bcb45b086 | aluisq/Python | /estrutura_repeticao/ex7.py | 143 | 3.953125 | 4 | x = 1
soma = 0
while x <= 10:
y = abs(float(input("Digite um número: ")))
soma += y # soma = soma + y
x += 1
print((soma / 10))
|
26e9a4bae35ef522d8bdcc84244a5d4f2a0b8d43 | rczwisler/wispChallenge | /wisp_api/special_math.py | 2,218 | 3.921875 | 4 | '''
Module to computer special math:
f(n) = n + f(n-1) + f(n-2)
and provide a Blueprint for a Flask app with endpoint(s):
/specialMath/<int>
Functions:
special_math_get(str)
special_math_memoize(int)
special_math_iterative(int)
'''
from flask import Blueprint
bp = Blueprint("specialMath", __name__)
@bp.route("/specialMath/<value>", methods=["Get"])
def special_math_get(value):
'''
Take input from endpoint, convert to int and pass to special math solver
Parameters:
value(str): input from HTTP endpoint
Returns:
result(str): result of special math solver
'''
try:
result = special_math_iterative(int(value))
return str(result)
except (ValueError, TypeError):
return "Invalid input value. Must be a positive whole integer", 400
def special_math_memoize(value, memoize = None):
'''
Recursive special math solver with memoization
Parameters:
value(int): Input value to evaluate
memoize(dict): Dictionary of previously calculated values
Returns:
result(int): Result of special math f(n) = n + f(n-1) + f(n-2)
'''
if memoize is None:
memoize = {}
if value in memoize:
return memoize[value]
if value == 0:
return value
if value == 1:
return value
result = value + special_math_memoize(value-1, memoize) + special_math_memoize(value-2, memoize)
memoize[value] = result
return result
def special_math_iterative(value):
'''
Iterative special math solver.
f(n) = n + f(n-1) + f(n-2) = fibonacci(n+4) - (3+n)
credit/source of formula at https://oeis.org/A001924
Parameters:
value(int): Input value to evaluate
Returns:
result(int): Result of special math fibonacci(n+4) - (3+n)
'''
if value < 0:
raise ValueError
result = _fibonacci(value+4) - (3+value)
return result
def _fibonacci(value):
'''
Return the Nth fibonacci value
Parameters:
value(int): N to look up
Returns:
fib_a(int): the Nth fibonacci value
'''
fib_a,fib_b = 0,1
for _ in range(value):
fib_a,fib_b = fib_b,fib_a + fib_b
return fib_a
|
1c23baa3d4f2bc44e50c5ce1afbefc5dfa90e5e5 | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 3/Exercicio 3a/Algoritmo130_se41.py | 338 | 3.8125 | 4 | # Programa: Algoritmo130_se41.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 25/03/2020 - 12:06
# Updated:
value = float(input("Enter with the value: "))
if value > 0:
if value<=20:
tax = 45
else:
tax = 30
else:
tax = 0
print("What fuck is this?!")
discount = value + ((value*tax)/100)
print(discount)
|
773f3b389a7163d46c81503d44a8be6d530cc346 | betty29/code-1 | /recipes/Python/65445_Decorate_output_stream_printlike/recipe-65445.py | 801 | 3.953125 | 4 | class PrintDecorator:
"""Add print-like methods to any file-like object."""
def __init__(self, stream):
"""Store away the stream for later use."""
self.stream = stream
def Print(self, *args, **kw):
""" Print all arguments as strings, separated by spaces.
Take an optional "delim" keyword parameter, to change the
delimiting character.
"""
delim = kw.get('delim', ' ')
self.stream.write(delim.join(map(str, args)))
def PrintLn(self, *args, **kw):
""" Just like print(), but additionally print a linefeed.
"""
self.Print(*args+('\n',), **kw)
import sys
out = PrintDecorator(sys.stdout)
out.PrintLn(1, "+", 1, "is", 1+1)
out.Print("Words", "Smashed", "Together", delim='')
out.PrintLn()
|
ad788169bd7cc707689f188dfd852f720ce4cf90 | Hrishikesh-3459/leetCode | /prob_20_0.py | 311 | 3.6875 | 4 | def isValid(s):
x = []
ope = ['{', '(', '[']
clos = ['}', ')', ']']
if(s[-1] in ope):
return(False)
if(len(s) == 0):
return(True)
for i in s:
if(i in ope):
x.append(i)
# diff = list(set(s)^set(x))
# print(diff)
print(x)
isValid("()[]")
|
be37c8273bdbe38abf2738a8a9cba388af53ba3d | T0biasLJ/Mis_practicas | /math_clases.py | 1,960 | 4.03125 | 4 | import math
class Operacion:
def __init__(self,numero):
self.__numero=numero
def floor(self):
a=math.floor(self.__numero)
return f"{a}"
def ceil(self):
b=math.ceil(self.__numero)
return f"{b}"
def raiz(self):
c=math.sqrt(self.__numero)
return f"{c}"
def factor(self):
d=math.factorial(self.__numero)
return f"{d}"
def potencia(self):
pot=int(input("A que potencia lo quieres elevar"))
e=math.pow(self.__numero,pot)
return f"{e}"
SEPARADOR=("-"*40 + "\n")
while True:
print("ESTE PROGRAMA AYUDA A ELEVAR,DISMINUIR UN ENTERO,OBTENER RAIZ CUADRADA,FACTORIAL Y POTENCIAS")
print(SEPARADOR)
n=float(input("Dame un numero: ")) #Pedimos un nuemro al usuario
print(SEPARADOR)
print("QUE DESEAS HACER")
menu=int(input("""1:Elevar numero hacia arriba,2:Llevar el numero hacia abajo,3: Obtener la raiz cuadrada del numero,
4: Obtener el factorial, 5: Potenciar numero, 6:SALIR : """))
print(SEPARADOR)
#Comienza el menu "if"
if menu==1:
x=Operacion(n)
y=x.ceil()
print(f"El entero hacia arriba de {n} es {y}")
print(SEPARADOR)
elif menu==2:
x=Operacion(n)
y=x.floor()
print(f"El entero hacia abajo de {n} es {y}")
print(SEPARADOR)
elif menu==3:
x=Operacion(n)
y=x.raiz()
print(f"La raiz del numero {n} es de {y}")
print(SEPARADOR)
elif menu==4:
x=Operacion(n)
y=x.factor()
print(f"El factorial del numero {n} es de {y}")
print(SEPARADOR)
elif menu==5:
x=Operacion(n)
y=x.potencia()
print(f"El numero {n} elevado a la potencia dada es {y} ")
print(SEPARADOR)
elif menu==6:
break
print("Gracias por usar el programa :3")
|
4c42580f825c09327c011acd3d555194fe9ac632 | Freshield/LEARNING_PYTHON | /30_chp7_3_filter.py | 757 | 3.609375 | 4 | #30/123
def is_odd(n):
return n%2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9,10])))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['a','','b',None,'c',''])))
def _odd_iter():
n = 1
while True:
n = n+ 1
yield n
def _not_divisible(n):
return lambda x:x % n >0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n),it)
for e in primes():
if e < 100:
print(e)
else:
break
def is_palindrome(n):
return str(n)==str(n)[::-1]
output=filter(is_palindrome,range(1,1000))
print(list(output))
|
7a6e896703416bd81019052c229852022840f356 | Enigmamemory/submissions | /7/intro-proj1/jstrauss_lakabas/original_files/analysis01.py | 4,821 | 3.640625 | 4 | #!/usr/bin/python
print "Content-Type: text/html\n"
heading = "Justin Strauss and James Xu (Team Dream) <br>"
heading += "IntroCS2 pd 6 <br>"
heading += "HW26 <br>"
heading += "2013-04-22"
intro = "<h3> Background: </h3>"
intro += "We chose basketball because the playoffs of the NBA just started. <br>"
intro += "We thought it would be interesting to compare the best players to <br>"
intro += "ever play the sport with each other. At first we were comparing the <br>"
intro += "Player Efficiency Rating and the regular stat line of the players, <br>"
intro += "but we realized that there would be no way to compare them. So we <br>"
intro += "just tried to determine who was the greatest player of all time <br>"
intro += "(G.O.A.T). An obstacle was manually transferring data into a csv <br>"
intro += "file, which was tedious because there were 100 players. <br>"
link = "Click <a href=" + str("data01.py") + ">here</a> to view Justin's "
link += "data file. <br> Click <a href=" + str("http://lisa.stuy.edu/~james.xu/data01.py")
link += ">here</a> to view James's data file. <br> <h3> Table of Summary Data: </h3>"
conc = "<h3> Conclusion: </h3>"
conc += "After we had finished with our code, we saw that the results of our <br>"
conc += "project generally created the same ranking order of the People's <br>"
conc += "Choice Ranking order. However, there were exceptions. For example, <br>"
conc += "Bill Russell, who was ranked by the People's Choice Ranking as the <br>"
conc += "3rd best player of all time. However, after factoring in the Career <br>"
conc += "Efficiency Value, Bill Russell ended up as 27th on our modified list. <br>"
conc += "His Efficiency ranking was 67, far from his People's Choice Ranking. <br>"
conc += "The Efficiency is a composite basketball statistic that theoretically <br>"
conc += "shows how good the player is. However, this rating is criticized for <br>"
conc += "not fairly weighing the defensive contribution as much as the <br>"
conc += "offensive contribution of a player. Bill Russell has been regarded as <br>"
conc += "the greatest defensive player in the history of the NBA, so our <br>"
conc += "results have supported the criticism of the unbalance of offensive <br>"
conc += "and defensive contributions of the player. Eventually, the NBA might <br>"
conc += "be able to come up with a better way to produce a ranking system. <br>"
def statcomparer(dataset1, dataset2):
inStream = open(dataset1, "r") # creates file object (read buffer)
rawdata1 = inStream.read() # stores results in rawdata variable
inStream.close() # closes the buffer
data1 = rawdata1.split("\n")
inStream = open(dataset2, "r") # creates file object (read buffer)
rawdata2 = inStream.read() # stores results in rawdata variable
inStream.close() # closes the buffer
data2 = rawdata2.split("\n")
efflist = [] # a list containing the raw values for efficiency
for eff in data2:
if eff != "": # eliminates any possible "ghost cells"
eff = eff.split(",")
efflist.append(eff[1][:-2]) # efficiency is listed in the 2nd column
i = 0
comb = [] # combined people's choice + efficiency ranking
for rank in data1:
if rank != "": # eliminates any possible "ghost cells"
rank = rank.split(",")
comb.append(int(rank[0])+int(100-sorted(efflist).index(efflist[i])))
# must be subtracted from 100 because a higher
# efficiency yields a lower, or better, ranking
i += 1 # keeping a counter is cleaner than using list.index()
i = 0
html = heading + "<br>" + intro + "<br>" + link # the opening html tags
html += "<table border=" + str(1) + "> <td> Player Name </td> <td> People's"
html += " Choice Ranking </td> <td> Efficiency Raw Value </td> <td>"
html += "Efficiency Ranking </td> <td> People's Choice + Efficiency "
html += " Ranking </td> <td> Overall Player Worth Ranking </td>"
for rank in data1:
if rank != "": # eliminates any possible "ghost cells"
rank = rank.split(",")
html += "<tr> <td>" + str(rank[1][:-1]) + "</td> <td>"
html += str(rank[0]) + "</td> <td>" + str(efflist[i]) + "</td> <td>"
html += str(100-sorted(efflist).index(efflist[i])) + "</td> <td>"
html += str(int(rank[0])+int(100-sorted(efflist).index(efflist[i])))
# combined people's choice + efficiency ranking (see above)
html += "</td> <td>"+str((sorted(comb).index(comb[i]))+1)+"</td>"
# 1 must be added because the list starts from index 0
i += 1 # keeping a counter is cleaner than using list.index()
html += "</table> <br>" + conc + "<br>" # the closing html tags
print html
statcomparer("PlayerRank.csv", "PlayerEfficiency.csv")
|
78eac952952cf186c3a2416109e325642e653006 | hengdii/practice | /src/main/python/excelBatchInsert.py | 2,366 | 3.515625 | 4 | import pymysql
import xlrd
'''
连接数据库
args:db_name(数据库名称)
returns:db
'''
def mysql_link(de_name):
try:
db = pymysql.connect("localhost",
"root",
"1q2w3e4r",
de_name)
return db
except:
print("could not connect to mysql server")
'''
读取excel函数
args:excel_file(excel文件,目录在py文件同目录)
returns:book
'''
def open_excel(excel_file):
try:
book = xlrd.open_workbook(excel_file) # 文件名,把文件与py文件放在同一目录下
return book
except:
print("open excel file failed!")
'''
执行插入操作
args:db_name(数据库名称)
table_name(表名称)
excel_file(excel文件名,把文件与py文件放在同一目录下)
hui
'''
def store_to(db_name, table_name, excel_file):
db = mysql_link(db_name) # 打开数据库连接
cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor
sql1 = "truncate table "+table_name
cursor.execute(sql1)
book = open_excel(excel_file) # 打开excel文件
sheets = book.sheet_names() # 获取所有sheet表名
for sheet in sheets:
sh = book.sheet_by_name(sheet) # 打开每一张表
row_num = sh.nrows
print(row_num)
list = [] # 定义列表用来存放数据
for i in range(1, row_num): # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1
row_data = sh.row_values(i) # 按行获取excel的值
value = (row_data[0], row_data[1], row_data[2], row_data[3], row_data[4])
list.append(value) # 将数据暂存在列表
# print(i)
sql = "INSERT INTO " + table_name + " (sku_id,supplier_id,\
deductio_type,billing_type,deduction_value)VALUES(%s,%s,%s,%s,%s)"
cursor.executemany(sql, list) # 执行sql语句
db.commit() # 提交
list.clear() # 清空list
print("worksheets: " + sheet + " has been inserted " + str(row_num) + " datas!")
cursor.close() # 关闭连接
db.close()
if __name__ == '__main__':
store_to('finance_calculate', 'billing_rule', 'billingRule.xlsx')
|
296dd75cbc77a834515929bc0820794909fb9e54 | sdaless/pyfiles | /CSI127/shift_left.py | 414 | 4.3125 | 4 | #Name: Sara D'Alessandro
#Date: September 12, 2018
#This program prompts the user to enter a word and then prints the word with each letter shifted left by 1.
word = input("Enter a lowercase word: ")
codedWord = ""
for ch in word:
offset = ord(ch) - ord('a') - 1
wrap = offset % 26
newChar = chr(ord('a') + wrap)
codedWord = codedWord + newChar
print("Your word in code is: ", codedWord)
|
efbbca18d032dde58d8b9e14c1003628c7babeee | roidelapluie/hiera-sorter | /hiera_sorter.py | 658 | 3.5 | 4 | #!/usr/bin/python
import sys
import os.path
# Check if at least one argument is passed
if len(sys.argv) <= 1:
print "File argument needed";
sys.exit(0);
# Loop over arguments ignoring first one (is filename of script)
for arg in sys.argv[1:]:
# Check if file passed actually exists
if not os.path.isfile(arg):
print "%s is not a file. Quiting..." % str(arg)
sys.exit(0);
# [DEBUG] Some debug stuff
#print "Filename: %s" % str(arg)
# Our array
# Read file
with open(arg, 'rw') as file:
arrayBlock_counter = 0;
data = file.readlines();
# Loop over every line and try to bundle in blocks
for line in data:
print line;
|
16870618af92301f5d494b836c65dc148005ab0e | ozbek94/blackjackoyunu | /KaraAlperen/2KaraAlperen1.py | 2,963 | 3.6875 | 4 | import random
kartlar = [2,3,4,5,6,7,8,9,10,11]
bakiye = 100
print("---------------------------------------")
print (" ***KARA ALPEREN***")
print("---------------------------------------")
print("\n")
while True:
acik_Kart = random.choices(kartlar, k=2)
rakip_Kart = random.choices(kartlar, k=2)
rakip_skor = rakip_Kart[0] + rakip_Kart[1]
sayi = 0
if bakiye > 0:
print("Bakiyeniz : " +str(bakiye))
print(" Oyuna başlama için '1' e bas : ")
sayi = acik_Kart[0] + acik_Kart[1]
islem = int(input())
else:
print("***GAME OVER***")
break
if(islem == 1) :
print("Kartlarınız : " + str(acik_Kart))
if sayi == 21 :
print("tebrikler KaraALPEREN yaptınız kazandınız")
bakiye = bakiye + 50
elif sayi < 21 :
while True :
print("Kart çekmek için '1'e sonucu görmek için '2' ye basınız")
islem1 = int(input())
if islem1 == 1 :
yeni_Kart = random.choices(kartlar, k=1)
sayi = sayi + yeni_Kart[0]
if sayi > 21 :
print("Açılan kart : ")
print(yeni_Kart)
print("/n Skorunuz : ")
print(sayi)
print("21' i gectiniz gitti paranız")
bakiye = bakiye - 50
break
else:
if sayi == 21:
print("tebrikler KaraALPEREN yaptınız kazandınız")
bakiye = bakiye + 50
break
else:
print("Yeni kartınız : ")
print(yeni_Kart)
print(sayi)
if rakip_skor + 2 < 21:
rakip_skor = rakip_skor +2
elif islem1 == 2 :
print("Skorunuz = " )
print(sayi)
print("Rakip Skor = ")
print(rakip_skor)
if rakip_skor < sayi :
print("Tebrikler, alın size 50$")
bakiye = bakiye + 50
break
elif rakip_skor == sayi :
print("Yenen yok bir dahakine")
break
else:
print("Gitti 50$ ...")
bakiye = bakiye - 50
break
else:
print("Geçerli işlem giriniz...")
else:
print("baştannn") |
231e2d77328f66cd8e68d1f6b214a80b98d7d0af | eschenfeldt/h1b_data_processing | /src/input_format.py | 3,299 | 3.734375 | 4 | """
Generate and store information about the structure of an input file, primarily
the locations of columns of interest.
"""
import re
class InputError(Exception):
pass
class Concept:
"""Constants representing the types of data we need for this problem."""
STATUS = 'status'
WORK_STATE = 'state'
SOC_CODE = 'soc_code'
SOC_NAME = 'soc_name'
class ColumnInfo:
"""Store information about a data column of interest, to aid in finding it
in a particular input file.
"""
@property
def index(self):
"""Index of the column for this data."""
return self._indices[0]
@property
def fallbacks(self):
"""Index of other columns that might contain this data."""
return self._indices[1:]
def __init__(self, name, known_names, pattern):
"""Column or columns representing a particular piece of data.
Arguments:
name -- name of this piece of data
known_names -- names known to correspond to the desired data; the
first of these to match will be used
pattern -- fallback regex pattern to match if no known names are
found
"""
self.name = name
self._known_names = known_names
self._pattern = pattern
self._indices = None
def find_indices(self, columns):
"""Find the indices for this piece of data in the given columns."""
indices = []
for name in self._known_names:
if name in columns:
indices.append(columns.index(name))
# If these don't match, search using a case-insensitive regex
for j, col in enumerate(columns):
if re.search(self._pattern, col, flags=re.IGNORECASE):
indices.append(j)
if not indices:
mes = 'No columns match for {} or "{}"'.format(
self._known_names, self._pattern
)
raise InputError(mes)
self._indices = indices
class InputFormat:
"""
Store the locations of columns of interest in a particular input file.
"""
def __init__(self, header):
"""Given the header row of an input file, parse format."""
columns = header.split(';')
info = {}
info[Concept.STATUS] = ColumnInfo(
Concept.STATUS,
['CASE_STATUS', 'STATUS'],
r'status'
)
info[Concept.WORK_STATE] = ColumnInfo(
Concept.WORK_STATE,
['WORKSITE_STATE', 'LCA_CASE_WORKLOC1_STATE'],
r'work.*state'
)
info[Concept.SOC_CODE] = ColumnInfo(
Concept.SOC_CODE,
['SOC_CODE', 'LCA_CASE_SOC_CODE'],
r'soc.*code'
)
info[Concept.SOC_NAME] = ColumnInfo(
Concept.SOC_NAME,
['SOC_NAME', 'LCA_CASE_SOC_NAME'],
r'soc.*name'
)
for col_info in info.values():
col_info.find_indices(columns)
self._info = info
def index(self, concept):
"""Get the primary index for the desired concept."""
return self._info[concept].index
def fallbacks(self, concept):
"""Get the fallback indices for the desired concept."""
return self._info[concept].fallbacks
|
f1270d64cfc5d3fd60f802dd3718654f4a0bf201 | HinataHinata/SimpleTensorflow | /Slides/slides_01.py | 1,972 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
' simple tensorflow demo '
__author__ = 'zhuchao'
import tensorflow as tf
# first tensorflow program
hello = tf.constant('Hello,Tensorflow')
sess = tf.Session()
result = sess.run(hello)
print(result) # result b'Hello,Tensorflow'
print(result.decode('utf-8')) # Hello,Tensorflow
print(result.decode('gb2312')) # Hello,Tensorflow
sess.close() # 关闭 Session
x = 3
y = 5
op1 = tf.add(x,y)
op2 = tf.multiply(x,y)
op3 = tf.add(op1,op2)
with tf.Session() as sess:
result = sess.run(op3)
print(result) # (3+5)+(3*5) = 23
# useless Graph 中 不需要计算的部分在 session.run() 的时候不真正的执行 已节约计算资源。
x = 2
y = 3
add_op = tf.add(x,y)
useless = tf.multiply(x,add_op)
mul_op = tf.multiply(x,y)
pow_op = tf.pow(add_op,mul_op)
with tf.Session() as sess:
result = sess.run(pow_op)
print(result) # 15625
#session.run()可以接收list参数 结果以list返回
x = 2
y = 3
add_op = tf.add(x,y)
useless = tf.add(x,add_op)
mul_op = tf.multiply(x,y)
pow_op = tf.pow(add_op,mul_op)
with tf.Session() as sess:
result_pow,result_useless = sess.run([pow_op,useless])
print(result_pow,result_useless) # 15627 7
# tensorflow 有可能会将图拆分成几块,分配到不同的CPU,GPU,或者是不同的设备上去运行。
# 虽然有办法创建多个 Graph 但是在tensorflow 中尽量只创建一个 Graph
# 01 多个图的计算需要多个 session 每个 session 默认都会使用所有的可用计算资源。 02 多个 Graph 之间不太容易传递数据 03更好的选择是在一个图中使用不连接的子图
# tf.Graph() 支持创建多个图 在使用多个图时,需要先将要使用的图设置为default。
g = tf.Graph()
with g.as_default():
x = tf.add(3,5)
# sess = tf.Session(graph=g)
# result = sess.run(x)
# sess.close()
with tf.Session(graph=g) as sess:
result = sess.run(x)
print(result)
# 获取默认的 Graph g1 = tf.get_default_graph()
|
11ec986377e6f971c4128759dc06874ef6c22d04 | Mplaban/MNIST-Train | /main.py | 2,878 | 3.78125 | 4 |
# Homecoming (eYRC-2018): Task 1A
# Build a Fully Connected 2-Layer Neural Network to Classify Digits
# NOTE: You can only use Tensor API of PyTorch
from nnet import model
# TODO: import torch and torchvision libraries
# We will use torchvision's transforms and datasets
import torch
import torchvision
from torchvision import transforms, datasets
from random import randint
from matplotlib import pyplot as plt
# TODO: Defining torchvision transforms for preprocessing
# TODO: Using torchvision datasets to load MNIST
# TODO: Use torch.utils.data.DataLoader to create loaders for train and test
# NOTE: Use training batch size = 4 in train data loader.
train = datasets.MNIST('./data',train=True,download=True,
transform=transforms.Compose([transforms.ToTensor()]))
test = datasets.MNIST('./data',train=False,download=True,
transform=transforms.Compose([transforms.ToTensor()]))
trainset= torch.utils.data.DataLoader(train,batch_size=4,shuffle=True)
testset= torch.utils.data.DataLoader(test,batch_size=10000,shuffle=True)
# NOTE: Don't change these settings
device = "cuda:0" if torch.cuda.is_available() else "cpu"
# NOTE: Don't change these settings
# Layer size
N_in = 28 * 28 # Input size
N_h1 = 256 # Hidden Layer 1 size
N_h2 = 256 # Hidden Layer 2 size
N_out = 10 # Output size
# Learning rate
lr = 0.001
# init model
net = model.FullyConnected(N_in, N_h1, N_h2, N_out, device=device)
# TODO: Define number of epochs
N_epoch = 40 # Or keep it as is
# TODO: Training and Validation Loop
# >>> for n epochs
## >>> for all mini batches
### >>> net.train(...)
## at the end of each training epoch
## >>> net.eval(...)
# TODO: End of Training
# make predictions on randomly selected test examples
# >>> net.predict(...)
batch_size=4
trainset=list(trainset)
for i in range(len(trainset)):
trainset[i][0]=trainset[i][0].view(batch_size,-1)
accuracy = 0;
for epoch in range(N_epoch):
print("Epoch ",epoch+1)
cre_l=[]
a=[]
for i in range(len(trainset)):
cressloss,acc,_=net.train(trainset[i][0],trainset[i][1],lr,False)
cre_l.append(cressloss)
a.append(acc)
total_loss=sum(cre_l)/len(cre_l)
total_acc=sum(a)/len(a)
print('loss: ', total_loss)
print('accuracy: ', total_acc)
torch.save(net,'model.pt')
#TESTING MODEL
batch_size_test=10000
test_loader=list(testset)
for i in range(len(test_loader)):
test_loader[i][0]=test_loader[i][0].view(batch_size_test,-1)
for i in range(len(test_loader)):
net.eval(test_loader[i][0],test_loader[i][1])
#PREDICTIONS FROM TRAINED MODEL
predict_loader = torch.utils.data.DataLoader(test,batch_size=10, shuffle=True)
batch_size_predict=10
predict_loader=list(predict_loader)
for i in range(len(predict_loader)):
predict_loader[i][0]=predict_loader[i][0].view(batch_size_predict,-1)
a=randint(0,len(predict_loader))
prediction_v,pred=net.predict(predict_loader[a][0])
print(pred)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.