blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
641003405cc28936693ac4ba623522af5d129e12
Putitamos28/CP3-Putita-Mosikarat
/Lec104_Putita_M.py
514
3.921875
4
class Customer: name = "" lastname = "" age = 0 def addCart(self): print("Added to ",self.name, self.lastname,"'s cart", ) customer1 = Customer() customer1.name = "Putita" customer1.lastname = "Mosikarat" customer1.age = 21 customer1.addCart() customer2 = Customer() customer2.name = "Dhi" customer2.lastname = "Geramethakul" customer2.age = 21 customer2.addCart() customer3 = Customer() customer3.name = "Gochakon" customer3.lastname = "Saengjun" customer3.age = 21 customer3.addCart()
d37bcd293b12c25641657cac90ce3b8605bd0723
himanshu2922t/FSDP_2019
/DAY-03/frequency.py
313
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 6 09:06:01 2019 @author: Himanshu Rathore """ input_string = input("Enter a string: ") frequency_dict = {} for char in input_string: if char not in frequency_dict: frequency_dict[ char ] = 1 else: frequency_dict[ char ] += 1 print(frequency_dict)
5204f30b0a8fcb2b3dc0da74f6e4190f07c85a9b
norlyakov/algorithms_battlefield
/arrays/move_zeroes.py
807
4.1875
4
""" Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ from typing import List def moveZeroes(nums: List[int]) -> None: length = len(nums) last_non_zero = -1 cur = 0 while cur < length: if nums[cur] != 0: last_non_zero += 1 elem = nums[last_non_zero] nums[last_non_zero] = nums[cur] nums[cur] = elem cur += 1 def main(): orig_list = [0, 1, 0, 3, 12] moveZeroes(orig_list) assert orig_list == [1, 3, 12, 0, 0] if __name__ == '__main__': main()
e713bb2ecafa1003d56c8c9879be65e4e4ac6e53
wenty2015/AdventOfCode
/day1_2.py
277
3.65625
4
file = open('day1_1.txt','r') str = file.read() i = 0 stairs = 0 length = len(str) while stairs >= 0 and i < length : if str[i] == '(': stairs += 1 else: stairs -= 1 i += 1 if i = length : print('never enter the basement') else: print(i)
16c9a095030cb2e7e4908360574a683b780d9289
KritoCC/Sword
/ex12.py
2,055
4.125
4
# 习题十二 # 前一题用 print() 打印问题,用input() 回答问题有点麻烦不是么? # input() 就是要用户输入内容的,何不把提示功能加进去省去写 print() 语句的麻烦。 age = input("How old are you? ") height = input("How tall are you? ") weight = input("How much do you weight? ") print("So, you're %s old, %s tall and %s heavy." % (age, height, weight)) # pydoc-文档生成工具 # 用途: # 是python自带的一个文档生成工具,使用pydoc可以很方便的查看类和方法结构 # python中pydoc模块可以从python代码中获取docstring,然后生成帮助信息。 # 主要用于从python模块中自动生成文档,这些文档可以基于文本呈现的、 # 也可以生成WEB页面的,还可以在服务器上以浏览器的方式呈现! # 方法: # pydoc <name> ... # 显示关于某事的文本文档。 <name>可以是a的名称 Python关键字,主题,功能,模块或包, # 或点缀引用模块或模块中的类或函数包。 # 如果<name>包含'\\',则将其用作a的路径 Python源文件到文档。 # 如果名称是'关键字','主题',或“模块”,显示这些内容的列表。 # pydoc -k <keyword> # 在所有可用模块的概要行中搜索关键字。 # pydoc -n <hostname> # 使用给定的主机名启动HTTP服务器(默认值:localhost)。 # pydoc -p <port> # 在本地计算机上的给定端口上启动HTTP服务器。港口 # 数字0可用于获取任意未使用的端口。 # pydoc -b # 在任意未使用的端口上启动HTTP服务器并打开Web浏览器 # 以交互方式浏览文档。此选项可用于与-n和/或-p组合。 # pydoc -w <name> ... # 将模块的HTML文档写入当前文件目录。如果<name>包含'\\',则将其视为文件名; # 如果它命名一个目录,为所有内容编写文档。 # 巩固练习 # 在命令行界面下运行你的程序,然后在命令行输入 python -m pydoc input # 输入 q 退出 pydoc # 使用 pydoc 看看 open、file 、 os 和 sys 的含义。
4ccae8bb1303c8c7c019a1f69f06665178984509
BerkeleyPlatte/competitiveCode
/generate_hashtag.py
759
3.953125
4
# The marketing team is spending way too much time typing in hashtags. # Let's help them with our own Hashtag Generator! # Here's the deal: # It must start with a hashtag (#). # All words must have their first letter capitalized. # If the final result is longer than 140 chars it must return false. # If the input or the result is an empty string it must return false. def generate_hashtag(s): capd_list = [each for each in s.title().strip()] for each in capd_list: if each == ' ': capd_list.remove(each) final = '#' + ''.join(capd_list).strip() new_final = ''.join(final.split()) if len(new_final) > 140 or s == '': return False else: return new_final print(generate_hashtag('Codewars '))
b83bbd529e3269a7292acf2e67f1461935f008d9
Ahmed--Mohsen/leetcode
/binary_tree_paths.py
991
4.0625
4
""" Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): """ :type root: TreeNode :rtype: List[str] """ def binaryTreePaths(self, root): result = [] # base case if not root: return result self.dfs(root, [], result) return result def dfs(self, current, path, result): # visit current root path.append(current.val) # current node is a leaf node if not current.left and not current.right: leaf_path = "->".join( str(p) for p in path ) result.append(leaf_path) # visit children if current.left: self.dfs(current.left, path, result) if current.right: self.dfs(current.right, path, result) # backtrack from current node path.pop(-1)
02de6055c0789a8cf1f0a9dcba500b7936578c24
enriquedcs/Algorithm
/Algorithm/Largest_sum_array.py
407
3.75
4
#Question 6 # Largest sum subarray # Algorith to find the sum of contiguos subarray def kadane_algorith(nums): max_global = nums[0] max_current = nums[0] for i in range (1,len(nums)): max_current = max(nums[i], max_current+nums[i]) if max_current > max_global: max_global = max_current return max_current nums = [1,-2,3,4,-5,8] print(kadane_algorith(nums))
b682b259f73afe186bb338a85772f3d56df90c69
SemajDraw/leetcode_solutions
/tree/searching.py
4,547
4.03125
4
from typing import List class Node: def __init__(self, val): self.val = val self.left = None self.right = None class Tree: def __init__(self): self.head = None def buildTree(self, nodesVals: List[int]): if len(nodesVals) <= 0: return 'Enter a non empty array' if self.head is None: self.createHeadNode(nodesVals[0]) del nodeVals[0] for val in nodeVals: self.insertNode(val, self.head) def insertNode(self, val: int, node: Node) -> None: if val <= node.val: if node.left is None: node.left = Node(val) else: self.insertNode(val, node.left) elif val > node.val: if node.right is None: node.right = Node(val) else: self.insertNode(val, node.right) def createHeadNode(self, val): self.head = Node(val) def printInOrder(self, node): if node is None: return self.printInOrder(node.left) print(node.val) self.printInOrder(node.right) class DepthFirstSearch: """ In order (Left,Root,Right) """ def inOrderSearch(self, node: Node, val): if node is None: return self.inOrderSearch(node.left, val) print(node.val) if node.val == val: print("Node with value found at ", node) return True self.inOrderSearch(node.right, val) """ Pre order (Root,Left,Right) """ def preOrderSearch(self, node: Node, val: int): if node is None: return False if node.val == val: print("Node with value found at ", node) return True print(node.val) self.preOrderSearch(node.left, val) self.preOrderSearch(node.right, val) """ Post order (Left,Right,Root) """ def postOrderSearch(self, node: Node, val: int): if node is None: return self.postOrderSearch(node.left, val) self.postOrderSearch(node.right, val) print(node.val) if node.val == val: print("Node with value found at ", node) return True class BreathFirstSearch: def search(self, node: Node, val: int): if node is None: print("Please enter a valid tree") return False height = self.height(node) for i in range(1, height): self.searchLevel(node, val, i) def searchLevel(self, node: Node, val: int, level: int): if node is None: return if node.val == val: print("Node with value found at: ", node) return True print(node.val) if level > 1: self.searchLevel(node.left, val, level - 1) self.searchLevel(node.right, val, level - 1) def height(self, node): if node is None: return 0 else: left_height = self.height(node.left) + 1 right_height = self.height(node.right) + 1 return left_height if left_height > right_height else right_height def binarySearch(self, node: Node, val: int) -> bool: if node is None: print("No node contains this value") return False if val == node.val: print("Found at ", node) return True print(node.val) if val < node.val: return self.binarySearch(node.left, val) if val > node.val: return self.binarySearch(node.right, val) if __name__ == '__main__': nodeVals = [20, 15, 11, 9, 41, 32, 30, 2, 3, 8, 26, 22, 1] tree = Tree() tree.buildTree(nodeVals) print("Printing tree in order") tree.printInOrder(tree.head) print("\nBinary search") tree.binarySearch(tree.head, 26) print("\nSearching tree in order") tree.DepthFirstSearch().inOrderSearch(tree.head, 26) print("\nSearching tree in pre order") tree.DepthFirstSearch().preOrderSearch(tree.head, 26) print("\nSearching tree in post order") tree.DepthFirstSearch().postOrderSearch(tree.head, 26) print("\nBreadth first search") tree.BreathFirstSearch().search(tree.head, 26)
5c72abe94262c36e64ee9235c3a8e88d09a0cb65
Anupya/leetcode
/hard/q239 slidingWindowMax.py
839
3.578125
4
# You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. # Return the max sliding window. import bisect class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: answers = [] start = 0 end = k slidingWindow = sorted(nums[:end]) answers.append(slidingWindow[-1]) while end < len(nums): del slidingWindow[bisect.bisect_left(slidingWindow, nums[start])] bisect.insort(slidingWindow, nums[end]) answers.append(slidingWindow[-1]) start+=1 end+=1 return answers
74c955e7e46fdfd87da388a1d770e0ffeec91304
colaso96/Hockey_Puck_Shooting_Robot_Capstone
/StepperMotor.py
1,598
3.65625
4
import random import math import time import numpy as np import RPi.GPIO as GPIO class StepperMotor: # Initializes a stepper motor given # int: direction - GPIO pin to control direction # int: step - GPIO pin to control the step def __init__(self, direction, step, delay): self.DIR = direction # Pin to control direction self.STEP = step # Pin to control the pulses self.delay = delay #0.0208 # Pulse time GPIO.setmode(GPIO.BOARD) # declare settings GPIO.setwarnings(False) # remove warnings # Set pins to outputs GPIO.setup(self.DIR, GPIO.OUT) GPIO.setup(self.STEP, GPIO.OUT) print("Stepper is live") # Method to spin the stepper motor # int: step_count - the number of steps to take # bool: direction - the direction (0 or 1) def spin(self, step_count, direction): GPIO.output(self.DIR, direction) # This sets direction pin to 0 or 1 print("Spinning ", step_count, " steps") # Pulses from 0 to step count for i in range(0, step_count): GPIO.output(self.STEP, GPIO.HIGH) time.sleep(self.delay) GPIO.output(self.STEP, GPIO.LOW) time.sleep(self.delay) def stepper_off(self): print("Stepper off") GPIO.cleanup() def test_stepper(self): stepper.spin(50, 0) time.sleep(1) stepper.spin(50, 1) time.sleep(1) stepper.stepper_off() #stepper = StepperMotor(38, 40) #stepper.test_stepper()
585b45e7a3ebe88843369bb913c274ba73e79ff0
jgerrish/nltk_ext
/pipelines/uniq.py
402
3.78125
4
# Module to return uniq elements given a list of elements # Stores every item seen in the stream, for large collections, # use the RedisUniq Redis-backed uniq module import itertools class Uniq(object): def __init__(self): self.items = set() def process(self, data): for s in data: if s not in self.items: self.items.add(s) yield s
67150f37caa5d90147f3d722a6b9234b456e0ca7
JohnnyBarber/Computational-Finance
/project 1 Jiaqi Li/project_1_Jiaqi_Li.py
7,236
3.8125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 15:56:02 2019 @author: Jiaqi Li """ import numpy as np import matplotlib.pyplot as plt import math import random import time #1-------------------------------- #Set random number generators a = 7**5 b = 0 m = 2**31-1 #Creat a list to store random numbers with U[0,1] unif = [None] * 10001 unif[0] = 1 #This loop is for generating random numbers with U[0,1] i = 1 while i < 10001: unif[i] = np.mod(a*unif[i-1]+b,m) i = i+1 unif = [x/m for x in unif] #Delete the first observation x_0 and keep x_1 to x_10000 del unif[0] #Draw the histogram of the sample uniform distribution plt.figure() ax1 = plt.hist(unif, normed = True, bins = 30) plt.title("Uniform Distribution") plt.ylabel("probability") plt.xlabel("value") print("mean: ", np.mean(unif)) print("std: ", np.std(unif)) #Use built-in function to generate uniform distribution build = np.random.uniform(0,1,10000) print("build in function mean: ", np.mean(build)) print("build in function std: ",np.std(build)) #2----------------------------------- #Creat a list to store random numbers from the discrete distribution dist = [None] * 10000 #Set probabilities for different outcomes from the distribution p1 = 0.3; p2 = 0.35; p3 = 0.2; p4 = 0.15 #This loop is for generating the discrete distribution i = 0 while i < 10000: if unif[i] <= p1: dist[i] = -1 elif p1 < unif[i] <= p1+p2: dist[i] = 0 elif p1+p2 < unif[i] <= p1+p2+p3: dist[i] = 1 elif p1+p2+p3 < unif[i] <= p1+p2+p3+p4: dist[i] = 2 i = i + 1 print("mean: ", np.mean(dist)) print("std: ", np.std(dist)) #Draw the histogram plt.figure() ax2 = plt.hist(dist, normed = True) plt.title("Discrete Distribution") plt.ylabel("probability") plt.xlabel("value") #3----------------------------------- #Set seed so that each time we can gerenate the same sequence #of random numbers for each loop that is used to generate #binomial random numbers #By setting such a seed, our result will be consistent and easy #to study with random.seed(9) #Creat a list to store random numbers from the bernoulli distribution ber = [None] * 44 p = 0.64 #Creat a list to store random numbers from the binomail distribution B = [None]*1000 #This loop will generate 1000 binomially distributed random numbers x = 1 while x < 1001: u = [None] * 45 #generate random number for x_0 in each loop u[0] = random.randint(1,100) #generate a set of 44 uniformly distributed random numbers #each set of these numbers will generate 1 random number #with Binomial(44,0.64) i = 1 while i < 45: u[i] = np.mod(a*u[i-1]+b,m) i = i+1 del u[0] j = 0 while j < 44: if u[j]/m <= p: ber[j] = 1 else: ber[j] = 0 j = j + 1 B[x-1] = sum(ber) x = x + 1 #Draw the histogram plt.figure() ax3 = plt.hist(B, normed = True) plt.title("Binomial Distribution") plt.ylabel("probability") plt.xlabel("value") #Compute P(X>=40) P = sum(1 for i in B if i >= 40) #Compute theoretical value of P(X>=40) to compare with the empirical result k = 40 n = 44 P_T = 0 while k < 45: P_true = math.factorial(n)/(math.factorial(k)*math.factorial(n-k))*(p**k)*((1-p)**(n-k)) P_T = P_T + P_true k = k + 1 print("Empirical probability =", P) print("Theoretical Probability =", P_T,"is approximately 0") #4---------------------------------- lam = 1.5 #Use the uniform distributed random numbers created in question 1 #to generate a exponential distribution U_4 = [1-x for x in unif] X_4 = -1/lam*np.log(U_4) #Compute P(X>=1) and P(X>=4) P_1 = sum(1 for i in X_4 if i >= 1)/10000 P_4 = sum(1 for i in X_4 if i >= 4)/10000 print("P(X >= 1) =", P_1, ", P(X >= 4) =", P_4) mu_4 = np.mean(X_4) sigma_4 = np.std(X_4) print("mean =", mu_4, ", std =", sigma_4) #Draw the histogram plt.figure() ax4 = plt.hist(X_4, normed = True, bins = 30) plt.title("Exponential Distribution") plt.ylabel("probability") plt.xlabel("value") #5------------------------------------------------- #Creat a function that can generate random number with U[0,1] #with sample size n and initial value x_0 def f_unif(n,x_0): U = [None] * (n+1) U[0] = x_0 i = 1 while i < (n+1): U[i] = np.mod(a*U[i-1]+b,m) i = i+1 del U[0] U = [x/m for x in U] return U #Generate a uniform distribution with 5000 observations and x_0 = 1 U_5 = f_unif(n = 5000, x_0 = 1) #Creat 2 lists with length 2500 each #These 2 lists will be used to store normally distributed random numbers Z_1 = [None]*2500 Z_2 = [None]*2500 #Here we used Box-Muller Method for i in range(2500): Z_1[i] = np.sqrt(-2*np.log(U_5[2*i]))*np.cos(2*math.pi*U_5[2*i+1]) Z_2[i] = np.sqrt(-2*np.log(U_5[2*i]))*np.sin(2*math.pi*U_5[2*i+1]) i = i + 1 #Combine 2 lists to get a normal distribution with 5000 observations Z_BM = Z_1+Z_2 mu_BM = np.mean(Z_BM) std_BM = np.std(Z_BM) print("Mox-Muller method: mean =", mu_BM, ", std =", std_BM) #Draw the histogram plt.figure() ax5 = plt.hist(Z_BM, normed = True, bins = 30) plt.title("Box-Muller Method") plt.ylabel("probability") plt.xlabel("value") #Here we used Polar-Marsaglia Method Z_1_1 = [None]*2500 Z_2_2 = [None]*2500 for i in range(2500): V_1 = 2*U_5[2*i]-1 V_2 = 2*U_5[2*i+1]-1 W = V_1**2+V_2**2 #drop V_1 and V_2 if W <= 1 if W <= 1: Z_1_1[i] = np.sqrt((-2*np.log(W))/W)*V_1 Z_2_2[i] = np.sqrt((-2*np.log(W))/W)*V_2 Z_PM = Z_1_1 + Z_2_2 Z_PM = [x for x in Z_PM if x != None] #Notice that this method will generate less than 5000 observations mu_PM = np.mean(Z_PM) std_PM = np.std(Z_PM) print("Polar-Marsaglia method: mean =", mu_PM, ", std =", std_PM) #Draw the histogram plt.figure() ax6 = plt.hist(Z_PM, normed = True, bins = 30) plt.title("Polar-Marsaglia Method") plt.ylabel("probability") plt.xlabel("value") #Now we want to compare time efficiency of the two methods #The following uniform distribution is used to generate #2 normal distributions each with 5000 observations #by using different methods U_5_test = f_unif(10000,2) Z_1_test = [None]*2500 Z_2_test = [None]*2500 #Box-Muller Method #Record starting time start_time1 = time.time() for i in range(2500): Z_1_test[i] = np.sqrt(-2*np.log(U_5_test[2*i]))*np.cos(2*math.pi*U_5_test[2*i+1]) Z_2_test[i] = np.sqrt(-2*np.log(U_5_test[2*i]))*np.sin(2*math.pi*U_5_test[2*i+1]) i = i + 1 #Record ending time and compute time used time_1 = (time.time() - start_time1) print("--- %s seconds ---" % time_1) Z_1_1_test = [None]*2500 Z_2_2_test = [None]*2500 #Record starting time start_time2 = time.time() x = 0 for i in range(10000): V_1 = 2*U_5_test[2*i]-1 V_2 = 2*U_5_test[2*i+1]-1 W = V_1**2+V_2**2 if W <= 1: Z_1_1_test[x] = np.sqrt((-2*np.log(W))/W)*V_1 Z_2_2_test[x] = np.sqrt((-2*np.log(W))/W)*V_2 x = x + 1 #when Z_1_1_test and Z_2_2_test both contain 2500 observations, exit loop if x > 2499: break #Record ending time and compute time used time_2 = (time.time() - start_time2) print("--- %s seconds ---" % time_2) print("Box-Muller takes", time_1, "seconds.") print("Polar-Marsaglia takes", time_2, "seconds.")
cbd928cae24bbd74b46ba80f7f1bb564e9285c2c
hogitayden/nguyenhoanggiang-fundametal-c4e22
/Session1/homework/c2f_hws1.py
113
3.65625
4
C = input ("Enter the temperature in Celsius? ") F = 33.8 * float(C) F = round(F,2) print (C, "(C) = ", F, "(F)")
488b640c5492c2a98920b06bcaa2ce29d4bd17e8
jedzej/tietopythontraining-basic
/students/bec_lukasz/lesson_01_basics/previous_and_next.py
215
4.15625
4
# Read an integer: # a = int(input()) # Print a value: # print(a) a = int(input()) print('The next number for the number '+str(a)+' is '+str(a+1)) print('The previous number for the number '+str(a)+' is '+str(a-1))
19df2585aed584e260918eaf8fb3d3871d87b611
hackernogg/CS_ELTE_BC
/Python/1.BasicHelloW/main.py
129
3.90625
4
print("This line will be printed.") x = 1 if x == 1: print ("x is 1.") #----------------------------- print("hello, World!")
8e19f364bd8a3ba8361e329644bfd696088a3a54
karimitani/ECE364
/Prelab08/listmod.py
291
3.71875
4
import os import sys import math def find_median(l1,l2): median = 0 result=[] result=l1+l2 result = sorted(result) if len(result) % 2 == 0: median = math.floor((len(result) - 1)/2) else: median = (len(result) - 1)/2 return (result[median],result)
ce5c41bbab5769e487ed52103cf58f47ac26874d
PawarKishori/QSE
/chi_par.py
616
3.96875
4
import sqlite3 conn = sqlite3.connect('Treebank_English.db') def word1(conn): cursor = conn.cursor() x = input("enter the first word\n") y = input("enter the secone word\n") y="'"+y+"'" x = "'"+x+"'" cursor.execute('select t.sid,t.sentence from Tsentence t,Tword w,Tword k WHERE w.word='+x+' AND k.word='+y+' AND w.sid=k.sid AND w.parent=k.wid AND t.sid=w.sid') myresult = cursor.fetchall() n = len(myresult) print("number of sentences with given word are :"+str(n)) for i in range(n): print('sentence_id:'+myresult[i][0]+'\tsentence: '+myresult[i][1]) word1(conn)
20aedf6083c255849137f71b5a707b1c9c85a6fd
yourapi/biz.data.processing
/types/nl/phone/_normalize.py
186
3.921875
4
import re def normalize(value): "Return a valid phonenumber with general separators removed. Keep letters to prevent false positives." return re.sub('[^0-9\+a-zA-Z]', '', value)
778aaa85c122c54c15f88e59d1c516d25c499448
ggsant/pyladies
/iniciante/Mundo 03/Exercícios Corrigidos/Exercício 092.py
929
3.75
4
""" EXERCÍCIO 092: Cadastro de Trabalhador em Python Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. Se por acaso a CTPS for diferente de ZERO, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se aposentar. """ from datetime import datetime dados = dict() dados['nome'] = str(input('Nome: ')) nasc = int(input('Ano de nascimento: ')) dados['idade'] = datetime.now().year - nasc dados['ctps'] = int(input('Carteira de Trabalho (0 não tem): ')) if dados['ctps'] != 0: dados['contratação'] = int(input('Ano de contratação: ')) dados['salário'] = float(input('Salário: R$ ')) dados['aposentadoria'] = dados['idade'] + ((dados['contratação'] + 35) - datetime.now().year) print('-=' * 30) for k, v in dados.items(): print(f' - {k} tem o valor {v}')
3c721c4f70657bf62919fbd1b7523e1354623391
Qiao-Liang/LeetCode
/LC50.py
1,269
3.5
4
class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ # if n == 0: # return 1 # else: # temp = self.myPow(x, n // 2) # if n % 2 == 0: # return temp * temp # else: # if n > 0: # return temp * temp * x # else: # return temp * temp / x if n == 0: return 1 else: is_minus = False if n < 0: is_minus = True n = -n if n == 1: result = x else: temp = x result = 1 while n > 1: m = 2 while m <= n: temp = temp * temp m = m * 2 n = n - m / 2 result = result * temp temp = x if n == 1: result = result * x if is_minus: return 1 / result else: return result
77d202ed61efd04426966ce5375aaf0619a39cf6
aleksandrakoziel/AI01
/data.py
686
3.5
4
def read_data_from_file(file): # file structure to load # quadratic matrix size # empty line # first matrix A # empty line # second matrix B with open(file, mode='r', encoding='utf-8') as data: size = int(data.readline()) #matrix size - amount of localizations data.readline() D = load_data_to_matrix(data, size) # distances data.readline() F = load_data_to_matrix(data, size) #flows return (size, D, F) def load_data_to_matrix(f, size): matrix = [] i = size while (i > 0): l = f.readline() matrix.append([int(x) for x in l.split(' ') if x != '']) i -= 1 return matrix
b68dbd3a129ed60b25038a658b4017c4957f1197
abdirashidabdi/LOGIN-SYSTEM-PRO
/tempCodeRunnerFile.py
2,136
4.28125
4
def navigate_user(): while True: user_input = input( "\nWelcome to our login system \nType login or register: ") if user_input == "register": return register_user() elif user_input == "login": return login_user() elif user_input == "": print("The option can not be left blank.") else: print("Invalid Option") def register_user(): print("\n ---CREATE YOUR ACCOUNT--- \n") first_name = input("FirstName: ") last_name = input("LastName: ") username = input("Username: ") password = input("Password: ") # the file database should be created first for it to work if first_name == last_name == username ==password == "": print("None of the fields can be left blank.") return navigate_user() f = open('database.txt', 'a') f.write(f"{first_name} ") f.write(f"{last_name} ") f.write(f"{username} ") f.write(f"{password} \n") f.close() print("User Created sucessfuly") return navigate_user() def login_user(): print("\n __login your Account__\n ") while True: user_name = input("Username: ") pass_word = input("password: ") if user_name == "" and pass_word == "": print("Username or Password can not be left blank.") return login_user() # The file database should be created first for it to work f = open("database.txt", "r") data = f.readlines() f.close() store_single_data = [] for single_data in data: store_single_data.append(single_data) for latter in store_single_data: replaced_char = latter.replace("\n", "") l = replaced_char.split(" ", 4) u = l[2:3] p = l[3:4] f = l[0:4] if u[0] == user_name and p[0] == pass_word: print("Welcome " + f[0].capitalize() + " " + f[1].capitalize()) break else: print("Invalid username or password") navigate_user()
ff95c49c7d95ff19f9e30ed7761d16dbaa03d957
daphnecarwin/AllProjectsGWC
/DictionaryAttack/dictionaryattack.py
1,264
4.25
4
#Opens a file. You can now look at each line in the file individually with a statement like "for line in f: f = open("dictionary.txt","r") print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password #NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords test_password = input("Type in a trial password: ") #Write logic to see if the password is in the dictionary file below here: #Opens a file. You can now look at each line in the file individually with a statement like "for line in f: file = open("dictionary.txt","r") for word in f: if word.strip() == test_password.strip(): print("NO THATS IN THE DICTIONARY") else: print("YE DAWG,") break #print("Can your password survive a dictionary attack?") #Take input from the keyboard, storing in the variable test_password ##NOTE - You will have to use .strip() to strip whitespace and newlines from the file and passwords #test_password = input("Type in a trial password: ") #if __name__ == '__main__': #main() #if 'test_password' not in f: #print("yo") #elif test_password in "dictionary.txt": #print("yup") #Write logic to see if the password
b2deb4f80e340b0cca3431717f67b056b502102a
JoshuaUrrutia/agave-cli
/bin/libs/python/richtext.py
1,215
3.53125
4
#!/usr/bin/env python # richtext.py # # A Python >=2.7 command line utility for converting json responses into a rich format # import sys debug = False def print_table(table): zip_table = zip(*table) widths = [max(len(value) for value in row) for row in zip_table] for row in table: result = "| " for i in range(len(row)): result = result + row[i].ljust(widths[i]) + " | " print result def main(): last = "" row = [] data = [] sys.argv.pop(0) sys.argv.append("|") for value in sys.argv: if value == 'rue': value = 'true' elif value == 'False': value = 'false' if (value == "|"): if (value == last): data.append(row) row = [] else: if (last != "|"): value = last + " " + value row[-1] = value else: row.append(value) last = value # Control output format with env variable here print_table(data) if __name__ == "__main__": try: main() except Exception as e: if debug: raise else: print e
ee76231252ac3f15432c83daec73d45ea74e5346
joaquimrsn/Exercios-python
/Estruturas de repetição/Nome_Senha.py
230
4.125
4
while True: nome = input("Digite seu nome de usuário!") senha = input("Sigite a senha!") if (senha == nome): print("Sua senha não pode ser igual ao nome de usuário, tente novamente!") else: break
a2ce2576306d9e70b77836e5ef890a994fb3a21d
raldenprog/python_tricks
/patterns/command.py
4,397
3.890625
4
""" https://refactoring.guru/ru/design-patterns/command Команда — это поведенческий паттерн проектирования, который превращает запросы в объекты, позволяя передавать их как аргументы при вызове методов, ставить запросы в очередь, логировать их, а также поддерживать отмену операций. """ from __future__ import annotations from abc import ABC, abstractmethod class Command(ABC): """ Интерфейс Команды объявляет метод для выполнения команд. """ @abstractmethod def execute(self) -> None: pass class SimpleCommand(Command): """ Некоторые команды способны выполнять простые операции самостоятельно. """ def __init__(self, payload: str) -> None: self._payload = payload def execute(self) -> None: print(f"SimpleCommand: See, I can do simple things like printing" f"({self._payload})") class ComplexCommand(Command): """ Но есть и команды, которые делегируют более сложные операции другим объектам, называемым «получателями». """ def __init__(self, receiver: Receiver, a: str, b: str) -> None: """ Сложные команды могут принимать один или несколько объектов-получателей вместе с любыми данными о контексте через конструктор. """ self._receiver = receiver self._a = a self._b = b def execute(self) -> None: """ Команды могут делегировать выполнение любым методам получателя. """ print("ComplexCommand: Complex stuff should be done by a receiver object", end="") self._receiver.do_something(self._a) self._receiver.do_something_else(self._b) class Receiver: """ Классы Получателей содержат некую важную бизнес-логику. Они умеют выполнять все виды операций, связанных с выполнением запроса. Фактически, любой класс может выступать Получателем. """ def do_something(self, a: str) -> None: print(f"\nReceiver: Working on ({a}.)", end="") def do_something_else(self, b: str) -> None: print(f"\nReceiver: Also working on ({b}.)", end="") class Invoker: """ Отправитель связан с одной или несколькими командами. Он отправляет запрос команде. """ _on_start = None _on_finish = None """ Инициализация команд. """ def set_on_start(self, command: Command): self._on_start = command def set_on_finish(self, command: Command): self._on_finish = command def do_something_important(self) -> None: """ Отправитель не зависит от классов конкретных команд и получателей. Отправитель передаёт запрос получателю косвенно, выполняя команду. """ print("Invoker: Does anybody want something done before I begin?") if isinstance(self._on_start, Command): self._on_start.execute() print("Invoker: ...doing something really important...") print("Invoker: Does anybody want something done after I finish?") if isinstance(self._on_finish, Command): self._on_finish.execute() if __name__ == "__main__": """ Клиентский код может параметризовать отправителя любыми командами. """ invoker = Invoker() invoker.set_on_start(SimpleCommand("Say Hi!")) receiver = Receiver() invoker.set_on_finish(ComplexCommand( receiver, "Send email", "Save report")) invoker.do_something_important()
2a4aa06f3cc2943d0be64137af2970798a4e93bf
TrellixVulnTeam/Demo_933I
/leetcode/693.Binary Number with Alternating Bits.py
1,428
3.78125
4
# Given a positive integer, check whether it has alternating bits: namely, if tw # o adjacent bits will always have different values. # # Example 1: # # Input: 5 # Output: True # Explanation: # The binary representation of 5 is: 101 # # # # Example 2: # # Input: 7 # Output: False # Explanation: # The binary representation of 7 is: 111. # # # # Example 3: # # Input: 11 # Output: False # Explanation: # The binary representation of 11 is: 1011. # # # # Example 4: # # Input: 10 # Output: True # Explanation: # The binary representation of 10 is: 1010. # # Related Topics Bit Manipulation # 👍 453 👎 78 # region time # 2020-07-28 23:56:34 # endregion # leetcode submit region begin(Prohibit modification and deletion) class Solution: def hasAlternatingBits(self, n: int) -> bool: # s = str(bin(n)).split('b')[1] # x = 0 # for i in s: # if not x: # x = int(i)+1 # continue # if x == int(i)+1: # return False # if x != int(i)+1: # x = int(i)+1 # return True n = bin(n)[2:] for i in range(1, len(n)): if n[i - 1] == n[i]: return False return True # leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': n = 42 print(Solution().hasAlternatingBits(n))
c755411c24e86800ba02c06094c12ffeb43d6f7e
huangqiank/Algorithm
/leetcode/binarySearch/first_bad_version.py
1,055
4.03125
4
##You are a product manager and currently leading a team to develop a new product. ##Unfortunately, the latest version of your product fails the quality check. ##Since each version is developed based on the previous version, ##all the versions after a bad version are also bad. ##Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, ##which causes all the following ones to be bad. ##You are given an API bool isBadVersion(version) ##which will return whether version is bad. ##Implement a function to find the first bad version. ##You should minimize the number of calls to the API. ##Example: ##Given n = 5, and version = 4 is the first bad version. ##call isBadVersion(3) -> false ##call isBadVersion(5) -> true ##call isBadVersion(4) -> true ##Then 4 is the first bad version.  def firstBadVersion( n): l = 0 r = n-1 while l +1 < r: mid = int((l+r)/2) if isBadVersion(mid): r = mid else: l = mid if isBadVersion(l): return l return r
e1b9954b4820bb8969a6898d5bd01f226df1ee87
Gambrinius/Python_Course
/week5/lost_card.py
122
3.875
4
n = int(input()) sum_ = sum(range(n+1)) for i in range(1, n): cur_num = int(input()) sum_ -= cur_num print(sum_)
9e1b7a7e24a19561f305f5b2a7812f78d0b79f78
rexfa/helloPython
/InterestPrepayment.py
612
3.703125
4
#计算预付利息的实际年利率,名义本金,实际利息 def interestPrepayment(namedPrincipal ,interest): print('名义利率',interest/namedPrincipal) monthlyRepayment = namedPrincipal/12 actualLoan = namedPrincipal - interest print('实际年利率',monthlyInterest(monthlyRepayment,actualLoan)) #每月利率,每月还款,名义本金 ,实际利息 def monthlyInterest(monthlyRepayment,namedPrincipal,interest): #实际贷款 actualLoan = namedPrincipal-interest m = monthlyRepayment/actualLoan x=(y-1)*12 return x interestPrepayment(120000,14430)
5a108cb7fb1ff0426c5e21786f4e9bdf90d8a1e2
gdh756462786/Leetcode_by_python
/ArraySum/submatrix-sum.py
1,126
3.515625
4
# coding: utf-8 ''' 给定一个整数矩阵,请找出一个子矩阵, 使得其数字之和等于0.输出答案时,请返回左上数字和右下数字的坐标。 样例 给定矩阵 [ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ] 返回 [(1,1), (2,2)] ''' class Solution: # @param {int[][]} matrix an integer matrix # @return {int[][]} the coordinate of the left-up and right-down number def submatrixSum(self, matrix): lenM = len(matrix) lenN = len(matrix[0]) if lenM == lenN == 1 and matrix[0][0] == 0: return [[0, 0], [0, 0]] f = [[0 for x in xrange(lenN + 1)] for y in xrange(lenM + 1)] for i in xrange(1, lenM + 1): for j in xrange(1, lenN + 1): f[i][j] = f[i - 1][j] + f[i][j - 1] - f[i - 1][j - 1] + matrix[i - 1][j - 1] for m in xrange(i): for n in xrange(j): if f[i][j] == f[i][n] - f[m][n] + f[m][j]: return [[m, n], [i - 1, j - 1]] solution = Solution() print solution.submatrixSum([ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ])
b40fe1e242f9ff36305af5c2b29f0ac85e6227a5
szama7/python_practice
/alarms/ToplistOfUnits.py
377
3.53125
4
import ListSorting from collections import Counter ListSorting.store_blocks() ListSorting.sort_list() computer_units = [] for i in range(0, len(ListSorting.threestar)): computer_units.append(ListSorting.threestar[i][0].split()[2]) for i in range(0, len(ListSorting.twostar)): computer_units.append(ListSorting.twostar[i][0].split()[2]) print Counter(computer_units)
eeb81a43267112b37d8d1f6cd0874af04767233a
Patacij/Calculator
/list_dict.py
1,520
3.796875
4
print ("Welcome to my TODO program.") to_do_tasks = [] done_task = [] tasks = [] while True: action = raw_input('Select add new task or edit existing tasks (new/edit)') if action == 'new': task_name = raw_input("Please enter new task: ") task = { 'task_name': task_name, 'task_done': False } print("Your task is: {0}".format(task)) to_do_tasks.append(task) elif action == 'edit': task_to_edit = raw_input("Enter task name to mark as done: ") for task in to_do_tasks:#namesto postavke "task" karkoli, ni nujno da je beseda task if task['task_name'] == task_to_edit: to_do_tasks.remove(task) task['task_done'] = True done_task.append(task) elif action == 'finish': break #shranimo v en file with open('todo.csv', 'w+') as todo_file: todo_file.writelines('Task Name, Tasl Done\n') for task in to_do_tasks: todo_file.writelines('{task_name},{task_done}\n'.format( task_name=task ['task_name'], task_done=task['task_done'] ) ) print("Done tasks: {0}".format(done_task)) print("TODO tasks: {0}".format(to_do_tasks)) print ("END") # empty_list = [] # print(empty_list) # print(type(empty_list)) # # list_with_el = [0, '1', "124abc", 2.1, True] # print(list_with_el) # print(type(list_with_el)) # # x = 'neki' # y = 'neki druzga' # # list_xy = [x, y] # print(list_xy) # print(type(list_xy))
e12b130c2cb9738aa69b5cb351be36bcb933d381
ArsenalGang/dzdykes.github.io
/Solutions/gcd.py
567
3.53125
4
def GCD(x,y): if x > y: return False if x%y == 0: return y else: result = 1 for i in range(int(y/2)): if x%(i+1) == 0 and y%(i+1) ==0: result = i+1 return result def LCM(x,y): if x > y: return False if x%y == 0: return x else: result = x*y for i in range(x*y,x,-1): if i%x==0 and i%y==0: result = i return result def Sum3(x,y,z): if x==y or y==z or x==z: return 0 else: return x+y+z
ff0e4b5120733be9cb2f28329f7eb806e3009e19
rajlath/rkl_codes
/LeetCodeContests/56/string_compression.py
1,954
4.0625
4
''' 443. String Compression My SubmissionsBack to Contest Difficulty: Easy Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". Example 2: Input: ["a"] Output: Return 1, and the first 1 characters of the input array should be: ["a"] Explanation: Nothing is replaced. Example 3: Input: ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". Notice each digit has it's own entry in the array. ''' class Solution(object): def compress(self, chars): """ :type chars: List[str] :rtype: int """ if not chars: return 0 curC = chars[0] curCount = 1 ans = [] for i in range(1, len(chars)): if chars[i] != curC: ans.append(curC) if curCount != 1: ans.extend(list(str(curCount))) curC = chars[i] curCount = 1 else: curCount += 1 ans.append(curC) if curCount != 1: ans.extend(list(str(curCount))) for i in range(len(ans)): chars[i] = ans[i] return len(ans) sol = Solution() print(sol.compress(["a","a","b","b","c","c","c"]))
1576a986be9b3792fd0f19913b672833b285a4e5
sibarras/games
/snake_game.py
6,141
3.890625
4
from random import randint from time import sleep import keyboard # deseo eliminar esta libreria en un futuro from raspberrypi import RPiSimulator class Snake: def __init__(self, limits=tuple): self.xf, self.yf = limits self.mouth = randint(0, self.xf), randint(0, self.yf) self.body = [self.mouth] self.direction = None self.step = None self.life = True def move(self, mvDir=str, foodposition=tuple): # verify current direction or last direction in memory # you cant reverse the snake if mvDir == 'up' and self.direction != 'down': self.step = 0, 1 self.direction = mvDir elif mvDir == 'down' and self.direction != 'up': self.step = 0, -1 self.direction = mvDir elif mvDir == 'left' and self.direction != 'right': self.step = -1, 0 self.direction = mvDir elif mvDir == 'right' and self.direction != 'left': self.step = 1, 0 self.direction = mvDir # new mouth position self.mouth = self.mouth[0]+self.step[0], self.mouth[1]+self.step[1] # you have food for me? if self.eat(foodposition) == False: self.body.insert(0, self.mouth) # insert the mouth in the body self.body.pop() # remove last part of body elif self.eat(foodposition) == True: self.body.insert(0, self.mouth) # just add mouth position def eat(self, foodPosition=tuple): if foodPosition == self.mouth: return True else: return False def stillAlive(self): x, y = self.mouth if x < 0 or x > self.xf or y < 0 or y > self.yf: # is not in in board range self.life = False for points in self.body[1:]: # if the mouth touch the snake body if self.mouth == points: self.life = False class Board: def __init__(self, xlim=int, ylim=int): self.xlimit = xlim - 1 self.ylimit = ylim - 1 def terminalPrintPanel(self, snakebody=list, food=tuple, move='up'): # cambiar a curses en el futuro p = [[' ' for i in range(self.xlimit+1)] for i in range(self.ylimit+1)] fx, fy = food p[self.ylimit-fy][fx] = '*' mouth = '' if move == 'up': mouth = 'v' elif move == 'down': mouth = '^' elif move == 'left': mouth = '>' elif move == 'right': mouth = '<' fx, fy = snakebody[0] p[self.ylimit-fy][fx] = mouth for points in snakebody[1:]: x,y = points p[self.ylimit-y][x] = 'O' print(' .'*(self.xlimit+2)) for rows in p: print(' .', end='') for cols in rows: print(cols, end=' .') print() print('\n\n') def terminalEndGame(self): print('\t\tthe end\t\t') class LedPrint: def __init__(self, dimensions=8): from time import sleep from raspberrypi import RPiSimulator self.dimensions = dimensions self.sleep = sleep self.IO = RPiSimulator() def makeParts(self, snakemouth=tuple, snakebody=list): lastPoint = snakemouth bodyparts = [[]] partNumber = 0 if snakebody[1][0] == lastPoint[0]: axis = 'X' elif snakebody[1][1] == lastPoint[1]: axis = 'Y' for point in snakebody: if point[0] == lastPoint[0] and axis == 'X': bodyparts[partNumber].append(point) elif point[1] == lastPoint[1] and axis == 'Y': bodyparts[partNumber].append(point) else: partNumber += 1 bodyparts.append([]) bodyparts[partNumber].append(point) if axis == 'Y': axis = 'X' elif axis == 'X': axis = 'Y' lastPoint = point return bodyparts def show(self, snakemouth=tuple, snakebody=list, food=tuple): bodyParts = self.makeParts(snakemouth, snakebody) bodyParts.append([food]) for part in bodyParts: for point in part: self.IO.setLed(point, 'ON') self.sleep(0.1) for point in part: self.IO.setLed(point, 'OFF') class Food: def __init__(self, limits=tuple): self.__limits = limits # create only inside the board self.position = None # coordinates def newFood(self, snakeBody=list): xf, yf = self.__limits # limits self.position = (randint(0, xf), randint(0, yf)) # if new food is created inside the snake if self.position in snakeBody: self.newFood(snakeBody) # create other (recursive) # object wall dim = int(input('Inserta la cantidad de filas y columnas: ')) screen = Board(dim, dim) limits = screen.xlimit, screen.ylimit # object snake snake = Snake(limits) # object food food = Food(limits) food.newFood(snake.body) # define first move (choose the largest distance) spaceToMove = {} spaceToMove['right'] = limits[0] - snake.mouth[0] spaceToMove['left'] = snake.mouth[0] spaceToMove['up'] = limits[1] - snake.mouth[1] spaceToMove['down'] = snake.mouth[1] spaceToMove = sorted(spaceToMove.items(), key=lambda sp: sp[1], reverse=True) snake.direction = spaceToMove[0][0] del spaceToMove # moving snake while snake.life: # imprime la pantalla screen.terminalPrintPanel(snake.body, food.position, snake.direction) userKey = '' keyboard.start_recording() sleep(0.5) listOfKeys = keyboard.stop_recording() if len(listOfKeys) > 0: userKey = str(listOfKeys[0])[14:][:-6] del listOfKeys if userKey == 'up' or userKey == 'down' or userKey == 'left' or userKey == 'right': snake.move(userKey, food.position) else: snake.move(snake.direction, food.position) if snake.eat(food.position) is True: food.newFood(snake.body) snake.stillAlive() else: print(""" THE END. SAMUEL IBARRA """)
bea4f2b02bc58f97b3823942d0f5f4132a41bfbe
Anirban2404/LeetCodePractice
/110_isBalanced.py
2,803
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 31 09:49:05 2019 @author: anirban-mac """ """ 110. Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def stringToTreeNode(self,inputValues): root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputValues): node = nodeQueue[front] front = front + 1 item = inputValues[index] index = index + 1 if item != "null": leftNumber = int(item) node.left = TreeNode(leftNumber) nodeQueue.append(node.left) if index >= len(inputValues): break item = inputValues[index] index = index + 1 if item != "null": rightNumber = int(item) node.right = TreeNode(rightNumber) nodeQueue.append(node.right) return root def prettyPrintTree(self, node, prefix="", isLeft=True): if not node: print("Empty Tree") return if node.right: self.prettyPrintTree(node.right, prefix + ("│ " if isLeft else " "), False) print(prefix + ("└── " if isLeft else "┌── ") + str(node.val)) if node.left: self.prettyPrintTree(node.left, prefix + (" " if isLeft else "│ "), True) def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def check(root): if root is None: return 0 left = check(root.left) if left == -1: return -1 right = check(root.right) if right == -1: return -1 if abs(left -right) > 1: return -1 return 1 + max(left,right) return check(root) != -1 treelist = [3,9,20,'null','null',15,7] treeNode = Solution().stringToTreeNode(treelist) Solution().prettyPrintTree(treeNode,"",True) print(Solution().isBalanced(treeNode))
5ddde85b31c38653430c512bc2074610cd96c82c
SergeiMerson/Experis
/!Projects/MP_Library/registers.py
2,353
3.796875
4
import basics class Register: def __init__(self): self.register = {} def get_items(self): return (val for _, val in self.register.items()) def get_by_key(self, key): try: return self.register[key] except KeyError: print('There is no such ID') def reset_register(self): user_input = input('Do you really want to reset the Register and delete all records? [Y]/[N]: ') if user_input.lower() == 'y': self.register.clear() print('The Register was reset successfully') class AuthorRegister(Register): def add(self, first_name, last_name): author = basics.Author(first_name, last_name) self.register[author.id] = author print(f'Successfully added {first_name} {last_name} to the Register with ID: {author.id}') return author def remove(self, author_id): try: author = self.register[author_id] del self.register[author_id] print(f'Successfully removed {author.first_name} {author.last_name} with ID: {author_id} form Register') except KeyError: print(f'There is no Author with ID: {author_id}') def search_by_name(self, first_name='?', last_name='?'): operator = any if any((first_name == '?', last_name == '?')) else all return [a for a in self.get_items() if operator(( first_name.lower() in a.first_name.lower(), last_name.lower() in a.last_name.lower() ))] class BookRegister(Register): def add(self, title, author_id): book = basics.Book(title, author_id) self.register[book.id] = book return book def remove(self, book_id): try: book_title = self.register[book_id].title del self.register[book_id] print(f'Successfully deleted Book {book_title} with id: {book_id}') except KeyError: print(f'There is no Book with ID: {book_id}') def search_by_title(self, title): return [b for b in self.get_items() if title.lower() in b.title.lower()] def search_by_author_id(self, author_id): return [b for b in self.get_items() if author_id == b.author_id]
8b7d6a2d1d9e4f049abcbe950c1306f742e0a3fc
yaolizheng/leetcode
/73/set_zero.py
603
3.546875
4
def set_zero(m): r = len(m) c = len(m[0]) for i in range(r): for j in range(c): if m[i][j] == 0: m[0][j] = 's' m[i][0] = 's' for i in range(r): if m[i][0] == 's': for j in range(c): if m[i][j] != 's': m[i][j] = 0 for j in range(c): if m[0][j] == 's': for i in range(r): m[i][j] = 0 return m if __name__ == '__main__': m = [[1, 1, 1], [1, 0, 1], [1, 1, 1]] m = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]] print set_zero(m)
8847a9eeb9cf40e07948726b816b310d877c3116
rafaelperazzo/programacao-web
/moodledata/vpl_data/83/usersdata/235/44011/submittedfiles/dec2bin.py
145
3.90625
4
# -*- coding: utf-8 -*- n=int(input('digite o numero:')) i=0 s=0 while n>0: M=n%2 F=(M*(10**i)) s=s+F n=n//2 i=i+1 print(s)
76cd561c5177147f91c284b3f4b106164b3b75b3
xbtlin/Learn-Python-the-Hard-Way-
/exercises/ex13-raw_input.py
189
3.59375
4
from sys import argv script, first_name, last_name = argv middle_name = raw_input("What is your middle name? ") print "Your full name is %s %s %s." % (first_name, middle_name, last_name)
31e88cbc8c7b925c7befc990eebe2eeec75197af
AllenLiuX/Application-of-Python-UCLA-PIC16
/hw/hw4.py
3,341
3.625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: Wenxuan Liu 805152602 """ import re """Use regex to seperately match the syntax of int, float, and list, and return the type if matched, otherwise return string.""" def mytype(v): """It performs the same action as type(), and can recognize integers, floats, strings, and lists.""" v1 = str(v) isInt = re.search(r'^[\-+]?\d+$', v1) #if I use ^ or $, I cannot use .group()? isFloat = re.search(r'^[\-+]?\d+\.\d+$', v1) isList = re.search(r'^\[[\-+]?\d*(, ?[\-+]?\d+)*\]$', v1) if isInt: return "int" if isFloat: return "float" if isList: return "list" return "string" """Iteratively, first match the syntax for a pdf, then catch the group of name without extension.""" def findpdfs(L): """It takes as input a list L of filenames, and returns a list of the names of all PDF files, without extension""" res = [] for file in L: if(re.search(r'^[0-9a-zA-Z]+\.pdf$', file)): name = re.search(r'([0-9a-zA-Z]+)(?=\.pdf)', file).group(1) res.append(name) return res import urllib2 """Match the pattern of email with some options for '@' and '.' in uncatched groups. Then, remove the duplicates with set() operation. And use 're.sub' to replace the hidden expressions of '@' and '.'.""" def findemail(url): """It takes as input a URL, and outputs any email addresses that look like “xxx@xxx.xxx.xxx” with any number of dots after the @-sign on this page. It also catches hidden expression of '@' and '.' and translates them.""" page = urllib2.urlopen(url).read() mails = re.findall(r'[0-9a-zA-Z]+(?:@| at | AT |\[at\]|\[AT\])[0-9a-zA-Z]+(?:(?:\.| dot | DOT |\[dot\]|\[DOT\])[a-z0-9A-Z]+){0,}', page) temp = list(set(mails)) res = [] for str in temp: str = re.sub(r'( at | AT |\[at\]|\[AT\])',r'@', str) str = re.sub(r'( dot | DOT |\[dot\]|\[DOT\])', r'.', str) res.append(str) return res import happiness_dictionary """First, use findall to get all the words seperately in the text and store them into a list. Then, for each word, add the value of the word in the dictionary if exists. Finally, calculate the average value of the words.""" def happiness(text): """uses the Dodds et al happiness dictionary to rate the happiness of a piece of english text (input as a single string)""" li = re.findall(r'[0-9a-zA-Z]+', text) sum = 0.0 count = 0 for word in li: word = word.lower() if(happiness_dictionary.happiness_dictionary.has_key(word)): sum += happiness_dictionary.happiness_dictionary[word] count += 1 return sum/count #testcase 1: print mytype(10) print mytype(-1.25) print mytype([1, 2, 3]) print mytype("abc") #testcase 2: res = findpdfs(["IMG2309.jpg", "lecture1.pdf", "homework.py", "homework2.pdf"]) print res #testcase 3: url1 = "https://www.math.ucla.edu/~hangjie/contact/" url2 = "https://www.math.ucla.edu/~hangjie/teaching/Winter2019PIC16/regexTest" print findemail(url1) print findemail(url2) #testcase 4: s1 = "Mary had a little lamb." s2 = "Mary had a little lamb. Mary had a little lamb!" s3 = "A quick brown fox jumps over a lazy dog." print happiness(s1) print happiness(s2) print happiness(s3)
6ceef081d9ddb33fe2a8ad60e48fd9af978c4f4a
raghavp96/autoneo
/autoneo/exporter.py
1,413
3.5625
4
import sqlite3 import csv def handle_sqlite3(db_path, query_file_path, csv_file_path): """ Handle the data export from a SQLite 3 DB to CSV """ connection = sqlite3.connect(db_path) cursor = connection.cursor() query_string = __query_file_to_string(query_file_path) with open(csv_file_path, "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter=",", quotechar='"', quoting=csv.QUOTE_NONNUMERIC) cursor.execute(query_string) csv_writer.writerow([d[0] for d in cursor.description]) for row in cursor: csv_writer.writerow(row) def handle_annotations(annotation_file_path, csv_file_path): """ Handle the data export from a Go Annotation File to CSV """ try: with open(annotation_file_path) as annotation_file, open(csv_file_path, "w") as csv_file: csv_writer = csv.writer(csv_file, delimiter=",", quotechar='"', quoting=csv.QUOTE_NONNUMERIC) for line in annotation_file: if line.startswith('UniProtKB'): line_arr = line.split('\t') csv_file_writer.writerow(line_arr) return True except: return False def __query_file_to_string(query_file_path): query_string = "" with open(query_file_path) as f: lines = f.readlines() query_string = " ".join(lines) return query_string
572531f6f1723b2c2ed19808dfc7968a8c3ad042
Eli-jah/a-byte-of-python
/io_using_file.py
612
3.71875
4
# encoding=utf-8 poem = '''\ Programming is fun When the work is done If you wanna make your work also fun Use Python! ''' # Open file for 'w'riting f = open('poem.txt', 'w') # Write text into file f.write(poem) # Close the file f.close() # If no mode is specified # The 'r'ead mode is assumed by default f = open('poem.txt') while True: line = f.readline() # Zero length indicates EOF if len(line) == 0: break # The `line` already has its newline '\n' # at the end of each line # since it is read from a file. print(line, end='') # Now, close the file. f.close()
5055468924fa40be02902451f8716c95c3eca4ae
dilynfullerton/tr-A_dependence_plots
/src/LegendSize.py
2,909
3.5
4
"""LegendSize.py Class definition for LegendSize, which specifies how a legend should be sized for matplotlib plots """ from __future__ import division from math import ceil class LegendSize: """A class to store the constants and methods for generating a nice legend outside the subplot area (matplotlib) """ def __init__(self, max_cols, max_h_space, max_fontsize, min_fontsize, total_fontsize, rows_per_col, space_scale): """Initialize a LegendSize instance :param max_cols: maximum allowed number of columns for the legend :param max_h_space: maximum proportion of horizontal space to be apportioned to the legend :param max_fontsize: maximum font size for legend labels :param min_fontsize: minimum font size for legend labels :param total_fontsize: value of font size * number of rows :param rows_per_col: number of rows in a column :param space_scale: some sort of scale factor or something """ self.max_cols = max_cols self.max_h_space = max_h_space self.max_fontsize = max_fontsize self.min_fontsize = min_fontsize self.total_fontsize = total_fontsize self.rows_per_col = rows_per_col self.space_scale = space_scale def num_cols(self, num_plots): """Returns the number of columns the legend will have :param num_plots: number of plots """ if self.max_cols is not None: return int( max(min(ceil(num_plots / self.rows_per_col), self.max_cols), 1)) else: return int(max(ceil(num_plots / self.rows_per_col), 1)) def fontsize(self, num_plots, num_cols=None): """Returns the font size for labels in the legend :param num_plots: number of plots :param num_cols: number of columns for the legend """ if num_cols is None: num_cols = self.num_cols(num_plots) if num_plots > 0: return max(min(num_cols * self.total_fontsize / num_plots, self.max_fontsize), self.min_fontsize) else: return self.min_fontsize def width_scale(self, num_plots, num_cols=None, fontsize=None): """Returns the scale factor for the width of the axis box :param num_plots: number of plots :param num_cols: number of columns in the legend :param fontsize: legend label font size """ if num_cols is None: num_cols = self.num_cols(num_plots) if fontsize is None: fontsize = self.fontsize(num_plots, num_cols) if self.max_cols is not None: return (1 - (self.max_h_space * num_cols / self.max_cols) * (fontsize / self.max_fontsize) * self.space_scale) else: return 1 - self.max_h_space * (fontsize / self.max_fontsize)
89e81ef50ea85213441253f1f47bc6df343a8bf6
AzharMithani/Handwritten-Digit-Recognition-With-Deep-Learning
/train.py
1,234
3.71875
4
#importing required modules from sklearn.externals import joblib from sklearn import datasets import numpy as np #for creating Neural Network I am using MLPClassifier from sklearn from sklearn.neural_network.multilayer_perceptron import MLPClassifier #getting MNIST of size 70k images dataset = datasets.fetch_mldata("MNIST Original") X = np.array(dataset.data) #Our Features y = np.array(dataset.target) #Our labels X = X.astype('float32') #splitting Dataset into Training and Testing dataset #First 60k instances are for Training and last 10k are for testing X_train, X_test = X[:60000], X[60000:] y_train, y_test = y[:60000], y[60000:] #Normalizing Our Features in range 0 and 1 X_train = X_train /255 X_test = X_test /255 #creating Neural Network # Neural Network has one hidden layer with 240 units # Neural NetWork is of size 784-240-10 mlp = MLPClassifier(hidden_layer_sizes=(240), max_iter=1200, verbose=True) #fitting our model mlp.fit(X_train, y_train) ''' Final Output: Iteration 33, loss = 0.00299869 ''' print("Training set score: %f" % mlp.score(X_train, y_train)) #output : 0.99 print("Test set score: %f" % mlp.score(X_test, y_test)) #output :0.98 #saving our model joblib.dump(mlp, "model.pkl")
f3307c60d80b06b0d0e1c5bea6c9c8ab2c43e7a7
ChaosJohn/c9.io-playground
/py2/default_argument_values.py
810
3.71875
4
"""Default Argument Values.""" def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): """Ask Prompt""" while True: answer = raw_input(prompt) if answer in ('y', 'ye', 'yes'): return True if answer in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 if retries < 0: raise IOError('refusenik user') print complaint I = 5 def f_2(arg=I): """The default values are evaluated at the point of function definition in the defining scope.""" print arg I = 6 f_2() def f_3(a, L=[]): L.append(a) return L print f_3(1) print f_3(2) print f_3(3) def f_4(a, L=None): if L is None: L = [] L.append(a) return L print f_4(1) print f_4(2) print f_4(3) print f_2.__doc__
5c45181788c5e511b8a545ce89d0b3b46ad875d3
bhanu-python/Python-Data
/milestone_project1/test.py
109
3.828125
4
s="hello" pos=1 mylist=["My","Name","is"] print(mylist) mylist[pos]=s #mylist.insert(pos,s) print(mylist)
2ae076df49d9aeb8f2c2f35ccf3e9596465b7c0f
TingliangZhang/VR_Robot
/Python/Practice/ch01/1.py
109
3.734375
4
import random for x in range(10): print("hello\n") print("hhh ",random.choice(range(10))) input() #233
c044f2ee7e8c5f9ca76c57f065bf049fe29d1b28
ddc899/cmpt145
/Code Examples/Chapter 01/coupon-collector.py
1,455
4.15625
4
""" CMPT 145 Computing with Python Lists The Coupon Collector Problem Suppose there are n coupons to collect, and coupons are obtained randomly (with equal probability), with repeats allowed (replacement). How many coupons need to be obtained before all coupons have been seen at least once? (Not answered: how many on average?) """ import random as random import time as time start = time.time() n = 100 # number of unique coupons to collect n_trials = 2000 for i in range(n_trials): count = 0 # number of total coupons collected collected_count = 0 # number of unique coupons collected is_collected = n*[False] # list tracking status of unique coupons collected # keep collecting coupons until we collect at least one of every kind of coupon while collected_count < n: # obtain a random new coupon value = random.randrange(0,n) count += 1 # if we obtained a new unique coupon, update status and count of unique coupons collected if not is_collected[value]: collected_count += 1 is_collected[value] = True end = time.time() dur = end - start # display number of total coupons collected print("Total Coupons Collected:", count) print("Coupons Collected per coupon:", count/n) end = time.time() dur = end - start print('Number of coupons collected:', count/n) print('Number of trials:', n_trials) print('Time:', dur, dur/n_trials)
462f37a1890707acc8e223b8b1f30ba949c47e5d
noshaikh/Graphs
/projects/graph/src/graph.py
6,390
3.90625
4
""" Simple graph implementation compatible with BokehGraph class. """ import random class Queue: def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if (self.size()) > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) class Stack: def __init__(self): self.stack =[] def push(self, value): self.queue.append(value) def pop(self): if (self.size()) > 0: return self.queue.pop(0) else: return None def size(self): return len """Represent a graph as a dictionary of vertices mapping labels to edges.""" class Graph: def __init__(self): """create an empty dictionary for the vertices""" self.vertices = {} def add_vertex(self, vertex_id): """add a vertex to the graph""" self.vertices[vertex_id] = Vertex(vertex_id) def add_edge(self, v1, v2): """add an undirected edge to the graph""" if v1 in self.vertices or v2 in self.vertices: self.vertices[v1].edges.add(v2) self.vertices[v2].edges.add(v1) else: raise IndexError("That vertex does not exist!") def add_directed_edge(self, v1, v2): """ add an edge to the graph""" if v1 in self.vertices: self.vertices[v1].edges.add(v2) else: raise IndexError("That vertex does not exist!") #DFT using recursion def dft(self, starting_node, visited=None): """Mark the node as visited""" if visited is None: #cant just have visited = [] in def dft because of weird python thing visited = [] # queue of visited nodes visited.append(starting_node) """For each child, if that child hasnt been visited, call dft() on that node for child in children: if child not in visited: dft (child,visited)""" for node in self.vertices[starting_node].edges: if node not in visited: self.dft(node, visited) return visited #you can implement dfs using stack instead of recursion #and for bfs if you use queue instead of stack it changes dfs to bfs def bft(self, starting_node): visited=[] """create an empty queue""" q = Queue() """put starting vert in the queue""" q.enqueue(starting_node) while q.size() > 0: # while queue is not empty... dequeued = q.dequeue() #dequeue the first element visited.append(dequeued) print(dequeued) for edge in self.vertices[dequeued].edges: if edge not in visited: q.enqueue(edge) #add it back to the queue return visited """ remove the first node from the queue... If it has not been visited yet... Mark it as visited... then put all its children in the back of the queue""" def dft_s(self, starting_node): #dft as a stack visited=[] """create an empty stack""" s = Stack() """put starting vert on top of the stack""" s.push(starting_node) while s.size() > 0: # while stack is not empty... current = s.pop() #pop the first element if current not in visited: visited.append(current) print(visited) for edge in self.vertices[current].edges:#for each child s.push(edge) #add it to the top of the stack def bfs(self, starting_node, target_node): visited = [] # create an empty queue q = Queue() # put starting vert in the queue q.enqueue(starting_node) while q.size() > 0:#while queue is not empty dequeued = q.dequeue()#dequeue the first element visited.append(dequeued)#mark it as visited print(dequeued) if dequeued ==target_node: return True for edge in self.vertices[dequeued].edges:#for each child if edge not in visited:#if it hasnt been visited q.enqueue(edge)#add it to the back of the queue return False #instead of storing just nodes in our queue, we store an entire path def bfs_path(self, starting_node, target_value): q= Queue() #create an empty queue q.enqueue([starting_vertex_id]) #put the first node in the queue as a path visited=[] while q.size() > 0: #then, while the queue is not empty path=q.dequeue() #Dequeue the first path in the queue v=path[-1] #Get the current vertex (the last element in the path) if v not in visited: #If that vertex has not been visited... print(path) if v ==target_value: #Check if its the target value return path visited.append(v) #mark as visited for next_vert in self.vertices[v].edges: #then, put all the children in the queue new_path = list(path) new_path.append(next_vert) #...as a path q.enqueue(new_path) return None def dfs(self, starting_node, target_node, visited=None): #Mark the node as visited if visited is None: #queue of visited nodes visited =[] visited.append(starting_node) if starting_node ==target_node: return True #for each child, if that child hasnt been visited, call dft() on that node for node in self.vertices[starting_node].edges: if node not in visited: if self.dfs(node,target_node,visited): return True return False def dfs_path(self, start_vert, target_value, visited=None, path=None): if visited is None: class Vertex: def __init__(self, vertex_id, x=None, y=None): """ Create an empty vertex""" self.id = vertex_id self.edges = set() if x is None: self.x = random.random() * 10 - 5 else: self.x = x if y is None: self.y = random.random() * 10 - 5 else: self.y = y def __repr__(self): return f"{self.edges}"
b7bbd087f56eb93a4012cee0a3151065ffbd89e4
LwandoG/LifeChoicesOnline
/main.py
6,418
4.28125
4
import getpass import user import datetime # This is the local sign in function. It is used to print the appropriate message based on the result of the sign in # function from the user module. def sign_in(user_name): if user.sign_in(user_name): print("Signed in successfully. Enjoy your day.") else: print("Already signed in. Signout first.") # This is the local sign out function. It is used to print the appropriate message based on the result of the sign out # function from the user module. def sign_out(user_name): if user.signout(user_name): print("Successfully signed out.") else: second_option = input("Not signed in.\n1. Sign in?\n2. Exit?\n") # Can't sign out if not signed in. if second_option == '1': sign_in(user_name) else: exit(0) option = input('Please select an option below: \n1.Login.\n2.Register.\n') if option == '1': username = input('Please enter your username: ') password = input('Enter password: ') if user.authenticate(username, password): # username and password authentication print('Welcome ', user.get_name(username)) print('Please choose an option below:') log = input('1. Sign-in.\n2. Signout.\n') if log == '1': sign_in(username) elif log == '2': sign_out(username) else: print('Incorrect selection.') # Error handling else: print('Incorrect username and password combination.') elif option == '2': print('Welcome to the registration page.') full_name = input('Please enter your full name: ') username = input('Please enter your username: ') while username in user.get_usernames(): # this is to make sure no two users share the same username. username = input('Username already taken. Please enter your username: ') password = input('Enter password: ') role = input('Are you a visitor, student or an employee? ') while role not in ['visitor', 'student', 'employee']: # to ensure the user doesn't select random roles. role = input('Incorrect input. Are you a visitor, student or an employee? ') new_user = user.User(full_name, username, password, role) # creating a new user object. new_user.register() # registering the new user second_option = input("Welcome to LifeChoices.\n1. Sign in?\n2. Exit?\n") if second_option == '1': sign_in(username) else: exit(0) elif option == 'a': print('Welcome to the admin page.') username = input('Please input your admin username: ') password = input('Please input your admin password: ') if user.authenticate(username, password): if user.admin(username): # ensuring the user is an actual admin. # admin privileges, each option is self explanatory. selection = input('Please choose an option:\n1. Sign in.\n2. Sign out.\n3. Add new user.\n4. Remove user\n' '5. Upgrade user to admin.\n6. Downgrade admin to normal user\n7. Show people who have ' 'signed in today.\n8. Show people who have signed out today.\n9. Show people who are ' 'inside.\n') if selection == '1': sign_in(username) elif selection == '2': user.sign_out(username) elif selection == '3': full_name = input('Please enter the full name: ') username = input('Please enter the username: ') while username in user.get_usernames(): username = input('Username already taken. Please enter another username: ') password = input('Enter password: ') role = input('Is this user a visitor, student, employee or an admin? ') while role not in ['visitor', 'student', 'employee', 'admin']: role = input('Incorrect input. Is the user a visitor, student, employee or an admin? ') new_user = user.User(full_name, username, password, role) new_user.register() print("Successfully registered new user.") elif selection == '4': expelled_user = input("Enter the username of the user to be removed: ") if expelled_user in user.get_usernames(): user.remove_user(expelled_user) else: print("Username does not exist.") elif selection == '5': new_admin = input("Enter username to be upgraded: ") if new_admin in user.get_usernames(): user.upgrade(new_admin) print("Successfully upgraded ", user.get_name(new_admin)) else: print("Username not in database.") elif selection == '6': downgrade = input("Enter username to be downgraded: ") new_role = input("Enter new role: ") while new_role not in ['visitor', 'student', 'employee']: role = input('Incorrect input. Is the user a visitor, student or an employee? ') user.downgrade(downgrade, new_role) print("Successfully downgraded ", user.get_name(downgrade)) elif selection == '7': result_list = user.show_sign_ins() print("List of people who signed in today:") for each in result_list: print(user.get_name(each[0])) # extracting the names from the list of tuples returned elif selection == '8': result_list = user.show_sign_outs() print("List of people who signed out today:") for each in result_list: print(user.get_name(each[0])) # extracting the names from the list of tuples returned elif selection == '9': result_list = user.inside() print("List of people who are inside:") for each in result_list: print(user.get_name(each[0])) # extracting the names from the list of tuples returned else: print("Invalid selection.") else: print('You do not have admin rights.') else: print('Invalid credentials.') else: print('Invalid input.')
9b936388a54c9b309d4a24b05cf0aa91e1134a55
Alibi14/thinkpython-solutions
/12.1.py
397
3.765625
4
def make_histogram(s): hist = {} for x in s: hist[x] = hist.get(x, 0) + 1 return hist def most_frequent(s): d = make_histogram(s) t = [] for x, freq in d.items(): t.append((freq, x)) t.sort(reverse=True) res = [] for freq, x in t: res.append(x) return res print(most_frequent('elementary'))
25981a052a1533bf8c9c5a79ad81239d4b32e997
nicob825/Bruno_Nico
/Lesson_04/4.2/average4.3.py
256
4.1875
4
num1=int(input("Enter the first number:")) num2=int(input("Enter the second number:")) num3=int(input("Enter the third number:")) def AVG(): return (num1+num2+num3)/3 def calcAVG(): print("The average of your numbers is",AVG()) AVG() calcAVG()
4b78eb3213cf2949a151a2696a56fd2f5b2fd8a6
craig-gundacker/salmon-run-sim
/Salmon.py
2,231
3.78125
4
import turtle import random from Coast import* class Salmon: def __init__(self): self.turtle = turtle.Turtle() self.turtle.speed(0) self.turtle.up() self.turtle.shape("fish.gif") self.turtle.turtlesize(.2, .2, .2) self.turtle.color("blue") self.xPos = 0 self.yPos = 0 self.moveDistX = 10 self.moveDistY = 2 self.moveCoords = [(0, 1), (0, -1), (1, 1), (1, 0), (1, -1)] self.Coast = None self.breedTicker = 0 def setX(self, newX): self.xPos = newX def setY(self, newY): self.yPos = newY def getX(self): return self.xPos def getY(self): return self.yPos def setInCoast(self, aCoast): self.Coast = aCoast def appear(self): self.turtle.goto(self.xPos, self.yPos) self.turtle.showturtle() def hide(self): self.turtle.hideturtle() def move(self, newX, newY): self.Coast.moveThing(self.xPos, self.yPos, newX, newY) self.xPos = newX self.yPos = newY self.turtle.goto(self.xPos, self.yPos) def liveLife(self): self.tryToMove() #Moves each salmon. If salmon has not reached end of screen (i.e, spawning #grounds), the salmon moves in a semi-random direction across screen. #Otherwise, salmon has reached spawning grounds and is deleted def tryToMove(self): moved = False while moved is False: indexMove = random.randrange(len(self.moveCoords)) coord = self.moveCoords[indexMove] nextX = self.xPos + (coord[0] * self.moveDistX) nextY = self.yPos + (coord[1] * self.moveDistY) if self.xPos + self.moveDistX < self.Coast.maxX: if 0 <= nextY < self.Coast.maxY: if self.Coast.emptyLocation(nextX, nextY): self.move(nextX, nextY) moved = True else: self.move(self.Coast.maxX - 1, self.yPos) self.Coast.numSpawnSalmon += 1 self.Coast.delThing(self) moved = True
772bd61be5647005ebba9bbf379d4f656c406b31
GustafGroning/python_time_tracker
/main.py
1,894
3.640625
4
import time import datetime import stats as s import sys import json from datetime import date def start_up(): print("Hi! What would you like to do? \n") user_choice() def user_choice(): command = input("work on a task - type \"task\"\ncheck your stats - type \"stats\" \n \n ") if command == "task": check_task() if command == "stats": s.get_stats() repeat() else: print("\nillegal input, please try again: \n \n") user_choice() def check_task(): categoryList = ["work", "fun", "waste"] category = input("Which category are you working in? Your options are \nwork \nfun \nwaste \n \n") if category not in categoryList: print("\nThat's not a valid category, please try again!\n") check_task() else: print("\ngreat! Get to work, just tell me when you're done.") timer(category) def timer(category): startTime = time.time() input("\nType \"y\" whenever you've done with this task \n") time_log(category, startTime) def time_log(category, startTime): data = (time.time() - startTime) timeInt = int(data) save_time(category, timeInt) def repeat(): again = input("Would you like to do something else? y/n") if again == "y": user_choice() if again == "n": print("\n Bye for now!") sys.exit() if again not in "y" or "n": print("\n illegal input, please try again \n") repeat() def save_time(category, timeInt): minutes = (timeInt / 60) minutesConverted = round(minutes, 2) with open('timeLog.json', 'r+') as f: taskInput = ", \n" + "{" + "\"category\": \"{}\", \"timeInMinutes\": {}".format(category, minutesConverted) + "}" s = f.read() index = s.rfind("]") f.seek(index) f.write(taskInput) f.write(s[index:]) repeat() start_up()
e4edd4801db285d1381245e7b20c953fa6272a26
ColeRichardson/CSC148
/labs/lab 04/tournament.py
1,924
4.125
4
class Tournament: """A sports tournament. === Attributes === teams: The names of the teams in this tournament. team_stats: The history of each team in this tournament. Each key is a team name, and each value stores the number of games played and the number won. === Sample usage === >>> t = Tournament(['a', 'b', 'c']) >>> t.record_game('a', 'b', 10, 4) >>> t.record_game('a', 'c', 5, 1) >>> t.record_game('b', 'c', 2, 0) >>> t.best_percentage() 'a' """ # Attribute types teams: List[str] team_stats: Dict[str, List[int]] def __init__(self, teams: List[str]) -> None: """Initialize a new Tournament among the given teams. """ self.team_stats = {} # Line 1 self.teams = [] # Line 2 for team_name in teams: # Line 3 self.teams.append(team_name) # Line 4 self.team_stats[team_name] = [0, 0] # Line 5 def record_game(self, team1: str, team2: str, score1: int, score2: int) -> None: """Record the fact that <team1> played <team2> with the given scores. <team1> scored <score1> and <team2> scored <score2> in this game. Precondition: team1 and team2 are both in this tournament. """ # YOUR CODE HERE self.team_stats[team1][0] += 1 self.team_stats[team2][0] += 1 if score1 > score2: self.team_stats[team1][1] += 1 else: self.team_stats[team2][1] += 1 def best_percentage(self) -> str: """Return the team name with the highest percentage of games won. If no team has won a game, return the empty string. Otherwise if there is a tie for best percentage, return the name of any of the tied teams. """ # YOUR CODE HERE
ef925095ade10b5f7d8350ed0a07777300eccc13
HioLeong/IrnBru
/IrnBru/extraction/wordoperations.py
887
3.53125
4
"""Word Operations""" """ Provides basic operations with texts such as tokenizing and splitting articles to arbitrary lengths, filtering and removing characters """ import nltk from nltk import word_tokenize from nltk import pos_tag from nltk import sent_tokenize from nltk.corpus import stopwords import re def getWordToks(sent): toks = word_tokenize(sent) return toks def removePunct(text): puncts = ['.',',','\'','\"','`','\'\'','-','...','``'] return [w for w in text if w not in puncts] def removeStopWords(text): stop_words = stopwords.words("english") return [w for w in text if w not in stop_words] def splitSent(text): sentSets = sent_tokenize(text) return sentSets def splitParagraphs(text): paragraphSets = re.split('\n\n',text) return paragraphSets def filter_stops(text): return removeStopWords(removePunct(text))
d7de75ba4773cf4f33c846e471c37d85bc139a10
plantdink/code_in_place
/welcome_to_python/agreement_bot.py
536
4.5
4
""" Write a program which asks the user what their favorite animal is, and then always responds with "My favorite animal is also ___!" (the blank should be filled in with the user-inputted animal, of course). Here's a sample run of the program (user input is in bold italics): $ python agreement_bot.py What's your favorite animal? cow My favorite animal is also cow! """ def main(): animal = input("What is your favourite animal? ") print("My favourite animal is also " + animal + "!") if __name__ == '__main__': main()
c5f1e62e454be97cfaf22b02b30f7a014caba188
anshi9061/Python
/dict.py
710
4.03125
4
#dictionary #1 mydict={"fruit":"apple","color":"red","seed":"yes"} print(mydict) #2 thisdict={"vegetable":"onion"} mydict.update(thisdict) print(mydict) #3 dict={"a":100,"b":200} x=input("enter the key:") if x in dict: print("key present") else: print("not present") #4 mydict.pop("fruit") print(mydict) #5 x={1:10,2:20} y={3:30,4:40} z={5:50,6:60} x.update(y) print(x) x.update(z) print(z) #set #6 myset={100,200,300} print(myset) #7 myset.remove(100) print(myset) #8 aset={1,2,3,4} bset={2,3,5,6} aset.intersection_update(bset) print(aset) #9 cset=aset.union(bset) print(cset) #10 aset.symmetric_difference_update(cset) print(aset)
b8d4768c0283b48310377fd6a2d44e0cba580c45
ziyadalvi/PythonBook
/6The Dynamic Typing Interlude/2Types Live with Objects, Not Variables.py
600
4.4375
4
#Types Live with Objects, Not Variables a = 3 # It's an integer a = 'spam' # Now it's a string a = 1.23 # Now it's a floating point """Names have no types so we are not changing the type here, but we simply have made variable refer to another object. Objects, on the other hand, know what type they are—each object contains a header field that tags the object with its type""" #The integer object 3, for example, will contain #the value 3, plus a designator that tells Python that the object is an integer (strictly #speaking, a pointer to an object called int, the name of the integer type).
faeb005db2d9a01aa234fef63673d7baf3ffbf7f
piotrbla/PyChessAnalizer
/board.py
918
3.890625
4
class Field: def __init__(self, r, c): self.r = r self.c = c self.letter = chr(c + ord('A') - 1) class Board: def __init__(self): self.fields = [] for r in range(1, 9): fields_row = [] for c in range(1, 9): fields_row.append(Field(r, c)) self.fields.append(fields_row) def display(self): for fields_row in reversed(self.fields): for field in fields_row: print(field.letter, end='') print(field.r, end=' ') print() def display_reversed(self): for fields_row in self.fields: for field in reversed(fields_row): print(field.letter, end='') print(field.r, end=' ') print() def main(): b = Board() b.display() b.display_reversed() if __name__ == '__main__': main()
fecaddbbe09b818173b95ed6021cfcd1de0dfb74
amenson1983/Python_couses
/Chapter 3 (11).py
310
3.890625
4
book = int(input("How many books bought? :")) score = 0 if book<=0: score = 0 elif book>0 and book<2: score = 0 elif book>=2 and book<4: score = 5 elif book>=4 and book<6: score = 15 elif book>=6 and book<8: score = 30 elif book>=8: score = 60 print("Your score is: ", score, "points.")
d7abe765304e2baf83f46f6e6f75a3ce9dc2a4a2
intfloat/AlgoSolutions
/hackerrank/Practice/python/NestedList.py
448
3.609375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from sys import stdin N = int(stdin.readline().strip()) students = [] for _ in xrange(N): name = stdin.readline().strip() score = float(stdin.readline().strip()) students.append((score, name)) score = sorted(list(set([e[0] for e in students]))) res = [] for sc, nm in students: if sc == score[1]: res.append(nm) res = sorted(res) print '\n'.join(res)
21007d05f012078a6b32149ef90e11319702953e
joncatanio/housing-classifier
/src/kc_model.py
2,136
3.953125
4
# Description: Kings County (Seattle area) linear regression model to predict # the price of a unit given a number of features. # # Model ID: 'KINGS_COUNTY' # Model Features: # 'bedrooms' - number of bedrooms # 'bathrooms' - number of bathrooms # 'sqft_living' - square footage of the living space # 'sqft_lot' - square footage of the entire lot # 'zipcode' - zipcode the property is located in # 'grade' - overally grade given to the unit based on King County system # 'condition' - how good the overall condition of the house is # 'yr_built' - year in which the house was built import pandas as pd from sklearn import linear_model class KingsCountyModel: features = ['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'zipcode', 'grade', 'condition', 'yr_built'] def __init__(self): self.instantiate_model() def instantiate_model(self): self.df = pd.read_csv('../datasets/kc_house_data.csv') ind_vars = self.df[KingsCountyModel.features] target = self.df['price'] # Split the data into training and testing sets x = int(len(ind_vars) * 0.70) train_ind_vars = ind_vars[0:x] train_target = target[0:x] test_ind_vars = ind_vars[x:len(ind_vars)] test_target = target[x:len(target)] self.lmodel = linear_model.LinearRegression() self.lmodel.fit(train_ind_vars, train_target) print("Kings County Model R^2 Score:", self.lmodel.score(test_ind_vars, test_target)) def predict(self, record): df = pd.DataFrame([[record['bedrooms'], record['bathrooms'], record['sqft_living'], record['sqft_lot'], record['zipcode'], record['grade'], record['condition'], record['yr_built']]], columns=KingsCountyModel.features) return self.lmodel.predict(df) def test(): model = KingsCountyModel() test = {'model': 'KINGS_COUNTY', 'bedrooms': 3, 'bathrooms': 1, 'sqft_living': 1180, 'sqft_lot': 5650, 'zipcode': 98178, 'grade': 7, 'condition': 3, 'yr_built': 1955 } print(model.predict(test)) if __name__ == '__main__': test()
bcff14a0fc7e9a6fa5d3750e08b2ce7db4660179
benbendaisy/CommunicationCodes
/python_module/examples/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py
1,188
3.640625
4
from collections import defaultdict class Solution: """ Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters. Example 1: Input: s = "eceba", k = 2 Output: 3 Explanation: The substring is "ece" with length 3. Example 2: Input: s = "aa", k = 1 Output: 2 Explanation: The substring is "aa" with length 2. Constraints: 1 <= s.length <= 5 * 104 0 <= k <= 50 """ def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int: if not s or k < 1: return 0 hashMap = defaultdict(lambda: 0) maxLength = 0 l = 0 for i in range(len(s)): hashMap[s[i]] = i if len(hashMap) == k + 1: minIndex = min(hashMap.values()) del hashMap[s[minIndex]] l = minIndex + 1 maxLength = max(maxLength, i - l + 1) return maxLength if __name__ == "__main__": s = "ab" solution = Solution() ret = solution.lengthOfLongestSubstringKDistinct(s, 1) print(ret)
f2b3b9dc851d41a0aef5f6ad56e389b3f843b994
chenshu/sorting-algorithms
/insertion.py
644
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint def prepare(): cnt = 10 return [randint(0, cnt) for _ in range(cnt)] def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] # compare avg O(N^2) best O(N) worst O(N^2) # swap avg O(N^2) best O(0) worst O(N^2) def insertion_sort(arr): length = len(arr) for i in range(1, length): for j in range(i, 0, -1): if arr[j] < arr[j - 1]: swap(arr, j - 1, j) else: break def main(): arr = prepare() print arr insertion_sort(arr) print arr if __name__ == '__main__': main()
92339a15cd35bc5e5e2b05f5a34f3a2b231b79cf
zhhiyuan/Cryptography
/Vigenere/1.py
3,481
3.9375
4
''' 实现维吉尼亚密码,用键盘接收明文和密钥,屏幕打印密文和解密后的明文 ''' def get_new_key(key,length): ''' 统一英文和密钥的长度 :param key: :param length: :return: ''' if len(key) == length: return key elif len(key) > length: #如果密钥过长,缩减密钥长度 return key[:length] else: #如果密钥过短,扩大密钥长度 round = int(length/len(key)) key = key * round + key[: length % len(key)] return key def get_ciphertext(plaintext,key,type): ''' 加密(解密)的处理部分 :param plaintext: :param key: :param type: :return: ''' ciphertext=[] if type=='cipher': for i in range(len(plaintext)): if plaintext[i].isalpha(): ciphertext.append(chr((ord(plaintext[i]) - ord('a') + ord(key[i]) - ord('a')) % 26 + ord('a'))) else: ciphertext.append(plaintext[i]) return ciphertext else: for i in range(len(plaintext)): if plaintext[i].isalpha(): ciphertext.append(chr((ord(plaintext[i]) - ord(key[i])) % 26 + ord('a'))) else: ciphertext.append(plaintext[i]) return ciphertext def cipher(plaintext, key): ''' 加密 :param plaintext: :param key: :return: ''' key=get_new_key(key,len(plaintext))#统一密文和明文的位数 ciphertext=get_ciphertext(plaintext,key,'cipher') return ciphertext def encipher(plaintext, key): ''' 解密 :param plaintext: :param key: :return: ''' key = get_new_key(key, len(plaintext)) # 统一密文和明文的位数 ciphertext = get_ciphertext(plaintext, key, 'encipher') return ciphertext def deal_data(plaintext,ciphertext,val): ''' 修改输出格式 :param plaintext: :param ciphertext: :param val: :return: ''' str_plaintext='' str_ciphertext='' for i in range(len(plaintext)): str_plaintext=str_plaintext+'{}'.format(plaintext[i]) str_ciphertext=str_ciphertext+'{}'.format(ciphertext[i]) if val: #如果明文是小写 return str_plaintext.lower(),str_ciphertext.upper() else: return str_plaintext.upper(),str_ciphertext.lower() if __name__ == '__main__': while True: print('pelase choose encryption or decryption:') print('1.encryption\n2.decryption') choose = input() if choose == '1': plaintext = input('please input plaintext:') key = input('please input key:') val = plaintext.islower() # 判断明文是不是小写 key = key.lower() plaintext = plaintext.lower() ciphertext = cipher(plaintext, key) plaintext, ciphertext = deal_data(plaintext, ciphertext, val) print('The ciphertext is :{}\n'.format(ciphertext)) elif choose == '2': ciphertext = input('please input ciphertext:') key = input('please input key:') val = ciphertext.islower() key = key.lower() ciphertext = ciphertext.lower() plaintext = encipher(ciphertext, key) ciphertext, plaintext = deal_data(ciphertext, plaintext, val) print('The plaintext is :{}\n'.format(plaintext)) else: print('Wrong choice!Please input again!\n')
dd9a932f54249b50056801cdd3012354e9796015
nandoken/CIS-122
/labs/lab4.py
1,998
4.5625
5
__author__ = 'Fernando Ames' # This program asks the user to enter a positive natural number and find whether it is # an even or odd number after that it finds the factorial of that number # Input Variable: num # Output Variable: factorial, number # Module introduction() # Set num = input("Please enter a positive natural number to check whether it is even or odd: ") # while not num.isdigit() or num== '0': # Display "Please Enter a positive natural number. Negative, floating numbers and zero are not allowed" # return eval(num) def introduction(): num = input("Please Enter a positive natural number to check whether it is even or odd: ") while not num.isdigit() or num == '0': num = input("Please Enter a positive natural number. Negative, floating numbers and zero are not allowed") return eval(num) # Function Real finding_the_factorial(Real num) # Declare factorial = 1 # for i in range(1, num+1): # factorial *= i # return factorial # End Function def finding_the_factorial(num): factorial = 1 for i in range(1, num + 1): factorial *= i return factorial # Function Real checking_input_number(Real factorial, Real number) # if number % 2 == 0 Then # print("The number", number,"is an even number.") # else: # print("The number", number, "is an odd number.") # Display ("The factorial of the number", number,"is", factorial) # End Function def checking_input_number(factorial, number): if number % 2 == 0: print("The number", number, "is an even number.") else: print("The number", number, "is an odd number.") print("The factorial of the number", number, "is:", factorial) # Module main # # Set number = introduction() # Set fact = finding_the_factorial(number) # Call checking_input_number(factorial, number) # End Module def main(): number = introduction() factorial = finding_the_factorial(number) checking_input_number(factorial, number) main()
18d26a9833507daa03d5cbc2d57f8b398b21da75
ZoranPandovski/al-go-rithms
/strings/string_search/all_substrings_occurances/python/all_substrings_occurances.py
4,737
3.828125
4
#!/bin/python3 import sys, string, re from random import * from timeit import default_timer as timer from collections import * def randstr(N,alphabet=string.ascii_lowercase): l=len(alphabet) return "".join( alphabet[randint(0,l-1)] for _ in range(N)) def timefunc(func, *args, **kwargs): """Time a function. args: iterations=1 Usage example: timeit(myfunc, 1, b=2) """ try: iterations = kwargs.pop('iterations') except KeyError: iterations = 1 elapsed = sys.maxsize start = timer() for _ in range(iterations): result = func(*args, **kwargs) elapsed = (timer() - start)/iterations print(('{}() : {:.9f}'.format(func.__name__, elapsed))) return result # Python program for Naive Pattern Searching def searchNaive(txt,pat): M = len(pat) N = len(txt) res=[] # A loop to slide pat[] one by one for i in range(N-M + 1): # For current index i, check for pattern match if txt[i:i+M] == pat: res.append(i) return res def searchRE(txt,pat): M = len(pat) N = len(txt) res=[m.start() for m in re.finditer('(?=%s)'%(pat), txt)] return res #https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/ #lps[i] could also be defined as longest prefix which is also proper suffix. def computeLPSArray(pat): M = len(pat) lenp = 0 # lenpgth of the previous longest prefix suffix lps=[0]*M # lps[0] is always 0 i = 1 # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]==pat[lenp]: lenp += 1 lps[i] = lenp i += 1 else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if lenp != 0: lenp = lps[lenp-1] # Also, note that we do not increment i here else: # lps[i] = 0 i += 1 return lps def searchKMP(txt,pat): M = len(pat) N = len(txt) res=[] # create lps[] that will hold the longest prefix suffix # values for pattern j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) lps = computeLPSArray(pat) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: res.append(i-j) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 return res def computeLPSmod(pat): M = len(pat) lenp = 0 # lenpgth of the previous longest prefix suffix lps=[0]*M # lps[0] is always 0 i = 1 mem=defaultdict(int) # the loop calculates lps[i] for i = 1 to M-1 while i < M: if pat[i]==pat[lenp]: lenp += 1 lps[i] = lenp mem[pat[i]] = lenp i += 1 else: if lenp != 0: #lenp = lps[lenp-1] lenp=mem[ pat[i] ] i+=1 else: # lps[i] = 0 i += 1 return lps def searchKMPmod(txt,pat): M = len(pat) N = len(txt) res=[] # create lps[] that will hold the longest prefix suffix # values for pattern j = 0 # index for pat[] # Preprocess the pattern (calculate lps[] array) lps = computeLPSmod(pat) i = 0 # index for txt[] while i < N: if pat[j] == txt[i]: i += 1 j += 1 if j == M: res.append(i-j) j = lps[j-1] # mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j-1] else: i += 1 return res if __name__ == "__main__": alpha="abc" #alpha=string.ascii_lowercase #S="AABAABACAADAABAAABAA" #P="AAB" S=randstr(1000000,alphabet=alpha) P=randstr(10,alphabet=alpha) rep=1 print("Len S={}, len P={}, iters={}".format(len(S),len(P),rep)) res0=timefunc( searchNaive, S, P, iterations=rep) print("Found:",len(res0)) res=timefunc( searchRE, S, P, iterations=rep) if(res!=res0): print("Wrong") res=timefunc( searchKMP, S, P, iterations=rep) if(res!=res0): print("Wrong") res=timefunc( searchKMPmod, S, P, iterations=rep) if(res!=res0): print("Wrong") #print(S) #print(P)
67dd07b7ffa31b09e4e7a667464da4a121741572
KulataevKanat/PythonData
/structures/oop/object/str.py
1,110
3.828125
4
class Car: def __init__(self, id, mark, color, model, dateOfManufacture) -> None: self.id = id self.mark = mark self.color = color self.model = model self.dateOfManufacture = dateOfManufacture def display_info(self): print(self.__str__) def __str__(self) -> str: return "\n id: {} \n Марка: {} \n Цвет: {} \n Модель: {} \n Дата начала-окончания производства: {}" \ .format(self.id, self.mark, self.color, self.model, self.dateOfManufacture) class Main: car1 = Car("10", "Tesla", "Белый", "X 100D", "Январь 2015 - В производстве") print(car1.__str__()) car2 = Car("36", "Toyota", "Чёрный", "Camry", "Январь 2014 - Январь 2017") print(car2.__str__()) car3 = Car("43", "Ford", "Серый", "Mustang Shelby GT 500", "Январь 2009 - Январь 2011") print(car3.__str__()) car4 = Car("16", "Nissan", "Красный", "GT-R", "Январь 2016 - В производстве") print(car4.__str__())
eda80c624f36171e5b67419e16aad35beb683e16
AlesyaKovaleva/IT-Academy-tasks
/tasks_3/list_reverse_max_0_1.py
382
3.90625
4
""" Задача 0 Дан список А1..AN. Вывести элементы списка в обратном порядке. """ list_number = [1, 2, 3, 4, 5, 6] list_number.reverse() print(list_number) """ Задача 1 Исключить из списка А1..AN максимальный элемент. """ list_number.remove(max(list_number)) print(list_number)
f76260ff6ecddfef52ba3edc87235f7cacafeb21
heathersky/ising
/python_with_c/annealing.py
391
3.546875
4
def T_anneal(T, step, num_steps, num_burnin): #implement annealing code here T_a = T T_0 = T_a+1 m = -T_0/num_burnin T_step = m*step+T_0 return float(max(T_step,T_a)) def B_anneal(B, step, num_steps, num_burnin): #implement annealing code here B_a = B B_0 = B_a+1 s = -B_0/num_burnin B_step = s*step+B_0 return float(max(B_step,B_a))
3928327ae11bb3b5f2397dec1d2d77ecfdce78ad
cmiddlet/FinalAssignment
/selectimage.py
1,544
3.59375
4
import requests import geojson def select_image(url, key, point, image_type, file_name): """Downloads an image matching the selected coordinates. Args: url (str): The source url of the image key (str): Authorisation key for the website point (lst): Decimal coordinates of the point for which the map should be retrieved image_type (str): The type of image you want to open (visual or analytic) file_name (str): The direction and file name of the created tif file Result: Tif file containing the downloaded image """ #Set coordinates bounding box nw = point se = (point[0]+0.001, point[1]+0.001) ne = (se[0], nw[1]) sw = (nw[0], se[1]) poly = geojson.Polygon([[nw, ne, se, sw, nw]]) intersects = geojson.dumps(poly) params = {"intersects": intersects,} #Retrieve map r = requests.get(url, params=params, auth=(key, '')) r.raise_for_status() data = r.json() scenes_data = data["features"] for scene in scenes_data: link = scene["properties"]["data"]["products"][image_type]["full"] r = requests.get(link, stream=True, auth=(key, '')) if 'content-disposition' in r.headers: local_filename = file_name else: local_filename = '.'.join(link.split('/')[-2:]) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return local_filename
63983b41e167860db1459d814ecfb4d31f3a9a8a
XiangyuDing/Beginning-Python
/Beginning/python3_cookbook/ch02/14-joins.py
1,057
3.9375
4
# 2.14 合并拼接字符串 parts = ['Is','Chicago','Not','Chicago?'] print(' '.join(parts)) print(','.join(parts)) print(''.join(parts)) a = 'Is Chicago' b = 'Not Chicago?' print(a + ' ' + b) print('{} {}'.format(a,b)) print(a + ' ' + b) a = 'Hello' 'World' print(a) data = ['ACME',50,91.1] print(','.join(str(d) for d in data)) # Version 1 (string concatenation, when string is small) f.write(chunk1 + chunk2) # Version 2 (separate I/O operations, when string is big) f.write(chunk1) f.write(chunk2) def sample(): yield 'Is' yield 'Chicago' yield 'Not' yield 'Chicago?' text = ''.join(sample()) for part in sample(): f.wirte(part) def combine(source, maxsize): parts = [] size = 0 for part in source: parts.append(part) size += len(part) if size > maxsize: yield ''.join(parts) parts = [] size = 0 yield ''.join(parts) # combine with files operations with open('filename','w') as f: for part in combine(sample(), 32768): f.wirte(part)
cf9fbffe54f26b940fddb7be0e9839f7be2f3168
chibiboss/Python-challanges
/Level_1/level1_ex3.py
512
3.96875
4
""" Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Hint Use __init__ method to construct some parameters """ class Palabra: def __init__(self, letras): self.letras = letras def getString(self): texto = input("introduce texto: ") self.letras = texto return texto def printString(self): return self.letras.upper() if __name__== '__main__': a = Palabra("") a.getString() print (a.printString())
763d87e47131d4e6043f7122f85ec391bc55917d
AbhishekTiwari0812/python_codes
/Spiral.py
694
3.640625
4
def R(i): global Size if i==Size: return else: global row global column for p in range(i): print A[row][column], column+=1 def U(i): global row global column for p in range(i): print A[row][column], row-=1 def L(i): global row global column for p in range(i): print A[row][column], column-=1 def D(i): global row global column for p in range(i): print A[row][column], row+=1 A=[] Size=input('Size=') from random import randint for i in range(Size): q=[] A.append(q) for j in range(Size): q.append(randint(1,100)) print q row=Size/2 column=Size/2 for i in range(len(A)+1): if i%2==1: U(i) R(i) else: D(i) L(i)
6c3798e4d88b8910cb8f4e166bf986281d384d30
gabriel-valenga/CursoEmVideoPython
/ex111.py
242
3.625
4
from utilidadesCeV import moeda valor = float(input('Digite um valor:')) aumento = float(input('Digite um valor para aumento:')) reducao = float(input('Digite um valor para redução:')) print(moeda.resumoValorMoeda(valor, aumento, reducao))
dd6fc46a8698e2f0a97904435be642f3850d0e2e
southpawgeek/perlweeklychallenge-club
/challenge-182/ealvar3z/python/ch-1.py
673
4.5625
5
#!/usr/bin/env python3 """ Created Thu Oct 13 07:47:17 PM EDT 2022 @author: E. Alvarez You are given a list of integers. Write a script to find the index of the first biggest number in the list. Example Input: @n = (5, 2, 9, 1, 7, 6) Output: 2 (as 3rd element in the list is the biggest number) Input: @n = (4, 2, 3, 1, 5, 0) Output: 4 (as 5th element in the list is the biggest number) """ import argparse p = argparse.ArgumentParser(description='Perl Weekly Challenge 182') p.add_argument( "-l", "--list", nargs="?", type=list, default=[4, 2, 3, 1, 5, 0]) args = p.parse_args() max_val = max(args.list) print(args.list.index(max_val))
ef658927b0d5cf2a4db44064a36d4c185eb07ff0
khanak077/Number-Guessing
/number guessing.py
1,488
4.03125
4
n = int(input("Enter no. from 1 to 10: ")) x = 8 for i in range(3): if (n != x): if (i == 1): print("The no. entered is wrong. Two chance left") n = int(input("Next chance: ")) elif (i == 2): print("The no. entered is wrong. One chance left") n = int(input("Next chance: ")) print("Chances over") if (x == n): print("The numb8er chosen is correct") break if (x == n): print("The number chosen is correct") break elif (x % 2 == 0): print("Choose a no. which is divisible by 2") elif (x % 3 == 0): print("Choose a no. which is divisible by 3") elif (x % 5 == 0): print("Choose a no. which is divisible by 5") else: print("Choose a no. which is divisible by 7") if (x - n == 1): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 2): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 3): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 4): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 5): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 6): print("The no. chosen is wrong. Choose a greater no.") elif (x - n == 7): print("The no. chosen is wrong. Choose a greater no.")
b42ac0432125d8ce7d88f379355ce74b2bf9dd46
ornichola/learning-new
/pythontutor-ru/07_lists/06_maximal_element.py
558
3.875
4
""" http://pythontutor.ru/lessons/lists/problems/maximal_element/ Дан список чисел. Выведите значение наибольшего элемента в списке, а затем индекс этого элемента в списке. Если наибольших элементов несколько, выведите индекс первого из них. """ _l = input().split() l = [int(i) for i in _l] maximum = l[0] for i in range(len(l)): if l[i] > maximum: maximum = l[i] print(maximum, l.index(maximum))
92c926f6ef8bed7bf75ffef7867a390c70abffff
felicitia/HiPHarness
/data-processing/merge_alg.py
1,125
3.65625
4
from csv import writer from csv import reader import os input_dir = '/Users/yixue/Documents/Research/LessIsMore/R/实验' def add_column_in_csv(input_file, output_file, alg): # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'a') as write_obj: csv_reader = reader(read_obj) csv_writer = writer(write_obj) # Read each row of the input csv file as list next(csv_reader) # skip header for row in csv_reader: # Append the default text in the row / list row.append(alg) # Add the updated row / list to the output file csv_writer.writerow(row) if __name__ == "__main__": for filename in os.listdir(input_dir): if filename.endswith(".csv"): alg = filename.split('_')[0] output = filename.replace(alg, 'all') # Add column with same text in all rows add_column_in_csv(os.path.join(input_dir, filename), os.path.join(input_dir, output), alg) else: continue
bcefd380bd94d436004b23ffe3faf674b8810c1b
cdbradley/py-numerical-programs
/7.Gambling_game/bradley_homework7.py
2,347
4.25
4
#Colt Bradley #2.2.16 #Homework 7 #import random import random as r #Interact with the user, explain what is going on. print "Welcome to the Casino! We've a special on the martingale" print "betting system, want to play? I see you have $20, buy in" print "is $2." ans = " " #Determine starting values for the variables while ans != ("n" or "N" or "no" or "No" or "y" or "Y" or "yes" or "Yes"): ans = raw_input("Would you like to use default values? Bet = $2, Goal = $40 (Y or N): ") if ans == ("n" or "N" or "no" or "No"): goal = raw_input("How much money would you like to win? ") goal = int(goal) bet1 = raw_input("What do you want as your starting bet? ($2 min, $20 max) ") bet1 = int(bet1) elif ans == ("y" or "Y" or "yes" or "Yes"): goal = 40 bet1 = 2 break else: print "What? It's a simple yes or no question!" #define vars money = 20 bet = bet1 it = 0 #while loop to simulate betting. while (0 < money < goal): rand = r.randint(1,38) #this section defines the 0 and 00 numbers if rand == 37: rand = 0 elif rand == 38: rand = 39 #We'll change this to 00 later else: if rand%2 == 0: #this case is if the number is even money = money + bet rand = str(rand) print "Your bet is {}".format(bet) print "ball lands on {}".format(rand) print "you win {}, you have {} dollars".format(bet,money) print bet = bet1 it = it+1 elif rand%2 ==1: #This is the cas tha tthe number is odd money = money - bet if rand == 39: rand = "00" else: rand = str(rand) it = it+1 print "Your bet is {}".format(bet) print "ball lands on {}".format(rand) print "you lose {}, you have {} dollars".format(bet,money) print bet = 2*bet #when money is outside of selected values, we get results as follows if money <= 0: print "You've lost everything after {} tries!".format(it) print "What will you tell the kids?" else: print "Congrats! It took you {} tries, but now you have {} dollars!".format(it,money)
5a699576ed252fa12169855c6f81a4a1a95f117d
AlejandroZapett/serieEjerciciosPython
/7_vocal.py
293
3.921875
4
import argparse def Vocal(letra): return letra+" es una vocal" if letra in ['a', 'e', 'i', 'o', 'u'] else "lo que ingresaste no es una vocal" parser = argparse.ArgumentParser() parser.add_argument("-l", "--letra", help="Ingresa una letra") args = parser.parse_args() print(Vocal(args.letra))
285c38f82620a0b431dcc5b19411a9ea9155f893
Shashi-Chaurasia/Python_array_practice
/append_item.py
706
3.8125
4
# from array import* # list = [2,4,6,8,3,5] # arr = array('i' , []) # arr.fromlist(list) # print(str(arr)) # from array import * # array_num = array('i', [1, 3, 5, 7, 9]) # print("Original array: "+str(array_num)) # print("Insert new value 4 before 3:") # array_num.pop(2) # print("New array: "+str(array_num)) def dublicate_number(nums): new_list = set() dubilacet_no = -1 for i in range(len(nums)): if nums[i] in new_list: return nums[i] else: new_list.add(nums[i]) return dubilacet_no print(dublicate_number([1,2,3,4,5,6,7,4])) print(dublicate_number([1,2,3,4,5,6,7])) print(dublicate_number([1,1,2,3,4,5,6,7,4]))
fb2d7edddceb9abbc0a2d4e9151b6ff215901cc6
daniel-reich/ubiquitous-fiesta
/YwXwxa6xmoonFRKQJ_3.py
423
3.5625
4
def josephus(n): people = [i for i in range(n)] index = 1 if n < 1: return False elif n == 1: return 0 else: while len(people) != 1: if people[index] == people[-1]: people.pop(index) index = 1 elif people[index] == people[-2]: people.pop(index) index = 0 else: people.pop(index) index += 1 return people[0] # [0, 1, 2, 3]
5f60fa3d4c60aea15ec3095aac9d927a5f1de13a
bgoonz/UsefulResourceRepo2.0
/_Job-Search/InterviewPractice-master/InterviewPractice-master/Python/workSchedule.py
725
3.671875
4
def findSchedules(workHours, dayHours, pattern): # Write your code here current = [] remainingList = [] for i in pattern: for s in i: if s.isdigit(): current.append(int(s)) else: remainingList.append(s) remaining = len(remainingList) currentTotal = sum(current[0 : len(current)]) hoursLeft = workHours - currentTotal if (hoursLeft % remaining) == 0: value = hoursLeft / remaining strVal = str(int(value)) result = pattern.replace("?", strVal) return result def main(): workHours = 56 dayHours = 8 pattern = "???8???" print(findSchedules(workHours, dayHours, pattern)) main()
fea7e6e238f196d6c721654579cb55be269bdd79
Misterion777/NetworkProgramming
/MailClient/main.py
2,115
3.546875
4
from MailClient.mail import * import getpass GOOGLE_PORT = 587 YANDEX_PORT = 465 def print_help(): print("Available commands:") print("SEND 'msg' <recipient> - send message to recipient") print("SHOW <n> - show n last messages") print("HELP - get list of commands") print("EXIT - close connection and exit\n") def main(): print("Welcome to E-Mail CLIENT!") print("Enter <server_name> <server_port>") print("(: Google port: {} Yandex/Mail.ru port: {} :)".format(GOOGLE_PORT, YANDEX_PORT)) while True: server_name, server_port = input().split(' ') try: email_conn = EmailConnection(server_name, server_port) except Exception as e: print(e) print("Try again") continue while True: log = input("Email:\n") psw = getpass.getpass() try: email_conn.auth(log, psw) break except smtplib.SMTPAuthenticationError as e: print(e) print("Try again") print_help() while True: inpt = input() message = inpt.split("'") if len(message) != 1: message = message[1] command = inpt.split(" ") command[0] = command[0].upper() if command[0] == 'SEND': email_conn.send_msg(message, command[-1]) elif command[0] == 'SHOW': if len(command) == 1: email_conn.show_messages(0) else: email_conn.show_messages(command[1]) try: id = input() email_conn.show_message(int(id)) except KeyError: pass elif command[0] == 'HELP': print_help() elif command[0] == 'EXIT': email_conn.close() exit(0) else: print("Wrong command! Type HELP to get list of commands") print("...") if __name__ == '__main__': main()
001e8c32ba8f889d49a332f02653c6cd2675a4e6
nikodemusk/PythonPrimeNumberTools
/primetools.py
3,560
3.9375
4
from math import sqrt def factorize(myNumber, checkPowers = True): # All the comments will be translated to English in the near future # Kommer att innehålla primfaktorerna till myNumber # Om powers = True, så innehåller den alla förekomster # av respektive enskild faktor (fullständig faktorisering). # Om powers = False finns enbart respektive unik primfaktor # med en gång oavsett antal förekomster. primeFactors = [] # Kolla först trivialiteter, samt om talet faktiskt är ett primtal if myNumber < 2: print("Bad input") return [] if (myNumber == 2 or myNumber == 3): primeFactors.append(myNumber) return primeFactors elif isPrime(myNumber): primeFactors.append(myNumber) return primeFactors # Loopen som letar efter delare for i in range(2, int(myNumber / 2) + 1): # Bara för att det är en delare behöver det inte vara en primfaktor... if myNumber % i == 0: if isPrime(i): # Om sant, i är en primfaktor till myNumber... primeFactors.append(i) # ...och ska läggas till i primeFactors. # Körs enbart om vi ska kolla efter mulipler av en och samma primfaktor if(checkPowers): # Nu måste vi kolla om det finns flera lika faktorer. # Det görs genom att testa om i^n (med ökande n) är # jämnt delbart med det talet som faktorisera. n = 1 # n håller reda på vilken potens som primtalet förekom i # (t ex 24 = 2^3 * 3^1) # Loopen kollar om det aktuella talet... while (i ** n) <= int(myNumber / 2) + 1: n += 1 if myNumber % i ** n == 0: if isPrime(i): # Ja, samma i som ovan förekommer en gång till i primtalsuppdelningen primeFactors.append(i) # Fortsätt loopa för att ev. hitta flera potenser av ett och samma i i talet # Ett värde på i är nu behandlat... # ...gå vidare till nästa. return primeFactors # En funktion som genererar primtal mellan två värden def genPrimesBetween(lower, upper): primeNumbers = [] for number in range(lower, upper + 1): if isPrime(number): primeNumbers.append(number) return primeNumbers # En funktion som genererar de n första primtalen def genFirstPrimes(number): primeList = [2] numberOfPrimes = 1 while numberOfPrimes < number: primeList.append(nextPrime(primeList[-1])) numberOfPrimes += 1 return primeList # En funktion som returnerar primtalet efter det givna talet def nextPrime(number): number += 1 while not isPrime(number): number += 1 return number # En funktion som returnerar primtalet före det givna talet def prevPrime(number): if number > 2: number -= 1 while not isPrime(number): number -=1 return number # Denna funktion avgör om ett tal är ett primtal def isPrime(number): if (number < 2): return False if (number <= 3): return True i = 2 while i <= sqrt(number): if (number % i) == 0: return False i += 1 return True # Denna funktion avgör om två tal är relativt prima def isRelPrime(a, b): if gcd(a,b) > 1: return False return True # Denna funktion returnerar största gemensamma delare till två tal def gcd(a, b): if a % b != 0: return gcd(b, a % b) else: return b # Denna funktion returnerar minsta gemensamma nämnare till två tal def lcd(a, b): return(a * b // gcd(a, b))
055fa4e5ab25bc1b8acbc59c36415ba9bd50cb18
Mikhaelius/phyton
/calc.py
848
4.21875
4
#simple calc def operateCalc(): first = '' second = '' operator = "" while first == '': try: first = int(input("Enter first Number.")) except ValueError: first = '' while second == '': try: second = int(input("Enter first Number.")) except ValueError: second = '' while operator == "": operator = input("Enter a valid operator (+-*/).") if operator != "+" and operator != "-" and operator != "*" and operator !="/": operator = "" #print(first) return first ,second ,operator def calculate(): data = operateCalc() first, second, operator = data if operator == '+': print(first + second) if operator == '-': print(first - second) if operator == '*': print(first * second) if operator == '/': print(first / second) calculate() calculate()
b1bae8421f1085f70bd33ad7e9098543c3ecf1eb
codenewac/python
/pythonbegin/learn_python/favorite_places6_9.py
372
3.53125
4
favorite_places={ 'newton':['beijing','paris','london'], 'bohr':['shanghai','berlin','newyork'], 'enstein':['Munich','Switzerland','beijing'] } for name,favorite_place in favorite_places.items(): print('\n'+name.title()+' love these cities:') for favorite_place_1 in favorite_place: print("\t"+favorite_place_1.title()) print("I love you baby")
2e07d2410daf177f45664f270591aef4323392fb
codic96/Array-Python-Code
/array1.py
248
4.0625
4
#Python 3 code to find sum #of elements in given array #driver function arr = [] #input values to list arr = [12,3,4,15] #sum() is an inbuilt function in Python #the value ans = sum(arr) #display sum print('Sum of the array is',ans)
fc5c91e8b0739c3a242d8691964aa05d6d19a885
JinSeonGyeong/202003_ai
/진선경/pre_python_05.py
227
3.8125
4
"""5. N을 입력 받은 뒤, 구구단 N단을 출력하는 프로그램을 작성하시오(format 활용)""" a = int(input("구구단의 아무단을 입력하세요.")) for i in range(1, 10): print(f"{a} X {i} = {a*i}")
04b0460162218b06670b4f6b4c14f1421cb6756b
Mariamjaludi/algorithms-practice
/python/frogJump.py
788
3.734375
4
def canCross(stones): for i in range(3, len(stones)): if stones[i] > stones[i - 1] * 2: return False lastStone = stones[-1] positions = [] # stack jumps = [] # stack stonePositions = {} for stone in stones: stonePositions[stone] = True positions.append(0) jumps.append(0) while positions: position = positions.pop() jumpDistance = jumps.pop() for i in range(jumpDistance - 1, jumpDistance + 2): if i <= 0: continue nextPosition = position + 1 if nextPosition == lastStone: return True elif nextPosition in stonePositions: positions.append(nextPosition) jumps.append(i) return False
1fe4b7582110ad80152dd6d4c469e55918b96aff
Djamal1/PythonProg
/Python1/l06/days.py
1,293
3.765625
4
import random player1 = {"Счёт": 1000} player2 = {"Счёт": 1000} player1["Имя"] = input("Введите имя первого игрока: ") player2["Имя"] = input("Введите имя второго игрока: ") while True: player1["Ставка"] = int(input("Введите ставку: ")) player2["Ставка"] = int(input("Введите ставку: ")) player1["Бросок"] = random.randint(1, 12) player2["Бросок"] = random.randint(1, 12) print(player1) print(player2) if player1["Бросок"] > player2["Бросок"]: print(player1["Имя"], "Выйграл ставку!!!") player1["Счёт"] += player2["Ставка"] player2["Счёт"] -= player2["Ставка"] if player2["Бросок"] > player1["Бросок"]: print(player2["Имя"], "Выйграл ставку!!!") player2["Счёт"] += player1["Ставка"] player1["Счёт"] -= player1["Ставка"] else: print("Ничья") print(player1["Имя"], player1["Счёт"]) print(player1["Имя"], player1["Счёт"]) elif player1["Счёт"] <= 0: print(player2["Имя"], "Проиграл!") break elif player2["Счёт"] <= 0: print(player2["Имя"], "Проиграл!") break
6b2db50e9d673306c03859ce4d610ce51d8f4ef4
nicosalaz/pythonProject
/s11/pandas_some.py
554
3.796875
4
import numpy as np import pandas as pd # leemos el archivo de datos csv titanic = pd.read_csv("titanic.csv") age_sex = titanic[["Age", "Sex"]] print(age_sex) # obtenemos solo los pasajeros mayores de 35 años above_35 = titanic[titanic["Age"] > 35] print(above_35) # visualizamos solo los 10 primeros... print(above_35.head(10)) # imprimimos solo los pasajeros de 2da y 3ra clase print(titanic[titanic["Pclass"].isin([2, 3])]) # imprimimos pasajeros cuya cabina es conocida #print(titanic[titanic["Cabin"]]) print(titanic[titanic["Cabin"].notna()])
617afcd0aca2d707adbfe45760b5b4202aec6045
Astony/Homeworks
/homework7/task01/find_occurrences.py
704
4.125
4
from typing import Any def find_occurrences(item: dict, required_element: Any) -> int: """ The function gives access for all values in nested structure and allows count the quantity of the required element. """ counter = 0 if item == required_element: counter += 1 elif isinstance(item, (list, set, tuple)): for element in item: counter += find_occurrences(element, required_element) elif isinstance(item, dict): for key, value in item.items(): if value == required_element: counter += 1 else: counter += find_occurrences(value, required_element) return counter
b2f6bf7f21a4e60815d400795cf0916352c6bb26
avishekbasak/Algorithm
/ds_project_2/problem_2.py
3,823
4.125
4
import os from collections import deque # Folder structure can be comparable to a tree like structure where parent directory is like the root node # So i have used BFS for traversing the complete folder structure # I have created Queue class for the queue that is used in BFS. Every path that i Encounter in the queue, I check if it is a file with valid extension # then i add it to the file list to be returned, else if it is a directory, i add all its contents to the queue. This process continues till i have visited # all the folders and all its files. class Queue(): def __init__(self): self.q = deque() def enq(self,value): self.q.appendleft(value) def deq(self): if len(self.q) > 0: return self.q.pop() else: return None def __len__(self): return len(self.q) def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ # files to be returned file_list = [] #return none if input is invalid if path is None or suffix is None or len (suffix) == 0 or len(path) == 0: return None #define the queue q = Queue() # add the incoming path to queue q.enq(path) #iterate till the queue is empty while len(q) > 0: #get the first value in queue val = q.deq() #check if the popped path is a file that ends with the suffix, if yes then add it to the list to return if valid_file(suffix,val): file_list.append(val) # if the path is a directory add all the items in the queue else: add_file_to_q(val,q) if len(file_list) == 0: return None return file_list def valid_file(suffix,path): ''' Method checks if it is a valid file that needs to be retrieved ''' if os.path.isfile(path): ext = os.path.splitext(path)[-1].lower() if ext == suffix: return True return False def add_file_to_q(path,q): ''' Method retrieves all the items in the given path and add it to the Queue ''' if os.path.isdir(path): listDir = os.listdir(path) if len(listDir) > 0: for fp in listDir: q.enq(path+"/"+fp) print(find_files('.c','/Users/avishekbasak/algo_udacity/testdir')) #['/Users/avishekbasak/algo_udacity/testdir/t1.c', #'/Users/avishekbasak/algo_udacity/testdir/subdir5/a.c', #'/Users/avishekbasak/algo_udacity/testdir/subdir1/a.c', #'/Users/avishekbasak/algo_udacity/testdir/subdir3/subsubdir1/b.c'] print(find_files('','/Users/avishekbasak/algo_udacity/testdir')) # None print(find_files('.c','')) # None print(find_files(None,'/Users/avishekbasak/algo_udacity/testdir')) # None print(find_files('.c',None)) # None print(find_files('.py','/Users/avishekbasak/algo_udacity/testdir')) # None print(find_files('.h','/Users/avishekbasak/algo_udacity/testdir')) #['/Users/avishekbasak/algo_udacity/testdir/t1.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir5/a.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir1/a.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir3/subsubdir1/b.h'] print(find_files('.h','/Users/avishekbasak/algo_udacity')) #['/Users/avishekbasak/algo_udacity/testdir/t1.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir5/a.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir1/a.h', #'/Users/avishekbasak/algo_udacity/testdir/subdir3/subsubdir1/b.h'] print(find_files('.h','/XUsers/avionic/')) # None
95f45196fc5244f6635900cee0d02ba49d9255b1
schahal/sample
/samplepkg/samplepkg.py
389
3.96875
4
def supercharge(num): """ Supercharges a number by multiplying it with "the answer to life, the universe and everything" Args: num (int): some number Returns: int """ if not isinstance(num, int): raise TypeError("Please provide an int argument.") ANSWER_TO_ULTIMATE_QUESTION = 42 return num * ANSWER_TO_ULTIMATE_QUESTION