blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c03ef669f56db61a5faf8c121b56c6ed37b2271d | msobiech/logia | /elementy.py | 1,738 | 3.5625 | 4 | from turtle import *
from math import sqrt
from random import *
#15:42 -
p = Turtle()
def losuj():
kolory = ["black"]#"yellow","green","brown","red","blue","pink","gray","magenta","lime")
k = randint(0,len(kolory)-1)
print(str(len(kolory)))
return kolory[k]
def element(bok):
for i in range(4):
p.fd(bok)
p.lt(90)
p.fd(bok/2)
p.lt(45)
p.begin_fill()
p.fillcolor(losuj())
for i in range(4):
p.fd(bok/sqrt(2))
p.lt(90)
p.end_fill()
p.rt(45)
p.bk(bok/2)
def trojkat(bok):
p.begin_fill()
p.fillcolor(losuj())
p.fd(bok/2)
p.lt(135)
p.fd(bok/2/sqrt(2))
p.lt(90)
p.fd(bok/2/sqrt(2))
p.lt(135)
p.end_fill()
def element2(bok):
for i in range(4):
p.begin_fill()
p.fillcolor(losuj())
for i in range(4):
p.fd(bok/4)
p.lt(90)
p.end_fill()
p.fd(bok)
p.lt(90)
p.fd(bok/2)
p.lt(90)
p.fd(bok/2)
p.rt(90)
for i in range(4):
trojkat(bok)
p.lt(90)
p.pu()
p.rt(90)
p.fd(bok/2)
p.rt(90)
p.fd(bok/2)
p.lt(180)
p.pd()
def pas(il,bok):
if il == 0 or il == 2:
element2(bok)
p.fd(bok)
element(bok)
p.fd(bok)
element2(bok)
p.bk(bok*2)
if il == 1:
element(bok)
p.fd(bok)
element2(bok)
p.fd(bok)
element(bok)
p.bk(bok*2)
p.lt(90)
p.fd(bok)
p.rt(90)
def KT(bokl):
p.pu()
p.rt(90)
p.fd(bokl/2)
p.rt(90)
p.fd(bokl/2)
p.lt(180)
p.pd()
bok = bokl/3
for i in range(3):
pas(i,bok)
KT(400)
|
508291b49d07dbc8c7ccef8c604333d73fdf2c2d | azossoukpo-berenger/fonction-python | /TD14exo0.py | 369 | 4.03125 | 4 | def cube(n):
n=str(n)
i=len(n)-1
somme=0
while (i>=0):
somme+=pow(int(n[i]),3)
i-=1
if(somme==int(n)):
return True
else:
return False
def recherche(nmaxi):
for i in range(0,nmaxi+1):
if cube(i) == True:
print(i)
nmaxi=int(input("Entrer la borne supérieure "))
recherche(nmaxi) |
3b9c14de993878342e89d659c501c39b27078042 | joelstanner/codeeval | /python_solutions/SIMPLE_SORTING/SIMPLE_SORTING.py | 873 | 4.53125 | 5 | """
Write a program which sorts numbers.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following
70.920 -38.797 14.354 99.323 90.374 7.581
-37.507 -3.263 40.079 27.999 65.213 -55.552
OUTPUT SAMPLE:
Print sorted numbers in the following way. Please note, that you need to print
the numbers till the 3rd digit after the dot including trailing zeros.
-38.797 7.581 14.354 70.920 90.374 99.323
-55.552 -37.507 -3.263 27.999 40.079 65.213
"""
from sys import argv
def sorter(input_file):
with open(input_file, 'r') as file:
for line in file:
line = line.rstrip()
sort_list = sorted([float(x) for x in line.split()])
for item in sort_list:
print("{:.3f}".format(item), end=" ")
print()
if __name__ == '__main__':
sorter(argv[1])
|
a6f026f02000c15a466f70505538d8d0d47501fc | Aasthaengg/IBMdataset | /Python_codes/p02264/s889112571.py | 729 | 3.625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
from collections import deque
def process_task(task,qua, elapsed_time, complete_task):
exe_task = task.popleft()
t = int(exe_task[1])
q = int(qua)
if t-q > 0:
exe_task[1] = (t - q)
task.append(exe_task)
elapsed_time += q
else:
elapsed_time += t
complete_task.append([exe_task[0], elapsed_time])
return elapsed_time,complete_task
def main():
n,q = map(int, raw_input().split())
task = [raw_input().split() for _ in range(n)]
que = deque(task)
ela_time = 0
comp_task = []
while len(que) != 0:
ela_time , comp_task= process_task(que, q, ela_time,comp_task)
for i in comp_task:
print i[0], i[1]
#def test():
if __name__ == '__main__':
main()
#test() |
d7de1455bcf19d6a72411b2003046cba65e03202 | jimmy623/LeetCode | /Solutions/Clone Graph.py | 737 | 3.546875 | 4 | # Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def __init__(self):
self.dict = {}
def cloneGraph(self, node):
if node == None:
return None
if node.label in self.dict:
return self.dict[node.label]
n = UndirectedGraphNode(node.label)
self.dict[node.label] = n
for nei in node.neighbors:
nn = self.cloneGraph(nei)
n.neighbors.append(nn)
return n
#Clone Graph
#https://oj.leetcode.com/problems/clone-graph/ |
c99faaee7d858e06793abb73796903472b1356bd | jnicolarsen/pytreasuryio | /treasuryio/query.py | 958 | 3.75 | 4 | from json import load
from urllib2 import urlopen
from urllib import urlencode
from pandas import DataFrame
def query(sql, format='df'):
'''
Submit an `sql` query (string) to treasury.io and return a pandas DataFrame.
For example::
print('Operating cash balances for May 22, 2013')
print(treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';'))
Return a dict::
treasuryio.query('SELECT * FROM "t1" WHERE "date" = \'2013-05-22\';', format='dict')
'''
url = 'http://api.treasury.io/cc7znvq/47d80ae900e04f2/sql/'
query_string = urlencode({'q':sql})
handle = urlopen(url + '?' + query_string)
if handle.code == 200:
d = load(handle)
if format == 'df':
return DataFrame(d)
elif format == 'dict':
return d
else:
raise ValueError('format must equal "df" or "dict"')
else:
raise ValueError(handle.read())
|
257bf1940443f71e04354bbbd198dd410bb09cfd | shubhammalhotra28/leetcode-problems | /Diameter.py | 711 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diaHeight(self,root):
if root is None:
return 0,0
ld,lh = self.diaHeight(root.left)
rd,rh = self.diaHeight(root.right)
ht = 1+max(lh,rh)
dia_with_root = lh+rh
# dia and ht
return max(ld,rd,dia_with_root),ht
def diameterOfBinaryTree(self, root: TreeNode) -> int:
diameter,height = self.diaHeight(root)
return diameter
|
e2df1b8b89c672476d30aa0ee9f013a0732ae877 | JosephArroyave/Herramientas-de-la-computacion-FINAL | /Final herramientas de la computacion.py | 2,145 | 4.125 | 4 | #Funcion que da valor de los descuentos segun el Rol.
#Rol 1 para estudiante, Rol 2 para profesor
def informacion(Rol):
if Rol == 1:
return 0.5
else:
return 0.2
#Varibles del menu
Hamburguesa = 3000
pizza = 2500
HotDog = 2300
producto = 0
cantidad = 0
#Bienvenida al programa
print ("BIENVENIDO A LA CAFETERIA")
print ("Ingrese sus datos porfavor: ")
#Datos del cliente
Cedula = int(input("Ingrese su numero de identificación: "))
Rol = int(input("Si es estudiante ingrese 1, si es profesor ingrese 2: "))
#Lista del menu
print ("Menu: \n1. Hamburguesa = 3000 / Codigo: 101. \n2. Pizza = 2500 / Codigo: 102.\n3. Hot dog: 2300 / Codigo: 103\n")
comida = int(input("Ingrese el codigo del producto que desea: "))
if comida == 101: #Pedido Hamburgesa
cantidad = int(input("Ingrese el numero de unidades del producto seleccionado: "))
producto = Hamburguesa * cantidad - (informacion(Rol)*cantidad*Hamburguesa)
if Rol == 1: #Estudiante
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
else: #Profesor
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
elif comida == 102: #Pedido Pizza
cantidad = int(input("Ingrese el numero de unidades del producto seleccionado: "))
producto = pizza * cantidad - (informacion(Rol)*cantidad*pizza)
if Rol == 1: #Estudiante
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
else: #Profesor
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
elif comida == 103: #Pedido Hotdog
cantidad = int(input("Ingrese el numero de unidades del producto seleccionado: "))
producto = HotDog * cantidad - (informacion(Rol)*cantidad*HotDog)
if Rol == 1: #Estudiante
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
else: #Profesor
print ("El estudiante","con cedula",Cedula,",debe pagar",producto ,"por el producto" ,comida)
|
1c32c4fa203d718e58a918f7b04a7457a7fa065a | Theeshs/jsonfilter | /Helpers/Helpers.py | 2,897 | 3.9375 | 4 | """
In here the functions are responsible for filtering data from JSON object. Each and every function requires three parameters
filter_by_tags(json_object, keyword, tags):
json_object = json data that has read before
keyword = the key that filtering based on
tags = the values that can consist that particular key
filterd_by_status(json_object, keyword, value):
json_object = json data that has read before
keyword = the key that filtering based on
tags = the values that can consist that particular key
filter_by_other_keys(json_object, keyword, value):
json_object = json data that has read before
keyword = the key that filtering based on
tags = the values that can consist that particular key
in here mostly the filtering list comprehension have used. It's somewhat faster than the for loops
"""
# the function that responsible for finding data in the JSON base on the tag
def filer_by_tags(json_object, keyword, tags):
# validating parameters
if json_object is None or keyword is None or tags is None:
return []
if json_object == "" or keyword == "" or tags == "":
return []
try:
tags_items = [item for item in json_object if tags in item.get(keyword)]
return tags_items
except Exception as e:
print('Problem in filtering by tags in Handlers')
print(e)
return []
# the function that responsible for finding data based on the true, false values
def filter_by_status(json_object, keyword, value):
# validating parameters
if json_object is None or keyword is None or value is None:
return []
if json_object == "" or keyword == "" or value == "":
return []
if value == 'true':
value = True
elif value == 'false':
value = False
else:
print("Unsopported format")
exit()
try:
filtered_items = [item for item in json_object if item.get(keyword) == value]
# for item in json_object:
# if item.get(keyword) == value:
# filtered_items.append(item)
return filtered_items
except Exception as e:
print('Problem in filtering by status in Handlers')
print(e)
return []
# the function that responsible for finding data based on the other keyword of the JSON file
def filter_by_other_keys(json_object, keyword, value):
# validating parameters
if json_object is None or keyword is None or value is None:
return []
if json_object == "" or keyword == "" or value == "":
return []
try:
filterd_items = [item for item in json_object if str(item.get(keyword)) == str(value)]
# print(filterd_items)
# exit()
return filterd_items
except Exception as e:
print('Problem in filtering by other keys in Handlers')
print(e)
return []
|
bc52b29f43ca1863d4209a5ea64ad5db08bc6569 | nonnikb/verkefni | /Próf 2/Dæmi 3.py | 711 | 4.28125 | 4 | """Hlutlisti (e. sublist) er listi sem hluti af lengri lista.
Tómi listinn, [], er hlutlisti í öllum listum.
Dæmi: Eftirfarandi eru hlutlistar í listanum ['1','2','3']:
[], ['1'], ['1', '2'], ['1', '2', '3'], ['2'], ['2', '3'], ['3']
Skrifið Python forrit sem prentar út alla hlutlista gefins lista.
Forritið á að innihalda a.m.k. eitt fall, make_sublists(a_list), sem
skilar lista af öllum hlutlistum í a_list.
Ábending: "List slicing" er þinn vinur!"""
# Main program starts here
def make_sublists(a_list):
my_list = []
my_list = input("Enter a list separated with commas: ")
my_list
# This should be the last statement in your main program/function
print(sorted(sub_lists))
|
3940bafd3bf41a20364de6ca14ffd8c2425bbc16 | Kartavya-verma/Python-Projects | /GFG/Capgemini_1.py | 333 | 3.625 | 4 | def count(a,b,m,n):
if (m == 0 and n == 0) or n == 0:
return 1
if m == 0:
return 0
if a[m-1] == b[n-1]:
return count(a,b,m-1,n-1) + count(a,b,m-1,n)
else:
return count(a,b,m-1,n)
a = "MOM"
b = "DAD"
st = input()
ans = count(st,a,len(st),len(a)) + count(st,b,len(st),len(b))
print(ans) |
3fc88952e7a3f03fb05aa7c43c1c2dc109b33a4d | Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021 | /answers/Tanmay Jaiswal/Day17/question2.py | 432 | 3.671875 | 4 | import numpy as py
import sys
print("Input: "
,end="")
n = int(input("N: "))
arr = py.array(input("Arr[] (give space after each digit) = ").split()).astype(int)
if len(arr) > n:
print("Enter number of the length",n)
sys.exit()
k = 0
count = 0
for i in range(len(arr)):
sum = 0
for j in range(i,n):
sum += arr[j]
if sum == k:
count += 1
print("Output:",count)
|
e61e5d57771efb5dd4e7992cf2c5c7cca04b29c8 | arohigupta/algorithms-interviews | /fizz_buzz.py | 1,233 | 4.15625 | 4 | # 1) Write a function "def fizzbuzz(fizz_number, buzz_number):" that prints the numbers from 1 to 100.
# But for multiples of "fizz_number" print "Fizz" instead of the number and for the multiples of "buzz_number" print "Buzz".
# For numbers which are multiples of both fizz_number and buzz_number print "FizzBuzz".
#
# - The output should be one line only, without a new line at the end
# - Each number or word should be separated by a space
#
# Example: fizzbuzz(3, 7)
# 1 2 Fizz 4 5 Fizz Buzz 8 Fizz 10 11 Fizz 13 Buzz Fizz 16 17 Fizz 19 20 FizzBuzz 22 23 Fizz 25 26 Fizz Buzz 29 Fizz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz 40 41 FizzBuzz 43 44 Fizz 46 47 Fizz Buzz 50 Fizz 52 53 Fizz 55 Buzz Fizz 58 59 Fizz 61 62 FizzBuzz 64 65 Fizz 67 68 Fizz Buzz 71 Fizz 73 74 Fizz 76 Buzz Fizz 79 80 Fizz 82 83 FizzBuzz 85 86 Fizz 88 89 Fizz Buzz 92 Fizz 94 95 Fizz 97 Buzz Fizz 100
def fizzbuzz(fizz_number, buzz_number):
for i in range(1, 101):
if i % fizz_number == 0 and i % buzz_number == 0:
print "FizzBuzz",
elif i % fizz_number == 0:
print "Fizz",
elif i % buzz_number == 0:
print "Buzz",
else:
print i,
if __name__ == "__main__":
fizzbuzz(3, 7) |
7ff767d4029dc1ae7c4a66091482609b52f96d53 | abhik1368/frowns | /Fingerprint/__init__.py | 1,058 | 3.859375 | 4 | """Codes for creating a daylight like fingerprint
for a molecule"""
import Fingerprint, Fingerlist, LinearPaths
# XXX FIX ME
# make the linear paths a generator eventually
# this should save memory...
def generateFingerprint(molecule, numInts=32, pathLength=7):
"""(molecule, numInts=32)->Fingerprint
given a molecule and the number of integers to use to generate
the fingerprint, return the fingerprint of the molecule)"""
paths = LinearPaths.generatePaths(molecule, maxdepth=pathLength)
fp = Fingerprint.Fingerprint(numIntegers=numInts)
for path in paths:
fp.addPath(path)
return fp
def generateFingerlist(molecule, numInts=1024, pathLength=7):
"""(molecule, numInts=32)->Fingerprint
given a molecule and the number of integers to use to generate
the fingerprint, return the fingerprint of the molecule)"""
paths = LinearPaths.generatePaths(molecule, maxdepth=pathLength)
fp = Fingerlist.Fingerlist(numIntegers=numInts)
for path in paths:
fp.addPath(path)
return fp
|
29fda79691667f8a45ebb2c743f90d3a6be29801 | Jhayes007/Python-code | /stringMethods.py | 799 | 3.75 | 4 | # Filename: stringMethods.py
# Author: J.Hayes
# Date: Oct. 23, 2019
# Purpose: To demonstrate various string methods
# available in Python.
# A quote from an IBM President, Thomas Watson, in 1943
quote = 'i think there is a world market for maybe five computers. '
# String methods
print('Original quote: ')
print(quote)
print('\nIn uppercase: ')
print(quote.upper())
print('\nIn lowercase: ')
print(quote.lower())
print('\nAs a title: ')
print(quote.title())
print('\nWith a minor replacement: ')
print(quote.replace('five', 'millions of'))
print('\nCapitalize: ')
print(quote.capitalize())
print('\nAfter swapping case: ')
print(quote.swapcase())
print('\nRemoving white spaces at the ends: ')
print(quote.strip())
print('\nOriginal quote is still: ')
print(quote)
|
dd57964b81b31b08bb7a58b3089d95cdfd10352a | luis-carmo/exercicios-uri | /Python/1044.py | 319 | 3.78125 | 4 | valores = input().split()
A = int(valores[0])
B = int(valores[1])
if A > B:
if (A % B) == 0:
print ('Sao Multiplos')
else:
print('Nao sao Multiplos')
if B > A:
if (B % A) == 0:
print('Sao Multiplos')
else:
print('Nao sao Multiplos')
if A == B:
print ('Sao Multiplos') |
bbb4e55c67dfac73bdae3eadd888dc940e263516 | lesenpai/project-euler | /task5.py | 366 | 3.765625 | 4 | def is_total_divided(x, numbers):
for n in numbers:
if x % n != 0:
return False
return True
# НОК
def lcm(a, b):
m = a * b
while a != 0 and b != 0:
if a > b:
a %= b
else:
b %= a
return m // (a + b)
x = 1
for n in range(1, 21):
x = lcm(x, n)
print('x =', x)
print(x)
|
30755675f9a3975cc79ce20de9136b853e9c8fb5 | Ging3y/gitTutorial | /main.py | 113 | 3.734375 | 4 | print("Hello Nathan!")
def my_func(x):
return x+4
print(str(my_func(int(input("Enter a number: ")))))
|
80b39f7bafad361031d0af018ad1cac8f3dd9307 | anandbadrinath-classes/perceptron | /perceptron_src/Perceptron_td.py | 4,857 | 3.953125 | 4 | from .Neuron import Neuron
import numpy as np
import random
import pickle
class Perceptron(object):
def __init__(self, numberOfNeurons, imageWidth, imageHeight, weights=None):
"""Loads an existing neural network if weights points to a valid
weights file, otherwise, initialises a new neural network.
Arguments:
numberOfNeurons {int} -- The number of neurons in the network
imageWidth {int} -- The width of the input images in pixels
imageHeight {int} -- The height of the input images in pixels
Keyword Arguments:
weights {string} -- The path to the weights file, or None to
initialize a new network(default: {None})
"""
if weights is None:
# TODO Exercise 1 Initialize a new network containing
# numberOfNeurons Neuron objects each with a different position chosen
# at random you can use the generatePositionList method below to help you.
self.network = []
else:
# TODO Bonus Load an existing network
self.load(weights)
def __eq__(self, other):
return (self.network == other.network)
def generatePositionList(self, imageWidth, imageHeight):
"""Generate a list of all possible positions in an image of dimensions
imageWidth x imageHeight
Arguments:
imageWidth {int} -- The width of the image
imageHeight {int} -- The height of the image
Returns:
list((tuple(int,int))) -- The list of positions presented as (x, y)
"""
positionList = []
for x in range(imageWidth):
for y in range(imageHeight):
positionList.append((x,y))
return positionList
# TODO Exercise 2: Implement the forward pass function
def forwardPass(self, image):
"""Takes a binary image as input, computes the weighted sum of the
of the products each neuron weight with the associated pixel value
and sets the neuron's active property to True if the pixel value is 1.
It then returns -1 if the weighted sum is negative, 0 if the
weighted sum is 0 and +1 if the weighted sum is positive.
Arguments:
image {numpy.array} -- The binary image input
"""
return 0
# TODO Exercise 3: Implement the backpropagation function
def backProp(self, expectedResult, result):
"""If the expected result does not match the actual result, add the
expected result to the value of all active neurons, then deactivate
them.
Arguments:
expectedResult {int} -- The expected result for the forward pass
result {int} -- The actual result for the forward pass
"""
pass
# TODO Exercise 4: Implement the error calculation function
def calcError(self, labels, results):
"""Compute the number of (expected result/actual result) pairs that are not equal and
return the result.
Arguments:
labels {list(int)} -- The list of labels
results {list(int)} -- The list of results
"""
return 0
# TODO Exercise 5: Implement the training function
def train(self, images, labels, maxIterations):
"""Train the perceptron by computing the result of a forward pass then
by backpropagating that result through the neural network until the
error reaches 0 or the max iteration number has been reached.
Arguments:
images {[type]} -- [description]
labels {[type]} -- [description]
numIterations {[type]} -- [description]
"""
pass
# TODO Exercise 6: Implement the testing function
def test(self, images):
"""Compute the forward pass results for a list of images
Arguments:
images {numpy.array} -- A list of binary images
Returns:
list(int) -- The forward pass results for each input image
"""
return []
# TODO Bonus: write the save and load functions that will allow you to save
# the result of a training and reuse those weights later
def save(self, file):
"""Save the current neural network to a file using
pickle
Arguments:
file {str} -- The path to the file the weights will be saved to
"""
pass
def load(self, file):
"""Load the neural network from a pickle file
Arguments:
file {str} -- The path to the file containing the weights
"""
self.network = []
|
bd7e3f1372d7197ac8c2b2020c65bb3ff1d595b1 | F0xedb/futurenetCalculator | /date.py | 581 | 3.703125 | 4 | import datetime
class date:
def __init__(self):
self.date = str(datetime.date.today().year) + "-" + '{:02d}'.format(
datetime.date.today().month) + "-" + '{:02d}'.format(datetime.date.today().day)
self.currentDate = datetime.datetime.now()
def getDaysFromNow(self,date):
return (date - self.currentDate).days
def getDateFromString(self,string):
_date = datetime.datetime.strptime(string, '%Y-%m-%d')
test = datetime.datetime.date(_date)
return datetime.datetime.combine(test, datetime.datetime.min.time())
|
0cd313a4f3165d56ba91d71b0e73c69370d64c57 | melodypei/Python | /example26.py | 147 | 3.5 | 4 | # -*- coding: UTF-8 -*-
'''
利用递归方法求5!
'''
def f(n):
if n == 1:
return 1
else:
return n*f(n-1)
print(f(4))
|
1437746dd0dee3790c3ebf368daffe5e5080e1fe | liucheng2912/py | /leecode/easy/链表/22链表中倒数第k个节点.py | 314 | 3.515625 | 4 | '''
输出链表的倒数第k位的链表
快慢指针的方法
p2先走k步,当p2到最后的时候,p1现在的内容就是倒数k的链表
'''
def order(head,k):
p1=head
p2=head
for i in range(k):
p1=p1.next
while p1:
p1=p1.next
p2=p2.next
return p2
|
76668f88a1c906da1bd93dc123f94f0afa04bd34 | Muckler/python-exercises-feb | /february_exercises/python_part3_exercises/turtle1_pent.py | 317 | 3.546875 | 4 | from turtle import *
def pent():
# move into position
up()
forward(50)
left(90)
forward(50)
left(90)
down()
# draw the pentagon
forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)
if __name__ == "__main__":
pent()
mainloop()
|
f3bf5110934459ff1f872f27d94217008144c0e4 | lalitsshejao/Python_PractiseCode | /scripts/pattern1.py | 404 | 3.53125 | 4 | # s="0123456789"
# print(s[2:0:-1])
l1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20, 10]
size = len(l1)
duplicate=[]
for i in range (size):
k = i + 1
for j in range (k, size):
if l1[i]==l1[j] and l1[i] not in duplicate:
duplicate.append(l1[i])
print(duplicate)
final_list=[]
for x in l1:
if x not in final_list:
final_list.append(x)
print(final_list) |
687c8ddf3bf3c1f8d3ac120e1d771bb36bdd9c0d | ImogenHay/Queues-and-Lists | /PriorityQueue3 (lists in lists).py | 3,082 | 4.4375 | 4 | ## PRIORITY QUEUE ##
class PriorityQueue(object): #class that proccesses items from front to back (removes after processed) but orders them in the list in order of priority
## Constructor
def __init__(self, maxSize):
print("A list has been created")
## Attributes
self.maxSize = maxSize
self.qList = []
## String Method - special method that will be called on print
def __str__(self):
report = "\nQueue "
report = report + "Max Size: " + str(self.maxSize) + "\n"
if len(self.qList) > 0:
report = report + "has the following Items\n"
for i in self.qList:
report = report + str(i) + ", "
report = report + "\n"
return report
## Other Methods
def isFull(self):
text = "No more items can be added\n"
return text
def isEmpty(self):
text = "List is empty"
return text
def addItem(self,item): #adds item to list in order of priority
self.qList.append(item)#appends item and priority within list to main list
self.qList.sort()#sorts main list by first item in mini lists which is priotity
return self.qList
def getItem(self):
item2 = self.qList.pop(0) #removes first item from whole list which has item and priority in it
item = item2.pop(1) #removes second item from list within list which is item
return item
def getLength(self):
length = len(self.qList) #finds length of list
return length
def emptyList(self):
length = len(self.qList)
for i in range(0,length):
self.qList.pop(0) #method that emptys list by popping each item in list one by one
##Adding items to queue
size = int(input("Max List Size: ")) #user input size of list
q1 = PriorityQueue(size) #creates object with list of maxsize 'size'
length = 0
while length < size-1: #repeats for each item there can be in list
length = q1.getLength() #gets length of list
current_item = []
item1 = input("Input Item: ") #user inputs item they want to add to list
priority1 = int(input("Input Priority (lower number higher priority): ")) #selects priority within queue
current_item.append(priority1) #appends priority first so that when the whole list is sorted it sorts it by the priority not the item
current_item.append(item1) #appends items
q1.addItem(current_item) #adds list of item and its priority to whole list
text = q1.isFull() #prints text stating list is full
print(text)
print(q1)
##Processing items from queue
while length > 1: #repeats for each item in list
length = q1.getLength() #find current length of list
item = q1.getItem() #getItem functions uses pop to remove first item from list
print("Processed ",item) #prints removed/processed item
text = q1.isEmpty() #prints text stating list is empty
print(text)
q1.emptyList() #runs function emptying list
input("\n\nPress the enter key to exit.") #end program
|
8445ac933b276e07da3f14819df841207a9e3756 | robertwildman/AdventOfCode2020 | /Day3/main.py | 963 | 3.625 | 4 | def part_one():
return tree_finder(3, 1)
def part_two():
trees_hit = tree_finder(1, 1)
trees_hit = trees_hit * tree_finder(3, 1)
trees_hit = trees_hit * tree_finder(5, 1)
trees_hit = trees_hit * tree_finder(7, 1)
trees_hit = trees_hit * tree_finder(1, 2)
return trees_hit
def tree_finder(addx, addy):
with open("input.txt") as f:
skimap = f.read().splitlines()
currentcords_x = 0
currentcords_y = 0
trees_hit = 0
while True:
currentcords_x += addx
currentcords_y += addy
if currentcords_y >= len(skimap):
break
if currentcords_x >= len(skimap[0]):
currentcords_x = currentcords_x - len(skimap[0])
if skimap[currentcords_y][currentcords_x] == "#":
trees_hit += 1
return trees_hit
print("Part one answer: " + str(part_one()))
print("Part two answer: " + str(part_two()))
|
3138ee7975f64e089524f369a6e3753e226a7bf7 | Calvonator/30-Days-of-Python | /Exercises/day-21-exercise/day-21-exercises.py | 793 | 4.0625 | 4 | # Day 21 Exercise - 30 Days Of Python
# Your task is to split this code into files.
import json
import store
import user_interaction
USER_CHOICE = """
Enter:
- 'a' to add a new book
- 'l' to list all books
- 'r' to mark a book as read
- 'd' to delete a book
- 'q' to quit
Your choice: """
BOOKS_FILE = 'books.json'
def menu():
store.create_book_table()
user_input = input(USER_CHOICE)
while user_input != 'q':
if user_input == 'a':
user_interaction.prompt_add_book()
elif user_input == 'l':
user_interaction.list_books()
elif user_input == 'r':
user_interaction.prompt_read_book()
elif user_input == 'd':
user_interaction.prompt_delete_book()
user_input = input(USER_CHOICE)
menu() |
6e9f112030c013bee79a7a29c27f50bb9fa70845 | dmlogv/particles | /particles.py | 966 | 3.703125 | 4 |
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if not isinstance(other, self.__class__):
raise TypeError('Unsupported operand type for +: {self} and {other}',
self=self.__class__.__name__,
other=other.__class__.__name__)
return Vector(self.x + other.x, self.y + other.y)
class Particle:
def __init__(self, weight, position: Vector,
velocity: Vector, acceleration: Vector):
self.weight = weight
self.position = position
self.velocity = velocity
self.acceleration = acceleration
class Emitter:
def __init__(self, position: Vector, direction: Vector, angle):
self.position = position
self.direction = direction
self.angle = angle // 360
class Field:
def __init__(self):
self.emitters = []
self.particles = []
|
97c91dcfae21a4d82f6a3a6dbe04691efd0046d0 | LLGwinn/flask-greet-calc | /calc/app.py | 1,347 | 3.6875 | 4 | from flask import Flask, request
from operations import add, sub, mult, div
app = Flask(__name__)
@app.route('/add')
def add_nums():
""" Multiply search parameters a, b and return result """
a = int(request.args.get('a'))
b = int(request.args.get('b'))
sum = add(a, b)
return str(sum)
@app.route('/sub')
def subtract_nums():
""" Subtract search parameters a, b and return result """
a = int(request.args.get('a'))
b = int(request.args.get('b'))
difference = sub(a, b)
return str(difference)
@app.route('/mult')
def multiply_nums():
""" Multiply search parameters a, b and return result """
a = int(request.args.get('a'))
b = int(request.args.get('b'))
product = mult(a, b)
return str(product)
@app.route('/div')
def divide_nums():
""" Divide search parameters a, b and return result """
a = int(request.args.get('a'))
b = int(request.args.get('b'))
dividend = div(a, b)
return str(dividend)
# FURTHER STUDY
opers = {
'add' : add(a, b),
'sub' : sub(a, b),
'mult' : mult(a, b),
'div' : div(a, b)
}
@app.route('/math/<oper>')
def do_math(oper):
""" Perform math operation based on path parameter and search parameters a, b """
a = int(request.args.get('a'))
b = int(request.args.get('b'))
return str(opers[oper])
|
c632f8390f7fc3da0be69f6a7971a600d8f4bd6b | sachinsehrawat/python_selenium_pytest | /Python basics/class_child.py | 266 | 3.515625 | 4 | from class_demo import calculator
class child(calculator):
num2 = 200
def __init__(self):
calculator.__init__(self,2,9)
def multiply(self):
return self.Firstnumber * self.Secondnumber * self.add()
obj = child()
print(obj.multiply())
|
4ea044b14e3c169633b76594534856b1acc62408 | manfrin/project-euler | /euler20.py | 240 | 3.53125 | 4 | # Finds 100! factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
longnum = factorial(100)
longstr = str(longnum)
total = 0
for each in longstr:
total += int(each)
print total
|
d54235fee7bd1277ccd0f8cc695ae7d432417200 | nnim99/Introduction-to-Programming-Python- | /Lab2/Task3.py | 990 | 4.0625 | 4 | import math
def myfunc():
valueOne= float(input("Enter a positive Number:"))
valueTwo= float(input("Enter another negative Number:"))
print (("Signs get swaped of two numbers:"), math.copysign(valueOne, valueTwo))
print (("Absolute value is returned of negative number:"), math.fabs(valueTwo))
print (("The square root of positive number is:"), math.sqrt(valueOne))
print (("Negative number is power of positive number so the answer is:"), math.pow (valueOne, valueTwo))
print (("If value One is entered in decimals then next largest possible integer value is:"), math.ceil(valueOne))
print (("If value Two is entered in decimals then the smallest possible integer value is:"), math.floor(valueTwo))
print (("The log of positive number entered with base 10 is:"), math.log10(valueOne))
print (("The sine of value One is:"), math.sin(valueOne))
print (("The cosine of value One is:"), math.cos(valueOne))
print (("The tangent of value Two is:"), math.tan(valueTwo))
myfunc()
|
5abdaf421f4b0657c7000a14af28678ff2453e59 | jadeskon/Solutions-Exercises-DeepLearning | /08_tensorflow_a_first_cnn/cnn_mnist.py | 7,511 | 4.28125 | 4 | # Convolutional Neural Network (CNN) example in TensorFlow
#
# Here we construct a simple Convolutional Neural Network (CNN)
# using TensorFlow (TF) which will learn using the MNIST training dataset
# to classify 28x28 pixel images of digits 0,...,9
#
# Network structure is:
# INPUT --> CONV1/MAXPOOL --> CONV2/MAXPOOL --> FC --> OUT
#
# ---
# by Prof. Dr. Juergen Brauer, www.juergenbrauer.org
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from random import randint
# 1. get the MNIST training + test data
# Note: this uses the mnist class provided by TF for a convenient
# access to the data in just a few lines of code
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
# show an example of a train image
img_nr = 489
label_vec = mnist.train.labels[img_nr]
print("According to the training data the following image is a ", np.argmax(label_vec) )
tmp = mnist.train.images[img_nr]
tmp = tmp.reshape((28,28))
plt.imshow(tmp, cmap = cm.Greys)
plt.show()
# 2. set up training parameters
learning_rate = 0.01
training_iters = 20000
batch_size = 128
display_step = 10
# 3. set up CNN network parameters
n_input = 784 # MNIST data input dimension (img has shape: 28*28 pixels)
n_classes = 10 # MNIST nr of total classes (0-9 digits)
dropout_rate = 0.75 # probability to keep an unit in FC layer during training
# 4. define TF graph input nodes x,y,keep_prob
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32)
# 5. define a helper function to create a single CNN layer
# with a bias added and RELU function output
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
#
# from: https://www.tensorflow.org/versions/r0.12/api_docs/python/nn.html#conv2d
#
# tf.nn.conv2d(input, filter, strides, padding,
# use_cudnn_on_gpu=None, data_format=None, name=None)
#
# Computes a 2-D convolution given 4-D input and filter tensors.
# Given an input tensor of shape
# [batch, in_height, in_width, in_channels]
# and a filter / kernel tensor of shape
# [filter_height, filter_width, in_channels, out_channels],
# this op performs the following:
#
# 1. Flattens the filter to a 2-D matrix with shape
# [filter_height * filter_width * in_channels, output_channels].
# 2. Extracts image patches from the input tensor to form a virtual
# tensor of shape
# [batch, out_height, out_width, filter_height * filter_width * in_channels].
# 3. For each patch, right-multiplies the filter matrix and the
# image patch vector.
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
# 6. define a helper function to create a single maxpool operation
# for the specified tensor x - with a max pooling region of 2x2 'pixels'
def maxpool2d(x, k=2):
# MaxPool2D wrapper
# Non overlapping pooling
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
# 7. helper function to create a CNN model
def conv_net(x, weights, biases, dropout):
# reshape input picture which has size 28x28 to a 4D vector
# -1 means: infer the size of the corresponding dimension
# here: it will result in 1
x = tf.reshape(x, shape=[-1, 28, 28, 1])
# create first convolution layer
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
# then add a max pooling layer for down-sampling on top of conv1
conv1 = maxpool2d(conv1, k=2)
# create second convolution layer
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
# then add a max pooling layer for down-sampling on top of conv2
conv2 = maxpool2d(conv2, k=2)
# create a fully connected layer
# thereby: reshape conv2 output to fit fully connected layer input
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# apply dropout during training for this fully connected layer fc1
fc1 = tf.nn.dropout(fc1, dropout_rate)
# add output layer: out=fc1*out_weights+out_biases
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
# return tensor operation
return out
# 8. initialize layers weights & biases normally distributed and
# store them in a dictionary each
weights = {
# 5x5 conv filter, 1 input (depth=1), 32 outputs (depth=32)
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
# 5x5 conv filter, 32 inputs, 64 outputs
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
# fully connected, 7*7*64 inputs, 1024 outputs
# 7x7 is the spatial dimension of CONV2, 64 is its depth
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
'bc1': tf.Variable(tf.random_normal([32])),
'bc2': tf.Variable(tf.random_normal([64])),
'bd1': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# 9. construct model using helper function
pred = conv_net(x, weights, biases, keep_prob)
# 10. define error function and optimizer
error_func = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(error_func)
# 11. evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 12. initializing the variables and init graph
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
# 13. keep training until we reached max iterations
step = 1
while step * batch_size < training_iters:
# get next training batch
batch_x, batch_y = mnist.train.next_batch(batch_size)
# set inputs & run optimization op (backprop)
sess.run(optimizer, feed_dict={x: batch_x,
y: batch_y,
keep_prob: 1.0-dropout_rate}
)
if step % display_step == 0:
# calculate batch loss and accuracy
batch_error, acc = \
sess.run([error_func, accuracy], feed_dict={x: batch_x,
y: batch_y,
keep_prob: 1.}
)
print("Iter " + str(step*batch_size) + ", Batch error= " + \
"{:.6f}".format(batch_error) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
step += 1
print("Optimization finished!")
# 14. calculate accuracy for test images
test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images[:990],
y: mnist.test.labels[:990],
keep_prob: 1.0} )
print("Testing Accuracy:", test_accuracy)
# 15. show an example of a test image used for computing the accuracy
img_nr = randint(0, 512)
tmp = mnist.test.images[img_nr]
tmp = tmp.reshape((28,28))
plt.imshow(tmp, cmap = cm.Greys)
plt.show()
|
5833ffecf404f90db396caf8059063e4fb6f6d1a | s4u10/Challenge_in_Python | /pythonCode/Number_Impartes.py | 78 | 3.890625 | 4 | i = int(input("Digite o valor de n: "))
for i in range(1, i+1, 2):
print(i) |
44cd0144c24d0c0ce852cd392d44504093c1df65 | Ttibsi/AutomateTheBoringStuff | /Ch.15 - Working With PDF & Word Documents/11-WritingToWord.py | 449 | 3.59375 | 4 | # Writing word docs
import docx
doc = docx.Document()
doc.add_paragraph('Hello, world!')
paraObj1 = doc.add_paragraph('This is a second paragraph. ')
paraObj2 = doc.add_paragraph('This is a third!')
paraObj1.add_run('This text is added to the second paragraph...')
# The second parameter here applies the Title style to the text of the first parameter
doc.add_paragraph('HelloHelloAnthony', 'Title')
doc.save('11-helloworld.docx') |
100baa8c5e362e676c98c3232d962b06d3a3308d | AnatRamon/Checkers-game | /board.py | 2,355 | 4.34375 | 4 | from style import Style
empty_cell = "0"
def make_board(pawn1, pawn2, empty):
""""
Creates a board for two given players.
:param pawn1: an instance from the class Player in players. This player will be at the top of the board.
:param pawn2: an instance from the class Player in players. This player will be at the bottom of the board.
:param empty: defines how an empty call will look.
:return: a board with the players pieces organized like in Checkers.
:rtype: nested list.
"""
row_0 = [empty, pawn1] * 4
row_1 = [pawn1, empty] * 4
row_2 = [empty, pawn1] * 4
row_3 = [empty] * 8
row_4 = [empty] * 8
row_5 = [pawn2, empty] * 4
row_6 = [empty, pawn2] * 4
row_7 = [pawn2, empty] * 4
board = [row_0] + [row_1] + [row_2] + [row_3] + [row_4] + [row_5] + [row_6] + [row_7]
return board
def print_board(board):
"""
Prints nicely a given board.
:param board: a given board.
:type board: nested lists
"""
possible_columns_names = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
columns = ""
columns_names = possible_columns_names[:len(board[0])]
for column in columns_names:
columns += " " + column
styled_columns = Style.Background.light_grey + Style.Foreground.dark_grey + " " + columns + " " + Style.end
print(styled_columns)
row_num = 0
if len(board) > 10:
for row in range(len(board)):
if row_num < 10:
styled_row_num = Style.Background.light_grey + Style.Foreground.dark_grey + " " + str(row_num) \
+ " " + Style.end
else:
styled_row_num = Style.Background.light_grey + Style.Foreground.dark_grey + " " + str(row_num) \
+ " " + Style.end
print(styled_row_num, *board[row])
row_num += 1
else:
for row in range(len(board)):
styled_row_num = Style.Background.light_grey + Style.Foreground.dark_grey + " " + str(
row_num) + " " + Style.end
print(styled_row_num, *board[row])
row_num += 1
if __name__ == "__main__":
ex_board = make_board(Style.Foreground.red + "0" + Style.end, Style.Foreground.blue + "0" + Style.end, "0")
print_board(ex_board)
|
a92fdf5edead0c41aae31cea3755b38cd30eb698 | tianyolanda/leetcoding | /leet7-3.py | 256 | 3.75 | 4 | # 最快的解法:转换为字符串,直接倒序输出
x = -12345
if x < 0:
flag = -1
else:
flag = 1
x_str = str(abs(x))
x_reverse = int(x_str[::-1])
if x_reverse <= 2**31-1:
output = flag * x_reverse
else:
output = 0
print(output) |
9938d4cda904f1e821dcea38f9d7a0a512c41361 | TonikX/ITMO_ICT_Programming_2020-2021_d3110 | /students/d3110/Дун Цзеюй/Lr1/caesar.py | 734 | 3.734375 | 4 | def mod(a,b):
c = a // b
r = a - c * b
return r
plaintext = input()
ciphertext = ''
for i in plaintext:
if i.isupper():
n = mod(ord(i) - 64 + 3, 26)
if n == 0:n =26
i = chr(64 + n)
elif i.islower():
n = mod(ord(i) - 96 + 3, 26)
if n == 0:n = 26
i = chr(96 + n)
ciphertext += i
print(ciphertext)
def mod(a,b):
c = a // b
r = a - c * b
return r
ciphertext = input()
plaintext = ''
for i in ciphertext:
if i.isupper():
n = mod(ord(i) - 64 - 3, 26)
if n == 0:n =26
i = chr(64 + n)
elif i.islower():
n = mod(ord(i) - 96 - 3, 26)
if n == 0:n = 26
i = chr(96 + n)
plaintext += i
print(plaintext)
|
a0add70d241389c97fda93aa4d662955b32b5af9 | Sanbu94/Python-kurssi2021 | /EXAMPLES/Classes/contact.py | 931 | 3.90625 | 4 | from datetime import datetime
class Contact():
def __init__(self, first_name, last_name, phone, birth_year):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.birth_year = birth_year
def ToString(self): # f-string formatoi stringing siten, että {} sisällä oleva muuttuja korvataan muuttujan arvolla.
return f"{self.first_name} {self.last_name}, p. {self.phone}"
def Age(self):
current_year = datetime.now().year
age = current_year - self.birth_year
return age
def main():
# Testataan Contact-luokan toimintaa main-funktiossa
person1 = Contact("Maija", "Mehiläinen", "29392949", 1994)
person2 = Contact("Matti", "Meikäläinen", "03846737", 1995)
print(person1.first_name)
print(person1.Age())
print(person2.first_name)
print(person2.Age())
if __name__ == "__main__":
main()
|
560380dcc3f5461211289e56314c60829103d81d | KevinKheng/khengsPortfolio | /Python/Paint Cost Calculator 2 Kevin Kheng.py | 4,055 | 4.25 | 4 | #Kevin Kheng
#Paint Cost Calculator
import math
'''
First I declared my variables.
Instead of dividing the surface area by 144, I converted my inches to feet first in order to make the program run better
and also it makes more sense to me.
'''
height_inches = 0
width_inches = 0
length_inches = 0
print("********************************************")
print("Welcome to my paint cost calculator program.")
print("********************************************")
height_inches = float(input("Enter the height of the room in inches: "))
width_inches = float(input( "Enter the width of the room in inches: "))
length_inches = float(input( "Enter the length of the room in inches:"))
'''
I convert the inches to feet by dividing the length , inches, and feet by 12.
I find the surface area of the 4 walls.
'''
height_feet = height_inches / 12
width_feet = width_inches/ 12
length_feet = length_inches/12
'''
I find the surface area first.
I use the if and else statement for the ceiling to see if they wanted to paint or not.
'''
total_surface_area = 2 * (height_feet * width_feet) + 2 *(height_feet * length_feet)
#print("total surface: " +str(total_surface_area))
ceiling_option = input("Do you want to paint the ceiling too? Type y for yes or n for no:")
if ceiling_option.lower().strip() == "y":
ceiling = width_feet * length_feet
total_surface_area = ceiling + total_surface_area
# print("total surface area: " +str(total_surface_area))
else:
total_surface_area = total_surface_area
# print("total_surface_area"+str(total_surface_area))
'''
I declare my number of windows and doors.
I find the surface area of the window and door by multiplying its by its dimension.
I then take the total_surface_area subtract by the total surface area of window and door.
'''
number_of_doors = 0
number_of_doors = int(input("How many doors are there? "))
doors_total_surface_area = number_of_doors * 7 * 3
#print("doors_total_surface_area: " + str(doors_total_surface_area))
number_of_windows = 0
number_of_windows = int(input("How many windows are there? "))
windows_total_surface_area = number_of_windows * 5 * 3
#print("windows_total_surface_area"+str(windows_total_surface_area))
total_surface_area = total_surface_area - windows_total_surface_area - doors_total_surface_area
#print("total surface: " +str(total_surface_area))
'''
In order for me to get my gallons of paint , I divide it by 350 so I know how much paint they need.I use the
ceil function on this.I also did this for the primer,if they aske.
'''
gallons_of_paint = (total_surface_area/350)
gallons_of_paint = math.ceil(gallons_of_paint)
#print("gallons of paint " + str(gallons_of_paint) )
cost_of_paint = float(input("Enter the cost of paint: "))
cost_of_paint = gallons_of_paint * cost_of_paint
#print("The total cost of paint is:" +str(cost_of_paint))
primer_option = primer_option = input("Is this the first time the room has been painted? Type y for yes or n for no: " )
primer = 0
total_cost = 0
gallons_of_primer = 0
if primer_option.lower().strip() == "y":
cost_of_primer =float(input("Enter the cost of primer:"))
gallons_of_primer = math.ceil(total_surface_area / 200)
# print("total surface: " +str(total_surface_area))
# print(gallons_of_primer)
cost_of_primer = gallons_of_primer * cost_of_primer
total_cost = cost_of_paint + cost_of_primer
else:
gallons_of_primer = 0
total_cost = cost_of_paint - 0
if primer_option.lower().strip() == "y":
print("You need to buy %d gallons of paint and %d gallons of primer." %(gallons_of_paint, gallons_of_primer))
print("Your total cost will be: $%.2f" %(total_cost))
print("Thank you for using Kevin Kheng paint cost calculator.Good-bye.")
else:
print("You need to buy %d2 gallons of paint."%(gallons_of_paint))
print("Your total cost will be:$%.2f" %(total_cost))
print("Thank you for using Kevin Kheng paint cost calculator.Good-bye.")
'''
I use the print statement earlier on to double check if my program of the math works.
I also commented it out
'''
|
c0d6d957ed7fed93254204719111a46dc53e5cab | will-a/Practice | /Python/maximumsubarray.py | 565 | 3.703125 | 4 | # https://leetcode.com/problems/maximum-subarray/
class Solution:
# dynamic programming solution that adds to the max subarray if the
# maximum subarray at the previous array index is greater than zero.
def maxSubArray(self, nums: list[int]) -> int:
res = []
res.append(nums[0])
maxn = nums[0]
for i in range(1, len(nums)):
res.append(nums[i] + max(res[i-1], 0))
print(res)
maxn = max(maxn, res[i])
return maxn
s = Solution()
s.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
|
c6abc2c12319dec40e5ca8675ee391b11418e41e | Success2014/Leetcode | /binaryTreeZigzagLevelOrderTraversal.py | 2,246 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 17 10:58:22 2015
Given a binary tree, return the zigzag level order traversal of its nodes'
values. (ie, from left to right, then right to left for the next level and
alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is
serialized on OJ.
Tags: Tree Breadth-first Search Stack
Similar Problems: (E) Binary Tree Level Order Traversal
idea:
跟(E) Binary Tree Level Order Traversal相比,只需要多
用一个变量toggle来记录是否应该从后往前加入数值。
@author: Neo
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[][]}
def zigzagLevelOrder(self, root):
if not root:
return []
toggle = False
res = []
level = []
que = [root, None]
while que:
node = que.pop(0)
if node is None:
if toggle:#只多了这么一个if判定
res.append(level[::-1])
else:
res.append(level[:])
level = []
toggle = not toggle#和这句更新toggle
if que:
que.append(None)
else:
level.append(node.val)
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return res
node1 = TreeNode(3)
node2 = TreeNode(9)
node3 = TreeNode(20)
node4 = TreeNode(15)
node5 = TreeNode(7)
node1.left = node2
node1.right = node3
node3.left = node4
node3.right = node5
sol = Solution()
print sol.zigzagLevelOrder(node1)
|
1621257bb6baf1e7c187f4b0b3b91fafe218c14a | uchihanuo/helloworld | /Program/str_format.py | 292 | 3.96875 | 4 | age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book.'.format(name, age))
print('Why is {0} playing that python?'.format(name))
print('{0:.5f}'.format(1.0/3))
print('{0:_^13}'.format('hello'))
print('{0} wrote {bookname}.'.format(name, bookname='A byte of Python'))
|
243fd3ae8f801dff642c9400f67af8df64684b22 | jang010505/Algorithm | /BOJ/7785.py | 484 | 3.734375 | 4 | n=int(input())
x_dict=dict()
for i in range(n):
name, info=input().split()
if name in x_dict:
if info=="leave":
x_dict[name]=0
else:
x_dict[name]=1
else:
if info=="leave":
x_dict.update({name:0})
else:
x_dict.update({name:1})
answer=list()
for name in x_dict.keys():
if x_dict[name]:
answer.append(name)
answer.sort()
answer.reverse()
for name in answer:
print(name)
|
bb6dab90d9776bb3611938691d45ba028b66cc9d | Carlzkh/CrazyPythonNotes | /8/dir_test.py | 419 | 3.859375 | 4 | """
__dir__:返回对象的所有属性和方法
"""
class Item:
def __init__(self, name, price):
self . name = name
self .price = price
def info(self):
pass
# 创建 Item 对象 将之赋值给 im 变量
im = Item('鼠标', 29.8)
print(im.__dir__()) # 返回所有属性(包括方法〉组成的列表
print(dir(im)) # 返回所有属性(包括方法〕排序之后的列表
|
f4c3681139e28b3e7e523db5cfc5339b14fe1329 | JeffreyAsuncion/CSPT15_ComputerScienceFundamentals | /Module01_Warmups/Objective12.py | 537 | 3.703125 | 4 | """
Objective 12 - Create user-defined functions and call them
"""
"""
Modify this function to make it return the sum of the arguments a and b.
"""
def sum(a, b):
# DELETE THE PASS STATEMENT AND WRITE YOUR CODE HERE
return a+b
# This should print 7
print(sum(2, 5))
"""
Modify this function to use the sum function above to return
the double of the sum of a and b.
"""
def double_the_sum(a, b):
# DELETE THE PASS STATEMENT AND WRITE YOUR CODE HERE
return 2*(a+b)
# This should print 14
print(double_the_sum(2, 5))
|
4d5c86692a9c5daa2cc758b14c286c1257a1865a | peter-stoyanov/Python | /Softuni Assignments/Lecture 07/diamond_problem.py | 541 | 3.796875 | 4 | #!/usr/bin/env python
"""Docstring"""
__author__ = "Petar Stoyanov"
import re
def main():
"""Docstring"""
text = input()
diamond_value = 0
regex = r"(<\w+>)"
matches = re.finditer(regex, text)
for match in matches:
match = match.group()
for ch in match:
if ch.isdigit():
diamond_value += int(ch)
if diamond_value == 0:
print('Better luck next time')
else:
print(f'Found {diamond_value} carat diamond')
if __name__ == '__main__':
main()
|
1786a4aff5b3cc21738b2a44aef8d430ce8af675 | cabbageGG/play_with_algorithm | /LeetCode/205_isIsomorphic.py | 954 | 4.09375 | 4 | #-*- coding: utf-8 -*-
'''
Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.
For example,
Given "egg", "add", return true.
Given "foo", "bar", return false.
Given "paper", "title", return true.
Note:
You may assume both s and t have the same length.
'''
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t) or len(set(s)) != len(set(t)):
return False
d = {}
for i in range(len(s)):
if s[i] not in d:
d[s[i]] = t[i]
elif d[s[i]] != t[i]:
return False
return True |
e1cc8d8b4203553dee82ffab550c2d1e54d2ccdf | Greycampus/pythondjango | /toc/serialization/natu.py | 262 | 3.890625 | 4 | #importing pickle module
import pickle
#storing in pickle dumps
pickled_list = pickle.dumps([i for i in range(1,int(input('enter the nth term:'))+1)])
print('serialized numbers')
#printing the serialized data using pickle loads
print(pickle.loads(pickled_list))
|
5cf5c06fbdc74ad879dc308672b2d5ac306a5259 | rakshsain20/ifelse | /citizen.py | 112 | 4 | 4 | age=int(input("enter the person"))
if age>60:
print("senior citizen")
else:
print("not senior citizen") |
74f17b4a85b000f5dda30c89e06f58a360eb7c5a | Goldenburgm/thinkpython | /is_pallindrome_word_list.py | 940 | 4.1875 | 4 | import bisect
def file_list(file_arg):
"""
Receives a file and converts it into a list.
"""
global file_list
file_list = []
open_file = open(str(file_arg))
for line in open_file:
item = line.strip()
file_list.append(item)
def word_bisect(s):
"""
Returns True if given word is in the words.txt file, using the bisect() function.
"""
b_right = bisect.bisect_right(file_list, s)
b_left = bisect.bisect_left(file_list, s)
if b_right > len(file_list) - 1:
return False
elif b_left < 0:
return False
else:
if file_list[b_right] == s or file_list[b_left] == s:
return True
return False
def reverse_pair():
"""
Finds all the reverse pairs in the file words.txt
and returns a list containing them.
"""
res = []
for i in file_list:
reverse_word = i[::-1]
if word_bisect(reverse_word) == True:
res.append(reverse_word)
res.append(i)
return res
file_list("words.txt")
print reverse_pair() |
6f05230f35a69d29955e2930fc2485265e58f801 | lucaslan/python-course | /ex5/3-primos-max.py | 320 | 3.796875 | 4 | def check_primo(x):
num = int(x)
primo = False
if (num % 2) != 0 and (num % 3) != 0:
primo = True
else:
primo = False
return primo
def maior_primo(x):
num = int(x)
while 2 <= num:
if check_primo(num):
return num
else:
num = num -1
|
3c2e494e6ced53a68c8427f48d8313eb9bfb7a38 | bdastur/notes | /frontend/reactjs/test.py | 766 | 3.859375 | 4 | #!/usr/bin/env python
def check_alert(mylist, idx, interval, threshold):
new_list = []
sum = 0
avg = 0
new_list = mylist[idx:idx+interval]
if len(new_list) < interval:
return 0
for item in new_list:
sum += item
avg = float(sum / interval)
print("avg: ", avg)
if avg >= threshold:
return 1
return 0
def rolling_avg(mylist, threshold, interval):
new_list = []
alert_count = 0
for idx in range(0, len(mylist)):
alert_count += check_alert(mylist, idx, interval, threshold)
return alert_count
def main():
mylist = [1, 3, 2, 1, 4, 5, 6, 7, 9]
alert_count = rolling_avg(mylist, 4, 3)
print("Alert: ", alert_count)
if __name__ == '__main__':
main()
|
89f3c7fa8bf6b8eb961bf61d0d44a9f16cca93cd | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/6b764b35efb94189882c063323510b4f.py | 1,441 | 4.09375 | 4 | '''
Leap Year
Author: Luke Shillabeer (lshillabeer@gmail.com)
This program implements the logic defined by the second problem (LEAP) in the
exercism.io python problem-set.
TESTING:
Units tests for this code exist in leap_test.py.
REVISION HISTORY:
24/09/14: First implemented and commented the is_leap_year function and
year module.
FEEDBACK:
'''
def is_leap_year(year):
'''
DESCRIPTION:
Determines whether or not a given year is a leap-year, using the following
logic;
It is a leap year on;
- every year evenly divisible by 400
- every year that is evenly divisible by 4
- unless that year is ALSO evenly divisible by 100
ASSUMPTIONS:
Assumes input will be an integer.
ARGS:
year: an integer representing a Gregorian calendar year.
RETURN:
True or False, depending on the year input.
EXAMPLES:
>>> is_leap_year(1996)
True
>>> is_leap_year(2400)
True
>>> is_leap_year(1900)
False
>>> is_leap_year(0)
True
'''
# determine whether year evenly divides into the numbers specified in the
# logic and store the results.
div_four = year % 4 == 0
div_hundred = year % 100 == 0
div_four_hundred = year % 400 == 0
# return based on the stored results and leap-year logic.
if div_four_hundred:
return True
elif div_four and not div_hundred:
return True
else:
return False
|
643309901e3561e946e9905b11222cd74515eb78 | mckkcm001/chemistry | /pythonscripts/discussion/Untitled Folder/Unit1Lesson2.py | 6,907 | 4.03125 | 4 | import random
import math
import Stuff.elements
def sigfig(n,s=3):
return round(n, s-int(math.floor(math.log10(n)))-1)
def group_problem1():
pairs=[]
elements = Stuff.elements.get_elements()
for e1 in elements:
for e2 in elements:
if elements[e1][1] < elements[e2][1] and elements[e1][2] > elements[e2][2]:
pairs.append([e1,e2])
question = '''<div id="question">
Find all pairs of elements where the average atomic weight <br>
of the element with the smaller atomic number is more than the<br>
average atomic weight of the element with the larger atomic number.<br>
</div>'''
answer = '<div id="answer"> '
for i in pairs:
answer += str(i)
answer += '</div> '
return question,answer
def group_problem2():
question = '''<div id="question">
Using only atomic symbols, write a short poem.<br>
Keep all leters upper and lower case as on the periodic table<br>
Examples: Ar + K = ArK, Ti + N + Y = TiNY
</div>'''
answer = '<div id="answer"> various</div>'
return question,answer
def group_problem3():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
The metric system uses prefixes to make new units.<br>
For example, kilo added to gram makes kilogram.<br>
The same is true using abbreviations: k with g makes kg.<br>
The relation between grams and kilograms is 1000 g = 1 kg.<br>
So kilo means 1000 or 10<sup>3</sup>.<br>
Converting from grams to kilograms, decrease the power of ten by 3.<br>
Converting from kilograms to grams, increase the power of ten by 3.<br>
Examples: 1e6 g = 1e3 kg, 1e6 kg = 1e9 g<br>
Convert the following to kg:<br>
{m[0]}e{e[0]} g<br>
{m[1]}e{e[1]} g<br>
{m[2]}e{e[2]} g<br>
{m[3]}e{e[3]} g<br>
{m[4]}e{e[4]} g<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]-3)
answer = '''<div id="answer">
{m[0]}e{e[0]} g = {m[0]}e{e1[0]} kg<br>
{m[1]}e{e[1]} g = {m[1]}e{e1[1]} kg<br>
{m[2]}e{e[2]} g = {m[2]}e{e1[2]} kg<br>
{m[3]}e{e[3]} g = {m[3]}e{e1[3]} kg<br>
{m[4]}e{e[4]} g = {m[4]}e{e1[4]} kg<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer
def group_problem4():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
Convert the following to g:<br>
{m[0]}e{e[0]} kg<br>
{m[1]}e{e[1]} kg<br>
{m[2]}e{e[2]} kg<br>
{m[3]}e{e[3]} kg<br>
{m[4]}e{e[4]} kg<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]+3)
answer = '''<div id="answer">
{m[0]}e{e[0]} kg = {m[0]}e{e1[0]} g<br>
{m[1]}e{e[1]} kg = {m[1]}e{e1[1]} g<br>
{m[2]}e{e[2]} kg = {m[2]}e{e1[2]} g<br>
{m[3]}e{e[3]} kg = {m[3]}e{e1[3]} g<br>
{m[4]}e{e[4]} kg = {m[4]}e{e1[4]} g<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer
def group_problem5():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
Another metrix prefix unit is milli.<br>
For example, milli added to gram makes milligram.<br>
The same is true using abbreviations: m with g makes mg.<br>
The relation between grams and milligrams is 1000 mg = 1 g.<br>
So milli means 0.001 or 10<sup>-3</sup>.<br>
Converting from grams to milligrams, increase the power of ten by 3.<br>
Converting from milligrams to grams, decrease the power of ten by 3.<br>
Examples: 1e6 g = 1e9 mg, 1e6 mg = 1e3 g<br>
Convert the following to mg:<br>
{m[0]}e{e[0]} g<br>
{m[1]}e{e[1]} g<br>
{m[2]}e{e[2]} g<br>
{m[3]}e{e[3]} g<br>
{m[4]}e{e[4]} g<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]+3)
answer = '''<div id="answer">
{m[0]}e{e[0]} g = {m[0]}e{e1[0]} mg<br>
{m[1]}e{e[1]} g = {m[1]}e{e1[1]} mg<br>
{m[2]}e{e[2]} g = {m[2]}e{e1[2]} mg<br>
{m[3]}e{e[3]} g = {m[3]}e{e1[3]} mg<br>
{m[4]}e{e[4]} g = {m[4]}e{e1[4]} mg<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer
def group_problem6():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
Convert the following to g:<br>
{m[0]}e{e[0]} mg<br>
{m[1]}e{e[1]} mg<br>
{m[2]}e{e[2]} mg<br>
{m[3]}e{e[3]} mg<br>
{m[4]}e{e[4]} mg<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]-3)
answer = '''<div id="answer">
{m[0]}e{e[0]} mg = {m[0]}e{e1[0]} g<br>
{m[1]}e{e[1]} mg = {m[1]}e{e1[1]} g<br>
{m[2]}e{e[2]} mg = {m[2]}e{e1[2]} g<br>
{m[3]}e{e[3]} mg = {m[3]}e{e1[3]} g<br>
{m[4]}e{e[4]} mg = {m[4]}e{e1[4]} g<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer
def group_problem7():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
Convert the following to kg:<br>
{m[0]}e{e[0]} mg<br>
{m[1]}e{e[1]} mg<br>
{m[2]}e{e[2]} mg<br>
{m[3]}e{e[3]} mg<br>
{m[4]}e{e[4]} mg<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]-6)
answer = '''<div id="answer">
{m[0]}e{e[0]} mg = {m[0]}e{e1[0]} kg<br>
{m[1]}e{e[1]} mg = {m[1]}e{e1[1]} kg<br>
{m[2]}e{e[2]} mg = {m[2]}e{e1[2]} kg<br>
{m[3]}e{e[3]} mg = {m[3]}e{e1[3]} kg<br>
{m[4]}e{e[4]} mg = {m[4]}e{e1[4]} kg<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer
def group_problem8():
man = [random.randint(100,800)/100. for i in range(5)]
exp = [random.randint(-50,50) for i in range(5)]
question = '''<div id="question">
Convert the following to mg:<br>
{m[0]}e{e[0]} kg<br>
{m[1]}e{e[1]} kg<br>
{m[2]}e{e[2]} kg<br>
{m[3]}e{e[3]} kg<br>
{m[4]}e{e[4]} kg<br>
</div>'''.format(m=man,e=exp)
exp1 = []
for i in range(5):
exp1.append(exp[i]+6)
answer = '''<div id="answer">
{m[0]}e{e[0]} kg = {m[0]}e{e1[0]} mg<br>
{m[1]}e{e[1]} kg = {m[1]}e{e1[1]} mg<br>
{m[2]}e{e[2]} kg = {m[2]}e{e1[2]} mg<br>
{m[3]}e{e[3]} kg = {m[3]}e{e1[3]} mg<br>
{m[4]}e{e[4]} kg = {m[4]}e{e1[4]} mg<br>
</div>''' .format(m=man,e=exp,e1=exp1)
return question,answer |
a8edc4775b82e094c1e0636c79a7e7ce58d88692 | MirandaRemmer/CA-H_TRACKS | /CA$H_TRACKS_Final_Draft copy/user_Class.py | 29,863 | 3.671875 | 4 | # CLASS: USER
from month_Class import Month
import csv
from os import listdir
class User(Month):
def __init__(self, month = None, year = None, income = None, budget = None, expenditures = None, budget_spending_tracker = None, dict_order = None):
Month.__init__(self, month, year)
self.my_month = Month(self.month, self.year)
self.my_month.income = self.income
self.my_month.budget = self.budget
self.my_month.expenditures = self.expenditures
self.my_month.budget_spending_tracker = self.budget_spending_tracker
self.dict_order = self.dict_order
def define_new_month(self, my_month, my_year):
return Month(self.month, self.year)
## MENU ITEMS ##
def show_welcome_message(self):
print "\n"
print "CA$H TRACKS"
print "\n"
def main(self):
self.show_welcome_message()
menu = (
"1. Create Budget",
"2. View / Edit Budget",
"3. Add Transaction",
"4. Track Spending Goals",
"5. Exit"
)
while (True):
for choice in menu:
print choice
user_choice = raw_input("Choose desired action by selecting it's corresponding number: ")
if (user_choice == "5") or (str.upper(user_choice) == "EXIT"):
exit()
elif user_choice == "1":
self.option_create_budget()
elif user_choice == "2":
self.option_view_edit_budget(self.my_month.month)
elif user_choice == "3":
self.option_add_transaction(self.my_month.month)
elif user_choice == "4":
self.option_track_budget_spending_goals(self.my_month.month)
elif user_choice not in ("1" , "2", "3", "4"):
print "Woops! Please choose which action by selecting it's cooresponding number."
def option_create_budget(self):
menu = (
"1. Create New Budget",
"2. Use a Budget from a Previous Month",
"3. Create Budget from Previous Month's Expenditures",
"4. Return to Home"
)
for choice in menu:
print "\t" + choice
user_choice = raw_input("Choose desired action by selecting it's corresponding number: ")
if (user_choice == "4") or (str.upper(user_choice) == "HOME"): # option 4: return home
None
elif (user_choice == "1"): # option 1: Create New Budget
self.create_new_budget()
elif (user_choice == "2"): # option 2: Use a Budget from a Previous Month
self.display_month_files()
print "Please be cautious of spelling!"
month_name = raw_input("Type desired month's budget: ")
print "\n"
self.return_formated_dict(self.extract_budget_data_from_file(month_name.upper()))
print "\n"
budget_question = raw_input("Would you like to use %s's budget data for this month's budget? (Y/N): " % (self.extract_month(month_name.upper())))
print "\n"
if (str.upper(budget_question) == "Y"): # use budget from previous month
self.my_month.month = (raw_input("Current Month: ").upper())
self.my_month.year = raw_input("Current Year: ")
currentMonth = self.define_new_month(self.my_month.month, self.my_month.year)
currentMonth.budget = (self.extract_budget_data_from_file(month_name.upper()))
self.my_month.budget = currentMonth.budget
self.file_save(self.my_month.month)
print "\n"
print "%s's Income: $%.2f" % (month_name.upper(), self.extract_income_data_from_file(month_name.upper()))
income_question = raw_input("Would you like to use the same income value? (Y/N): ")
if (str.upper(income_question) == "Y"): # use same income value
print "\n"
currentMonth.income = float(self.extract_income_data_from_file(month_name.upper()))
self.my_month.income = currentMonth.income
self.return_formated_dict(currentMonth.budget)
print "Income for this month: $%.2f" % (currentMonth.income)
print "Unallocated Money: $%.2f" % (self.calculate_unallocated_money(currentMonth.income, currentMonth.budget))
self.file_save(self.my_month.month)
# # # OLD DATA # :
# self.my_month.income = self.extract_income_data_from_file(month_name.upper())
# self.view_budget(self.my_month.month)
# self.file_save(self.my_month.month)
elif (str.upper(income_question) == "N"): # use new income
print "\n"
currentMonth.income = float(raw_input("This month's income: $"))
self.file_save(self.my_month.month)
self.my_month.income = currentMonth.income
self.return_formated_dict(currentMonth.budget)
print "Income for this month: $%.2f" % (currentMonth.income)
print "Unallocated Money: $%.2f" % (self.calculate_unallocated_money(currentMonth.income, currentMonth.budget))
self.file_save(self.my_month.month)
else:
self.main()
elif (user_choice == "3"): # option 3: Create Budget from Previous Month's Expenditures
self.display_month_files()
print "\n"
print "Please be cautious of spelling!"
month_name = raw_input("Type desired month's expenditures to create budget: ")
print "\n"
self.return_formated_dict(self.extract_expenditure_data_from_file(month_name.upper()))
budget_question = raw_input("Would you like to use %s's expenditure data for this month's budget? (Y/N): " % (month_name.upper()))
print "\n"
if (str.upper(budget_question) == "Y"): # use other month's expenditure data
self.my_month.month = (raw_input("Current Month: ").upper())
self.my_month.year = raw_input("Current Year: ")
currentMonth = self.define_new_month(self.my_month.month, self.my_month.year)
currentMonth.budget = (self.extract_expenditure_data_from_file(month_name.upper()))
self.my_month.budget = currentMonth.budget
self.file_save(self.my_month.month)
print "\n"
print "%s's Income: $%.2f" % (month_name.upper(), self.extract_income_data_from_file(month_name.upper()))
income_question = raw_input("Would you like to use the same income value? (Y/N): ")
if (str.upper(income_question) == "Y"): #use other month's income data
print "\n"
currentMonth.income = float(self.extract_income_data_from_file(month_name.upper()))
self.my_month.income = currentMonth.income
self.return_formated_dict(currentMonth.budget)
print "Income for this month: $%.2f" % (currentMonth.income)
print "Unallocated Money: $%.2f" % (self.calculate_unallocated_money(currentMonth.income, currentMonth.budget))
self.file_save(self.my_month.month)
elif (str.upper(income_question) == "N"): # put new income value
print "\n"
currentMonth.income = float(raw_input("This month's income: $"))
self.file_save(self.my_month.month)
self.my_month.income = currentMonth.income
self.return_formated_dict(currentMonth.budget)
print "Income for this month: $%.2f" % (currentMonth.income)
print "Unallocated Money: $%.2f" % (self.calculate_unallocated_money(currentMonth.income, currentMonth.budget))
self.file_save(self.my_month.month)
else:
self.main()
elif user_choice not in ("1" , "2", "3", "4"):
print "\n" + "Woops! Please choose which action by selecting it's cooresponding number." + "\n"
def option_view_edit_budget(self, month):
menu = (
"1. View Budget",
"2. Edit Budget",
"3. Return to Home"
)
while (True):
for category in menu:
print "\t" + category
user_choice = raw_input("Choose desired action by selecting it's corresponding number: ")
if (user_choice == "3") or (str.upper(user_choice) == "HOME"): # option 3: return home
self.main()
elif user_choice == "1": # View Current Budget
print "\n"
self.display_month_files()
print "\t"
print "Please be cautious of spelling!"
print "\t"
month_name = (raw_input("Month: ").upper())
print "\n"
self.my_month.month = month_name.upper()
self.my_month.year = self.extract_year(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.expenditures = self.extract_expenditure_data_from_file(month_name.upper())
self.my_month.budget_spending_tracker = self.extract_tracker_data_from_file(month_name.upper())
self.show_budget_message(self.extract_month(month_name.upper()), self.extract_year(month_name.upper()))
self.view_budget(month_name.upper())
print "\n"
user_choice2 = raw_input("Would you like to edit the above budget?(Y/N) ")
if (str.upper(user_choice2) == "N"):
self.main()
elif (str.upper(user_choice2) == "Y"): # edit budget
print "\n"
print "Edit your budget for %s, %s" % (month_name.upper(), self.extract_year(month_name.upper()))
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.edit_budget_value_by_number_listing(self.my_month.budget, self.extract_income_data_from_file(month_name.upper()), self.extract_month(month_name.upper()))
self.file_save(month_name.upper())
elif user_choice == "2": # Edit Current Budget
self.display_month_files()
print "Please be cautious of spelling!"
month_name = (raw_input("Month: ").upper())
self.my_month.month = month_name.upper()
self.my_month.year = self.extract_year(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.expenditures = self.extract_expenditure_data_from_file(month_name.upper())
self.my_month.budget_spending_tracker = self.extract_tracker_data_from_file(month_name.upper())
print "Edit your budget for %s, %s" % (month_name.upper(), self.extract_year(month_name.upper()))
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.view_budget(self.my_month.month)
self.file_save(month_name.upper())
self.edit_budget_value_by_number_listing(self.extract_budget_data_from_file(month_name.upper()), self.extract_income_data_from_file(month_name.upper()), self.extract_month(month_name.upper()))
self.file_save(month_name.upper())
def option_add_transaction(self, user_month_input = None):
self.display_month_files()
print "Please be cautious of spelling!"
month_name = (raw_input("Month: ").upper())
self.my_month.month = month_name.upper()
self.my_month.year = self.extract_year(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.expenditures = self.extract_expenditure_data_from_file(month_name.upper())
self.my_month.budget_spending_tracker = self.extract_tracker_data_from_file(month_name.upper())
self.add_transaction_by_number_listing(self.my_month.expenditures, self.my_month.budget_spending_tracker)
self.file_save(self.my_month.month)
def option_track_budget_spending_goals(self, month):
self.display_month_files()
print "Please be cautious of spelling!"
month_name = (raw_input("Month: ").upper())
self.my_month.month = month_name.upper()
self.my_month.year = self.extract_year(month_name.upper())
self.my_month.income = self.extract_income_data_from_file(month_name.upper())
self.my_month.budget = self.extract_budget_data_from_file(month_name.upper())
self.my_month.expenditures = self.extract_expenditure_data_from_file(month_name.upper())
self.my_month.budget_spending_tracker = self.extract_tracker_data_from_file(month_name.upper())
print "\n"
self.show_budget_spending_tracker_message(self.my_month.month, self.my_month.year)
self.calculate_budget_spending_tracker_values(self.my_month.budget, self.my_month.budget_spending_tracker)
self.return_formated_budget_spending_tracker(self.my_month.budget_spending_tracker)
self.file_save(self.my_month.month)
menu = (
"1. Add Transaction",
"2. Return home"
)
while (True):
for choice in menu:
print "\t" + choice
user_choice = raw_input("Choose desired action by selecting it's corresponding number: ")
if (user_choice == "2") or (str.upper(user_choice) == "HOME"): #option 2: return home
self.main()
elif user_choice == "1":
self.option_add_transaction(self.my_month.month)
elif user_choice not in ("1" , "2"):
print "Woops! Please choose which action by selecting it's cooresponding number."
def create_new_budget(self): # MY_MONTH
self.my_month.month = raw_input("Current Month: ")
self.my_month.year = raw_input("Current Year: ")
self.file_save(self.my_month.month)
self.show_budget_message(self.my_month.month, self.my_month.year)
self.return_formated_dict(self.my_month.budget) #prints out entire budget w/ "$0.00" next to each category
print "\n"
self.my_month.set_all_budget_values(self.my_month.budget)
self.my_month.income = float(raw_input("This month's income: "))
self.file_save(self.my_month.month)
print "\n"
self.show_budget_message(self.my_month.month, self.my_month.year)
self.view_budget(self.my_month.budget) #prints budget w/ new values
self.file_save(self.my_month.month)
self.return_unallocated_money_question()
self.file_save(self.my_month.month)
def view_budget(self, my_month):
self.return_formated_dict(self.my_month.budget)
self.view_income_message(self.my_month.month)
print "Unallocated Money: $%.2f" % (self.calculate_unallocated_money(self.my_month.income, self.my_month.budget))
def edit_budget_by_cateogry(self, my_month):
self.edit_budget_value_by_number_listing(self.my_month.budget, self.my_month.income, self.my_month.month)
self.file_save(self.my_month.month)
def add_to_budget(self, budget, unallocated_money):
self.add_to_budget_by_cateogry_listing(self.my_month.budget, self.my_month.income, self.my_month.month)
self.file_save(self.my_month.month)
def return_unallocated_money_question(self):
my_month_unallocated_money = float(self.my_month.calculate_unallocated_money(self.my_month.income, self.my_month.calculate_total_est_spending(self.my_month.budget)))
if my_month_unallocated_money > 0:
user_choice = raw_input("Based on your monthly income of $%.2f and your total estimated budget of $%.2f, you have $%.2f remaining, would you like to allocate it into budget category? (Y/N) " % (
self.my_month.income,
self.calculate_total_est_spending(self.my_month.budget), #removed self.my_month.calculate_total_est_spending
my_month_unallocated_money
))
if (str.upper(user_choice) == "Y"): #user wants to add extra money to category
#self.add_to_budget(self.my_month.budget, my_month_unallocated_money)
self.add_to_budget_by_cateogry_listing(self.my_month.budget, self.my_month.income, self.my_month.month)
self.file_save(self.my_month.month)
elif(str.upper(user_choice) == "N"):
self.main()
if my_month_unallocated_money < 0:
user_choice = raw_input("Your budget of $%.2f is net negative compared with your income of $%.2f. Would you like to edit your exisitng budget? (Y/N) " % (
self.calculate_total_est_spending(self.my_month.budget), #removed self.my_month.calculate_total_est_spending
self.my_month.income
))
if (str.upper(user_choice) == "Y"): #user wants to add extra money to category
#self.edit_budget_by_cateogry(self.my_month.budget)
self.edit_budget_value_by_number_listing(self.my_month.budget, self.my_month.income, self.my_month.month)
self.file_save(self.my_month.month)
else:
self.main()
def show_budget_message(self, my_month, my_year):
print "Your budget for %s, %s is: " % (my_month.upper(), self.my_month.year)
def show_budget_spending_tracker_message(self, my_month, my_year):
print "Budget vs. Spending for %s, %s is: " % (my_month.upper(), self.my_month.year)
def view_income_message(self, my_month):
print "Income for this month: $%.2f" % (self.my_month.income)
def display_month_files(self):
for file in listdir("/Users/Miranda/Desktop/Intro to Programming/FINAL PROJECT/CA$H_TRACKS_Final_Draft"):
if file.startswith ("my_month_data_") and file.endswith(".csv"):
file_name = str(file)
file_name_split = str(file_name.split("my_month_data_"))
month = file_name_split[6:-6]
print month
#### FILE SAVING & WRITING ####
def file_save(self, month): #CURRENT ONLY SAVES FOR 1 MONTH - DATA WILL OVERWRITE (use a file name as a parmameter?)
with open('my_month_data_' + month + '.csv', 'w') as my_month_out_file:
fieldnames = [
'month',
'year',
'income',
'budget_rent',
'budget_utilities',
'budget_transportation',
'budget_food_dining',
'budget_bars',
'budget_shopping',
'budget_personal',
'budget_health_fitness',
'budget_entertainment',
'budget_travel',
'budget_medical',
'budget_savings',
'expenditures_rent',
'expenditures_utilities',
'expenditures_transportation',
'expenditures_food_dining',
'expenditures_bars',
'expenditures_shopping',
'expenditures_personal',
'expenditures_health_fitness',
'expenditures_entertainment',
'expenditures_travel',
'expenditures_medical',
'expenditures_savings',
'budget_spending_tracker_rent',
'budget_spending_tracker_utilities',
'budget_spending_tracker_transportation',
'budget_spending_tracker_food_dining',
'budget_spending_tracker_bars',
'budget_spending_tracker_shopping',
'budget_spending_tracker_personal',
'budget_spending_tracker_health_fitness',
'budget_spending_tracker_entertainment',
'budget_spending_tracker_travel',
'budget_spending_tracker_medical',
'budget_spending_tracker_savings'
]
writer = csv.DictWriter(my_month_out_file, fieldnames = fieldnames)
writer.writeheader()
writer.writerow(
{
'month' : self.my_month.month, #HOW TO INPUT THIS - CALLING %S OF CLASS OBJECT "MONTH"
'year' : self.my_month.year,
'income' : self.my_month.income, #my_month_income,
'budget_rent' : self.my_month.budget['Rent'], #my_month_budget_data,
'budget_utilities' : self.my_month.budget['Utilities'],
'budget_transportation' : self.my_month.budget['Transportation'],
'budget_food_dining' : self.my_month.budget['Food & Dining'],
'budget_bars' : self.my_month.budget['Bars'],
'budget_shopping' : self.my_month.budget['Shopping'],
'budget_personal' : self.my_month.budget['Personal'],
'budget_health_fitness' : self.my_month.budget['Health & Fitness'],
'budget_entertainment' : self.my_month.budget['Entertainment'],
'budget_travel' : self.my_month.budget['Travel'],
'budget_medical' : self.my_month.budget['Medical'],
'budget_savings' : self.my_month.budget['Savings'],
'expenditures_rent' : self.my_month.expenditures['Rent'], #my_month_expenditure_data
'expenditures_utilities' : self.my_month.expenditures['Utilities'],
'expenditures_transportation' : self.my_month.expenditures['Transportation'],
'expenditures_food_dining' : self.my_month.expenditures['Food & Dining'],
'expenditures_bars' : self.my_month.expenditures['Bars'],
'expenditures_shopping' : self.my_month.expenditures['Shopping'],
'expenditures_personal' : self.my_month.expenditures['Personal'],
'expenditures_health_fitness' : self.my_month.expenditures['Health & Fitness'],
'expenditures_entertainment' : self.my_month.expenditures['Entertainment'],
'expenditures_travel' : self.my_month.expenditures['Travel'],
'expenditures_medical' : self.my_month.expenditures['Medical'],
'expenditures_savings' : self.my_month.expenditures['Savings'],
'budget_spending_tracker_rent' : self.my_month.budget_spending_tracker['Rent'], #my_month_budget_spending_tracker_data
'budget_spending_tracker_utilities' : self.my_month.budget_spending_tracker['Utilities'],
'budget_spending_tracker_transportation' : self.my_month.budget_spending_tracker['Transportation'],
'budget_spending_tracker_food_dining' : self.my_month.budget_spending_tracker['Food & Dining'],
'budget_spending_tracker_bars' : self.my_month.budget_spending_tracker['Bars'],
'budget_spending_tracker_shopping' : self.my_month.budget_spending_tracker['Shopping'],
'budget_spending_tracker_personal' : self.my_month.budget_spending_tracker['Personal'],
'budget_spending_tracker_health_fitness' : self.my_month.budget_spending_tracker['Health & Fitness'],
'budget_spending_tracker_entertainment' : self.my_month.budget_spending_tracker['Entertainment'],
'budget_spending_tracker_travel' : self.my_month.budget_spending_tracker['Travel'],
'budget_spending_tracker_medical' : self.my_month.budget_spending_tracker['Medical'],
'budget_spending_tracker_savings' : self.my_month.budget_spending_tracker['Savings']
}
)
def extract_month(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(row['month'])
extract_month = row['month']
self.my_month.month = extract_month
return self.my_month.month
def extract_year(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(row['year'])
extract_year = row['year']
self.my_month.year = extract_year
return self.my_month.year
def extract_income_data_from_file(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(row['income'])
extract_income = float(row['income'])
self.my_month.income = extract_income
return self.my_month.income
def extract_budget_data_from_file(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(
row['budget_rent'],
row['budget_utilities'],
row['budget_transportation'],
row['budget_food_dining'],
row['budget_bars'],
row['budget_shopping'],
row['budget_personal'],
row['budget_health_fitness'],
row['budget_entertainment'],
row['budget_travel'],
row['budget_medical'],
row['budget_savings']
)
extract_budget_rent = float(row['budget_rent'])
extract_budget_utilities = float(row['budget_utilities'])
extract_budget_transportation = float(row['budget_transportation'])
extract_budget_budget_food_dining = float(row['budget_food_dining'])
extract_budget_bars = float(row['budget_bars'])
extract_budget_shopping = float(row['budget_shopping'])
extract_budget_personal = float(row['budget_personal'])
extract_budget_health_fitness = float(row['budget_health_fitness'])
extract_budget_entertainment = float(row['budget_entertainment'])
extract_budget_travel = float(row['budget_travel'])
extract_budget_medical = float(row['budget_medical'])
extract_budget_savings = float(row['budget_savings'])
self.my_month.budget['Rent'] = extract_budget_rent
self.my_month.budget['Utilities'] = extract_budget_utilities
self.my_month.budget['Transportation'] = extract_budget_transportation
self.my_month.budget['Food & Dining'] = extract_budget_budget_food_dining
self.my_month.budget['Bars'] = extract_budget_bars
self.my_month.budget['Shopping'] = extract_budget_shopping
self.my_month.budget['Personal'] = extract_budget_personal
self.my_month.budget['Health & Fitnessent'] = extract_budget_health_fitness
self.my_month.budget['Entertainment'] = extract_budget_entertainment
self.my_month.budget['Travel'] = extract_budget_travel
self.my_month.budget['Medical'] = extract_budget_medical
self.my_month.budget['Savings'] = extract_budget_savings
return self.my_month.budget
def extract_expenditure_data_from_file(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(
row['expenditures_rent'],
row['expenditures_utilities'],
row['expenditures_transportation'],
row['expenditures_food_dining'],
row['expenditures_bars'],
row['expenditures_shopping'],
row['expenditures_personal'],
row['expenditures_health_fitness'],
row['expenditures_entertainment'],
row['expenditures_travel'],
row['expenditures_medical'],
row['expenditures_savings']
)
extract_expenditures_rent = float(row['expenditures_rent'])
extract_expenditures_utilities = float(row['expenditures_utilities'])
extract_expenditures_transportation = float(row['expenditures_transportation'])
extract_expenditures_food_dining = float(row['expenditures_food_dining'])
extract_expenditures_bars = float(row['expenditures_bars'])
extract_expenditures_shopping = float(row['expenditures_shopping'])
extract_expenditures_personal = float(row['expenditures_personal'])
extract_expenditures_health_fitness = float(row['expenditures_health_fitness'])
extract_expenditures_entertainment = float(row['expenditures_entertainment'])
extract_expenditures_travel = float(row['expenditures_travel'])
extract_expenditures_medical = float(row['expenditures_medical'])
extract_expenditures_savings = float(row['expenditures_savings'])
self.my_month.expenditures['Rent'] = extract_expenditures_rent
self.my_month.expenditures['Utilities'] = extract_expenditures_utilities
self.my_month.expenditures['Transportation'] = extract_expenditures_transportation
self.my_month.expenditures['Food & Dining'] = extract_expenditures_food_dining
self.my_month.expenditures['Bars'] = extract_expenditures_bars
self.my_month.expenditures['Shopping'] = extract_expenditures_shopping
self.my_month.expenditures['Personal'] = extract_expenditures_personal
self.my_month.expenditures['Health & Fitnessent'] = extract_expenditures_health_fitness
self.my_month.expenditures['Entertainment'] = extract_expenditures_entertainment
self.my_month.expenditures['Travel'] = extract_expenditures_travel
self.my_month.expenditures['Medical'] = extract_expenditures_medical
self.my_month.expenditures['Savings'] = extract_expenditures_savings
return self.my_month.expenditures
def extract_tracker_data_from_file(self, month):
with open('my_month_data_' + month + '.csv') as my_month_in_file:
reader = csv.DictReader(my_month_in_file)
for row in reader:
(
row['budget_spending_tracker_rent'],
row['budget_spending_tracker_utilities'],
row['budget_spending_tracker_transportation'],
row['budget_spending_tracker_food_dining'],
row['budget_spending_tracker_bars'],
row['budget_spending_tracker_shopping'],
row['budget_spending_tracker_personal'],
row['budget_spending_tracker_health_fitness'],
row['budget_spending_tracker_entertainment'],
row['budget_spending_tracker_travel'],
row['budget_spending_tracker_medical'],
row['budget_spending_tracker_savings']
)
extract_budget_spending_tracker_rent = float(row['budget_spending_tracker_rent'])
extract_budget_spending_tracker_utilities = float(row['budget_spending_tracker_utilities'])
extract_budget_spending_tracker_transportation = float(row['budget_spending_tracker_transportation'])
extract_budget_spending_tracker_food_dining = float(row['budget_spending_tracker_food_dining'])
extract_budget_spending_tracker_bars = float(row['budget_spending_tracker_bars'])
extract_budget_spending_tracker_shopping = float(row['budget_spending_tracker_shopping'])
extract_budget_spending_tracker_personal = float(row['budget_spending_tracker_personal'])
extract_budget_spending_tracker_health_fitness = float(row['budget_spending_tracker_health_fitness'])
extract_budget_spending_tracker_entertainment = float(row['budget_spending_tracker_entertainment'])
extract_budget_spending_tracker_travel = float(row['budget_spending_tracker_travel'])
extract_budget_spending_tracker_medical = float(row['budget_spending_tracker_medical'])
extract_budget_spending_tracker_savings = float(row['budget_spending_tracker_savings'])
self.my_month.budget_spending_tracker['Rent'] = extract_budget_spending_tracker_rent
self.my_month.budget_spending_tracker['Utilities'] = extract_budget_spending_tracker_utilities
self.my_month.budget_spending_tracker['Transportation'] = extract_budget_spending_tracker_transportation
self.my_month.budget_spending_tracker['Food & Dining'] = extract_budget_spending_tracker_food_dining
self.my_month.budget_spending_tracker['Bars'] = extract_budget_spending_tracker_bars
self.my_month.budget_spending_tracker['Shopping'] = extract_budget_spending_tracker_shopping
self.my_month.budget_spending_tracker['Personal'] = extract_budget_spending_tracker_personal
self.my_month.budget_spending_tracker['Health & Fitnessent'] = extract_budget_spending_tracker_health_fitness
self.my_month.budget_spending_tracker['Entertainment'] = extract_budget_spending_tracker_entertainment
self.my_month.budget_spending_tracker['Travel'] = extract_budget_spending_tracker_travel
self.my_month.budget_spending_tracker['Medical'] = extract_budget_spending_tracker_medical
self.my_month.budget_spending_tracker['Savings'] = extract_budget_spending_tracker_savings
return self.my_month.budget_spending_tracker
|
813ffdaae53987771d09116b06b90418be69163c | priya510/Python-codes | /5.11.2020/python important questions/python19.py | 290 | 3.59375 | 4 | import pandas as pd
import numpy as np
df=pd.DataFrame({"A":[1,5,3,4,2],
"B":[3,2,4,3,4],
"C":[2,2,7,3,4],
"D":[4,3,6,12,7]},
columns=["A","B","C","D"])
#Row - 0
#Column - 1
print(df.apply(np.mean,axis=1))
|
74220b368e2116a0d8fa1425e851199dc57f09b8 | dongheelee1/LeetCode | /goog/680_Valid_Palindrome_II.py | 1,229 | 3.90625 | 4 | '''
680. Valid Palindrome II
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class Solution:
def validPalindrome(self, s: str) -> bool:
#pointers at each end
i = 0
j = len(s) - 1
while i < j:
#characters at either end don't match up
#check to see if (i+1, j) -th characters onwards or (i, j+1) -th characters onwards match up
if s[i] != s[j]:
return self.checkPalindrome(s, i+1, j) or self.checkPalindrome(s, i, j-1)
i += 1
j -= 1
return True #at this point, the given string is a perfect palindrome
def checkPalindrome(self, s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
|
feb78f1fd577177b8d13d5b0c5e7f60375b8d994 | dskatkov/prographing_project | /sources/utils.py | 12,241 | 3.515625 | 4 | import json
# import os
import tkinter as tk
from settings import *
class Point:
"""Класс точки-вектора/ class of a point-vector"""
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(a, b):
"""a + b"""
return Point(a.x + b.x, a.y + b.y)
def __mul__(a, k):
"""a * k"""
return Point(a.x * k, a.y * k)
def __imul__(self, k):
self.x *= k
self.y *= k
return self
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __ineg__(self):
self.x *= -1
self.y *= -1
def __isub__(self, other):
self.x -= other.x
self.y -= other.y
return self
def __idiv__(self, k):
"""a * k"""
if k:
self.x /= k
self.y /= k
else:
self.x = 0
self.y = 0
return self
def __neg__(a):
"""-a"""
return a * (-1)
def __sub__(a, b):
"""a - b"""
return a + (-b)
def __truediv__(a, k):
"""a * k"""
if k:
return Point(a.x / k, a.y / k)
else:
return Point(0, 0)
def __str__(self):
"""str(self)"""
return f'({self.x},{self.y})'
def __eq__(a, b):
"""a == b"""
return a.x == b.x and a.y == b.y
def __lt__(a, b):
"""a < b"""
if a.y < b.y:
return True
if a.y > b.y:
return False
return a.x < b.x
def abs(self):
"""Длина вектора/vector length"""
return (self.x ** 2 + self.y ** 2) ** 0.5
@staticmethod
def fromTuple(tup):
"""Создает Point из кортежа/ create point out of tuple"""
return Point(*tup)
def set(self, x, y):
self.x = x
self.y = y
return self
def tuple(self):
"""Создает кортеж из Point/ create tuple out of point"""
return self.x, self.y
def round(self, s=1):
"""Округляет координаты до требуемой точности/ round to the necessary accuracy"""
return Point(round(self.x / s) * s, round(self.y / s) * s)
def swap(self):
return Point(self.y, self.x)
def norm(self, k=1):
return self / (self.abs() / k)
def dist(self, other):
return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
def setInPlace(self, x, y):
self.x = x
self.y = y
return self
def sumInPlace(self, other):
self.x += other.x
self.y += other.y
return self
def mulInPlace(self, k):
self.x *= k
self.y *= k
return self
def negInPlace(self):
self.x *= -1
self.y *= -1
return self
def subInPlace(self, other):
self.x -= other.x
self.y -= other.y
return self
def divInPlace(self, k):
"""a * k"""
if k:
self.x /= k
self.y /= k
else:
self.x = 0
self.y = 0
return self
def roundInPlace(self, s=1):
"""Округляет координаты до требуемой точности/ round to the necessary accuracy"""
self.x = round(self.x / s) * s,
self.y = round(self.y / s) * s
return self
def swapInPlace(self):
"""interchange x and y coordinates"""
self.x, self.y = self.y, self.x
return self
def normInPlace(self):
self.divInPlace(self.abs())
return self
def copy(self):
"""Make copy of the point"""
return Point(self.x, self.y)
def same(self, other):
if self.x == other.x and self.y == other.y:
return True
return False
class Area():
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def upperleft(self):
x = min(self.p1.x, self.p2.x)
y = min(self.p1.y, self.p2.y)
return Point(x, y)
def downright(self):
x = max(self.p1.x, self.p2.x)
y = max(self.p1.y, self.p2.y)
return Point(x, y)
def rect(self):
return(self.upperleft().x, self.upperleft().y, self.downright().x, self.downright().y)
def boundrect(self):
s = selection_boundary
return (self.upperleft().x - 1*s, self.upperleft().y - 1*s, self.downright().x + 2*s, self.downright().y + 2*s)
def height(self):
return (self.downright().y - self.upperleft().y)
def width(self):
return (self.downright().x - self.upperleft().x)
def __contains__(self, other):
if (other.x >= self.upperleft().x) and (other.x <= self.downright().x):
if (other.y >= self.upperleft().y) and (other.y <= self.downright().y):
return True
return False
debug_log = ...
def debug_init(file):
"""Установка файла для дебагового лога/ set file for debug log"""
global debug_log
debug_log = file
def debug_close():
"""Закрытие файла лога/ Closing log file"""
global debug_log
debug_log.close()
def debug_return(s: str):
"""Вывод в дебаговый лог/ output to debug log"""
if debug_to_console:
print(s)
if debug_flag:
debug_log.write(str(s) + '\n')
def json_load(path: str):
"""Загружает json-объект из файла"""
fp = open(path, 'rt')
obj = json.load(fp)
fp.close()
return obj
def createMenu(master, tree: dict):
"""Создает меню и прикрепляет его к master/ create menu and assign it to master"""
for key, val in tree.items():
m = tk.Menu(master=master, tearoff=0)
if isinstance(val, dict):
createMenu(m, val)
else:
master.add_command(label=key, command=val)
continue
master.add_cascade(label=key, menu=m)
def placeButtons(master, buttons: list, side: str = 'left', fg=btnFG, bg=btnBG):
"""Располагает кнопки на фрейме/ place buttons on frame"""
for btn in buttons:
b = tk.Button(
master=master, text=btn[0], command=btn[1], fg=btnFG, bg=btnBG)
b.pack(side=side, padx=3, pady=3)
# def getSettingsByLang(lang):
# """Устанавливает настройки в связи с языком программирования/Set setting associated with programming language"""
# raise Exception
# res = {}
# for type in allTypes:
# res = dictMerge(
# res,
# createDictByPath(
# f'{type}.build',
# dictMerge(
# getDictValByPath(allTypes, f'{type}.build.{lang}'), getDictValByPath(allTypes, f'{type}.build.*')
# )
# )
# )
# for key, val in allTypes[type].items():
# if not (key in ['build']):
# res = dictMerge(res, {type: {key: val}})
# return res
def takeFirst(x, y): return x
def takeSecond(x, y): return y
def normalMerge(a, b, f=None):
"""Функция слияния двух элементов/ Function of merging two elements"""
if isinstance(a, dict) and isinstance(b, dict):
return dictMerge(a, b)
else:
if a == b:
return a
elif f is not None:
return f(a, b)
else:
raise Exception(f'Merge conflict: {a} and {b}')
def dictMerge(*dicts, f=None):
"""Соединяет несколько словарей в один/ merge s number of dictionaries into one"""
if len(dicts) == 2:
a, b = dicts
res = a
for key, val in b.items():
if key in a:
val2 = a[key]
if val == val2:
res[key] = val
else:
if isinstance(val, dict) and isinstance(val2, dict):
res[key] = dictMerge(val, val2)
elif f is not None:
res[key] = f(val2, val)
else:
raise Exception(f'Merge conflict: {a} and {b}')
else:
res[key] = val
return res
elif len(dicts) > 2:
return dictMerge(dictMerge(dicts[0:2]), dicts[2:])
elif len(dicts) == 0:
return {}
elif len(dicts) == 1:
return dicts[0]
def _getDictValByPath(d: dict, path: str, err=None):
"""Возвращает значение элемента в словаре по пути к элементу
/ returns element value in dictionary by path to the element"""
val: dict = d
spl: list = path.split('.')
for key in spl:
if key in val:
val = val[key]
else:
return err
return val
def getDictValByPath(d, form, *args, braces='<>'):
lb, rb = braces
s = form
for i in range(len(args) - 1, -1, -1):
s = s.replace(f'{lb}{i + 1}{rb}', args[i])
res = _getDictValByPath(d, s)
if res is None:
raise Exception(f'Cannot get dict value by path: \ndict:{d} \npath:{form} \nargs: {args}')
return res
def distance_to_line(begin: Point, end: Point, point: Point):
"""Расстояние от отрезка (begin, end) до точки point/ distance from the segment (begin, end) to the point"""
x1, y1 = begin.tuple()
x2, y2 = end.tuple()
x, y = point.tuple()
if begin == end:
dist = begin.dist(point)
else:
# A, B, C are factors of Ax+By+C=0 equation
a = (x2 - x1) # 1/A
b = (y1 - y2) # 1/B
c = -x1 * b - y1 * a # C/AB
dist = (b * x + a * y + c) / (a ** 2 + b ** 2) ** 0.5
dist = abs(dist)
return dist
def near_to_line(begin: Point, end: Point, point: Point):
"""Проверяет близость точки прямой/ Check whether point is near to the line"""
eps = nearToLine
d = distance_to_line(begin, end, point)
x1, y1 = begin.tuple()
x2, y2 = end.tuple()
x, y = point.tuple()
return (d < eps) and (min(x1, x2) - eps < x < max(x1, x2) + eps) and (min(y1, y2) - eps < y < max(y1, y2) + eps)
# TODO: перенести эти функции в gp_sourcefile.py
def findCycle(SF, block, root):
"""Проверяет существование цикла ссылок/ checking existence of cycle links"""
for id in block.childs:
child = SF.object_ids[id]
if child is root:
return True
elif findCycle(SF, child, root):
return True
return False
def cycle_checkout(SF, block):
"""Проверяет существование цикла ссылок/ checking existence of cycle links"""
return findCycle(SF, block, block)
def find_block_(click, canvas, SF, mode=1):
"""Находит блок по позиции клика/ Find block by its position"""
# def scale(pos):
# return canvas.scale(pos)
def unscale(pos):
return canvas.unscale(pos)
clickpos = Point(click.x, click.y)
sfclick = unscale(clickpos)
debug_return(f'handling click: {clickpos}')
if mode == 0: # находжение по радиусу блока
for _, block in SF.object_ids.items():
# debug_return('checking block: ' + block.convertToStr())
distance = (block.pos - sfclick).abs()
if distance <= blockR:
debug_return(f'block found: {block.convertToStr()}')
return block
elif mode == 1: # нахождение по клетке клика
for _, block in SF.object_ids.items():
# debug_return('checking block: ' + block.convertToStr())
d = block.pos - sfclick
if abs(d.x) < 0.5 and abs(d.y) < 0.5:
debug_return(f'block found: {block.convertToStr()}')
return block
# Число Эйлера и число пи/ Euler's number and pi number
e = 2.718281828459045
pi: float = 3.1415926535
if __name__ == '__main__':
print('This module is not for direct call!')
|
489e7e4432e15a057b2ffdd0816b3a0358c2ea95 | JuanesKill/Modelos2- | /palindromo.py | 258 | 3.921875 | 4 | def palindromo(s):
if (len(s) < 2):
return "palindromo"
else:
if (s[-len(s)]) == (s[len(s)-1]):
return palindromo(s[1: len(s)-1])
else:
return "no palindromo"
print palindromo("rotor")
|
9d512cdccb2e088f93f2702642ca18c9e7e6eae1 | Incutero/flovary | /tests/sp14_006_ps4_folder_test/PSET4.py | 2,133 | 4 | 4 | from decimal import Decimal
# Returns the next guess after one iteration of Newton's method.
#
# Arguments:
# - number: The number whose cube root is to be calculated.
# - guess: The current guess of the cube root.
def CubeRootNewtonIteration(number, guess):
assert type(number) == int
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
# Returns an integer guess for the cube root of the number.
#
# Arguments:
# - number: The number whose cube root is to be calculated.
def CubeRootGuess(number):
assert type(number) == int
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
# Returns the best floating-point approximation to the cube root of the number.
#
# Arguments:
# - number: The number whose cube root is to be calculated.
def FloatCubeRoot(number):
assert type(number) == int
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
# Returns a guess of the reciprocal of the given decimal number.
#
# Arguments:
# - number: The decimal number whose reciprocal is to be guessed.
def ReciprocalGuess(number):
assert type(number) == Decimal
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
# Returns the reciprocal of the give decimal number, computed to the same
# precision as number itself (i.e., number.precision).
#
# Arguments:
# - number: The decimal number whose reciprocal is to be computed.
def DecimalReciprocal(number):
assert type(number) == Decimal
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
# Returns the best approximation to the cube root of the number using decimal
# numbers with the given number of digits of precision.
#
# Arguments:
# - number: The number whose cube root is to be calculated.
# - precision: The number of digits of precision to use.
def DecimalCubeRoot(number, precision):
assert type(number) == int
assert type(precision) == int
# Note: You will need to pass reciprocal=DecimalReciprocal when creating
# Decimal numbers with support for division.
# BEGIN STUDENT CODE
raise NotImplementedError()
# END STUDENT CODE
|
08db4dd4e93395b660a11f97e1ba0ae5262bbe42 | toadereandreas/Babes-Bolyai-University | /1st semester/Fundamentals-of-programming/Test_19.12/domain/entitity.py | 899 | 3.859375 | 4 | import random
class player(object):
'''
This class creates and manages the entity player.
'''
def __init__(self,name,dist,speed,wind):
'''
The constructor atributes the properties to the object.
'''
self.__name = name
self.__time = dist
self.__speed = speed
self.__wind = wind
self.__distance = float(self.__time) * (float(self.__speed) + round(random.uniform(-0.5,0.5),2) * int(self.__speed) + int(self.__wind))
def get_name(self):
return self.__name
def get_time(self):
return self.__time
def get_speed(self):
return self.__speed
def get_wind(self):
return self.__wind
def get_distance(self):
return self.__distance
def __str__(self):
return self.__name + "," + str(self.__time) + "," + str(self.__speed) + "," + str(self.__wind) |
1142e955a81d2660c23dcc62c35b8c3934919825 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2674/58616/316242.py | 236 | 3.59375 | 4 | for _ in range(int(input())):
s = input()
n = len(s)
a, ab, abc = 0, 0, 0
for i in range(n):
if s[i] == "a": a = 1 + 2 * a
elif s[i] == "b": ab = a + 2 * ab
else: abc = ab + 2 * abc
print(abc) |
a21bb44cdd3493ffff105c8c9a7ee889849f53df | yoonwoolee/efp | /e29.py | 530 | 3.96875 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import math
import sys
my_input = input if sys.version_info >= (3,0) else raw_input
if __name__ == "__main__":
error = False
while True:
try:
input_value = float(my_input("What is the rate of return? "))
except ValueError:
error = True
else:
if input_value == 0:
error = True
else:
break
if error == True:
print("Sorry. That's not a valid input.")
year = 72 / input_value
print("It will take %d years to double your initial investment." % year)
|
c31cbddcecf752ee3099e69a4cb15614c8b74b75 | thiagoAlexandre3/cursos-auto-didata | /curso-python/scripts-para-aula/tipos-primitivos-a.py | 149 | 3.828125 | 4 | n1 = int(input('Digite um número: '));
n2 = int(input('Digite outro: '));
soma = n1 + n2;
print("A soma de {} + {} vale, {}!".format(n1, n2, soma)); |
37aced4ff9b8b37802229e50159dd72147a3c637 | rbnbrls/think-python | /chapter2/excersises.py | 1,858 | 4.625 | 5 | #2.10 Exercises
print ("Exercise 1")#Exercise 1
#Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.
#We’ve seen that n = 42 is legal. What about 42 = n?
#How about x = y = 1?
#In some languages every statement ends with a semi-colon, ;. What happens if you put a semi-colon at the end of a Python statement?
#What if you put a period at the end of a statement?
#In math notation you can multiply x and y like this: x y. What happens if you try that in Python?
print ("Exercise 2")
#Practice using the Python interpreter as a calculator:
#The volume of a sphere with radius r is 4/3 π r3. What is the volume of a sphere with radius 5?
r = 5
pi = 3.141592653589793
volume = (4/3) * pi * r**3
print("the volume of a sphere with radius 5 is: ", volume)
#Suppose the cover price of a book is $24.95, but bookstores get a 40% discount. Shipping costs $3 for the first copy and 75 cents for each additional copy.
# What is the total wholesale cost for 60 copies?
book_price = 24.95
discount = 0.6
amount_books = 60
shipping = 3 + (amount_books - 1)* 0.75
wholesale = amount_books * (book_price * discount) + shipping
print("Wholesale for ", amount_books, "copies is:$",wholesale)
#If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
""""in seconds"""
easy_pace = (8*60)+15
tempo = (7*60)+12
run_time = 2 * easy_pace + 3 * tempo
run_minutes = run_time / 60
time = int(run_minutes)-8
print("I get home for breakfast at: 7:",time, "am")
""""in minutes"""
easy_pace = 8.25
tempo = 7.2
run_time = 2 * easy_pace + 3 * tempo
time = int(run_time)-8
print("I get home for breakfast at: 7:",time, "am")
|
fb6903714f6b3cb2617344e8a2147632fe4301a3 | AveryPratt/code-katas | /src/string_manipulation.py | 237 | 3.671875 | 4 | """Returns a deformed concatination of two strings."""
def reverse_and_mirror(s_1, s_2):
"""Manipulates two strings in several different ways to get an obscure result."""
return (s_2[::-1] + "@@@" + s_1[::-1] + s_1).swapcase()
|
ef6e069d68cf92263051012bb7c2e6f8987135e1 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_117/503.py | 609 | 3.5625 | 4 | #! /usr/bin/env python3
def check_lawn(lawn, N, M, rm, cm):
for i in range(N):
for j in range(M):
if lawn[i][j] < rm[i] and lawn[i][j] < cm[j]:
return "NO"
return "YES"
T = int(input())
for case in range(T):
lawn = []
N, M = [int(x) for x in input().split()]
for line in range(N):
lawn.append([int(x) for x in input().split()])
row_maxs = [max(row) for row in lawn]
col_maxs = [max(row[i] for row in lawn) for i in range(M)]
answer = check_lawn(lawn, N, M, row_maxs, col_maxs)
print("Case #{0}: {1}".format(case + 1, answer))
|
aba0fee1872dc03e27f2f5fe3f8b4e3024715f93 | kamal-mk/Zorro | /test.py | 195 | 3.546875 | 4 | from geotext import GeoText
query="Golden Gate is an amazing place in San Francisco, I don't think anywhere uin London comes close."
places = GeoText(query)
for y in places.cities:
print(y) |
ea78cbce3cb9e692b8dc7e01398e2831a5e10ed6 | alyssakelley/projects_in_python | /binary_search_tree/BST.py | 7,327 | 4.125 | 4 | """
Name: Alyssa Kelley
CIS 313 Winter 2019
Due: Feb. 18th, 2019
Disclaimer: I worked on this project with Anne Glickenhause, Kiana Hosaka, and Miguel N. None of the code was copied, but
the logic was discussed and ideas were shared amoung all of us. I also used GeeksforGeeks with help on understand the logic
behind the BST and their different functionalities. Once again, no code was copied and here is the link I used:
https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/
"""
from Node import Node
class BST(object):
def __init__(self):
self.__root = None
def getRoot(self):
# Private Method, can only be used inside of BST.
return self.__root
def __findNode(self, data):
# Private Method, can only be used inside of BST.
root_data = self.getRoot()
# searching the tree for a node whose data
# field is equal to data.
if root == None:
return None
else:
while root != None:
if data > root.getData():
root = root.getRightChild()
else:
root = root.getLeftChild()
return root.getParent() # Return the Node object
def contains(self, data):
# Please note: You refer to this function as exist in your project spec
# but when I downloaded the source code, it is called contained so I am
# not renaming it, but they are the same function.
# return True of node containing data is present in the tree.
# otherwise, return False.
# using getParent to keep it public
parent = self.getParent(data)
if parent == None: # if there is no parent for the data, it is not in tree
return False
else:
return True
def insert(self, data):
new_node = Node(data) # This is the node we need to insert so we create an
# instance of a node.
if (self.__root == None): # If there is no root, then it becomes the root.
self.__root = new_node
else:
current_node = self.__root # Since there is a root, we are going to start there,
# and move down to find where we can insert the new_node.
parent = None # Keeping track of the parent of current node (so initially that is root
# but this will change)
while(current_node != None): # Wanting to find the location/position
# where we can insert the new_node so we are looping through until the current position
# is not null.
current_node.setParent(current_node)
parent = current_node
if data < current_node.getData():
current_node = current_node.getLeftChild()
else:
current_node = current_node.getRightChild()
# We found the right position, and now we need to insert that new_node into
# the correct position.
if data < parent.getData():
new_node.setParent(parent)
current_node = parent
current_node.setLeftChild(new_node)
else:
new_node.setParent(parent)
current_node = parent
current_node.setRightChild(new_node)
def delete(self, data):
# Find the node to delete.
# If the value specified by delete does not exist in the tree, then don't change the tree.
# If you find the node and ...
# a) The node has no children, just set it's parent's pointer to Null.
# b) The node has one child, make the nodes parent point to its child.
# c) The node has two children, replace it with its successor, and remove
# successor from its previous location.
# Recall: The successor of a node is the left-most node in the node's right subtree.
# Hint: you may want to write a new method, findSuccessor() to find the successor when there are two children
root = self.getRoot()
deleted_node = self.deleteTheNode(root, data)
def deleteTheNode(self, root, data):
# This is a function I created to assist the delete function so I can take in the current root (which
# changes as you can see below) to accurently delete the desired node.
if root == None:
return root
if data < root.getData():
root.setLeftChild(self.deleteTheNode(root.getLeftChild(), data))
elif data > root.getData():
root.setRightChild(self.deleteTheNode(root.getRightChild(), data))
else:
if root.getLeftChild() == None: # If there is no left child, then that means there are either no children,
# or it has just one right child.
temp_node = root.getRightChild()
root = None
return temp_node
elif root.getRightChild() == None: # No children.
temp_node = root.getLeftChild()
root = None
return temp_node
# This is a node with two children
temp_node = self.findSuccessor(root.getRightChild())
root.setData(temp_node.getData())
# delete the successor node
root.setRightChild(self.deleteTheNode(root.getRightChild(), temp_node.getData()))
return root
def findSuccessor(self, aNode):
# This is a new method to find the successor when there are two children and it does so
# by looping through the node when it definitly has two children (aka when there is
# a left child, you know there is an automatic right child so there are gaurenteed
# two children) and then you keep going to the left child and checking.
# Successor = smallest value greater than the node aka the next # after the node.
current_node = aNode
while(current_node.getLeftChild() != None):
current_node = current_node.getLeftChild()
return current_node
def traverse(self, order, top):
# traverse the tree by printing out the node data for all node in a specified order.
# Recall the different traversals: (also indicated next to the function calls below)
# preorder --> Root, Left, Right
# inorder --> Left, Root, Right
# postorder --> Left, Right, Root
if top != None:
if order == "preorder": # Root, L, R
print top.getData(), # Root
self.traverse("preorder", top.getLeftChild()) # Left
self.traverse("preorder", top.getRightChild()) # Right
elif order == "inorder": # Left, Root, Right
self.traverse("inorder", top.getLeftChild()) # Left
print top.getData(), # Root
self.traverse("inorder", top.getRightChild()) # Right
elif order == "postorder": # Left, Right, Root
self.traverse("postorder", top.getLeftChild()) # Left
self.traverse("postorder", top.getRightChild()) # Right
print top.getData(), # Root
else:
print("Error, order {} undefined".format(order)) # Error check for an undefined traversal
|
a6463e88bc46d95e9ff335f51bb7adec480dff98 | vishweshs4/digitalcrafts | /week1/tuesday/str-inter.py | 168 | 4.125 | 4 | first_name = raw_input("What is your first name? ")
last_name = raw_input("What is your last name? ")
print("Hello, My name is {0}, {1}").format(first_name,last_name)
|
ce7a0785f43dbba339f3215db275539eba03abf1 | pawanprjl/python-and-django-training | /Python Basics/palindrome(string).py | 245 | 4.25 | 4 | word = input("Enter a word: ")
def reverse(word):
temp = ''
for i in range(len(word)):
temp = temp+word[-1]
word = word[:-1]
return temp
if(reverse(word)==word):
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
|
912e363fb3de4e48726c7d7c28be17b8ba0fc751 | realpython/materials | /python-311/kalkulator.py | 729 | 3.5625 | 4 | import operator
import parse
OPERATIONS = {
"pluss": operator.add, # Addition
"minus": operator.sub, # Subtraction
"ganger": operator.mul, # Multiplication
"delt på": operator.truediv, # Division
}
EXPRESSION = parse.compile("{operand1:g} {operation} {operand2:g}")
def calculate(text):
if (ops := EXPRESSION.parse(text)) and ops["operation"] in OPERATIONS:
operation = OPERATIONS[ops["operation"]]
return operator.call(operation, ops["operand1"], ops["operand2"])
if __name__ == "__main__":
for calculation in [
"20 pluss 22",
"2022 minus 1991",
"45 ganger 45",
"11 delt på 3",
]:
print(f"{calculation} = {calculate(calculation)}")
|
7f1b011cc709cd6db1f47036e1300eb7407cd8fc | heiv82/test_one | /f_sort.py | 856 | 3.921875 | 4 | # Быстрая сортировка Хоара Python.
from random import randrange
def sort(array):
"""Sort the array by using quicksort."""
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
elif x == pivot:
equal.append(x)
elif x > pivot:
greater.append(x)
# Don't forget to return something!
return sort(less)+equal+sort(greater) # Just use the + operator to join lists
# Note that you want equal ^^^^^ not pivot
else: # You need to handle the part at the end of
return array
list = [randrange(1, 20) for i in range(10)]
print(' '.join([str(s) for s in list]))
list_last = sort(list)
print(' '.join([str(i) for i in list_last]))
|
481e175276d7add4a75e4b068eede8996fe7d649 | ivanlyon/exercises | /kattis/k_ladder.py | 606 | 4.25 | 4 | '''
Compute hypotenuse length given angle and opposite side length.
Status: Accepted
'''
import math
###############################################################################
def compute_length(length, angle):
'''Compute hypotenuse length'''
return math.ceil(length / math.sin(angle * math.pi / 180.0))
###############################################################################
if __name__ == '__main__':
length, angle = [int(i) for i in input().split()]
print(compute_length(length, angle))
###############################################################################
|
aa0755c5ee00871a395dd23a93f76ce5618ef633 | AlisonZXQ/leetcode | /Algorithms/203. Remove Linked List Elements/Solution.py | 662 | 3.59375 | 4 | #coding=utf-8
__author__ = 'xuxuan'
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
ans=head
while ans and ans.val==val:
ans=ans.next
if ans is not None:
node=ans
while node.next:
if node.next.val == val:
node.next=node.next.next
else:
node=node.next
return ans |
34419cbbbbcd1e10d1c6205f2f9ec62a234dfb7e | SeanUnland/Python | /Python Day 5/main.py | 1,869 | 4.28125 | 4 | # for loops
fruits = ["Apple", "Pear", "Peach"]
for fruit in fruits:
print(fruit)
print(fruit + " Pie")
# CODING EXERCISE
# 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
total_height = 0
for height in student_heights:
total_height += height
# print(total_height)
number_of_students = 0
for student in student_heights:
number_of_students += 1
# print(number_of_students)
average_height = round(total_height / number_of_students)
print(average_height)
# CODING EXERCISE
# 🚨 Don't change the code below 👇
student_scores = input("Input a list of student scores ").split()
for n in range(0, len(student_scores)):
student_scores[n] = int(student_scores[n])
print(student_scores)
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
# max() function returns highest value in array
print(max(student_scores))
# min() function returns lowest value in array
print(min(student_scores))
highest_score = 0
for score in student_scores:
if score > highest_score:
highest_score = score
print(f"The highest score in the class is {highest_score}")
# for loop with range() function
for number in range(1, 11, 3):
print(number)
total = 0
for number in range(1, 101):
total += number
print(total)
# CODING EXERCISE
total = 0
for number in range(2, 101, 2):
total += number
print(total)
# FIZZBUZZ CODING EXERCISE
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("fizz")
elif number % 5 == 0:
print("buzz")
else:
print(number) |
212820644ce6b6d82eb1d408927f4112a45149ef | antoinemouchet/MOOC | /Bio-info/reverseComplement.py | 721 | 3.578125 | 4 | import Getting_fre as gf
# Get list with each letter of file as an element
initial = gf.str_to_list(gf.get_text("./dataset_3_2.txt"))
#initial = gf.str_to_list("AAAACCCGGT")
complement = initial
# Reverse complement
complement.reverse()
# Loop on every element to replace it by its complement
for letter_id in range(len(complement)):
if complement[letter_id] == "A":
complement[letter_id] = "T"
elif complement[letter_id] == "T":
complement[letter_id] = "A"
elif complement[letter_id] == "G":
complement[letter_id] = "C"
elif complement[letter_id] == "C":
complement[letter_id] = "G"
# Make it a string
complement = "".join(complement)
print(complement) |
559ae05a3eb0b0c3bc15404c3bd5611590db61ea | RyanHankss/PRG_WhileBottles | /bottles1.py | 439 | 4.03125 | 4 | def beer_song(num_beers):
while num_beers > 0:
#convert to string
str_number = str(num_beers)
print(str_number + " bottles of beer on the wall")
print(str_number + " bottles of beer")
print("if one of those bottles should happen to fall")
#convert to string
num_beers -= 1
str_number = str(num_beers)
print(str_number + "bottles of beer on the wall")
beer_song(99)
|
025b0813599a0fd28cd4800eb63d4a2d62196b81 | lorenzokuo/Inheritance_Python-oop | /Inheritance_practice.py | 1,632 | 4.21875 | 4 | class Vehicle: #parent
#parent attributes
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
#parent methods
def drive(self,miles):
self.mileage += miles
return self
def reverse(self,miles):
self.mileage -= miles
return self
#child bike inherited parent vehicle
# create new attribute vehicle_type and return bike
class Bike(Vehicle):
def vehicle_type(self):
return "Bike"
class Car(Vehicle):
def set_wheels(self):
self.wheels = 4
return self
class Airplane(Vehicle):
def fly(self, miles):
self.mileage += miles
return self
# like product assignment, make v as "instance" of class vehicle
# v is instance of class
v = Vehicle(4,8,"dodge","minivan")
print(v.make)
# bike inherited parent class vehicle
# create its own attribute vehicle type
# need to print becuase no display methods existed
# print(subclass b invoke its own function vehicle type, return bike value, which is not exsited in parent class vehicle's attribute
b = Bike(2,1,"Schwinn","Paramount")
print(b.vehicle_type())
# c is subclass of class with 8 wheels
# the function set_wheel modify inherant attribute "wheel" from class
# c invoke its own func set_wheels, which is modified as 4
c = Car(8,5,"Toyota", "Matrix")
c.set_wheels()
print(c.wheels)
# a is sub class of class
# new methods fly(), which added new value on existing mileage
a = Airplane(22,853,"Airbus","A380")
a.fly(580)
print(a.mileage) |
6289ae5bc5c5c3fb72abb8798218ed77612ea7f7 | JardelBrandon/Algoritmos_e_Programacao | /Atividades/Roteiro 1 - O Shell do Python/Programas/Roteiro 1 Questão 5.py | 606 | 3.859375 | 4 | #5. Modifique o comando para “Olá, \n Mundo” na saída padrão.
print ( " Olá, \n Mundo")
# O \n realiza a quebra de linha na saída do programa
# A modificação no programa com o comando \n fez a descida de uma linha após ele
# O comando print é utilizado para imprimir algo na saída do interpretador (tela)
# O comando deve ser utilizado seguido de parêntesis que indica o ínicio e o fim do comando
# O comando deve ser utilizado com aspas caso se faça necessário o uso de uma string entre os parêntesis
# No caso dessa questão foi " Impresso na tela" o mensagem:
# >>>Olá,
# Mundo |
07736037dae72ca47d61f6447a27b9df3d768491 | jhonatheberson/sockets | /TCP/servidorTCP-C.py | 1,516 | 3.625 | 4 | # UNIVERSIDADE FEDERAL DO RIO GRANDE DO NORTE
# DEPARTAMENTO DE ENGENHARIA DE COMPUTACAO E AUTOMACAO
# DISCIPLINA REDES DE COMPUTADORES
# AUTOR: JHONAT HEBERSON AVELINO DE SOUZA
#
# SCRIPT: Servidor de sockets TCP modificado para enviar comandos do sistemas para o servidor
# importacao das bibliotecas
from socket import * # sockets
import os #comandos do systema
# definicao das variaveis
serverName = '' # ip do servidor (em branco)
serverPort = 60000 # porta a se conectar
serverSocket = socket(AF_INET,SOCK_STREAM) # criacao do socket TCP
serverSocket.bind((serverName,serverPort)) # bind do ip do servidor com a porta
serverSocket.listen(1) # socket pronto para 'ouvir' conexoes
print ('Servidor TCP esperando conexoes na porta %d ...' % (serverPort))
while 1:
connectionSocket, addr = serverSocket.accept() # aceita as conexoes dos clientes
sentence = connectionSocket.recv(1024) # recebe dados do cliente
sentence = sentence.decode('utf-8')
try:
os.system(sentence)
print ('Cliente %s enviou: %s, E executando o comando: %s' % (addr, sentence, sentence))
data = 'comando executado com sucesso'
connectionSocket.send(data.encode('utf-8')) # envia para o cliente o texto transformado
connectionSocket.close() # encerra o socket com o cliente
except:
print ('Cliente %s enviou: %s, comando não executado' % (addr, sentence))
error = 'Comando não aceito, por favor degite "ls"'
serverSocket.sendto(error.encode('utf-8'), addr)
serverSocket.close() # encerra o socket do servidor |
095ca0ac5d363c9fb2d003034524beffc6a74c85 | Gaurav2912/Code-With-Harry-Python-tutes- | /python files/tut115.py | 933 | 3.921875 | 4 | import random
def guess_num(initial,final,rand_num):
n_guess = 0
while True:
n_guess += 1
inp = int(input(f"Guess a number between {initial} and {final}: "))
if inp < rand_num:
print("Your number is small.")
elif inp > rand_num:
print("Your number is large.")
else:
print(f"Correct answer you guess {n_guess} times")
break
return n_guess
initial = int(input("Enter initial boundry number: "))
final = int(input("Enter final boundry: "))
rand_num1 = random.randint(initial, final)
rand_num2 = random.randint(initial, final)
# Player A
print("Player A")
gA = guess_num(initial,final,rand_num1)
# Player B
print("Player B")
gB = guess_num(initial,final,rand_num2)
if gA<gB:
print("Player A won the game.")
elif gA>gB:
print("Player B won the game.")
else:
print("Match draw.")
|
b7935f4b005215b5c152d46a3ca2af0dc2dfcb6d | 3xp1r3-Pr1nc3/agecc | /agecc.py | 512 | 4.03125 | 4 | print(" [~] Age Calculator [~] ")
print(" [~] BY [~]")
print(" [=] 3xp1r3 Pr1nc3 [=]")
print(" [=] Greetz: Crypt3d G1rL [=]")
import datetime
year=input("Your Birth Year: ")
month=input("Your Birth Month: ")
day=input("Your Birth Date: ")
time = datetime.datetime.now()
age=time.year-int(year)
age_one=time.month-int(month)
age_two=time.day-int(day)
print("Your age is now "+str(age)+" years "+str(age_one)+" months "+str(age_two)+" days")
|
f02d72536f8af817d574e17f40a85d5b44afd0d8 | chancebeyer1/CSC110 | /listfuncs.py | 256 | 3.765625 | 4 | # return the sum of a list of numbers L
def sum(L):
result = 0
for i in range(len(L)):
num = L[i]
result = result + num
return result
def sum(L):
result = 0
for x in L:
result = result + x
return result |
d385f5cc3aff4522506b05cf39f7ab89f9053587 | wudixiaoyu008/data-vis-pygame | /button.py | 1,808 | 3.5 | 4 | import pygame
BLACK = (0,0,0)
GRAY = (127, 127, 127)
RED = (255, 0, 0)
class Button:
def __init__(self, text1, text2, rect):
self.text1 = text1
self.text2 = text2
self.rect = rect
self.rect2 = pygame.Rect(
self.rect.x,
self.rect.y + self.rect.height,
self.rect.width,
self.rect.height
)
def draw(self, surface):
pygame.draw.rect(surface, RED, self.rect)
font = pygame.font.Font(None, 24)
label_view = font.render(self.text1, False, BLACK)
label_pos = label_view.get_rect()
label_pos.centery = self.rect.centery
label_pos.centerx = self.rect.centerx
surface.blit(label_view, label_pos)
pygame.draw.rect(surface, GRAY, self.rect2)
font = pygame.font.Font(None, 24)
label_view2 = font.render(self.text2, False, BLACK)
label_pos2 = label_view2.get_rect()
label_pos2.centery = self.rect2.centery
label_pos2.centerx = self.rect2.centerx
surface.blit(label_view2, label_pos2)
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
(x, y) = pygame.mouse.get_pos()
if x >= self.rect.x and \
x <= self.rect.x + self.rect.width and \
y >= self.rect.y and \
y <= self.rect.y + self.rect.height * 2:
self.on_click(event)
def on_click(self, event):
print("button clicked")
|
561a89ed409e45de982f075d1488f2fe33cd412a | javis-code/ericundfelix | /felix/archive/bla.py | 225 | 3.78125 | 4 | gefühl = input()
gut = ["gut", "schön"]
schlecht = ["schlecht", "scheisse"]
if gefühl.lower().strip() in gut:
print("Das freut mich")
elif gefühl.lower().strip() in schlecht:
print(":C")
else:
print("bruh") |
244af5abff711f8ee0c81307e3ecd5bcb22735b4 | yellankisanthan/Competitive-Programming | /Competitive-Programming/Week-1/Day-2/Rectangular_Love.py | 3,110 | 3.5625 | 4 | def find_rectangular_overlap(rect1, rect2):
left_x = max(rect1['left_x'], rect2['left_x'])
right_x = min(rect1['left_x'] + rect1['width'], rect2['left_x'] + rect2['width'])
width = right_x - left_x
lower_y = max(rect1['bottom_y'], rect2['bottom_y'])
upper_y = min(rect1['bottom_y'] + rect1['height'], rect2['bottom_y'] + rect2['height'])
height = upper_y - lower_y
if width < 1 or height < 1:
intersection = {'left_x': None, 'bottom_y': None, 'width': None, 'height': None}
else:
intersection = {'left_x': left_x, 'bottom_y': lower_y, 'width': width, 'height': height}
return intersection
# Tests
rect1 = {
'left_x': 1,
'bottom_y': 1,
'width': 6,
'height': 3,
}
rect2 = {
'left_x': 5,
'bottom_y': 2,
'width': 3,
'height': 6,
}
expected = {
'left_x': 5,
'bottom_y': 2,
'width': 2,
'height': 2,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 1,
'bottom_y': 1,
'width': 6,
'height': 6,
}
rect2 = {
'left_x': 3,
'bottom_y': 3,
'width': 2,
'height': 2,
}
expected = {
'left_x': 3,
'bottom_y': 3,
'width': 2,
'height': 2,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 2,
'bottom_y': 2,
'width': 4,
'height': 4,
}
rect2 = {
'left_x': 2,
'bottom_y': 2,
'width': 4,
'height': 4,
}
expected = {
'left_x': 2,
'bottom_y': 2,
'width': 4,
'height': 4,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 1,
'bottom_y': 2,
'width': 3,
'height': 4,
}
rect2 = {
'left_x': 2,
'bottom_y': 6,
'width': 2,
'height': 2,
}
expected = {
'left_x': None,
'bottom_y': None,
'width': None,
'height': None,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 1,
'bottom_y': 2,
'width': 3,
'height': 4,
}
rect2 = {
'left_x': 4,
'bottom_y': 3,
'width': 2,
'height': 2,
}
expected = {
'left_x': None,
'bottom_y': None,
'width': None,
'height': None,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 1,
'bottom_y': 1,
'width': 2,
'height': 2,
}
rect2 = {
'left_x': 3,
'bottom_y': 3,
'width': 2,
'height': 2,
}
expected = {
'left_x': None,
'bottom_y': None,
'width': None,
'height': None,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected)
rect1 = {
'left_x': 1,
'bottom_y': 1,
'width': 2,
'height': 2,
}
rect2 = {
'left_x': 4,
'bottom_y': 6,
'width': 3,
'height': 6,
}
expected = {
'left_x': None,
'bottom_y': None,
'width': None,
'height': None,
}
actual = find_rectangular_overlap(rect1, rect2)
print(actual == expected) |
8d76872e91a9b35d0fe2883f16ed9545bd06412a | kilicsedat/LeetCode-Solutions | /0000. Single-Row Keyboard.py | 1,129 | 3.953125 | 4 |
# coding: utf-8
# # single row keyboard
# There is a special keyboard with all keys in a single row.
#
# Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25),
# initially your finger is at index 0.
# To type a character, you have to move your finger to the index of the desired character.
# The time taken to move your finger from index i to index j is |i – j|.
#
# You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.
#
# Example 1:
#
# Input: keyboard = "abcdefghijklmnopqrstuvwxyz", word = "cba"
# Output: 4
# Explanation: The index moves from 0 to 2 to write 'c' then to 1 to write 'b' then to 0 again to write 'a'.
# Total time = 2 + 1 + 1 = 4.
# In[1]:
def singlerowkyeb(strng):
keyboard = "abcdefghijklmnopqrstuvwxyz"
c = 0
d = 0
for i in range (len(strng)):
if i == 0:
d = abs(keyboard.index(strng[i]))
else:
d = abs(keyboard.index(strng[i]) - keyboard.index(strng[i-1]))
c = c + d
return c
# In[5]:
print(singlerowkyeb('ffpo'))
|
81f897741722d72cfc777ce1bf21d0ff048978c4 | chaglare/learning_python | /environments/my_env/ex2_keyword-arguments.py | 293 | 3.578125 | 4 | #Ex1
def print_something(name, age):
print("My name is " + name + " and my age is " + str(age))
print_something("Caglar", 36)
print("Both of the functions work same")
#Ex2
def print_something(name, age):
print("My name is", name, "and my age is", age)
print_something("Caglar", 36) |
3c89eb71e04ecdca121f9bb9ea74e80d571b85cc | tomlovett/MIT-OCW-6.00 | /ProbSet11/self_originated.py | 6,934 | 3.5 | 4 | import string
## Nodes
class Node(object):
def __init__(self, name):
self.name = str(name)
def __str__(self):
return self.name
def __repr__(self):
return self.name
def __lt__(self, other):
if int(self.name) < int(other.name):
return True
else:
return False
def __eq__(self, other):
return self.name == other.name
def __ne__(self, other):
return not self.__eq__(other)
## Edge
class Edge(object):
def __init__(self, src, dest, total_weight, outside_weight):
self.src, self.dest = src, dest
self.total_weight, self.outside_weight = total_weight, outside_weight
def getSource(self):
return self.src
def getDestination(self):
return self.dest
def __str__(self):
return str(self.src) + '->' + str(self.dest)
## Path class
class Path(object):
def __init__(self, digraph, src, dest, nodes):
self.digraph, self.src, self.dest, self.nodes = digraph, src, dest, nodes
self.total_weight, self.outside_weight = 0, 0
self.calc_total()
self.calc_outside()
def calc_total(self):
self.total_weight = 0
for i in range(len(self.nodes) - 1):
self.total_weight += self.digraph.edge_weight[(self.nodes[i], self.nodes[i+1])]
def calc_outside(self):
self.outside_weight = 0
for i in range(len(self.nodes) - 1):
self.outside_weight += self.digraph.edge_outside_weight[(self.nodes[i], self.nodes[i+1])]
## Digraph
class Digraph(object):
def __init__(self, mapFileName):
self.nodes = set([])
self.edges = {}
self.edge_weight = {}
self.edge_outside_weight = {}
self.memo = {}
self.origin = None
self.goal = None
self.trial = []
self.maxOutside = 10000
self.maxTotal = 10000
self.load_map(mapFileName)
# Digraph initilization
def load_map(self, mapFileName):
text = open(mapFileName, 'r')
for line in text:
line = line.strip()
line = line.split()
self.read_line(line)
'sort nodes for each'
for node in self.edges:
self.edges[node].sort()
def read_line(self, line):
src, dest, total_weight, outside_weight = line[0], line[1], int(line[2]), int(line[3])
try:
self.addNode(src)
except:
pass
try:
self.addNode(dest)
except:
pass
edge = Edge(src, dest, total_weight, outside_weight)
self.addEdge(edge)
def addNode(self, node):
if node in self.nodes:
raise ValueError('Duplicate node')
else:
self.nodes.add(node)
self.edges[node] = []
def addEdge(self, edge):
src = edge.getSource()
dest = edge.getDestination()
if not(src in self.nodes and dest in self.nodes):
raise ValueError('Node not in graph')
self.edges[src].append(dest)
self.edge_weight[(src, dest)] = edge.total_weight
self.edge_outside_weight[(src, dest)] = edge.outside_weight
# Helper functions
def childrenOf(self, node):
return self.edges[node]
def hasNode(self, node):
return node in self.nodes
def parentsOf(self, child):
parents = []
for node in self.nodes:
if child in self.edges[node]:
parents.append(node)
parents.sort()
return parents
def total_weight(self, src, dest):
return self.total_weight[(src, dest)]
def outside_weight(self, src, dest):
return self.outside_weight[(src, dest)]
def total_path_weight(self, path):
total = 0
if len(path) < 2:
return total
for i in range(len(path) - 1):
total += self.total_weight(path[i], path[i+1])
return total
def outside_path_weight(self, path):
total = 0
if len(path) < 2:
return total
for i in range(len(path) - 1):
total += self.outside_weight(path[i], path[i+1])
return total
## Depth-first search
def fullDFS(self, origin, goal):
self.DFS(origin, origin, goal)
return self.memo[(origin, goal)]
def DFS(self, origin, current, goal):
if current == goal:
print 'goal achieved'
return
## if goal in self.childrenOf(current):
## if (origin, current) in self.memo:
## self.memo[(origin, goal)] = Path(self, origin, goal, self.memo[(origin, current)].nodes + [goal])
## else:
## self.memo
## return
for node in self.childrenOf(current):
if self.node_already_in_path(node, origin, current):
continue
print node
path_nodes = self.call_path_nodes(origin, current, node)
path = Path(self, origin, node, path_nodes)
self.memo_paths(path_nodes)
if (node, goal) in self.memo:
complete_nodes = path.nodes + self.memo([node,goal]).nodes
complete = Path(self, origin, goal, complete_nodes)
self.memo_paths(complete_nodes)
return
self.DFS(origin, node, goal)
print 'returning'
return
def call_path_nodes(self, origin, current, node):
if origin == current:
return [origin, node]
else:
return self.memo[(origin, current)].nodes + [node]
def node_already_in_path(self, node, origin, current):
if (origin, current) in self.memo:
if node in self.memo[(origin, current)].nodes:
return True
else:
return False
def memo_paths(self, nodes):
for x in nodes:
for y in nodes:
if x == y or nodes.index(y) < nodes.index(x):
continue
path = Path(self, x, y, nodes[nodes.index(x):(nodes.index(y) + 1)])
if (x,y) not in self.memo or path.total_weight < self.memo[(x,y)].total_weight:
self.memo[(x,y)] = path
# Depth-limited search
def call_depth_limited(self, path, goal, depth):
completed = []
for i in range(limit):
result = self.depth_limited(self, origin, limit, 0)
def depth_limited(self, path, goal, limit, depth):
if path[-1] == goal:
return path
elif limit == depth:
return 0
else:
children = self.childrenOf(path[-1])
# String function
def __str__(self):
res = ''
for k in self.edges:
for d in self.edges[k]:
res = res + str(k).ljust(2) + ' -> ' + str(d).rjust(2) + '\n'
return res[:-1]
## __main__
MIT = Digraph('mit_map.txt')
|
b21dc8689cf34eefa53774dc59b074f6c08bd1e5 | AditiGarg09/Python | /string_replace.py | 463 | 4.21875 | 4 | #Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
string=input("Enter String: ")
result=string[0]
flag=0
for i in range(1,len(string)):
for j in result:
if string[i]!=j:
flag=1
else:
flag=0
break
if flag is 1:
result+=string[i]
else:
result+='$'
print(result)
|
af4f70a5b0671d4c0fca4e893e33a8a4586ef5e9 | moqi112358/leetcode | /solutions/1374-leftmost-column-with-at-least-a-one/leftmost-column-with-at-least-a-one.py | 2,214 | 4.125 | 4 | # (This problem is an interactive problem.)
#
# A row-sorted binary matrix means that all elements are 0 or 1 and each row of the matrix is sorted in non-decreasing order.
#
# Given a row-sorted binary matrix binaryMatrix, return the index (0-indexed) of the leftmost column with a 1 in it. If such an index does not exist, return -1.
#
# You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
#
#
# BinaryMatrix.get(row, col) returns the element of the matrix at index (row, col) (0-indexed).
# BinaryMatrix.dimensions() returns the dimensions of the matrix as a list of 2 elements [rows, cols], which means the matrix is rows x cols.
#
#
# Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
#
# For custom testing purposes, the input will be the entire binary matrix mat. You will not have access to the binary matrix directly.
#
#
# Example 1:
#
#
#
#
# Input: mat = [[0,0],[1,1]]
# Output: 0
#
#
# Example 2:
#
#
#
#
# Input: mat = [[0,0],[0,1]]
# Output: 1
#
#
# Example 3:
#
#
#
#
# Input: mat = [[0,0],[0,0]]
# Output: -1
#
# Example 4:
#
#
#
#
# Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
# Output: 1
#
#
#
# Constraints:
#
#
# rows == mat.length
# cols == mat[i].length
# 1 <= rows, cols <= 100
# mat[i][j] is either 0 or 1.
# mat[i] is sorted in non-decreasing order.
#
#
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x: int, y: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
m, n = binaryMatrix.dimensions()
x, y = 0, n - 1
res = n
while x < m and y >= 0:
if binaryMatrix.get(x, y) == 1:
res = min(res, y)
y -= 1
continue
elif binaryMatrix.get(x, y) == 0:
x += 1
continue
if res == n:
return -1
else:
return res
|
2a4e6cdae9e6d0637b39c123e82edc150e904416 | BlancaLobato/ActividadesPython | /1.UMDC/UMDC 02/03.py | 1,101 | 4 | 4 | """
Ejercicio 03
Escribir una función que dados cuatro números, devuelva el mayor producto de
dos de ellos. Por ejemplo, si recibe los números 1, 5, -2, -4 debe devolver 8,
que es el producto más grande que se puede obtener entre ellos.
"""
def mayor_producto(n1, n2, n3, n4):
mayor = n1 * n2
n1n3 = n1 * n3
n1n4 = n1 * n4
n2n3 = n2 * n3
n2n4 = n2 * n4
n3n4 = n3 * n4
if n1n3 > mayor:
mayor = n1n3
if n1n4 > mayor:
mayor = n1n4
if n2n3 > mayor:
mayor = n2n3
if n2n4 > mayor:
mayor = n2n4
if n3n4 > mayor:
mayor = n3n4
return mayor
leyendo = True
while leyendo:
try:
num1 = int(input("Introduce número 1 : "))
num2 = int(input("Introduce número 2 : "))
num3 = int(input("Introduce número 3 : "))
num4 = int(input("Introduce número 4 : "))
leyendo = False
except ValueError:
print("Error en la introducción de datos\n")
print("El mayor producto entre ellos es: ",
mayor_producto(num1, num2, num3, num4)) |
ccc3c46b89b7841a39cda523c1ecc732539b123a | abhiramr/Everything_Python | /Random_Py_scripts/filter_files_dirs.py | 1,143 | 3.578125 | 4 | import os
import sys
import re
'''Different ways of searching for files'''
def get_files_list_dir(path):
list_files =[]
for i in os.listdir(path):
if os.path.isfile(os.path.join(path,i)) and 'cmd' in i:
list_files.append(i)
return list_files
list_files_=[]
def listdir(d):
if not os.path.isdir(d):
list_files_.append(d)
else:
for item in os.listdir(d):
listdir((d + '/' + item) if d != '/' else '/' + item)
def list_3(path,pattern):
#rx = re.compile(r'(cmd_).+\.(py)$')
r = []
rx = re.compile(pattern)
for path, dnames, fnames in os.walk(path):
r.extend([os.path.join(path, x) for x in fnames if rx.search(x)])
return r
def list_4(path,pattern):
# rx = re.compile(r'(cmd_).+\.(py)$')
rx = re.compile(pattern)
r = []
for fnames in os.listdir(path):
if rx.search(fnames):
r.append(os.path.join(path,fnames))
return r
def main():
#print(get_files_list_dir(sys.argv[1]))
#listdir(sys.argv[1])
#print(list_files_)
print(list_4(sys.argv[1],sys.argv[2]))
if __name__ == "__main__":
main()
|
5a6f0907d6fdf63ca70603f9c26a221788291adc | emilyruby/learning_algorithms_lol | /27.py | 883 | 4.09375 | 4 | # Given 2 trees, verify the second tree is a subtree of the other
def subtree(root, root2):
if not root2:
return True
if not root and root2:
return False
tree1 = []
tree2 = []
def traverse(root, values):
if root.left:
traverse(root.left)
values.append(root.value)
if root.right:
traverse(root.right)
if root:
traverse(root, tree1)
if root2:
traverse(root, tree2)
return tree1 == tree2
def subtree2(one, two):
def match(one, two):
if not (one and two):
return False
if one.value == two.value:
return subtree2(one.left, two.left) and subtree2(one.right, two.right)
if match(one, two):
return True
if not one:
return False
return subtree2(one.left, two) or subtree2(one.right, two)
|
2f5292f2dbc39b4947202e218d42fc8f6bf4e0fd | sebastian7159/FindSmallestNumber | /SmallestNumber.py | 366 | 4.125 | 4 | def find_smallest_int(arr1):
#return min(arr1) the min funcition finds the minimum value in a list
var2 = arr1[0]
for i in range(0, len(arr1)):
var1 = arr1[i]
if var2 <= var1:
res1 = var2
else:
var2 = var1
res1 = var2
return res1
print(find_smallest_int([78, 56, 232, 12, 11, 43]), 11) |
88a9b8f88cfed9a8c4757e9bb4b5b5c8696da4ca | SridharPy/MyPython | /SQL/tkSQL.py | 1,633 | 3.625 | 4 | import sqlite3
from tkinter import *
def view():
con = sqlite3.connect("lite.db")
cur = con.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
t1.delete(1.0,END)
t1.insert(END,rows)
con.close()
def delete():
con = sqlite3.connect("lite.db")
cur = con.cursor()
cur.execute("DELETE FROM store where item = ?",(e1_val.get(),))
con.commit()
con.close()
def insert():
con = sqlite3.connect("lite.db")
cur = con.cursor()
cur.execute("INSERT INTO Store VALUES (?,?,?)",(e2_val.get(),e3_val.get(),e4_val.get()))
con.commit()
con.close()
win = Tk()
b1 = Button(win,text ="Show Data",command= view)
b1.grid(row = 0, column = 0 )
t1 = Text(win,height = 2, width = 60)
t1.grid(row =0, column = 1)
l1 = Label(win,text= "Item Name")
l1.grid(row =3, column =0)
e1_val = StringVar()
e1 = Entry(win,textvariable= e1_val)
e1.grid(row = 3, column = 1)
b2 = Button(win,text="Delete Item", command= delete)
b2.grid(row=3,column = 2)
l4 = Label(win, text = "Insert Data in Table")
l4.grid(row = 4, column = 1)
l2 = Label(win, text = "Item")
l2.grid(row = 5, column = 0)
e2_val= StringVar()
e2 = Entry(win,textvariable = e2_val)
e2.grid(row = 5, column = 1)
l3 = Label(win, text = "Quantity")
l3.grid(row = 6, column = 0)
e3_val= StringVar()
e3 = Entry(win,textvariable = e3_val)
e3.grid(row = 6, column = 1)
l3 = Label(win, text = "Price")
l3.grid(row = 7, column = 0)
e4_val= StringVar()
e4 = Entry(win,textvariable = e4_val)
e4.grid(row = 7, column = 1)
b2 = Button(win,text = "Insert Data", command = insert)
b2.grid(row = 8 , column = 1)
win.mainloop()
|
9ce093babc81561588474ce806baa6221a49095a | alexbabkin/yalgorithms | /task3.py | 1,767 | 3.671875 | 4 |
def group_str(start, end, last):
result = f"{start}" if start == end else f"{start}-{end}"
if not last:
result += ", "
return result
def colapse1(lst):
result = ""
max_number = max(lst)
group_start, group_end = None, None
for i in range(max_number+1):
if i in lst:
if group_start is None:
group_start = i
else:
if group_start is not None:
group_end = i - 1
result += group_str(group_start, group_end, False)
group_start = None
if group_start:
result += group_str(group_start, max_number, True)
return result
def colapse2(lst):
result = ""
sorted_lst = sorted(lst)
group_start, group_end, prev_elem = None, None, None
for elem in sorted_lst:
if group_start is None:
group_start = elem
if prev_elem is not None:
if elem != prev_elem + 1:
group_end = prev_elem
result += group_str(group_start, group_end, False)
group_start = elem
prev_elem = elem
result += group_str(group_start, prev_elem, True)
return result
lst = [1, 4, 5, 2, 3, 9, 8, 11, 0]
print(f"1: {lst} -> {colapse1(lst)}")
lst = [1, 4, 5, 2, 3, 9, 11, 0]
print(f"1: {lst} -> {colapse1(lst)}")
lst = [1, 4, 3, 2]
print(f"1: {lst} -> {colapse1(lst)}")
lst = [1, 4]
print(f"1: {lst} -> {colapse1(lst)}")
lst = [1, 4, 5, 2, 3, 9, 8, 11, 0]
print(f"2: {lst} -> {colapse2(lst)}")
lst = [1, 4, 5, 2, 3, 9, 11, 0]
print(f"2: {lst} -> {colapse2(lst)}")
lst = [1, 4, 3, 2]
print(f"2: {lst} -> {colapse2(lst)}")
lst = [1, 4]
print(f"2: {lst} -> {colapse2(lst)}")
|
de49ffad1117b0806209ec9490c8a511c169d3de | jacosta18/Project_01 | /Python_JSON/JSON.py | 1,258 | 3.859375 | 4 | #JSON Javascript Object Notation
# Person = {
# name : "markson",
# age : age,
# speak : function(){
# console.log("my name is "+ name)
# }
# }
# TYPES of data inside a JSON file
# JSON is a key value system or a large dictionary as we knoe it in python
# - "key" : "value"
# - a string
# - a number
# - a key or an object (Json object)
# - an array
# - a boolean
# - null
# {
# "Trainer1 = {
# "name" : "markson",
# "age" : 25,
# "job" : "mechanic"
# },
# "Trainer2"
# "name" : "markson",
# "age" : 25,
# "job" : "mechanic"
# }
import json
car_data = {"name" : "tesla", "engine" : "electric"}
# We need two methods ins JSON:
# 1. json.dumps()
# 2. json.dump()
car_data_jason_string = json.dumps(car_data)
print(car_data_jason_string)
print(car_data)
json_file = open("json_out_alternative.json","w")
car_data_jason_string = json.dump(car_data,json_file)
# This is an alternative to the statement above
with open("json_out_alternative.json", "w")as json_file2:
json.dump(car_data, json_file2)
with open('json_out_alternative.json') as open_json_file:
electric_car = json.load(open_json_file)
print(type(electric_car))
print(electric_car['name'])
print(electric_car['engine'])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.