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 |
|---|---|---|---|---|---|---|
5ddd34c57c11a654a74f96da8370922eacbe87d3 | Helloworld616/algorithm | /SWEA/Homework/1206_View/sol5.py | 815 | 3.515625 | 4 | # 교수님 해설 2
import sys
sys.stdin = open('input.txt')
T = 10
for tc in range(1, T+1):
# 아파트 단지의 가로 길이
length = int(input())
buildings = list(map(int, input().split()))
# 조망권 확보된 집
total = 0
idx = 2
while idx < length-2: # for은 index 마음대로 조절 못 함!
# 5개 집
l1, l2, current, r1, r2 = [buildings[idx+n] for n in range(-2, 3)]
sides = [l1, l2, r1, r2]
highest = sides[0]
for side in sides:
if side > highest:
highest = side
# 확보!
if current > highest:
total += current - highest
idx += 3 # 뒤 두 개 집은 어차피 view가 안 좋음
else:
idx += 1
print('#{} {}'.format(tc, total)) |
9892e00f8b08b5d3ab5ff89d60f7e6eb2bedf918 | Yuziquan/LeetCode | /Problemset/next-permutation/next-permutation.py | 830 | 3.5 | 4 |
# @Title: 下一个排列 (Next Permutation)
# @Author: KivenC
# @Date: 2018-07-19 21:21:29
# @Runtime: 44 ms
# @Memory: N/A
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
flag = False
for i in range(len(nums)-2, -1, -1):
if nums[i] < nums[i+1]:
flag = True
break
if flag:
for j in range(len(nums)-1, i, -1):
if nums[j] > nums[i]:
nums[i], nums[j] = nums[j], nums[i]
break
for j in range(0, (len(nums) - i)//2):
nums[i+j+1], nums[len(nums)-j-1] = nums[len(nums)-j-1], nums[i+j+1]
else:
nums.reverse()
|
4073e7c1bbe7db5dc02128f7cdd79833412b7534 | PierreVieira/URI | /Python/Grafos/1466 - Percurso em Árvore por Nível.py | 2,202 | 3.796875 | 4 | """
Autor: Pierre Vieira
Data da submissão: 24/02/2020 15:12:27
"""
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None # Referência para o nó à esquerda
self.right = None # Referência para o nó à direita
def __str__(self):
return str(self.data)
class BinaryTree:
def __init__(self, data=None, node=None):
if node:
self.root = node
elif data: # se o usuário especificou o nó
node = TreeNode(data)
self.root = node # Raiz da árvore
else:
self.root = None
class BinarySearchTree(BinaryTree):
def insert(self, value):
"""
Faz a inserção de um nó em uma árvore binária de busca.
:param value: valor a ser inserido.
:return: None
"""
no = TreeNode(value)
parent = None # determina o pai do novo nó a ser inserido
x = self.root # x começa na raiz
cont_altura = 0
while x is not None: # enquanto x diferente de vazio
parent = x
cont_altura += 1
if value < x.data: # se o valor informado é menor que x
x = x.left # desça pela direita
else: # se não
x = x.right # desça pela esquerda
if parent is None: # se não tinha nada na árvore (sem raíz)
self.root = no # defina uma nova raíz
elif value < parent.data: # se o valor é menor que o parent
parent.left = no # insira o nó à esquerda do parent
else: # se não
parent.right = no # insira o nó à direita do parent
lista_alturas.append((cont_altura, no.data))
qtde_casos_teste = int(input())
def saida():
print('Case {}:'.format(c + 1))
for d in range(len(lista_alturas) - 1):
print(lista_alturas[d][1], end=' ')
print(lista_alturas[len(lista_alturas) - 1][1], end='\n\n')
for c in range(qtde_casos_teste):
lista_alturas = []
n = int(input())
arvore_binaria_de_busca = BinarySearchTree()
for v in map(int, input().split()):
arvore_binaria_de_busca.insert(v)
lista_alturas.sort()
saida()
|
a4c4a610e198328dda067a6430d7114f7789cc1b | Cenibee/PYALG | /python/fromBook/chapter6/linked_list/16_add_two_numbers/16-m-2.py | 1,297 | 3.859375 | 4 | from typing import List
class ListNode:
def __init__(self, val=0, next=None, list=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
upper = 0
result = l1
while l1:
node_num = l1.val + upper
if l2:
node_num += l2.val
l2 = l2.next
upper, l1.val= divmod(node_num, 10)
if not l1.next and not l2:
if upper > 0:
l1.next = ListNode(1)
break
elif not l1.next and l2:
l1.next, l1, l2 = l2, l2, l1.next
else:
l1 = l1.next
return result
def list_to_list_node(list: List) -> ListNode:
node = None
for i in range(-1, ~len(list), -1):
node = ListNode(list[i], node)
return node
def print_node(node: ListNode):
while node.next is not None:
print(node.val)
node = node.next
print(node.val)
sol = Solution()
print_node(
sol.addTwoNumbers(
list_to_list_node([2, 4, 3]),
list_to_list_node([5, 6, 3])))
print_node(
sol.addTwoNumbers(
list_to_list_node([9, 9, 9, 9]),
list_to_list_node([9, 9, 9, 9, 9, 9, 9]))) |
1c266d9f8a888c2a994f09130326e33ca704b437 | farooq-teqniqly/docker-name-generator | /docker_name_generator.py | 1,662 | 3.78125 | 4 | """
A Docker style name generator.
"""
import io
import random
from itertools import islice
def __read_file(path, target_set):
"""
Reads a file and appends each line to a list.
Args:
path: The path to the file to read.
target_set: The set to append each line to.
Returns:
None
"""
with io.open(path, "r", encoding="utf8") as lines:
try:
for line in lines:
target_set.add(line.replace(" ", "").strip())
except UnicodeDecodeError:
pass
def load_files(names_file, nouns_file):
"""
Loads a names and nouns file.
Args:
names_file: The path to the names file.
nouns_file: The path to the nouns file.
Returns:
A two element tuple. The first element is a list containing
the names.
The second element is a list containing the nouns.
The lengths of each list is limited to 1000 elements.
"""
max_results_to_return = 1000
names = set()
nouns = set()
__read_file(names_file, names)
__read_file(nouns_file, nouns)
return list(islice(names, max_results_to_return)), list(islice(nouns, max_results_to_return))
def generate_name(names_nouns_tuple):
"""
Generates a Docker style name in the format 'name_noun'.
Args:
names_nouns_tuple: An two element tuple.
The first element is a list containing the names.
The second element is a list containing the nouns.
Returns:
A name in the format 'name_noun'.
"""
names, nouns = names_nouns_tuple
return f"{random.choice(names)}_{random.choice(nouns)}".lower()
|
443ef5abe9f885880a26c1a0e0baebbe57a8d4d1 | yaodingyd/PyIC | /questions/kth_to_last_node_in_singly_linked_list.py | 560 | 3.78125 | 4 | # Write a function kth_to_last_node() that takes an integer k and the head_node of a singly-linked list, and returns the kth to last node in the list.
# Assume k will not always be valid
def solution(k, head):
if k < 1:
raise ValueError('Can not find node less than first to last')
list_length = 1
cur = head
while cur.next:
cur = cur.next
list_length += 1
if k > list_length:
raise ValueError('k is larger than length of list')
index = list_length - k
cur = head
for i in range(index):
cur = cur.next
return cur |
1ea28dc90459ba15269ce329f9ba3d858fb1fc1a | rtl251/inventory-mgmt-app | /products_app/app.py | 6,855 | 3.890625 | 4 | import csv
import os
def menu(username, products_count):
# this is a multi-line string, also using preceding `f` for string interpolation
menu = f"""
-----------------------------------
INVENTORY MANAGEMENT APPLICATION
-----------------------------------
Welcome {username}!
There are {products_count} products in the database.
operation | description
--------- | ------------------
'List' | Display a list of product identifiers and names.
'Show' | Show information about a product.
'Create' | Add a new product.
'Update' | Edit an existing product.
'Destroy' | Delete an existing product.
'Reset' | Reset list to original state.
""" # end of multi- line string. also using string interpolation
return menu
def read_products_from_file(filename="products.csv"):
filepath = os.path.join(os.path.dirname(__file__), "db", filename)
#print(f"READING PRODUCTS FROM FILE: '{filepath}'")
products = []
with open(filepath, "r") as csv_file:
reader = csv.DictReader(csv_file) # assuming your CSV has headers, otherwise... csv.reader(csv_file)
for row in reader:
#print(row["name"], row["price"])
products.append(dict(row))
return products
def write_products_to_file(filename="products.csv", products=[]):
filepath = os.path.join(os.path.dirname(__file__), "db", filename)
#print(f"OVERWRITING CONTENTS OF FILE: '{filepath}' \n ... WITH {len(products)} PRODUCTS")
with open(filepath, "w", newline="") as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=["id","name","aisle","department","price"])
writer.writeheader()
for p in products:
writer.writerow(p)
def reset_products_file(filename="products.csv", from_filename="products_default.csv"):
print("RESETTING DEFAULTS")
products = read_products_from_file(from_filename)
write_products_to_file(filename, products)
def run():
# First, read products from file...
products = read_products_from_file() # reading products from file and passing it into a variable called products
# Then, prompt the user to select an operation...
print(menu(username="Inventory Manager", products_count=len(products))) #TODO instead of printing, capture user input
choice =(input("Please select an operation:")).lower()
print(choice)
if choice == "list":
print("* * * * * * * * * * * * * * *")
print(f"LISTING {len(products)} PRODUCTS")
print("* * * * * * * * * * * * * * *")
for p in products:
print("#" +p["id"] +": " + p["name"])
elif choice == "show":
accepted_ids = [(p["id"]) for p in products] # list of accepted IDs: 1-20
showproduct=[] #new list to add selected product
productid=(input("Ok. Please provide Product ID:")) #ask for product ID
while productid not in accepted_ids:
productid = input("Product ID Not Found. Please provide valid product ID:")
showproduct = [product for product in products if product["id"] == productid]
print(showproduct)
elif choice == "create":
accepted_ids = [int((p["id"])) for p in products]
newproductid = max(accepted_ids)+1
newname=(input("Ok. Please provide the name of the new product:"))
newaisle=(input("Ok. Please provide the aisle of the new product:"))
newdepartment=(input("Ok. Please provide the department of the new product:"))
while True:
try:
newprice=(input("Ok. Please provide the price of the new product:"))
while newprice != '{0:.2f}'.format(float(newprice)):
newprice=((input("PRICE NOT IN 'x.xx' FORMAT. PLEASE PROVIDE PRICE IN 'x.xx' FORMAT:")))
products.append({"id": str(newproductid),"name": newname,"aisle": newaisle, "department": newdepartment, "price":newprice})
showproduct = [product for product in products if product["id"] == str(newproductid)]
print("* * * * * * * * * * * * * * *")
print("CREATING NEW PRODUCT")
print("* * * * * * * * * * * * * * *")
print(showproduct)
break
except ValueError:
print("PRICE NOT IN 'x.xx' FORMAT. PLEASE PROVIDE PRICE IN 'x.xx' FORMAT:")
elif choice == "update":
accepted_ids = [(p["id"]) for p in products] # list of accepted IDs: 1-20
updateid=(input("Ok. Please provide the ID of the product you want to update:"))
while updateid not in accepted_ids:
updateid = input("Product ID Not Found. Please provide valid product ID:")
updatename=(input("Ok. What is the product's new name?"))
updateaisle=(input("Ok. What is the product's new aisle?"))
updatedepartment=(input("Ok. What is the product's new department?"))
while True:
try:
updateprice=(input("Ok. What is the product's new price?"))
while updateprice != '{0:.2f}'.format(float(updateprice)):
updateprice=((input("PRICE NOT IN 'x.xx' FORMAT. PLEASE PROVIDE PRICE IN 'x.xx' FORMAT:")))
mutateproduct = [product for product in products if product["id"] == updateid][0]
mutateproduct["name"]= updatename
mutateproduct["aisle"]= updateaisle
mutateproduct["department"]= updatedepartment
mutateproduct["price"]= updateprice
print("ITEM #" + str(mutateproduct["id"]) + " NOW UPDATED IN INVENTORY!")
print(mutateproduct)
break
except ValueError:
print("PRICE NOT IN 'x.xx' FORMAT. PLEASE PROVIDE PRICE IN 'x.xx' FORMAT:")
elif choice == "destroy":
accepted_ids = [(p["id"]) for p in products]
destroyid=input("What is the ID of the product that you want to destroy?")
while destroyid not in accepted_ids:
destroyid = input("Product ID Not Found. Please provide valid product ID:")
destroyproduct = [product for product in products if product["id"] == destroyid][0]
print("DELETED PRODUCT #" + str(destroyproduct["id"]) + " FROM INVENTORY!")
del products[products.index(destroyproduct)]
elif choice == "reset":
reset_products_file()
return
else:
print("Sorry, the operation you selected is not recognized. Please select one of the following: 'List, 'Show', 'Create', 'Update', 'Destroy', or 'Reset'")
write_products_to_file(products=products)
# only prompt the user for input if this script is run from the command-line
# this allows us to import and test this application's component functions
if __name__ == "__main__":
run()
|
9230ddefd5e07920c6ac534dbbd067129e73dfd6 | AlexRuadev/python-bootcamp | /17 - Python Pdf Spreadsheets/csv_python.py | 520 | 3.78125 | 4 | import csv
data = open('example.csv', encoding='utf-8')
# Convert it into csv data
csv_data = csv.reader(data)
# reformat into a python object list of lists
data_lines = list(csv_data)
# print(data_lines)
# get our column label
data_lines[0]
# print the number of lines of our csv file
len(data_lines)
for line in data_lines[:5]:
print(line)
# Grqb 10th column, on the 3rd line
data_lines[10][3]
# all emails, located on line 3
all_emails = []
for line in data_lines[1:15]:
all_emails.append(line[3]) |
dffa82fbe867832ac61f5e3e73645648b9be3439 | samhithaaaa/PreCourse_2 | /Exercise_4.py | 836 | 4.21875 | 4 | def merge_list(a,b):
result = []
l, r = len(a), len(b)
i = j =0
while(i<l and j<r):
if(a[i]<b[j]):
result.append(a[i])
i = i+1
else:
result.append(b[j])
j = j+1
print("result",result+ a[i:] + b[j:])
return result + a[i:] + b[j:]
def mergeSort(arr):
length = len(arr)
if(length==2):
if(arr[0]<arr[1]):
return arr
else:
return arr[::-1]
elif(length==1):
return arr
left = mergeSort(arr[:int(length/2)])
right = mergeSort(arr[int(length/2):])
if(left is not None or right is not None):
a = merge_list(left,right)
return a
arr = [12, 11, 13, 5, 6, 7]
# print ("Given array is", end="\n")
# print(arr)
# print("Sorted array is: ", end="\n")
print(mergeSort(arr))
|
2030b6afbc4f8210d5d84bdd77d719fedb916be4 | manishask112/Applied-Algorithms | /Selection Problem/SelectionProblem.py | 2,029 | 4.1875 | 4 | import sys
#Merge Sort Algorith from Programming Assignment
def merge_sort(arr,low,high):
if low!=high:
mid=(low+high)/2
merge_sort(arr, low, mid)
merge_sort(arr, mid+1, high)
merge(arr,low,mid,high)
return arr
def merge(arr,low,mid,high):
temp= [None]*len(arr)
i=low
j=mid+1
k=low
while i<=mid and j<=high:
if arr[i][1]<=arr[j][1]:
temp[k]=arr[i]
k=k+1
i=i+1
else:
temp[k]=arr[j]
k=k+1
j=j+1
while i<=mid:
temp[k]=arr[i]
k=k+1
i=i+1
while j<=high:
temp[k]=arr[j]
k=k+1
j=j+1
for i in range(low,high+1):
arr[i]=temp[i]
#Job Selection Function
def selection_problem(start_state):
# Data Structure for Dynamic Programming
dynamic_max_weight=[-1]*len(start_state)
dynamic_max_weight[0]=start_state[0][2]
for i in range(1,len(start_state)):
low=0
high=i-1
new_weight=-1
# Binary Search for the first previous element that satisfies constarint
while(low<=high):
mid=(low+high)/2
if(start_state[mid][1]<=start_state[i][0]):
if(start_state[mid+1][1]<=start_state[i][0]):
low=mid+1
else:
new_weight=start_state[i][2]+dynamic_max_weight[mid]
break
else:
high=mid-1
if(new_weight!=-1):
dynamic_max_weight[i]=max(new_weight,dynamic_max_weight[i-1])
else:
dynamic_max_weight[i]=max(start_state[i][2],dynamic_max_weight[i-1])
return dynamic_max_weight[len(start_state)-1]
# filename="input1.txt"
start_state=[]
with open(sys.argv[1], 'r') as file:
for line in file:
start_state += [[int(i) for i in line.split()]]
merge_sort(start_state,0,len(start_state)-1)
print(selection_problem(start_state)) |
fd7c800da3996d44f828de63bd2f05066de01dbe | rizniyarasheed/python | /Flowcontrolls/decisionmaking/rgmtfc.py | 141 | 4.15625 | 4 | #if....else
age=int((input("enter the age :")))
if(age>18):
print("ur eligible for voting")
else:
print("ur not eligible for voting") |
68164cff7f5c159c5767c32e2218efc6d61aa6e4 | tianyi33/Python | /while1_cases.py | 132 | 4.03125 | 4 | number= input('How many people are in your group?')
if number>= 8:
print("Please come in.")
else:
print("Please wait out side.")
|
ba72d605f540aa41e16514e7621d25a73e9def5d | ImkyungHong/algorithm | /code06-01.py | 443 | 3.578125 | 4 | #stack 초기화
stack = [None, None, None, None, None]
top = -1
# push
top += 1
stack[top] = '커피'
top += 1
stack[top] = '녹차'
top += 1
stack[top] = '꿀물'
print(stack)
# pop한 뒤 사용해야 하는거 = data
data = stack[top]
stack[top] = None
top -= 1
print('Pop--->', data)
data = stack[top]
stack[top] = None
top -= 1
print('Pop--->', data)
data = stack[top]
stack[top] = None
top -= 1
print('Pop--->', data)
print(stack) |
86ff22146700f35e8567922e491a3a9d3b822b31 | d80b2t/python | /bootcamp/age1.py | 745 | 4.28125 | 4 | #!/usr/bin/env python
"""
PYTHON BOOT CAMP BREAKOUT3 SOLUTION;
created by Josh Bloom at UC Berkeley, 2012 (ucbpythonclass+bootcamp@gmail.com)
"""
import datetime
import sys
def days_since_now(year,month,day):
now = datetime.datetime.now()
print "days since then...", (now - datetime.datetime(year,month,day,12,0,0)).days
return
def date_from_now(ndays):
now = datetime.datetime.now()
print "date in " + str(ndays) + " days", now + datetime.timedelta(days=ndays)
if __name__ == "__main__":
if len(sys.argv) == 2:
date_from_now(int(sys.argv[1]))
elif len(sys.argv) == 4:
days_since_now(int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[2]))
else:
print "dont know what to do with", repr(sys.argv[1:])
|
9bc07068235bb15a60a55a7934afe32fa008d916 | iezer/progkb | /python/phrasebook/split_str.py | 273 | 3.8125 | 4 | sentence = "A Simple Se\tnte\nnce."
paragraph = "This is a simple paragraph.\n\
It is made up of of multiple\n\
lines of text."
entry = "Name:Brad Dayley:Occupation:Software Engineer"
print sentence.split()
print entry.split(':')
print paragraph.splitlines(1)
|
d740961fb907ca58722f4a13be3f1809532e8629 | tapa8728/code-programs | /Binary Search Trees/BST_nodelist_at_each_depth.py | 1,760 | 4.09375 | 4 | # Create a list of lists of nodes at each level of depth
import random
class Node(object):
def __init__(self,val):
self.left = None
self.right = None
self.value = val
class Tree(object):
def __init__(self):
self.root = None
self.lis = []
def getroot(self):
if self.root != None:
return self.root
else:
return None
def add(self, val):
if self.root == None:
self.root = Node(val)
print "Node with value {} has been added as root".format(val)
else:
self._add(val, self.root)
def _add(self, val, node): #lesser values than root to the left always
if val == node.value:
return None
if val < node.value: #left subtree
if node.left != None:
self._add(val, node.left)
else:
node.left = Node(val)
print "Node with value {} has been added to the left of {}".format(val, node.value)
else: #Right subtree
if node.right != None:
self._add(val, node.right)
else:
node.right = Node(val)
print "Node with value {} has been added to the right of {}".format(val, node.value)
def depth(self):
if self.root ==None:
print "Tree is empty!"
return 0
else
self._depth(self.root)
def _depth(self, node):
if node == None:
return 0
if node.right == None and node.left == None:
return 1
else: # either left or right child is present
l_depth = 1 + self._depth(node.left)
r_depth = 1 + self._depth(node.right)
if l_depth > r_depth:
return l_depth
else:
return r_depth
def printTree(self):
if self.root == None:
print "TRee is empty!"
else:
self._printTree(self.root)
# pre - order traversal
def _printTree(self, node, lis):
if node!= None:
print "{}--".format(node.value),
self._printTree(node.left)
self._printTree(node.right) |
68c6274e48e9782a0ff56a388f3b9ffa4f9662c6 | C-MTY-TC1028-037-2113/tarea-programacion-condicionales-intermedio-cmta09 | /assignments/09CmaKmMtCm/src/exercise.py | 531 | 3.859375 | 4 | def main():
# Escribe tu código abajo de esta línea
num = int(input("Introduce los cm: "))
if num<100:
print(num,"cm")
elif num<1000:
x=num//100
y=num-(x*100)
print(x,"m")
if y!=0:
print(y,"cm")
else:
x=num//100000
y=(num-(x*100000))//100
z=(num-(x*100000)-(y*100))
if x!=0:
print(x,"km")
if y!=0:
print(y,"m")
if z!=0:
print(z,"cm")
if __name__ == '__main__':
main()
|
a9334fece7fa8d56ca186848d1279b831d6981ee | ErickMwazonga/sifu | /linked_list/singly/sort_merge_sort.py | 1,543 | 4.0625 | 4 | '''
Time complexity: O(nlogn)
Space complexity: O(logn)
'''
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self, head=None):
self.head = head
def mergeSortedLists(self, head1, head2):
ptr1, ptr2 = head1, head2
returnedHead, tail = None, None
while ptr1 or ptr2:
if ptr1 and ptr2:
if ptr1.data < ptr2.data:
lower = ptr1
ptr1 = ptr1.next
else:
lower = ptr2
ptr2 = ptr2.next
elif ptr1:
lower = ptr1
ptr1 = ptr1.next
else:
lower = ptr2
ptr2 = ptr2.next
if returnedHead is None:
returnedHead = lower
tail = lower
else:
tail.next = lower
tail = tail.next
return returnedHead
def mergeSort(self, head):
if head is None or head.next is None:
return head
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
headRightHalf = slow.next
slow.next = None
head = self.mergeSort(head)
headRightHalf = self.mergeSort(headRightHalf)
return self.mergeSortedLists(head, headRightHalf)
def sortList(self, list):
list.head = self.mergeSort(list.head)
|
28590737a39d67eca3b34da4d3ba9e48db71ac06 | thuanthan258/VLSP2020 | /vlsp/preprocessing.py | 1,530 | 3.796875 | 4 | import pandas as pd
def check_is_number(input_value: str) -> bool:
if type(input_value) == int:
return True
if input_value.isnumeric():
return True
# Do this in case the input value is float as string
try:
result = float(input_value)
return True
except:
return False
def basic_preprocess(input_data: str):
""" Transform the original dataframe
Basic steps:
1. Fill N/A
2. Replace unknown with -1
Args:
input_data: pd.DataFrame
The dataframe you want to transform
Returns:
pd.DataFrame: The result dataframe
"""
df: pd.DataFrame = input_data.copy()
df.fillna('0', inplace=True)
df = df.replace('unknown', '-1')
# Unnecessary string
elements = ['like', 'comment', 'share']
regex_pattern = r'\d+ {}'
repl = lambda m: m.group(0).split()[0]
for i in elements:
# Remove the unnecessary element
df[f'num_{i}_post'] = df[f'num_{i}_post'].astype(str)
df[f'num_{i}_post'] = df[f'num_{i}_post'].str.replace(regex_pattern.format(i), repl)
# Transform other to -1
indexing_non_number = df[f'num_{i}_post'].apply(lambda x: check_is_number(x))
false_indexes = indexing_non_number[indexing_non_number == False].index
for j in false_indexes:
df.at[j, f'num_{i}_post'] = '-1'
df[f'num_{i}_post'] = df[f'num_{i}_post'].astype(float)
return df |
f1d7086d9cd8f98a40146739a5a2b65c5e13fc7b | AleByron/AleByron-The-Python-Workbook-second-edition | /Chap-8/ex166.py | 900 | 3.9375 | 4 | from ex117 import splitWords
def FreqNamesTot():
try:
inf = open('C:\\Users\\ale\\PycharmProjects\\WorkbookExercises\\Files\\Popular_Baby_Names.csv')
yearsm = []
yearsf = []
for l in inf:
line = inf.readline()
line = line.upper()
arr = splitWords(line)
if arr[len(arr) - 3] not in yearsm and arr[1] == 'MALE':
yearsm.append(arr[len(arr) - 3])
if arr[len(arr) - 3] not in yearsf and arr[1] == 'FEMALE':
yearsf.append(arr[len(arr) - 3])
except FileNotFoundError:
return print('Something went wrong, the program wil quit')
return yearsm, yearsf
def main():
print('Most popular male names are:', FreqNamesTot()[0])
print('Most popular female names are:', FreqNamesTot()[1])
if __name__ == "__main__":
main() |
a997cf0bc719b320a234ebb9f098828d1930dc21 | shouliang/Development | /Python/SwordOffer/has_path_in_matrix_01.py | 2,502 | 4 | 4 | ''' 矩阵中的路径
题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个
格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路
径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含
"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
'''
'''
思路:优化版回溯法
1.将matrix字符串模拟映射为一个字符矩阵(但并不实际创建一个矩阵)
2.取一个boolean[matrix.length]标记某个字符是否已经被访问过,用一个布尔矩阵进行是否存在该数值的标记。
3.如果没找到结果,需要将对应的boolean标记值置回false,返回上一层进行其他分路的查找。
'''
# coding=utf-8
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i * cols + j] == path[0]:
if self.findPath(list(matrix), rows, cols, path[1:], i, j):
return True
def findPath(self, matrix, rows, cols, path, i, j):
if not path:
return True
matrix[i * cols + j] = 0
if j + 1 < cols and matrix[i * cols + j + 1] == path[0]:
return self.findPath(matrix, rows, cols, path[1:], i, j + 1)
elif j - 1 >= 0 and matrix[i * cols + j - 1] == path[0]:
return self.findPath(matrix, rows, cols, path[1:], i, j - 1)
elif i + 1 < rows and matrix[(i + 1) * cols + j] == path[0]:
return self.findPath(matrix, rows, cols, path[1:], i + 1, j)
elif i - 1 >= 0 and matrix[(i - 1) * cols + j] == path[0]:
return self.findPath(matrix, rows, cols, path[1:], i - 1, j)
else:
return False
# matrix = [
# ['A', 'B', 'C', 'E'],
# ['S', 'F', 'C', 'S'],
# ['A', 'D', 'E', 'E']
# ]
# matrix 为一维数组的形式
matrix = ['A', 'B', 'C', 'E', 'S', 'F', 'C', 'S', 'A', 'D', 'E', 'E']
s = Solution()
path = "ABCCED"
flag = s.hasPath(matrix, 3, 4, path)
print(flag)
path = "SEEDE"
flag = s.hasPath(matrix, 3, 4, path)
print(flag)
path = "ABCESCEE"
flag = s.hasPath(matrix, 3, 4, path)
print(flag)
|
6c50f1a2e7fe461ad188bf1bc4433b9330a3296c | Lucasbertilima/PythonPro | /Aula3/aula3.py | 252 | 3.78125 | 4 | n1=10
n2=15
resultado =n1+n2
print(f'Resultado soma:{resultado}')
resultado = n1-n2
print(f'Resultado subtração:{resultado}')
resultado = n1*n2
print(f'Resultado multiplicação:{resultado}')
resultado = n1/n2
print(f'Resultado divisão:{resultado}') |
4b95540bd01a644bea001669cbaa4c62ab270992 | xue9981/LP2 | /Chapter07/movie_ticket.py | 367 | 3.703125 | 4 | prompt = "\nTo buy the ticket, Please input your age."
prompt += "\n(Enter 'quit' to finish) "
age = ''
active = True
fee = 0
while active:
age = input(prompt)
if age == 'quit':
break
elif int(age) < 3:
fee = 0
elif int(age) <= 12:
fee = 10
else:
fee = 15
print("Your ticket fee is $" + str(fee) + ".")
|
0f78993b17c72b16dfc92916c9dde80e3edc2ab4 | xr71/python_design_patterns | /4_behavioral_patterns/3_iterator.py | 253 | 3.53125 | 4 | import pytest
# iterators allow for isolation
# interface
def count_to():
numbers = ["un", "deux", "trois", "quatre", "cinq"]
it = zip(range(len(numbers)), numbers)
for p, n in it:
yield n
for num in count_to():
print(num)
|
ad01f189d5a4b3697ebcb2c23c674643b90844b5 | J14032016/LeetCode-Python | /leetcode/algorithms/p0094_binary_tree_inorder_traversal_1.py | 534 | 3.671875 | 4 | from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
values = []
self._traversal(root, values)
return values
def _traversal(self, root: TreeNode, values: List[int]) -> None:
if not root:
return
self._traversal(root.left, values)
values.append(root.val)
self._traversal(root.right, values)
|
53f5edc0f5e6c90319aeb59f163a77f7b739cbbc | bayoishola20/Python-All | /LeetCode/design_underground_system.py | 2,847 | 3.765625 | 4 | # Implement the UndergroundSystem class:
# void checkIn(int id, string stationName, int t)
# A customer with a card id equal to id, gets in the station stationName at time t.
# A customer can only be checked into one place at a time.
# void checkOut(int id, string stationName, int t)
# A customer with a card id equal to id, gets out from the station stationName at time t.
# double getAverageTime(string startStation, string endStation)
# Returns the average time to travel between the startStation and the endStation.
# The average time is computed from all the previous traveling from startStation to endStation that happened directly.
# Call to getAverageTime is always valid.
# You can assume all calls to checkIn and checkOut methods are consistent. If a customer gets in at time t1 at some station, they get out at time t2 with t2 > t1. All events happen in chronological order.
# HINT: Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
# DESIGN UNDERGROUND SYSTEM
from collections import defaultdict
class UndergroundSystem:
def __init__(self):
self.ins = {} # customer_id: (start_station, start_time)
self.outs = defaultdict(list) # (start_station, end_station)
def checkIn(self, id, stationName, t):
self.ins[id] = (stationName, t)
def checkOut(self, id, stationName, t):
start_station, start_time = self.ins[id]
total = t - start_time
self.outs[(start_station, stationName)].append(total)
def getAverageTime(self, startStation, endStation):
key = (startStation, endStation)
difference = self.outs[key]
return sum(difference) / len(difference)
# TIME COMPLEXITY:
class UndergroundSystem:
def __init__(self):
self.checkIns = {}
self.times = {}
def checkIn(self, id, stationName, t):
self.checkIns[id] = (stationName, t)
def checkOut(self, id, stationName, t):
try:
self.times[self.checkIns[id][0] + "-" + stationName].append(t-self.checkIns[id][1])
except KeyError:
self.times[self.checkIns[id][0] + "-" + stationName] = [t-self.checkIns[id][1]]
def getAverageTime(self, startStation, endStation):
return sum(self.times[startStation + "-" + endStation])/len(self.times[startStation + "-" + endStation])
# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)
a = UndergroundSystem()
# Test 1
a.checkIn(10,"Leyton",3)
a.checkOut(10,"Paradise", 8)
print(a.getAverageTime("Leyton", "Paradise"))
|
85ccfcc9b0f655e2421aedbe0a840e814412e071 | AleksandrBud/Python | /lesson5/task2.py | 308 | 3.59375 | 4 | import os
def list_dir():
cur_dir = os.getcwd()
dirs = [i for i in os.listdir(cur_dir) if os.path.isdir(os.path.join(cur_dir, i))]
for dir in dirs:
print(dir)
def list_all():
cur_dir = os.getcwd()
dirs = [i for i in os.listdir(cur_dir)]
for dir in dirs:
print(dir) |
f194ae551f520dff8d456c93cdd63c73fec5438d | LucasLima21/PDS | /Project3-PDS.py | 3,115 | 3.578125 | 4 | """
UEA - Universidade do Estado do Amazonas
EST - Escola Superior de Tecnologia
Processamendo Digital de Sinais
Equipe: Beatriz Moura, Lucas Lima, Luiz Gadelha
E-mail: ldsllm.eng@uea.edu.br
"""
import math #biblioteca utilizada para algumas funções de constantes da math
#bibliotecas abaixo utilizadas para plotagem dos polos e zeros da resultante da transformada Z
import matplotlib.pyplot as plt
from numpy import *
from pylab import *
def trade_X_to_Y(signalInput):
concatenation = ""
for i in range(len(signalInput)):
if(signalInput[i] == 'x'):
concatenation+="y"
else:
concatenation+=signalInput[i]
return concatenation
def option1():#função que roda a opção 1 a qual recebe a equação do sinal analógico
print("Insira o sinal Analogico\n Exemplos do formato de entrada(sin(x) + cos(x), cos(2*x) - 2*sin(x): ")
x = np.linspace(-2*pi, 2*pi, 60)
signalInput = input()
signalNormalFrequency = eval(signalInput)
#sinal analogico ja com o valor do periodo de amostragem
#seguindo o teorema de amostragem de nyquist
#para que eu nao tenha aliasing
#preciso representar a frequencia de amostragem
#com o dobro da frequencia maxima do sinal !!
#como eu estabeleci uma período que todo sinal terá, o qual é de 2pi
#logo é só reduzir esse periodo, assim, duplicanddo a frequencia
y = np.linspace(-4*pi, 4*pi, 80)
signalInputTraded = trade_X_to_Y(signalInput)
signalDoubleFrequency = eval(signalInputTraded)
#print(x,"\n")
#print(signal)
sample = x
sample1 = y
#Plot Analogico
plt.subplot(2,1,1)
plt.subplots_adjust(hspace=0.6, wspace=0.6)
plt.title("Sinal Analogico")
plt.axhline(0, color = 'black')
plt.axvline(0, color = 'black')
plt.ylabel('X[n]')
plt.xlabel('n')
plt.grid()
plt.plot(sample,signalNormalFrequency,'-', color='green')
#plot discretizado
plt.subplot(2,1,2)
plt.subplots_adjust(hspace=0.6, wspace=0.6)
plt.title("Sinal Discretizado")
plt.axhline(0, color = 'black')
plt.axvline(0, color = 'black')
plt.ylabel('X[n]')
plt.xlabel('n')
plt.grid()
#reduzindo pela metade o período, duplicando a frequencia!
plt.stem(sample1/2,signalDoubleFrequency)
#mostrando todos os 4 plot
plt.show()
#limpando a cada iteracao do programa
plt.clf()
# OBS.: por estarem no mesmo subplot precisam estar na mesma subrotina
print("\n")
def startProgram():#funçãoo que inicia o programa, fica em looping mostrando o pequeno menu feito
#apenas para fins calcular mais de uma vez,
print("Digite as opções:\n[0] Para sair\n[1] Para inserir a equação do sinal analógico: ")
option = int(input("Escolha a opção: "))
while(option != 0):
if(option == 1):
option1()
option = int(input("Escolha a opção: "))
#Inicio!!! chamada da subrotina que inicializa o programa
startProgram()
|
3f013217c9391083b2b1c329110f696d01d5311d | yenbohuang/online-contest-python | /leetcode/easy/tree/test_subtree_of_another_tree.py | 2,193 | 3.75 | 4 | #
import unittest
from ...leetcode_data_model import TreeNode
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if t is None:
return True
elif s is None:
return False
else:
return self.__compare(s, t) or \
(s.left is not None and self.isSubtree(s.left, t)) or \
(s.right is not None and self.isSubtree(s.right, t))
def __compare(self, node1, node2):
"""
:type node1: TreeNode
:type node2: TreeNode
:rtype: bool
"""
if node1 is None and node2 is None:
return True
elif node1 is not None and node2 is not None \
and node1.val == node2.val:
return self.__compare(node1.left, node2.left) and \
self.__compare(node1.right, node2.right)
else:
return False
class TestSolution(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def tearDown(self):
pass
def test_case_1(self):
T1 = TreeNode(1)
T1.left = TreeNode(2)
T1.right = TreeNode(3)
T1.right.left = TreeNode(4)
T2 = TreeNode(3)
T2.left = TreeNode(4)
self.assertTrue(self.solution.isSubtree(T1, T2))
def test_case_2(self):
T1 = TreeNode(1)
T1.left = TreeNode(2)
T1.right = TreeNode(3)
T1.right.left = TreeNode(4)
T2 = TreeNode(3)
T2.right = TreeNode(4)
self.assertFalse(self.solution.isSubtree(T1, T2))
def test_case_3(self):
T1 = None
T2 = TreeNode(3)
T2.right = TreeNode(4)
self.assertFalse(self.solution.isSubtree(T1, T2))
def test_case_4(self):
T1 = TreeNode(1)
T1.left = TreeNode(2)
T1.right = TreeNode(3)
T1.right.left = TreeNode(4)
T2 = None
self.assertTrue(self.solution.isSubtree(T1, T2))
def test_case_5(self):
self.assertTrue(self.solution.isSubtree(None, None))
if __name__ == '__main__':
unittest.main()
|
0fd10e4d0289a330c2cdab5305c34507634a791a | davidxbuck/playground | /src/BubbleSortRecursive.py | 981 | 3.5 | 4 | '''
BUBBLESORT Algorithm with recursion
NOT directly following pseudocode from CLRS
Uses recursion rather than nested for loops
'''
class Array:
def __init__(self, values=[]):
self.A = values
def alen(self):
return len(self.A)
length = property(alen)
# BUBBLESORT(A)
# for i = 1 to A.length - 1
# for j = A.length down to i + 1
# if A[j] < A[j - 1]
# exchange A[j] with A[j - 1]
# def BUBBLESORT(self):
# for i in range(0, self.length - 1):
# for j in range(self.length - 1, i + 1, -1):
# if self.A[j] < self.A[j - 1]:
# self.A[j], self.A[j - 1] = self.A[j - 1], self.A[j]
def BUBBLESORT(self, i=0):
if i < self.length - 1:
for j in range(self.length - 1, i + 1, -1):
if self.A[j] < self.A[j - 1]:
self.A[j], self.A[j - 1] = self.A[j - 1], self.A[j]
self.BUBBLESORT(i + 1)
|
76f8da518a458ac24f48680b3a1bf40e2ab79301 | derekpa2/Advent_of_code_2019 | /aoc_day6_1.py | 4,513 | 3.90625 | 4 |
class Orbit:
#this is the orbit class.
#name is the name of the body.
#length is the length from the center of mass (COM)
#children is a list of all the orbiting bodies
#totallength is the sum of all the chilren's lengths
#
#there is only one method, the addChild method. This appends a children
#to the node. In effect it adds and object to orbit this body.
def __init__(self,name,length=0):
self.name = name
self.length = length
self.children = []
self.totallength = 0
def addChild(self,orbitObj):
self.children.append(orbitObj)
def findOrbits(orbitlist,name):
#this helper function takes a list of orbits and finds the matches where
#the first element is equal do the name. It then returns the full orbits
#(both elements) of each match
#TODO: make this better. Use generators or something like that
indicies = []
orbits = []
#first, find the indicies of all the matches
for i in orbitlist:
if i[0] == name:
indicies.append(orbitlist.index(i))
#pop the indicies off of the orbit list, needs to be done in reverse order
#or else the wrong elements will be removed.
for j in range(len(indicies)):
child = orbitlist.pop(indicies[len(indicies) - j -1])
orbits.append(child[1])
return orbits
def buildTree(orbitlist,name,length):
#create the orbit object. This is a node
orbitObject = Orbit(name,length)
#find the children by calling the findOrbits function
children = findOrbits(orbitlist,name)
#iterate over all the chilren that were found. This will create the child object,
#then set those created objects as chilren to this object. Don't forget to
#calculate the length!
for i in children:
childObject = buildTree(orbitlist,i,orbitObject.length + 1)
orbitObject.addChild(childObject)
orbitObject.totallength += childObject.totallength + childObject.length
return orbitObject
def findOrbitTransfers(orbit,orbitone,orbittwo):
#The matchstring is used to immediately return if a match is found.
#This effectively returns the "first" match in which both chilren match
#the orbitone and orbittwo string, and is a way to return the calculated
#length to the calling function.
matchstring = 'Found match!'
boolone, booltwo = False, False
#if the name matches the matchstring, we're done, return what was given.
#if any of the names match orbitone, we've found one match.
#store the length to be returned or used in the length calculation later
#if any of the names match orbitone, we've found another match.
#store the length to be returned or used in the length calculation later
for index,i in enumerate(orbit.children):
name, length = findOrbitTransfers(i,orbitone,orbittwo)
if name == matchstring:
return name, length
elif name == orbitone:
boolone = True
lengthone = length
elif name == orbittwo:
booltwo = True
lengthtwo = length
#if orbitone and orbittwo are both found, we're done!
#return the matchstring so the calling function will succeed.
#return the calculated length. formula determined by inspection of the example
#if orbitone is found, return the name and length to the calling function.
#if orbittwo is found, return the name and length to the calling function.
#if nothing is found (or there were no children), just return the name and length.
if boolone and booltwo:
return matchstring, (lengthone - orbit.length - 1) + (lengthtwo - orbit.length - 1)
elif boolone:
return orbitone, lengthone
elif booltwo:
return orbittwo, lengthtwo
else:
return orbit.name, orbit.length
if __name__ =="__main__":
#read the numbers in
#readfile = open('aoc_day6_1.txt')
readfile = open('aoc_day6_1.txt')
orbitlist = []
#read each line of the text file
for line in readfile:
element = line.split(')')
element[1] = element[1].strip()
orbitlist.append(element)
orbitlistcopy = orbitlist.copy()
#day 1, builds the tree.
orbitNode = buildTree(orbitlist,'COM',0)
print(orbitNode.totallength)
#day 2, calculates the least amount of orbit transfers
resultname,resultlength = findOrbitTransfers(orbitNode,'YOU','SAN')
print('Result is:',resultname,resultlength)
#comment
|
8fe2b8ffe45fa21e268349610c684a5c185b7fd6 | ramazanyersainov/hashcode2018 | /main.py | 1,011 | 3.53125 | 4 | class photo:
def __init__(self, i, orien, tags):
self.index = i
self.tags = set(tags)
self.orien = orien
class slide:
def __init__(self, p_list):
if len(p_list) > 2 or len(p_list) < 1:
print("wrong number of photos for slide")
return
if len(p_list) == 2:
if not (p_list[0] == 'V' and p_list[1] == 'V'):
print("not two verticals for slide")
return
self.tags = set()
self.p_i_list = []
for p in p_list:
self.p_i_list.append(p.index)
self.tags |= p.tags
def score(sl):
if sl.index == len(sl_list) - 1:
return 0;
set1 = set(sl.tags)
set2 = set(sl_list[sl.index + 1].tags)
return min(len(set1 & set2), len(set1 - set2), len(set2 - set1))
if __name__ == "__main__":
p1 = photo(0, 'H', ['1', '3'])
p2 = photo(1, 'V', ['3', '3'])
s1 = slide([p1])
s2 = slide([p2])
sl_list = [s1, s2]
print(score(p1))
|
630bdd5c13f4ec241b016ee6636bfe70af9b1448 | mark-morelos/CS_Notes | /Assignments/Sprint3/FindAllPaths.py | 1,496 | 3.890625 | 4 | """
Understand
Note: For some reason, it's failing one of the tests. I
think it's because the test case didn't sort their output.
In that case, the test is wrong :)
Drawing graphs via text are a pain, so I'm just gonna use the example given
Plan
1. Translate the problem into graph terminology
- Each index in the list given is a node
- Each subarray are the node's outgoing edges to its neighbors
2. Build your graph
- The graph is actually already built for us. We can traverse
the given list like a graph since
we have access to the node we're at and its neighbors.
3. Traverse the graph
- Any type of traversal would work, we just need to keep
track of the path that we've currently taken
- We add that path to the result once we reach the destination node
- Note that we don't need a visited set since we're
guaranteed that the graph is a DAG
Runtime: O(number of nodes^2)
Space: O(number of nodes^2)
Imagine a dense graph
"""
from collections import deque
def csFindAllPathsFromAToB(graph):
stack = deque()
stack.append((0, [0]))
res = []
destinationNode = len(graph) - 1
while len(stack) > 0:
curr = stack.pop()
currNode, currPath = curr[0], curr[1]
for neighbor in graph[currNode]:
newPath = currPath.copy()
newPath.append(neighbor)
if neighbor == destinationNode:
res.append(newPath)
else:
stack.append((neighbor, newPath))
res.sort()
return res |
ebb26bdcbcffdf412648aee04858a8b3447ad3ae | hamidihekmat/Programming-Practice | /Days/day13/aps.py | 1,252 | 3.953125 | 4 | '''
Two students challenge each other to a basketball shootout. They agree to limit the number of
attempts to 3 throws each. The game will be constructed in two sessions where the first student will
make all 3 attempts followed by the second student. The student who makes the most baskets (gets
the ball in the hoop) will be declared the winner. In the case of a tie, the game will be repeated until a
winner can be determined.
'''
def basket():
p1_score = 0
p2_score = 0
n_throws = 0
while True:
if n_throws == 3:
n_throws = 0
break
n_throws += 1
shot = int(input("Player 1 take the shot: 1 = In, 2 = Miss "))
if shot == 1:
p1_score += 1
else:
p1_score = p1_score
while True:
if n_throws == 3:
n_throws = 0
break
n_throws += 1
shot = int(input("Plater 2 take the shot: 1 = In, 2 = Miss "))
if shot == 1:
p2_score += 1
else:
p2_score = p2_score
if p1_score > p2_score:
print('Player 1, won!')
elif p2_score > p1_score:
print('Player 2, won!')
else:
print('Tie')
basket()
|
9611c63851e312eb03026b2525438dc80f596bf6 | siddheshmhatre/Algorithms | /DP/weighted_independent_set.py | 332 | 3.734375 | 4 | # Compute optimal value of weighted independent set
def wis(weights):
A = []
A.append(weights[0])
A.append(max(weights[0],weights[1]))
for i in range(2,len(weights)):
A.append(max(A[i-1],A[i-2] + weights[i]))
return A[len(weights)-1]
def main():
weights = [1,4,5,4]
print wis(weights)
if __name__ == "__main__":
main()
|
a153b34d38315d25f7553f52e12caecf71102c13 | sabartheman/basic-serial-recording | /serial_test/Arduino_to_text.py | 2,483 | 3.71875 | 4 | import time
#need to install pyserial before you can use this module
#which can be done by typing:
# pip install pyserial
#into the terminal as long as you have python installed first
import serial
#arch linux
#programLocation = "/usr/bin/arduino"
arduinoPort = "COM14"
def SERIAL_TO_TEXT():
# you can also google how to create a serial object to use for this script
# but this is initializing a object with the serial.Serial functions
s = serial.Serial()
# we are setting up the serial.Serial.port setting
# you can also just put the string "COM14" to the right of the equal sign instead of arduinoPort
s.port = arduinoPort
# the baud rate has to match what is set on the microcontroller
s.baudrate = 9600
# This is how many seconds before the serial port on the PC side waits before assuming no data from the microcontroller
s.timeout = 5
s.open()
# print("opening serial line")
# toggling these lines to reset the arduino
# this doesn't need to be done, but this will make sure arduino
# is starting from the beginning of it's code.
s.setDTR(False)
s.setRTS(False)
time.sleep(.2)
s.setDTR(True)
s.setRTS(True)
# print statements can be used in python as debug points to make sure that
# the code arrived at this point.
print("Serial port setup complete")
try:
#initializing arduino string to be empty
arduinoSerial = ""
#initialize a file object to write to when we receive data
serialRecord = open("Testing_serial", "a")
print("Starting to read from serial port")
while(True):
if(s.in_waiting > 0):
# the readline function reads from the serial port and outputs
# the byte datatype, not a string
arduinoSerial = s.readline()
# we can still print out a byte by itself
print(arduinoSerial)
# if we want to concatinate a string to the output we need to convert
# the byte to a string using str()
print("This is the output from the serial line:" + str(arduinoSerial))
# if we want to record the data to a text file we need to convert it
serialRecord.write(str(arduinoSerial))
except KeyboardInterrupt:
print("\nexistential crisis") #why not
s.close()
# if __name__ == "__main__":
# SERIAL_TO_TEXT()
SERIAL_TO_TEXT()
|
4fd5388c4f97afb52e005c3d4b5bdb129a4df0c0 | NischalVijayadeva/tutorial_01 | /Dump/Models/Students.py | 733 | 3.5625 | 4 | import unittest
import Models
class Student:
def __init__(self, id, name, dept):
self.id = id
self.name = name
self.dept = dept
class Students:
def __init__(self):
self.students = list()
def addStudent(self, name, dept):
id = len(self.students)+1
self.students.append(Student(id, name, dept))
return id
def removeStudentById(self, id):
stud = self.getStudentById(id)
self.students.remove(stud)
def getStudentById(self, id):
for s in self.students:
if (s.id == id):
return s
if __name__=="__main__":
students = Students()
students.addStudent("Nischal","IT")
students.addStudent("TestUser","BA")
print(len(students.students))
|
bb91ad8084d7a82df4dd4333f2ce12f01c91aebb | GuilhermeSalles/Python | /Python codes/24.py | 190 | 4 | 4 | # Idades
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Print das idades em ordem normal
print(lista)
# "Função" para inverter os numeros
lista.reverse()
# Print da lista invertida
print(lista) |
7eff8d6a274774295815e546c3aec57afe53a401 | detcitty/100DaysOfCode | /python/unfinshed/convertReversedArrayDigits.py | 407 | 4.03125 | 4 | # https://www.codewars.com/kata/5583090cbe83f4fd8c000051/train/python
'''
Convert number to reversed array of digits
Given a random non-negative number, you have to return the digits of this number within an array in reverse order.
Example(Input => Output):
348597 => [7,9,5,8,4,3]
0 => [0]
'''
def digitize(n):
numbers_split = list(map(lambda x: int(x), list(str(n))))
return numbers_split[::-1] |
45d8062017340752e054ddbd52861106ba7fa9cf | eventia/zbc_python | /temp09A.py | 656 | 3.6875 | 4 | number = 23
running = True
loopState = False
while running:
guess = int(input('숫자를 입력하세요 : '))
if guess == 777:
print('종료합니다')
break
if guess == number:
print ('맞았습니다.')
running = False
elif guess < number:
print ('틀렸습니다. 조금 더 큰 수입니다.')
else:
print ('틀렸습니다. 조금 더 작은수입니다.')
else:
print ('반복문이 정상적으로 종료되었습니다.')
loopState = True
if loopState == True:
print('프로그램 정상종료')
else :
print ('프로그램이 강제종료되었습니다.')
|
f428b07dd80d74f9ddbc899e8339d90b05e1ef5a | greatabel/PythonRepository | /04Python workbook/ch4function/randomPlate95.py | 677 | 3.875 | 4 | from random import randint
import string, random
def randomPlate():
result = ""
# for i in range(3):
# print(ord('A'),ord('z'))
# randomChar = chr(randint(ord('A'),ord('z')))
# print('randomChar=',randomChar)
# result = result + randomChar
result = ''.join(random.choice(string.ascii_lowercase) for x in range(3))
myintrange = 0
myrandomtype = randint(0,1)
# print('myrandomtype=',myrandomtype)
if myrandomtype%2==0:
myintrange = 3
else:
myintrange = 4
for j in range(myintrange):
randomNum = str(randint(0,9))
result = result + randomNum
return result
def main():
print("Your random pass is:", randomPlate())
if __name__ == "__main__":
main() |
4793bfeb3585bf7af2f27cfcb1434890959bda63 | zahlenteufel/pynball | /ball.py | 1,559 | 3.5625 | 4 | from vector import Vector, distance
from draw import draw_circle
GRAVITY_ACC = Vector(0, 0.02)
#Vector(0, 0.002)
class Ball:
def __init__(self, center, radius, velocity):
self.center = center
# rename it to position...
self.radius = radius
self.velocity = velocity
def intersection(self, segment):
closest_point = segment.closest_point(self.center)
if distance(closest_point, self.center) <= self.radius:
return closest_point
else:
return None
def draw(self, screen):
draw_circle(screen, (255, 255, 255), self.center, self.radius)
def collides_segment(self, segment):
return self.intersection(segment) is not None
def at(self, time):
newPosition = self.center + \
GRAVITY_ACC * (time ** 2) + self.velocity * time
newVelocity = self.velocity + GRAVITY_ACC * time
return Ball(newPosition, self.radius, newVelocity)
def apply_colissions_to_segments(self, segments):
for segment in segments:
collision_point = self.intersection(segment)
if collision_point:
self.center -= self.velocity # undo move
if segment.is_extreme(collision_point):
self.velocity = segment.direction.reflect(self.velocity)
else:
orthogonal = (collision_point - self.center).normal()
self.velocity = orthogonal.reflect(self.velocity)
self.velocity = self.velocity * 0.7
|
568db2eb6c30751c9f6554c41aa73c94a0fc9e35 | QiXuanWang/MachineLearning | /TF/lstm_xsin.py | 6,103 | 4.21875 | 4 | # ref: https://raw.githubusercontent.com/joostbr/tensorflow_lstm_example/master/lstm_sine_example.py
#Yu: This example trains to recognize a one period sine wave
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
num_inputs = 1 # input dimension
num_outputs = 1 # output dimension
sample_step_in_degrees = 6 # sine wave sampled each 6 degrees
num_steps = int(360/sample_step_in_degrees) # number of time steps for the rnn, also, it's sequence_lengths
num_hidden = 10 # use 5 cells/units in hidden layer
num_epochs = 1000 # 100 iterations
batch_size = 1 # only one sine wave per batch; Yu: what if we use 2? we can't since we only have num_steps data in one sequence. The purpose of batch is to make similar data separated into batches, but if we have several sine waves in sequence, then we may change batch_size to 2. Can we say that it's the major difference between word rnn and these periodic waves. What if the wave is x*sin(x)?
# generate two full sine cycle for one epoch, but use only one
def gen_data(distort=False, epoch=1):
# generate sin(x)
sinx = np.arange(0,360,sample_step_in_degrees) # 60 points every sequence
sinx = np.sin(2*np.pi * sinx/360.0)/2 # sine wave between -0.5 and +0.5
if distort:
sinx = np.add(sinx, np.random.uniform(-0.1,0.1,size=num_steps))
sinx2 = np.stack([sinx, sinx]).reshape(60*2)
# add logx
logx2 = 0.1*np.log(np.linspace(epoch, epoch+60*2,60*2))
if epoch == 0:
logx2[0] = 1e-8
X2 = sinx2 + logx2
X = X2[0:60]
X = X.reshape(num_steps,1) # num_steps == 60
#This actually shift X for 1 timestep, but X[0] needs to multiply next logx
#y = np.concatenate((X[1:num_steps,:],X[0:1,:]))
y = X2[1:61]
X = X.reshape(batch_size,num_steps,1)
y = y.reshape(batch_size,num_steps,1)
#a, = plt.plot(X.reshape(60,1), label="X", marker='+',c='b')
#b, = plt.plot(y.reshape(60,1), label="Y", marker='*',c='r')
#c, = plt.plot(logx2, label="LOG", marker='^',c='g')
#d, = plt.plot(logx2+sinx2, label="LOG+SIN", marker='o', c='y')
#plt.show([a,b,c,d])
return (X,y)
def create_model():
cell1 = tf.nn.rnn_cell.BasicLSTMCell(num_units=num_hidden)
cell2 = tf.nn.rnn_cell.BasicLSTMCell(num_units=num_hidden)
cell = tf.contrib.rnn.MultiRNNCell([cell1, cell2], state_is_tuple=True)
inputs = tf.placeholder(shape=[batch_size, num_steps,num_inputs],dtype=tf.float32)
result = tf.placeholder(shape=[batch_size, num_steps, 1],dtype=tf.float32)
X = tf.transpose(inputs,[1,0,2]) # num_steps (T) elements of shape (batch_size x num_inputs)
X = tf.reshape(X,[-1, num_inputs]) # flatten the data with num_inputs values on each row
X = tf.split(X, num_steps, axis=0) # create a list with an element per timestep, cause that is what the rnn needs as input
resultY = tf.transpose(result,[1,0,2]) # swap the first two dimensions, in order to be compatible with the input args
print(X)
outputs,states = tf.nn.static_rnn(cell, inputs=X, dtype=tf.float32) # initial_state=init_state) # outputs & states for each time step
w_output = tf.Variable(tf.random_normal([num_steps, num_hidden], stddev=0.01, dtype=tf.float32))
b_output = tf.Variable(tf.random_normal([num_steps, 1], stddev=0.01, dtype=tf.float32))
# purpose of the_output: X^T * W + b, it's a linearRegression
the_output = []
for i in range(num_steps):
print("Outputs[%d]:"%i, outputs[i])
print(w_output[i:i+1,:])
print(tf.matmul(outputs[i],w_output[i:i+1,:],transpose_b=True))
# print (the_output[i])
print ( tf.nn.sigmoid(tf.matmul(outputs[i], w_output[i:i+1,:], transpose_b=True)) )
#the_output.append( tf.nn.tanh(tf.matmul(outputs[i], w_output[i:i+1,:], transpose_b=True) ) )
the_output.append(tf.matmul(outputs[i], w_output[i:i+1,:], transpose_b=True) )
# + b_output[i])
# change it to a list
outputY = tf.stack(the_output)
print("outputY shape: {}".format(outputY.shape))
cost = tf.reduce_mean(tf.pow(outputY - resultY,2))
#cross_entropy = -tf.reduce_sum(resultY * tf.log(tf.clip_by_value(outputY,1e-10,1.0)))
#train_op = tf.train.RMSPropOptimizer(0.005,0.2).minimize(cost)
#train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost)
train_op = tf.train.AdamOptimizer(0.001).minimize(cost)
valX,valy = gen_data(False, 100) # validate
testX, testy = gen_data(False, 2000)
with tf.Session() as sess:
print("gen data")
#tf.merge_all_summaries()
#writer = tf.train.SummaryWriter("/Users/joost/tensorflow/log",flush_secs=10,graph_def=sess.graph_def)
#tf.initialize_all_variables().run()
tf.global_variables_initializer().run()
for k in range(num_epochs):
# print("start k={}".format(k))
tempX,y = gen_data(False, k)
# tempX has batch_size elements of shape ( num_steps x num_inputs)
# print((tempX,y))
traindict = {inputs: tempX, result: y}
sess.run(train_op, feed_dict=traindict)
valdict = {inputs: valX, result: valy}
costval,outputval = sess.run((cost,outputY), feed_dict=valdict)
if k == num_epochs-1:
print("output shape: {}".format(outputval.shape))
o = np.transpose(outputval,(2,0,1))
print ("o={}".format(o))
print("end k={}, cost={}, output={}, y={}".format(k,costval,o,valy))
print("diff={}".format(np.subtract(o,valy)))
predicted = [v[0] for v in o[0]]
plot_predicted, = plt.plot(predicted, label="predicted", marker='+',c='b')
realy = [v[0] for v in valy[0]]
plot_valy, = plt.plot(realy, label='valy', marker='1', c='r')
realX = [v[0] for v in valX[0]]
plot_valx, = plt.plot(realX, label='valx', marker='*', c='y')
plt.show()
else:
print("end k={}, cost={}".format(k,costval))
create_model()
|
c1b233e71ab47fba47029f7a0f40b3a7d144d23a | dictator-x/practise_as | /algorithm/leetCode/0240_search_a_2d_matrix_II.py | 387 | 3.703125 | 4 | """
240. Search a 2D Matrix II
"""
class Solution:
def searchMatrix(self, matrix, target):
row, col = len(matrix)-1, 0
while row >= 0 and col < len(matrix[0]):
if target > matrix[row][col]:
col += 1
elif target < matrix[row][col]:
row -= 1
else:
return True
return False
|
207d8e6021b1126bb8f6c7e7e0c50a5966070733 | klq/euler_project | /euler15.py | 905 | 3.5 | 4 | def euler15():
# Problem:
"""
Starting in the top left corner of a 2x2 grid,
and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20x20 grid?
"""
# Solve:
N = 21
routes = [[None] * N] * N
for i in range(N):
routes[i][N-1] = 1
routes[N-1][i] = 1
for i in range(N-2,-1,-1):
for j in range(N-2,-1,-1):
routes[i][j] = routes[i+1][j] + routes[i][j+1]
print i,j,routes[i][j]
return routes
euler15() #137846528820
"""
Analytical solution:
You will go down exactly 20 steps, and go right exactly 20 steps. 40 steps in total.
So the total number of different routes is 40 choose 20.
C(20,40) = P(20,40) / P(20,20) = 40! / (20! (40-20)!)
"""
import math
print math.factorial(40) / (math.factorial(20)**2)
|
5fba55c812ea2136030876a0dd5440be9f9dd45e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2674/60825/298898.py | 308 | 3.640625 | 4 | t=""
while True:
try:
ts=input()
t+=ts
except:
break
if t=='2abbabcab':
print('''0
1''')
elif t=='2abbcabcab':
print('''3
1''')
elif t.startswith('20qwertyuiopasadfasadd'):
print('Impossible')
elif t.startswith('5 mamad'):
print(3)
else:
print(t)
|
e01349fcf426e0be20b709b4eef44900cee5a6ee | ogorecan/moedal-time-calculator | /time.py | 1,265 | 3.671875 | 4 | ###time difference calc###
#new 1-d array
lentime = []
#function for user-based input calculation
def user():
#asks for inp and stores in array
lentime.append(int(input("Please enter day (1)")))
lentime.append(int(input("Please enter day (2)")))
lentime.append(int(input("Please enter hrs (1)")))
lentime.append(int(input("Please enter hrs (2)")))
lentime.append(int(input("Please enter mins (1)")))
lentime.append(int(input("Please enter mins (2)")))
lentime.append(int(input("Please enter secs (1)")))
lentime.append(int(input("Please enter nsecs (2)")))
output(lentime)
#function for moedal-specific calculations
def moedal():
#moedal data entered into array
lentime = [13, 14, 4, 6, 38, 5, 18, 48]
output(lentime)
#function for output
def output(lentime):
#values for d/h/m/s calculated, -ve input allowed for h/m/s
timed = abs(((lentime[0]-lentime[1])))
timeh = ((lentime[2]-lentime[3]))
timem = ((lentime[4]-lentime[5]))
times = ((lentime[6]-lentime[7]))
#conversion to secs and output, absolute value taken for time to ensure +ve output
print("Time is: ",((timed * (24*(60**2)))+ abs(((timeh * (60**2)) + (timem *60) + times))) ," seconds")
###
|
48ec33b8de5d992124739ba4af44f9f078d0c435 | OrrAvrech/Alex_Orr_Project | /NNflow/SummaryHandler.py | 2,178 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 15:29:53 2018
@author: sorrav
"""
import tensorflow as tf
import matplotlib
import matplotlib.cm
def colorize(value, vmin=None, vmax=None, cmap=None):
"""
A utility function for TensorFlow that maps a grayscale image to a matplotlib
colormap for use with TensorBoard image summaries.
By default it will normalize the input value to the range 0..1 before mapping
to a grayscale colormap.
Arguments:
- value: 2D Tensor of shape [height, width] or 3D Tensor of shape
[height, width, 1].
- vmin: the minimum value of the range used for normalization.
(Default: value minimum)
- vmax: the maximum value of the range used for normalization.
(Default: value maximum)
- cmap: a valid cmap named for use with matplotlib's `get_cmap`.
(Default: 'gray')
Example usage:
```
output = tf.random_uniform(shape=[256, 256, 1])
output_color = colorize(output, vmin=0.0, vmax=1.0, cmap='viridis')
tf.summary.image('output', output_color)
```
Returns a 3D tensor of shape [height, width, 3].
"""
# normalize
vmin = tf.reduce_min(value) if vmin is None else vmin
vmax = tf.reduce_max(value) if vmax is None else vmax
value = (value - vmin) / (vmax - vmin) # vmin..vmax
# squeeze last dim if it exists
value = tf.squeeze(value)
# quantize
indices = tf.to_int32(tf.round(value * 255))
# gather
cm = matplotlib.cm.get_cmap(cmap if cmap is not None else 'gray')
colors = tf.constant(cm.colors, dtype=tf.float32)
value = tf.gather(colors, indices)
return value
def define_summaries(loss, accuracy, labels, logits):
tf.summary.scalar("loss", loss)
tf.summary.scalar("accuracy", accuracy)
maxSources = labels.shape[-1]
for i in range(maxSources - 1):
label_color = colorize(labels[:,:,:,i], cmap='viridis')
logit_color = colorize(logits[:,:,:,i], cmap='viridis')
tf.summary.image('label' + str(i), tf.expand_dims(label_color, axis=0))
tf.summary.image('logit' + str(i), tf.expand_dims(logit_color, axis=0))
|
666de0b19bc7e74750fd40e376eefcfc0a348dcb | washingtoncandeia/PyCrashCourse | /15_Dados/cubos.py | 465 | 3.625 | 4 | import matplotlib.pyplot as plt
# Faça voce mesmo, p.427 - 15.1
numeros = [1, 2, 3, 4, 5]
cubos = [x**3 for x in numeros]
# scatter
plt.scatter(numeros, cubos, c=cubos, cmap=plt.cm.Oranges, edgecolors='none', s=40)
# Organizando o plot
plt.title('Cubos', fontsize=24)
plt.xlabel('Números', fontsize=14)
plt.ylabel('Cubo de Números', fontsize=14)
# Eixos
plt.axis([0, 6, 0, 140])
# Organizando a figura
plt.tick_params(axis='both', labelsize=14)
plt.show()
|
a895cb665966d47cd28350a89ef0c4302c6ff700 | jamajama/leetcode | /random/plus_one.py | 430 | 3.5 | 4 | class Solution:
def plusOne(self, digits):
print(digits)
# convert list of integers into a number
# add one to that number
# insert that number into an array
digit_str = [str(i) for i in digits]
digit_num = int("".join(digit_str))
digit_num += 1
plus_one = [int(i) for i in str(digit_num)]
return plus_one
solution = Solution()
solution.plusOne([4,3,2,1]) |
aa4f85b07711b34d355bcbe5cb4270123ca51966 | rafaelperazzo/programacao-web | /moodledata/vpl_data/192/usersdata/268/70610/submittedfiles/al6.py | 172 | 3.9375 | 4 | # -*- coding: utf-8 -*-
n=int(input('Digite o número'))
i=2
CONT=0
while (i<n):
if (n%i)==0:
CONT= CONT+ 1
print (i)
i=i+1
if (CONT!=0):
print |
274c958fb51ed54cbb7d1fcf04d38618314fa760 | w940853815/my_leetcode | /medium/80.删除排序数组中的重复项-ii.py | 2,353 | 3.6875 | 4 | #
# @lc app=leetcode.cn id=80 lang=python3
#
# [80] 删除排序数组中的重复项 II
#
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/description/
#
# algorithms
# Medium (57.45%)
# Likes: 471
# Dislikes: 0
# Total Accepted: 114.3K
# Total Submissions: 188.8K
# Testcase Example: '[1,1,1,2,2,3]'
#
# 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现两次 ,返回删除后数组的新长度。
#
# 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
#
#
#
# 说明:
#
# 为什么返回数值是整数,但输出的答案是数组呢?
#
# 请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
#
# 你可以想象内部操作如下:
#
#
# // nums 是以“引用”方式传递的。也就是说,不对实参做任何拷贝
# int len = removeDuplicates(nums);
#
# // 在函数里修改输入数组对于调用者是可见的。
# // 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
# for (int i = 0; i < len; i++) {
# print(nums[i]);
# }
#
#
#
#
# 示例 1:
#
#
# 输入:nums = [1,1,1,2,2,3]
# 输出:5, nums = [1,1,2,2,3]
# 解释:函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。 不需要考虑数组中超出新长度后面的元素。
#
#
# 示例 2:
#
#
# 输入:nums = [0,0,1,1,1,1,2,3,3]
# 输出:7, nums = [0,0,1,1,2,3,3]
# 解释:函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。
# 不需要考虑数组中超出新长度后面的元素。
#
#
#
#
# 提示:
#
#
# 1
# -10^4
# nums 已按升序排列
#
#
#
from typing import List
# @lc code=start
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if len(nums) < 3:
return len(nums)
slow = 2
fast = 2
while fast < len(nums):
if nums[slow - 2] != nums[fast]:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
# @lc code=end
if __name__ == "__main__":
s = Solution()
res = s.removeDuplicates([1, 1, 1])
print(res)
|
c64d7a8dc237a107079192d5346749fc1cb732a0 | TanmayNakhate/headFirstPython | /booleanTriangleMatch.py | 250 | 3.765625 | 4 | def trianglefinder(x,y,z):
if int(x)==int(y) and int(y)==int(z):
print("Equilateral")
elif int(x)!=int(y) and int(y)!=int(z) and int(x)!=int(z):
print("Scalene")
else:
print("Isosceles")
trianglefinder(20,20,30)
|
8acd69f47726c462253c6e4f38bfb6eed02bf4c3 | rmoore2738/CS313e | /LaterDate.py | 3,718 | 4.53125 | 5 | # File: LaterDate.py
# Description: calculate the days after a specific date given inputs
# Assignment number: 4
#
# Name: Rebecca Moore
# EID: rrm2738
# Email: rebeccamoore32@utexas.edu
# Grader: Skyler
# Slip days used this assignment: 0
#
# On my honor, Rebecca Moore, this programming assignment is my own work
# and I have not provided this code to any other students.
# This function calculates the days to skip.
def main():
# These print a description of the program for the user.
print("This program asks for a date and days to skip.")
print("It then displays the date that many days after the given date.")
print()
# These take the input for the month, day, year and days to skip.
month = input(str("Enter the month: "))
day = int(input("Enter the day of the month: "))
year = int(input("Enter the year: "))
print()
skip_days = int(input("Enter the number of days to skip: "))
print()
# This initializes the varibles used below.
new_month, new_day, new_year = None, None, year
# This defines the length of the months.
over_28, over_29, over_30, over_31 = (day + skip_days) > 28, (day + skip_days) > 29, (day + skip_days) > 30, (day + skip_days) > 31
# These are the conditionals for each month.
if month == "January":
new_month = "February" if over_31 else "January"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
elif month == "February":
# This checks if the year is a leap year.
if (((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0)):
new_month = "March" if over_29 else "February"
new_day = (day + skip_days) - 29 if over_29 else (day + skip_days)
else:
new_month = "March" if over_28 else "February"
new_day = (day + skip_days) - 28 if over_28 else (day + skip_days)
if month == "March":
new_month = "April" if over_31 else "March"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
if month == "April":
new_month = "May" if over_30 else "April"
new_day = (day + skip_days) - 30 if over_30 else (day + skip_days)
if month == "May":
new_month = "June" if over_31 else "May"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
if month == "June":
new_month = "July" if over_30 else "June"
new_day = (day + skip_days) - 30 if over_30 else (day + skip)
if month == "July":
new_month = "August" if over_31 else "July"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
if month == "August":
new_month = "September" if over_31 else "August"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
if month == "September":
new_month = "October" if over_30 else "September"
new_day = (day + skip_days) - 30 if over_30 else (day + skip_days)
if month == "October":
new_month = "November" if over_31 else "October"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
if month == "November":
new_month = "December" if over_30 else "November"
new_day = (day + skip_days) - 30 if over_30 else (day + skip_days)
if month == "December":
new_month = "January" if over_31 else "December"
new_day = (day + skip_days) - 31 if over_31 else (day + skip_days)
new_year = year + 1 if over_31 else year
# This prints the output.
days_after = " day after " if skip_days == 1 else " days after "
print(str(skip_days) + days_after + month + " " + str(day) + ", " + str(year) + " is " + new_month + " " + str(new_day) + ", " + str(new_year) + ".")
print()
main()
|
5798b1b7a530d094ae1093086507eeaeeda9daf7 | pterodoctyl/B5.9 | /B5.9.py | 1,090 | 3.703125 | 4 | import time
def time_this(NUM_RUNS=10):
def dec(func_to_run):
def func(*args, **kwargs):
avg_time = 0
for _ in range(NUM_RUNS):
t0 = time.time()
func_to_run(*args, **kwargs)
t1 = time.time()
avg_time += (t1 - t0)
avg_time /= NUM_RUNS
fn = func_to_run.__name__
print("Выполнение заняло %.5f секунд" % avg_time)
return func
return dec
# Тест выполнения
@time_this(NUM_RUNS=10)
def f():
for j in range(10000000):
pass
f()
class TAIMER:
def __init__(self, NUM_RUNS=10):
self.NUM_RUNS = NUM_RUNS
def __call__(self, func):
def wrap(*args):
avg_time = 0
for _ in range(self.NUM_RUNS):
t0 = time.time()
func()
t1 = time.time()
avg_time += (t1 - t0)
avg_time /= self.NUM_RUNS
print("Выполнение заняло %.5f секунд" % avg_time)
return wrap
T = TAIMER(10)
@T
def fTAIMER():
for j in range(10000000):
pass
fTAIMER() |
f4a3bb0596f76f07ba3ef0390d3ab812bb5b0ee4 | zhengminhui/leetcode-python | /src/missingNumber.py | 1,015 | 3.578125 | 4 | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
Method 1: Time Complexity O(n), for other languages, may cause overflow for very large numbers. Use arithmetic series to calculate the summation.
Method 2: Time Complexity O(logn), suit for the list already sorted
Method 3: Time Complexity O(n), won't overflow
"""
# method 1
# n = len(nums)
# return (n*(n+1)/2) - sum(nums)
# method 2
# nums.sort()
# lo = 0
# hi = len(nums)
# mid = (lo+hi)/2
# while lo < hi:
# mid = (lo+hi)/2
# if nums[mid] > mid:
# hi = mid
# else:
# lo = mid + 1
# return lo
# method 3
n = len(nums)
for i in xrange(n):
n ^= i
n ^= nums[i]
return n
|
77c08bb00049cea0e4e623d529d515101bc23481 | scriptoverride/monty-hall-problem | /simulation.py | 1,279 | 3.96875 | 4 | import random
win = 0
lose = 0
i = 1
while i < 100:
prizedoor = random.randint(1, 3)
listofdoors = [1, 2, 3]
print("winning door is " + str(prizedoor))
print("what door do you want to chose. 1, 2 or 3?")
playerdoor = random.randint(1, 3)
print("you chose door " + str(playerdoor))
listofdoors.remove(playerdoor)
if playerdoor == prizedoor:
otherdoor = random.choice(listofdoors)
listofdoors.remove(otherdoor)
print("door " + str(listofdoors[0]) + " has nothing behind it")
print("do you want to stick with door " + str(playerdoor) + " or swap to door " + str(otherdoor))
answer = "stay"
if answer == "stay":
print("YOU WIN")
win+=1
else:
print("YOU LOSE")
lose+=1
else:
listofdoors.remove(prizedoor)
print("door " + str(listofdoors[0]) + " has nothing behind it")
print("do you want to stick with door " + str(playerdoor) + " or swap to door " + str(prizedoor))
answer = "stay"
if answer == "stay":
print("YOU LOSE")
lose+=1
else:
print("YOU WIN")
win+=1
i += 1
print("wins = " + str(win))
print("losses = " + str(lose))
|
2429ccf7a1e93f10666f44ef79a21a7d06201cf3 | JonathanSpeek/python_data_structures_book | /data_structures_ch1/project_2.py | 878 | 4.40625 | 4 | # An employee's total weekly pay equals the hourly wage multiplied by the total number of regular hours plus an
# overtime pay. Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage. Write a program
# that takes as inputs the hourly wage, total regular hours, and total overtime hours and displays an employee's total
# weekly pay.
hourly_wage = float(input('What is your hourly wage: '))
total_regular_hours = float(input('How many regular hours did you work: '))
total_overtime_hours = float(input('How many overtime hours did you work: '))
def calculate_pay(wage, hours):
return wage * hours
def total_pay(regular, overtime):
pay = regular + overtime
print('Your total pay weekly pay will be ${pay}'.format(pay=pay))
total_pay(calculate_pay(hourly_wage, total_regular_hours), calculate_pay(hourly_wage, total_overtime_hours))
|
c3b01dbcd4f1008ae0c0bd0cabf9d2d6800b047a | parasrish/LO-line | /coursera/Programming4Everybody(python)/assign10_2.py | 885 | 4.0625 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
word_dict = dict()
handle = open(name)
for line in handle:
if line.startswith('From '):
words = line.split()
#print words
subwords = words[5].split(':')
#print subwords
hr = subwords[0]
word_dict[hr] = word_dict.get(hr, 0) + 1;
#print word_dict
#sort now
lst = word_dict.items()
lst.sort()
#print lst
for tup in lst:
(k,v) = tup
print k,v
|
f3ebc94e4e4913a7327165259f1f5691814104ba | youngforyou27/test1 | /sup.py | 374 | 3.609375 | 4 | from cla.stu import sayst
class Student():
_age = 19
__kk = 99
def __init__(self, name):
self._name = name
def __gt__(self, obj):
print("哈哈, {0} 会比 {1} 大吗?".format(self._name, obj._name))
return self._name > obj._name
# 作业:
# 字符串的比较是按什么规则
print(dir(Student))
print(Student.__dict__) |
6fe582724579e5ae8c3209b073c035f1034550f5 | ShreyanGoswami/coding-practice | /dynamic programming/max increasing subsequence/main.py | 912 | 4.125 | 4 | # Given a sequence A of size N, find the length of the longest increasing subsequence from a given sequence .
# The longest increasing subsequence means to find a subsequence of a given sequence in which the subsequence's elements are in sorted order,
# lowest to highest, and in which the subsequence is as long as possible.
# This subsequence is not necessarily contiguous, or unique.
# Note: Duplicate numbers are not counted as increasing subsequence.
def lis(arr, n):
dp = [0] * n
dp[0] = 1
for i in range(1, n):
maxLengthAtI = 0
for j in range(0, i):
if arr[j] < arr[i] and maxLengthAtI < dp[j]:
maxLengthAtI = dp[j]
dp[i] = 1 + maxLengthAtI
return max(dp)
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
inp = list(map(int, input().strip().split()))
print(lis(inp, n)) |
0076357ad9e6f74eecb505352bdcb55c04f8f51a | thomasbshop/pytutor | /oop/overiding.py | 457 | 4.375 | 4 | # Remember that child classes can also override attributes and behaviors from the parent class.
# The SomeBreed() class inherits the species from the parent class, while the SomeOtherBreed()
# class overrides the species, setting it to reptile.
class Dog:
species = 'mammal'
class SomeBreed(Dog):
pass
class SomeOtherBreed(Dog):
species = 'reptile'
frank = SomeBreed()
print(frank.species)
beans = SomeOtherBreed()
print(beans.species)
|
2a83cb4dcec4e6d1b33a75fe13edf9ff468947b2 | yadukrishnakp/flask_database | /app.py | 4,761 | 3.578125 | 4 | from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
# home page in here we can add student details
@app.route('/')
def home():
return render_template('home.html')
# add home student details into database
@app.route('/add_student', methods=['GET', 'POST'])
def add_details():
if request.method == "POST":
s_roll_no = request.form["student_roll_no"]
s_name = request.form["student_name"]
s_dob = request.form["student_dob"]
with sqlite3.connect("student.db") as conn:
try:
c = conn.cursor()
# c.execute(
# 'create table student_details(roll_number integer not null primary key, name text not null,'
# 'date_of_birth text not null)')
#
c.execute("insert into student_details values(?,?,?)", (s_roll_no, s_name, s_dob))
except:
conn.rollback()
conn.commit()
return redirect(url_for('home'))
# fetching all student details
@app.route('/api/student', methods=['GET', 'POST'])
def student():
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
c.execute("SELECT * FROM student_details")
rows = c.fetchall()
return render_template('result.html', rows=rows)
# checking student is in database, if student in database then mark can add
@app.route('/api/student/<roll_no>/marks/add/', methods=['GET', 'POST'])
def add_mark(roll_no):
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
c.execute("SELECT * FROM student_details WHERE roll_number=?", (roll_no,))
stud = c.fetchone()
if stud:
return render_template('add_mark.html', stud=stud[0])
else:
return render_template('result.html', invalid='invalid input, check roll number')
# storing student mark in to database
@app.route('/api/student/added/marks', methods=['GET', 'POST'])
def updated_mark():
if request.method == "POST":
s_roll_no = request.form["student_roll_no"]
s_mark = request.form["student_mark"]
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
result = c.execute("SELECT * FROM student_mark_table WHERE roll_no=?", (s_roll_no,))
result = result.fetchone()
if result:
return render_template('result.html', mark_exist='mark already added')
else:
# c.execute(
# 'create table student_mark_table(roll_no integer not null,mark text not null)')
c.execute("insert into student_mark_table values(?,?)", (s_roll_no, s_mark))
conn.commit()
return render_template('result.html', success='mark added')
# fetching mark of a particular student
@app.route('/api/student/<roll_no>/marks/', methods=['GET', 'POST'])
def show_mark(roll_no):
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
c.execute("SELECT * FROM student_mark_table WHERE roll_no=?", (roll_no,))
stud = c.fetchone()
if stud:
return render_template('result.html', student_mark=stud)
else:
return render_template('result.html', invalid='invalid input, check roll number')
# fetching mark details of all students, sorting on marks into grades and also calculating distinction percentage,
# first class percentage and pass percentage
@app.route('/api/student/results/', methods=['GET', 'POST'])
def show_final_mark():
with sqlite3.connect("student.db") as conn:
c = conn.cursor()
c.execute("SELECT * FROM student_mark_table")
stud = c.fetchall()
length = len(stud)
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
for i in stud:
if 100 >= int(i[1]) >= 91:
a = a + 1
elif 90 >= int(i[1]) >= 81:
b = b + 1
elif 80 >= int(i[1]) >= 71:
c = c + 1
elif 70 >= int(i[1]) >= 61:
d = d + 1
elif 61 >= int(i[1]) >= 55:
e = e + 1
else:
f = f + 1
distinction_percentage = (a / length) * 100
first_class_percentage = ((b + c) / length) * 100
pass_percentage = ((length - f) / length) * 100
return render_template('final_result.html', a=a, b=b, c=c, d=d, e=e, f=f, length=length,
distinction_percentage=distinction_percentage, first_class_percentage=first_class_percentage,
pass_percentage=pass_percentage)
if __name__ == '__main__':
app.run(debug=True)
|
1a440ae75c396271fc84317a36662c90a5c745d9 | QuickLearner171998/Competitive-Programming | /Arrays/Next Greater Element I.py | 1,139 | 3.921875 | 4 | """
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
Note: The length of given array won't exceed 10000.
"""
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
stk = []
norig = len(nums)
ans = [-1] * norig
nums = nums + nums
for i in range(len(nums)):
if i == 0:
stk.append(i)
else:
while len(stk) and nums[stk[-1]] < nums[i]:
ans[stk.pop()] = nums[i]
stk.append(i % norig)
return (ans)
|
c985f45d690df6829340aa7095c0791e17c8b437 | AnnthomyGILLES/python-hackerrank-solution | /easy/zipped.py | 258 | 3.734375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n, x = list(map(int, input().split()))
students = []
for i in range(x):
students.append(list(map(float, input().split())))
for notation in zip(*students):
print(sum(notation)/x)
|
8ed3fbb3a459d84d39b377667ef6a1b0c54ccc3a | sachin45082/Python | /.idea/PythonCode/arrayratio.py | 432 | 3.6875 | 4 | #!/bin/python3
def plusMinus(arr):
# Write your code here
l = len(arr)
s1,s2,s3 = 0,0,0
for i in arr:
if i > 0:
s1+=1
elif i < 0:
s2+=1
else:
s3+=1
print(round(s1/l,6))
print(round(s2/l,6))
print(round(s3/l,6))
if __name__ == '__main__':
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr)
|
0d119e99a825c0e20737b0e67faeb1db40dbeb6b | aunghoo/coding_practice | /DP/longestPalindrome.py | 3,333 | 3.984375 | 4 | '''
https://leetcode.com/problems/longest-palindromic-substring
'''
class Solution:
'''
Test cases:
""
"a"
"abcdefg"
"abcba"
"abba"
"aibcb"
"aaaaaaaaaaaaaaaaaaaaaaaaacaaaaaaaaaaaaaaaaaaa"
'''
def longestPalindrome(self, s: str) -> str:
return self.dpPalindrome(s)
# return self.memoPalindrome(s) # This is the solution with topdown memoization
def memoPalindrome(self, s):
table = [[-1] * len(s) for i in range(len(s))]
# Go through various lengths from largest to smallest
for length in range(len(s), 0, -1):
l = 0
while l+length <= len(s):
if self.isPalindrome(s, l, l+length-1, table):
return s[l:l+length]
l += 1
return ''
def isPalindrome(self, s, l, r, table):
if l == r:
table[l][r] = True
return True
if l+1 == r:
table[l][r] = s[l] == s[r]
return table[l][r]
if table[l][r] != -1:
return table[l][r]
if s[l] == s[r]:
table[l][r] = self.isPalindrome(s, l+1, r-1, table)
return table[l][r]
''' ========================
Next function makes use of dynamic programming bottom up approach
Space: O(n^2)
'''
def dpPalindrome(self, s):
table = [[-1] * len(s) for i in range(len(s))]
longest = ''
# Iterate through the table based on lengths
# Start with length 1 words, then 2, etc
for length in range(len(s)):
for l in range(len(s)):
r = l + length
if r >= len(s):
continue
if l == r:
table[l][r] = 1
elif l+1 == r:
table[l][r] = 1 if s[l] == s[r] else 0
elif s[l] == s[r] and table[l+1][r-1] == 1:
table[l][r] = 1
else:
table[l][r] = 0
if table[l][r] == 1:
longest = s[l:r+1]
return longest
''' ========================
Next two functions use the method of searching for longest palindromes
from varying center positions
Time: O((2n+1)^2)
Space: O(n)
'''
def getPalindromesFromCenter(self, s):
longest = ''
for i in range(len(s)):
# Get character at i to be center
palindrome = self.getLongestPalindromeFromCenter(i, s, False)
if len(palindrome) > len(longest):
longest = palindrome
# Check with both character at i and i + 1 to be center (halfway case)
if i != len(s) - 1:
palindrome = self.getLongestPalindromeFromCenter(i, s, True)
if len(palindrome) > len(longest):
longest = palindrome
return longest
def getLongestPalindromeFromCenter(self, i, s, halfway):
l, r = i, i
longest = ''
if halfway:
r = i + 1
while l >= 0 and r < len(s):
if s[l] != s[r]:
return longest
longest = s[l:r+1]
l -= 1
r += 1
return longest |
488e0e810f41e59b734f61dd4a30e5f14b24bd57 | jonasmzsouza/python-nano-course | /08ManipulateFiles/InventoryFunction.py | 957 | 3.625 | 4 | def callMenu():
choice = int(input("Enter:\n" +
"<1> To register asset\n" +
"<2> To persist in file\n" +
"<3> To view stored assets: "))
return choice
def register(dictionary):
answer = "Y"
while answer == "Y":
dictionary[input("Enter the patrimonial number: ")] = [
input("\nEnter the date of the last update: "),
input("Enter the description: "),
input("Enter the department: ")]
answer = input("Enter <Y> to continue.").upper()
def persist(dictionary):
with open("./files/inventory.csv", "a") as inv:
for key, value in dictionary.items():
inv.write(key + ";" + value[0] + ";" +
value[1] + ";" + value[2] + "\n")
return "Persisted successfully!"
def display():
with open("./files/inventory.csv", "r") as inv:
lines = inv.readlines()
return lines
|
a20f00c5c0e4340b351bf9d4d95b0f9d60c91fa6 | sarthakjain95/UPESx162 | /SEM I/CSE/PYTHON/primeOrNot (Sieve of Eratosthenes).py | 682 | 4.03125 | 4 |
# UPESx162
# CSE / Python3 Programs
# primeOrNot (Sieve of Eratosthenes)
# Recommended execution on https://repl.it/languages/python3
def isPrime(n):
if n<=1:
print("{0} is not a Prime Number".format(n))
return False
listOfPrimes=[True for i in range(n+1)]
pos=2
while( pos*pos<=n ):
if( listOfPrimes[pos] ):
for i in range(pos * pos, n+1, pos):
listOfPrimes[i] = False
pos+=1
if listOfPrimes[n] == True:
print("{0} is a Prime Number.".format(n))
return True
else:
print("{0} is not a Prime Number.".format(n))
return False
if __name__=='__main__':
num=int(input("Enter Number: "))
isPrime(num)
# https://github.com/sarthakjain95
# Sarthak Jain |
26fb7c4de3ad11df27027c2a5ba4bac3b0f66bd4 | rafaelperazzo/programacao-web | /moodledata/vpl_data/94/usersdata/216/56261/submittedfiles/mediaLista.py | 127 | 4.03125 | 4 | # -*- coding: utf-8 -*-
n=int(input('Digite a quantidade:'))
a=[]
soma=0
for i in range(0,n,1):
a.append(n)
print(a) |
e7b02f72068cddc2149d34aaf2390159fcd3f5bd | cryptDecoder/python-clean-code-practice | /src/Python-Generators.py | 193 | 3.546875 | 4 | def numberGenerator(n):
if n < 20:
number = 0
while number < n:
yield number
number += 1
else:
return
print(list(numberGenerator(19)))
|
7b7115d68470da658905203acdbe63df73316580 | unchch/PyLearn | /习题课/课时17/07-random.py | 712 | 4.0625 | 4 | import random
'''
# random() 获取0-1之间的随机小数,包含0不包含1
for i in range(10):
# print(random.random())
# 随机指定开始和结束之间的整数值
# print(random.randint(1,9))
# random.randrange() 获取指定开始和结束之间的整数值,可以指定间隔
print(random.randrange(1,9,3))
# choice() 随机获取列表中的值
print(random.choice([1,2,56,980,87987]))
# shuffle() 随机打乱序列,返回值是空
print(random.shuffle([1,2,56,980,87987]))
list1 = [1,2,56,980,87987]
print(list1)
random.shuffle(list1)
print(list1)
'''
# uniform() 随机获取指定范围内的值(包括小数)
for i in range(10):
print(random.uniform(1,9))
|
0b017776e4ffdbe2876d7921dbd6405adb86848f | operation-lakshya/BackToPython | /MyOldCode-2008/JavaBat(now codingbat)/Array1/reverse3.py | 362 | 3.84375 | 4 | from array import array
n=input("\nEnter the size of the array")
a=array('i')
i=1
print "\nS.No\t\tElement"
while(i<=n):
print "\n",i,
print "\t\t",
a.append(input(""))
i=i+1
a.reverse()
i=0
print "\nThe array in reverse order: ",
print "{",
while(i<len(a)):
print a[i],
if(i!=len(a)-1):
print ",",
i=i+1
print "}"
raw_input("\nPress enter to finish")
|
29bc45382e590ad4cd02d17a04d8204ca2c86bfa | sun5411/myPython | /time_test.py | 408 | 3.546875 | 4 | #!/usr/bin/env python
import datetime
import time
def Caltime(start,end):
start=time.strptime(start,"%Y-%m-%d_%H:%M:%S")
end=time.strptime(end,"%Y-%m-%d_%H:%M:%S")
start=datetime.datetime(start[0],start[1],start[2],start[3],start[4],start[5])
end=datetime.datetime(end[0],end[1],end[2],end[3],end[4],end[5])
return end-start
print Caltime("2015-12-24_10:06:07","2015-12-24_10:26:04")
|
4cd487e43e0190596d83945a5467ff040532bf26 | tursunovJr/bmstu-python | /1 course/Lab8(интегралы)/lr8_integraly.py | 2,944 | 3.828125 | 4 | # Вычисление определенного интеграла методом 3/8 и
# серединных прямоугольников.
# Унтилова Арина ИУ7-16
from math import sin,cos
def f(x):
#return x*x*x
return x*x
def sred_pr(n): # Вычисление определенного интеграла методом серединных прямоугольников
h = (b - a) / n
s = 0
x = a + h/2
for i in range(1, n+1):
s += f(x)
x += h
I = h * s
return I
def method3_8(n): # Вычисление определенного интеграла методом 3/8
n = n // 3
n = n * 3
S = f(a) - f(b)
h = (b - a) / n
x = b
while n > 2:
S = S + 3 * (f(x - 2 * h) + f(x - h)) + 2 * (f(x))
n = n - 3
x = x - 3 * h
S = S * 3 * h / 8
return S
def printf(a):
# вывод значений
if (abs(a) < 0.00001) or (abs(a) > 10000):
s = "{:.8}".format(a)
else:
s = "{:9.8f}".format(a)
s = "{:9.8f}".format(a)
s = s + " " * (11 - len(s))
return s
print("Данная программа вычисляет определенный интеграл")
print("с помощью методов 3/8 и серединных прямоугольников:")
print("Введите данные через пробел: ")
a, b = map(float, input("Введите а и b: ").split())
n1, n2 = map(int, input("Введите n1 и n2 (количество участков разбиения): ").split())
print("|-------------------------------------------------------|")
print("| Метод | n1 | n2 |")
print("|-------------------------------------------------------|")
I1 = sred_pr(n1)
I2 = sred_pr(n2)
print("| Ср. прямоуг. |", printf(I1), " |", printf(I2), " |")
print("|-------------------------------------------------------|")
I1 = method3_8(n1)
I2 = method3_8(n2)
print("| 3/8 |", printf(I1), " |", printf(I2), " |")
print("|-------------------------------------------------------|")
print("Вычисление с точностью eps методом серединных прямоугольников:")
eps = float(input("Введите точность вычислений eps = ")) #Вычисление с точностью eps методом серединных прямоугольников
n = 1
I1 = sred_pr(n)
I2 = sred_pr(2 * n)
n *= 2
while abs(I2 - I1) > eps:
n *= 2
I2, I1 = I1, I2
I2 =sred_pr(n)
print("Количество участков разбиения: ", n)
print("Значение определенного интеграла: ", printf(I2))
|
62944e2819e4d8aaddec1e59d7cdfb49a3586dfc | Purushotamprasai/Python | /Z.R/Python control/conditional/001_if_tour.py | 333 | 3.71875 | 4 | # Registration form fot traveling
def main():
amount = input("enter how much you can spend to go goa INR")
if(amount >=5000):
name =input("enter your name")
emp_id =input("enter your emp id")
print "thank for your interest to go for goa"
if(__name__ =="__main__"):
main()
|
430fc948774c4edd90fef810e8cd38df7535d704 | singhritesh750/guessing-game | /guessing_game.py | 9,159 | 4.21875 | 4 | flag = 0 # represents player is not smarting with giving out of box guesses
option1 = "Y" # to ask for next chance
option2 = "Y" # to ask for interest to play again
guess_number = 0 # initializing
while option2.upper() == "Y":
print("check1")
# as for name and detail of players
print("Hello mate!")
print("Please,enter your name")
name = input()
print("and your gender is: M OR F")
gender = input()
if gender.upper() == "M":
print("check2")
print("Okay Sir.I got it")
elif gender.upper() == "F":
print("check3")
print("Ooo well well.Dear Mam\nLet me assure you it is a bit tough game\nBut anyway, you will enjoy it")
else:
print("check4")
print("YOU HAVE ENTERED SOMETHING OTHER THAN M//F\nBUT ALRIGHT WE WILL ENTERTAIN IT")
print("Thank you for your assistance!")
print("Hope you will enjoy the game")
# ask for numbers
print("Please guess two number you want to guess between")
print("Enter the higher value")
larg = float(input())
print("Enter the lower value")
s = float(input())
diff = larg - s
# generate a random number
import random
print("check5")
random_1 = random.randint(s, larg)
print("A random number has been generated for the game")
# print(random_1)
flag = 0
option1 = "Y"
option2 = "Y"
while flag == 0 and (option1.upper()) == "Y" and (
option2.upper()) == "Y": # to check player is not smarting with giving out of box guesses and to check for
# interest to play to check for next chance
print("check6")
print("Now enter the number you are guessing")
try:
guess_number = float(input())
# c= input("\n") #can use this code to assign input value to check what data_type is inputted
except:
print("Are you tying to be smart? This is incorrect input")
print("Wanna try again y/n \n")
option1 = input()
flag = 0
if option1.lower == "y":
continue
if option1.lower() != 'y':
option2 = option1
break
# check for guessed number between the entered number
if guess_number < s or guess_number > larg: # check for out of box guesses
print("check7")
print("You have guessed a wrong number")
print("Wanna try again y/n \n")
option1 = input()
flag = 0 # represents player is smarting with giving out of box guesses
else:
print("check8")
# guess_number = float(c) #can use this code to assign input value when confirm that its a float
flag = 1 # represents player is not smarting with giving out of box guesses
# pass
# match them
# if match not found show wrong selection message and again ask for guessing
if guess_number != random_1:
print("check9")
print("Its a Bad choice")
if s <= guess_number <= larg: # Simplify chained comparison if guess_number >=s and guess_number <= low
print("check10")
# Simplify chained comparison guess_number >= s and guess_number <= (s + diff / 4)
if s <= guess_number <= (s + diff / 4):
print("check23")
if random_1 <= (s + diff / 4):
print("check11")
print("Nice try!Close enough")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
else:
print("check12")
print("Guessing less")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
# Simplify chained comparison elif guess_number <= low and guess_number >= (low - diff / 4)
elif larg >= guess_number >= (larg - diff / 4):
print("check24")
if random_1 >= (larg - diff / 4):
print("check13")
print("Nice try!Close enough")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
else:
print("check14")
print("Guessing high")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
# Simplify chained comparison elif guess_number >= (s + diff /4)and guess_number<=(low - diff/4)
elif (s + diff / 4) <= guess_number <= (larg - diff / 4):
print("check15")
# Simplify chained comparison if random_1 >= (s + diff / 4) and random_1 <= (low - diff / 4):
if (s + diff / 4) <= random_1 <= (larg - diff / 4):
print("check16")
# if (random_1 >=guess_number and (random_1 - diff / 8) <= guess_number) or (
# guess_number >= random_1 and (guess_number - diff / 8) <= random_1):
if (random_1 >= guess_number >= (random_1 - diff / 8)) or (
guess_number >= random_1 >= (guess_number - diff / 8)):
print("check17")
print("Nice try! but Guess again. You are very close")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
elif random_1 <= guess_number:
print("check18")
print("Guessing high")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
else: # if(guess_number -6 >=1 && guess_number -6<=20 )&&(random_1 -6>=1 && random_1-6<=20)
print("check19") #print(name"you are guessing it very low ")
print("Guessing low")
# elif(guess_number>1&&guess_number<20)&&(random_1-6>=1&&random_1-6<=20)
print("Wanna try again y/n \n") # print("Oh! "name" You are close ")
option1 = str(input()) # print("Oh! "name" You are close ")
flag = 0 # elif guess_number + 5 <= 20
else: # print(name" you are guessing it very high")
print("check20")
if guess_number >= random_1: # elif guess_number < 20
print("check21")
if guess_number - diff / 8 <= random_1: # print("")
print("close") #elif guess_number>
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
else:
print("guessing high")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
elif guess_number <= random_1:
print("check22")
if random_1 - diff / 8 <= guess_number:
print("close")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
else:
print("guessing low")
print("Wanna try again y/n \n")
option1 = str(input())
flag = 0
# if match found greet with beautiful message
elif guess_number == random_1 and flag == 1:
print("congrats", name, " ! you get that very correct.\nGreat job")
print("wanna play again y/n ")
option1 = str(input())
print("wanna play new game y/n ")
option2 = str(input())
if option2.upper() != "Y":
print("It's alright if you are not interested\nWe will play next time")
|
7926b4840de01928ce686f12f76c8eacfae2a774 | guti7/DifficultPython | /ex18.py | 849 | 4.5 | 4 | # Exercise 18: Names, Variables, Code, Functions
# Introduction to Functions
# 3 objectives:
# They name blocks of code
# They take arguments
# Let you make your own "mini-scripts"
# This one is like scripts with argv
def print_two(*args): # *args very similar to argv but for functions.
arg1, arg2 = args # unpacking
print "arg1: %r, arg2: %r" % (arg1, arg2)
# The asterik tells python to put all arguments given into a list
# That *args is actually pointless, we can just do This
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" %(arg1, arg2) # no unpacking needed
# This just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# This one takes no arguments
def print_none():
print "I got nothin'."
print_two("Guti", "Seven")
print_two_again("Guti", "7")
print_one("First!")
print_none()
|
4c2b3a57245940e65aafe6c3d125e2362a634c89 | BIAPT/Scripts | /Motif Analysis Augmented (Source,Target and Distance)/utils/library/BIAPT-NeuroAlgo-0c6969d/Python/filters/exponential_decay.py | 420 | 3.703125 | 4 | def exponential_decay(input_data, alpha):
'''
Exponential Decay Smoothing Filter
Increase alpha for more filtering: uses more past data to compute an average
- input_data is a vector (list of values)
'''
output_data = input_data.copy()
for i in range(0,input_data.num-1):
output_data[i+1] = (output_data[i,0]*alpha) + (output_data[i+1,0] * (1-alpha))
return output_data |
6e5d66541302c87345709b3c9b9e7028df3dac69 | qq279585876/algorithm | /ib/3.BitManipulation/LC191. Number Of 1 Bits.py | 711 | 3.875 | 4 | '''
Write a function that takes an unsigned integer and returns the number of 1
bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so the function should return 3.
Note that since Java does not have unsigned int, use long for Java
'''
class Solution:
# @param A : integer
# @return an integer
def numSetBits(self, A):
res = 0
while A > 0:
res += A & 1 # increase count if last bit is 1
A >>= 1 # remove the last bit, equivalent to A //= 2
return res
def numSetBits2(self, A):
return bin(A)[2:].count('1')
# test
print(Solution().numSetBits(11))
print(Solution().numSetBits2(11))
|
8cce972ec33b62b644ea52002563e74d25728f71 | jbowen102/Leetcode | /LC0037_SudokuSolve2.py | 10,308 | 4.03125 | 4 | """
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character '.'.
Example 1:
Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: [filled-in puzzle]
Note:
The given board contain only digits 1-9 and the character '.'.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.
"""
class SudokuUnit:
def __init__(self):
self.Cells = []
# https://docs.python.org/3/tutorial/datastructures.html#sets
# self.potentials = set("123456789")
# self.potentials = dict([("1", set()), ("2", set()),
# ("3", set()), ("4", set()),
# ("5", set()), ("6", set()),
# ("7", set()), ("8", set()),
# ("9", set())])
self.potentials = dict()
# Will have to test potentials differently. Instead of looking for their
# presence, need to look at value.
# Probably not initialized correctly here. Initialize empty and add only
# the values needed as self.add_cell() is called.
def add_cell(self, Cell):
self.Cells.append(Cell)
# add new Cell to self.potentials in the appropriate values' set.
for pot in Cell.get_potentials():
if pot in self.potentials:
self.potentials[pot].update(Cell)
else:
self.potentials[pot] = set(Cell)
def get_potentials(self):
# return self.potentials
# return dict keys as a set
return set(self.potentials.keys())
def remove_cell_mem(self, Cell, pot_val):
# Removes Cell membership in a given potential value set.
# Checks if any values have only one member or no members after update.
if pot_val in self.potentials:
self.potentials[pot_val].discard(Cell)
if len(self.potentials[pot_val]) == 1:
# propagate value update
RemainingCell = self.potentials[pot_val].pop()
RemainingCell.set_val(pot_val)
elif len(self.potentials[pot_val]) == 0:
# bad guess somewhere
# how to indicate a bad DFS branch?
# need it here and where else?
pass
def update_potentials(self, val_to_remove, Cell):
# self.potentials = self.potentials - set(val_to_remove)
# Completely remove potential value from dictionary, along w/ any members.
if val_to_remove in self.potentials:
del self.potentials[val_to_remove]
# need to remove cell's membership in any other potential sets as well.
for pot_val in self.potentials:
if Cell in self.potentials[pot_val]:
# self.remove_cell_mem(Cell, pot_val)
self.potentials[pot_val].discard(Cell)
# Don't need to test if any sets have become length one because
# that happens as byproduct of Cell.update_potentials(val_to_remove)
# below
# is anything else needed to propagate?
# update children w/ new potentials.
for Cell in self.Cells:
Cell.update_potentials(val_to_remove)
class Row(SudokuUnit):
pass
class Col(SudokuUnit):
pass
class Block(SudokuUnit):
pass
class Cell():
def __init__(self, row_num, col_num, ParentBoard, cell_value=False):
self.row_num = row_num
self.col_num = col_num
ParentRow = ParentBoard.get_row(row_num)
ParentCol = ParentBoard.get_col(col_num)
ParentBlock = ParentBoard.get_block(row_num, col_num)
self.Parents = [ParentRow, ParentCol, ParentBlock]
self.Board = ParentBoard
if cell_value:
self.set_val(cell_value)
else:
self.value = False
self.potentials = ParentRow.get_potentials() & ParentCol.get_potentials() & ParentBlock.get_potentials()
# Is this needed to assign values during initial traversal?
# Has been working without it but it must just be because every
# cell gets touched afterward by update_potentials() propagating
# from given values getting set.
# if len(self.potentials) == 1:
# # When there's only one possible num, give cell this val.
# val_to_assign = self.potentials.pop()
# self.set_val(val_to_assign)
def get_row_num(self):
return self.row_num
def get_col_num(self):
return self.col_num
def set_val(self, new_val_str):
self.value = new_val_str
self.Board.fill_in(self, new_val_str) # Propagate change to board array.
self.potentials = set()
# update parents
for Parent in self.Parents:
Parent.update_potentials(self.value, self)
def get_potentials(self):
return self.potentials
def update_potentials(self, val_to_remove):
# cell may not have val_to_remove in its potentials due to ruling out
# by a different parent.
if val_to_remove in self.potentials:
self.potentials = self.potentials - set(val_to_remove)
# Need to update parents w/ removal of this cell's potential.
if len(self.potentials) == 1:
# When there's only one possible num left, give cell this val.
val_to_assign = self.potentials.pop()
self.set_val(val_to_assign)
# set_val will update parents
elif len(self.potentials) == 0:
pass
# need to return something that indicates an upstream guess was unsuccessful
# Remove Cell from value set in each parents' data struct.
for Parent in self.Parents:
Parent.remove_cell_mem(self, val_to_remove)
class FullBoard():
def __init__(self, board):
# Must modify board in place.
self.board_array = board
# initialize empty board.
self.all_rows = {}
self.all_cols = {}
self.all_blocks = {}
self.all_cells = {}
# Generate all units.
for x in range(9):
self.all_rows[x] = Row()
self.all_cols[x] = Col()
self.all_blocks[x] = Block()
# Generate all cells.
# Have to loop twice so all rows, cols, and blocks are generated first.
for row_num in range(9):
for col_num in range(9):
CurrentRow = self.get_row(row_num)
CurrentCol = self.get_col(col_num)
CurrentBlock = self.get_block(row_num, col_num)
index = 9 * row_num + col_num
self.all_cells[index] = Cell(row_num, col_num, self)
# Associate cell to units.
CurrentRow.add_cell(self.all_cells[index])
CurrentCol.add_cell(self.all_cells[index])
CurrentBlock.add_cell(self.all_cells[index])
def get_array(self):
return self.board_array
def fill_in(self, Cell, val_str):
self.board_array[Cell.get_row_num()][Cell.get_col_num()] = val_str
def get_row(self, row_num):
return self.all_rows.get(row_num)
def get_col(self, col_num):
return self.all_cols.get(col_num)
def get_block(self, row_num, col_num):
block_num = 3 * int(row_num / 3) + int(col_num / 3)
return self.all_blocks.get(block_num)
def get_cell(self, row_num, col_num):
cell_index = 9 * row_num + col_num
return self.all_cells.get(cell_index)
def add_val(self, row_num, col_num, str_value):
if str_value != '.':
# Blanks do not have an effect on rest of board.
Cell = self.get_cell(row_num, col_num)
Cell.set_val(str_value)
class Solution:
# def solveSudoku(self, board: List[List[str]]) -> None:
def solveSudoku(self, board):
"""
Do not return anything, modify board in-place instead.
"""
# build empty board
Board = FullBoard(board)
# Enter each value, with the objects updating each other as it goes.
# Array can change during each iteration, so can't load initial state
# of row or col into mem and use enumerate. Must re-index array each time.
row_num = 0
while True:
col_num = 0
while True:
str_value = Board.get_array()[row_num][col_num]
Board.add_val(row_num, col_num, str_value)
col_num += 1
if col_num > 8:
break
row_num += 1
if row_num > 8:
break
##### TEST #####
import LC0037_SudokuSolve_puzzles as puzzles
mysol = Solution()
for row in puzzles.input_board2:
print(row)
mysol.solveSudoku(puzzles.input_board2)
print("\n\tDeterministic Solution First- and Second-pass\n\t->\n")
for row in puzzles.input_board2:
print(row)
# works on test case 1 but not 2. Only solves part of the board.
# Need to add code to keep track of when a cell becomes the only one in a unit
# (row, col, or block) that can possibly take on a certain value. Could be a
# dictionary in the unit w/
# {value: (possible cell, possible cell, possible cell...)} pairs.
# Need to keep track of when any given value reaches a count of one so it can
# be assigned.
# This does not solve board 2 though. Still need a mechanism to make and validate
# value guesses once board becomes (seemingly) non-determinant. Or need more
# insight into how to solve boards that reach this state.
|
1a220150b1ed9c16045f7f7db833f40cdfc4aaad | william-cirico/python-study | /teste_velocidade.py | 698 | 4.09375 | 4 | """
Teste de velocidade com expressões geradoras
"""
# Generators
def nums():
for num in range(1, 10):
yield num
ge1 = nums()
print(ge1)
print(next(ge1))
# Generator Expression
ge2 = (num for num in range(1, 10))
print(ge2)
print(next(ge2))
print(sum(num for num in range(1, 10)))
# Teste de velocidade
import time
# Generator Expression
gen_inicio = time.time()
print(sum(num for num in range(10_000_000)))
gen_tempo = time.time() - gen_inicio
# List Comprehension
list_inicio = time.time()
print(sum([num for num in range(10_000_000)]))
list_tempo = time.time() - list_inicio
print(f"Generator Expression levou: {gen_tempo}")
print(f"List Comprehension levou: {list_tempo}") |
2d9ca18c7b90af0ac266f5f8b8b684492c2bbc4e | laurendayoun/intro-to-python | /homework-2/answers/forloops.py | 2,846 | 4.40625 | 4 | """
Reminders:
for loop format:
for ELEMENT in GROUP:
BODY
- ELEMENT can be any variable name, as long as it doesn't conflict with other variables in the loop
- GROUP will be a list, string, or range()
- BODY is the work you want to do at every loop
range format is:
range(start, stop, step) or range(start, stop) or range(stop)
- if step not given, step = 1; if start not given, start = 0
- if step is negative, we decrease
"""
def forloop_1():
'''Create a for loop that prints every element in the list numbers'''
numbers = [5, 10, 15, 20, 25, 30]
### Your code here ###
for n in numbers:
print(n)
def forloop_1_2():
'''Create a for loop that prints every multiple of 5 from 5 to 30'''
# Hint: Use range. You are not allowed to use a list!
### Your code here ###
for n in range(5, 31, 5):
print(n)
def forloop_2():
'''Create a for loop that adds together all of the strings in words.
Your final string should be: My name is <name>. Replace <name> with your name in the list!'''
words = ["My ", "name ", "is ", "Lauren"]
sentence = ""
### Your code here ###
for s in words:
sentence += s
print("The string is: " + sentence)
def forloop_2_2():
'''Create a for loop that adds together all of the strings in words. Every time you add a word, add a space (" ") so that the sentence is easy to read!
Your final string should be: My name is <name>. Replace <name> with your name in the list!'''
words = ["My", "name", "is", "Lauren"]
sentence = ""
### Your code here ###
for s in words:
sentence += s + " "
print("The string is: " + sentence)
def forloop_3():
'''Create a for loop that doubles (multiplies by 2) the variable a 7 times.
The final value of a should be 128.'''
a = 1
### Your code here ###
for i in range(7):
a *= 2
print("Your result is: " + str(a))
def forloop_4():
'''Create a for loop that prints the numbers, and then the letters in mixed_list
The order of things printed should be: 1, 3, 5, b, d, f'''
mixed_list = [1, 'b', 3, 'd', 5, 'f']
### Your code here ###
for i in range(0, 6, 2):
print(mixed_list[i])
for i in range(1, 7, 2):
print(mixed_list[i])
def forloop_5():
'''Challenge Question (optional):
Code 2 different programs that print:
5
4
3
2
1
Take off!
Hint: Use a list in one program, and range in another. '''
### Your code here ###
for i in range(5, 0, -1):
print(i)
print("Take off!")
###
for i in [5, 4, 3, 2, 1, 'Take off!']:
print(i)
def main():
print("Question 1:")
forloop_1()
print("\nQuestion 1.2:")
forloop_1_2()
print("\nQuestion 2:")
forloop_2()
print("\nQuestion 2.2:")
forloop_2_2()
print("\nQuestion 3:")
forloop_3()
print("\nQuestion 4:")
forloop_4()
print("\nQuestion 5:")
forloop_5() |
a396f6c20442dbaf6d2f4d61247ba0e44bb71f06 | johnboscor/codingpractice | /calculator.py | 210 | 4.0625 | 4 | num1=input("Enter the first number: ")
num2=input("Enter the second number: ")
sum = int(num1) + int(num2)
product = int(num1) * int(num2)
print("The sum is " + str(sum))
print("The product is " + str(product)) |
fe8beca90862d5514433651bfba152f65996ae48 | Limrvl/homework | /sorting_by_choice.py | 1,137 | 3.6875 | 4 | import time
from datetime import datetime
file = open("ai183.txt", "r")
nums = []
test1 = False
test2 = False
while True:
check = file.read(1)
if not check:
break
if check == "1":
check = file.read(1)
if check == "1":
test1 = True
check = file.read(1)
if check == ":":
test2 = True
if test1 == True and test2 == True:
file.seek(file.tell() + 1)
check = file.read(1)
while check != "}":
nums.append(int(check))
check = file.read(1)
break
file.close()
print("Array: ", nums)
def find_smallest(nums):
smallest = nums[0]
smallest_index = 0
for i in range(1, len(nums)):
if nums[i] < smallest:
smallest = nums[i]
smallest_index = i
return smallest_index
def main_sort(nums):
new_arr = list()
for i in range(len(nums)):
smallest = find_smallest(nums)
new_arr.append(nums.pop(smallest))
return new_arr
start_time = datetime.now()
print("Quick sorted array: ", main_sort(nums))
end_time = datetime.now()
print('---Duration: {}'.format(end_time - start_time)) |
02559316ddd3f82e560a8b84050d6369e0cd7849 | Pikciochain/T1_voting | /test.py | 1,664 | 3.984375 | 4 | """This test shows how one can simply create a poll with the vote token and let
people decide which option they prefer.
This is not a unit test.
"""
from random import Random
from pikciotok import context
import vote
def test_vote():
# Let's create a new vote...
voters_count = 10000
context.sender = 'vote place'
vote.init(
supply=voters_count,
name_="What is the best way to eat strawberries?",
symbol_="STBY"
)
print("Today's question is: {}".format(vote.name))
# Add a few options...
candidates = (
"With a friend at Pikcio.",
"With Yogurt and sugar.",
"In a tart, with a scoop of ice cream.",
"As jam on a toast."
)
for candidate in candidates:
vote.add_candidate(candidate)
print("Candidates are:\n{}\n".format('\n'.join(candidates)))
# And loads of voters.
for i in range(voters_count):
vote.register_voter(str(i))
print("There are {} voters.".format(vote.get_voters_count()))
# Start the vote.
vote.start()
rand = Random()
# Each voter may now hav an opinion.
for i in range(voters_count):
# About 70% of the population cares to answer.
if rand.randint(0, 9) > 2:
context.sender = str(i)
vote.vote(rand.choice(candidates))
# Time to stop the poll and collect results.
context.sender = 'vote place'
vote.interrupt()
print('Duration was: ' + str(vote.get_vote_duration()))
print('Participation was: {:.2f}%'.format(vote.get_participation() * 100))
print('Winner was: ' + vote.get_winner())
if __name__ == '__main__':
test_vote()
|
384f8695120b704dd4021e300e6547fa5f0acd37 | PyETLT/etlt | /etlt/cleaner/WhitespaceCleaner.py | 711 | 3.84375 | 4 | from typing import Optional
class WhitespaceCleaner:
"""
Utility class for cleaning whitespace from strings.
"""
# ------------------------------------------------------------------------------------------------------------------
@staticmethod
def clean(string: Optional[str]) -> Optional[str]:
"""
Prunes whitespace from a string.
:param str string: The string.
:rtype: str
"""
# Return empty input immediately.
if not string:
return string
return string.replace(' ', ' ').strip()
# ----------------------------------------------------------------------------------------------------------------------
|
e1354ac83c6b776c088cb3c1aa5ccb6d104274db | QuentinDuval/PythonExperiments | /linked/CheckIfPalindrome.py | 2,866 | 4.21875 | 4 | """
https://practice.geeksforgeeks.org/problems/check-if-linked-list-is-pallindrome/1
Given a singly linked list of size N of integers.
The task is to check if the given linked list is palindrome or not.
"""
from linked.Node import *
def is_palindrome(head: Node):
"""
Basic solution is to push the numbers visited on a stack, then do a second traversal
Complexity: O(N) time and O(N) space
"""
stack = []
for val in head:
stack.append(val)
for val in head:
if val != stack.pop():
return False
return True
def is_palindrome_2(head: Node):
"""
Optimized version consist in only visiting once by splitting at the middle:
- collect the first half in a stack
- visit the second half and pop from the stack
How to detect the breaking point?
- A slow pointer will move one by one
- A fast pointer will move two by two
For even length collections:
1 2 3 4 5 6 .
^
^
For odd length collections, you have to drop the last element on the stack (if 'next' is None directly):
1 2 3 4 5 6 7 .
^
^
Complexity: O(N) time and O(N/2) space
"""
stack = []
slow = head
fast = head
while fast is not None:
fast = fast.next
if fast:
stack.append(slow.val) # only put the value if fast can at least move once (deal with odd length)
fast = fast.next
slow = slow.next
while slow is not None:
if slow.val != stack.pop():
return False
slow = slow.next
return True
def is_palindrome_3(head: Node):
"""
If we can destroy the list while moving through it, we can even change the pointers of the nodes to form a stack
in place. We could even reconstruct it afterwards.
Complexity: O(N) time and O(1) space
"""
stack = Node
slow = head
fast = head
while fast is not None:
fast = fast.next
if fast:
curr = slow
slow = slow.next
curr.next = stack
stack = curr
fast = fast.next
else:
slow = slow.next
head = slow # To reconstruct the list as it was
while slow is not None:
if slow.val != stack.val:
return False
curr = stack # To reconstruct the list as it was
stack = stack.next
curr.next = head # To reconstruct the list as it was
head = curr # To reconstruct the list as it was
slow = slow.next
return True
for l in [[1, 2, 3, 2, 1], [1, 2, 2, 1], [1, 2, 3, 1, 2], [1, 2, 1, 2]]:
for f in [is_palindrome, is_palindrome_2, is_palindrome_3]:
node = Node.from_list(l)
print(node.to_list(), "->", f(node))
|
6aa66c988c708ac3c95e0a170b65902b9ac1a635 | venkatsvpr/Problems_Solved | /LC_Find_Disappeared_Numbers.py | 593 | 3.5 | 4 | # Find Disappeared Numbers
# https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/
class Solution:
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
size = len (nums)
for i in range(size):
if (nums[i]<=size):
index = abs(nums[i])-1
nums[index] = (-1 * abs(nums[index]))
lt = []
for i in range(size):
if (nums[i] >0):
lt.append(i+1)
return lt
|
909abf42be6f2ccab619b5ae70d0ad27818c6549 | daviuezono/mc920 | /01-random-image-generation/random_image_generation.py | 604 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
name = raw_input("Enter image name (without file extension): ")
size = raw_input("Enter image size (square): ")
depth = raw_input("Enter image depth: ")
my_file = open(name + ".pgm", "w")
my_file.write("P2\n")
my_file.write(size + " " + size + "\n")
my_file.write(depth + "\n")
my_file.write("# optional info is (not) optional\n")
size = int(size)
depth = int(depth)
for i in range(1, size):
list = []
for j in range(1, size):
list.append(str(randint(0, depth-1)))
my_file.write(" ".join(list) + "\n")
my_file.close()
|
a81005f4e279dad383276fd99666f6258b587594 | mvanveen/anchor | /anchor/utils.py | 472 | 3.765625 | 4 | def rensure(items, count):
"""Make sure there are `count` number of items in the list otherwise
just fill in `None` from the beginning until it reaches `count` items."""
fills = count - len(items)
if fills >= 1:
return [None] * fills + items
return items
def rrsplit(string, separator=None, maxsplit=-1):
"""Works just like rsplit but always return `maxsplit+1` items."""
return rensure(string.rsplit(separator, maxsplit), maxsplit+1)
|
f13bf8e78ff5dbf61a7eb39e27da2b976883dc7b | pilihaotian/pythonlearning | /leehao/learn103.py | 476 | 3.578125 | 4 | # 面向对象编程
# 静态方法 定义在类内部的函数,函数的作用域是类内部
# 静态方法需要@static装饰符定义
# 静态方法和普通方法相同,不需要传入self和cls
# 目的:静态方法只能凭借该类和该实例调用,限制作用域
# 静态方法不能访问类变量和实例变量
class A:
@staticmethod
def my_add(a, b):
print(a + b)
A.my_add(100, 200) # 类调用
A().my_add(300, 400) # 实例调用
|
3def973d8d2fc28507468c076db2f8528dcfd359 | Prabhjyot2/workshop-python | /L7/P3.py | 775 | 3.90625 | 4 | '''
wapp to read two set of names:
1.Java student names
2 python student names
find 1. names of all student
2. names of common student
3. students in java not in python
'''
java = set()
python = set()
# read java names
reply = input("do u wish to add java names y/n ")
while reply == 'y':
ele = input("enter name to add ")
java.add(ele)
reply = input("do u wish to more java names y/ n ")
# read python names
reply = input("do u wish to add python names y/n ")
while reply == 'y':
ele = input("enter name to add ")
python.add(ele)
reply = input("do u wish to more python names y/ n ")
# perform set operation
print("Total students",(java | python))
print("Common names",(java & python ))
print("Students in java but no python",(java - python))
|
d5280fecd521085a537d5459d8df526e7e29fe0f | liaison/LeetCode | /python/96_numberOfUniqueBST.py | 1,666 | 4 | 4 | """
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
@author: Lisong Guo <lisong.guo@me.com>
@date: Sep 9, 2018
"""
class Solution:
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
G = [0]*(n+1)
G[0], G[1] = 1, 1
for i in range(2, n+1):
for j in range(1, i+1):
G[i] += G[j-1] * G[i-j]
return G[n]
def catalanNumber(self, n):
"""
The above number is actually known as Catalan number.
:type n: int
:rtype: int
"""
C = 1
for i in range(0, n):
C = 2 * (2*i+1)/(i+2) * C
return int(C)
def verify(case_name, test_input, test_target, test_func):
"""
utility function for unit testing
"""
actual_output = test_func(*test_input)
print(case_name, test_input, ' target:', test_target,
' output:', actual_output)
assert(test_target == actual_output)
if __name__ == "__main__":
solution = Solution()
test_case_1_input = (3, )
test_case_1_target = 5
verify('test case 1:',
test_case_1_input, test_case_1_target, solution.numTrees)
test_case_2_input = (3, )
test_case_2_target = 5
verify('test case 2:',
test_case_2_input, test_case_2_target, solution.catalanNumber)
|
c27421f613f47951c9bbab1ecd692131d13b4606 | abdulsamad19951/Python-Learning | /for-string-snippet.py | 69 | 3.859375 | 4 | name=["Ben","Jack","Allis"]
for i in name:
print("Hello",i) |
8b234f9e3d625355c8dee9ace562484939fda548 | mosesxie/CS1114 | /Lab #4/q4.py | 497 | 4.3125 | 4 | import turtle
color = input("PLease enter a color: ")
shape = input("PLease enter a shape: ")
size = int(input("PLease enter a size number: "))
turtle.color(color)
counter = 0
if (shape == "triangle"):
sides = 3
angle = 60
elif (shape == "square"):
sides = 4
angle = 90
elif(shape == "pentagon"):
sides = 5
angle = 108
else:
print("The shape is invalid")
while sides > counter:
turtle.forward(size)
turtle.left(180-angle)
counter = counter + 1
|
8140b4dceb40cdbb4348f0548cc3fdacc7a6664c | AlexEmerton/urban-robots-DSA | /DS_A_CW3/Odd-Even Sorting.py | 488 | 4.09375 | 4 | A = [1, 7, 8, 11, 14, 16]
i = 0
even_array = []
odd_array = []
# B = [1, 7, 11, 8, 14, 16]
# All odd elements occur before even ones. Sorted in increasing order
# Algorithm should not exceed O(n) complexity
def is_odd(x):
if x % 2 != 0:
return True
else:
return False
while i <= len(A)-1:
if is_odd(A[i]):
odd_array.append(A[i])
else:
even_array.append(A[i])
i += 1
B = odd_array + even_array
print(B)
|
488d9a5ea84c338738badf85cf355e712da6a5d3 | DamianDominoDavis/hs-oop | /2_stack/parentheses.py | 393 | 3.65625 | 4 | from stack import Stack
def balanced(string):
opening = '([{<'
closing = ')]}>'
conv = dict(zip(opening, closing))
s = Stack()
for ch in string:
if ch in conv.keys():
s.push(ch)
elif ch in conv.values():
o = s.pop()
if conv[o] != ch:
return False
return s.isEmpty()
if __name__ == "__main__":
print(balanced(input("string for ({[<>]}) balance? (use \"quotes\"): ")))
|
a10eaf46337e30a96e45b9ff229133a8f2945918 | fahadnayyar/codechef | /junequickcode/test.py | 232 | 3.59375 | 4 | from random import *
print(2)
for j in range(2):
n=100000
q=100000
print(n,q)
for i in range(n):
print(randint(10**8,10**9),end=" ")
print()
for i in range(q):
l= randint(1,n);
r = randint(l,n)
print(randint(1,2),l,r) |
60d3205b8bf85ab2ddcf51893ccd97a5ab064b03 | preethika2308/code-kata | /even.py | 110 | 3.609375 | 4 | fm,sm= (input().split())
fm=int(fm)
sm=int(sm)
for x in range(fm+1,sm,1):
if (x%2==0):
print(x,end=' ')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.