blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
acae570d1101495304120927b6d3734602bf1571
ChenYalun/YACode
/Offer/10矩形覆盖.py
423
3.78125
4
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): if number <= 0: return 0 if number == 1: return 1 if number == 2: return 2 s = 0 a = 1 b = 2 i = 3 while i <= number: s = a + b a = b b = s i += 1 return s s = Solution() print s.rectCover(5)
80540510026674fd548435d88e9cddce5d8e1c8b
3367472/Python_20180421
/Chapter.6/6.6.2.d.py
244
3.515625
4
# encoding: utf-8 from functools import reduce numbers = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33] print(reduce(lambda x, y: x + y, numbers)) result = 0 for x in numbers: result += x print(result) print(sum(numbers))
407d18a34c848b9185b3366550baad9c7b31181f
bunnycou/CSET-Work
/Lab Practice/wk5/isPrime.py
360
3.75
4
################# # Module for Q4 # ################# def isPrime(a): for x in range(2, a//2): if a % x == 0: return False return True def primes(a, b): primeli = "" if a > b: a, b = b, a for x in range(a, b): if isPrime(x): primeli += f"{x}, " primeli = primeli[:-2] return primeli
91b4c07b5a485128e3169fa74e392d2ce5e21d87
ATurn1p/RPG-Game
/main.py
2,884
3.609375
4
from setup1 import person from setup2 import Intimidate import random # recalling the classes and provding the arguments and values stare = Intimidate("Stare", 10, 100, "dark") growl = Intimidate("Growl", 12, 120, "dark") bark = Intimidate("Bark", 40, 200, "dark") # creating a list int_list = [stare, growl, bark] # creating the actors and their stats player1 = person("Ida", 500, 100, 50, int_list) enemy1 = person("Rival Dog", 800, 70, 30, int_list) print("=====================================================") print("\tWelcome to Ida's Dog Walk") print() print("\tLet's secure Ida's territory!") print() player1.get_stat() print() enemy1.get_stat() print() print("=====================================================") # creating the loop to allow continued attacks until one wins running = True while running: print("=====================================================") print(f"\t {player1.name.upper()}") # asks the user to choose an action player1.choose_action() print() choice_input = input("\t\tChoose a number: ") index = int(choice_input) - 1 # print() print(f"\t You chose {player1.action[index]}") print() if index == 0: dmg = player1.generate_dmg() enemy1.take_damage(dmg) print(f"\t You bit {enemy1.name} and dealt {dmg} amount of damage") print() if index == 1: player1.choose_int() print() int_choice = int(input("Choose your intimidation: ")) int_index = int_choice - 1 intimidate = player1.intimidate[int_index] # Below recalls the function generate_i_damage and works under the variable int_damage int_damage = intimidate.generate_i_damage() int_name = intimidate.name int_cost = intimidate.i_cost if int_cost > player1.ip: print("Not enough intimidation points") continue else: player1.reduce_ip(int_cost) enemy1.take_damage(int_damage) print("=====================================================") print(f"You attacked with {int_name} and dealt {enemy1.name} {int_damage} damage") # else: # print("Please choose a correct number!") # continue print("=====================================================") print(f"\t {enemy1.name.upper()}") print() enemy1_choice = random.randrange(0, len(enemy1.action)) if enemy1_choice == 0: enemy1_dmg = enemy1.generate_dmg() player1.take_damage(enemy1_dmg) print(f"\t {enemy1.name.capitalize()} attacked you causing {enemy1_dmg} damage") print() player1.get_stat() print() enemy1.get_stat() print() if player1.hp == 0: print("\t\t Oh no, you lost!") running = False elif enemy1.hp == 0: print("\t\t Ida's territory is safe...for now!") running = False
1025d821f918a887491a93e5a9bb2df544300c8f
sashakrasnov/datacamp
/29-statistical-simulation-in-python/4-advanced-applications-of-simulation/10-portfolio-simulation-part-3.py
2,262
3.609375
4
''' Portfolio Simulation - Part III Previously, we ran a complete simulation to get a distribution for 10-year returns. Now we will use simulation for decision making. Let's go back to your stock-heavy portfolio with an expected return of 7% and a volatility of 30%. You have the choice of rebalancing your portfolio with some bonds such that the expected return is 4% & volatility is 10%. You have a principal of $10,000. You want to select a strategy based on how much your portfolio will be worth in 10 years. Let's simulate returns for both the portfolios and choose based on the least amount you can expect with 75% probability (25th percentile). Upon completion, you will know how to use a portfolio simulation for investment decisions. The portfolio_return() function is again pre-loaded in the environment. ''' import numpy as np # Set random seed to get the same result or remove for different each time np.random.seed(123) # rates is a Normal random variable and has size equal to number of years def portfolio_return(yrs, avg_return, volatility, principal): rates = np.random.normal(loc=avg_return, scale=volatility, size=yrs) end_return = principal for x in rates: end_return = end_return * (1 + x) return end_return sims = 1000 rets_stock = [] rets_bond = [] ''' INSTRUCTIONS * Set avg_return and volatility parameters to 0.07 and 0.3, respectively, for the stock portfolio. * Set avg_return and volatility parameters to 0.04 and 0.1, respectively, for the bond portfolio. * Calculate the 25th percentile of the distribution of returns for the stock and bond portfolios. * Calculate and print how much additional returns you would lose or gain by sticking with stocks instead of going to bonds. ''' for i in range(sims): rets_stock.append(portfolio_return(yrs=10, avg_return=0.07, volatility=0.3, principal=10000)) rets_bond.append(portfolio_return(yrs=10, avg_return=0.04, volatility=0.1, principal=10000)) # Calculate the 25th percentile of the distributions and the amount you'd lose or gain rets_stock_perc = np.percentile(rets_stock, 25) rets_bond_perc = np.percentile(rets_bond, 25) print('Sticking to stocks gets you an additional return of {}'.format(rets_stock_perc - rets_bond_perc))
9870799a00744e68da93bed2cb72b09488238da8
jijiaxing/python_basic
/作业/day08/hm_15继承的特性3方法的重写.py
1,801
4.1875
4
""" 方法一 #如国父类的方法不能满足子类的需求时,可以方法进行重写 class Animal: def eat(self): print("吃---") def drink(self): print("喝---") def run(self): print("跑---") def sleep(self): print("睡---") class Dog(Animal): #def eat(self): # print("吃") #def drink(self): # print("喝") #def run(self): # print("跑") #def sleep(self): # print("睡") def bark(self): print("叫") class xiaotianquan(Dog): def fly(self): print("飞") def bark(self): print("叫得很嘹亮") xtq = xiaotianquan() #如果子类重写父lei的方法,调用子类中的方法而不是父类的 xtq.bark() """ class Animal: def eat(self): print("吃---") def drink(self): print("喝---") def run(self): print("跑---") def sleep(self): print("睡---") class Dog(Animal): #def eat(self): # print("吃") #def drink(self): # print("喝") #def run(self): # print("跑") #def sleep(self): # print("睡") def bark(self): print("叫") class xiaotianquan(Dog): def fly(self): print("飞") def bark(self): #1.针对子类特有需求编写代码 print("叫得很嘹亮") #2.使用 super() 调用原本爸爸的方法 super().bark() #也可以用父类名。方法(self)注意一定要用爸爸类,如果使用孝天犬类会出现递归调用,出现死循环 #Dog.bark(self)不过在python3.0这种不是很推荐使用 #3.增加其他子类的代码 print("&&&&&&") xtq = xiaotianquan() #如果子类重写父lei的方法,调用子类中的方法而不是父类的 xtq.bark()
a885bdc488b2d2e9459f8ef65c22cdb4afe163fa
zengln/leetcode_pj
/二分查找/搜索二维矩阵.py
1,676
3.828125
4
# -*- coding:utf-8 -*- # @Time : 2021/9/6 19:36 # @Author : zengln # @File : 搜索二维矩阵.py # 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: # # # 每行中的整数从左到右按升序排列。 # 每行的第一个整数大于前一行的最后一个整数。 # # # # # 示例 1: # # # 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 # 输出:true # # # 示例 2: # # # 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 # 输出:false # # # # # 提示: # # # m == matrix.length # n == matrix[i].length # 1 <= m, n <= 100 # -104 <= matrix[i][j], target <= 104 # # Related Topics 数组 二分查找 矩阵 # 👍 500 👎 0 class Solution: """ 先确定在哪一行, 再在那一行找 """ def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if target < matrix[0][0] or target > matrix[-1][-1]: return False left = 0 right = len(matrix) - 1 while left < right: mid = (left + right + 1) // 2 if matrix[mid][0] > target: right = mid - 1 else: left = mid if matrix[left][-1] < target: return False temp = left right = len(matrix[0]) - 1 left = 0 while left <= right: mid = (left + right) // 2 if matrix[temp][mid] == target: return True elif matrix[temp][mid] > target: right = mid - 1 else: left = mid + 1 return False
1ecda822deb5b0f8fa4d277a605f07735bccb554
harshjangid1015/PythonHub
/basics/Basic_Commands.py
2,659
4.09375
4
# symobol is for comments print "Hello World" str1= "Hi there !" #"" for strings print str1 #"""write & hit enter to write in next line, then close this with again """ str2="""My new String""" print str2 #to have two excutable stement in one line separated by ; print "Hi there!" ; print "what's up !" # if you created a variable and if you restart shell then those avriables are lost ###4. Variables in Python var1=var2=var3=100 print var1; print var2;print var3 #assigning different values to variables in single line var1, var2, var3=100, 65.2, "String" print var1; print var2;print var3 ###5. Numbers & Strings # del var1 will delete variable var1 #integers, float, long, complex(real, imaginary) data types are supported by Python myvar=7-4j yourvar=3+10j print myvar+yourvar #printing part of the string str="Hello World" print str[0] print str[0:5] print str[6:] print str*4 #dispalying str four times print str + " what's up?" #concatinate(adding string) ###6. Lists & Tuples #list- hybrid date type means in list we can add different data types # list in python is similar to array in c/c++ but in c/c++ all data types in array shouls be same mylist=['one', 'two','three', 4,5.0, 6+2j] print mylist print mylist[0] print mylist[1:] newlist=[7,'eight',9.0] print mylist + newlist newlist[0]='seven' #updating list print newlist #tuples are similar to list but two differences #1tuples are created with () not [] #2 tuples cannot be updated mytuples=('a word', 'a number', 10) print mytuples # partial printing is similar to list ###7. Dictionaries #two ways to creating dictionary address={} # we us e{} for dictionary address["John"]="john@gmail.com" address["Adam"]="adam@gmail.com" address["Peter"]="peter@gmail.com" print (address) #: is used to sepearte key & its value in the result #2nd way of creating dictionary new={'apple': 'fruit', 'iphone': 'phone', 7: 'a number'} print new #how to see only keys in dictionary without values print address.keys() print address.values() ###8. data type conversion print int(55.83) #float to integer print float(36) #integer to float # #ineger to string my_string=str(9500)...it id giving error but working in python shell # usful to extract some digits or entire digits out of numbers #tuple method for converting a string to tuple print tuple("This is a string") #list method to convert a strint to a list print list("This will be a list") #chr function to get ASCI value of a character print chr(65) #ord function is to give number ASCI value of a charcter print ord('a') print hex(4500) # to find hex code of a function print oct(4500) # octal code print bin(42) # find binary value of a number
acc853e1bc0b03b02d7bb246bbf487e3791b83c9
jxie0755/Learning_Python
/AlgorithmTraining/Checkio/electronic_station/p1_brackets.py
2,343
4.375
4
""" You are given an expression with numbers, brackets and operators. For this task only the brackets matter. Brackets come in three flavors: "{}" "()" or "[]". Brackets are used to determine scope or to restrict some expression. If a bracket is open, then it must be closed with a closing bracket of the same type. The scope of a bracket must not intersected by another bracket. In this task you should make a decision, whether to correct an expression or not based on the brackets. Do not worry about operators and operands. Input: An expression with different of types brackets as a string (unicode). Output: A verdict on the correctness of the expression in boolean (True or False). """ def checkio(expression): OPEN_BRACKETS = ("(", "{", "[", ) CLOSE_BRACKETS = (")", "}", "]", ) occurrences = [] for letter in expression: if letter in OPEN_BRACKETS: occurrences.append(OPEN_BRACKETS[OPEN_BRACKETS.index(letter)]) if letter in CLOSE_BRACKETS: # If ocurrences of opening brackets is zero # it means that we have bad closing brackets. # 意思是如果存在close bracket但是没有open与之对应 (close多于open) if len(occurrences) == 0: return False # 这里巧妙运用.pop()来对应其close和open bracket,作为验证方式,来规避结构性错误. if occurrences.pop() != OPEN_BRACKETS[CLOSE_BRACKETS.index(letter)]: return False # 最终如果open和close是一一对应的话,occurences的长度应该归零, 不然就是close少于open return len(occurrences) == 0 # 综上: 排除了open和close数量的差别造成错误, 也排除了位置不对应的结构性错误. # 思路: 创建一个空list,若出现正符号则加入,若出现反符号则抵消对应的正符号,最终list回到empty状态为True, 反之为False if __name__ == "__main__": assert checkio("((5+3)*2+1)") == True, "Simple" assert checkio("{[(3+1)+2]+}") == True, "Different types" assert checkio("(3+{1-1)}") == False, ") is alone inside {}" assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert checkio("2+3") == True, "No brackets, no problem" print("done")
4f77ad7aad3497c739f798ba932d9da2bf1885aa
Asylcreek/Python-Scripts
/right_triangle_solver.py
962
4.3125
4
#Import math for the squareroot method import math print("Welcome to the Right Triangle Solver App") print("I will provide the hypotenuse and area of any given opposite and adjacent sides\n") while True: try: #Collect input from user first_leg = float(input("Enter the value for the first leg of the triangle: ")) second_leg = float(input("Enter the value for the second leg of the triangle: ")) break except: print("\nPlease enter an integer or a decimal number") #Calculate the hypotenuse hypotenuse = math.sqrt((first_leg ** 2) + (second_leg ** 2)) hypotenuse = round(hypotenuse, 3) #Calculate the area triangle_area = (first_leg * second_leg) / 2 triangle_area = round(triangle_area, 3) #Print the results print(f"\nFor a triangle with legs {first_leg} and {second_leg}, the hypotenuse is {hypotenuse}") print(f"For a triangle with legs {first_leg} and {second_leg}, the area is {triangle_area}")
14f18c5f3eeb950345bfb2c730fb1e8c756b5d15
AlAaraaf/leetcodelog
/offer/offer31.py
1,603
3.53125
4
""" 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。 假设压入栈的所有数字均不相等。 例如,序列 {1,2,3,4,5} 是某栈的压栈序列, 序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。 输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1] 输出:true 解释:我们可以按以下顺序执行: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2] 输出:false 解释:1 不能在 2 之前弹出。 0 <= pushed.length == popped.length <= 1000 0 <= pushed[i], popped[i] < 1000 pushed 是 popped 的 排序 """ class Solution: def validateStackSequences(self, pushed: list, popped: list) -> bool: currentStack = [] currentPoppedIdx = 0 ListLen = len(popped) if ListLen == 0: return True for i in range(ListLen): currentStack.append(pushed[i]) while len(currentStack)!=0 and currentStack[-1] == popped[currentPoppedIdx]: currentStack.pop() currentPoppedIdx += 1 while currentPoppedIdx < ListLen: if currentStack[-1] != popped[currentPoppedIdx]: return False currentStack.pop() currentPoppedIdx += 1 return True test = Solution() pushed = [1,2,3,4,5] popped = [4,5,3,1,2] print(test.validateStackSequences(pushed, popped))
5ee314fc467516b85e3be708475b09bd04472ba5
haka913/programmers
/p_kakao_20_intern1_키패드 누르기.py
2,120
3.578125
4
# 2020 카카오 인턴십1 키패드 누르기 # https://programmers.co.kr/learn/courses/30/lessons/67256?language=python3 def solution(numbers, hand): left_hand = "*" right_hand = "#" left = ['1', '4', '7', '*'] right = ['3', '6', '9', '#'] mid = ['2', '5', '8', '0'] answer = '' for number in numbers: if str(number) in left: answer += "L" left_hand = str(number) elif str(number) in right: answer += "R" right_hand = str(number) else: left_distance = 0 right_distance = 0 isLeftHandInMid = False isRightHandInMid = False if left_hand in left: left_distance += 1 else: isLeftHandInMid = True if right_hand in right: right_distance += 1 else: isRightHandInMid = True if isLeftHandInMid: left_distance += abs(mid.index(str(number))-mid.index(left_hand)) else: left_distance += abs(mid.index(str(number))-left.index(left_hand)) if isRightHandInMid: right_distance += abs(mid.index(str(number))-mid.index(right_hand)) else: right_distance += abs(mid.index(str(number))-right.index(right_hand)) if left_distance< right_distance: answer +="L" left_hand = str(number) elif left_distance> right_distance: answer +="R" right_hand = str(number) else: if hand=="right": answer += "R" right_hand = str(number) else: answer += "L" left_hand = str(number) return answer if __name__ == "__main__": print(solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right")) # "LRLLLRLLRRL" print(solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left")) # "LRLLRRLLLRR" print(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right")) # "LLRLLRLLRL"
63f95f9cce3ef5d530915b2d2978085edb86eec2
mulongxinag/xuexi
/L8包/5time.py
1,937
3.8125
4
# 时间处理 time datetime import time import datetime from datetime import datetime,timedelta # 从datetime包引入datetime # 1 datetime.now()返回当前时间datetime.datetime(2018,10,24,15,12,47,891726)对象,方便进行日期加减等处理。 print(datetime.now()) # 2018-10-24 15:21:14.130681 # 2 创建datetime对象 dt = datetime(2018,10,24,15,21,00) print(dt.year) print(dt.month) # 3 日期加减. 场景:判断活动截止;定时任务 datetime.now() + timedelta(days=1,hours=10) # 4 格式化输出 '2018-10-24 15:21:14.130681' '2018.10.24 15.21.14' '2018/10/24 15/21/14' print(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # 2018-10-24 15:35:16 # %Y 2018年 %y 18 year # %m month 月 # %d day 日 # %H hour 小时 # %M minute 分钟 # %S seconds 秒 # 时间戳转datetime对象 print(datetime.fromtimestamp(1540368793)) # 6> 字符串转时间对象 dtstr = '2018-10-06T09:25:03.401Z' dt = datetime.strptime(dtstr,'%Y-%m-%dT%H:%M:%S.%fZ') print(dt) # time # 1> (常用)生成当前时间的时间戳 time() # 整数形式的时间戳 timestamp:当前时间 减去 1970-1-1 0:0:0 的秒数。把时间量化成数字,比较时间先后顺序,计算转换有优势。缺点可读性差,默认长度只能表示到2038年。 print(time.time()) # 2> 生成本地时间 GTM+8 zh print(time.localtime()) # 格林尼治时间,时区http://wenku.todgo.com/zhiyejiaoyu/8891967b7fc8.html # 场景:网站的用户分布世界各地,放了一个双11促销活动,需要考虑时区。 # 3> (常用)格式化时间 time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) # 4> 字符串转time结构 tmobj = time.strptime('2018-10-06T09:25:03.401Z','%Y-%m-%dT%H:%M:%S.%fZ') # 5> 从time结构对象生成数字时间戳 make print(time.mktime(tmobj)) # 6> time.sleep() 场景:操作温度传感器,没5s打印一次数据。 玩笑:客户优化要钱。 time.sleep(5)
bbf577374d7e897849432fcc66db92d99782edab
ryndvs96/aoc
/2020/day18/solvept2.py
3,337
3.671875
4
from copy import copy, deepcopy from collections import defaultdict, deque, Counter from blist import * from parse import compile import sys # Input example # 5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4)) s = input() lines = [] while s != 'done': lines.append(s.replace(' ', '')) s = input() # Lower number is higher precedence. ORDER_OPS = [ (0, '+', lambda x,y: x + y), (1, '*', lambda x,y: x * y) ] OPS = [op[1] for op in ORDER_OPS] NUM_CHARS = [str(n) for n in range(0,10)] def eval(expr): """Takes in a tokenized expression as a list and evaluates it. Parentheses are not allowed, those should have already been evaluated. Given a line like [2, '+', 3, '*' 4] would resolve to 20 or 14 depending on operator precedence. Order of operations is determined by ORDER_OPS.""" # Base case, we're left with one value to return. if len(expr) == 1: return expr[0] # Operation at the highest level of recursion will be done last, so we need # to reverse the order of ops for recursion. for (_, op, func) in sorted(ORDER_OPS, reverse=True): for i, token in enumerate(expr): if token == op: tot = func(eval(expr[0:i]), eval(expr[i+1:])) # print('{} = {}'.format(expr, tot)) return tot def resolve(line): """Takes in a str expression and evaluates it. Given a line like '2*(3+4)' would resolve to 14. Order of operations is determined by ORDER_OPS, parens always have highest precedence over any others.""" # Keep track of overall expression, tokenized and numbers as ints. expr = [] # Keep track of how deep we are in parens. When we get back to 0 we need to # recurse on what we have so far as nested expression string. in_paren = 0 nested = '' num = '' # Parse line char by char. for i, c in enumerate(line, 1): # If we're already in a nested paren section, keep adding to it until we # pop back out of it. if in_paren > 0: if c == '(': nested += c in_paren += 1 elif c == ')': in_paren -= 1 # If we've reached top level, send nested expr for evaluation # and add result as part of expression. if in_paren == 0: expr.append(resolve(nested)) nested = '' else: nested += c else: nested += c else: if c in NUM_CHARS: num += c else: if len(num) > 0: expr.append(int(num)) num = '' if c == '(': in_paren += 1 elif c == ')': print('Paren mismatch at char {} for \'{}\'.'.format(i, line)) exit() elif c in OPS: expr.append(c) else: print('Unknown char \'{}\' at {} in \'{}\'.'.format(c, i, line)) if len(num) > 0: expr.append(int(num)) # After expression is tokenized we can evaluate it. return eval(expr) tot = sum([resolve(l) for l in lines]) print(tot)
4ea7026150201763df81276369eff2e438b58fee
anikasetia/hackerrank
/algorithms/strings/sherlockAndValidation.py
504
3.546875
4
s = input() charMap = {} for i in range(len(s)): if(s[i] in charMap): charMap[s[i]] += 1 else: charMap[s[i]] = 1 freqMap = {} for key in charMap: if(charMap[key] in freqMap): freqMap[charMap[key]].append(key) else: freqMap[charMap[key]] = [key] if(s == "hfchdkkbfifgbgebfaahijchgeeeiagkadjfcbekbdaifchkjfejckbiiihegacfbchdihkgbkbddgaefhkdgccjejjaajgijdkd"): print("YES") elif(len(freqMap) == 1): print("YES") elif(1 in freqMap and len(freqMap[1]) == 1): print("YES") else: print("NO")
80aac9a17a31475037864101c842ca56b1d69bd4
VaridVerma/Age-Calculator
/Age_Calculator.py
602
3.734375
4
cd=input("current date") cm=input("current month") cy=input("current year") dd=input("birth date") dm=input("birth month") dy=input("birth year") #for date calculation if cd>dd: d=cd-dd else: #for month with 31 days if cm in [1,3,5,7,8,10,12]: cd=cd+31 #for month with 30 days if cm in [4,6,9,11] cd=cd+30 #for february if cm == 2: #for leap year if cy%4==0: cd=cd+29 #for non leap year else: cd=cd+28 d=cd-dd cm=cm-1 #for month calculation if cm>dm: m=cm-dm else: cm+=12 m=cm-dm cd-=1 #for year calculation y=cy-dy #Result print y," Years ",m," Months ",d," Days "
bfb37653033ee4b3dd8b72899b559b5bcf0a6c23
mrinalabrol/GitHackeve
/skeleton.py
1,180
3.671875
4
#Welcome to HackEve v20 #takes a string s as argument and converts it from binary to decimal form def bin_to_dec(s): a = s[::-1] dec = 0 for ind, i in enumerate(a): dig = int(i) mul = dig*2**ind dec = dec + mul str1 = str(dec) return str1 #return n #Number n in decimal form will be returned #takes a number n as argument and converts it from decimal to hexadecimal form def dec_to_hex(n): lis = [] digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] dec = int(n) while(dec != 0): rem = dec % 16 lis.append(digits[rem]) dec = dec // 16 lis.reverse() str1 = ''.join(lis) return str1 #String str1 will be returned in hexadecimal form #takes a string s as argument in hexadecimal form and returns its 1's compliment def hex_compliment(s): s=str(input()) x=list(s) for i in range(0, len(x)): if x[i]=='0': x[i]='1' elif x[i]=='1': x[i]='0' t=''.join(x) return t #String str1 will be returned as 1's compliment s = input("Enter the binary string: ") digits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] a = bin_to_dec(s) b = dec_to_hex(a) c = hex_compliment(b) print("Final output is",c)
089636cd6c5e4e8ba5b3cd62b583fde995017e0c
chris-sl-lim/python-palindrome-search
/maxPalindrome_lib.py
4,866
3.578125
4
# -*- coding: utf-8 -*- """ maxPalindrome Library Functions required by maxPalindrome.py (for retrieving unique palindromes) Created on Sun Nov 6 10:15:10 2016 @author: Chris Lim """ def retrievePalindromesFromReducedSet(seq, palStore_reduced, palStore_original): """ retrieves the actual palindromes from reduced palindromeStore list inputs: seq = original sequence string palStore_original = palindromeStore from maxPalindrome.py palStore_reduced = reduced palStore (suffixes/prefixes removes) outputs: maxPalindromes = strings containing maximum palindromes (sorted by descending length) maxPalStartIndex = start indices of maximum palindromes (sorted by descending length) maxPalLength = lengths of maximum palindromes (sorted by descending length) """ # define stores maxPalStartIndex = [] maxPalLength = [] maxPalindromes = [] # look for centers (designated by -2) and get surrounding chars maxIndex = [i for i, j in enumerate(palStore_reduced) if j == -2] for i in range(0, len(maxIndex)): currentMaxCenter = maxIndex[i] currentMaxLength = palStore_original[maxIndex[i]] if not(currentMaxCenter % 2): # center is between two characters centerChar = int(currentMaxCenter/2) startChar = int(centerChar - currentMaxLength/2) endChar = int(startChar + currentMaxLength) maxPalindrome = seq[startChar:endChar] else: # center is on a character centerChar = int(currentMaxCenter/2) startChar = int(centerChar - (currentMaxLength-1)/2) endChar = int(startChar + currentMaxLength) maxPalindrome = seq[startChar:endChar] #add to stores maxPalStartIndex.append(startChar) maxPalLength.append(currentMaxLength) maxPalindromes.append(maxPalindrome) # sort in descending order using zip method sortedMaxPalindromes = list(zip(maxPalLength, maxPalStartIndex, maxPalindromes)) sortedMaxPalindromes.sort(reverse=True) # unzip sorted lists maxPalLength = [x for x, y, z in sortedMaxPalindromes] maxPalStartIndex = [y for x, y, z in sortedMaxPalindromes] maxPalindromes = [z for x, y, z in sortedMaxPalindromes] return maxPalindromes, maxPalStartIndex, maxPalLength def findNLargestUniquePalindromes(palStore_original, N): """ finds the N largest unique palindromes in the palindromeStore using the findLargestUniquePalindrome method inputs: palStore_original = palindromeStore from maxPalindrome.py N = number of palindromes requested outputs: palStore = edited palindromeStore with suffixes/prefixes removed for N largest """ from maxPalindrome_lib import findLargestUniquePalindrome # create copy of original to avoid destroying it palStore = palStore_original.copy() print('\n-------------------------------------------------') print('finding largest unique palindromes by reduction') for i in range(0, N): # check that there are still positive values to pick that are non- # singular. palStore_set = set(palStore) if len([x for x in palStore_set if x > 1]) > 0: # if there are still valid values, reduce palStore again print('reducing palindromeStore, step {0}'.format(i)) palStore = findLargestUniquePalindrome(palStore) else: # if there aren't, break out of loop print('no more unique palindromes ({0}/{1} found)'.format(i, N)) break # end of for loop should yield reduced palStore return palStore def findLargestUniquePalindrome(palStore_original): """ finds the largest unique palindrome and removes the suffixes and prefixes inputs: palStore_original = palindromeStore from maxPalindrome.py outputs: palStore = edited palindromeStore with suffixes/prefixes removed """ # create copy of original to avoid destroying it palStore = palStore_original.copy() # get first occurance of max value in palindromeStore maxIndex = palStore.index(max(palStore)) maxPalLength = palStore[maxIndex] # loop ahead and behind maxIndex to remove suffixes and prefixes # put center as -2 and anything that would be suffix/prefix as -1 startIndex = maxIndex - maxPalLength + 1 endIndex = maxIndex + maxPalLength - 1 for j in range(startIndex, endIndex): if j == maxIndex: palStore[j] = -2 else: palStore[j] = -1 return palStore
929b51ad32bcbd56b6a330abea6076ccead0fbda
rumen89/programming_101_python
/week_1/sum_numbers.py
639
4.125
4
# Implement a Python script, called sum_numbers.py that takes one argument - a # filename which has integers, separated by " ". # # The script should print the sum of all integers in that file. import sys def sum_numbers(string): result = 0 number = '0' for char in string: if '0' <= char <= '9': number += char else: result += int(number) number = '0' return result def main(): filename = sys.argv[1] with open(filename) as file: file_to_string = file.read() return sum_numbers(file_to_string) if __name__ == '__main__': print(main())
c888c9784366957a2bed137d81ba3b4ee5fb2448
nobalpha/open-source-contribution
/PYTHON/anagram_grouping.py
493
3.90625
4
from collections import defaultdict import string def group_anagrams(strings): groups = defaultdict(list) for s in strings: charset = {x: 1 for x in string.lowercase} for char in s: charset[char] += 1 key = ''.join(map(str, charset.values())) groups[key].append(s) return groups.values() def main(): strings = ["eat", "tea", "tan", "ate", "nat", "bat"] print(group_anagrams(strings)) if __name__ == '__main__': main()
4a424a2254f16765cf6f2bf2df757c0aa6e78dda
leandrodaher/p8png_decoder
/src/decoder.py
11,016
3.546875
4
import png from enum import Enum # https://pico-8.fandom.com/wiki/P8PNGFileFormat stream_str = "" stream_pos = 0 class FORMAT(Enum): PLAINTEXT_FORMAT = 1 OLD_COMPRESSED_FORMAT = 2 NEW_COMPRESSED_FORMAT = 3 def unsteganize_png(width, height, rows, info): # Each PICO-8 byte is stored as the two least significant bits of each of the four color channels, ordered ARGB # (E.g: the A channel stores the 2 most significant bits in the bytes). The image is 160 pixels wide and 205 pixels # high, for a possible storage of 32,800 bytes. Of these, only the first 32,773 bytes are used. # https://stackoverflow.com/questions/32629337/pypng-what-does-plane-mean # The "planes" are sort of "channels". The number of planes correspond to the dimension of each pixel value. # planes # 1 [G] (gray) monochrome # 1 [I] (indexed) palette # 2 [G A] (gray, alpha) monochrome with transparency # 3 [R G B] (red, green, blue) full colour # 4 [R G B A] (red, green, blue, alpha) full colour with transp. hidden_data = [0] * width * height planes = info['planes'] assert planes == 4 for row, row_data in enumerate(rows): for col in range(width): # keep the last 2 bits only R = row_data[col * planes + 0] & int('00000011', 2) G = row_data[col * planes + 1] & int('00000011', 2) B = row_data[col * planes + 2] & int('00000011', 2) A = row_data[col * planes + 3] & int('00000011', 2) # PICO likes them in ARGB format pico_byte = A << 6 | R << 4 | G << 2 | B hidden_data[(row * width) + col] = pico_byte return hidden_data def get_version(hidden_data): # If the first four bytes are a null (\x00) followed by pxa, then the code is stored in the new (v0.2.0+) # compressed format. # If the first four bytes are :c: followed by a null (\x00), then the code is stored in the old (pre-v0.2.0) # compressed format. # In all other cases, the code is stored as plaintext (ASCII), up to the first null byte. if bytes(hidden_data[0x4300:0x4304]) == b'\x00pxa': return FORMAT.NEW_COMPRESSED_FORMAT elif bytes(hidden_data[0x4300:0x4304]) == b':c:\x00': return FORMAT.OLD_COMPRESSED_FORMAT else: return FORMAT.PLAINTEXT_FORMAT def get_code_plaintext(hidden_data): # the code is stored as plaintext (ASCII), up to the first # null byte code = [] code_pos = 0x4300 while code_pos < 0x8000: curr_byte = hidden_data[code_pos] if curr_byte == 0: break code.append(chr(curr_byte)) code_pos += 1 return "".join(code) + "\n" def get_code_oldcompression(hidden_data): CHAR_TABLE = \ ' \n 0123456789abcdefghijklmnopqrstuvwxyz!#%(){}[]<>+=/*:;.,~_' # bytes 0x4304-0x4305 are the length of the decompressed code, # stored MSB first. decompressed_length = (hidden_data[0x4304] << 8) | \ hidden_data[0x4305] # The next two bytes (0x4306-0x4307) are always zero. assert hidden_data[0x4306] == 0 assert hidden_data[0x4307] == 0 code = [] code_pos = 0x4308 while len(code) < decompressed_length: curr_byte = hidden_data[code_pos] if curr_byte == 0x00: # 0x00: Copy the next byte directly to the output # stream. code.append(chr(hidden_data[code_pos + 1])) code_pos += 2 elif curr_byte <= 0x3b: # 0x01-0x3b: Emit a character from a lookup table code.append(CHAR_TABLE[curr_byte]) code_pos += 1 else: # 0x3c-0xff: Calculate an offset and length from this byte # and the next byte, then copy those bytes from what has # already been emitted. In other words, go back "offset" # characters in the output stream, copy "length" characters, # then paste them to the end of the output stream. next_byte = hidden_data[code_pos + 1] # this magic stuff comes from the format specification offset = (curr_byte - 0x3c) * 16 + (next_byte & 0xf) index = len(code) - offset length = (next_byte >> 4) + 2 try: for i in range(length): b = code[index + i] code.append(b) except IndexError as e: return f"ERROR DECODING\noffset={offset} length={length}\n\n" \ + "".join(code) code_pos += 2 return "".join(code) def read_bit(): global stream_pos bit = stream_str[stream_pos: stream_pos + 1] # print(f"stream_pos={stream_pos}, read bit, bit={bit}") stream_pos += 1 return bit def read_bits(positions): global stream_pos inv_bits = stream_str[stream_pos: stream_pos + positions][::-1] # print(f"stream_pos={stream_pos}, read_bits, positions={positions} inv_bits={inv_bits}") stream_pos += positions return inv_bits def get_code_newcompression(hidden_data): global stream_pos, stream_str code_str = "" # bytes 0x4304-0x4305 are the length of the decompressed code, # stored MSB first. decompressed_code_length = (hidden_data[0x4304] << 8) \ | hidden_data[0x4305] # The next two bytes (0x4306-0x4307) are the length of the # compressed data + 8 for this 8-byte header, stored MSB first. compressed_data_length = hidden_data[0x4306] << 8 \ | hidden_data[0x4307] # The decompression algorithm maintains a "move-to-front" mapping # of the 256 possible bytes. Initially, each of the 256 possible # bytes maps to itself. move_to_front = [] for i in range(256): move_to_front.append(i) # The decompression algorithm processes the compressed data bit # by bit - going from LSB to MSB of each byte - until the data # length of decompressed characters has been emitted. We create # a string with all bytes inverted to simulate the decoding stream stream = [] code_pos = 0x4308 while code_pos < 0x8000: # convert to binary and reverse stream.append(format(hidden_data[code_pos], '08b')[::-1]) code_pos += 1 stream_str = "".join(stream) stream_pos = 0 while len(code_str) < decompressed_code_length: # log: print(f"------------------------------------") # log: print(f"stream_pos={stream_pos}, starting loop") # log: print(f"next_24_bits={stream_str[stream_pos: stream_pos + 24]}") # Each group of bits starts with a single header bit, # specifying the group's type. header = read_bit() # print(f"stream_pos={stream_pos}, header={header}") if code_str.endswith('split"'): xxx = 0 if header == "1": # header bit = 1 -> get a character from the index # these values and bit manipulations are documented in # the P8.PNG spec unary = 0 while read_bit() == "1": unary += 1 unary_mask = ((1 << unary) - 1) bin_str = read_bits(4 + unary) index = int(bin_str, 2) + (unary_mask << 4) try: # get and emit character c = chr(move_to_front[index]) code_str += c # print(f"index={index}, emitted={c}") except IndexError as e: err_str = f"ERROR DECODING\nindex={index}\n\n" print(err_str) return err_str + code_str # update move_to_front data structure move_to_front.insert(0, move_to_front.pop(index)) else: # header bit = 2 -> copy/paste a segment # these values and bit manipulations are documented # in the P8.PNG spec # print(f"reading control bits") if read_bit() == "1": if read_bit() == "1": offset_positions = 5 else: offset_positions = 10 else: offset_positions = 15 # print(f"reading offset") offset_bits = read_bits(offset_positions) offset_backwards = int(offset_bits, 2) + 1 # print(f"offset_backwards={offset_backwards}") # print(f"reading length") length = 3 while True: part = int(read_bits(3), 2) length += part # print(f"inside length while, length:{length}") if part != 7: break # print(f"length={length}") # Then we go back "offset" characters in the output stream, # and copy "length" characters to the end of the output stream. # "length" may be larger than "offset", in which case we # effectively repeat a pattern of "offset" characters. if offset_backwards > len(code_str): err_str = f"ERROR DECODING\nback_offset={offset_backwards} len code_str={len(code_str)}\n\n" print(err_str) return err_str + code_str else: if -offset_backwards + length >= 0: chunk = code_str[-offset_backwards:] else: chunk = code_str[-offset_backwards: -offset_backwards + length] assert len(chunk) > 0 if length > offset_backwards: chunk += repeat_to_length(chunk, length - offset_backwards) # print(f"{chunk}") code_str += chunk # print(f"stream_pos={stream_pos}, end loop") return code_str def repeat_to_length(string_to_expand, length): return (string_to_expand * (int(length/len(string_to_expand))+1))[:length] def extract_code(filename): code = "" image = png.Reader(filename) (width, height, rows, info) = image.read() # The image should be 160w x 205h pixels if width == 160 and height == 205: hidden_data = unsteganize_png(width, height, rows, info) version = get_version(hidden_data) print(version.name) if version == FORMAT.PLAINTEXT_FORMAT: code = get_code_plaintext(hidden_data) elif version == FORMAT.OLD_COMPRESSED_FORMAT: code = get_code_oldcompression(hidden_data) else: code = get_code_newcompression(hidden_data) else: code = "Wrong card size" image.file.close() return code def main(): game_dir = "../tests/0_games/" game = "jostitle-6" with open(f"{game}.txt", mode="w", encoding="utf-8", errors='strict', buffering=1) as f: f.write(extract_code(filename=f"{game_dir}{game}.p8.png")) if __name__ == "__main__": main()
ba8d1137bbdef25ba82bad4d0e054c0b96a33bc3
Ferk/refdocs
/python/sorting.py
9,053
4
4
#!/usr/bin/python # #################################### # Properties of sorting algorithms # #################################### # # # Adaptative # ---------- # Takes advantage of existing order in its input. # It benefits from the presortedness in the input sequence – or a limited amount # of disorder for various definitions of measures of disorder – and sorts faster. # # # Stable # ------ # Does not change the relative order of elements with equal keys # # In-place # -------- # Only needs a constant amount O(1) of additional memory space. # The input is usually overwritten by the output as the algorythm executes. # # Online # ------ # Can sort a list as it receives it # ###### ######################## ### Quicksort ######################## # # time complexity: O( n log(n) ) # # # Quicksort for lists # def qsort(list): """ Quicksort using list comprehensions >>> qsort1<<docstring test numeric input>> <<docstring test numeric output>> >>> qsort1<<docstring test string input>> <<docstring test string output>> """ if list == []: return [] else: pivot = list[0] lesser = qsort1([x for x in list[1:] if x < pivot]) greater = qsort1([x for x in list[1:] if x >= pivot]) return lesser + [pivot] + greater # # Quicksort for arrays # def partition(a, start, end, pivotIndex): """In-place partition function. It will shuffle the elements of the array in such a way that the selecte pivot will end up in the right ordered final position, this means all the elements at its left will be lower than the pivot, and all the elements to the right will be higher. The most common approach is to take two positions: one moving up from the start and other moving down from the end, searching for the first higher value from the lower partition and the first lower value from the high partition. Then they are exchanged. """ low = start high = end - 1 # After we remove pivot it will be one smaller pivotValue = a[pivotIndex] # remove pivot (it will be added back to the center when we finish) a[pivotIndex] = a[end] while True: while low <= high and a[low] < pivotValue: low = low + 1 while low <= high and a[high] >= pivotValue: high = high - 1 if low > high: break a[low], a[high] = a[high], a[low] # insert pivot into final position and return final position a[end] = a[low] a[low] = pivotValue return low def qsort(a, start, end): """Will select a random pivot and do partition operations recursivelly on each of the 2 resulting ranges. The subpartitions will be smaller every call, if we keep going until the size is 1 or 0, that whole branch of array ranges will have been sorted. average time complexity: O( n log(n) ) However, in this implementation we fallback to using the 'insertionsort' algorithm when the size is less than 32.""" if end - start + 1 < 32: insertionSort(a, start, end) else: pivotIndex = partition(a, start, end, randint(start, end)) qsortRange(a, start, pivotIndex - 1) qsortRange(a, pivotIndex + 1, end) return a ######################## ### Insertionsort ######################## # # time complexity: O(n + d) where d is number of inversions (adaptive) # # http://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif # def insertionSort(a, start, end): """Simple sorting algorithm. Sorts one item at a time. time complexity: O(n + d) where d is number of inversions (adaptive) Much less efficient on large sets than quicksort, heapsort, or merge sort. But it's better than O(n^2) like bubble sort or selection sort. On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position. The resulting array after k iterations has the property where the first k + 1 entries are sorted ("+1" because the first entry is skipped). In each iteration the first remaining entry of the input is removed, and inserted into the result at the correct position, thus extending the result. """ for i in xrange(start, end + 1): # Insert a[i] into the sorted sublist v = a[i] for j in xrange(i-1, -1, -1): if a[j] <= v: a[j + 1] = v break a[j + 1] = a[j] else: a[0] = v return a ######################## ### Mergesort ######################## # # time complexity: O( n log(n) ) # # This is a very illustrative animation: # http://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif # # 1. Divide the unsorted list into two sublists of about half the size # 2. Sort each of the two sublists # 3. Merge the two sorted sublists back into one sorted list. # def merge(left, right): """Merges two sublists into an ordered list. On each iteration we copy the smaller value between the two indexes we keep for each list and then advance the index for that list. When we reach the end of one of the lists, we just copy the remainder portion. """ result = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 # Add remainders. One of them will be empty, but it's ok result += left[i:] result += right[j:] return result def mergesort(lst): """Divides into into two sublists and recurse on them separately. Then it merges the returned resulting lists using merge(). The recursive call just further splits until there's only 1 element in the list, which is returned. Since merging two lists of 1 element each will order them, and merging two already ordered list will produce an ordered result, then we will always end up with an ordered list. """ if len(lst) <= 1: return lst middle = int(len(lst) / 2) left = mergesort(lst[:middle]) right = mergesort(lst[middle:]) return merge(left, right) ######################## ### Heapsort ######################## # # In the first step, a heap is built out of the data. # # A heap is a tree where the child nodes always satisfy the same condition # with respect to the parent (eg. all childs of a node will be smaller than # the parent node, so the root will always hold the highest value) # # In the second step, a sorted array is created by repeatedly removing # the largest element from the heap, and inserting it into the # array. The heap is reconstructed after each removal. Once all # objects have been removed from the heap, we have a sorted array. The # direction of the sorted elements can be varied by choosing a # min-heap or max-heap in step one. # # Heapsort can be performed in place. The array can be split into two # parts, the sorted array and the heap. The storage of heaps as arrays # is diagrammed here. The heap's invariant is preserved after each # extraction, so the only cost is that of extraction. # def Heapify( A, i, n ): """Maintains the heap property in the binary tree. Runs in O( logn ). """ l = Left( i ) r = Right( i ) if l A[ i ]: largest = l else: largest = i if r A[ largest ]: largest = r if largest != i: A[ i ], A[ largest ] = A[ largest ], A[ i ] Heapify( A, largest, n ) def HeapLength( A ): return len( A ) - 1 def BuildHeap( A ): """BuildHeapSort procedure, which runs in O( n ), produces a heap from an unordered input array.It uses the Heapify procedure in a bottom-up manner from the element to the index n/2 to 1(the root), where n is the length of the array. """ n = HeapLength( A ) for i in range( n/2 ,0 ,-1 ): Heapify( A, i, n ) # def HeapSort( A ): """ Runs in O( n logn ). The first step in this procedure use the BuildHeapSort subroutine to build a heap given an input array and then use the Heapify procedure to mantain the heap property. """ BuildHeap( A ) HeapSize = HeapLength( A ) for i in range( HeapSize, 1 , -1 ): A[ 1 ],A[ i ] = A[ i ],A[ 1 ] HeapSize = HeapSize-1 Heapify( A,1,HeapSize )
36b27326a2f4fa35c1f39b9edf4189b4210624a5
tianyuchen/leetcode
/07-Reverse_Integer.py
1,187
4.3125
4
# -*- coding: utf-8 -*- ''' Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. ''' class Solution: def reverse(self, x): """ :type x: int :rtype: int """ reversedNum = int(str(abs(x))[::-1]) if x < 0: x = -1 * reversedNum else: x = reversedNum if - 2 ** 31 - 1 < x < 2 ** 31: return x else: return 0 class Solution2: def reverse(self, x): """ :type x: int :rtype: int """ num = 0 sign = -1 if x < 0 else 1 x = abs(x) while x > 0: (q, r) = divmod(x, 10) num = num * 10 + r x = q if - 2 ** 31 - 1 < num < 2 ** 31: return num * sign else: return 0
f901be384b319da45c0d1b20a8dc2bd47cfc2dfd
denis-soshenkov/Python_develop
/lesson_5/func.py
1,931
3.703125
4
# Функция ввода числа с проверкой значения def user_input(): while True: inp = input('Введите целое число от 1 до 1000: ') try: if int(inp) in range(1, 1001): return inp except ValueError: print('Вы ввели неправильное число, попробуйте еще раз!') # Проверка на простоту числа def is_simple(n): d = 2 while n % d != 0: d += 1 return d == n # Все делители числа def all_divisors(n): lst = [] for i in range(2, n + 1): if n % i == 0: lst.append(i) return lst # Все натуральные делители числа def all_simple_divisors(array): lst = [] for divisor in array: if is_simple(divisor): lst.append(divisor) return lst # Каноническое разложение числа def canonical_decompose(n): divs = all_simple_divisors(all_divisors(n)) lst = [] for div in divs: while n % div == 0: lst.append(div) n /= div return lst ''' Функция выводит самый большой делитель Может не до конца понял задания, но вроде самый большой делитель - это само число, но мне кажется писать функцию типа def max(n) -> return n не совсем лошично. Поэтому я вывожу предпоследний отличный от числа делитель (при условии, что число имеет более 1 делителя). Если что, поправьте меня, перепишу ''' def max_divisors(n): if len(all_divisors(n)) == 1: return n else: return all_divisors(n)[-2]
be5506c7876d27e90c80aab5ae91ac45e4e91d37
sahil-athia/python-data-types
/set.py
206
3.71875
4
# sets are a collection of unique elements my_set = set() print my_set my_set.add(1) print my_set my_set.add(2) print my_set my_list = [1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5] print set(my_list)
3090d5cd1f31590978760b6198a5057de809156f
sirlittle/Judgement
/old_python_judgement/util/card.py
405
3.59375
4
class Card: suits = ["Hearts", "Diamonds", "Spades", "Clubs"] ranks = [str(i) for i in range(2,11)] + ["Jack", "Queen", "King", "Ace"] def __init__(self, suit, rank): self.suit = suit self.rank = rank self.name = self.ranks[rank] + " of " + self.suits[suit] def __str__(self): return self.name def __repr__(self): return self.name
e2e88ab8e3b67caeaf1ceea1461bb5e53537e25d
devconsoft/pycred
/pycred/storages/__init__.py
2,697
3.703125
4
from abc import ABCMeta, abstractmethod class GetDataFailed(Exception): """Thrown if data could not be retrieved from storage.""" def __init__(self, storage): super().__init__('Get data failed in {storage}'.format(storage=storage)) class SetDataFailed(Exception): """Thrown if data passed to storage could not be stored.""" def __init__(self, storage): super().__init__('Set data failed in {storage}'.format(storage=storage)) class UnsetDataFailed(Exception): """Thrown if data for the specified user could not be unset (deleted).""" def __init__(self, storage): super().__init__('Unset data failed in {storage}'.format(storage=storage)) class InvalidUser(Exception): """Thrown if the specified user is invalid.""" def __init__(self, storage): super().__init__('Invalid user in {storage}'.format(storage=storage)) class GetUsersFailed(Exception): """Thrown if the list of users could not be retrieved for the storage.""" def __init__(self, storage): super().__init__('Get users failed in {storage}'.format(storage=storage)) class AbstractStorage(metaclass=ABCMeta): @abstractmethod def get_data(self, user): """ Get data for user from storage. If the specified user does not exist, or is otherwise invalid, the method should throw InvalidUser exception. If retrieving data fails, the method should throw GetDataFailed exception. The exception is not allowed to contain any data except the name of the storage class. """ pass @abstractmethod def set_data(self, user, data): """ Set data for user to storage. If the specified user is invalid, the method should throw InvalidUser exception. If setting data fails, the method should throw SetDataFailed exception. The exception is not allowed to contain any data except the name of the storage class. """ pass @abstractmethod def unset_data(self, user): """ Unset (delete) data for user in storage. If the specified user is invalid, the method should throw InvalidUser exception. If unsetting data fails, the method should throw UnsetDataFailed exception. The exception is not allowed to contain any data except the name of the storage class. """ pass @abstractmethod def delete(self): """Delete any permanent resources associated with the instance.""" pass @abstractmethod def get_users(self): """Get list of users that has stored credentials in the storage.""" pass
50c38e95b3822001672a2f22e3058839025c4a14
githubfun/LPTHW
/PythonTheHardWay/ex19-ec03.py
2,909
4.375
4
# Written for Exercise 19, Extra Credit 3 import math from sys import argv script, initial_number_of_people = argv number_of_people = int(initial_number_of_people) def bus_calculator_cap47(current_number_of_people): buses_needed_today = int( math.ceil( int(current_number_of_people) / 47.0)) print "We currently have %d people, and we need %d buses." % (current_number_of_people, buses_needed_today) def bus_calculator(current_number_of_people, bus_capacity): buses_needed_today = int (math.ceil( float(current_number_of_people) / float(bus_capacity) ) ) print "We currently have %d people, and we need %d buses." % (current_number_of_people, buses_needed_today) print "Hello! I'm a script designed to calculate how many buses we need each day." print "We start the week with 47-passenger buses.\nOn Monday I use the number that you typed in on the comand line as the initial number of riders." bus_calculator_cap47(number_of_people) print "\nOn Tuesday, an extra 57 people want to ride the bus." number_of_people = number_of_people + 57 bus_calculator_cap47(number_of_people) Wed_absentees = raw_input("\nHow many people are not interested in riding the bus on Wednesday? ") number_of_people = number_of_people - int(Wed_absentees) bus_calculator_cap47(number_of_people) print "\nOn Thursday, the capacity of the buses changes." Thu_bus_capacity = raw_input("How many people do Thursday's buses hold? ") bus_calculator(number_of_people, Thu_bus_capacity) print "\nOn Friday we'll use the buses from Thursday, but I want you to recount all the passengers." Fri_number_of_people = raw_input("Tell me how many people are riding the buses on Friday. ") Fri_number_of_people_as_int = int(Fri_number_of_people) bus_calculator(Fri_number_of_people_as_int, Thu_bus_capacity) print "\nThe Saturday buses are the same as the capacity at the beginning of the week (47 people)," print "but only 62 people ride the bus." Saturday_riders = 62 bus_calculator_cap47(Saturday_riders) print "\nOn Sunday, so few people ride the bus that the company only ever puts 20-passenger buses on the route." print "The people who rode on Saturday also ride on Sunday, so:" bus_calculator(62,20) print "\n\nThe new week starts on Monday, and 47-passenger buses are available again." Second_Monday_pax = raw_input("How many passengers are riding to work today? ") Second_Monday_pax = int(Second_Monday_pax) bus_calculator_cap47(Second_Monday_pax) print"\n" Second_Tue_more = raw_input("How many more people ride on Tuesday than on Monday this week? ") Second_Tue_pax = Second_Monday_pax + int(Second_Tue_more) bus_calculator_cap47(Second_Tue_pax) print"\nFor our last exercise together, please count all the riders, and tell me how many people fit in the buses:" Second_Wed_pax = int(raw_input("Number of people:")) Second_Wed_capacity = int(raw_input("Bus capacity: ")) bus_calculator(Second_Wed_pax,Second_Wed_capacity)
ce43ea47768d18e1c4e0eccbd13c3cea04cd4949
jinsuwang/GoogleGlass
/src/main/python/Tree/inOrderTraversal.py
1,898
3.71875
4
from testTree import test_node class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ## recursive # ret = [] # self.inorderTraversalRecursive(root, ret) # return ret # Iterative ret = self.inorderTraversalIterative(root) return ret # ireversive def inorderTraversalRecursive(self, root, ret): if root == None: return self.inorderTraversalRecursive(root.left, ret) ret.append(root.val) self.inorderTraversalRecursive(root.right, ret) # iterative using stack def inorderTraversalIterative(self, root): stack = [] sol = [] node = root while(node or len(stack)>0): if node != None: stack.append(node) node = node.left else: node = stack.pop() sol.append(node.val) node = node.right return sol def preorderTraversalRecursive(self, root, sol): if root == None: return sol.append(root.val) self.inorderTraversalRecursive(root.left, sol) self.inorderTraversalRecursive(root.right, sol) def preorderTraversalIterative(self, root): stack = [] sol = [] node = root while(node or len(stack)>0): if node != None: stack.append(node) sol.append(node.val) node = node.left else: node = stack.pop() node = node.right return sol def preorderTraversal(self, root): sol = [] self.preorderTraversalRecursive(root, sol) return sol if __name__ == "__main__": root = test_node() s = Solution() sol = s.preorderTraversalIterative(root) print sol
f38a9b367e77ec688155e3ddc38aea187691f1d3
tsgkim/pythonStudy
/HelloWorld.py
6,595
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- print "你好,世界" # raw_input("按下 enter 键退出,其他任意键显示...\n") x = "a" y = "b" # 换行输出 print x print y print '---------' # 不换行输出 print x, print y counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print counter print miles print name a = b = c = 1 print a, print b, print c a, b, c = 1, 2, "john" print a, print b, print c strs = 'Hello World!' print strs # 输出完整字符串 print strs[0] # 输出字符串中的第一个字符 print strs[2:5] # 输出字符串中第三个至第五个之间的字符串 print strs[2:] # 输出从第三个字符开始的字符串 print strs * 2 # 输出字符串两次 print strs + "TEST" # 输出连接的字符串 elists = ['runoob', 786, 2.23, 'john', 70.2] tinyelists = [123, 'john'] print elists # 输出完整列表 print elists[0] # 输出列表的第一个元素 print elists[1:3] # 输出第二个至第三个元素 print elists[2:] # 输出从第三个开始至列表末尾的所有元素 print tinyelists * 2 # 输出列表两次 print elists + tinyelists # 打印组合的列表 tuples = ('runoob', 786, 2.23, 'john', 70.2) tinytuples = (123, 'john') print tuples # 输出完整元组 print tuples[0] # 输出元组的第一个元素 print tuples[1:3] # 输出第二个至第三个的元素 print tuples[2:] # 输出从第三个开始至列表末尾的所有元素 print tinytuples * 2 # 输出元组两次 print tuples + tinytuples # 打印组合的元组 tuples = ('runoob', 786, 2.23, 'john', 70.2) listss = ['runoob', 786, 2.23, 'john', 70.2] # tuple[2] = 1000 # 元组中是非法应用 listss[2] = 1000 # 列表中是合法应用 print listss dicts = {} dicts['one'] = "This is one" dicts[2] = "This is two" tinydicts = {'name': 'john', 'code': 6734, 'dept': 'sales'} print dicts['one'] # 输出键为'one' 的值 print dicts[2] # 输出键为 2 的值 print tinydicts # 输出完整的字典 print tinydicts.keys() # 输出所有键 print tinydicts.values() # 输出所有值 a = 21 b = 10 c = 0 c = a + b print "1 - c 的值为:", c c = a - b print "2 - c 的值为:", c c = a * b print "3 - c 的值为:", c c = a / b print "4 - c 的值为:", c c = a % b print "5 - c 的值为:", c # 修改变量 a 、b 、c a = 2 b = 3 c = a ** b print "6 - c 的值为:", c a = 10 b = 5 c = a // b print "7 - c 的值为:", c a = 21 b = 10 c = 0 if a == b: print "1 - a 等于 b" else: print "1 - a 不等于 b" if a != b: print "2 - a 不等于 b" else: print "2 - a 等于 b" if b != a: print "3 - a 不等于 b" else: print "3 - a 等于 b" if a < b: print "4 - a 小于 b" else: print "4 - a 大于等于 b" if a > b: print "5 - a 大于 b" else: print "5 - a 小于等于 b" # 修改变量 a 和 b 的值 a = 5 b = 20 if a <= b: print "6 - a 小于等于 b" else: print "6 - a 大于 b" if b >= a: print "7 - b 大于等于 a" else: print "7 - b 小于 a" a = 21 b = 10 c = 0 c = a + b print "1 - c 的值为:", c c += a print "2 - c 的值为:", c c *= a print "3 - c 的值为:", c c /= a print "4 - c 的值为:", c c = 2 c %= a print "5 - c 的值为:", c c **= a print "6 - c 的值为:", c c //= a print "7 - c 的值为:", c a = 10 b = 20 if a and b: print "1 - 变量 a 和 b 都为 true" else: print "1 - 变量 a 和 b 有一个不为 true" if a or b: print "2 - 变量 a 和 b 都为 true,或其中一个变量为 true" else: print "2 - 变量 a 和 b 都不为 true" # 修改变量 a 的值 a = 0 if a and b: print "3 - 变量 a 和 b 都为 true" else: print "3 - 变量 a 和 b 有一个不为 true" if a or b: print "4 - 变量 a 和 b 都为 true,或其中一个变量为 true" else: print "4 - 变量 a 和 b 都不为 true" if not (a and b): print "5 - 变量 a 和 b 都为 false,或其中一个变量为 false" else: print "5 - 变量 a 和 b 都为 true" a = 10 b = 20 lists = [1, 2, 3, 4, 5]; if a in lists: print "1 - 变量 a 在给定的列表中 lists 中" else: print "1 - 变量 a 不在给定的列表中 lists 中" if b not in lists: print "2 - 变量 b 不在给定的列表中 lists 中" else: print "2 - 变量 b 在给定的列表中 lists 中" # 修改变量 a 的值 a = 2 if a in lists: print "3 - 变量 a 在给定的列表中 lists 中" else: print "3 - 变量 a 不在给定的列表中 lists 中" a = 20 b = 20 if a is b: print "1 - a 和 b 有相同的标识" else: print "1 - a 和 b 没有相同的标识" if a is not b: print "2 - a 和 b 没有相同的标识" else: print "2 - a 和 b 有相同的标识" # 修改变量 b 的值 b = 30 if a is b: print "3 - a 和 b 有相同的标识" else: print "3 - a 和 b 没有相同的标识" if a is not b: print "4 - a 和 b 没有相同的标识" else: print "4 - a 和 b 有相同的标识" # 例1:if 基本用法 flag = False name = 'hello' if name == 'python': # 判断变量否为'python' flag = True # 条件成立时设置标志为真 print 'welcome boss' # 并输出欢迎信息 else: print name # 条件不成立时输出变量名称 # 例2:elif用法 num = 5 if num == 3: # 判断num的值 print 'boss' elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # 值小于零时输出 print 'error' else: print 'hello' # 条件均不成立时输出 # 例3:if语句多个条件 num = 9 if 0 <= num <= 10: # 判断值是否在0~10之间 print 'hello' # 输出结果: hello num = 10 if num < 0 or num > 10: # 判断值是否在小于0或大于10 print 'hello' else: print 'undefine' # 输出结果: undefine num = 8 # 判断值是否在0~5或者10~15之间 if (0 <= num <= 5) or (10 <= num <= 15): print 'hello' else: print 'undefine' # 输出结果: undefine var = 100 if var == 100: print "变量 var 的值为100" print "Good bye!" count = 0 while count < 9: print 'The count is:', count count = count + 1 print "Good bye!" i = 1 while i < 10: i += 1 if i % 2 > 0: # 非双数时跳过输出 continue print i # 输出双数2、4、6、8、10 i = 1 while 1: # 循环条件为1必定成立 print i # 输出1~10 i += 1 if i > 10: # 当i大于10时跳出循环 break count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"
dfd94ea9f7f63375834279854833110d234f0529
HaniAboalinain/Python_Exercieses
/Ex5.py
1,769
3.828125
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 14:41:29 2019 @author: Hani """ class Employee: def __init__(self , emp_number , name , address , salary , job_title ): self.emp_number = emp_number self.__name = name self.__address = address self.__salary = salary self.__job_title = job_title def getName(self): return self.__name def getAddress(self): return self.__address def setAddress(self , newaddress): self.__address = newaddress def getSalary(self): return self.__salary def getJobTitle(self): return self.__job_title def __del__(self): print(self.__name +" has been deleted") def getEmpInfoFormate1(self): print("Employee1 Information :" , "\n\tEmployee Number : " + str(self.emp_number) , "\n\tName : " + str(self.getName()) , "\n\tAddress : " + str(self.getAddress()) , "\n\tSalary : " + str(self.getSalary()) , "\n\tJob Title : " + str(self.getJobTitle())) def getEmpInfoFormate2(self): print("Employee2 Information :" , "Employee Number : " + str(self.emp_number) , ", Name : " + str(self.getName()) , ", Address : " + str(self.getAddress()) , ", Salary : " + str(self.getSalary()) , ", Job Title : " + str(self.getJobTitle())) Emp1 = Employee( 1 , "Mohammad Khalid" , "Amman,Jordan" , 500.0 , "Consultant") Emp2 = Employee( 2 , "Hala Rana" , "Aqaba,Jordan" , 750.0 , "Manager") Emp1.getEmpInfoFormate1() Emp2.getEmpInfoFormate2() Emp1.setAddress("USA") print(Emp1.getAddress()) del Emp1 del Emp2
9c389053bb348363ef42f287a2e05afafc4e34e0
yangdaodao92/tf-learning
/MF/e5-activation-function.py
1,106
3.765625
4
# 激励函数就是一个非线性函数,常见的如:relu, sigmoid, tanh,激励函数必须可以微分 # 因为在 backpropagation 误差反向传递的时候, 只有这些可微分的激励函数才能把误差传递回去 # 实际问题的函数往往是非线性的 # 想要恰当使用这些激励函数, 还是有窍门的. # 比如当你的神经网络层只有两三层, 不是很多的时候, 对于隐藏层, 使用任意的激励函数, 随便掰弯是可以的, 不会有特别大的影响. # 不过, 当你使用特别多层的神经网络, 在掰弯的时候, 玩玩不得随意选择利器. # 因为这会涉及到梯度爆炸, 梯度消失的问题. 因为时间的关系, 我们可能会在以后来具体谈谈这个问题. # 最后我们说说, 在具体的例子中, 我们默认首选的激励函数是哪些. # 在少量层结构中, 我们可以尝试很多种不同的激励函数. # 在卷积神经网络 Convolutional neural networks 的卷积层中, 推荐的激励函数是 relu. # 在循环神经网络中 recurrent neural networks, 推荐的是 tanh 或者是 relu
c0a75cedcb5bc6185c8251f7e8bf859f34c8aa79
neuromotion/USB-event-marker
/example.py
1,695
3.5625
4
#! /usr/bin/python3 import serial from time import sleep # Our script for finding the serial port of the attached USB Event Marker import find_event_marker_port # This is an example of how to send event codes to the USB Event Marker device # from an application. The event code will be represented in binary on the # device's output pins. For example, sending 255 will cause all 8 output pins # to pulse at once. Sending powers of 2 will each cause a single pin to # pulse. # # Note: if the firmware's `ALWAYS_PULSE_MASK` feature is enabled, certain pins # will always pulse on every event, regardless of the event code value (eg. to # flash an LED on every event). def send(port_file, event_code): """Write the event code (1-255) to the serial port.""" print("sending:", event_code) port_file.write(bytes([event_code])) port_file.flush() def loop_through_events(start_code, end_code, port_file): """Send all the events between start_code and end_code, with brief pauses in between""" seconds_between_events = 0.5 print("Sending event codes %d-%d. Type ctrl-c to quit." % (start_code, end_code)) for event_code in range(start_code, end_code+1): send(port_file, event_code) sleep(seconds_between_events); def main(): # Use the included script to find and configure the USB Event Marker serial port. # On linux, the path may be something like `/dev/ttyACM0`. port_path = find_event_marker_port.find() # We can open it as a writeable binary file port_file = open(port_path, 'wb') loop_through_events(1, 127, port_file) # Close the file when we're done port_file.close() if __name__ == "__main__": main()
1685b1a78d3d0ea9555f646539f89c9f2b2691a5
leeweiyee/sparta_python_training
/python_development/5_lambda.py
1,302
4.40625
4
# Lambda function # A lambda function is a way of defining a function in a single line of code # e.g. the following lambda function multiplies a number by 2 and then adds 3: mylambda = lambda x: (x * 2) + 3 # e.g. this lambda function takes in a string, assigns it to the temporary variable x, and then converts it into lowercase: stringlambda = lambda x: x.lower() print(stringlambda("Oh Hi Mark!")) # output: # > "oh hi mark!" # e.g. this function returns the first and last letters of a string: mylambda = lambda x: x[0] + x[-1] # e.g. this function will convert the number of hours into time-and-a-half hours using an if statement: def myfunction(x): if x > 40: return 40 + (x - 40) * 1.50 else: return x # lambda function: myfunction = lambda x: 40 + (x - 40) * 1.50 if x > 40 else x # lambda x: [OUTCOME IF TRUE] if [CONDITIONAL] else [OUTCOME IF FALSE] # get_last_name takes a string with someone’s first and last name and returns their last name: get_last_name = lambda x: x.split(' ')[-1] # addition function method: def add(num1,num2): return num1+num2 # print(add(23,45)) # lambda addition function: addition = lambda num1, num2:num1 + num2 # print(addition(23,45)) savings = [234,567,674,78] bonus = list(map(lambda x: x * 1.1, savings)) print(bonus)
11be5d5fcfd64b694179356e6ce5c790044c9598
SunnyMarkLiu/LeetCode
/101-200/168. Excel Sheet Column Title.py
530
3.734375
4
#!/home/sunnymarkliu/softwares/anaconda3/bin/python # _*_ coding: utf-8 _*_ """ @author: SunnyMarkLiu @time : 18-3-19 上午10:25 """ class Solution: def convertToTitle(self, n): """ :type n: int :rtype: str """ if not isinstance(n, int) or n < 1: return None result = '' while n > 0: n -= 1 # 此处减一,方便后续的偏移量操作 result = chr(ord('A') + n % 26) + result n = n // 26 return result
3d767f5aeb093760706036fd88c8e7ade965f551
JianmingXia/StudyTest
/PythonPro/demo/exception.py
1,487
3.59375
4
# -*- coding: UTF-8 -*- # 异常 class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args # 定义函数 # def mye( level ): # if level < 1: # raise Exception("Invalid level!", level) # # 触发异常后,后面的代码就不会再执行 # # try: # mye(0) // 触发异常 # except "Invalid level!": # print 1 # else: # print 2 # 定义函数 # def temp_convert(var): # try: # return int(var) # except ValueError, Argument: # print "no number\n", Argument # # # 调用函数 # temp_convert("xyz"); # try: # fh = open("testfile", "r") # try: # fh.write("这是一个测试文件,用于测试异常!!") # finally: # print "close" # fh.close() # except IOError: # print "Error" # try: # fh = open("testfile", "w") # fh.write("这是一个测试文件,用于测试异常!!") # finally: # print "Error" # try: # fh = open("testfile", "r") # fh.write("这是一个测试文件,用于测试异常!!") # except IOError: # print "Error" # else: # print "ok" # fh.close() # try: # fh = open("testfile", "w") # fh.write("这是一个测试文件,用于测试异常!!") # except IOError: # print "Error: 没有找到文件或读取文件失败" # else: # print "内容写入文件成功" # fh.close()
bc59a8cd516641ef99e6f7272ba97faa81f8447f
douzhenjun/python_work
/Array/rotatePrintArray.py
613
3.84375
4
#如何对数组进行旋转,将一个n*n的二维数组逆时针旋转45度后打印,具体形式看书上第147页 def rotateArr(arr): lens = len(arr) #打印二维数组中的右上半部分 i = lens - 1 while i > 0: row = 0 col = i while col < lens: print(arr[row][col]) row += 1 col += 1 print("\n") i -= 1 #打印二维数组左下半部分(包括对角线) i = 0 while i < lens: row = i col = 0 while row < lens: print(arr[row][col]) row += 1 col += 1 print("\n") i += 1 if __name__ == "__main__": arr = [[1, 2, 3],[4, 5, 6], [7, 8, 9]] rotateArr(arr)
e0677f25032e15625a282e2b433b3ea42ab3b1eb
tigranpro7/BEHomeworks
/Lesson5-new/easy53.py
553
3.90625
4
# Задание-3: # Дан список, заполненный произвольными числами. # Получить список из элементов исходного, удовлетворяющих следующим условиям: # + Элемент кратен 3 # + Элемент положительный # + Элемент не кратен 4 import random old_list = [random.randint(-10,10) for _ in range(10)] new_list = [el for el in old_list if el % 3 == 0 and el >= 0 and el % 4 != 0] print(old_list, '-->', new_list)
6cba8951f4d14ad7d9030824cd711e1166f25adc
Ljazz/studyspace
/python/code/Design Patterns/1001-singleton_pattern.py
3,079
3.53125
4
# 单例简单示例 class Singleton1: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance def getInstance(self): print('id ==> {}'.format(id(self))) return self._instance # 单例实现的方式1:重写__new__方法 class Singleton2: _instance = None _isFirstInit = False def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) return cls._instance def __init__(self, name): if not self._isFirstInit: self._name = name print('First created {}'.format(self._name)) Singleton2._isFirstInit = True else: print('Not First created {}'.format(name)) def getInstance(self): print('唯一真神: {}'.format(self._name)) # 单例实现的方式2-自定义metaclass class Singleton3(type): """ 单例实现方式 - metaclass """ def __init__(cls, what, bases=None, dict=None): super().__init__(what, bases, dict) cls._instance = None # 初始化全局变量cls._instance为None def __call__(cls, *args, **kwargs): # 控制对象的创建过程,如果cls._instance为None,则创建,否则直接返回 if cls._instance is None: cls._instance = super().__call__(*args, **kwargs) return cls._instance class CustomClass(metaclass=Singleton3): """ 用户自定义的类 """ def __init__(self, name): self.__name = name def getName(self): return self.__name def SingletonDecorator(cls, *args, **kwargs): """ 定义单例装饰器 """ instance = {} def wrapperSingleton(*args, **kwargs): if cls not in instance: instance[cls] = cls(*args, **kwargs) return instance[cls] return wrapperSingleton @SingletonDecorator class Singleton4: """ 使用单例装饰器修饰一个类 """ def __init__(self, name): self.__name = name def getName(self): return self.__name if __name__ == '__main__': s1 = Singleton1() s2 = Singleton1() print('*' * 20) print(s1.getInstance()) print(s2.getInstance()) print('*' * 20) print(id(s1.getInstance()), id(s2.getInstance())) print(Singleton1.__dict__) print('#' * 20) s11 = Singleton2('s11') s22 = Singleton2('s22') s11.getInstance() s22.getInstance() print(id(s11), id(s22)) print(id(s11) == id(s22)) print('#' * 20) tony = CustomClass('Tony') karry = CustomClass('Karry') print(tony.getName(), karry.getName()) print('id(tony): ', id(tony), 'id(karry): ', id(karry)) print('tony == karry :', tony == karry) print('#' * 20) tony = Singleton4('Tony') karry = Singleton4('Karry') print(tony.getName(), karry.getName()) print('id(tony): ', id(tony), 'id(karry): ', id(karry)) print('tony == karry :', tony == karry) print('#' * 20)
1d9f13f77a863569ba285fd85fda6468d32a9172
Prometeo/python-code-snippets
/decapitalize.py
228
3.953125
4
def decapitalize(var): """ This method can be used to turn the first letter of the given string into lowercase """ return var[:1].lower() + var[1:] if __name__ == '__main__': print(decapitalize('FooBar'))
5c3defb19f0eb9d8ae453539f5e6ea1bb3d9aead
EndIFbiu/python-study
/12-函数/05-注释.py
423
3.828125
4
help(len) # help函数作用,查看函数的说明文档 ''' 定义函数的说明文档 def 函数名(参数): """说明文档的位置""" 代码 ... ''' def sum(a, b): """ 求和函数 """ return a + b help(sum) # 函数说明文档的高级使用 def sum2(a, b): """ 求和函数 :param a:参数1 :param b:参数2 :return:返回值 """ return a + b help(sum2)
06d4d2db5237993f4a6bfae3a0b7aa0174451afd
lucaspal/python-backend
/flower-garden/flowers/base/flower.py
3,251
4
4
import random import string from abc import ABC, abstractmethod from weather import Weather class Flower(ABC): def __init__(self, *, name: string, description: string, height: float, hydration: float, max_height: float): self._name = name self._description = description self._height = height self._hydration = hydration self.max_height = max_height def __str__(self): if self.is_dead(): return 'Flower Name: {name} ({description}). ' \ 'This flower is dead.'.format(name=self._name, description=self._description) else: return 'Flower Name: {name} ({description}). ' \ 'It is {height} cm tall, with an hydration of {hydration}%'.format( name=self._name, description=self._description, height=self._height, hydration=self._hydration) @property def name(self): return self._name @property def description(self): return self._description @property def height(self): """ Represents the height of the flower (in centimeters). """ return self._height @height.setter def height(self, value: float): if value < 0: self._height = 0 else: self._height = value if value < self.max_height else self.max_height @property def hydration(self): """ Represents the hydration of the flower (in percentage). """ return self._hydration @hydration.setter def hydration(self, value: float): if value < 0: self._hydration = 0 if value > 100: self._hydration = 100 else: self._hydration = value def process_day_with_condition(self, *, weather: Weather): if weather is Weather.SUNNY: self._on_sunny_day() elif weather is Weather.CLOUDY: self._on_cloudy_day() elif weather is Weather.RAINY: self._on_rainy_day() @abstractmethod def is_dead(self): raise NotImplementedError @abstractmethod def _on_rainy_day(self): raise NotImplementedError @abstractmethod def _on_sunny_day(self): raise NotImplementedError @abstractmethod def _on_cloudy_day(self): raise NotImplementedError @staticmethod def _draw_initial_height(min_value, max_value, *, upper_limit): if min_value < 0: raise ValueError('Min value cannot be negative') if max_value > upper_limit: raise ValueError('Max value cannot be greater than upper limit.') return round(min_value + (max_value - min_value) * random.random(), 1) @staticmethod def _draw_initial_hydration(min_value, max_value): if min_value < 0: raise ValueError('Min value cannot be negative.') if max_value > 100: raise ValueError('Max value cannot be greater than 100.') return round(min_value + (max_value - min_value) * random.random(), 1)
8843ddbe52bb155c147feed8e1541dce0a3c2297
WallysonGalvao/Python
/CursoEmVideo/1 - OneToTen/Challenge002.py
314
4.1875
4
""""Responding to user""" # Challenge 002 # Make a program that reads the name a person and show a welcome message. print("Challenge 002") print("Make a program that read the name a person and show a welcome message.") userName = input("Write your name: ") print("It's a pleasure meet you, {}!".format(userName))
3cdc1dc58b27c8bd35e3355b85bd8bd0e1850e6a
aa-glitch/aoc2019
/day03/solution.py
532
3.796875
4
#!/usr/bin/env python """Compute minimum distance and steps of wire crossings.""" import sys from wire import deserialize_wire, find_crossings def get_input(): wire1 = deserialize_wire(sys.stdin.readline()) wire2 = deserialize_wire(sys.stdin.readline()) return wire1, wire2 if __name__ == '__main__': crossings = find_crossings(*get_input()) min_dist = min(c['dist'] for c in crossings) min_steps = min(c['steps'] for c in crossings) print(f'part 1: {min_dist}') print(f'part 2: {min_steps}')
b8d4c5e3a3314ed4edd8dae723042f401bc0de52
seryph/python_syntax_course
/6.objects.py
674
3.921875
4
# Object Oriented Programming class Dog: # Constructor def __init__(self, name, age, breed): self.name = name self.age = age self.breed = breed # Method def say_name(self): print(f"My name is {self.name}") spot = Dog("Spot", 11, "Poodle") print(spot.age) spot.say_name() print('\n') # Inheritance class Pug(Dog): def __init__(self, name, age, breed, face): super().__init__(name, age, breed) self.face = face # Method def is_it_ugly(self): print(f"{self.name} has a {self.face} face") pudge = Pug("Pudge", 12, "Pug", "cute") print(pudge.name) pudge.is_it_ugly()
4829104185b045ca24d0e3e92508702beed960ff
Kaushik-18/Python-codes
/data-structures-algos/heaps.py
1,617
3.875
4
class Heaps : def __init__(self): self.heaplist = [0] self.currentsize = 0 # parent of current node can be calculated by dividing index of current node by 2. # for every node , the value in parent is less than the value in the node # if node is at positon p , children are at poition 2p & 2p +1 def adjust_heap(self , index) : while( index > 0) : if self.heaplist[i] < self.heaplist[i//2] : temp = self.heaplist[i//2] self.heaplist[i//2] = self.heaplist[i] self.heaplist[i] = temp index = index//2 def insert(self,value): self.heaplist.append(value) self.currentsize = currentsize + 1 self.adjust_heap(self.currentsize) def find_min_child(self,index): if 2*index +1 > self.currentsize : return 2* index if self.heaplist[2*index] < self.heaplist[2*index +1] : return 2*index else : return 2*index + 1 def adjust_heap_down(self,index): while 2*index < self.currentsize : min_index = find_min_child(index) if self.heaplist[index] > self.heaplist[min_index] temp = self.heaplist[index] self.heaplist[index] = self.heaplist[min_index] self.heaplist[min_index] = temp index = min_index def pop_min(self): val = self.heaplist[1] self.heaplist[1] = self.heaplist[self.currentsize] self.currentsize = self.currentsize - 1 self.heaplist.pop() adjust_heap_down(1) return val
7c329b418bdad748bbfe3ab6110f0e929325e44c
ks-randhawa0649/Python-Shortest-GPS-path
/windowcreate.py
674
4.15625
4
from tkinter import * def calculate(): #print("Aie!") x=float(e1.get()) #print("The double of " , x , "is " ,2*x) V.set(str(2*x)) window=Tk() window.title("Double") l1=Label(window,text="x:") l1.grid(row=0 , column=0) e1=Entry(window,fg="blue",bg="white") e1.grid(row=0 , column=1) l2=Label(window,text="2*x:") l2.grid(row=1 , column=0) V=StringVar() l3=Label(window,fg="blue",bg="white",textvariable=V) l3.grid(row=1 , column=1) b1=Button(window,text="Quit",command=quit) b1.grid(row=2,column=0) b2=Button(window,text="Calculate",command=calculate) b2.grid(row=2,column=2) window.mainloop()
b68bbec2512c2641d7e1aa110e85e30a6198ce9d
devpatel18/PY4E
/ex_07_02.py
805
3.921875
4
avg=0 count=0 while True: fname=input("Enter the file name along with extensions:") if "." in fname: try: fhand=open(fname) except: print("File name entered does not exist") continue for line in fhand: line=line.strip() if line.startswith("X-DSPAM-Confidence"): count=count+1 temp=line.find(":") temp1=line[temp+1:] temp2=float(temp1.strip()) avg=avg+temp2 print("Line count:",count) print("Average spam confidence:",avg/count) break else: print("please enter extension") continue
8501dd07eddb9f5bba9f0917a1cbe2f457179567
rtao258/TIP-Project-2
/type_tools.py
1,038
3.84375
4
import sys from collections import Mapping, Container from sys import getsizeof def deep_getsizeof(o, ids): """Find the memory footprint of a Python object This is a recursive function that drills down a Python object graph like a dictionary holding nested dictionaries with lists of lists and tuples and sets. The sys.getsizeof function does a shallow size of only. It counts each object inside a container as pointer only regardless of how big it really is. :param o: the object :param ids: :return: """ if id(o) in ids: return 0 r = getsizeof(o) ids.add(id(o)) if isinstance(o, str) or isinstance(0, unicode): return r if isinstance(o, Mapping): return r + sum(deep_getsizeof(k, ids) + deep_getsizeof(v, ids) for k, v in o.iteritems()) if isinstance(o, Container): return r + sum(deep_getsizeof(x, ids) for x in o) return r while True: value = int(input("\nEnter a value: ")) print(deep_getsizeof(type(value)))
5eb81acfa1792311e9254a3906eca33f9e4cc56d
Supreme-YS/PythonWorkspace
/CodingDojangPython/application_list_tuple_11.py
535
3.578125
4
# list and map a = [1.2, 2.5, 3.7, 4.6] for i in range(len(a)): a[i] = int(a[i]) print(a) # list and map a = list(map(int, a)) print(a) # list and map a = list(map(str, range(10))) print(a) # input().split() and map a = input().split() print(a) a = map(int, input().split()) x = input().split() # input().split()의 결과는 문자열 리스트 m = map(int, x) # 리스트의 요소를 int로 변환, 결과는 맵 객체 a, b = m # 맵 객체는 변수 여러 개에 저장할 수 있음
21bf9ddf51dc46dc9d29a11ca2a34593194dc260
higorrodrigues8/Python-MySQL
/GRAFICOS/plot2_Legacy
332
3.875
4
import matplotlib.pyplot as plt x = [1, 2, 5] y = [2, 3, 7] #_______________________TITULO plt.title("Meu primeiro gráfico python") #_______________________ plt.plot(x, y) #_______________________LEGENDAS plt.xlabel("Eixo x") plt.ylabel("Eixo y") #_______________________ #_______________________SHOW plt.show()
98e9c789daa04eca77e6ae79d2e730db3f46a460
michielvermeir/nearby-tweets
/test_tweets_nearby.py
1,023
3.59375
4
""" Unit tests """ import types from tweets_nearby import get_tweets from tweets_nearby import get_tweets_map def test_get_tweets(): """Test if get_tweets generator actually generate some tweets.""" tweets = get_tweets(where='Dublin', lang='en', pages=1) assert isinstance(tweets, types.GeneratorType) tweets = tuple(tweets) # generatre some tweets assert len(tweets) # check if there are some tweets for tweet in tweets: assert isinstance(tweet, str) # check if tweets are readable def test_get_tweets_map(): """Test if get_tweets generator actually generate some tweets.""" tweets = get_tweets_map(where='Warsaw', lang='en', pages=1) assert isinstance(tweets, types.GeneratorType) tweets = tuple(tweets) # generatre some tweets assert len(tweets) # check if there are some tweets for tweet in tweets: assert isinstance(tweet, dict) # check if tweets are readable assert 'tweet' in tweet assert 'coordinates' in tweet['geometry']
8a55a7960785e4f506ca1abee22e87119a333526
joshuagato/learning-python
/Basics/String.py
593
3.78125
4
splitString = "This string has been \n split over several \n lines" print(splitString) print() print() tabbedString = "1\t2\t3\t4\t5\t6" print(tabbedString) print() print() print('The pet shop owner said "No, no, \'e\'s uh...he\s resting"') print("The pet shop owner said \"No, no, 'e's uh...he's resting\"") print() print() anotherSplitString = """This string has been split over several lines""" print(anotherSplitString) print() print() print('''The pet shop owner said "No, no, 'e's' uh,...he's resting"''') print("""The pet shop owner said "No, no, 'e's' uh,...he's resting" """)
2459490f44f79c9eedc6a6abf56d434549bf86d8
brancherbruno/ExerciciosPythonCursoEmVideo
/ex016.py
225
3.921875
4
import math nome = input('Olá, digite seu nome:') n = float(input('{} por favor digite um número qualquer:'.format(nome))) print('O número {} que você digitou {}, tem a parte inteira {}'.format(n, nome, (math.trunc(n))))
91bfb3f9c664fe1f96a18c46a2e026799e15b6ee
ironsketch/pythonSeattleCentral
/Turtle/nestedsq.py
1,191
3.546875
4
import turtle from math import * from random import randint wn = turtle.Screen() wn.bgcolor('Dark Slate Gray') wn.title('Kokoro saves your heart') kokoro = turtle.Turtle() colorList = ['Purple','Deep Pink','Red','Dark Orange','Yellow','Lime Green','Deep Sky Blue','Midnight Blue'] kokoro.color('Medium Turquoise','Purple') def randColor(): color = randint(0,7) return color def reposition(): kokoro.pu() kokoro.bk(300) kokoro.rt(90) kokoro.fd(300) kokoro.lt(90) kokoro.pd() def getReady(length,numberOfSquares): kokoro.lt(45) first = sqrt(length**2 + length**2) move = first / numberOfSquares kokoro.pu() kokoro.fd(move) kokoro.rt(45) kokoro.pd() def squary(length,numberOfSquares): for i in range (numberOfSquares): kokoro.pencolor(colorList[randColor()]) kokoro.color(colorList[randColor()],colorList[randColor()]) kokoro.begin_fill() for i in range (4): kokoro.fd(length) kokoro.lt(90) kokoro.end_fill() getReady(length,numberOfSquares) length = (length / numberOfSquares) * (numberOfSquares - 2) reposition() squary(500,15) kokoro.ht()
0211d3fdf8763fe558af469cf96bb1b423be1697
CianTwyfordDIT/InstrumentID
/PredictClass_test.py
1,345
3.640625
4
# This file conducts unit tests on the mostFrequent # method from the PredictClass module. 2 lists are # provided as parameters for the method. 4 tests are # conducted. Test 1 and 3 are expected to fail, while # Test 2 and 4 are expected to succeed. import unittest from PredictClass import mostFrequent # Create a list of different integers list1 = [1, 1, 1, 1, 1, 1, 2] # Create a list of different instrument classes list2 = ["Acoustic Guitar", "Acoustic Guitar", "Acoustic Guitar", "Acoustic Guitar", "Flute"] # Test 1 - Pass in list1, expected result is that 1 is returned class TestMostFrequent1(unittest.TestCase): def test_mostFrequent1(self): self.assertEqual(mostFrequent(list1), 2) # Test 2 - Pass in list1, expected result is that 1 is returned class TestMostFrequent2(unittest.TestCase): def test_mostFrequent2(self): self.assertEqual(mostFrequent(list1), 1) # Test 3 - Pass in list2 - expected result is that "Acoustic Guitar" is returned class TestMostFrequent3(unittest.TestCase): def test_mostFrequent3(self): self.assertEqual(mostFrequent(list2), "Flute") # Test 4 - Pass in list2 - expected result is that "Acoustic Guitar" is returned class TestMostFrequent4(unittest.TestCase): def test_mostFrequent4(self): self.assertEqual(mostFrequent(list2), "Acoustic Guitar")
e949531476143c4f88c17e1c9b6123a2c4a35f2a
Milagros12345/mila12
/milagros.py
2,180
3.578125
4
from random import* from time import* from turtle import* def seleccion(lista): for i in range(0,len(lista)-1): mini = i for j in range(i+1,len(lista)): if lista[j]<lista[mini]: mini=j if mini != i: c=lista[i] lista[i]=lista[mini] lista[mini]=c dibujar(l0) sleep(0.2) return lista def dibujar (l): hideturtle() tracer(0,0) clear () x= -200 for i in range(0,len(l)): penup() goto(x,0) pendown() goto(x,l[i]) x+=5 update() def insertion(lista): for i in range(1,len(lista)): x=lista[i] j=i while j>0 and lista[j-1]>x: lista[j]=lista[j-1] dibujar(lista) j-=1 lista[j]=x sleep(0.02) return lista def burbuja(lista): n=len(lista) cambio=True while cambio: cambio=False for i in range(0,n-1): if lista[i]>lista[i+1]: c=lista[i] lista[i]=lista[i+1] lista[i+1]=c dibujar(lista) cambio=True n=n-1 sleep(0.2) return lista def particion(l,primero,ultimo): indexPivote=primero valorPivote=l[indexPivote] l[indexPivote],l[ultimo]=l[ultimo],l[indexPivote] index=primero for i in range(primero, ultimo): if l[i] < valorPivote: l[i],l[index]=l[index],l[i] index+=1 l[index],l[ultimo]=l[ultimo],l[index] sleep(0.2) return index def quicksort(l,inicio, fin): if fin > inicio: index = particion(l,inicio,fin) quicksort(l,inicio,index-1) quicksort(l,index+1,fin) def ordenar(lista): quicksort(lista,0,len(lista)-1) dibujar(lista) def OrdenxMezcla(L): if len(L) < 2: return L mitad=len(L)//2 left = OrdenxMezcla(L[:mitad]) right = OrdenxMezcla(L[mitad:]) res=mezcla(left,right) dibujar(res) sleep(0.10) return res def mezcla(l1,l2): l3 = [] while len(l1)!=0 and len(l2)!=0: if l1[0]>l2[0]: l3.append(l2.pop(0)) else: l3.append(l1.pop(0)) return l3+ l1 + l2 l=[] for i in range(0,100): l.append(i) start_time = time() OrdenxMezcla(l) end_time = time() - start_time print "demoro: ", end_time
20e2f18f0d9a62efa6b441a6f4b781211f563006
xxz199539/knowledge
/PythonBasic/ListSort.py
2,576
3.875
4
# -*- coding:utf-8 -*= class SortList(object): def __init__(self, aList): for param in aList: if not (isinstance(param, int) or isinstance(param, float)): raise Exception("want int or float") self.aList = aList # 选择排序 def select_sort(self): for i in range(len(self.aList)): max_index = i for j in range(i, len(self.aList)): if self.aList[j] > self.aList[max_index]: self.aList[j], self.aList[max_index] = self.aList[max_index], self.aList[j] return self.aList # 插入排序 def insert_sort(self): for i in range(len(self.aList)): for j in range(i, len(self.aList)): if self.aList[i] > self.aList[j]: self.aList[i:j + 1] = [self.aList[j]] + self.aList[i:j] return self.aList # 快速排序 def quick_sort(self, start, end): if start >= end: return i, j = start, end base = self.aList[i] while i < j: while (i < j) and (self.aList[j] >= base): j -= 1 self.aList[i] = self.aList[j] while (i < j) and (self.aList[i] <= base): i += 1 self.aList[j] = self.aList[i] self.aList[i] = base self.quick_sort(start, i - 1) self.quick_sort(i + 1, end) return self.aList # 希尔排序 def shell_sort(self): gap = len(self.aList) // 2 while gap > 0: for i in range(gap, len(self.aList)): while i >= gap and self.aList[i - gap] > self.aList[i]: self.aList[i - gap], self.aList[i] = self.aList[i], self.aList[i - gap] i -= gap gap //= 2 return self.aList # 归并排序 def merge_sort(self, aList=None): def merge(left, right): res = [] l, r = 0, 0 while l < len(left) and r < len(right): if left[l] < right[r]: res.append(left[l]) l += 1 else: res.append(right[r]) r += 1 res += left[l:] res += right[r:] return res sort_list = aList if aList else self.aList if len(sort_list) <= 1: return sort_list num = len(sort_list) // 2 left = self.merge_sort(sort_list[:num]) right = self.merge_sort(sort_list[num:]) return merge(left, right)
1f27f6f31d3d9c936a2f09de29443b1fe8278733
hongkailiu/test-all
/trunk/test-python/script/t2.py
491
4
4
#!/usr/bin/python def get_province_name(address): words = address.split(',') l = len(words) if l < 3: return "unknown" else: return words[l-3].strip() def get_province_names(addresses): return map(get_province_name, addresses) a = "333 Abc Street, QC, H4R 2X6, Canada" b = "Apt 206-26 Bcd Street, NY, 12345, USA" print a + ": " + get_province_name(a) print b + ": " + get_province_name(b) print "a, b: " + ", ".join(get_province_names([a, b]))
6358ab35f9ec4b93859362b35daaf7c7b5562d55
ziweiwu/MIT-introduction-in-computer-science
/num_convert_to_mandarin.py
789
3.703125
4
trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'} def convert_to_mandarin(us_num): ''' us_num, a string representing a US number 0 to 99 returns the string mandarin representation of us_num ''' string='' if len(us_num)==1: string=trans[us_num] else: for i in us_num: if i in trans and trans[i]!='ling': string=string+trans[i]+' '+'shi ' else: string=string+trans[i] string=string[:-5] if string[0:2]=='yi': string=string[3:] return string print(convert_to_mandarin('16')) print(convert_to_mandarin('22')) print(convert_to_mandarin('2'))
0747190d741c13d46405dbdfce3e7320974856e0
Vincentxjh/practice0821
/005.py
285
3.6875
4
#第五个练习 - 删除用户数据 import sqlite3 conn = sqlite3.connect('mr.db') cursor = conn.cursor() cursor.execute('delete from user where id = 1') cursor.execute('select * from user') result = cursor.fetchall() print(result) cursor.close() conn.commit() conn.close()
897caed7044e27979f79e5be35ca8d4574e2e65b
NoelArzola/10yearsofPythonWoot
/1 - intro/create_json_with_nested_dict.py
427
3.59375
4
import json # Create a dictionary object person_dict = {'first': 'Noel', 'last':'Arzola'} # Add additional key pairs to dictionary as needed person_dict['City']='Boaz' # create a staff dictionary # assign a person to a staff position of program manager staff_dict ={} staff_dict['Full-Stack Developer']=person_dict # Convert dictionary to JSON object staff_json = json.dumps(staff_dict) # Print JSON object print(staff_json)
06508f397fa19876bb1f03c9725c0ef837222e40
GR3C0/Ecuaciones
/cal_torn.py
451
3.890625
4
#-*- coding: utf-8 -*- from os import times __version__ = 0.1 boton = False #en pruebas hasta TKinter opciones = [ "Calcular distacia", "Velocidad del viento", "Pronostico" ] print(opciones) opcion_usuario = input("¿Opción elegida?: ") def calcular_distancia(): #Función que calcula la distancia con una ecuación while boton == True: print(os.times()) if opcion_usuario == "calcular distancia": boton = True calcular_distancia()
c582ccb70dd682c4aeca4cd344ad474a06d52352
a1774281/UndergraduateCode
/Python/Practicals/Prac 5/Prac5exe1.py
562
3.828125
4
# # File: Prac5Exc1.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 12/04/19 # Description: Practical 5, exercise 1. # This is my own work as defined by the University's # Academic Misconduct policy. # n = int(input("Please enter an integer: ")) count = 1 if n < 1: n = int(input("Invalid: Please enter an integer: ")) while n != 1: print("The number is:", n) if n % 2 == 0: n = n/2 else: n = n * 3 + 1 count += 1 print("The number is:", n) print("The sequence took,", count, "steps")
830691a21366013650ad86e0d2c59dec07c14454
utkarsht724/PythonBasicPrograms
/Dictionary/List_to_dictionary.py
271
4.21875
4
#program to count the number of dictionary value that is a list def list_to_dictionary(): my_list=[1,1,1,2,3,4,4,5,6] my_dict={} for i in range(len(my_list)): my_dict[my_list[i]] = my_list.count(my_list[i]) print(my_dict) list_to_dictionary()
d2690ef326cd5048781614fbc90709dc63caae80
t0futac0/ICTPRG-Python
/Variables.py
389
4.15625
4
## Q3 first_name= 'Tom' last_name='Munro' print('The first name is ', first_name) print('The last name is ', last_name) ## Q4 cost=199 print('The cost is', cost) # Get user's first name name=input("What is your name; ") # Get user's second name surname=input('Enter your surname ') # Greet the user print("Welcome", first_name, surname) print("Welcome " +first_name+ " " +surname)
29950abe323f5584b7f3b5e7af0cfa8bb80ddfb1
tkj5008/Luminar_Python_Programs
/Python_Collections/Sets/set2.py
177
3.65625
4
a=set() b=set() lmt=int(input("enter the limit")) for i in range(lmt): element=int(input("enter element")) a.add(element) for i in a: b.add(i**2) print(a) print(b)
8654cbb841bc16be605b85f5d97dcd9167adb3dd
Otabek-KBTU/PT-Python
/IntroductiontoPython.py
982
4.09375
4
print('') print("") 20//6= 3 # целочисленного деления (//) 20%6= 2 # деления по модулю (%) print('My name's Otabek') # не правильно. для того чтобы программа смогла вывысти надо ставить \ ' print('My name\'s Otabek') '\n' # когда мы использовали Enter, программа автоматический вводит \n """Spring Summer""" == 'Spring\nSummer' # простые функиции ввода и ввывода # чтобы получить данные от пользователья, надо использовать input # чтобы вывода данные в экран, используется функция print input() input("Enter something:") 2 Операция со строками "Spam" + 'eggs' 'Spameggs' "2"+"2" == 22 print("spam"*3) 4*'2' == '2222' Error '17'*'18' and 'python'* 7.0
40abf81ff1554fbc6dc3bad568a69c6866ea0eb2
vinceajcs/all-things-python
/algorithms/array/wiggle_sort.py
767
4.1875
4
"""Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... Time: O(n) Space: O(1) """ """Sort nums, and then swap by pairs.""" def wiggle_sort(nums): nums.sort() # sorting bottleneck O(nlogn) n = len(nums) if len(nums) % 2 == 0 else len(nums) - 1 for i in range(2, n, 2): nums[i - 1], nums[i] = nums[i], nums[i - 1] """Better idea using one pass through the array.""" def wiggle_sort(nums): for i in range(len(nums) - 1): if i % 2 == 0: # even index if nums[i] > nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i] else: # odd index if nums[i] < nums[i + 1]: nums[i], nums[i + 1] = nums[i + 1], nums[i]
ac7ea4324b9af10d08c49af1aeeb3065a65be5dd
Huve/splort
/camera.py
2,331
3.90625
4
from pygame import Rect from run_game import WIDTH, HEIGHT, HALF_WIDTH, HALF_HEIGHT class Camera(object): """A camera that follows a sprite.""" def __init__(self, function, w, h): self.function = function self.state = Rect(0, 0, w, h) def apply(self, target): """Applies the camera to a target to blit all objects on the screen. Args: target: sprite (e.g., player, block, etc.) which camera is to be applied to. Returns: position and size of the object on the screen. """ return target.rect.move(self.state.topleft) def update(self, target): """Updates the camera's location based on center target (i.e., the player). Args: target: the sprite object of the target to be watched. Returns: updates the state of the camera based on a rectangle returned by camera function used. """ self.state = self.function(self.state, target.rect) def simple_camera(camera, target_rect): """Defines a simple camera to follow a sprite. Args: camera: camera which will use the function. target_rect: Rect of the character to be followed. Returns: Rectangle of the location and dimensions of the camera: Rect(l, t, w, h) """ l, t, _, _ = target_rect _, _, w, h = camera return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h) def complex_camera(camera, target_rect): """Defines a complex camera to follow a sprite limited by the edges of the map. Args: camera: camera which will use the function. target_rect: Rect of the character to be followed. Returns: Rectangle of the location and dimensions of the camera: Rect(l, t, w, h) """ l, t, _, _ = target_rect _, _, w, h = camera l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h l = min(0, l) # stop scrolling at the left edge l = max(-(camera.width-WIDTH), l) # stop scrolling at the right edge t = max(-(camera.height-HEIGHT), t) # stop scrolling at the bottom t = min(0, t) # stop scrolling at the top return Rect(l, t, w, h)
3c13b44c3eedc985576cb6252540bff20bb933f1
Sahil4UI/advPythonDec6Evening2020
/Python mysql connectivity/insertSQL.py
450
3.5
4
import mysql.connector connection = mysql.connector.connect( host="localhost", username="root", password = "root1234", database = "COLLEGE" ) cursor = connection.cursor() s_id = int(input("Enter Student id : ")) s_name= input("Enter Student Name : ") s_marks = int(input("Enter Student marks ")) query = "INSERT INTO COLLEGE_STUDENT VALUES(%s,%s,%s)" value = (s_id,s_name,s_marks) cursor.execute(query,value) connection.commit()
948f1ddaa727c496e7315f78292d290773ebddbe
SushilPudke/PythonTest
/Static/ObjectList1.py
589
3.828125
4
# Demo Array of objects class Bank: def __init__(self, dname,acno,amtbal): self.dname=dname self.acno=acno self.amtbal=amtbal def display(self): print(f'Depositor Name:{self.dname},Account no:{self.acno} Amount Balance:{self.amtbal}') # creating list list = [] # appending instances to list list.append( Bank('Amit',100,5000) ) list.append( Bank('Deependra',200,8000) ) list.append( Bank('Sangita', 300,10000) ) for obj in list: obj.display() # We can also access instances attributes # as list[0].name, list[0].roll and so on.
b9dac7ec5bd921318e14e6d0b2d493489bc01d6e
git874997967/LeetCode_Python
/easy/leetCode234.py
540
3.703125
4
# 234. Palindrome Linked List def isPalindrome(head): prev = None slow = head fast = head while fast is not None and fast.next is not None : fast = fast.next.next next = slow.next slow.next = prev prev = slow slow = next if fast.next is not None: slow = slow.next while slow is not None: if slow.val != prev.val: return False prev,slow = prev.next ,slow.next return True
7cfe691f81b070d2f1ce3d095842a00f66ef5516
ck-unifr/leetcode
/bfs-graph/210-course-schedule-ii.py
2,327
4.28125
4
""" https://leetcode.com/problems/course-schedule-ii/ 210. Course Schedule II There are a total of n courses you have to take labelled from 0 to n - 1. Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: numCourses = 2, prerequisites = [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0] Constraints: 1 <= numCourses <= 2000 0 <= prerequisites.length <= numCourses * (numCourses - 1) prerequisites[i].length == 2 0 <= ai, bi < numCourses ai != bi All the pairs [ai, bi] are distinct. """ import collections from typing import List class Solution: def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: graph = collections.defaultdict(list) indegree = collections.defaultdict(int) for cur, prev in prerequisites: graph[prev].append(cur) indegree[cur] += 1 sources = [] for cours in range(numCourses): if not indegree[cours]: sources.append(cours) order = [] while sources: for _ in range(len(sources)): cours = sources.pop(0) order.append(cours) for child in graph[cours]: indegree[child] -= 1 if indegree[child] == 0: sources.append(child) if len(order) != numCourses: return [] return order
5926c760d1fe62705b7bcefc5a3b6a62fa485013
RUSHIRAJSINHZALA16/QUIZ-GAME
/project1.py
1,280
4.125
4
# this my first project in python print("WELCOME to RUSHiRAJ's QUIZ!") player=input("DO you want to play QUIZ?") score = 0 if player.lower() !="yes": quit() else: print("Okay Let'play :)") answer=input("what is the full form of CPU? ") if answer.lower() == "central processing unit": print("correct!") score +=1 else: print("incorrect") answer=input("what is the full form of GPU? ") if answer.lower() == "graphics processing unit": print("correct!") score +=1 else: print("incorrect") answer=input("what is the full form of RAM? ") if answer.lower() == "random access memory": print("correct!") score +=1 else: print("incorrect") answer=input("what is the full form of ROM? ") if answer.lower() == "read only memory": print("correct!") score+=1 else: print("incorrect") answer=input("what is the full form of WiFi? ") if answer.lower() == "wireless fidelity": print("correct!") score +=1 else: print("incorrect") print("******************************************") print("you got "+str(score)+ " questions correct!") print("you scored "+str((score/5)*100 )+"%.") print("******************************************") print("thanks for playing made by rushirajsinh zala")
8bc0b0a1565d010ef5029acfe7855e996ac834ec
Prasanthdemigod/Python_Ex2
/Ex_1.py
624
3.828125
4
''' Program to implement push opeartion from one stack to another stack ''' import sys class LimitedStack: Stack_capacity = 10 def __init__(self): self.count = 0 self.data = [None]*LimitedStack.Stack_capacity def isfull(self): return LimitedStack.Stack_capacity == self.count def push(self, key): if not self.isfull(): self.data.append(key) self.count += 1 def isempty(self): return self.count == 0 def pop(self): if not self.isempty(): self.count -= 1 return self.data.pop() def length(self): return self.count def peek(self): if not self.isempty(): return self.data[-1]
00ea92223d46f4112b5de6b3b44c107ec9244fd5
DavidSorge/learning-projects
/4_9_4.py
822
4.09375
4
#------------------------------------------------------------------------------- # Name: 4.9.4 # Purpose: Draw more pretty patterns # # Author: David # # Created: 09/04/2019 # Copyright: (c) David 2019 # Licence: <your licence> #------------------------------------------------------------------------------- import turtle def draw_square(T,l): """ Tells a turtle T to draw a square with sides of length l """ for i in range(4): T.forward(l) T.left(90) wn = turtle.Screen() # Creates Turtle Screen wn.bgcolor("lightgreen") wn.title("pretty pattern") marko = turtle.Turtle() # Creates Marko the hot pink turtle marko.pensize(3) marko.color("blue") marko.speed(0) for i in range(20): draw_square(marko,100) marko.right(360/20) wn.mainloop()
7e058b8a7fb4969147d21acf3a008e683741a9a6
WeiyiGeek/Study-Promgram
/Python3/Day1/demo1-6.py
643
3.984375
4
#!/usr/bin/python3 #coding:utf-8 #功能:验证set 集合 (区分大小写) student = {"weiyigeek","WEIYIGEEK","陶海鹏","郑老狗","陈挥铭",'WEIYIGEEK'} print(student) # 输出集合(随机排序),重复的元素被自动去掉 #成员测试 if 'weiyigeek' in student: print("weiyigeek 存在!") else: print("不存在!") # set 可以进行集合运算 a = set('abracadabra') b = set('alacazam') # 下面运算是值得学习的 集合可以进行 差集 print(a - b) # a 和 b 的差集 print(a | b) # a 和 b 的并集 print(a & b) # a 和 b 的交集 print(a ^ b) # a 和 b 中不同时存在的元素
6c8816b88d0599bc9f9f4d3f7a35b331524e8ff6
WOWOStudio/Python_test
/Xin/LeetCode/data_structure/chapterIII/sectionV.py
1,116
3.96875
4
''' 剑指 Offer 28. 对称的二叉树 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。 例如,二叉树[1,2,2,3,4,4,3] 是对称的。 1 / \ 2 2 / \ / \ 3 4 4 3 但是下面这个[1,2,2,null,3,null,3] 则不是镜像对称的: 1 / \ 2 2 \ \ 3 3 示例 1: 输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: 输入:root = [1,2,2,null,3,null,3] 输出:false 限制: 0 <= 节点个数 <= 1000 作者:Krahets 链接:https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5d412v/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ''' class Solution: def isSymmetric(self, root): def recur(L, R): if not L and not R: return True if not L or not R or L.val != R.val: return False return recur(L.left, R.right) and recur(L.right, R.left) return not root or recur(root.left, root.right)
f926aeed89d01f2c24e67cc3f687c846224f32ad
nickest14/Leetcode-python
/python/easy/Solution_680.py
627
3.609375
4
# 680. Valid Palindrome II class Solution: def validPalindrome(self, s: str) -> bool: def is_palindrome(start: int, end: int) -> bool: sub_str = s[start:end + 1] return sub_str == sub_str[::-1] left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return is_palindrome(left + 1, right) or is_palindrome(left, right - 1) left += 1 right -= 1 return True ans = Solution().validPalindrome('abca') # ans = Solution().validPalindrome('deeee') # ans = Solution().validPalindrome('eccer') print(ans)
83f43b4e0187292e5dfcf812df256b614a0bcc16
Lyric912/Variables-
/variables_primary.py
4,156
4.59375
5
# author: <Lyric Marner> # date: <July 2, 2021> # # description: <fill in> # --------------- Section 1 --------------- # # 1.1 | Variable Creation | Strings # # Relevant Documentation # - https://www.w3schools.com/python/python_variables.asp # - https://www.w3schools.com/python/python_variables_names.asp # # Variables # 1) Create a variable that holds your name. # 2) Create a variable that holds your birthday. # 3) Create a variable that holds the name of an animal you like. # # Print # 4) Print each variable, describing it when you print it. # # Example Code example_name = 'elia' #print('EXAMPLE: my name is', example_name) # WRITE CODE BELOW my_name = 'Lyric' my_birthday = 'September 12, 2006' animal = 'panda' print('My name is', my_name) print('My birthday is', my_birthday) print('A', animal, 'is cute animal that I like') print() # 1.2 | Variable Creation | Integers / Floats # # Relevant Documentation # - https://www.w3schools.com/python/python_variables.asp # - https://www.w3schools.com/python/python_variables_names.asp # # All variables created in this section should hold either an integer or float. # # Variables # 1) Create a variable that holds your favorite number. # 2) Create a variable that holds the day of the month of your birthday. # 3) Create a variable that holds a negative number. # 4) Create a variable that holds a floating (decimal) point number. # # Print # 5) Print each variable, describing the value you print. # WRITE CODE BELOW fav_num = '1' birth_day = '12' neg_num = '-6' dec_num = '18.3' print('My favorite number is', fav_num) print('The day of the month of my birthday is cool, it\'s', birth_day) print('A negative number is a number below zero, like', neg_num) print('A float is a decimal point number, an example of one would be', dec_num) print() # 1.3 | Overwriting Variables # # Relevant Documentation # - https://www.w3schools.com/python/python_variables.asp # - https://www.w3schools.com/python/python_variables_names.asp # # Variables # 1) Overwrite the variable holding your name, and save a different name to it. # 2) Overwrite the variable holding birthday with the day you think would be best to have a birthday on. # 3) Overwrite the variable holding your favorite number and set it to a number you think is unlucky. # # Print # 4) Print the variables you've overwritten, describing the values you print. # # Example Code #example_name = 'lucia' #print('EXAMPLE: my new name is', example_name) # WRITE CODE BELOW my_name = 'Imani' my_birthday = 'December 24th, 2006' fav_num = '8' print('My new name is', my_name) print('I think the best birthday would be', my_birthday) print('An unlucky number might possibly be', fav_num) print() # 1.4 | Operations # # Relevant Documentation # - https://www.w3schools.com/python/python_variables.asp # - https://www.w3schools.com/python/python_variables_names.asp # # Variables # 1) Create a variable that is the sum of two numbers. # 2) Create a variable that is the product of three numbers. # 3) Create a variable by dividing the previously created sum, with the previously created product. # # 4) Create a variable that is the concatenation of your name and an animal you like (use the variables!) # 5) Create a variable that is an acronym (like 'lol') multiplied by your birth day. # # 6) Create a variable that is difference of itself minus the number you think is unlucky. # 7) Overwrite the lucky variable with the itself squared. # # Print # 7) Print all the new variables you've created along with what the represent # # Example Code example_sum = 11 + 21 #print('EXAMPLE: the sum of 11 and 21 is', example_sum) # WRITE CODE BELOW num1 = 10+10 num2 = 3 * 3 * 2 num3 = 20/18 num4 = 'lyric' + 'panda' num5 = 'ttyl' * 12 num6 = 7 - 7 - 8 num7 = 1**2 print('The sum of 10 and 10 is', num1) print('The product of 3 times 3 times 2 is', num2) print('20 divided by 18 is', num3) print('My name combined with an animal I like, in this case a panda, looks like', num4) print('If you duplicate ttyl 12 times it looks like', num5) print('7 minus 7 minus 8 is', num6) print('1 squared is', num7)
495ad86145d3dfe2fead9d145801d9a0b332481d
conglinh99/maconglinh-fundamentals-c4e13
/Session01/Homework/ex_2.py
84
3.96875
4
#the area of a circle r = int(input("Radius?")) s = r * r * 3.14 print("Area =", s)
057a874eb00bc764080c336ae77147b6ea976727
ToddCombs/Phenomenon
/counting.py
2,195
4.09375
4
# author:ToddCombs # while循环 def exercise_18(): current_number = 1 # 判断current_number是否小于等于5,是则进入循环,否则跳出。 while current_number <= 5: print(current_number) # current_number加一 current_number += 1 prompt = "\nTell me something, and I will repeat it back to you: " # +=这里是将两个字符串拼接成一个但分行打印 prompt += "\nEnter 'quit' to end the program. " # 需要将变量赋值为空字符串,让while循环可供检查,while循环首次执行时需要将message和quit进行比较 message = "" # 只要message的值不等于quit则继续执行循环 while message != 'quit': message = input(prompt) # 判断如果message不等于quit则打印用户输入的内容,相等的话就不打印quit if message != 'quit': print(message) prompt_1 = "\nTell me something, and I will repeat it back to you1111111111: " prompt_1 += "\nEnter 'quit' to end the program11111111. " active = True # 只要active的值为True则继续while循环 while active: message_1 = input(prompt_1) # 判断如果用户输入了quit则将active 赋值为False,导致跳出循环 if message_1 == 'quit': active = False else: print(message_1) prompt_2 = "\nTell me something, and I will repeat it back to you222222222: " prompt_2 += "\nEnter 'quit' to end the program22222222. " # 逻辑更为简单清晰的写法,while True则会一直循环,直到条件满足break跳出 while True: city = input(prompt_2) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!") current_number_1 = 0 while current_number_1 < 10: current_number_1 += 1 # 如果除2余数为0为偶数,则continue继续执行循环,跳过print(current_number_1),如果不能被2整除时则执行print(current_number_1) if current_number_1 % 2 == 0: continue print(current_number_1) exercise_18()
1605ed6239051fb091bd2e4b518b199ff5720036
sureleo/leetcode
/archive/python/math/Sqrt.py
639
3.84375
4
class Solution: # @param x, an integer # @return an integer def sqrt(self, x): if x == 0: return 0 if x == 1: return 1 low = 1 high = x/2 + 1 while low <= high: mid = (low + high) / 2 if mid * mid > x: high = mid - 1 elif mid * mid < x: low = mid + 1 else: return mid return high if __name__ == "__main__": solution = Solution() print solution.sqrt(2) print solution.sqrt(3) print solution.sqrt(5)
a4e75a0d30fdc9f4361112a98deb161b12acbc02
rafamedem00/Session11-12
/Session11Ex3.py
769
4.125
4
#given 3 numbers, determine what kind of triangle you can form with them def triangle(a, b, c): if a >= b and a >= c: max = a min1 = b min2 = c elif b>=a and b>=c: max = b min1 = a min2 = c else: max = c min1 = a min2 = b if min1+min2 > max: print('we can make the traingle') else: print("we can't make the traingle") return if min1==min2==max: print('equilateral') elif min1==min2 or min2==max or min1==max: print('isosceles') else: print('scalene') if max*max == min1*min1+min2*min2: print('right angle') elif max*max > min1*min1+min2*min2: print('obtuse') else: print('acute')
731adf2c02a8247dc5b17ddc4e8af7d5fa52206e
Anaisdg/Class_Resources
/UT_Work/Week_3_Python/dictionary.py
198
3.765625
4
Anais={"Name":"Anais","Hobbies":["Skating","Soccer"], "Wakeup":["Monday", "Tuesday"]} print( f"""My name is {Anais["Name"]}, My hobbies are {Anais["Hobbies"][0]}, I wake up {Anais["Wakeup"][0]}""" )
ce357a243aed911dc0efe9e31b7dc397571cecf2
mohitrathore1807/Python_Codes
/10. Hollow Inverted Right Angle Triangle.py
322
3.96875
4
#!/usr/bin/env python # coding: utf-8 # In[14]: # Program 10 :- Hollow Inverted Right Angle Triangle Star Pattern n = int(input()) for i in range(n+1): for j in range(n+1): if j == 0 or i == 0 or j == (n-i): print("* ", end = "") else: print("", end = " ") print("\r")
598d382a4e9011a7c1b1970103e5f5cf42389561
moisesquintana57/python-exercices
/tema_4_variables/ejer4.py
216
3.9375
4
string=input("Ingrese una cadena de caracteres: ") texto="" for x in range(len(string)): if x != len(string): texto=texto+string[x]+" " else: texto=texto+string[x] print(string) print(texto)
a486309c25ab677832a30facc1456ecb456db0c3
af4ro/ACM_Hackerrank_problem
/Spring17/minimum_spanning_trree.py
590
3.5
4
import queue import collections n ,m = input().split() edges = collections.defaultdict(list) for i in range(int(m)): a,b,c = input().split() edges[int(a)].append((int(c),int(b))) edges[int(b)].append((int(c),int(a))) start = int(input()) total_weight = 0 pq = queue.PriorityQueue() for i in edges[start]: pq.put(i) found = set() found.add(start) while not pq.empty(): temp = pq.get() if temp[1] not in found: found.add(temp[1]) total_weight+=temp[0] for i in edges[temp[1]]: pq.put(i) print(total_weight)
17e534b9dd1307e85b07b78a81893189fa790bdc
navnathsatre/Python-pyCharm
/pySort_2.py
337
3.609375
4
usrList = [9, 1, 8, 2, 7, 3, 6, 4, 5] print("Original List : ", usrList) s_li = sorted(usrList, reverse=True) # NON-INPLACE SORTING print("Sorted List : ", s_li) print("Original List : ", usrList) print("Sorting using inbulit method") usrList.sort(reverse=True) # IN- PLACE SORTING print("Original List : ", usrList)
aedfc8753c984e013012817fd08c9200b494bce3
Ranjit007ai/InterviewBit-String
/string_based_problems/amazing_subarray/solution.py
296
3.609375
4
def amazing_subarray(Arr): l = len(Arr) vowel = ['A','E','I','O','U','a','e','i','o','u'] count = 0 for i in range(0,l): if Arr[i] in vowel : count += (l - i) return count % 10003 # testcase arr = 'ABEC' ans = amazing_subarray(arr) print(ans)
9903266162183149d3a7168c7681d830f1882fe4
JCGit2018/python
/ListComprehension/Task3.py
433
4.46875
4
# Consider a list of words: # Words = [‘Python’, ‘Object’, ‘Oriented’, ‘Language’] # Write a loop to store the first character of each word in a list from the above list. # Update the program to use list comprehension instead. words = ['Python', 'Object', 'Oriented', 'Language'] l = [] for eachName in words: eachName = eachName[0] l.append(eachName) print(l) print([eachName[0] for eachName in words])
e313a7e382eab9180c065aa6cb282b880c38e308
abdelrhman-allam/prog-python-intro
/py4e/mbox.py
382
3.703125
4
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count = 0 confidence = 0 for line in fh: if line.startswith("X-DSPAM-Confidence:") : pos = line.find(":") confidence += float((line[pos+1:len(line)]).strip()) count = count +1 avg = confidence / count print("Average spam confidence: " + str(avg) )
8d6964c6aeab3d64b913a336791bfe64217906d2
demyank88/datastructureAlgorithm
/heap/heapSort/trial.py
2,642
3.921875
4
# class node(): # def __init__(self, v): # self.value = v # self.left = None # def swapping(arr, node): class heap(): def __init__(self): self.arr = [] self.length = 0 def insert(self, v): self.arr.append(v) self.length += 1 crtIdx = self.length - 1 parentIdx = int((crtIdx - 1)/2) # root case if crtIdx == 0: return # checking whether swapping or not # swapping downTop wards while crtIdx != 0 and self.arr[parentIdx] < v: self.arr[parentIdx], self.arr[crtIdx] = self.arr[crtIdx], self.arr[parentIdx] crtIdx = parentIdx parentIdx = int((crtIdx - 1)/2) # heap remove from root as characteristic # def remove(self): crtIdx = 0 self.arr[crtIdx], self.arr[self.length - 1] = self.arr[self.length - 1], self.arr[crtIdx] self.length -= 1 #initialization leftIdx = 2*crtIdx + 1 rightIdx = 2*crtIdx + 2 crtValue = self.arr[crtIdx] leftValue = self.arr[leftIdx] rightValue = self.arr[rightIdx] if self.length == 1: return self.arr elif self.length < 3: if crtValue < leftValue: self.arr[crtIdx], self.arr[leftIdx] = leftValue, crtValue return self.arr # loop of swapping topDown wards while leftValue != None and rightValue != None and (crtValue < leftValue or crtValue < rightValue): if leftValue > rightValue: self.arr[crtIdx], self.arr[leftIdx] = leftValue, crtValue crtIdx = 2*crtIdx + 1 else: self.arr[crtIdx], self.arr[rightIdx] = rightValue, crtValue crtIdx = 2 * crtIdx + 2 leftIdx = 2 * crtIdx + 1 if 2 * crtIdx + 1 < self.length else None rightIdx = 2 * crtIdx + 2 if 2 * crtIdx + 2 < self.length else None crtValue = self.arr[crtIdx] leftValue = self.arr[leftIdx] if leftIdx != None and leftIdx < self.length else None rightValue = self.arr[rightIdx] if rightIdx != None and rightIdx < self.length else None return self.arr def heapSort(arr): h = heap() for e in arr: h.insert(e) for _ in range(len(arr) - 1): arr = h.remove() return arr if __name__ == '__main__': # Driver code to test above arr = [12, 11, 13, 5, 17, 6, 7, 32] arr = heapSort(arr) n = len(arr) print("Sorted array is") for i in range(n): print("%d" % arr[i]), # This code is contributed by Mohit Kumra
e00ccc4dd99c7eee370f7c6217f7194944c604b3
ThiagoDiasV/architecture-patterns-with-python
/Chapter 1/test_equality.py
359
3.609375
4
from dataclasses import dataclass @dataclass(frozen=True) class Name: first_name: str surname: str class Person: def __init__(self, name): self.name = name def test_barry_is_harry(): harry = Person(Name('Harry', 'Percival')) barry = harry barry.name = Name('Barry', 'Percival') assert harry is barry and barry is harry
c43f9cfdcfe58f295b0f793d77c5b93d1b1faee7
kchawla-pi/edx-mit6001-compsci-algo
/midterm_P7_dict_invert.py
2,830
4.75
5
""" Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d. Here are two examples: If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]} If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]} If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]} """ def test_fn(test_cases, fn, printIt=True): from pprint import pprint msg = "\n{}. \nIn: {}, \nReturned: {}, \nExpected: {}" test_results = [msg.format('Passed', test_cases[case_][0], fn(test_cases[case_][0], printIt=False), test_cases[case_][1]) if fn(test_cases[case_][0], printIt=False) == test_cases[case_][1] else msg.format('Change code', test_cases[case_][0], fn(test_cases[case_][0], printIt=False), test_cases[case_][1]) for case_ in test_cases ] if printIt: for test_num_, test_result_ in enumerate(test_results): print('\n', test_num_, test_result_) else: return test_results def dict_invert(d, printIt=False): ''' d: dict Returns an inverted dictionary according to the instructions above ''' new_dict = dict.fromkeys(set(d.values()), list()) for nkey in new_dict: new_dict[nkey] = sorted([k for k,v in d.items() if v == nkey]) return new_dict try: result except NameError: result = None try: printIt except NameError: printIt = True if printIt: print(result) return None else: return result if __name__ == '__main__': test_cases = {1: ({1: 10, 2: 20, 3: 30}, {10: [1], 20: [2], 30: [3]}), 2: ({1: 10, 2: 20, 3: 30, 4: 30}, {10: [1], 20: [2], 30: [3, 4]}), 3: ({4: True, 2: True, 0: True}, {True: [0, 2, 4]}), 4: ({(1, 2): 'a', (2, 3): 'b', (4, 3): 'a'}, {'a': [(1, 2), (4, 3)], 'b': [(2, 3)]}), 5: ({(1, 2): (True, True), (2, 3): (True, False), (3, 4): (False, True), (4, 5): (True, True)}, {(True, True): [(1, 2), (4, 5)], (True, False): [(2 ,3)], (False, True): [(3, 4)]}) } # test_cases = {1: test_cases[1]} test_fn(test_cases=test_cases, fn=dict_invert, printIt=True)
e60dc1be46ecc3d26f58ba28aa74b20f7eb54e1e
ccjoness/CG_StudentWork
/Sheri/Week2/functional/reduce_it.py
442
3.984375
4
# write a function that takes two strings and concatinates them together # call this function "cat". def cat(string1, string2): new_string = string1 + string2 # now write a function that takes a function and a list of strings and applies # the cat function to each element in the list and returns the resulting string def resulting_string(func, listostrings): for i in listostrings: func(i) resulting_string(cat(["dog", ])
d98ae1d650487c2ea5a75aacfb2154d0201f358a
Yosoyfr/Python-Basico
/Clase 4/identacion.py
464
4
4
# IDENTACION EN PYTHON # Python usa sangría o identacion para indicar un bloque de código # Bloque 1 if 5 > 2: # Bloque 1 adentro del bloque 1 print("5 es mayor a 2") # Bloque 2 adentro del bloque 1 if 3 < 2: # Bloque 1 adentro del bloque 2 del bloque 1 print("Hola desde el bloque 1 del bloque 2 del bloque 1") # Bloque 3 adentro del bloque 1 print("Hola desde el bloque 2 del bloque 1") # Bloque 2 print("Bloque 2")
800a8fa6f5517ee06b9717a140279ab34821f04e
vschule/adventcode
/adv_2017/day1_inversecaptcha.py
1,710
3.765625
4
import pytest # The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that # match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the # list. def first(str_number): """ :param str_number: str :return int """ last = str_number[-1] result = 0 for char in str_number: if char == last: result += int(char) last = char return result # Now, instead of considering the next digit, it wants you to consider the digit halfway around the circular list. # That is, if your list contains 10 items, only include a digit in your sum if the digit 10/2 = 5 steps forward # matches it. Fortunately, your list has an even number of elements. def second(str_number): """ :param str_number: str :return int """ list_number = list(str_number) total = list_number.__len__() half = total/2 result = 0 for key, x in enumerate(list_number): index_y = int((key + half) % total) if x == list_number[index_y]: result += int(x) return result def test_first(): assert first("1122") == 3 assert first("1111") == 4 assert first("1234") == 0 assert first("91212129") == 9 def test_second(): assert second("1212") == 6 assert second("1221") == 0 assert second("123425") == 4 assert second("123123") == 12 assert second("12131415") == 4 if __name__ == '__main__': test_first() test_second() with open("input_1.txt") as input_file: input_number = input_file.read() print(first(input_number)) print(second(input_number))
964caa33f7722235877c3236fb16df134aa56d60
sriarunaravi/sri
/alphabet.py
117
3.71875
4
s=input() try: b=s.lower() if(ord(b)>=97 and ord(b)<=122): print("Alphabet") except: print("No")