blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d5297e6171ea9e92e6ba880a5b14f3d3c171bc90
shanroy1999/Miscellaneous
/Currency-Converter.py
959
3.640625
4
with open(r"C:\Users\Lenovo\Desktop\New folder\python\Small Projects\Currency.txt") as f: lines = f.readlines() print(lines) curr_dict = {} for line in lines: split = line.split("\t") curr_dict[split[0]] = split[1] print(curr_dict) amount = int(input("Enter the amount: ")) print("Enter Conversion Currency: \nAvailable Options:\n") [print(item) for item in curr_dict.keys()] currency = input("Enter one of these values:") print(f"{amount} INR is equal to {amount * float(curr_dict[currency])} {currency}") from forex_python.converter import CurrencyRates, CurrencyCodes c = CurrencyRates() print(c.get_rate('INR','USD')) print(c.convert("INR","USD",500)) print(c.get_rate('USD','INR')) print(c.convert("USD","INR",500)) curr = CurrencyCodes() print(curr.get_symbol("INR")) print(curr.get_currency_name("INR")) from forex_python.bitcoin import BtcConverter bt = BtcConverter() print(bt.get_latest_price("INR"))
ced9e02afe5595046dd60e1a6f085d07a7206b40
bsdworkin/Regression
/SimpleLinearRegression/slr.py
1,104
4.03125
4
#Simple Linear Regression import numpy as np import matplotlib.pyplot as plt import pandas as pd dataSet = pd.read_csv('Salary_Data.csv') #The colon means we take all the lines X = dataSet.iloc[:,:-1].values y = dataSet.iloc[:, 1].values #Splitting to test and training set from sklearn.cross_validation import train_test_split xTrain, xTest, yTrain, yTest = train_test_split(X, y, test_size = 1/3, random_state=0) #fitting SLR to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(xTrain, yTrain) #Prediciton yPred = regressor.predict(xTest) #Graphing the data results plt.scatter(xTrain, yTrain, color = 'red') plt.plot(xTrain, yTrain, regressor.predict(xTrain), color='blue') plt.title('Salary vs Experience(Training Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() #Switching the results plt.scatter(xTest, yTest, color = 'red') plt.plot(xTrain, yTrain, regressor.predict(xTrain), color='blue') plt.title('Salary vs Experience(Training Set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
538da5198b5fcf1f6ef17569fb5b8f0e869216ae
MrZebarth/PythonCheatSheet2019
/Loops.py
782
4.375
4
# Loops # Repeat code using a condition (while loop) password = "" while password != "Irish": password = input("Enter your password: ") # any of the conditions in the "conditionals.py" file will work here # Repeat code over a range (for loop) # We can repeat starting at 0, stopping before a value range(5) # We can repeat starting at a value, stopping before a separate value range(3,8) # We can repeat starting at a value, stopping before a separate value, increasing by a set amount range(2,20,3) total = 0 for counter in range(3, 8): total = total + counter print(total) # Repeat over the parts of a collection, example, the letters in a string counter = 1 for letter in password: print("letter #", counter, letter) counter += 1
8118ded6c60484d14b114646b736c8ff145c9fe4
OpenMined/PyStatDP
/pystatdp/utils.py
1,771
3.578125
4
from collections import deque from logging import getLogger, basicConfig, INFO logger = getLogger(__name__) basicConfig(level=INFO) def arr_n_check(privacy, test_range, n_checks): """ returns the test_privacy tuple seek for it to be symmetrical, therefore, equal number of observations on either side of the original privacy budget. As a result n_checks should always be an odd number. test_range: it is the absolute difference between consecutive test privacy budget being returned """ if privacy < 0: p_old = privacy privacy = -privacy logger.info(f"value provided for privacy(={p_old}) argument is negative; \ using instead privacy={privacy}") if n_checks < 0: check_old = n_checks n_checks = -1*n_checks logger.info(f"value provided for n_checks(={check_old}) argument is negative; \ using instead n_checks={n_checks}") if n_checks % 2 == 0: check_old = n_checks n_checks = n_checks-1 if n_checks > 2 else 3 logger.info(f"value provided for n_checks(={check_old}) argument is even or \ smaller than 3; using instead n_checks={n_checks}") return_tuple = deque([privacy]) for i in range(1, n_checks//2 + 1): l = privacy - (i*test_range) if l < 0: logger.info(f"value for test privacy reached below 0 on {i-1}th iteration\ terminating further population of the tuple") break r = privacy + (i*test_range) return_tuple.appendleft(l) return_tuple.append(r) return_tuple = tuple(return_tuple) logger.info(f"final test_privacy tuple at PyStatDP/pystatdp/utils.py; \ arr_n_check() = str{return_tuple}") return return_tuple
88fff08f162268e757a765355cc03b6a9509f02c
felipmarqs/exerciciospythonbrasil
/exercicios/EstruturaSequencial/peso_ideal_homem_mulher.py
359
3.875
4
#Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas: h = float(input("Qual sua altura ?")) s = str(input("Você é homem ou mulher ? [H/M]?")).lower() if s == 'h': pi=(72.7 * h) - 58 elif s == 'm': pi = (62.1*h) - 44.7 print(f"Seu peso ideal é {pi:.2f}.")
beb6441f70f9081ae7c02e2fc48de69477f4c489
Mirkics/probazarovizsga2
/testproject/guess_the_number.py
2,706
3.578125
4
'''3 Feladat: Guess the number automatizálása Készíts egy Python python applikációt (egy darab python file) ami selenium-ot használ. A program töltse be a Guess the number app-ot az https://witty-hill-0acfceb03.azurestaticapps.net/guess_the_number.html oldalról. Feladatod, hogy automatizáld selenium webdriverrel az app funkcionalitását tesztelését. Nem jár plusz pont azért ha úgy automatizálsz, hogy minnél optimálisabban és gyosabban találja ki a helyes számot a program Egy tesztet kell írnod ami addig találgat a megadott intervallumon belül amíg ki nem találja a helyes számot. Amikor megvan a helyes szám, ellenőrizd le, hogy a szükséges lépések száma mit az aplikáció kijelez egyezik-e a saját belső számlálóddal. Teszteld le, hogy az applikáció helyesen kezeli az intervallumon kívüli találgatásokat. Az applikéció -19 vagy 255 értéknél nem szabad, hogy összeomoljon. Azt kell kiírnia, hogy alá vagy fölé találtál-e.''' import random from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager import time options = Options() options.headless = False driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) try: # Oldal betöltése driver.get('https://witty-hill-0acfceb03.azurestaticapps.net/guess_the_number.html') time.sleep(2) # number = () # guess = random.randint(1, 100) # random számot beírni input_number = driver.find_element_by_xpath("/html/body/div/div[2]/input") # input_number.send_keys(guess) # # time.sleep(2) guess_button = driver.find_element_by_xpath('/html/body/div/div[2]/span/button') # guess_button.click() # time.sleep(2) input_number.clear() # for i in input_number: # if guess == number: # print("Yes! That is it.") # if guess > number: # print("Guess lower") # else: # print("Guess higher") # # szamolok = 0 # for i in range(1, 100): # szamolok += 1 # határéertéken kívüli érték tesztelése # testdata = -19 message: Guess higher.", 255 message: "Guess lower."} input_number.send_keys('-19') guess_button.click() answer_higher = driver.find_element_by_xpath('//p[@class="alert alert-warning"]').text print(answer_higher) assert answer_higher == "Guess higher." time.sleep(1) input_number.clear() input_number.send_keys("255") guess_button.click() answer_lower = driver.find_element_by_xpath('/html/body/div/p[3]').text print(answer_lower) assert answer_lower == "Guess lower." finally: driver.close()
39d1a6f82194e1e2702c7a1e2f37d5a5d1ce5991
oirk/school
/progam 4 m.py
2,370
4.03125
4
import math def deflatlong(lat1,long1,lat2,long2): deltaLong = math.radians(long2) - math.radians(long1) deltaLat = math.radians(lat2) - math.radians(lat1) a = (math.sin((deltaLat/2))**2) + (math.cos(math.radians(lat1))) * (math.cos(math.radians(lat2))) * (math.sin((deltaLong/2))**2) c = 2 * math.atan2( math.sqrt(a), math.sqrt(1-a)) d = 3961 * c #3961 is the radius of the earth in miles. return d start = True while start == True : try: stop_block = 0 if stop_block == 0 : lat_long_1=((input('what is your frist lat? ')),(input('what is your frist long? '))) radius = float(input('what is the radius you want to use?')) if float(lat_long_1[0])< -90 or float(lat_long_1[0])>90: print('enter a number between -90 and 90 for your lat.') if float(lat_long_1[1])< -180 or float(lat_long_1[1])>180: print('enter a number between -180 and 180 for your long.') stop_block = 1 if stop_block == 1: Start = False except ValueError: print('please enter a number') except TypeError: print('type error') continue while True: try: stop_block = 0 if stop_block == 0 : source_file = open(input('what is the source file do you want to use?' ) + '.txt') stop_block = 1 except FileNotFoundError: stop_block = 0 print('Please enter a vaild file name.') if stop_block == 1: False write_file = open((input('what file do you want to write to?' ) + '.txt'),'w',encoding = 'utf-8') lat_long_2 = [] check_loop = True source_file.readline() while check_loop == True: try: for line in source_file: lat_long_2 = [] lat_long_2.append(line[135:149]) lat_long_2.append(line[150:165]) defra = deflatlong(float(lat_long_1[0]),float(lat_long_1[1]),float(lat_long_2[0]),float(lat_long_2[1])) if defra <= radius: write_file.write(line) except ValueError: continue check_loop = False source_file.close() write_file.close()
af6e378801755d6b72d20be32dc516cf3867e95b
garciacello/Python-Exercises
/módulos.py
443
4
4
#FUNCOES DA BIBLIOTECA MATH # ceil = > arredonda pra cima # floor => arredonda pra baixo # trunc => tira as casas decimais em excesso # pow => potencia # sqrt = >raiz quadrada # factorial => fatorial #import math => Importa toda a biblioteca # from math import sqrt => importo apenas uma funcao from math import sqrt,floor num= int(input('Digite um numero: ')) raiz = sqrt(num) print('A raiz de {} é igual a {:.2f}'.format(num, floor(raiz)))
5824918ea189497767632c3b4e489153300202f8
hemantghuge/HackerRank
/Algorithms/Implementation/12 - Counting Valleys.py
651
3.578125
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): list_s = list(s) count = 0 count_prev = 0 valley = 0 for l in list_s: if l == 'D': count -=1 elif l == 'U': count +=1 if count_prev < 0 and count == 0: valley +=1 count_prev = count return valley if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() result = countingValleys(n, s) fptr.write(str(result) + '\n') fptr.close()
20e1f6800469b28764157ff50c4dbfa974df4dba
deepcpatel/data_structures_and_algorithms
/Graph/satisfiability_of_equality_equations.py
1,354
4.03125
4
# Link: https://leetcode.com/problems/satisfiability-of-equality-equations/ # Approach: Union Find. Firts iterate all the equations having '==' operation. Union both the LHS and RHS symbol to connect to a common parent. Now, iterate through all the equations having '!=' # operator. For each LHS and RHS, find their paeremts using find() function. If both the parents are same then return False. Because '!=' signifies that LHS and RHS should not be connected and here # they are. Return True at end if all things go well. class Solution(object): def find(self, x): if self.char_par[x] != x: self.char_par[x] = self.find(self.char_par[x]) return self.char_par[x] def union(self, a, b): par_a = self.find(a) par_b = self.find(b) self.char_par[par_a] = par_b def equationsPossible(self, equations): a_num = ord('a') self.char_par = {chr(i+a_num):chr(i+a_num) for i in range(26)} for e in equations: if e[1] == '=': self.union(e[0], e[-1]) for e in equations: if e[1] == '!': a_par, b_par = self.find(e[0]), self.find(e[-1]) if a_par == b_par: return False return True
9aacd55956076d1a3151c66a40d17e31243d3a47
nivipandey/python
/exception_handling/e4.py
118
3.65625
4
a=5 b=0 print("exception demo") try: c=a/b print(c) except: print("zero division error") finally: d=a+b print(d)
af39852d0bd6afc2dd61eda2215c4b8e8ccff7fb
habibabdo/firstpython
/Functions.py
489
3.6875
4
def person(name,age=12): print(name) print(age) def mathimatics(x,y): a=x+y b=x-y c=x*y d=x/y return a,b,c,d def sum(*b): c=0 for i in b: c = c + i print(c) def person1(name, **data): print(name) for i,j in data.items(): print(i,j) resul1,result2,result3,result4=mathimatics(10,2) print(resul1,result2,result3,result4) person('Habib',57) sum(5,6,7,8,9) person1('Habib',age='57',city='Tarshiha',mobile='0504257430')
720be6194cf012100c54e20866955656db8d4db0
Lekuro/python_core
/CodeWars5/3_name_start_R_r.py
669
4.3125
4
# Create a function which answers the question "Are you playing banjo?". # If your name starts with the letter "R" or lower case "r", you are playing banjo! # The function takes a name as its only argument, and returns one of the following strings: # name + " plays banjo" # name + " does not play banjo" # Names given are always valid strings. def areYouPlayingBanjo(name): """ function checks to start the name from 'R' or 'r' param name - string return - name and something strange """ if name[:1] == 'R' or name[:1] == 'r': return name + " plays banjo" return name + " does not play banjo" print(areYouPlayingBanjo('Rgb'))
25627f2bf4831a58400d43ce8f94623864edc154
Zahidsqldba07/codingbat-programming-problems-python
/Solutions/list-2/centered_average.py
809
4.21875
4
# Return the "centered" average of an array of ints, which we'll # say is the mean average of the values, except ignoring the largest # and smallest values in the array. If there are multiple copies of # the smallest value, ignore just one copy, and likewise for the # largest value. Use int division to produce the final average. # You may assume that the array is length 3 or more. # centered_average([1, 2, 3, 4, 100]) → 3 # centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 # centered_average([-10, -4, -2, -4, -2, 0]) → -3 def centered_average(nums): largest = nums[0] smallest = nums[0] sum = 0 for i in range(len(nums)): largest = max(largest, nums[i]) smallest = min(smallest, nums[i]) sum += nums[i] return (sum - largest - smallest) / (len(nums) - 2)
41e624c7f005c15f6bcbb0ff0bb5108d6ca1b8cf
mjkushman/automate-stuff
/mapIt.py
563
3.640625
4
#! python3 #mapIt.py - Launches a map in the browser using an address from the # command line or clipboard. import webbrowser, sys, pyperclip if len(sys.argv) > 1: # Get address from command line. address = ' '.join(sys.argv[1:]) else: #Get address from clipboard address = pyperclip.paste() webbrowser.open('https://google.com/maps/place/' + address) ''' print('first arg (index 0): ' + sys.argv[0]) print('second arg (index 1): ' + sys.argv[1]) print('third arg (index 2): ' + sys.argv[2]) print('fourth arg (index 3): ' + sys.argv[3]) '''
1a1fe52a2c7b3b6c2790a09fff00a1906328e214
makrandp/python-practice
/Other/Companies/Amazon/AmazonBlind/SubtreeWithMaximumAverage.py
2,740
4
4
''' Given a tree, find the subtree with the maximum average. Return the root of the subtree. A subtree of a tree is any node of that tree plus all its descendants. The average value of a subtree is the sum of its values, divided by the number of nodes. Examples Example 1: Input: Output: 13 Example 2: Input: Output: 21 Explanation: For the node with value = 1 we have an average of (- 5 + 21 + 5 - 1) / 5 = 4. For the node with value = -5 we have an average of (-5 / 1) = -5. For the node with value = 21 we have an average of (21 / 1) = 21. For the node with value = 5 we have an average of (5 / 1) = 5. For the node with value = -1 we have an average of (-1 / 1) = -1. So the subtree of 21 is the maximum. ''' from typing import List class TreeNode(): def __init__(self, val: int=None, children: List['TreeNode']=list()): self.val = val self.children = children class Solution(): def subtreeWithMaximumAverage(self, root: TreeNode) -> TreeNode: # We're going to use the recursive approach; O(n) time, O(n) space because of recursive stack. # Could be simplified by taking an interative approach, removing recursive stack problems. self.maximalValue, self.maximalNode = float('-inf'), None self.recurse(root) return self.maximalNode def recurse(self, root: TreeNode) -> tuple: # Handling base-case curMaxValue, curNodeCount = float('-inf'), 0 if len(root.children) <= 0: curMaxValue, curNodeCount = root.val, 1 else: # Getting the values of all children subtrees subtreeTotal, subtreeCount = 0, 0 for child in root.children: childValue = self.recurse(child) subtreeTotal += childValue[0] subtreeCount += childValue[1] subtreeTotal += root.val subtreeCount += 1 curMaxValue = subtreeTotal / subtreeCount curNodeCount = subtreeCount if curMaxValue > self.maximalValue: self.maximalValue = curMaxValue self.maximalNode = root return (curMaxValue, curNodeCount) ''' Construcing our test case ''' root = TreeNode(1) leftNode = TreeNode(-5) leftLeftNode = TreeNode(1) leftRightNode = TreeNode(2) leftNode.children = [leftLeftNode, leftRightNode] centerNode = TreeNode(13) centerLeft = TreeNode(4) centerRight = TreeNode(-2) centerNode.children = [centerLeft, centerRight] root.children = [leftNode, centerNode, TreeNode(4)] rootTwo = TreeNode(1) rootTwo.children = [TreeNode(-5), TreeNode(21), TreeNode(5), TreeNode(-1)] s = Solution() print(s.subtreeWithMaximumAverage(root).val) print(s.subtreeWithMaximumAverage(rootTwo).val)
a2bb75a06fc80ba6b2ab34dc5e6554618876624d
rehmanalira/Python-Programming
/28 JOin Func.py
349
4.40625
4
""" JOIn function: it is used for example if we have list and we write all names and then we want to add a word in it so we simply can add this by writing "word".join(list) """ list=["Rehman","ALi","Ehsan","Rizwan","Tayyab","jutt"] #for item in list: # print(item,end=" ") by this we get the names l=" Love , ".join(list) print(l)
b0ddb26ae094f4ba0631c14306c66c35ecbc7946
Ajit171098/python-lab
/3(a).py
179
3.9375
4
n=int(input("Enter the number:")) list1=[] for i in range(1,n+1): if n%i==0: list1.append(i) print("the possiblr divisors of {} are {}".format(n,list1))
36fd599cedf0d524a1f205deedcff9627d476397
SnoopySYF/leetcode
/leetcode_814.py
1,018
3.875
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if(not root): return None self.check(root) return root def check(self, node): if(not node.left and not node.right): if(node.val == 0): return False return True if(node.left): if(not self.check(node.left)): node.left = None if(node.right): if(not self.check(node.right)): node.right = None if(not node.left and not node.right): if(node.val == 0): return False return True s = Solution() root = TreeNode(1) node1 = TreeNode(0) node2 = TreeNode(0) node3 = TreeNode(1) root.right = node1 node1.left = node2 node1.right = node3 print(s.pruneTree(root))
300731285be9017a267e816ab156b6840104daa9
AT538/Python-Programs
/9.py
819
3.859375
4
m=[[1,2],[3,4]] n=[[5,6],[7,8]] def add(m,n): print("Sum is") for i in range(len(m)): print() for j in range(len(m[0])): print(m[i][j]+n[i][j],end=" ") def sub(m,n): print("\n Difference is") for i in range(len(m)): print() for j in range(len(m[0])): print(m[i][j]-n[i][j],end=" ") def mul(m,n): print();print() print("Product is") result=[[0,0],[0,0]] for i in range(len(m)): for j in range(len(n[0])): for k in range(len(n)): result[i][j]+=m[i][k]*n[k][j] for i in range(len(result)): print() for j in range(len(result[0])): print(result[i][j],end=" ") add(m,n) sub(m,n) mul(m,n)
52e6da5338713a17e2b57c00e85f1677cccfa3d5
MeatballNissan/py
/untitled/day06/dog.py
1,262
3.625
4
__author__ = "bxd" class Dog: def __init__(self, name): self.name = name def bulk(self): print(" %s :wang wang wang" % self.name) d1 = Dog("bxd1") d2 = Dog("bxd2") d3 = Dog("bxd3") d1.bulk() d2.bulk() d3.bulk() roles = { 1:{},2:{} } class Role(): n = 123 # 类变量 def __init__(self,name,role,gun,n): #构造函数 self.name = name self.gun = gun; self.role = role self.n = n def buy_gun(self,gun_name): print("%s just bought %s" %(self.name,gun_name)) self.gun_name = gun_name; self.gun = gun_name self.__value = gun_name #私有属性 def __show_value(self): #私有方法 print(self.__value) def __del__(self): print("自动销毁了") r1 = Role("bxd", "terrorist", "c43","321") print(r1.gun) print(r1.name,r1.role) r1.buy_gun("ak47") print(r1.gun_name, r1.gun ) print(r1) print(r1.n) print(Role.n) r1.n = 3214 # 改类变量只能通过 类名.n = 1234 的方式调用 print(Role.n) del r1 print(111) #r1 = Role("bxd", "terrorist", "c43") # 初始化过程 Role(r1,"bxd", "terrorist", "c43") r1即self, 所以初始化为将r1 传入构造函数,然后给r1这个内存地址中的变量赋值
5e7ebd0f7e608de5bfaea14e3d3ecf103cc0b640
Niranjana55/Array-Programs
/2prg.py
281
4.09375
4
#2.Given an unsorted integer array A and an integer value X, # find if A contains the value X. def unsorted(A,x): for i in A: if i==x: return True else: return False A=[2,3,5,7,8,9] x=int(input("enter the num:")) print (unsorted(A,x))
683f57699579618a048cdd4f6e4e948811d6a125
Vicuko/100DaysOfCode
/Day20-21/SnakeGame/snake.py
1,893
4.09375
4
import turtle as t class Snake: def __init__(self, initial_size = 3, body_size = 20, body_shape = "square", color = "white"): self.body = [] self.init_size = initial_size self.body_size = body_size self.body_shape = body_shape self.snake_color = color self.create_snake() self.head = self.body[0] self.last_direction = self.head.heading() def create_snake(self): for position in range(self.init_size): position_x = -position * self.body_size self.add_segment(position_x) def add_segment(self, position_x, position_y=0): body_part = t.Turtle(self.body_shape) body_part.color(self.snake_color) body_part.penup() body_part.setpos(x = position_x, y = position_y) self.body.append(body_part) def extend(self): tail_pos = self.body[-1].position() self.add_segment(tail_pos[0], tail_pos[1]) def move(self): for i in range(len(self.body) - 1, 0, -1): this_body_part = self.body[i] next_body_part = self.body[i - 1] next_position = next_body_part.position() this_body_part.goto(next_position) self.head.forward(self.body_size) self.last_direction = self.head.heading() def move_up(self): self.change_direction(90) def move_down(self): self.change_direction(270) def move_right(self): self.change_direction(0) def move_left(self): self.change_direction(180) def change_direction(self, new_direction): # We make sure the snake doesn't go backwards: if abs(self.last_direction - new_direction) != 180: self.head.setheading(new_direction) def restart(self): for part in self.body: part.hideturtle() self.body=[] self.create_snake()
76b271670264e42e982f9daa12dc04b4d366daa9
sammienjihia/dataStractures
/Strings/stringPermutation.py
1,258
3.921875
4
class Permutation: def __init__(self): self.mySet = set() def swap(self, myString, left, index): # NB: String are imutable, meaning you'll have to change it to an array, perform the swap then change it back to a string stringAsList = list(myString) # swap the characters in the given indices stringAsList[left], stringAsList[index] = stringAsList[index], stringAsList[left] # reconvert list to string return ''.join(str(e) for e in stringAsList) def calculate(self, someString, left, right): # base case if left == right: # this means the permutation of a single character shall always be 1 print(self.mySet) return else: for i in range(len(someString)): # call swap method newString = self.swap(someString, left, i) # add string to set if newString not in self.mySet: self.mySet.add(newString) # recursively perform the calculate function with the new permutation self.calculate(newString, left+1, right) if __name__ == "__main__": x = Permutation() x.calculate("ABCD", 0, len("ABCD")-1)
13692915a1c5f25407a17b0dcfc958772f6cdacc
OksanichenkoFedor/Order-of-the-flame
/LevelParts/Map.py
6,036
3.984375
4
from math import sqrt class Map: """ Class of level Map :field x: First coordinate of left up corner of map :field y: Second coordinate of left up corner of map :field width: Width of picture of map :field height: Height of picture of map :field number_of_left_roads: Number of left roads :field Left_Roads: Massive of left roads, each road has number of tuple, which contains coordinates of nodes of road :field number_of_right_roads: Number of right roads :field Right_Roads: Massive of right roads, each road has number of tuple, which contains coordinates of nodes of road :field Pole_Points: Massive of point of battle pole :field self.total_length_L: Massive of full length of each left road :field self.total_length_R: Massive of full length of each right road :field self.total_coords_L: Massive of coordinate of each node on its road. For left roads First argument - number of road Second argument - number of node :field self.total_coords_R: Massive of coordinate of each node on its road. For right roads First argument - number of road Second argument - number of node :field bush: Picture of bush "field tree: Picture of tree :method __init__: Initialise level map. Receives file_name, x, y, w, h """ # TODO Создать класс, который будет по файлу строить карту, а так же её рисовать def __init__(self, file_name, x, y, w, h, bush, tree, bushes, trees): """ :param file_name: Name of the file where we will get information about the map :param x: First coordinate of left up corner of map :param y: Second coordinate of left up corner of map :param w: Width of picture of map :param h: Height of picture of map """ self.x = x self.y = y self.width = w self.height = h self.bush = bush self.tree = tree self.trees = trees self.bushes = bushes file_obj = open(file_name, "r") self.number_of_left_roads = int(file_obj.readline()) self.number_of_right_roads = int(file_obj.readline()) self.Left_Roads = [] self.Right_Roads = [] self.Pole_Points = [] for i in range(self.number_of_left_roads): self.Left_Roads.append([]) points_number = int(file_obj.readline()) for j in range(points_number): self.Left_Roads[i].append((int(file_obj.readline()) + int(x), int(file_obj.readline()) + int(y))) for i in range(self.number_of_right_roads): self.Right_Roads.append([]) points_number = int(file_obj.readline()) for j in range(points_number): self.Right_Roads[i].append((int(file_obj.readline()) + int(x), int(file_obj.readline()) + int(y))) self.polygon_points_number = int(file_obj.readline()) for i in range(self.polygon_points_number): self.Pole_Points.append((int(file_obj.readline()) + int(x), int(file_obj.readline()) + int(y))) self.total_length_L = [] self.total_length_R = [] self.total_coords_L = [] self.total_coords_R = [] for i in range(len(self.Left_Roads)): self.total_length_L.append(0) self.total_coords_L.append([]) self.total_coords_L[i].append(0) for j in range(1, len(self.Left_Roads[i]), 1): r = sqrt((self.Left_Roads[i][j][0] - self.Left_Roads[i][j - 1][0]) ** 2 + ( self.Left_Roads[i][j][1] - self.Left_Roads[i][j - 1][1]) ** 2) self.total_length_L[i] += r self.total_coords_L[i].append(self.total_length_L[i]) for j in range(len(self.Left_Roads[i])): self.total_coords_L[i][j] = (1.0 * self.total_coords_L[i][j]) / (1.0 * self.total_length_L[i]) for i in range(len(self.Right_Roads)): self.total_length_R.append(0) self.total_coords_R.append([]) self.total_coords_R[i].append(0) for j in range(1, len(self.Right_Roads[i]), 1): r = sqrt((self.Right_Roads[i][j][0] - self.Right_Roads[i][j - 1][0]) ** 2 + ( self.Right_Roads[i][j][1] - self.Right_Roads[i][j - 1][1]) ** 2) self.total_length_R[i] += r self.total_coords_R[i].append(self.total_length_R[i]) for j in range(len(self.Right_Roads[i])): self.total_coords_R[i][j] = (1.0 * self.total_coords_R[i][j]) / (1.0 * self.total_length_R[i]) def nearest_road(self, x, y, side_param): #Получает на вход координаты x,y и сторона города, из которого вышел юнит nearest_road_num = 0 if side_param == "right": distance = ((x-self.Left_Roads[0][-1][0])**2 + (y-self.Left_Roads[0][-1][1])**2)**0.5 for i in range(len(self.Left_Roads)): d = ((x-self.Left_Roads[i][-1][0])**2 + (y-self.Left_Roads[i][-1][1])**2)**0.5 if d < distance: nearest_road_num = i distance = d elif side_param == "left": distance = ((x - self.Right_Roads[0][-1][0]) ** 2 + (y - self.Right_Roads[0][-1][1]) ** 2) ** 0.5 for i in range(len(self.Right_Roads)): d = ((x - self.Right_Roads[i][-1][0]) ** 2 + (y - self.Right_Roads[i][-1][1]) ** 2) ** 0.5 if d < distance: nearest_road_num = i distance = d return (nearest_road_num, distance) #На выходе кортеж из номера ближайшей дороги и расстояния до ее крайнего узла if __name__ == "__main__": print("This module is not for direct call!")
a5fe435935e00a32db6d6a0868e2ad4742876f0a
PK1NONLY/python
/5Ifelse.py
303
4.28125
4
name = "parshant" if name is "raj": print (name) elif name is "rahul": print (name) elif name is "Pkay": print(name) else: print "please sign up to the website" # you can try this also age = 27 # age = 13 if age < 21: print("No! you can't vote!") else: print " you can vote!"
034302f51d82d58dd3b01940a1ec86d30d6a4de5
TangBean/AdvancePython
/chapter11/python_thread.py
1,159
3.734375
4
# 对于 IO 操作,多线程和多进程的差距不大 import threading import time # 实现多线程的方法 # 1. 通过 Thread 类实例化 def get_detail_html(url): print("get detail html started") time.sleep(2) print("get detail html end") def get_detail_url(url): print("get detail url started") time.sleep(4) print("get detail url end") # 2. 通过继承 threading.Thread class GetDetailHtml(threading.Thread): def run(self): print("get detail html started") time.sleep(2) print("get detail html end") class GetDetailUrl(threading.Thread): def run(self): print("get detail url started") time.sleep(4) print("get detail url end") if __name__ == '__main__': # Method 1 thread1 = threading.Thread(target=get_detail_html, args=("123",)) thread2 = threading.Thread(target=get_detail_url, args=("123",)) # Method 2 thread1 = GetDetailHtml() thread2 = GetDetailUrl() start_time = time.time() thread1.start() thread2.start() thread1.join() thread2.join() print("last time: {}".format(time.time() - start_time))
4674375fe2a38fd76ff83632aceca5e8854c13f7
rathinitish29/Python
/check_emptyor_not.py
151
4.125
4
#check empty or not name = input('Eneter your name :') if name: print(f'your name is {name}') else : print('you didn\'t enter anything')
cdc2be5bb77e26ac52d0ca2dc565d66e3afa6442
markdrago/caboose
/src/repo/date_iterator.py
450
3.546875
4
from datetime import timedelta class DateIterator(object): def __init__(self, start, end, delta=timedelta(days=30)): self.start = start self.end = end self.delta = delta self.current = start def __iter__(self): return self def next(self): if self.current > self.end: raise StopIteration result = self.current self.current += self.delta return result
0cc50ea2a9a700bc8996a9df41224ca1c2eaf993
hasnasaal/Basic-Python
/Soal 1 (Tugas 2).py
912
3.984375
4
print("Selamat Datang!") #menu def fungsiMenu(): print(''' --- Menu --- 1. Daftar Kontak 2. Tambah Kontak 3. Keluar''') menu = (int(input("Pilih menu: "))) while menu != 3: while menu == 2: menudua() while menu == 1: menusatu() else: print("Menu tidak tersedia") fungsiMenu() print("Program selesai, sampai jumpa!") exit() #list listNama = [] listNomor = [] #fungsi menu satu def menusatu() : print("Daftar Kontak") for x in range(0, len(listNama)): print(x+1,". Nama: " ,listNama[x] ) print("Nomor Telepon: ",listNomor[x]) fungsiMenu() #fungsi menu dua def menudua() : listNama.append(str(input("Nama: "))) listNomor.append(input("Nomor Telepon: ")) print("Kontak berhasil ditambahkan") fungsiMenu() fungsiMenu()
48ea7c35cd4a93694836db5d88b480d818ea3da5
bharadwajpro/food-recommender-bot
/services/foods.py
627
3.859375
4
import sys foods = { 'samosa': ['C3'], 'sandwich': ['Yummpys', 'C3', 'Bits & Bytes', 'ANC 1', 'ANC 2'], 'rice': ['ANC 1', 'ANC 2', 'Mess 1', 'Mess 2'], 'noodles': ['Yummpys', 'ANC 1', 'ANC 2'], 'paratha': ['Mess 1', 'Mess 2', 'C3'] } if len(sys.argv) == 2: for food in foods: if food == sys.argv[1].lower(): print('{} is available in the following eateries||'.format(sys.argv[1].title()), end='') for eatery in foods[food]: print('{}||'.format(eatery), end='') exit(0) print('This food is not available') else: print('Wrong command')
de1cdd7c24ce9e56af7baaf562ad915960eb246d
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/uniquePaths.py
1,433
4.15625
4
""" Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? """ """ DP (recursion is 2^n) Time: O(m*n) Space: O(m*n) => can be reduced to just storing one row to O(n) space """ class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0 for _ in range(m)] for _ in range(n)] dp[0][0] = 1 for i in range(n): for j in range(m): if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] """ Math Way """ # math C(m+n-2,n-1) def uniquePaths1(self, m, n): if not m or not n: return 0 return math.factorial(m+n-2)/(math.factorial(n-1) * math.factorial(m-1)) class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ grid = [[1 for i in range(m)] for _ in range(n)] for i in range(n): for j in range(m): if not i or not j: continue grid[i][j] = grid[i - 1][j] + grid[i][j - 1] return grid[n - 1][m - 1]
371fc70d5c5e21a2dd95f777535db187ce1ec949
jaioo7/python
/aag.py
574
3.828125
4
# Python Tupnle Methods tp=(5,8,9,69, 'jai',5.9) tp1=(5,7,8,9,3,1,4,5,6,8) # Iteration for t in tp: print(t) # Tuple Indexing & Tuple Slicing ([]) print(tp[0]) print(tp[-1]) print(tp[0:4]) # Tuple lengh, Maximum,minumum print(len(tp)) print(max(tp1)) print(min(tp1)) # Repetition (*) print(tp*3) # Concatenation (+) print(tp+tp1) # Membership (in, not in) print('jai' in tp) print('jai' in tp1) print('jai' not in tp) print('jai' not in tp1) # sequence lst=[2,4,5,8,7,6,9,2.5,True,False,'jai'] print(tuple(lst)) ''' int() float() str() tuple() list() dict() '''
5a264798ae57f511b82b72776c4f7d5bca453196
RajeshA76/EdyodaPracticeArena
/Dictionary/Student_Record.py
2,284
4.125
4
""" Given n names and phone numbers, assemble a students record that maps student's names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for is not found, print Not found instead. Note: Your student Rrecord should be a Dictionary data structure. Input Format The first line contains an integer, n, denoting the number of entries in the student record. Each of the n subsequent lines describes an entry in the form of I2 space-separated values on a single line. The first value is a student's name, and the second value is an 10-digit phone number. After the n lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a name to look up, and you must continue reading lines until there is no more input. Note: Names consist of lowercase English alphabetic letters and are first names only. Output Format On a new line for each query, print Not found if the name has no corresponding entry in the student record; otherwise, print the full Iname and phone number in the format name=phoneNumber. Sample Input 3 david 9991222222 sam 1112222222 tom 12299933 david edward tom Sample Output david=9991222222 Not found tom=1229993333 Explanation We add the following (Key,Value) pairs to our dictionary so it looks like this: studetnRecord = {'david':9991222222,'sam':1112222222,'tom':1229993333} We then process each query and print key=value if the queried is found in the dictionary; otherwise, we print Not found. Query 0: david Sam is one of the keys in our dictionary, so we print daivd=99912222. Query 1: edward Edward is not one of the keys in our dictionary, so we print Not found. Query 2: tom Harry is one of the keys in our dictionary, so we print tom=12299933. """ # Write your code here use STDIN for inout and STDOUT for output n = int(input()) dict = {} for i in range(n): inp = input().split() dict[inp[0]] = inp[1] # enter name in order to get phone number while True: name = input() if name in dict.keys(): print("{0}={1}".format(name,dict[name])) elif(name == ''): break else: print("Not found")
47e49757962bc312ee052bcae6e00f9ca0046d04
AntonioPelayo/leetcode
/all/387-first-unique-character-in-string.py
758
3.828125
4
''' Antonio Pelayo April 2, 2020 Problem: 387. First Unique Character in a String Difficulty: Easy Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only lowercase letters. ''' def firstUniqChar(s): counts = {} for letter in s: if letter in counts: counts[letter] += 1 else: counts[letter] = 1 # Find first char with count of 1 for i in range(len(s)): if counts[s[i]] == 1: return i # None were found return -1 a = 'leetcode' b = 'loveleetcode' print(firstUniqChar(a)) print(firstUniqChar(b))
f6e4581494ebc2540a6880e0df199ec85d0f0c3f
ahmedyoko/python-course-Elzero
/DB_insert_data79.py
1,821
3.625
4
# insert data into db #............................................................ # cursor => all operation in sql done by cursor not by the connection itself # commit => save all changes #............................................................ # import sqlite module # import sqlite3 # # create db and connect # db = sqlite3.connect("app.db") # # setting up the cursor # cr = db.cursor() # # execute the tables and fields # cr.execute("CREATE TABLE if not exists users(user_id INTEGER,name TEXT)") # cr.execute("CREATE TABLE if not exists skills(name TEXT,progress INTEGER,user_id INTEGER)") # # insert data # cr.execute("insert into users(user_id,name)values(1,'Ahmed')") # cr.execute("insert into users(user_id,name)values(2,'Nagib')") # cr.execute("insert into users(user_id,name)values(3,'Osama')") # # save(commit)changes => to transmit to data base and appear in browser # db.commit() # # close the db # db.close() print('*'*50) # delete db and make it again with for loop import sqlite3 # create db and connect db = sqlite3.connect("app.db") # setting up the cursor cr = db.cursor() # execute the tables and fields cr.execute("CREATE TABLE if not exists users(user_id INTEGER,name TEXT)") cr.execute("CREATE TABLE if not exists skills(name TEXT,progress INTEGER,user_id INTEGER)") # insert data # cr.execute("insert into users(user_id,name)values(1,'Ahmed')") # cr.execute("insert into users(user_id,name)values(2,'Nagib')") # cr.execute("insert into users(user_id,name)values(3,'Osama')") my_list = ["Ahmed","Osama","Maged","tharwat","wael","waleed","Mohammed","Aadel"] for key,user in enumerate(my_list) : cr.execute(f"insert into users(user_id,name)values({key+1},'{user}')") # save(commit)changes => to transmit to data base and appear in browser db.commit() # close the db db.close()
09292f64408b201dddfb8c1341880653da9de0f9
freedomDR/coding
/codeforces/1101B.py
590
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- s = input() ans = -1 left = 0 right = len(s) - 1 lok = 1 while left < len(s): if s[left] == '[': lok = 2 left += 1 elif s[left] == ':' and lok == 2: break else: left += 1 rok = 1 while right >= 0: if s[right] == ']': rok = 2 right -= 1 elif s[right] == ':' and rok == 2: break else: right -= 1 if rok == lok and rok == 2 and left < right: ans = 4 while left < right: if s[left] == '|': ans += 1 left += 1 else: ans = -1 print(ans)
d24489dff97599fed289230cabc0290a609655d2
rafaelperazzo/programacao-web
/moodledata/vpl_data/330/usersdata/299/93537/submittedfiles/lista1.py
451
3.5625
4
# -*- coding: utf-8 -*- n_valores=int(input('Digite quantos valores sua lista terá: ')) l=[] contpar=0 contimpar=0 somapar=0 somaimpar=0 for i in range(0,n_valores,1): l.append(int(input('Digite o valor %d: ' %(i+1)))) for i in range(0,n_valores,1): if l[i]%2==0: contpar+=1 somapar+=l[i] else: contimpar+=1 somaimpar+=l[i] print(somaimpar) print(somapar) print(contimpar) print(contpar) print(l)
9aaec35c7d6b8da75144c6b513f849c7fc495548
dmurawski/python
/26kwietnia/9.py
451
3.828125
4
def Upper(wyraz): for index in range(len(wyraz)): yield wyraz[index].upper() generator = Upper("Hello World") print(next(generator)) print(next(generator)) print("costam123") print(next(generator)) print(next(generator)) print("costam123") print(next(generator)) print(next(generator)) print(next(generator)) print(next(generator)) print("costam123") print(next(generator)) print(next(generator)) print("costam123") print(next(generator))
5ffd285c0a7f08b21aec8dca00f4dd10a31de1fa
JeromeLefebvre/ProjectEuler
/Python/Problem057.py
1,082
4.40625
4
#!/usr/local/bin/python3.3 ''' It is possible to show that the square root of two can be expressed as an infinite continued fraction. √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213... By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5 1 + 1/(2 + 1/2) = 7/5 = 1.4 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666... 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379... The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator. In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator? ''' ''' Notes on problem 57(): ''' from fractions import Fraction def f(a): return 1 + 1/(1+a) def problem57(): count = 0 a = Fraction(1) for i in range(1,1000): a = f(a) if len(str(a.denominator)) < len(str(a.numerator)): count += 1 return count if __name__ == "__main__": print(problem57() == 153) from cProfile import run run("problem57()")
1a49ee2acfd1b2d010ac0236499a637f2207cd15
akfunes/studyProblems
/diameter_of_binary_tree.py
691
3.90625
4
# https://leetcode.com/problems/diameter-of-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def __init__(self): self.s = 0 def helper(self,node): if not node: return 0 left = self.helper(node.left) right = self.helper(node.right) newpath = left + right + 1 self.s = max(self.s,newpath) return max(left,right) + 1 def diameterOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 self.helper(root) return self.s- 1
516fefd701102458050fae4e839ce89a5f736cfa
homawccc/PythonPracticeFiles
/2x3.py
239
3.78125
4
x=2 y=3 z=x*y teams = ["Pirates","Phillies","Expos", "Mets", "Cubs", "Cardinals"] for i in teams: print(i) print("Hello Git") #new comment from GitHub #new comment from GitHub Windows Version #new comment from GitHub Lab 226
d33c25e54bea555c6e8ecb5e8897246bd74eb5d5
larners/ACA_HW
/homework2/digit_product.py
175
3.921875
4
def digit_product(n): res = 1 while(n) : if( n % 10 ) : res *= n % 10 n //= 10 return res n = int(input()) print(digit_product( n ))
5aabdc6e0e839ba00770e0b61b475aa72bdea5bb
Peett2/infoshare
/day_6/scopes.py
272
4.03125
4
name = 'Ola' def hello(username): ''' Returns uppercased username\n :param username: string\n :return: str.upper() ''' name = username.upper() return name data = input('Podaj imie:\n') uppercased = hello(data) print(uppercased) print(name)
648969571c611e38839d072ee20a03371da2b38b
duoduo3369/exercise
/algorithm/fibonacci/fibonacci.py
1,097
3.90625
4
# coding=UTF8 def fibonacci(n): """树形递归""" if n is 0: return 0 if n is 1: return 1 return fibonacci(n-1) + fibonacci(n-2) def fib_line(n): def fib_iter(a,b,count): if count is 0: return b else: return fib_iter(b,a+b,count-1) return fib_iter(1,0,n) def fib_fast(n): def isEven(num): return num % 2 is 0 def fib_iter(a,b,p,q,count): """ p = 0, q = 1 T变换: a<-bq+aq+ap b<-bp+aq 详情请见:sicp 练习1.19 """ if count is 0: return b if isEven(count): return fib_iter(a, b, q*q + p*p, 2*p*q + q*q, count/2) else: return fib_iter(b*q + a*q + a*p, b*p + a*q, p, q, count-1) return fib_iter(1,0,0,1,n)
372004aa3fd1c9bade120a862cebc657b538fa12
wassm/Gltps
/VectorHelper.py
3,080
4.28125
4
import math as math class VectorHelper: """A class that handle vectors handle a vector presented in a list contain functions that: sort a vector. add two vectors. return its minimum and maximum. reverse a vector. apply a function on the elements of a vector. """ @staticmethod def sort(vector): """ sort a vector. parameters: vector: a list which contains the componenets of a vector. apply changes in the parameter itself. """ ind1 = ind2 = 0 while (ind1 <= len(vector) - 2): ind2 = ind1 + 1 while (ind2 <= len(vector) - 1): if vector[ind1] > vector[ind2]: vector[ind1], vector[ind2] = vector[ind2], vector[ind1] ind2 += 1 ind1 += 1 @staticmethod def add(vector1, vector2): """add two vectors and returns the result. rise an exception when the two parameters have not the sime length. parameters: vector1: the list of components of the first vector. vector2: the list of components of the second vector. return: vector3 : a list of the components of the sum of the 2 vectors. """ vector3 = [] if len(vector1) != len(vector2): raise Exception("Impossible to add two vectors with different sizes !!") else: i = 0 while i <= len(vector1)- 1: vector3.append(vector1[i] + vector2[i]) i += 1 return vector3 @staticmethod def maxandmin(vector): """return the maximum and the minimum in the vector. parameters: vector: the list of components of the vector. return: max: the maximum of the components of the vector. min: the minimum of the components of the vector. """ minimum = maximum = vector[1] for element in vector: if element > maximum: maximum = element if element < minimum: minimum = element return maximum, minimum @staticmethod def inverse(vector): """reverse the vector. reverse the components of the vector so they look like, the first will be the last, the last will be the first ... parameters: vector: the list of components of the vector. apply changes in the parameter itself. """ size = len(vector) milieu = (size + 1) / 2 i = 0 while i < milieu: vector[i], vector[size - i - 1] = vector[size - i - 1], vector[i] i += 1 @staticmethod def formule(vector): """ apply a formula on the elements in the vector. parameters: vector: the list of components of the vector. apply changes in the parameter itself. """ size = len(vector) ind = 0 while ind < size: vector[ind] = 1 / (1 + math.exp(-vector[ind])) ind += 1
ea8ba7623b25bda8f17d34e0cb49a4e7fe230f44
abenetsol/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
218
3.9375
4
#!/usr/bin/python3 def uppercase(str): strig = "" for i in str: if (ord(i) in range(97, 123)): strig += chr(ord(i) - 32) else: strig += i print("{:s}".format(strig))
c572ec5246fd786379aae2e8debd7bb037967991
crystalapril/python-notes-april
/exercise-filter.py
775
4.21875
4
''' 前两题来自于codewars 1.筛选出不包含在geese列表中的值 2.筛选出偶数 第三题是构造filter函数 ''' #1.Filter out the geese.py #A1.1 def goose_filter(birds): a=[] for x in birds: if x not in geese: a.append(x) return a #A1.2 def goose_filter(birds): return list(filter(lambda x:x not in geese,birds)) #2.Find numbers which are divisible by given number.py #A2.1 def divisible_by(numbers, divisor): l=[] for i in numbers: if i % divisor ==0: l.append(i) return l #A2.2 def divisible_by(a,b): return list(filter(lambda x:x % b ==0,a)) #3.构造filter函数 def filter1(f,xs): l = [] for x in xs: if f(x): l.append(x) return l
af7adf16f9ab6bf84080e38a8a9c9d23c46299b8
ksompura/python_training
/guessing_game/guess_game.py
1,057
4.21875
4
import random # play = "y" # while play == "y": # rand_num = random.randint(1,10) #randint is inclusive and numbers are from 1-10 # intro = int(input("Guess a number between 1-10: ")) # while intro != rand_num: # if intro > rand_num: # intro = int(input("Too high, keep gussing: ")) # elif intro < rand_num: # intro = int(input("Too low, keep gussing: ")) # else: # print("You guessed correctly on your first try!") # print("You got it right!") # play = input("Do you want to play again (y/n):") #Ask if they want to play again (y/n) #Another way to code the same thing random_number = random.randint(1,10) while True: guess = input("Guess a number between 1-10: ") guess = int(guess) if guess < random_number: print("Too low, keep gussing: ") elif guess > random_number: print ("Too high, keep gussing: ") else: print("You win!!") play_again = input("Do you want to play again? (y/n): ") if play_again == "y": random_number = random.randint(1,10) guess = None else: print("Thanks for playing") break
441734b46c071d56e427bf50137bafb3dc3afc3c
psujug/Leetcode
/3_sum.py
1,661
3.5625
4
''' 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 注意:答案中不可以包含重复的三元组。 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 满足要求的三元组集合为: [ [-1, 0, 1], [-1, -1, 2] ] ''' from typing import List class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: res = [] # 1.特判,对于数组长度 nn,如果数组为 nullnull 或者数组长度小于 33,返回 [][]。 n = len(nums) if (not nums or n < 3): return res # 2.排序 nums.sort() # 3.遍历排序后数组 for i in range(n): if (nums[i] > 0): return res if (nums[i] == nums[i - 1] and i > 0): continue first = i + 1 last = n - 1 while (first < last): result = nums[i] + nums[first] + nums[last] if (result == 0): res.append([nums[i], nums[first], nums[last]]) while (first < last and nums[first] == nums[first + 1]): first += 1 while (first < last and nums[last] == nums[last - 1]): last -= 1 first += 1 last -= 1 elif (result > 0): last -= 1 else: first += 1 return res if __name__ == '__main__': print(Solution().threeSum([-1, 0, 1, 2, -1, -4]))
278720ddf3447fa4c2645767637f566a6b5bbcf9
khalidsalata/py_practice
/vector.py
7,265
3.984375
4
from misc import Failure #Class implementing a fixed-length vector class Vector(object): #Constructor for a vector. Size can either describe the size of the #vector object, or the elements you wish to see in the Vector. def __init__(self,size): if isinstance(size, list): self.vec = size[:] elif isinstance(size, int) or isinstance(size, long): if int(size) < 0: raise ValueError("Vector length argument is negative") else: self.vec = int(size) * [0.0] else: raise TypeError("Could not use as list or length") #Returns a string concatinating the type of the Vector #with the string representation of the object's internal list def __repr__(self): res = "Vector(" + repr(self.vec) + ")" return res #Returns the length of the calling object's internal list def __len__(self): return len(self.vec) #Uses the yield call to obtain the next value in a Vector object's #internal list. Overrides the __iter__ function to extend functionality #to Vectors def __iter__(self): for i in self.vec: yield i #Defines how python should understand Vector Addition def __add__(self,other): t = [] #If the other is a vector, we must specify its internal list if type(other).__name__ == "Vector": for m in range(0, len(self.vec)): t.append(self.vec[m] + other.vec[m]) #If other is some other iterable object, we specify behavior also else: for m in range(0, len(self.vec)): t.append(self.vec[m] + other[m]) return Vector(t) #If the caller is not a Vector, but a vector is still being added, #We swap "other" and "self" and add as specified in "__add__" def __radd__(self,other): t = [] if type(other).__name__ == "Vector": for m in range(0, len(self.vec)): t.append(self.vec[m] + other.vec[m]) else: for m in range(0, len(self.vec)): t.append(self.vec[m] + other[m]) return Vector(t) #How to perform incremented addition, we insure that information about #the caller's previous value isn't lost when returning the new vector def __iadd__(self,other): if type(other).__name__ == "Vector": for m in range(0, len(self.vec)): self.vec[m] += other.vec[m] else: for m in range(0, len(self.vec)): self.vec[m] += other[m] return self #This function returns the key'th item in a vector object's internal #list. Throws an exception if the key is out of bounds, and accomodates #for negative output as well. def __getitem__(self,key): if abs(key) >= len(self): raise IndexError("Index out of bounds") if key < 0: key = len(self) + key return self.vec[key] #This function takes the key'th item in a vector object's internal #list and sets it equal to the value argument. If the key is out of #bounds, raises the appropriate exception def __setitem__(self,key,value): if key >= len(self): raise IndexError("Index out of bounds") if key < 0: key = len(self) + key self.vec[key] = value #Describes how to check for equality between vector objects. def __eq__(self,other): #If both arguments are vectors, check their internal lists if type(other).__name__ == "Vector": return self.vec == other.vec #Different objects are never the same else: return False #Describes how to check for inequality operating off of the assumption #that objects that are equal are never inequal at the same time, and #vice verse def __ne__(self,other): return not self == other #Describes how to check for a "greater than" relationship between two #vectors. def __gt__(self,other): if type(other).__name__ == "Vector": #We define two temporary lists oL = other.vec sL = self.vec while sL != []: #If their largest values match, remove them from both if max(sL) > max(oL): return True else: sL.remove(max(sL)) oL.remove(max(oL)) #At this point either self <= other, or other is not a vector return False #Describes how to check for a "greather than or equal to" relationship #between two vectors def __ge__(self,other): if type(other).__name__ == "Vector": #Define two temporary lists representing self.vec and other.vec oL = other.vec sL = self.vec eq = True while sL != []: if max(sL) > max(oL): return True else: #If their max values are not equal, then other/self #will never be equal if max(sL) != max(oL): eq = False sL.remove(max(sL)) oL.remove(max(oL)) return eq return False #Describes how to check for a "less than" relationship between two #vectors. def __lt__(self,other): if type(other).__name__ == "Vector": oL = other.vec sL = self.vec while sL != []: #We consider the largest value of each list, its the quickest #way to determine which list is "larger" if max(sL) < max(oL): return True else: sL.remove(max(sL)) oL.remove(max(oL)) return False #Describes how to check for a "less than or equal to" relationship #between two vectors. def __le__(self,other): if type(other).__name__ == "Vector": oL = other.vec sL = self.vec eq = True while sL != []: #First we try to figure out which list is "greater" than #the other if max(sL) < max(oL): return True else: #If their max values are not equal, then other/self #will never be equal if max(sL) != max(oL): eq = False sL.remove(max(sL)) oL.remove(max(oL)) return eq return False #Takes at least one vector and a list-like object, and returns the #sum of multiplying their respective elements together. We maintain an #accumulator to hold the result of our product addition, fold-style. def dot(self,other): res = 0 #If other is a vector, multiply the elements in their internal lists if type(other).__name__ == "Vector": for m in range(0, len(self.vec)): res += self.vec[m] * other.vec[m] else: #If other is somelist-like object, we multiply it with self's #corresponding internal list element for m in range(0, len(self.vec)): res += self.vec[m] * other[m] return res
484408d5afa0fcab725c4edb35dce3185d269a51
IaroslavaDubitkaia/07.10.2020
/Problema_4.py
110
3.640625
4
a=int(input('Numarul de globulete albe:')) r=a+3 n=(a+3)-2 print("Bradul are in total", a+r+n, "globulete")
db13f3cd70a12b17793ef202a0c8f4b0303b02b6
SKosztolanyi/Python-exercises
/78_Creating Spell class and sublass.py
1,331
4.375
4
## Creating an object and a subclass of the object + function that calls the method of parent object, that is a superclass. class Spell(object): def __init__(self, incantation, name): self.name = name self.incantation = incantation def __str__(self): return self.name + ' ' + self.incantation + '\n' + self.getDescription() def getDescription(self): return 'No description' def execute(self): print self.incantation class Accio(Spell): # subclass of Spell def __init__(self): Spell.__init__(self, 'Accio', 'Summoning Charm') # Inserts incantation and name of Spell class Confundo(Spell): def __init__(self): Spell.__init__(self, 'Confundo', 'Confundus Charm') def getDescription(self): return 'Causes the victim to become confused and befuddled.' # Inserts description. def studySpell(spell): # defines a function to print Spell information according to __str__ method. print spell spell = Accio() # prints nothing, just assigns value to a variable spell.execute() # prints incantation of the spell. In this case "Accio" studySpell(spell) # prints Summoning Charm Accio /n No description studySpell(Confundo()) # prints Confundus Charm Confundo /n Causes the victim to become confused and befuddled.
d280009ef531e6b75291d1de5fd547151714a5e3
vimalanignatius/unsorted-array
/get_index.py
374
4.03125
4
#3. Given an unsorted integer array A and an integer value X, # return the index at which X is located in A or return -1 if it is not found in A. def count(a,x): index=-1 count=0 for i in a: if(i==x): index=count break count+=1 return index a=[2,3,4,5,7,7] x=input("enter the value") print(count(a,x))
8a93fe32bcfa87f5ef795ce2c8ac14d5927d59fe
Anusha260/dictionary
/.vscode/saral14.py
263
3.984375
4
word _dict={'bijender':45,'deepak':60,'param':20,';'anu':30,'roshini':50} sorted_dict = dict( sorted(word_dict.items(), key=lambda item: item[1], reverse=True)) print('Sorted Dictionary: ') print(sorted_dict)
ffa4eaabf64a3c933b7055fe407a04dac88ccd4a
yejinee/Algorithm
/Algorithm Concept/Fractional_knapsack.py
1,587
3.75
4
""" [ Fractional Knapsack ] n개의 물건과 1개의 배낭이 있다 물건 i의 무게는 W(i), 값어치는 P(i), 배낭용량은 M까지 가능 이윤이 최대가 되도록 물건을 담는 방법? (물건을 잘라서 담을 수 있다) [ solution ] - Greedy Algorithm을 사용 < Fractional Knapsack Function > 1. 무게 당 값어치가 큰 물건순서대로 정렬해준다 -> Sortitem 2. list의 앞에서 차례로 가방에 담을 수 있는 물건들을 담아준다 -> 즉, M-item의 무게가 0보다 크면 계속해서 반복 3. M이 남았다면, 안담은 item의 부분만 담아준다. """ def Sortitem(iteminfo): for i in range(len(iteminfo)): iteminfo[i].append(round(iteminfo[i][1]/iteminfo[i][0],2)) # price/weight값을 저장 iteminfo.sort(key=lambda x:x[2]) # price/weight값이 큰 순서대로 정렬 iteminfo.reverse() def Factional_Knapsack(iteminfo,M): Sortitem(iteminfo) i=0 price=0 while (M-iteminfo[i][0])>=0: print(i) M-=iteminfo[i][0] price+=iteminfo[i][1] i+=1 if i>=len(iteminfo): # 모든 item들을 다 담은 경우 break # 남은 경우에 if M>0 and i<len(iteminfo): price+=iteminfo[i][1]*(round(M/iteminfo[i][0],2)) return price # Data input itemlist=[] n=int(input('물건 갯수?')) M=int(input('배낭 용량? ')) for i in range(n): item= list(map(int,input('물건의 무게, 값어치를 차례로 입력').split())) itemlist.append(item) print(Factional_Knapsack(itemlist,M))
b9f0710057cfee0caac55d262dbbf00a6dc84629
brunogh88/Teste-Python
/src/utils/timer.py
679
3.984375
4
"""This module contains the Timer class""" import time class Timer(object): """Timer class""" def __init__(self): self.start_time = None self.end_time = None self.duration = None def start(self): """Start timer""" self.start_time = time.time() def end(self): """End timer""" self.end_time = time.time() total_time = self.end_time - self.start_time self.duration = time.strftime("%H:%M:%S", time.gmtime(total_time)) self.duration = "%f seconds" % round( total_time, 2) \ if self.duration == '00:00:00' else str(self.duration) return self.duration
09ee91d49b39df4aeddeae0109781a8bcf85360e
Mahmoud-Shosha/Fundamentals-of-Computing-Specialization-Coursera
/Principles of Computing (Part 1)/Week 2 - Testing, plotting, and grids/plotting2.py
1,458
4.625
5
""" Example of creating a plot using simpleplot Input is a list of point lists (one per function) Each point list is a list of points of the form [(x0, y0), (x1, y1, ..., (xn, yn)] """ import matplotlib.pyplot as plt # create three sample functions def double(num): """ Example of linear function """ return 2 * num def square(num): """ Example of quadratic function """ return num ** 2 def exp(num): """ Example of exponential function """ return 2 ** num def create_plots(begin, end, stride): """ Plot the function double, square, and exp from beginning to end using the provided stride The x-coordinates of the plotted points start at begin, terminate at end and are spaced by distance stride """ # generate x coordinates for plot points x_coords = [] current_x = begin while current_x < end: x_coords.append(current_x) current_x += stride # compute list of (x, y) coordinates for each function double_plot = [double(x_val) for x_val in x_coords] square_plot = [square(x_val) for x_val in x_coords] exp_plot = [exp(x_val) for x_val in x_coords] # plot the list of points plt.figure(figsize=[20, 20]) plt.plot(x_coords, double_plot, 'o-') plt.plot(x_coords, square_plot, 'o-') plt.plot(x_coords, exp_plot, 'o-') plt.legend(['double', 'square', 'exp']) plt.show() create_plots(0, 10, .5)
e91bb582041f3d98eeba01a3eca4039d55cdfc27
Tevitt-Sai-Majji/fun-coding-
/Abundant number.py
114
3.671875
4
n=int(input()) a=0 for i in range(1,int(n/2+1)): if n%i==0: a=a+i if a>=n: print("Abundant Number")
fae1122d0b5f4a9ffb8fa954f66a55205333f6b2
Waldij/py-programs
/test_tasks/tetrika/task_1.py
1,128
3.734375
4
""" Дан массив чисел, состоящий из некоторого количества подряд идущих единиц, за которыми следует какое-то количество подряд идущих нулей: 111111111111111111111111100000000. Найти индекс первого нуля (то есть найти такое место, где заканчиваются единицы, и начинаются нули) print(task("111111111111111111111111100000000")) # >> OUT: 25... """ def task(array: str) -> int: return array.find('0') def main(): """ Встроенный метод str.find вызывает Objects/stringlib/fastsearch.h n - длина строки m - длина подсторки В худшем случаем сложность будет O(n * m) Внекоторых случаях O(n / m) В нашей задаче, длина подсторки m = len('0') = 1 И сложность будет O(n) """ print(task("111111111111111111111111100000000")) if __name__ == '__main__': main()
d5ee5a2eb7879ff8fe2fb8e684f4ab098fd228be
ArunDruk/Repo1_python_basic_pgms
/Anonymous_Lambda.py
1,804
4.3125
4
# # lambda argument_list : expression # n=int(input("Enter a num: ")) # s=lambda n:n*n # print(f'Square of {n} is:', s(n)) #filter(function,sequence) #We can use filter() function to filter values from the given sequence based on some condition. #Filter function will only return the value for the function which is TRUE # a=[] # for i in range(0,10): # a.append(i) # l1=list(filter(lambda x: x%2==0,a)) # l2=list(filter(lambda x: x%2!=0,a)) # print("List of Even numbers between 0-10",l1) # print("List of odd numbers between 0-10",l2) # map(function,sequence) #For every element present in the given sequence,apply some functionality and generate #new element with the required modification. For this requirement we should go for map function #a=[] # for i in range(0,10): # a.append(i) # l1=list(map(lambda x: x*x,a)) # print("List of Squares for the numbers between 0-10",l1) # Ex:2, Map function use to apply some expression only to the second element in all the list elements l=[("Arun",29),("Sharmila",25)] c_to_f=lambda x:(x[0],((9/5)*x[1])+32) l2=list(map(c_to_f,l)) print(l2) #reduce(function,sequence) #reduce() function reduces sequence of elements into a single element by applying the specified function. #reduce() function present in functools module and hence we should write import statement. # from functools import * # l1=list(range(0,10)) # l2=reduce(lambda x,y:x+y,l1) # print(l2) # In the below example decor is a decorator function which takes function as an argument # def decor(func): # def inner(name): # if name=="Sunny": # print("Hello Sunny Bad Morning") # else: # func(name) # return inner # # @decor # def wish(name): # print("Hello",name,"Good Morning") # # wish("Durga") # wish("Ravi") # wish("Sunny")
754f6b0587541bffa9b5fbcb792cca1251bcf1a0
piskunovma/logic_python
/lesson6/task_1.py
5,172
3.640625
4
# Подсчитать, сколько было выделено памяти под переменные # в ранее разработанных программах в рамках первых трех уроков. # Проанализировать результат и определить программы # с наиболее эффективным использованием памяти. import sys # macOS Catalina 10.15.4, 64-разрядная. Версия интерпретатора - Python 3.7 # Функция подсчета затрачиваемой памяти def size_func(obj): sum_memory = sys.getsizeof(obj) # print(f'type={type(obj)}, size={sys.getsizeof(obj)}, obj={obj}') if hasattr(obj, '__iter__'): if hasattr(obj, 'items'): for key, value in obj.items(): sum_memory += size_func(key) sum_memory += size_func(value) elif not isinstance(obj, str): for item in obj: if item is not True and item is not False: sum_memory += size_func(item) return sum_memory # Вариант первый: def my_func(number): global i first_num = 2 idx = 1 while idx != number: first_num += 1 for i in range(2, first_num): if first_num % i == 0: break else: idx += 1 tuple_for_sum = ((i, number, idx, range(2, first_num), first_num)) sum_res = size_func(tuple_for_sum) return f'Ваше простое число - {first_num}.\n' \ f'Сумма памяти переменных - {sum_res - sys.getsizeof(tuple_for_sum)} байт.' print(my_func(10)) print('*' * 50) # Вариант второй: def my_eratosphens(number): global idx, i CONST = 10 array = [i for i in range(2, (number + 1) * CONST)] if number == 1: tuple_for_sum = (CONST, array, number) sum_res = size_func(tuple_for_sum) return f'Ваше простое число - {array[number - 1]} .\n' \ f'Сумма памяти переменных - {sum_res - sys.getsizeof(tuple_for_sum) + sys.getsizeof(False)} байт.' p = 2 while p < number: idx = 0 for i in array: if i >= p ** 2: if i % p == 0: array[idx] = False idx += 1 p += 1 result_list = [i for i in array if i != False] tuple_for_sum = (CONST, array, p, number, result_list, i, idx) sum_res = size_func(tuple_for_sum) return f'Ваше простое число - {result_list[number - 1]} .\n' \ f'Сумма памяти переменных - {sum_res - sys.getsizeof(tuple_for_sum) + sys.getsizeof(False)} байт.' print(my_eratosphens(4)) print('*' * 50) # Вариант третий: def eratosphen_teach(num): global item for_sum = 0 CONST = 10 array = [True for _ in range(num * CONST)] count = 0 for i in range(2, len(array)): if array[i]: count += 1 if count == num: tuple_for_sum = (CONST, array, count, i, item) sum_res = size_func(tuple_for_sum) + for_sum return f'Ваше простое число - {i} .\n' \ f'Сумма памяти переменных - {sum_res - sys.getsizeof(tuple_for_sum) + sys.getsizeof(False) + sys.getsizeof(True)} байт.' # return i for item in range(i ** 2, len(array), i): array[item] = False print(eratosphen_teach(8)) # Вывод: В плане затрачиваемой памяти менее затратный - первый вариант. # Но он также является наиболее долгим на больших значениях. # Я бы выбрал 3ий вариант, он менее затратен по памяти чем второй вариант, # но по скорости работы и удобству чтения кода сильно превосходит остальные варианты. # Так же не сломался вывод первого простого числа во всех вариантах. # (Во втором вроде поправил, отдельно добавив обработку случая когда ищем первое простое число. # В первом можно сделать также, но не уверен, что это в принципе верное решение, поэтому там не стал ничего менять.) # Почему так произошло полноценного понимания нет, буду рад любым комментариям, которые помогут разобраться. # Как я понял, это из-за того, что при поиске первого простого числа, # некоторые переменные в коде не определяются и как следствие не выводятся и не суммируются позже
a8439d0e1af3b77cdeade3c23e91d2987d5680ba
kiranmah92/Pattern-matching
/pattern_matching.py
5,083
3.59375
4
import pandas as pd from matplotlib import pyplot as plt import numpy as np from datetime import datetime as dt from matrixprofile import * class Matrix_profile: def __init__(self): pass def get_date(self , df): max_ = df['temp'].max() min_ = df['temp'].min() print("max = " , max_) print("min = " , min_) # print(df['temp']) # print(type(df['temp'][0])) try: d = input("Enter the date you want to find pattern from in (dd/mm/yyyy) format only") d = d.split("/") temp = dt(int(d[-1]), int(d[-2]), int(d[-3])) ind_ = df.index[ df['temp'] == temp][0] print("index",type(ind_)) if ind_ >= 0: return ind_ else: print("entered date is not in range") self.get_date(df) except: print("entered date does not exist") self.get_date(df) def read_data(self): try: flag = 1 path = input("Enter the path to csv file") df = pd.read_csv(path) df["index_"] = [i+1 for i in df.index] columns_ = df.columns while(flag==1): df_column = input("Enter the column name") if df_column not in columns_: print("Entered column is not in data") flag = 1 else: flag = 0 df[df_column] = pd.to_numeric(df[df_column]) df['temp'] = pd.to_datetime(df['Date']) pattern_date = self.get_date(df) flag1 = 1 test = int(input("Do you want to give size of pattern ? Enter 1 if yes 0 if no.")) if test == 1: while(flag1): m = int(input("enter the length of pattern")) if (m >= 10) & (m <= 30): flag1 = 0 else: print("please enter the window of size between 10 to 30 only") else: m = 10 return df[df_column] , df_column , df['Date'] , m , pattern_date except FileNotFoundError: print("File not found at " , path) except: print("some exception occured") def matrix_profile(self , df , df_column , m , date_): # plt.plot(df) # plt.show() # print(df.values) pattern = df.values[:] df1 = pd.DataFrame() df1[df_column]= pattern # print(pattern) mp = matrixProfile.stomp(pattern , m) df1['mp'] = np.append(mp[0] , np.zeros(m-1)+np.nan ) df1["mp_loc"] = np.append(mp[1] , np.zeros(m-1)+np.nan) df1['date'] = date_[:] # plt.plot(df1['mp']) # plt.show() # df1.index = [i+2 for i in df1.index] df1.to_csv("D:/cloud_coe_work/timeseries/retail_ts_v4_2_op.csv") plt.plot(df1.index , df1[df_column] , color = "orange") max_val = df1.nlargest(1 , ['mp'])[df_column] i = max_val.index.values[0] print("anomoly ",i) rng = df1[df_column][i: (i+m)] max_val = range(i , i+m) print("max val " , max_val) plt.plot(max_val,rng, color = "red" , ) date_val = [str(x)[:-5] for x in df1.date] # plt.xticks(df1.index[1::4] , date_val[1::4] ,rotation=45) plt.xlabel("Dates") plt.ylabel(df_column) plt.show() return df1 def plot_pattern_matching(self , data_copy , colnm ,m , p_d): # print("-----" , p_d) y = data_copy.index dt_ = [str(x) for x in data_copy.date] # dt_ = [str(x)[:-5] for x in data_copy.date] plt.plot(data_copy.index, data_copy[colnm] , color = 'orange') plt.xlabel("Dates") plt.xticks(y[1::2],dt_[1::2], rotation = 90) plt.ylabel(colnm) # ind_ = data_copy.iloc[data_copy.date == p_d] # print("----------date----" , ind_) # ind = dat.index.values.astype(int) # mp_val = data_copy['mp'][p_d] i = p_d indexces = [] # print("i ",data_copy[i-1:i]) # while( mp_val < 2 and i != 0) : while( mp_val < 2 ) : indexces.append(i) # print("mp_val ",mp_val) plt.plot(data_copy.index[ i : i + m ],data_copy[colnm][ i : i + m ] , color = 'blue') print(data_copy[colnm][ i : i + m ]) mp_val = data_copy['mp'][i] i = int(data_copy['mp_loc'][i]) # print(" ",data_copy['mp_loc'][i-1:i]) if i not in indexces: print("mp val",i) continue else: break plt.show() if __name__ == '__main__': mp = Matrix_profile() temp = mp.read_data() if temp: data , column_name , date_ , m , p_d = temp[0], temp[1], temp[2], temp[3], temp[4] dt = mp.matrix_profile(data , column_name , m , date_) mp.plot_pattern_matching(dt ,column_name, m , p_d)
7959789e8c04c980a63eb1ef1cbf0ddbcd78e508
ckallum/Daily-Coding-Problem
/solutions/#163.py
672
3.890625
4
def reverse_polish(equation): num_stack = list() operations = {"*": lambda x, y: x * y, "/": lambda x, y: x / y, "-": lambda x, y: x - y, "+": lambda x, y: x + y} for char in equation: if char in operations: if len(num_stack) < 2: return None res = operations[char](num_stack.pop(), num_stack.pop()) num_stack.append(res) else: num_stack.append(char) return num_stack.pop() def main(): assert reverse_polish([15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']) == 5 if __name__ == '__main__': main()
2471c93f83fb7c0e5567897c4b3df7602a50a231
kdung109/OpenSource_Class
/7주차 6번.py
269
3.59375
4
import math d = [1, 2, 3, 4, 5] print("총점은? :",sum(d)) mean = sum(d) / len(d) print("평균은? :",mean) vsum = 0 for x in d: vsum = vsum + (x - mean) ** 2 var = vsum / len(d) print("분산은? :",var) std = math.sqrt(var) print("표준편차는? :",std)
5fb42551f78c852b27903f5853cae21f2683059f
AndrewKalil/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
3,528
3.53125
4
#!/usr/bin/python3 """Base class""" import json import csv class Base: """class Base """ __nb_objects = 0 def __init__(self, id=None): """Instantiation for the class Args: id (int, optional): id of object. Defaults to None. """ if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects @staticmethod def to_json_string(list_dictionaries): """converts object to json string Args: list_dictionaries (object): object to be coverted Returns: str: string representation """ if list_dictionaries is None or len(list_dictionaries) is 0: return "[]" else: return json.dumps(list_dictionaries) @classmethod def save_to_file(cls, list_objs): """saves a json string to a file Args: list_objs (objcet): object to convert to string """ ls = [] if list_objs: ls = [i.to_dictionary() for i in list_objs] with open("{}.json".format(cls.__name__), mode='w') as fd: fd.write(cls.to_json_string(ls)) @staticmethod def from_json_string(json_string): """converts json string to object Args: json_string (str): string representation of object Returns: object: object representation of json string """ if json_string is None or len(json_string) is 0: return [] else: return json.loads(json_string) @classmethod def create(cls, **dictionary): """creates a new object with dictionary values Returns: object: new created object """ if cls.__name__ == "Rectangle": dummy = cls(1, 1) elif cls.__name__ == "Square": dummy = cls(1) dummy.update(**dictionary) return dummy @classmethod def load_from_file(cls): """loads a dictionary from a file and converts it to an instance Returns: object: new object that was created from dict in file """ try: with open("{}.json".format(cls.__name__)) as fd: return [cls.create(**i) for i in cls.from_json_string(fd.read())] except Exception: return [] @classmethod def save_to_file_csv(cls, list_objs): if cls.__name__ == "Rectangle": fieldnames = ["id", "width", "height", "x", "y"] else: fieldnames = ["id", "size", "x", "y"] with open("{}.csv".format(cls.__name__), mode="w") as fd: if list_objs: writer = csv.DictWriter(fd, fieldnames=fieldnames) writer.writeheader() for line in list_objs: writer.writerows([line.to_dictionary()]) else: writer = csv.writer(fd) writer.writerow([[]]) @classmethod def load_from_file_csv(cls): try: with open("{}.csv".format(cls.__name__), newline='') as fd: reader = csv.DictReader(fd) ls = [] for line in reader: for key, value in line.items(): line[key] = int(value) ls.append(line) return [cls.create(**i) for i in ls] except Exception: return []
e320c9bd1c6d7bc73bcd22628fd2bbbea91b84b7
Geekersen/Python_Exercises
/100_Python_Exercises/006-sensitive_word_detection_shield.py
779
3.609375
4
""" 006-sensitive_word_detection_shield.py 描述:敏感词文本文件 filtered_words.txt ,当用户输入敏感词时,将敏感词用 ** 代替。 """ import os def sensitive_word_detection_shield(detected_words, filter_words): for word in filter_words: detected_words = detected_words.replace(word, len(word) * '*') print(detected_words) if __name__ == '__main__': os.chdir('/Users/richardsen/PycharmProjects/Python_Exercises/Test_Data') with open('filtered_words') as fileter_file_object: fileter_file = fileter_file_object.read() filter_words = fileter_file.split('\n') while True: words_in = input() if words_in == '^Z': break sensitive_word_detection_shield(words_in, filter_words)
7027f97674e9b8bb7f361a77030111a423530449
ActuallyACat/cs4920
/noj/data_structures.py
7,200
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from db_interface import * SENTENCE = 0 PHRASE = 1 CORPUS = 0 DICTIONARY = 1 FORMAT_TABS = 0 class Dictionary(object): """docstring for Dictionary A Dictionary contains a 'name' for the dictionary and a subsequent list of 'entries'. """ def __init__(self, name): super(Dictionary, self).__init__() self.name = name self.entries = list() # def import_non_recursive(self, db_interface): # """docstring for import""" # db_interface.create_dictionary(self) # pass # def get_id(self, db_interface): # """docstring for import""" # pass class DictionaryEntry(object): """docstring for DictionaryEntry Creates Dictionary Entry structure which consists of 5 elements: kana = How the Japanese word is pronounced (stored as string) kanji = The entry in proper Japanese form (sotred as list) entry_number = ID number given to entry (stored as integer) meanings = A list of meanings for the associated entry """ def __init__(self, kana, kanji, entry_number, id_ = None): super(DictionaryEntry, self).__init__() self.kana = kana self.kanji = kanji # is a list self.entry_number = entry_number self.meanings = list() self.id_ = id_ def add_meaning(self, meaning): """docstring for add_meaning Add meaning to Dictionary Entry NOTE: An entry can have multiple meanings """ self.meanings.append(meaning) def num_meanings(self): """docstring for num_meanings Returns the number of meanings for a Dictionary Entry as entries may have multiple meanings """ return len(self.meanings) def kanji_string(self): """Return a string containing kanji separated by a dot""" return u"・".join(self.kanji) def get_meanings(self, dbi): """Get meanings from database.""" if self.meanings == [] or None: if self.id_ is not None: print "get meanings from db" self.meanings = dbi.get_meanings(self.id_) return self.meanings def __str__(self): meaning_str_list = list() for m in self.meanings: meaning_str_list.extend(str(m).split('\n')) meaning_str = '\n'.join(["\t{}".format(m) for m in meaning_str_list]) kanji_str = u'·'.join(self.kanji) return ("{} {} [{}]\n{}".format(self.kana.encode('utf-8'), self.entry_number, kanji_str.encode('utf-8'), meaning_str)) def __repr__(self): lines = list() lines.append("e = DictionaryEntry({}, {}, {})".format( repr(self.kana), repr(self.kanji), repr(self.entry_number))) for meaning in self.meanings: lines.append(repr(meaning)) lines.append("e.add_meaning(m)") return '\n'.join(lines) class DictionaryMeaning(object): """docstring for DictionaryMeaning A Dictionary Entry may have a Dictionary Meaning A Dictionary Meaning has 3 elements: meaning = the definition meaning_number = as there might be multiple meanings, this will keep track usage_examples = a list of usage examples that use this dictionary meaning(optional) """ def __init__(self, meaning, meaning_number, id_ = None): super(DictionaryMeaning, self).__init__() self.meaning = meaning self.meaning_number = meaning_number self.id_ = id_ self.usage_examples = list() def add_usage_example(self, ue): """docstring for add_ue Helper function that appends usage examples to Dictionary Meaning""" self.usage_examples.append(ue) def get_usage_examples(self, dbi): """Get usage examples from database.""" if self.usage_examples == [] or None: if self.id_ is not None: print "get ues from db" self.usage_examples = dbi.get_usage_examples(self.id_) return self.usage_examples def __str__(self): ue_str_list = list() for ue in self.usage_examples: ue_str_list.extend(str(ue).split('\n')) ue_str = '\n'.join(["\t{}".format(ue) for ue in ue_str_list]) return ("{}: {}\n{}".format(self.meaning_number, self.meaning.encode('utf-8'), ue_str)) def __repr__(self): lines = list() lines.append("m = DictionaryMeaning({}, {})".format( repr(self.meaning), repr(self.meaning_number))) for ue in self.usage_examples: lines.append(repr(ue)) lines.append('m.add_usage_example(ue)') return '\n'.join(lines) class UsageExample(object): """docstring for UsageExample An usage example is a sentence that is associated with a particular word This class has 4 elements: expression = the sentence itself meaning = the meaning of the word assocaited witht he usage example type = is this a sentence or phase -> default is sentence components = what are the break up of words in the sentence """ def __init__(self, expression, meaning, type_=SENTENCE): super(UsageExample, self).__init__() self.expression = expression self.meaning = meaning self.type_ = type_ self.components = None def get_components(self, parser): """docstring for get_components Places words that belong to the usage example as a list """ if self.components is None: self.components = parser.parse(self.expression).components return self.components def __str__(self): return ("{}\n{}".format(self.expression.encode('utf-8'), self.meaning.encode('utf-8'))) def __repr__(self): lines = list() lines.append("ue = UsageExample({}, {}, {})".format( repr(self.expression), repr(self.meaning), repr(self.type_))) return '\n'.join(lines) class UsageExampleList(object): """docstring for UsageExampleList""" def __init__(self, name): super(UsageExampleList, self).__init__() self.name = name self.ue_list = list() self.id_ = None def add_usage_example(self, ue): """docstring for add_usage_example""" self.ue_list.append(ue) def add_usage_examples(self, ue_list): """docstring for add_usage_example""" self.ue_list.extend(ue_list) def set_ue_list(self, ue_list): """docstring for add_usage_example""" self.ue_list = ue_list def save(self): """Save UE list to database""" print "TODO: save list=({}) to database".format(self.name) pass if __name__ == '__main__': db_interface = DatabaseInterface('sentence_library.db') dictionary = Dictionary('Test Dict') dictionary.import_non_recursive(db_interface)
c32176487913aebb4d2787bbc116537f952be7b4
Tony-Mok/Date-Timer
/date_string.py
2,148
4.4375
4
class DateString: ''' A class containing year, month and day of a date ''' def __init__(self, year: int, month: int, day: int) -> None: self.day = day self.month = month self.year = year def __lt__(self, other) -> bool: if self.year != other.year: # different year, then compare the year return self.year < other.year elif self.month != other.month: # the year is the same but month is different return self.month < other.month else: # year and month are the same, but the day might different return self.day < other.day @staticmethod def more_than_a_month_apart(date_str1, date_str2) -> bool: ''' definition: A month is from some day to the same day in the following month, regardless of the number of days. So, Jan 3rd to Feb 3rd is exactly one month. Jan 3rd to Feb 4th is more than a month. observation 1: only the edge cases is important, omit year diff >= 2 observation 2: when the year diff == 1, the only case to be False will be Dec and next Jan ''' # to make sure the ordering if date_str1 < date_str2: earlier_date, later_date = date_str1, date_str2 else: earlier_date, later_date = date_str2, date_str1 # case 1: year different > 1 year_diff = later_date.year - earlier_date.year if year_diff >= 2: return True # case 2: year different == 0 or year different == 1 # then we can simply convert the extra year to 13 .. 24 (next year Jan - next year Dec) earlier_month = earlier_date.month later_month = 12 * year_diff + later_date.month month_diff = later_month - earlier_month if month_diff == 0: # within the same month return False elif month_diff > 1: # difference more than one month return True else: # only one month apart, so need to check the day value for comparison return later_date.day > earlier_date.day
0ed85021bf3f32ea2e53a45a9f58c5d920c44220
kiara-williams/ProgrammingII
/prac_02/files.py
693
4
4
FILE = "name.txt" NUMBER_FILE = "numbers.txt" # asks for input and prints name to file read_file = open(FILE, "w") name = str(input("Please enter your name: ")) print(name, file=read_file) read_file.close() # reads name from file and prints it to console. write_file = open(FILE, "r") name = write_file.readline() stripped_name = name.strip() print("Your name is", stripped_name) write_file.close() # reads number file and adds contents. Currently using file w/ 17 and 42, but scalable for larger files. read_file = open(NUMBER_FILE, "r") file_list = read_file.readlines() total = 0 for line in file_list: line = line.strip() total += int(line) print("The total is", total)
0664ca69436e62ceed541e1188eada82c0abcaa1
steliostss/advent-of-code2020
/day03/day03.py
884
3.75
4
# implementation for the day03 quiz of "advent of code" def read_input(infile): input = [] with open(infile) as f: for line in f: input.append(line.strip('\n')) return input def begin_slope(ground, step_right=3, step_down=1): counter = 0 dest = 0 row = 0 while row < len(ground): line = ground[row] if (line[dest%len(line)] == '#'): counter += 1 # print("[", row, "]", "[", dest%len(line)-1, "]", " counter = ", counter, sep="") dest += step_right row += step_down return counter input = read_input("input.txt") hits = begin_slope(input) print("Part 1:", hits) slopes = [(1,1), (3,1), (5,1), (7,1), (1,2)] trees = [] for i in range(0, len(slopes)): r, d = slopes[i] trees.append(begin_slope(input, r, d)) mul = 1 for i in trees: mul *= i print("Part 2:", mul)
c129b15baab105863264af400c1ac70dbf3673c3
mustafasisik/mstfssk
/contains.py
178
3.578125
4
def contains(x, liste): if x in liste: return True else: return False assert contains(2, [1, 2, 3, 4, 5]) == True assert contains(1, [3,4,5,6]) == False
229a3f9015ce0639a2f4ae7b07a46895133f3634
cgifford99/Artificial-Intelligence
/Tensorflow/tf_understanding 9-21-17.py
2,049
3.953125
4
import tensorflow as tf #tf.constant is essentially a variable in tensorflow node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0, dtype=tf.float32) print(node1, node2) #It ends up printing data information about the nodes, not the values #To print the values of the nodes, run the computational graph within tf.session() sess = tf.Session() print("Node1:", sess.run(node1)) print("Node2:", sess.run(node2)) #To add two tf.constants, use tf.add node3 = tf.add(node1, node2) print("Node3:", sess.run(node3)) #Here we're just adding two values, just using a different method a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a + b print("Adder_Node:", sess.run(adder_node, {a: 3, b: 4.5})) print("Adder_Node:", sess.run(adder_node, {a: 6, b: 24})) #Now we're just multiplying adder_node by 3 and printing it with multiple #values of 'a' and 'b' triple_adder_node = adder_node * 3 print("Triple_Adder_Node:", sess.run(triple_adder_node, {a: [2, 6], b: [4, 12]})) #Now we're creating a trainable model. Why? I'm not exactly sure. W = tf.Variable([8], dtype=tf.float32) b = tf.Variable([-4], dtype=tf.float32) x = tf.placeholder(tf.float32) linear_model = W * x + b #We need to initialize all tf.Variables() before printing anything #in order for variables to work. sess.run(tf.global_variables_initializer()) #Now we're running the trainable model with some test data print(sess.run(linear_model, {x: [1, 2, 3, 4]})) #This will create a loss function #It will measure how far apart our model is from the provided data #Although I'm not sure why the loss function works y = tf.placeholder(tf.float32) squared_deltas = tf.square(linear_model - y) loss = tf.reduce_sum(squared_deltas) print(sess.run(loss, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]})) #This is optimizing some stuff or something optimizer = tf.train.GradientDescentOptimizer(0.001) train = optimizer.minimize(loss) for i in range(1000): sess.run(train, {x: [1, 2, 3, 4], y: [0, -1, -2, -3]}) print(sess.run([W, b])) #Now the loss is 0
349eec672ac4c218ffbacc0f61b705e8e7f91e9a
abnerfcastro/ml-nanodegree
/chicago-bikeshare/chicago_bikeshare_en.py
13,436
3.859375
4
# coding: utf-8 # Here goes the imports import csv import matplotlib.pyplot as plt import datetime as dt from os import path # Let's read the data as a list print("Reading the document...") filepath = path.abspath(path.join(path.dirname(__file__), "chicago.csv")) with open(filepath, "r") as file_read: reader = csv.reader(file_read) data_list = list(reader) print("Ok!") # Let's check how many rows do we have print("Number of rows:") print(len(data_list)) # Printing the first row of data_list to check if it worked. print("Row 0: ") print(data_list[0]) # It's the data header, so we can identify the columns. # Printing the second row of data_list, it should contain some data print("Row 1: ") print(data_list[1]) input("Press Enter to continue...") # TASK 1 # TODO: Print the first 20 rows using a loop to identify the data. print("\n\nTASK 1: Printing the first 20 samples") print('\n'.join(map(str, data_list[:20]))) # Let's change the data_list to remove the header from it. data_list = data_list[1:] # We can access the features through index # E.g. sample[6] to print gender or sample[-2] input("Press Enter to continue...") # TASK 2 # TODO: Print the `gender` of the first 20 rows print("\nTASK 2: Printing the genders of the first 20 samples") for i in range(20): print(data_list[i][6]) # Cool! We can get the rows(samples) iterating with a for and the columns(features) by index. # But it's still hard to get a column in a list. Example: List with all genders input("Press Enter to continue...") # TASK 3 # TODO: Create a function to add the columns(features) of a list in another list in the same order def column_to_list(data, index): """ Given a matrix, returns designated column as a list. Args: data: The matrix index: The index of the column to be returned as a list Returns: The desired column as a list. """ column_list = [item[index] for item in data] return column_list # Let's check with the genders if it's working (only the first 20) print("\nTASK 3: Printing the list of genders of the first 20 samples") print(column_to_list(data_list, -2)[:20]) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(column_to_list(data_list, -2)) is list, "TASK 3: Wrong type returned. It should return a list." assert len(column_to_list(data_list, -2)) == 1551505, "TASK 3: Wrong lenght returned." assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[1] == "Male", "TASK 3: The list doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Now we know how to access the features, let's count how many Males and Females the dataset have # TASK 4 # TODO: Count each gender. You should not use a function to do that. male = 0 female = 0 for gender in column_to_list(data_list, -2): if gender == 'Male': male += 1 elif gender == 'Female': female += 1 # Checking the result print("\nTASK 4: Printing how many males and females we found") print("Male: ", male, "\nFemale: ", female) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert male == 935854 and female == 298784, "TASK 4: Count doesn't match." # ----------------------------------------------------- input("Press Enter to continue...") # Why don't we creeate a function to do that? # TASK 5 # TODO: Create a function to count the genders. Return a list # Should return a list with [count_male, counf_female] (e.g., [10, 15] means 10 Males, 15 Females) def count_gender(data_list): """ Counts how many Males and Females are there in the gender column (index=-2) of the data matrix. Args: data_list: The data matrix Returns: A list of two items containing the count of Males and Females """ count_male, count_female = 0, 0 genders = column_to_list(data_list, -2) for gender in genders: if gender == 'Male': count_male += 1 elif gender == 'Female': count_female += 1 return [count_male, count_female] print("\nTASK 5: Printing result of count_gender") print(count_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(count_gender(data_list)) is list, "TASK 5: Wrong type returned. It should return a list." assert len(count_gender(data_list)) == 2, "TASK 5: Wrong lenght returned." assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, "TASK 5: Returning wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # Now we can count the users, which gender use it the most? # TASK 6 # TODO: Create a function to get the most popular gender and print the gender as string. # We expect to see "Male", "Female" or "Equal" as answer. def most_popular_gender(data_list): """ Uses count_gender function to determine the most popular gender. Args: data_list: The data matrix Returns: "Equal", when the gender count is equal "Male", if Male is the predominant gender "Female", if Female is the predominant gender """ males, females = count_gender(data_list) answer = "Equal" if males == females else "Male" if males > females else "Female" return answer print("\nTASK 6: Which one is the most popular gender?") print("Most popular gender is: ", most_popular_gender(data_list)) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert type(most_popular_gender(data_list)) is str, "TASK 6: Wrong type returned. It should return a string." assert most_popular_gender(data_list) == "Male", "TASK 6: Returning wrong result!" # ----------------------------------------------------- # If it's everything running as expected, check this graph! gender_list = column_to_list(data_list, -2) types = ["Male", "Female"] quantity = count_gender(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('Gender') plt.xticks(y_pos, types) plt.title('Quantity by Gender') plt.show(block=True) input("Press Enter to continue...") # TASK 7 # TODO: Plot a similar graph for user_types. Make sure the legend is correct. print("\nTASK 7: Check the chart!") def count_user_type(data_list): """ Counts how many Subscriber, Customer and Dependent are there in the user type column (index=-3) of the data matrix. Args: data_list: The data matrix Returns: A list of three items containing the counts of Subscriber, Customer and Dependent """ count_subscriber, count_customer, count_dependent = 0, 0, 0 user_type_list = column_to_list(data_list, -3) for user_type in user_type_list: if user_type == 'Subscriber': count_subscriber += 1 elif user_type == 'Customer': count_customer += 1 elif user_type == 'Dependent': count_dependent += 1 return [count_subscriber, count_customer, count_dependent] user_type_list = column_to_list(data_list, -3) types = ["Subscriber", "Customer", "Dependent"] quantity = count_user_type(data_list) y_pos = list(range(len(types))) plt.bar(y_pos, quantity) plt.ylabel('Quantity') plt.xlabel('User Type') plt.xticks(y_pos, types) plt.title('Quantity by User Type') plt.show(block=True) input("Press Enter to continue...") # TASK 8 # TODO: Answer the following question male, female = count_gender(data_list) print("\nTASK 8: Why the following condition is False?") print("male + female == len(data_list):", male + female == len(data_list)) answer = "Because there are len(data_list) - (935854 + 298784) = 316868 entries where gender is not available." print("Answer:", answer) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert answer != "Type your answer here.", "TASK 8: Write your own answer!" # ----------------------------------------------------- input("Press Enter to continue...") # Let's work with the trip_duration now. We cant get some values from it. # TASK 9 # TODO: Find the Minimum, Maximum, Mean and Median trip duration. # You should not use ready functions to do that, like max() or min(). def get_median(data): """ Calculate the median value of a list of floats. Args: data: The list of floats Returns: The median value of a list """ middle = len(data) // 2 data.sort() if len(data) % 2 > 0: return data[middle] elif len(data) % 2 == 0: return (data[middle] + data[~middle]) / 2.0 trip_duration_list = column_to_list(data_list, 2) trip_duration_list = [float(duration) for duration in trip_duration_list] min_trip = float('inf') max_trip = 0 mean_trip = 0 median_trip = get_median(trip_duration_list) for item in trip_duration_list: duration = float(item) mean_trip += duration min_trip = duration if min_trip > duration else min_trip max_trip = duration if max_trip < duration else max_trip mean_trip = mean_trip / len(trip_duration_list) print("\nTASK 9: Printing the min, max, mean and median") print("Min: ", min_trip, "Max: ", max_trip, "Mean: ", mean_trip, "Median: ", median_trip) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert round(min_trip) == 60, "TASK 9: min_trip with wrong result!" assert round(max_trip) == 86338, "TASK 9: max_trip with wrong result!" assert round(mean_trip) == 940, "TASK 9: mean_trip with wrong result!" assert round(median_trip) == 670, "TASK 9: median_trip with wrong result!" # ----------------------------------------------------- input("Press Enter to continue...") # TASK 10 # Gender is easy because usually only have a few options. How about start_stations? How many options does it have? # TODO: Check types how many start_stations do we have using set() user_types = set(column_to_list(data_list, 3)) print("\nTASK 10: Printing start stations:") print(len(user_types)) print(user_types) # ------------ DO NOT CHANGE ANY CODE HERE ------------ assert len(user_types) == 582, "TASK 10: Wrong len of start stations." # ----------------------------------------------------- input("Press Enter to continue...") # TASK 11 # Go back and make sure you documented your functions. Explain the input, output and what it do. Example: # def new_function(param1: int, param2: str) -> list: """ Example function with annotations. Args: param1: The first parameter. param2: The second parameter. Returns: List of X values """ input("Press Enter to continue...") # TASK 12 - Challenge! (Optional) # TODO: Create a function to count user types without hardcoding the types # so we can use this function with a different kind of data. print("Will you face it?") answer = "yes" def count_items(column_list): """ Counts distinct types in a list. Args: column_list: The list to count items from Returns: A list of the distinct types and a list of each respective count """ item_types = list(set(column_list)) count_items = [0] * len(item_types) for item in column_list: for i, atype in enumerate(item_types): if atype == item: count_items[i] += 1 break return item_types, count_items if answer == "yes": # ------------ DO NOT CHANGE ANY CODE HERE ------------ column_list = column_to_list(data_list, -2) types, counts = count_items(column_list) print("\nTASK 11: Printing results for count_items()") print("Types:", types, "Counts:", counts) assert len(types) == 3, "TASK 11: There are 3 types of gender!" assert sum(counts) == 1551505, "TASK 11: Returning wrong result!" # ----------------------------------------------------- # -------------------- EXTRA TASKS -------------------- # EXTRA TASK #1 Plot a histogram of the age distribution def get_duration_by_age(data_list, min_age=0, max_age=120): """ Calculates the age for the entries where Birth Year is available, and create a tuple containing age and trip duration. Args: data_list: The data matrix min_age: A threshold for the minimum age min_age: A threshold for the maximum age Returns: A list of tuples formed by age and trip duration """ results = [] current_year = dt.datetime.now().year for row in data_list: birth_year = row[-1] if birth_year == '': continue age = current_year - round(float(birth_year)) # Filter by min and max ages if age > max_age or age < min_age: continue trip_duration = round(float(row[2])) results.append((age, trip_duration)) return results duration_by_age_lst = get_duration_by_age(data_list) ages_lst, duration_lst = zip(*duration_by_age_lst) # Plot Histogram from 0 to 120 years old plt.hist(ages_lst, bins=50, color='green', edgecolor='black') plt.ylabel('Quantity') plt.xlabel('Age') plt.title('Histogram of Age Distribution') plt.show(block=True) # From the histogram we conclude that there aren't many records # outside the range of 18 to 70 years old # Let's plot another histogram within those constraints duration_by_age_lst = get_duration_by_age(data_list, min_age=18, max_age=70) ages_lst, duration_lst = zip(*duration_by_age_lst) plt.hist(ages_lst, bins=50, color='green', edgecolor='black') plt.ylabel('Quantity') plt.xlabel('Age') plt.title('Histogram of Age Distribution') plt.show(block=True) # Task: Plot the average duration trip per age using a bar chart count_by_age = count_items(ages_lst) mean_duration_by_age = [] for i, age in enumerate(count_by_age[0]): duration_sum_by_age = sum([item[1] for item in duration_by_age_lst if item[0] == age]) mean = duration_sum_by_age // count_by_age[1][i] mean_duration_by_age.append((age, round(mean))) x = [i[0] for i in mean_duration_by_age] y = [i[1] for i in mean_duration_by_age] plt.bar(x, y) plt.ylabel('Average Trip Duration') plt.xlabel('Age') plt.title('Bar Chart of Average Trip Duration by Age') plt.show(block=True)
28dbe8f55fc17efe8204634256f0afff65664e04
sptuan/RL-playground
/01_Q-learning/ex2/main.py
1,648
4.03125
4
""" Reinforcement learning maze example. This script is our main script, in which a bike driver tries to arrive at FINAL POINT. This script is modified from https://morvanzhou.github.io/tutorials/ """ from env_tk import Maze from RL_brain import QLearningTable def update(): for episode in range(10000): # initial observation # return state, format "A B C ..." action_space = env.action_space observation = env.reset() while True: # fresh env, tkinter env.render() # RL choose action based on observation #while True: action = RL.choose_action(str(observation)) if action == 0: action_step = 'UP' elif action == 1: action_step = 'DOWN' elif action == 2: action_step = 'RIGHT' elif action == 3: action_step = 'LEFT' #if action_step in action_space: # break # RL take action and get next observation and reward observation_, reward, done, action_space = env.step(action_step) # RL learn from this transition RL.learn(str(observation), action, reward, str(observation_)) # swap observation observation = observation_ # break while loop when end of this episode if done: break # end of game print('game over') env.destroy() if __name__ == "__main__": env = Maze() RL = QLearningTable(actions=list(range(4))) env.after(50, update) env.mainloop()
36bdabd0f343ca80fd00888bec8ef7f706477edf
mrmattuschka/python-lecture-mobi-17
/exercises_3/task_1/task_1_d.py
2,122
4.1875
4
# Task 1d: get counts statistics for the sequence dna_seq = "GATTACA" rna_seq = "GAUUACA" permitted_letters = "ATCGU" seq_list = [dna_seq, rna_seq] for seq in seq_list: print("Validating sequence:", seq) seq = seq.upper() for letter in seq: if not letter in permitted_letters: print("Sequence invalid, contains invalid letters!") break else: if not ('U' in seq and 'T' in seq): if 'U' in seq: print("Sequence is RNA") elif 'T' in seq: print("Sequence is DNA") else: print("Impossible to determine whether sequence is RNA or DNA!") continue # This will stop further execution of the current iteration and jump to the next iteration of the containing loop # (i.e. go to next sequence) else: print("Sequence invalid, contains both U and T!") continue # same as above # After passing the above checks, create statistics for each base stats_dict = {} # Create an empty dictionary for the statistics # As we want to treat both DNA and RNA, we better create this dictionary dynamically to fit the possible bases for letter in seq: # Most simple approach (however it's quite redundant) stats_dict[letter] = 0 # Additional approach that will only set the entries for each unique letter: for letter in set(seq): stats_dict[letter] = 0 # Third approach, using a comprehension, making the whole thing a one-liner # for comprehensions, check LP part IV, chapter 20, super useful stuff - while not of relevance for the exam I suppose stats_dict = {letter:0 for letter in set(seq)} for letter in seq: stats_dict[letter] += 1 sequence_length = len(seq) # The length of a string (or any other iterable, such as lists) can easily be determined using len() print("Counts for each base:", stats_dict) print("Total length of the sequence:", sequence_length)
7198a98c34a433054030e673a2f7ab640f348f4f
Anirudh-Muthukumar/Python-Code
/BFS.py
750
3.984375
4
class Node: def __init__(self, key): self.val = key self.left = None self.right = None def bfs(root): if root is None: return # create a queue queue = [] dis = [] temp = [root.val] dis.append(temp) queue.append(root) while len(queue)>0: print(queue[0].val) temp = queue[0].val dis.append(temp) node = queue.pop(0) if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) dis.append() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) bfs(root)
d0cfa4c2d10a6da6dad9a89a06a43864602a642e
kevyang1004/LPTHW
/mygame.py
2,624
4.09375
4
from sys import exit def first_floor(): print "There is the way to go the office" print "There is the way to go to the basement" print "There is the way to go to second floor" print "Where do you want to go?" choice = raw_input("> ") if choice == "office": print "No one is there" office() elif choice == "basement": print "All the SCS students and faculties are in chapel" basement() elif choice == "second floor": print "There is the elementary school" second_floor() else: dead("You're kicked out of school!") def office(): print "Suddenly, two dogs are trying to attack you" print "Are you going to fight or run away?" choice = raw_input("> ") if choice == "run away": print "You just survived from the attack" first_floor() else: dead("They bite you") def basement(): print "Mr.Olinda comes and tells you to be in the chapel" print "Are you going to seat or go out?" choice = raw_input("> ") if choice == "seat": print "Pastor Johnson is having his speech!" print "You just got message from him" print "You're saved!" print "Chapel just finished" first_floor() else: dead("Pastor Johnson just called your name!") def second_floor(): print "some elementary students are asking you to hang out with them." print "What are you going to do?" choice = raw_input("> ") if choice == "hang out": print "You just got extra points from elementary teachers." third_floor() else: dead("They start to cry, so teachers come out and you are in trouble") def third_floor(): print "The door is locked" print "Are you going to break the door or go up?" choice = raw_input("> ") if choice == "go up": print "You're in the roof" roof() else: dead("All the teachers are coming up because of you. You're doomed hahaha") def roof(): print "There is a helicopter waitin for you!" print "Are going to take in or just ignore?" choice = raw_input("> ") if choice == "take in": print "Welcome! you're in the special force from now on!" exit(0) else: dead("The building is just destroyed..") def dead(why): print why, "I'm sorry, good bye" exit(0) def start(): print "You are in front of the SCS building" print "Do you want to go in or not?" choice = raw_input("> ") if choice == "Yes": first_floor() else: dead("You just got all F!") start()
9dde11bb2c8340fd79a7e1cc8fb0f1f1ddfcb913
Hiten-98/Password-Manager-Using-Python
/main_password_manager.py
4,059
3.59375
4
from tkinter import * from tkinter import messagebox import random import json GREY = "#DCDCDC" #Password Generator def generate_password(): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+'] nr_letters = random.randint(8, 10) nr_symbols = random.randint(2, 4) nr_numbers = random.randint(2, 4) password_letters = [random.choice(letters) for _ in range(nr_letters)] password_numbers = [random.choice(numbers) for _ in range(nr_numbers)] password_symbols = [random.choice(symbols) for _ in range(nr_symbols)] password_list = password_letters + password_numbers + password_symbols random.shuffle(password_list) password = "".join(password_list) password_entry.insert(0,password) print(f"Your password is: {password}") #Saving data to file def save(): website = website_entry.get() email = email_entry.get() password = password_entry.get() new_data = { website: { "email": email, "password": password, } } if len(website) == 0 or len(email) == 0 or len(password) == 0: messagebox.showinfo(title="OOPS",message="Please make sure you haven't left any fields empty") else: try: with open("data.json","r") as data_file: #Reading old data data = json.load(data_file) except FileNotFoundError: with open("data.json","w") as data_file: json.dump(new_data,data_file,indent=3) else: #Updating new data with old data data.update(new_data) with open("data.json","w") as data_file: #Writing data json.dump(data,data_file, indent=3) finally: website_entry.delete(0,END) email_entry.delete(0,END) password_entry.delete(0,END) def find_password(): website = website_entry.get() try: with open("data.json") as data_file: data = json.load(data_file) except FileNotFoundError: messagebox.showinfo(title="Error",message="This data does not exist") else: if website in data: email = data[website]["email"] password = data[website]["password"] messagebox.showinfo(title=website,message=f"Email: {email}\nPassword: {password}") window =Tk() window.title("Password Manager") window.config(padx=20,pady=20,bg=GREY) canvas = Canvas(width = 225, height = 225,bg=GREY,highlightthickness=0) image = PhotoImage(file="images-removebg-preview.png") canvas.create_image(111,111,image=image) canvas.grid(column=1,row=0) #Labels website_label = Label(text="Website: ",font = ("Aerial",12,"normal"),bg=GREY) website_label.grid(column=0,row=1) email_label = Label(text="Email/Username: ",font = ("Aerial",12,"normal"),bg=GREY) email_label.grid(column=0,row=2) password_label = Label(text="Password: ",font = ("Aerial",12,"normal"),bg=GREY) password_label.grid(column=0,row=3) #Entry website_entry = Entry(width = 35) website_entry.grid(column=1,row=1) website_entry.focus() email_entry = Entry(width = 35) email_entry.grid(column=1,row=2) password_entry = Entry(width = 35) password_entry.grid(column=1,row=3) #Buttons generate_password = Button(text="Generate Password",width=25,command = generate_password) generate_password.grid(column=2,row=3) add_password = Button(text="Add",width=30, command = save) add_password.grid(column=1,row=4) search_button = Button(text="Search",width=25, command = find_password) search_button.grid(column=2,row=1) window.mainloop()
95c7b8be7bee37a6272df4199a3257b1c852c053
ghostassault/AutomateTheBoringWithPython
/Projects/combinePdfs.gyp
1,468
3.671875
4
#Combine select Pages from many PDFs #This program allows you to customize which pages you want in the combined PDF #At a high level this is what the program will do #TODO: Find all PDF files in the currnt working directory #TODO:Sort the filenames so The PDFs are added in order. #TODO:Write each page, excluding the first page, of each PDF to the output file #TODO:Call os.listdir() to find all the files in the working directory and remove any on-PDf files #TODO:Call Python's sort() list method to alphabetize the filenames #TODO:Create a PdfFileWriter object for the output PDF #TODO:Loop over each Pdf file, creating a PdfFileReader object for it #TODO:Loop over each page(except the first) in each Pdf file #TODO:Add the pages to the output PDF #TODO:Write the output Pdf to a file named allminutes.pdf import PyPDF2, os pdfFiles = [] for filename in os.listdir('.'): if filename.endswith('.pdf'): pdfFiles.append(filename) pdfFiles.sort(key/str.lower) pdfWriter = PyPDF2.PdfFileWriter() #TODO: Loop through all the PDF files. for filename in pdfFiles: pdfFileObj= open(filename, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) #TODO: Loop through all the pages (except the first) and them. for pageNum in range(1, pdfReader.numPages): pageObj = pdfReader.getPage(pageNum) pdfWriter.addPage(pageObj) #TODO: Save the resulting PDF to a file. pdfOutput = open('allminutes.pdf', 'wb') pdfWriter.write(pdfOutput) pdfOutput.close()
e0f7151db0a5cdd844399ca669f8bc8deffa0170
JPWS2013/SoftDes_Project
/trace_playback.py
1,107
4
4
import time import math import numpy class Trace(object): """ Trace is a class that inherits from object and provides methods for simulating data from sensors. For the purposes of the project for the class Software Design, Fall 2013, this module only simulates the data from a hall effect sensor """ def halleffect(self): """ Takes a Trace object and returns a rate of rotation in revolutions per minute This function is supposed to mimic the data which would be read from a hall effect sensor. For convenience, the data this function returns is revolutions per minute instead of a voltage because data processing for a hall effect sensor was not known at the time of writing. """ current_time=time.time()%60 #This current_time is used in a sine function to generate hall effect sensor data z=3800*(math.sin(current_time*math.pi/30)) #Assumes maximum number of revolutions per minute is 3800rpm return abs(z) if __name__ == '__main__': trace=Trace() print trace.halleffect('accelerometer')
9984765d81a45fd68c31346f38a31d5953da6fc5
maryammouse/ud036
/random_builtin_abs.py
350
4.03125
4
# the assignment is to look at the built in python function documentation # pick a function to use and write a program using it. # here is mine: def is_absolute(number): if number == abs(number): print True else: print False # a few test cases is_absolute(3) is_absolute(-3) is_absolute(141414) is_absolute(-13431413)
008c2fa5630fb7bba2e3e5da20db884c7ff8a26e
gangyou/python_execrise
/magicmethod/functional_list.py
1,020
3.75
4
# coding=utf-8 class FunctionalList(object): def __init__(self, values=None): if values is None: self.values = [] else: self.values = values def __len__(self): return len(self.values) def __getitem__(self, key): # may raise a KeyError if the key is not exists return self.values[key] def __setitem__(self, key, value): self.values[key] = value def __delitem__(self, key): del self.values[key] def __iter__(self): return iter(self.values) def __reversed__(self): return FunctionalList(reversed(self.values)) def append(self, value): self.values.append(value) return self def head(self): return self.values[0] def tail(self): return self.values[1:] def init(self): return self.values[:-1] def last(self): return self.values[-1] def drop(self, n): return self.values[n:] def take(self, n): return self.values[:n] if __name__ == '__main__': fl = FunctionalList() fl.append(1).append(2).append(3) for x in fl: print x print fl[2] print fl.take(2)
8f41c59fb973c5ec442de4d30687e5629496b85e
WillianJefferson/teste
/Aula 5/Aula 5 - Tarefa_7.py
496
3.734375
4
def valor_pagamento(valor, dias_a): if (valor < 0): return None if (dias_a > 0): multa = valor * 0.03 adicional = valor * (dias_a * 0.01) return valor + multa + adicional else: return valor valor = 1 while (valor != 0): valor = float(input('Informe o valor da prestação: ')) if (valor != 0): dias_a = int(input('Informe a quantidade de dias de atraso: ')) print("Valor a ser pago: ", valor_pagamento(valor, dias_a))
1a18c17f5949bd7fb3169928031ad1fa86838b7a
Shristipatne/github-demo
/math.py
247
3.8125
4
#addition def add(x,y): return x+y #subtract def subtract(x,y): if y>x: return negative_value_error else return x-y #multiply def multiply(x,y): return x*y #divide def divide(x,y): return x/y
ce94cc05ec40c1ff696c14610a57a941d2ddd967
Daisyhaxx/Cryptography-App
/codes/main.py
1,260
3.53125
4
import onetimepad from tkinter import * root = Tk() root.title("Python Cryptography App") root.geometry("700x200") def encryptMessage(): pt = e1.get() # * encrypt function ct = onetimepad.encrypt(pt, 'random') e2.insert(0, ct) def decryptMessage(): ct1 = e3.get() # * decrypt function pt1 = onetimepad.decrypt(ct1, 'random') e4.insert(0, pt1) # * Etkileşim menüleri label1 = Label(root, text ='Text:') label1.grid(row = 10, column = 1) label2 = Label(root, text ='Encrypted Text: ') label2.grid(row = 11, column = 1) l3 = Label(root, text = "Encrypted Text: ") l3.grid(row = 10, column = 13,) l4 = Label(root, text = "Text: ") l4.grid(row = 11, column = 13) # * bilgi girişleri ve yerleri e1 = Entry(root) e1.grid(row = 10, column = 2, pady=20) e2 = Entry(root) e2.grid(row = 11, column = 2, pady=20) e3 = Entry(root) e3.grid(row = 10, column = 15, pady=20) e4 = Entry(root) e4.grid(row = 11, column = 15, pady=20) # * encrypt button ent = Button(root, text = "Encrypt", bg ="red", fg ="white", command = encryptMessage) ent.grid(row = 13, column = 2) # * decrypt button b2 = Button(root, text = "Decyrpt", bg ="green", fg ="white", command = decryptMessage) b2.grid(row = 13, column = 15) root.mainloop()
8f753e7c5d2e52b587a4865734d5235139effd74
AlexMetodieva/SoftUni
/toy_shop.py
665
3.53125
4
excursion = float(input()) puzzles = int(input()) dolls = int(input()) bears = int(input()) minions = int(input()) trucks = int(input()) sum_puzzles = puzzles * 2.6 sum_dolls = dolls * 3 sum_bears = bears * 4.1 sum_minions = minions * 8.2 sum_trucks = trucks * 2 total_sum = sum_puzzles + sum_dolls + sum_bears + sum_minions + sum_trucks num = puzzles + dolls + bears + minions + trucks if num >= 50: total_sum = total_sum -(total_sum*0.25) rent = total_sum * 0.10 total_sum -= rent yes = total_sum - excursion no = excursion - total_sum if excursion <= total_sum: print(f"Yes! {yes:.2f} lv left.") else: print(f"Not enough money! {no:.2f} lv needed.")
a9dbbfc96e273875ecbca944ff13f2e02785ab69
fxyyy123/book_codes
/ch2/exercises/ans2_10.py
82
3.609375
4
sum = eval(input("Please Enter an Addition formula:")) print(f"The sum is {sum}.")
f14633fb648f8c092dbd7f7df20d3cb01451362b
kene111/DS-ALGOS
/Hackerrank and Leetcode/collections_deque.py
306
3.609375
4
from collections import deque n = int(input()) d = deque() for i in range(n): m = input().split() if m[0] == 'append': d.append(m[1]) if m[0] == 'appendleft': d.appendleft(m[1]) if m[0] == 'pop': d.pop() if m[0] == 'popleft': d.popleft() print(*d)
e4d51cebe30ca0fa1ea9724fa12eec10fcb5633b
crystalarnspiger/scripts
/test/palindrome.py
182
3.84375
4
import copy def palindrome(word): new_word = '' x = len(word) - 1 while x >= 0: new_word += word[x] x -= 1 if word == new_word: return True
fa113f93cb2a15aaed18ef7b1bdc2ee90f50e648
zaarabuy0950/assignment-3
/assign10.py
659
4.53125
5
"""10. Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case (i.e. this_is_camel_cased). Modify the function by adding an argument, separator, so it will also convert to the kebab case (i.e.this-is-camel-case) as well.""" def naming_style(string, seperator): glue = ' ' for i in range(1, len(string)): string = ''.join(glue + x if x.isupper() else x for x in string).strip(glue).split(glue) snake_case = "_".join(string).lower() kebab_case = seperator.join(string).lower() return snake_case, kebab_case print(naming_style('ThisIsCamelCased', '-'))
d98afb1dc83ad00bd5f8f287796ad67aafb4aacd
JoMaAlves/ArtesaoDeGrafos
/src/components/graph.py
10,528
3.546875
4
from components.prints import * from components.vertex import vertex class graph: def __init__(self, direc, weight): self.nodeList = [] self.edgeList = [] self.direc = direc self.weight = weight self.size = 0 # Adds a vertex def addNode(self): printAddNode() nodes = input() node_aux = nodes.strip().split(' ') if(nodes.strip() == ""): return 1 # Check if the nodes exist newNodes = [] for i in node_aux: check = False for j in self.nodeList: if(i == j.value): check = True if(not check): newNodes.append(i) if(len(self.nodeList)): for i in self.nodeList: i.addNewPaths(newNodes) allNodes = self.getNodes() + newNodes for i in newNodes: dicto = dict.fromkeys(allNodes) for j in allNodes: dicto[j] = [0,[]] self.nodeList.append(vertex(i, dicto)) printDone() # Creates Edges over a loop def addEdge(self): while 1: printAddEdge() nodes = input() # Breaks creation if there is no input if(nodes.strip() == ""): break nodes = nodes.strip().split(" ") # Checks if there were more then 1 vertex and corrects if not if(len(nodes) == 1): sec = "" while sec == "": print(" " * 24,end="") sec = input("Digite o segundo vertice: ") nodes.append(sec) # Checks if it is the same vertex if(nodes[0] == nodes[1]): printSameVertex() continue # Checks if both vertex exist and connect them with the node variables check = [False, False] node1 = None node2 = None for i in range(len(nodes)): if(i == 1 and check[0] == False): break for j in self.nodeList: if(nodes[i] == j.value): check[i] = True if(i): node2 = j else: node1 = j break # Checks if both vertex were found if(not check[0] or not check[1]): printNotFound() continue # Check if it is a paralel conection if(node1.checkEdges(node2, self.direc, self.weight)): printParalelEdge() continue # Adds the edge into the nodes edge lists according to weight and direction if(self.weight): # Gets the edge's weight while True: try: print(" " * 24,end="") new_weight = int(input("Digite o peso da aresta: ")) break except: continue self.edgeList.append( (new_weight, node1.value, node2.value) ) # A tuple is being used if there is a weight for the edge (vertex, weight) if(self.direc): node1.addNext( (node2, new_weight) ) node2.addPrevious( (node1, new_weight) ) self.createPaths(node1, node2, new_weight) else: node1.addEdge( (node2, new_weight) ) node2.addEdge( (node1, new_weight) ) else: if(self.direc): node1.addNext( node2 ) node2.addPrevious( node1 ) else: node1.addEdge( node2 ) node2.addEdge( node1 ) self.size += 1 printDone() def printGraph(self): printGraphMenu() answer = input().strip() if(answer == "1" or answer.capitalize() == "Lista de adjacencia"): vertex, destinies= self.getGraph(1) printAdjacencyList(vertex, destinies) elif(answer == "2" or answer.capitalize() == "Matriz de adjacencia"): vertex, binary = self.getGraph(2) printAdjacencyMatrix(vertex, binary) elif(answer == "3" or answer.capitalize() == "Lista de arestas"): edges, destinies = self.returnEdges() printListEdges(edges, destinies) # Gets the graph order def getOrder(self): printValue( "GetOrder", len(self.nodeList) ) # Gets the graph size def getSize(self): printValue( "GetSize", self.size ) # Gets the graph degree def getDegree(self): printDegree() vert= input().strip() # Get the degree of a vertex call its method getDegreeEdges() found = False answer, answer2 = None, None for i in self.nodeList: if(i.value == vert): answer, answer2 = i.getDegreeEdges(self.direc) found = True break # Breaks if the vertex was not found if(not found): printNotFound() return 1 # Checks if the graph is directed not if(self.direc): printGetDegree( self.direc, answer, answer2 ) else: printGetDegree( self.direc, answer ) # Gets the list of adjacency of a vertex def vertexAdjacencyList(self): printAdjListMenu() check = input().strip() # Search for the node and gets its list using its method listAdjacents() found = False for i in self.nodeList: if(i.value == check): i.listAdjacents(self.direc, self.weight) found = True break # If not found, breaks if(not found): printNotFound() return 1 # Checks the adjacency between two vertex def adjacencyCheck(self): printAdjCheckMenu() vertex = input().strip().split(" ") # Looks over a vertex, for the other one found = False for i in self.nodeList: if(i.value == vertex[0]): result = i.adjacencyCheck(vertex[1], self.direc, self.weight) found = True break # Breaks if not found if(not found): printNotFound() return 1 printAdjCheckResult(result) def getGraph(self, choice): list_values = [] list_table = [] max_size = 0 for i in self.nodeList: list_values.append(i.value) if(choice == 1): list_aux, size = i.getValuesList(self.direc, self.weight) if(size > max_size): max_size = size elif(choice == 2): list_aux = i.getMatrixAdj(self.direc, self.weight,self.nodeList) list_table.append( list_aux) if(choice == 1): for i in list_table: while(len(i) < max_size): i.append("") return list_values,list_table def returnEdges(self): list_weight = [] list_destinies = [] for i in self.edgeList: list_weight.append(str(i[0])) list_destinies.append( (i[1],i[2]) ) return list_weight,list_destinies def dijkstraAlgorithm(self): if(not self.direc or not self.weight): printDijkstraFail() return 1 printDijkstraMenu() nodes = input() # Breaks creation if there is no input if(nodes.strip() == ""): return 1 nodes = nodes.strip().split(" ") # Checks if both vertex were found if(len(nodes) == 2): check = [ self.checkNodeExists(nodes[0]), self.checkNodeExists(nodes[1]) ] if(check[0][0] and check[1][0]): printDijkstra(check[0][1], check[1][1].value) return 0 else: printNotFound() return 1 else: check = self.checkNodeExists(nodes[0]) if(check[0]): printDijkstra(check[1]) return 0 else: printNotFound() return 1 def checkNodeExists(self, node): for i in self.nodeList: if(node == i.value): return [True,i] return [False,i] def getNodes(self): nodes = [] for i in self.nodeList: nodes.append(i.value) return nodes def createPaths(self, node1, node2, value): if((node1.paths[node2.value][0] > value or node1.paths[node2.value][0] == 0)): node1.paths[node2.value][0] = value node1.paths[node2.value][1] = [node2.value] for target in self.nodeList: for nextEdge in target.nextEdges: for key in self.nodeList: if(key == target): continue if(nextEdge[0].paths[key.value] != [0,[]]): if(target.paths[key.value] == [0,[]] or target.paths[key.value][0] > (nextEdge[0].paths[key.value][0] + target.paths[nextEdge[0].value][0])): target.paths[key.value][0] = target.paths[nextEdge[0].value][0] + nextEdge[0].paths[key.value][0] target.paths[key.value][1] = target.paths[nextEdge[0].value][1] + nextEdge[0].paths[key.value][1] for prevEdge in target.prevEdges: for key in self.nodeList: if(key == target): continue if(target.paths[key.value] != [0,[]]): if(prevEdge[0].paths[key.value] == [0,[]] or prevEdge[0].paths[key.value][0] > (target.paths[key.value][0] + prevEdge[0].paths[target.value][0])): prevEdge[0].paths[key.value][0] = prevEdge[0].paths[target.value][0] + target.paths[key.value][0] prevEdge[0].paths[key.value][1] = prevEdge[0].paths[target.value][1] + target.paths[key.value][1]
5cbbfcf02882dac09c1752d64df96f74f69d4689
ISdawu/Python-study
/01 Guess01.py
305
3.703125
4
score = 0 print('guess the animals!') print('最大的树是什么树?') guess = input() if guess == '巨杉谢尔曼将军': print('回答正确!!!!!!!!!!') score = score + 1 else: print('回答错误' + '!!!!!!!!!!') print('得分:' + str(score))
183c5d0542c1ad71c03f0ab504d1beb4a9369524
thailanelopes/exercicios_em_python
/23exercicio.py
1,642
3.828125
4
#variáveis contador_total = 0 contator_sit_1 = 0 contator_sit_2 = 0 contator_sit_3 = 0 contator_sit_4 = 0 #entrada identificador = int(input("Informe a identificação: ")) #processamento/processamento while identificador != 0: print("1- Necessidade de esfera.") print("2- Necessita de limpeza.") print("3- Necessidade troca do cabo ou conector.") print("4- Quebrado ou inutilizado.") #entrada defeito = int(input("Informe o tipo de defeito: ")) #processamento if defeito == 1: contator_sit_1 = contator_sit_1 + 1 elif defeito == 2: contator_sit_2 = contator_sit_2 + 1 elif defeito == 3: contator_sit_3 = contator_sit_3 + 1 elif defeito == 4: contator_sit_4 = contator_sit_4 + 1 contador_total = contador_total + 1 #entrada identificador = int(input("Informe a identificação: ")) p1 = contator_sit_1 / contador_total * 100.0 p2 = contator_sit_2 / contador_total * 100.0 p3 = contator_sit_3 / contador_total * 100.0 p4 = contator_sit_4 / contador_total * 100.0 print("Quantidades de mouses: {0}".format(contador_total)) print(" SITUAÇÃO QUANTIDADE PERCENTUAL") print("1- Necessidade de esfera {0} {1:.2f}% ".format(contator_sit_1, p1)) print("2- Necessita de limpeza {0} {1:.2f}% ".format(contator_sit_2, p2)) print("3- Necessidade troca do cabo ou conector {0} {1:.2f}% ".format(contator_sit_3, p3)) print("4-Quebrado ou inutilizado {0} {1:.2f}% ".format(contator_sit_4, p4))
1dd083983de4f00d15edd3ea6bb56fb6344516aa
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/exercism/exercism-python-master/zebra-puzzle/zebra_puzzle.py
2,112
3.59375
4
from itertools import permutations def solution(): """Finds solutions to the zebra puzzle""" solutions = list(zebra_puzzle()) assert(len(solutions) == 1) return ("It is the %s who drinks the water.\n" "The %s keeps the zebra." %(solutions[0]['water'], solutions[0]['zebra'])) def zebra_puzzle(): """Iterator that finds all solutions to the zebra puzzle""" residents = 'Englishman, Spaniard, Ukranian, Japanese, Norwegian'.split(', ') orderings = list(permutations(residents)) first, _, middle, _, _ = (0, 1, 2, 3, 4) for (red, green, ivory, yellow, blue) in orderings: if red != 'Englishman': continue for order in orderings: if abs(order.index('Norwegian') - order.index(blue)) != 1: continue if order[0] != 'Norwegian': continue if order.index(green) - order.index(ivory) != 1: continue for (dog, snails, fox, horse, ZEBRA) in orderings: if dog != 'Spaniard': continue for (coffee, tea, milk, oj, WATER) in orderings: if order.index(milk) != middle: continue if coffee != green: continue if tea != 'Ukranian': continue for (OldGold, Kools, Chesterfields, LuckyStrike, Parliaments) in orderings: if OldGold != snails: continue if Kools != yellow: continue if abs(order.index(Chesterfields) - order.index(fox)) != 1: continue if abs(order.index(Kools) - order.index(horse)) != 1: continue if LuckyStrike != oj: continue if Parliaments != 'Japanese': continue yield { 'zebra': ZEBRA, 'water': WATER }
987f9a5bb1c9c82230c29dd433d6b2644e4c6163
TemitopeOladokun/My-Python-Notebook
/Emoji Converter.py
205
3.734375
4
message = input (">") words = message.split(' ') emojis = { ":)" : "😊", ":(" : "☹" } converter = "" for ch in words: converter += emojis.get(ch, ch) + " " print(converter)
36710adc0bf78650eacd3cf340054b43be2a8457
jeffrey-hong/interview-prep
/Daily Coding Problem/Problem16.py
855
3.796875
4
""" You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API: record(order_id): adds the order_id to the log get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N. """ class Log(object): def __init__(self, n): self.n = n self._log = [] self._cur = 0 def record(self, order_id): if len(self.log) == self.n: self._log[self._cur] = order_id else: self._log.append(order_id) self._cur = (self._cur + 1) % self.n def get_last(self, i): return self._log[self._cur - i] """ This structure is called a ring buffer. Uses index wrapping to avoid having to shift elements of array on pop, which is O(N). This implementation is thus better because record and get_last now have constant time """
2852253a1a4727a31a22ed0f1070b4700974d21f
maximkfd/ibfk
/public_key_gen.py
1,163
3.578125
4
import random # Bob generates these. # So Alice will encrypt m with PK and send it (M) to bob for sign, # so Bob will return M and sign to Alice, # and she will recover her message. Does she need it? Probably no, she only needs sign to send it further. # and what is further? # So now Alice has m and sign for M (and m too). What do she do now? # She will send it to 3rd person for validation. Right. # And Charlie will receive m and sign. So she needs to know SK to check the sign. # Let's do it! with open("keygen.in", 'r') as f: n = int(f.readline()) q = -1 for i in range(2, n): if pow(i, n - 1) % n == 1: q = i break if q == -1: print("ALERT") exit(1) else: print("q = " + str(q)) b = random.randint(1, n - 1) c = pow(q, b) % n pk = [n, q, c] sk = [b] print("Public key = " + str(pk)) print("Secret key = " + str(sk)) with open("pk", 'w') as f: print(n, q, c, end=" ", file=f) with open("sk", 'w') as f: print(b, file=f) print(n, q, c, end=" ", file=f) # такое минимальное число k, что g^(fi(m)) = 1 (mod m) # fi(m) - минимальное число, что g^(fi(m)) == 1 (mod m)
d83c407a055812a4b889e4585db0adf225a9943f
InseongJoe/SoftwareDesign
/hw4/random_art.py
3,362
3.921875
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 11:34:57 2014 @author: pruvolo """ # you do not have to use these particular modules, but they may help from math import * from random import * import Image def build_random_function(min_depth, max_depth): # your doc string goes here '''This function takes in the minimum depth and the maximum depth and outputs a random function of random depth.''' # your code goes here i = randint(min_depth,max_depth) if i == 1: return choice([["x"],["y"]]) else: return choice([["p1",build_random_function(i-1,i-1),build_random_function(i-1,i-1)],["p2",build_random_function(i-1,i-1),build_random_function(i-1,i-1)],["prod",build_random_function(i-1,i-1),build_random_function(i-1,i-1)],["cos_pi",build_random_function(i-1,i-1)],["sin_pi",build_random_function(i-1,i-1)],["avg",build_random_function(i-1,i-1),build_random_function(i-1,i-1)],["sqr",build_random_function(i-1,i-1)]]) def evaluate_random_function(f, x, y): # your doc string goes here '''This function takes in the random function created and the x and y values and outputs the evaluation of the random function using the x and y.''' # your code goes here if f[0] == "x": return x elif f[0] == "y": return y else: if f[0] == "sin_pi": return sin(pi* evaluate_random_function(f[1] ,x,y )) elif f[0] == "prod": return evaluate_random_function(f[1],x,y)*evaluate_random_function(f[2],x,y) elif f[0] == "cos_pi": return cos(pi*evaluate_random_function(f[1],x,y)) elif f[0] == "avg": return (evaluate_random_function(f[1],x,y)+evaluate_random_function(f[2],x,y))/2.0 elif f[0] == "sqr": return evaluate_random_function(f[1],x,y)**2 elif f[0] == "p1": return evaluate_random_function(f[1],x,y) elif f[0] == "p2": return evaluate_random_function(f[2],x,y) def remap_interval(val, input_interval_start, input_interval_end, output_interval_start, output_interval_end): """ Maps the input value that is in the interval [input_interval_start, input_interval_end] to the output interval [output_interval_start, output_interval_end]. The mapping is an affine one (i.e. output = input*c + b).""" # your code goes here return (val-input_interval_start)/float((input_interval_end - input_interval_start))*(output_interval_end - output_interval_start) + output_interval_start #make image here #make random functions for red green and blue r_func = build_random_function(2,3) g_func = build_random_function(3,5) b_func = build_random_function(2,6) #create image and pixels im = Image.new("RGB",(350,350)) pix = im.load() #set x and y intervals to (-1,1) and then each color to (0,255) for x in range(0,350): xnew = remap_interval(x,0,350,-1,1) for y in range(0,350): ynew = remap_interval(y,0,350,-1,1) r = evaluate_random_function(r_func,xnew,ynew) g = evaluate_random_function(g_func,xnew,ynew) b = evaluate_random_function(b_func,xnew,ynew) rc = remap_interval(r,-1,1,0,255) gc = remap_interval(g,-1,1,0,255) bc = remap_interval(b,-1,1,0,255) pix[x,y] = (int(rc),int(gc),int(bc)) #save image im.save("img3.JPEG")
d2e1d508c2ef7e3cc94ef351483f38c4e79f950f
ChangxingJiang/LeetCode
/1601-1700/1634/1634_Python_1.py
1,489
3.90625
4
class PolyNode: def __init__(self, x=0, y=0, next=None): self.coefficient = x self.power = y self.next = next class Solution: def addPoly(self, poly1: 'PolyNode', poly2: 'PolyNode') -> 'PolyNode': ans = node = PolyNode(0, 0) while poly1 and poly2: if poly1.power > poly2.power: node.next = PolyNode(poly1.coefficient, poly1.power) node = node.next poly1 = poly1.next elif poly1.power < poly2.power: node.next = PolyNode(poly2.coefficient, poly2.power) node = node.next poly2 = poly2.next else: coefficient = poly1.coefficient + poly2.coefficient if coefficient != 0: node.next = PolyNode(coefficient, poly1.power) node = node.next poly1 = poly1.next poly2 = poly2.next if poly1: node.next = poly1 if poly2: node.next = poly2 return ans.next if __name__ == "__main__": p1 = PolyNode(1, 1) p2 = PolyNode(1, 0) print(Solution().addPoly(p1, p2)) p13 = PolyNode(3, 0) p12 = PolyNode(4, 1, p13) p11 = PolyNode(2, 2, p12) p23 = PolyNode(-1, 0) p22 = PolyNode(-4, 1, p23) p21 = PolyNode(3, 2, p22) print(Solution().addPoly(p1, p2)) p1 = PolyNode(1, 2) p2 = PolyNode(-1, 2) print(Solution().addPoly(p1, p2))