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
0c57c05f14a560af96ed993214eb9bb72637783b
SohyunOh/python
/class_0317.py
7,050
3.5625
4
# accountBook ="shose 03/02 59000, coffee 03/03 2500, food 03/04 7000, dress 03/13 130000" # #공백과 콤마 로 구분되어있고 품목과 날짜,가격으로 나열 # replaceAB = accountBook.split(',')# ',' 기준으로 리스트 로 저장 # k=0 # for i in replaceAB: # replaceAB[k] = i.lstrip(',')#각 문자열의 왼쪽 공백 삭제 후 저장(_coffee,_food,_dress) # k+=1 # kk='$ ' #' $' 뒤로 표시 # print('item'.ljust(10),end="") # print('date'.ljust(10),end="") # print('$(price)'.ljust(10)) # for i in range(len(replaceAB)): # z= replaceAB[i].split() #공백을 기분으로 리스트로 저장 # for k in range(len(z)): # if k ==0: # print(z[k].ljust(10), end="")#10칸 확보 후 왼쪽 출력 # elif k ==1: # print(z[k].ljust(10), end="")#10칸 확보 후 왼쪽 출력 # elif k ==2: # print("{:,}".format(int(z[k])).join(kk).ljust(10)) #=========================================================================================== # ======판단만 하는 함수 = True ot False 판단 ==== # Str = 'python te12st 1324' # print("Str .isdigit(): ", Str.isdigit()) #숫자로만 구성 # print("Str[9:11] .isdigit(): ", Str[9:11].isdigit())# 숫자로만 구성 # print("Str .isalpha(): ", Str.isalpha())#글자 # print("Str[:6] .isalpha(): ", Str[:6].isalpha())#글자 # print("Str .isalnum(): ", Str.isalnum())#글자+숫자 # print("Str[7:13].isalnum():",Str[7:13].isalnum()) #글자+숫자 # print("Str.islower():",Str.islower())#소문자 # print("Str.isupper():",Str.isupper())#대문자 # print("Str.isspace():",Str.isspace())#공백 # ========================================================================================= # # 문자구성요소 파악 함수, 리플레이스, 하이픈을 기준으로 왼쪽 오른쪽 검사할수있도록 파인드 # info = """ # jo 9abc08-302023 # cho 900402-1011232 # test 1234567-1234567 # lee 980908-3a2c0c3 # kim 900514-2022023 # """ # print(info) # k=0 # for i in range(info.count('-')): # k=info.find('-',k+1) # if info [k+1:k+8].isdigit() and not info[k-7:k].isdigit and info[k-6:k].isdigit(): # info =info.replace() # <풀이>============================================================================ # info = """ # jo 9abc08-302023 # cho 900402-1011232 # test 1234567-1234567 # lee 980908-3a2c0c3 # kim 900514-2022023 # """ # print(info) # k=0 # for i in range(info.count('-')): #'-'로 반복문 횟수 결정 # k=info.find ('-',k+1) #find로 팢고 찾은 다음 K+1로 다음 걸 또 찾는다. ##여러 행의 문자열이지만 인덱스 값은 계속 연속적이기 때문. # if info [k+1:k+8].isdigit() and not info[k-7:k].isdigit() and info[k-6:k].isdigit(): ## '-'을 기준으로 뒷 7자리가 숫자로만 되어있는지, 7자리(6자리도 있음)가 숫자로만 이루어지 말아야함. ##다시 6자리만 숫자로 이루어져있는지. # info =info.replace(info[k+1:k+8],'*******') #6가지 조건을 만족하는 값만 '-'을 기준으로 7자리 *로 출력 # print(info) # ================================================================================================= # 함수 - 어떤 이름을 가진 코드가 구체적으로 어떻게 동작하는지 구체적으로 기술하는 것 # 파이선에서는 함수나 메소드를 정의할때 definition를 두인 키워드인 'def'를 사용_사용자 정의 함수 # 내장 함수 (컴파일에 내용 포함),외장함수 (사용자 모듈함수로 사용할때 마다 불러오기 예)decopy 활용) # result,temp = 0,0 # result = int (input("수 입력 : ")) # while True: # temp = int(result%10) #임시변수에 나머지 값 # result= int (result/10) #나머지에 몫값만 # print(temp,end="") # if not result: break; # #result 0이 되면 부정을 시키면 참가 , 남아 있지 않으면 거짓 -거짓이여서 break실핼하지 않고 반복 # print("\n 프로그램 종료") # 여러(5)개 입력할경우 # result,temp = 0,0 # for i in range (5): # result = int (input("수 입력 : ")) # while True: # temp = int(result%10) # result= int (result/10) # print(temp,end="") # if not result: break; # print("\n 프로그램 종료") # =========================================================================== # 꺼구로 함수 정의함 # def reverseCode(): # result,temp = 0,0 # result = int (input("수 입력 : ")) # while True: # temp = int(result%10) # result= int (result/10) # print(temp,end="") # if not result: break; # print() # print("프로그램시작") # reverseCode() # print("\n 프로그램 종료") # ================================================================================ # #*** # def sel_machine():#변수와 규칙이 같음, 숫자가 앞으로 올수없음. 앞에'_',한글 사용가능 /공백,특수문자안됨 # sel =0 # sel =int (input("음료 선택\n1.골라\n2.핫6\n3.포카리\n입력:")) # if sel ==1 : print('콜라등장') # if sel ==2 : print('핫6등장') # if sel ==3 : print('포카리등장') # else : print('만들어 드세요^^') # if sel >= 1 and sel<=3: # print("맛있게 드세요^^") # sel_machine() # ======================================================================== # 예제 # def calc(): # result =0 # su1,op,su2 = int(input("숫자 :")),input("부호:"),int(input("숫자:")) # result = su1+su2 # print(su1,'+',su2,'=',result) # calc() # +,-,*,/연산식 만들기 # def calc(): # result =0 # su1,op,su2 = int(input("숫자 :")),input("부호:"),int(input("숫자:")) # if op == '+': result = su1+su2 # elif op == '-': result = su1-su2 # elif op == '*': result = su1*su2 # elif op == '/': result = su1/su2 # print("%d%s%d=%.2f"% (su1,op,su2,result)) # calc() # =============================================================================== # def calc(su1,op,su2 ):#매개변수에서 인수 전달받음 / 지역변수 (종속된곳에서 사용되고 소멸) # result =0 #초기화 연산이 이루어질걸 알수있음 # result = su1+su2 #연산자 부호는 활용이 안됨. # print('calc 실행') # return result # 되돌려 받는 값 상수를 지정하면 매번 상수지정되어 출력 됨. # su1,op,su2 = int(input("숫자 :")),input("부호:"),int(input("숫자:")) # result =calc(su1,op,su2) # print(su1,'+',su2,'=',result) #전역변수 프로그램시작할때 부터 메모리 할당된 변수가 그대로 보존됨. # print("다음문장") # # ================================================================================= # def showAvrg(a,b,c): # print("{}와{}의 평균".format(a,b)) # print("값은{}입니다.".format(round(c,1))) #반올림 함수에 소수 첫째 자리 짤라씀 # def avrg(j,k): # total= j+k; # f= total/2 # return f; # i=2; j=3; # f=avrg(i,j) # showAvrg(i,j,f) # print()
be031aef18c5a55bca0c5ee076a8e85b8fe8f550
Hk4Fun/algorithm_offer
/leetcode/array/medium/16. 3Sum Closest.py
2,753
3.96875
4
__author__ = 'Hk4Fun' __date__ = '2018/4/8 18:36' '''题目描述: Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). ''' '''主要思路: 时间O(n^2),空间O(1) 这题就在3sum的基础上改一改:既然求的是离target最近的和, 那么每次求和时若和与target的绝对值更小就更新为该和即可,等于时直接就是target了 这题其实更简单,不用跳过重复值,不影响求离target最近的和 ''' class Solution: def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() res = nums[0] + nums[1] + nums[2] for i in range(len(nums) - 2): l, r = i + 1, len(nums) - 1 while l < r: s = nums[i] + nums[l] + nums[r] if abs(target - s) < abs(target - res): res = s if s > target: r -= 1 elif s < target: l += 1 else: return res # 提前退出,就是target return res # ================================测试代码================================ from Test import Test class MyTest(Test): def my_test_code(self): self.debug = False # debug为True时每个测试用例只测试一遍,默认情况下关闭debug模式 self.TEST_NUM = 1 # 单个测试用例的测试次数, 只有在debug为False的情况下生效 testArgs = [] # 只需在此处填写自己的测试代码 # testArgs中每一项是一次测试,每一项由两部分构成 # 第一部分为被测试函数的参数,第二部分只有最后一个,为正确答案 testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) testArgs.append([]) return testArgs def convert(self, result, *func_arg): # 在此处填写转换函数,将测试结果转换成其他形式 return result def checked(self, result, expected, *func_arg): # 在此处填写比较器,测试返回的结果是否正确 return result == expected if __name__ == '__main__': solution = Solution() MyTest(solution=solution).start_test()
1fe450f5b6265a0a4c4789ab063e5e94d0e9f351
alessandraburckhalter/Bootcamp-Exercises
/python101/11-tip-calculator.py
962
4.15625
4
#Task: Write a program that calculates how much of a tip to leave at a restaurant. #Prompt the user for two things: #The total bill amount #The level of service, which can be one of the following: good, fair, or bad #Calculate the tip amount and the total amount (bill amount + tip amount). The tip percentage based on the level of service is based on: #good -> 20% #fair -> 15% #bad -> 10% total = float(input("Total bill amount? ")) level = str(input("""\nLevel of service: good -> 20% fair -> 15% bad -> 10%? """ )).lower() #Calculate the tip tip1 = (total * 20) / 100 tip2 = (total * 15) / 100 tip3 = (total * 10) / 100 if level == "good": print('\nTip amount: $%.2f' %tip1) print('\nTotal amount: $%.2f' %(tip1 + total)) elif level == "fair": print('\nTip amount: $%.2f' %tip2) print('\nTotal amount: $%.2f' %(tip2 + total)) elif level == "bad": print('\nTip amount: $%.2f' %tip3) print('\nTotal amount: $%.2f' %(tip3 + total))
c73b4590ae82a93ae553767f3dc6c87e4a62112e
rayhanzfr/latihan_github
/lat12/lat12-2.py
116
3.671875
4
x=(int(input("Input angka: "))) for i in range(10): hasil=x*(i+1) print("{} x {} = {}".format(x,i+1,hasil))
ba623472a81e0045ed89d7763136ded5fd9a805e
me-here/example_something
/cheesepuff.py
149
3.5
4
def are_you_awesome(s): if s == "awesome": print("You are awesome!") else: print("don't be a cheesepuff") are_you_awesome()
99b9e1ec67af63150a1497a48580913e257aef08
sandrosa1/instrucoes_python
/impar_ou_par.py
242
3.546875
4
def main(): par = 0 impar = 0 n = int(input("dd ")) while ( n != 0): if (n % 2 == 0): par = par + 1 else: impar = impar + 1 n = int(input("dd ")) print(par) print(impar)
2135fa6bbd2ac01f5f362b9e610aeda7cd01af6b
suhasreddy123/python_learning
/Finoramic assignment/powfunction2.py
922
4.28125
4
"""def exponent(x, n): if (n <0): return exponent(1 / x, -n); elif( n == 0 ): return 1; elif (n == 1): return x ; elif( n%2==0): return exponent(x * x, n / 2); else: return x * exponent(x * x, (n - 1) / 2); print(exponent(2,3)%3)""" ############################################################################### """def pow(x,n,d): return ((x**n)%d) print(pow(2,3,3))""" ################################################################### """def calp(x,y,z): t = 1; for j in range (0,y,1): t = (t*(x%z))%z; return t; print(calp(2,3,3)) #Hint : (ab) mod n = ((a mod n) (b mod n)) mod n""" ######################################################## def compute(x,y,z): r = x % z for i in range(y-1): r = r * x r = r % z return r; print(compute(2,3,3)) ###########################################################
b8c093c9af7c9fffa2e247dd9e3088ee325a57d2
caveman0612/python_fundeamentals
/miniprojects/binary_search.py
873
3.953125
4
sorted_list = [1, 3, 3, 4, 7, 7, 7, 9, 10, 10, 10, 10, 10, 11, 11, 12, 13, 15, 15, 16, 16, 17, 17, 18, 19, 21, 21, 21, 21, 21, 22, 25, 27, 28, 28, 29, 31, 33, 34, 35, 37, 39, 40, 41, 42, 43, 44, 45, 46, 48, 48, 48, 49, 49, 50, 51, 51, 51, 52, 52, 52, 53, 53, 53, 53, 54, 54, 57, 58, 59, 61, 62, 62, 62, 64, 66, 69, 71, 73, 74, 76, 81, 83, 85, 85, 87, 88, 88, 89, 90, 90, 92, 95, 95, 95, 96, 97, 99, 99, 99] def binary_Search(target, list): length = len(list) half = int(length/2) pivot = list[half] if length == 1 and pivot != target: return False if pivot == target: return True elif pivot < target: search = binary_Search(target, list[half:]) return search elif pivot > target: search = binary_Search(target, list[:half]) return search search = binary_Search(2, sorted_list) print(search)
0f164e6c407113c670b9160a2e4f082a0f83b82e
remusezequiel/Python
/paso_a_paso/Funciones/fun_anidadas.py
2,286
3.921875
4
""" Forma no anidada """ ########################################## def validacion(num_uno, num_dos): return num_uno > 0 and num_dos > 0 ########################################## ########################################## def division(num_uno, num_dos): if validacion(num_uno, num_dos): return num_uno / num_dos ########################################## """ Forma anidada """ ########################################## def division_anidada(num_uno, num_dos): #Las variables de division anidada son variables utilizables # dentro de las anidadas como si fuesen globales dentro de la funcion def validacion_ani(): return num_uno > 0 and num_dos > 0 if validacion_ani(): return num_uno / num_dos ########################################## """ Funciones Clousure: Son basicamente funciones que crean funciones """ ########################################## def crear_funcion(num_uno,num_dos): def validacion(): return num_uno>0 and num_dos>0 return validacion ########################################## """ Funciones que reciven otras funciones como parametros """ ########################################## def aplicar_funcion(func): result = func()#V o F print(result) ########################################## """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #A partir de aca se ejecutara el programa. """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" print("Forma no anidada") resultado = division(10,5) print(resultado) print("Forma anidada") resultado = division_anidada(10,5) print(resultado) print("Funciones Clousure") nueva_funcion = crear_funcion(10,5) print(nueva_funcion()) print("Funciones aplicadas como parametros") """A aplicar_funcion se la pasa la funcion crear_funcion la cual crea sibre la variable local result de aplicar_funcion una nueva funcion. En particular, como los parametros de crear_funcion pasan primero por la validacion este devolvera true si cumplen con los requicitos de la validacion y si no devolvera false""" print("Llamado de aplicar_funcion de crear_funcion(10,5):") aplicar_funcion(crear_funcion(10,5)) print("Llamado de aplicar_funcion de crear_funcion(10,0):") aplicar_funcion(crear_funcion(10,0))
490e7355115b3a2cd2223ec2420a14f04679d26a
shibinbalan/pythoninterviewpreparation
/Interview Prograams/fibonaci series.py
179
3.90625
4
def fibonaci(n): if n<1: print(n,"Invlid Input") elif n==1: return 0 elif n==2: return 1 else: return fibonaci(n-1) + fibonaci(n-2)
98775bbeea8fdd8db8cd1a8238b01c98c7395b27
Charlesmutua/Python_Virtual_Bootcamp
/Intro to Python And Data Types/Assignment5.py
151
4.46875
4
# 5.Write a python program that checks if a string begins with a capital letter. sentence = input("Enter a sentence: ") print(sentence.isupper())
23044c15636580b54c2ed945b49fa9d010baa4d7
justincruz97/DataStructures-and-Algos
/LinkedLists/reverse_LL.py
811
4.5
4
from LinkedList import * ## reversing a linked list def reverse_linked_list(L): prev = None # this will be assigned as the new next curr = L # this is the node we are reassigning next next = None # this is the next node we wil work on while (curr != None): # store the next value next = curr.next # reassign current.next to previous (reverses) curr.next = prev # set previous to current to work on the next one prev = curr # assign curr to next to work on the next node curr = next return prev LL = Node(1) LL.next = Node(2) LL.next.next = Node(3) LL.next.next.next = Node(4) reversedLL = reverse_linked_list(LL) print(reversedLL) print(reversedLL.next) print(reversedLL.next.next) print(reversedLL.next.next.next) print(reversedLL.next.next.next.next)
5f3bb63d4da44d5438ee1a98fadc8b429a76846d
scorp6969/potential-fiesta
/f.py
205
3.703125
4
patterns = [5, 2, 5, 2, 2] # cheat # for pattern in patterns: # print('x' * pattern) for x_count in patterns: output = '' for count in range(x_count): output += 'x' print(output)
cdfbeb6d8fdb4de686bd9bc1c5b0699d97460440
manh9amazing/Nguyenphumanh-C4T10
/btmoi/HWholiday/bt1.py
333
3.703125
4
b=str(input("mat khau")) d=str(input("nhap lai mat khau")) loop_count= 0 while loop_count<1: if b != d or len(b)<8 or b.isdigit()==True or b.isalpha()==True : print("loi da xay ra") b=str(input("mat khau")) d=str(input("nhap lai mat khau")) else: print("welcome") loop_count+=1
538c72c47f894ce05d1590227ee452fce88c14af
sophialee0628/Basic-Algorithm
/concepts/DoublyLinkedList.py
1,601
4.34375
4
#!/usr/bin python class Node : def __init__(self,data,next=None,prev=None): self.data=data #데이터 저장 self.next=next #링크저장 self.prev=prev def init_list(): global node_A node_A=Node("A") node_B=Node("B") node_D=Node("D") node_E=Node("E") node_A.next=node_B node_B.next=node_D node_B.prev=node_A node_D.next=node_E node_D.prev=node_B def delete_node(del_data): global node_A pre_node =node_A next_node=pre_node.next next_next_node=next_node.next if pre_node.data==del_data: node_A=next_node del pre_node return while next_node: if next_node.data==del_data: next_next_node.next=next_node.next pre_node.next=next_node.next next_next_node.prev=next_node.prev del next_node break pre_node=next_node next_node=next_node.next def insert_node(data): global node_A new_node=Node(data) node_P=node_A node_T=node_A while node_T.data <=data: node_P=node_T node_T=node_T.next new_node.next=node_T node_P.next=new_node new_node.prev=node_P node_T.prev=new_node def print_list(): global node_A node=node_A while node: print(node.data) node=node.next print if __name__=='__main__': print("After initializing the Linked List") init_list() print_list() print("After inserting node C") insert_node("C") print_list() print("Deleting the node D") delete_node("D") print_list()
58b08753ce61d2b577e09b91743af33f6728465d
DiWuDi/LeetCode_Python
/67_addBinary.py
778
3.734375
4
"""Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0.""" class Solution: def addBinary(self, a: str, b: str) -> str: result, carry, val = "", 0, 0 for i in range(max(len(a), len(b))): val = carry # collect carry from last loop if i < len(a): val += int(a[-(i+1)]) #start from the last digit if i < len(b): val += int(b[-(i+1)]) carry, val = val // 2, val % 2 result += str(val) if carry: result += str(1) return result[:: -1] #return it reversely test = Solution() a = "1010" b = "1010" print(test.addBinary(a,b))
42056be9acac1b4eceaa185f451710bdece41fec
theodao/nanodegree-algorithm-datastructures
/Chapter3/sorting_algorithm/bubble_sort.py
268
4.0625
4
def bubble_sort(array): for i in range(len(array)): for j in range(len(array) - 1 - i): if array[j] > array[j + 1]: temp = array[j + 1] array[j + 1] = array[j] array[j] = temp return array print(bubble_sort([64,25,12,22,11]))
c04ea4a8fe81fe4ea4a926c25cf953d304bd0211
3367472/Python_20180421
/Chapter.5/5.6.b.py
180
3.65625
4
# encoding: utf-8 boys = ['chris', 'arnold', 'bob'] print boys girls = ['alice', 'bernice', 'clarice'] print girls print [b + '+' + g for b in boys for g in girls if b[0] == g[0]]
06708bfc8976dc16d87bc343853afffdf3fe734c
A-DBN/Maths_2019
/Borwein_2019/110borwein
2,279
3.6875
4
#!/usr/bin/python3 from math import * import sys def prompt(nb1, nb2, option): if (option == 1): print("Midpoint:") print("I" + sys.argv[1] + " = %.10f\ndiff = %.10f\n" % (nb1, nb2)) elif (option == 2): print("Trapezoidal:") print("I" + sys.argv[1] + " = %.10f\ndiff = %.10f\n" % (nb1, nb2)) else: print("Simpson:") print("I" + sys.argv[1] + " = %.10f\ndiff = %.10f" % (nb1, nb2)) def fonction(x, n): a = 0 n = float(n) result = 1 while a <= n: if x != 0: result *= sin(x / ((2 * a) + 1)) / (x / ((2 * a) + 1)) a += 1 return result def check_int(): ac = len(sys.argv) i = 1 j = 1 while i < ac: try: int(sys.argv[i]) except ValueError: return 84 i += 1 if j == 1: return 0 else: return 84 def rectangles(n): counter = 0 result = 0.0 h = 5000.0 / 10000.0 while counter <= 10000 - 1: x = counter * h result += fonction(x, n) counter = counter + 1 result = result * h diff = result - (pi/2) prompt(result, diff, 1) def trapezoidal(n): counter = 1 result = 0.0 h = 5000.0 / 10000.0 while counter < 10000: result += fonction(counter * h, n) counter += 1 result = 0.25 * (fonction(0, n) + fonction(5000, n) + 2 * result) diff = result - (pi/2) prompt(result, -1 * diff, 2) def simpson(n): c = 1 r1 = 0.0 h = 5000.0 / 10000.0 while c < 10000: r1 = r1 + fonction(c * h, n) c = c + 1 r2 = 0.0 c = 0 while c < 10000: r2 = r2 + fonction(c * h + (h * 0.5), n) c = c + 1 result = 5000.0 / 60000.0 * (fonction(0, n) + fonction(5000, n) + 2 * r1 + 4 * r2) diff = result - (pi/2) prompt(result, -1 * diff, 3) if __name__=="__main__": if len(sys.argv) != 2: exit(84) if sys.argv[1] != "-h" and check_int() == 84: exit(84) if sys.argv[1] == "-h": print("USAGE\n ./110borwein n\n\nDESCRIPTION\n n constant defining the integral to be computed\n") if int(sys.argv[1]) < 0: exit(84) rectangles(sys.argv[1]) trapezoidal(sys.argv[1]) simpson(sys.argv[1])
7f2187bfb11270a04420ab3457183a80c3510f70
VGovindarajan/python_play
/algorithms/sieve_of_eratosthenes.py
924
3.65625
4
# From CTCI. # Vijayarajan Govindarajan 2018 def get_prime_numbers_upto(number): sieve = [] sieve.insert(0,False) sieve.insert(1,False) for i in range(2, number): sieve.insert(i,True) prime = 2 while (prime < len(sieve)): sieve = remove_non_primes(prime, sieve) prime = get_next_prime(prime, sieve) print(prime) return sieve def remove_non_primes(prime, sieve): for i in range(prime*prime, len(sieve), prime): #print(prime, i) sieve[i] = False #print(sieve) return sieve def get_next_prime(prime, sieve): next_prime = prime + 1 while (len(sieve) > next_prime and (not sieve[next_prime])): next_prime = next_prime + 1 return next_prime def main(): sieve = get_prime_numbers_upto(10000000) #print(sieve) for i in range(2,len(sieve)): if sieve[i]: print(i) if __name__ == "__main__": main()
20cc3b77e689d0e3cd0afa3b8281b41e61db6833
JustProsa/Python-Exercises
/M1/005-again-unit-time/005-againUnitsOfTime.py
1,012
4.4375
4
# In this exercise you will reverse the process described in Exercise 24. # Develop a program that begins by reading a number of seconds from the user. # Then your program should display the equivalent amount of time in the form # D:HH:MM:SS, where D, HH, MM, and SS represent days, hours, minutes and seconds respectively. # The hours, minutes and seconds should all be formatted so that they occupy exactly two digits. # Use your research skills determine what additional character needs to be included in the format # specifier so that leading zeros are used instead of leading spaces when a number is formatted # to a particular width. print("\nSTART PROGRAM") print("------------------") print("\nDays") days = int(input()) print("\nHours") hours = int(input()) print("\nMinutes") minutes = int(input()) print("\nSeconds") seconds = int(input()) print("\nTime...") # print(str(days)+":"+str(hours)+":"+str(minutes)+":"+str(seconds)) print("{:02d}:{:02d}:{:02d}:{:02d}".format(days, hours, minutes, seconds))
558596d27c6e57a2c365306d4829c762eb8b5b16
BeataOstrowska/WD
/Zajecia20.04.2020/zadanie4.py
490
3.625
4
class Point: counter = [] def __init__(self, x=0, y=0): """Konstruktor punktu.""" self.x = x self.y = y def update(self, n): self.counter.append(n) p1 = Point(0,0) p2 = Point(1,1) p3= Point(3,15) p4 = Point(4,1) p5 = Point (7,3) print(p1.counter) print(p2.counter) p1.update(1) print(p1.counter) print(p2.counter) #print(p3.counter=3) tak nie można print(p4.counter) p3.update(7) print(p4.counter) print(p3.counter)
21e130d4b65321a32b6d017d570ee48442eb1de3
MrHamdulay/csc3-capstone
/examples/data/Assignment_1/mtledn001/question2.py
357
3.96875
4
#MTLEDN001 Sewagodimo Matlapeng #Assignment 1 question 2 #Computer Sciences 1015F # 25 February 2014 hour,minute,second = eval(input("Enter the hours:\n")),eval(input("Enter the minutes:\n")),eval(input("Enter the seconds:\n")) if(0<=hour<=23 and 0<=minute<=60 and 0<=second<=60): print("Your time is valid.") else: print("Your time is invalid.")
9b63157f7c82dbfe3f6e1442f0610d30b4d5445c
hvn2001/LearnPython
/Scratch/Functions/Lambda.py
357
3.84375
4
# def triple(num): return num * 3 # Assigning the lambda to a variable triple = lambda num: num * 3 print(triple(10)) # Calling the lambda and giving it a parameter def concat_strings(a, b, c): return a[0] + b[0] + c[0] print(concat_strings("World", "Wide", "Web")) def my_lambda(num): return "High" if num > 50 else "Low" print(my_lambda(60))
1f7f7c44a2f77797b8a0995f3f05480364189159
tinnan/python_challenge
/06_itertools/053_compress_the_string.py
302
3.953125
4
""" You are given a string S. Suppose a character 'c' occurs consecutively X times in the string. Replace these consecutive occurrences of the character 'x' with (X, c) in the string. """ from itertools import groupby print(' '.join(['({}, {})'.format(len(list(g)), k) for k, g in groupby(input())]))
600c682d2cf139bcff184b9cc0a3c33d266a5978
DISAN2010/Python
/Supermarket.py
2,627
3.703125
4
import re def items_removed(total_bill, items_present, bill, total): try: with open(total_bill, "r") as FH: all_lines = FH.read() print("\nBill in the Supermarket:\n") print(all_lines) with open(items_present, "r") as FH: list_of_items = [] list_of_items_removed = [] print("\nWhatsApp message with the list of items already present at home\n") for items in FH: parts = items.split("\n") product = parts[0] print(product) list_of_items.append(product) for item in list_of_items: for key in list(bill.keys()): if key == item: removed_items = bill.pop(key) list_of_items_removed.append(removed_items) list_of_items_removed = [int(i) for i in list_of_items_removed] print("\nTotal amount of the bill :", total) Total_Saved = sum(list_of_items_removed) print("Amount of money Sunita and her husband saved for themselves :", Total_Saved) Total_Payed = int(total) - Total_Saved print("Total amount payed : ", Total_Payed) except IOError: print("Could not open file") except: print("Oops") def bill(file): try: with open(file, "r") as FH: bill = dict() for line in FH: if not line.strip() or line.startswith("#") or line.startswith("=") or line.startswith("Sl"): continue else: parts = re.split(': |[.]|\n', line) if line.startswith("TOTAL"): items = parts[0].strip() price = parts[1].strip() total = price else: items = parts[1].strip() price = parts[2].strip() bill[items] = price return bill, total except IOError: print("Could not open file") except: print("Oops") def get_file(): file = input("File to open : ") file = file + ".txt" return file def main(): Total_Bill = get_file() Bill, Total = bill(Total_Bill) Items_Present = get_file() items_removed(Total_Bill, Items_Present, Bill, Total) #Main starts from here main()
ed624f759b20604ce7120a166ab647627ca5c16f
coderkearns/school
/math/v2/conic_sections.py
2,674
3.828125
4
#!/usr/bin/env python3 doc = """ ## Conic Sections All circles, ellipses, hyperbolas, and parabolas are conic sections. They all share the same equation, so it can be difficult to tell the apart. We use discriminants to tell the apart from one another. ### Equation of a Conic Section The equation for a conic section is: ``` Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0 ``` where `A`, `B`, and `C` are not all 0. ### Discriminants The discriminant of a conic section (using the above formula) can be calculated by using: ``` d = B^2 - 4AC ``` From there, you can tell the type of conic section using this table: | Conic Section | Discriminant | | ------------- | ------------ | | Parabola | `d = 0` | | Hyperbola | `d > 0` | | Circle | `d < 0, B = 0, A = C` | | Ellipse | `d < 0, B != 0` | | Ellipse | `d < 0, A != 0, C != 0, A != C` | ### Class Info `::__init__(A, B, C, D, E, F)` <br/> Create a new ConicSection. <br/> A, B, C, D, E, and F are the same as in the equation. `::discrimiant` <br/> A property, which calulates the discrimiant. <br/> It uses `B^2 - 4AC` `::type` <br/> Get the type of Conic Section. <br/> It uses the table listed above, and return the class for that type of conic section. """ __doc__ = doc from util import newerror ConicSectionException = newerror("ConicSectionException") from parabola import Parabola from hyperbola import Hyperbola from circle import Circle from ellipse import Ellipse class ConicSection(): __doc__ = doc def __init__(self, A, B, C, D, E, F): if (A == 0 and B == 0 and C == 0): raise ConicSectionException("A, B, and C cannot all be 0") self.A = A self.B = B self.C = C self.D = D self.E = E self.F = F @property def discriminant(self): return (self.B**2) - (4 * self.A * self.C) @property def type(self): d = self.discriminant if d == 0: return Parabola if d > 0: return Hyperbola if d < 0: if (self.B == 0 and self.A == self.C): return Circle if (self.B != 0): return Ellipse if (self.A != 0 and self.C != 0 and self.A != self.C): return Ellipse raise ConicSectionException("Not a Parabola, Hyperbola, Circle, or Ellipse") def main(A, B, C, D, E, F): conic_section = ConicSection(A, B, C, D, E, F) print(conic_section.type.__name__) if __name__ == '__main__': from util import get_vars print("Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0") main(**get_vars({ "A": float, "B": float, "C": float, "D": float, "E": float, "F": float, }))
1dccd88763731825aa247fca6851630d23c490fc
meenal-shree/Analysis-of-Suicide-Cases-in-India
/suicide-analysis.py
7,463
3.65625
4
from pyspark.sql import SparkSession spark = SparkSession.builder.enableHiveSupport().getOrCreate() spark.sparkContext.setLogLevel('ERROR') spark.sql("use indiaDB") data = spark.sql("select * from suicides") print("\n--------------0.Verifying the data from Hive Table--------------") data.show(20,False) data.createOrReplaceTempView("suicides") from pyspark.sql.functions import sum,col,min,max print("--------------1.List of States in the Dataset--------------") spark.sql("select distinct(state) as STATES from suicides order by STATES").show(40,False) print("--------------2.Total Cases according to the Year--------------") query1 = spark.sql("select type_code, year, sum(case_count) as Total from suicides where group by type_code,year order by year").filter(col("type_code")=="Means_adopted").drop("type_code") query1.show(40,False) print("--------------3.Percentage of increase in suicides between 2001 and 2012--------------\n") maxVal = query1.select(max("Total")).collect()[0][0] minVal = query1.select(min("Total")).collect()[0][0] print("Average increase: " + str((float(maxVal)-float(minVal))/float(minVal)*100)) print("\n--------------4.Cases every year gender wise with %share of both gender--------------") maleData = data.filter((data.type_code == "Means_adopted") & (data.gender == "Male")).groupBy("year","gender").agg(sum("case_count").alias("Male")).orderBy("year").drop("gender") femaleData = data.filter((data.type_code == "Means_adopted") & (data.gender == "Female")).groupBy("year","gender").agg(sum("case_count").alias("Female")).orderBy("year").drop("gender") genderData = maleData.join(femaleData,"year") genderData.withColumn("Male %", col("Male")/(col("Male")+col("Female"))*100).withColumn("Female %" ,col("Female")/(col("Male")+col("Female"))*100).show() print("--------------5.Causes for suicide in descending order of total of cases--------------") data.filter(data.type_code == "Causes").groupBy("type").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(50,False) print("--------------6.Causes for suicide based on age groups in descending order of total cases--------------") data.filter(data.type_code == "Causes").groupBy("type","age_group").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(200,False) print("--------------7.Total cases categorised under cause of suicide gender wise--------------") maleData = data.filter((data.type_code == "Causes") & (data.gender == "Male")).groupBy("type").agg(sum("case_count").alias("Male")).orderBy(col("Male").desc()) femaleData = data.filter((data.type_code == "Causes") & (data.gender == "Female")).groupBy("type").agg(sum("case_count").alias("Female")).orderBy(col("Female").desc()) genderData = maleData.join(femaleData,"type") genderData.show(50,False) print("--------------8.Total cases categorised under cause of suicide of specific age group--------------") data.filter((data.type_code == "Causes") & (data.age_group == "15-29")).groupBy("type").agg(sum("case_count").alias("Age 15-29")).orderBy(col("Age 15-29").desc()).show(20,False) print("--------------9.Total cases categorised under professional profile of the people who committed suicide--------------") data.filter(data.type_code == "Professional_Profile").groupBy("type").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(50,False) print("--------------10.Total cases categorised under method adopted for suicide--------------") data.filter(data.type_code == "Means_adopted").groupBy("type").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(50,False) print("--------------11.Total cases categorised under state--------------") data.filter(data.type_code == "Means_adopted").groupBy("state").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(50,False) print("--------------12.Cases on the causes of suicide for Maharashtra--------------") data.filter((data.type_code == "Causes") & (data.state == "Maharashtra")).groupBy("state","type").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).drop("state").show(50,False) print("--------------13.Cases on the education status of the people committed suicide--------------") data.filter(data.type_code == "Education_Status").groupBy("type").agg(sum("case_count").alias("Total_Cases")).orderBy(col("Total_Cases").desc()).show(50,False) print("\n--------------14.Creating Partitions based on state and type_code--------------\n") spark.sparkContext.setLogLevel('INFO') data.write.option("header",True).partitionBy("state","type_code").mode("overwrite").csv("/suicideData") spark.sparkContext.setLogLevel('ERROR') print("\n--------------15.Reading data from partition and comparing two states based on cause for suicide--------------") MHData = spark.read.options(header='True', inferSchema='True').csv("/suicideData/state=Maharashtra/type_code=Causes/").withColumnRenamed("case_count", "MH Cases") WBData = spark.read.options(header='True', inferSchema='True').csv("/suicideData/state=West Bengal/type_code=Causes/").withColumnRenamed("case_count", "WB Cases") outData = MHData.join(WBData,['year','type','gender','age_group']) outData.groupBy('type').agg(sum("MH Cases").alias("Cases in Maharashtra"), sum("WB Cases").alias("Cases in West Bengal")).orderBy(col("Cases in Maharashtra").desc(),col("Cases in West Bengal").desc()).withColumnRenamed("type","Causes for Suicide").show(50,False) print("--------------16.Reading data from partition and comparing two states based on method adopted for suicide--------------") WBData = spark.read.options(header='True', inferSchema='True').csv("/suicideData/state=West Bengal/type_code=Means_adopted/").withColumnRenamed("case_count", "WB Cases") MHData = spark.read.options(header='True', inferSchema='True').csv("/suicideData/state=Maharashtra/type_code=Means_adopted/").withColumnRenamed("case_count", "MH Cases") outData = MHData.join(WBData,['year','type','gender','age_group']) outData.groupBy('type').agg(sum("MH Cases").alias("Cases in Maharashtra"), sum("WB Cases").alias("Cases in West Bengal")).orderBy(col("Cases in Maharashtra").desc(),col("Cases in West Bengal").desc()).withColumnRenamed("type","Means Adopted for Suicide").show(50,False) print("--------------17.Trend of a particular cause between the timeframe along with percentage contribution--------------") totalValue = data.filter(data.type == "Drug Abuse/Addiction").groupBy("year").agg(sum("case_count").alias("TC")).agg(sum("TC")).collect()[0][0] data.filter(data.type == "Drug Abuse/Addiction").groupBy("year").agg(sum("case_count").alias("TC")).orderBy("year").withColumn("% Share of Total (" +str(totalValue)+ ")",(col("TC")/totalValue)*100).withColumnRenamed("TC", "Drug Abuse/Addiction Cases").show(50,False) print("--------------18.Division of suicide cases in various age groups for Students--------------") data.filter((data.type == "Student")).groupBy("type","age_group").agg(sum("case_count").alias("Student Cases")).orderBy(col("age_group").desc()).drop("type").show(20,False) print("--------------19.Division of suicide cases in various age groups for Failure in Examination--------------") data.filter((data.type == "Failure in Examination")).groupBy("type","age_group").agg(sum("case_count").alias("Student Cases")).orderBy(col("age_group").desc()).drop("type").show(20,False)
f699e91570c0c090d46a1a35bb8f20a070120c87
aashaanX/learn
/python/geeks/sorting/quickSort.py
669
3.96875
4
# this element takes last element as pivot,places # the pivot element at its correct position in sorted # array, and places all smaller (smaller then pivot) # to the left of the pivot and all greater elements to right # of pivot def partition(arr,low,high): i = low -1 #index of smaller element pivot = arr[high] # pivot for j in range(low,high): if arr[j] <=pivot: i = i+1 arr[i],arr[j] = arr[j],arr[i] arr[i+1],arr[high] = arr[high],arr[i+1] return(i+1) def quickSort(arr,low,high): if (low<high): pi = partition(arr,low,high) quickSort(arr,low,pi-1) quickSort(arr,pi+1,high) arr = [10,2,5,8,4,6,1] quickSort(arr,0,len(arr)-1) print(arr)
09a565541c73d1f52db93eef16a6d74eed1bc10c
safwanc/python-sandbox
/algorithms/consecutive_groups.py
287
3.546875
4
def get_consecutive_groups(iterable): s = tuple(iterable) for size in range(1, len(s) + 1): for index in range(len(s) + 1 - size): yield iterable[index:index+size] print(list(get_consecutive_groups('abcde'))) print(list(get_consecutive_groups([1, 2, 3, 4])))
b21f15c863784ec632408aca2843a4541cc82356
RDCLder/DC_November_2018_Cohort
/Week_1/11-15-18/function_exercises.py
1,796
3.90625
4
# 1. Hello def sayHello(name): return f"Hello, {name}!" # 2. y = x + 1 import matplotlib.pyplot as plt def f1(x): return x + 1 x1 = list(range(-3, 4)) y1 = [f1(x) for x in x1] plot1 = plt.plot(x1, y1) plt.title('X + 1') plt.show(plot1) # 3. Square of x def f2(x): return x ** 2 x2 = list(range(-100, 101)) y2 = [f2(x) for x in x2] plot2 = plt.plot(x2, y2) plt.title('Square of x') plt.show(plot2) # 4. Odd or Even def f3(x): if x % 2 == 0: return -1 elif x % 2 != 0: return 1 x3 = list(range(-5, 6)) y3 = [f3(x) for x in x3] plot3 = plt.bar(x3, y3) plt.title('Odd vs. Even') plt.show(plot3) # 5. Sine from math import sin def f4(x): return sin(x) x4 = list(range(-5, 6)) y4 = [f4(x) for x in x4] plot4 = plt.plot(x4, y4) plt.title('Sine Transformation 1') plt.show(plot4) # 6. Sine 2 from numpy import arange x5 = arange(-5, 5.1, 0.1) y5 = [f4(x) for x in x5] plot5 = plt.plot(x5, y5) plt.title('Sine Transformation 2') plt.show(plot5) # 7. Degree Conversion def c2f(celsius): return celsius * 1.8 + 32 ctemps = arange(-10, 40, 0.5) ftemps = [c2f(celsius) for celsius in ctemps] plot6 = plt.plot(ctemps, ftemps) plt.title('Fahrenheit vs. Celsius') plt.xlabel('Celsius') plt.ylabel('Fahrenheit') plt.show(plot6) # 8. Play Again? def play_again(): ask = input('Do you want to play again (Y/N): ') if ask == 'Y': return True print(play_again()) # 9. Play Again? Again def play_again_again(): ask = ' ' while ask != 'Y' or ask != 'N': ask = input('Do you want to play again (Y/N): ') if ask == 'Y': return True elif ask == 'N': return False else: print('Invalid input.') print(play_again_again())
ee26b19d995163c72f3c817352a48275245ae6cc
aishwat/missionPeace
/graph/floydWarshall.py
838
3.578125
4
INF = float('inf') class Graph: def __init__(self, vertices): self.V = vertices self.graph = [] def floydWarshall(self): dist = [row[:] for row in self.graph] for k in range(self.V): for i in range(self.V): for j in range(self.V): if dist[i][k] != float('inf') and dist[k][j] != float('inf') and \ dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] for i in range(self.V): for j in range(self.V): print(dist[i][j], end="\t") print("\n") g = Graph(4) g.graph = [[0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] # Print the solution g.floydWarshall();
c0d446274aa2210d354f1a798e5a0032713d73b0
LionWar22/Lista_de_exercicios
/ex04.py
1,148
4.25
4
# v = float(input("Velocidade em km/h: ")) # # t = float(input("Tempo em h : ")) # # s = v * t # # print("Distancia de {} Km".format(s)) #Aperfeiçoando o exercicio def calcDistancia(): #Função calcula a distancia v = float(input("Velocidade em km/h: ")) #As variaveis necessarias para o calculo são criadas dentro das funções t = float(input("Tempo em H: ")) print("Distancia: {} Km" .format(v * t)) # A impressão do resultado ocorre dentro da função def calcVelocidade(): #Função calcula a velocidade t = float(input("Tempo em H: ")) s = float(input("Distancia em Km: ")) print("Velocidade: {} km/h".format( s / t )) def calcTempo(): #Função calcula o Tempo v = float(input("Velocidade em km/h: ")) s = float(input("Distancia em Km: ")) print("Tempo: {} H".format( s / v )) opcao = int(input("[1]Calcular Distancia \n[2]Calcular Tempo \n[3]Calcular Velocidade \nDigite sua escolha:")) #Uma variavel armazena a opção do usuario if 1 == opcao: #Verifica qual opção o usuario escolhe e chama a função calcDistancia() elif opcao == 2: calcTempo() else: calcVelocidade()
44a8d726d3307c98bbb5cbfd2712b07480c7648b
jabc1/ProgramLearning
/python/python-Michael/ProcessThreads/multiprocess.py
6,499
3.59375
4
# -*- coding: utf-8 -*- # 多进程(multiprocessing) # Unix/Linux操作系统提供了一个fork()系统调用 # 普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次 # 操作系统自动把当前进程(称为父进程)复制了一份(称为子进程),然后,分别在父进程和子进程内返回。 # 子进程永远返回0,而父进程返回子进程的ID # 子进程只需要调用getppid()就可以拿到父进程的ID # Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程: import os print('Process (%s) start...' % os.getpid()) # Only work on Unix/Linux/Mac pid = os.fork() if pid == 0: print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())) else: print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) # 输出: # Process (876) start... # I (876) just created a child process (877). # I am child process (877) and my parent is 876. # fork调用,一个进程在接到新任务时就可以复制出一个子进程来处理新任务 # 常见的Apache服务器就是由父进程监听端口,每当有新的http请求时,就fork出子进程来处理新的http请求 # multiprocessing # 编写多进程的服务程序,Unix/Linux无疑是正确的选择 # multiprocessing模块就是跨平台版本的多进程模块 # multiprocessing模块提供了一个Process类来代表一个进程对象,下面的例子演示了启动一个子进程并等待其结束: from multiprocessing import Process import os #子进程要执行的代码 def run_proc(name): print('Run child process %s (%s)...' % (name, os.getpid())) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) # 创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例 p = Process(target = run_proc, args = ('test', )) print('Child process will start.') # start()方法启动 p.start() # join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。 p.join() print('Child process end.') # 输出: # Parent process 928. # Process will start. # Run child process test (929)... # Process end. # Pool # 如果要启动大量的子进程,可以用进程池的方式批量创建子进程: from multiprocessing import Pool import os, time, random def long_time_task(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) p = Pool(4) for i in range(5): p.apply_async(long_time_task, args = (i, )) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.') # 输出: # Parent process 669. # Waiting for all subprocesses done... # Run task 0 (671)... # Run task 1 (672)... # Run task 2 (673)... # Run task 3 (674)... # Task 2 runs 0.14 seconds. # Run task 4 (673)... # Task 1 runs 0.27 seconds. # Task 3 runs 0.86 seconds. # Task 0 runs 1.41 seconds. # Task 4 runs 1.91 seconds. # All subprocesses done. # 对Pool对象调用join()方法会等待所有子进程执行完毕 # 调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了 # 请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行 # 因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程 # 这是Pool有意设计的限制,并不是操作系统的限制 # p = Pool(5) 可以同时跑5个进程 # 由于Pool的默认大小是CPU的核数,如果你不幸拥有8核CPU,你要提交至少9个子进程才能看到上面的等待效果 # 子进程 (subprocess) # 很多时候,子进程并不是自身,而是一个外部进程 # 创建子进程后,还需要控制子进程的输入和输出 # subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出 # 如何在Python代码中运行命令nslookup www.python.org import subprocess print('$ nslookup www.python.org') r = subprocess.call(['nslookup', 'www.python.org']) print('Exit code:', r) # 如果子进程还需要输入,则可以通过communicate()方法输入: import subprocess print('$ nslookup') p = subprocess.Popen(['nslookup'], stdin = subprocess.PIPE, stderr = subprocess.PIPE) output, err = p.communicate(b'set q = mx\npython.org\nexit\n) print(output.decode('utf-8')) print('Exit code:', p.returncode) # 等价于:在命令行执行 nslookup # 然后手动输入:set q = mx python.org exit # 进程间通信 # Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据 # 以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据: from multiprocessing import Process, Queue import os, time, random # 写数据进程执行的代码 def write(q): print('Process to write: %s' % os.getpid()) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) # 读数据进程执行的代码 def read(q): print('Process to read: %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue.' % value) if __name__ == '__main__': # 父进程创建Queue,并传给子进程 q = Queue() pw = Process(target = write, args = (q, )) pr = Process(target = read, args = (q, )) # 启动子进程pw, 写入 pw.start() # 启动子进程pr,读取 pr.start() # 等待pw结束 pw.join() # pr进程里是死循环,无法等待其结束,只能强行终止 pr.terminate() # 输出: Process to write: 50563 Put A to queue... Process to read: 50564 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue. # 在Unix/Linux下,multiprocessing模块封装了fork()调用,使我们不需要关注fork()的细节 # 由于Windows没有fork调用,因此,multiprocessing需要“模拟”出fork的效果 # 父进程所有Python对象都必须通过pickle序列化再传到子进程去 # 因此,如果multiprocessing在Windows下调用失败了,要先考虑是不是pickle失败了 ## 要实现跨平台的多进程,可以使用multiprocessing模块 ## 进程间通信是通过Queue、Pipes等实现的
2516a5f3edac451f2d7af8e5232c5ee5102733a7
4wqre/cp2019
/Y5 Practical 1/q3_miles_to_kilometre.py
145
4.21875
4
miles = float(input("Number of miles: ")) kilometres = float(miles * 1.60934) print("Number of kilometres: " + "{0:<10.3f}".format(kilometres))
bd86bf4281fece3d30f3c4378d351cffc05ad5a1
landrea-velez/pyton-45
/medio-avanzado/Ejercicio13.py
473
3.90625
4
# Ejercicio 13: Dada una lista de N números enteros x, calcular su promedio. Mostrar el resultado. n = int(input("Ingresar N: ")) sumador = 0 for c in range(n): x = int(input("Ingresar X: ")) sumador += x print("El promedio es:", sumador / n) lista = [] n = int(input("Ingresar N: ")) for c in range(n): x = int(input("Ingresar X: ")) lista.append(x) sumador = 0 for numero in lista: sumador += numero print("El promedio es:", sumador / len(lista))
f4fe91e5b99dce94860adbfa254768f3f07fec19
lidongsheng90/advences
/chapter01/all_is_object.py
400
3.625
4
#-*- coding:utf-8 -*- __author__ = 'lds' __date__ = '2019/3/25 22:45' def ask(name='boby'): return name class Person: def __init__(self): print ('boby1') def decorator_func(): print ('desc start') return ask my_ask = decorator_func() print (my_ask) print(my_ask('toms')) obj_list = [] obj_list.append(ask) obj_list.append(Person) for item in obj_list: print (item())
aa12445999fc5256ea28eb0a200b967536dee5e0
Rameshtech17/PythonTestCode
/CommandLine.py
181
3.6875
4
import sys a=int(sys.argv[1]) b=int(sys.argv[2]) c=a+b print(c) z=0 x=len(sys.argv) print("Number of argument passed: " ,x) for y in range(1,x): z+=int(sys.argv[y]) print(z)
266e744a6ddf5850fd1c50cf25a17594346e07b0
wanghuafeng/lc
/剑指 Offer/52. 两个链表的第一个公共节点.py
908
3.71875
4
#!-*- coding:utf-8 -*- """ https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/ 如果两个链表没有交点,返回 null. 在返回结果后,两个链表仍须保持原有的结构。 可假定整个链表结构中没有循环。 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 本题与主站 160 题相同:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ h1 = headA h2 = headB while h1 != h2: h1 = h1.next if h1 else headB h2 = h2.next if h2 else headA return h1
18c30cdd84d710bf1aa2579021137e461b261ef7
klprabu/myprojects
/Python/HackerRank/IndroductionSets.py
1,304
4.28125
4
#Task # Now, let's use our knowledge of sets and help Mickey. # Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse. # # Formula used: # # Function Description # # Complete the average function in the editor below. # # average has the following parameters: # # int arr: an array of integers # Returns # # float: the resulting float value rounded to 3 places after the decimal # Input Format # # The first line contains the integer, , the size of . # The second line contains the space-separated integers, . # # Constraints # # 0< N < 100 # # Sample Input # # STDIN Function # ----- -------- # 10 arr[] size N = 10 # 161 182 161 154 176 170 167 171 170 174 arr = [161, 181, ..., 174] # # # Sample Output 169.375 def average(array): # your code goes here if 0 <= len(array) <= 100: v_array = set(array) return round(sum(v_array)/len(v_array),3) if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) result = average(arr) print(result)
6f1dc81409baa5b22efe663068b8d0f2b640a4fa
Karls-Darwin/kreck
/exercise5/ex5b.py
1,007
3.96875
4
def matrixSum(A,B): AplusB=[] for i in range(len(A)): x = [] for j in range(len(A[0])): x+=[A[i][j]+B[i][j]] AplusB+=[x] return AplusB def sizeMatch(A,B): rowsA=len(A) rowsB=len(B) colsA=len(A[0]) colsB=len(B[0]) if rowsA==rowsB and colsA==colsB: return True else: return False def getMatrix(): matrix=[] r=input("Matrix enter values separated by commas: ") while r!="": row=eval(r) rowdata=list(row) matrix.append(rowdata) r=input("Matrix enter values separated by commas: ") print("Matrix B: ") return matrix def printMatrix(matrix): for row in matrix: for value in row: print(value,end=" ") print() def main(): a = getMatrix() b = getMatrix() if sizeMatch(a,b): printMatrix(matrixSum(a,b)) else: print("Error: cannot sum matrices of different sizes") if __name__ == '__main__': main()
6cf3f016cc74d0c1db6a915b040fc8137f9ea7e8
shubhamjain31/Competitive_Coding
/Data_Structure/DS_Using_Python/DeQueue.py
889
4.15625
4
class Dequeue: def __init__(self): self.queue = [] def isEmpty(self): return self.queue == [] def addFront(self, element): self.queue.insert(0, element) def addEnd(self, element): self.queue.append(element) def delFront(self): self.queue.pop(0) def delEnd(self): self.queue.pop() def display(self): for i in self.queue: print(i, end=' ') def size(self): print("\n\nLength of dequeue is {}".format(len(self.queue))) dq = Dequeue() dq.addFront(5) dq.addFront(25) dq.addFront(54) print("Dequeue insertion of elements at front is:") dq.display() print() print("\nDequeue insertion of elements at rear is:") dq.addEnd(19) dq.addEnd(10) dq.display() dq.delFront() print() print("\nDequeue after deleting element at front is:") dq.display() dq.delEnd() print() print("\nDequeue after deleting element at rear is:") dq.display() dq.size()
7db190253817ee9dc92b4a44de65c7daab6625ca
QinDie/wave-3
/Is a number prime.py
200
3.859375
4
from b import primenumber a = int(input('Please Input an Positive Int Number Greater Than One :')) b = primenumber(a) if b: print('is a Prime Number') else: print(' is not a Prime Number')
19fe3540ca175ee990f326bf0733dc7d0b64ce78
zxwtry/OJ
/python/leetcode/P073_SetMatrixZeroes.py
1,274
3.53125
4
#coding=utf-8 ''' url: leetcode.com/problems/set-matrix-zeroes/ @author: zxwtry @email: zxwtry@qq.com @date: 2017年4月17日 @details: Solution: 182ms 36.33% ''' class Solution(object): def setZeroes(self, m): """ :type m: List[List[int]] :rtype: void Do not return anything, modify m in-place instead. """ if m == None or len(m) == 0: return if m[0] == None or len(m[0]) == 0: return rn, cn = len(m), len(m[0]) rs, cs = False, False for ri in range(rn): rs = rs or (m[ri][0] == 0) for ci in range(cn): cs = cs or (m[0][ci] == 0) for ri in range(1, rn): for ci in range(1, cn): if m[ri][ci] == 0: m[0][ci] = 0 m[ri][0] = 0 for ri in range(1, rn): for ci in range(1, cn): if m[0][ci] == 0 or m[ri][0] == 0: m[ri][ci] = 0 if rs: for ri in range(rn): m[ri][0] = 0 if cs: for ci in range(cn): m[0][ci] = 0 if __name__ == "__main__": m = [[1, 2, 3], [0, 4, 5]] Solution().setZeroes(m) print(m)
81d897c3388f61b00630150ba79f5769aa129c99
Peggyliu613/pong_game
/scoreboard.py
768
3.859375
4
from turtle import Turtle class Scoreboard(Turtle): def __init__(self): super().__init__() self.color("white") self.penup() self.goto(0, 240) self.hideturtle() self.player_one_score = 0 self.player_two_score = 0 self.update_score() def update_score(self): self.clear() self.write(f"{self.player_one_score} {self.player_two_score}", align="center", font=("Arial", 50, "normal")) def player_one_get_point(self): self.player_one_score += 1 def player_two_get_point(self): self.player_two_score += 1 def end_game(self): self.color("red") self.goto(0, 0) self.write("Game Over", align="center", font=("Arial", 50, "normal"))
51a641fb1949c05b82915f461040bdf749654fed
Shruthi21/Algorithms-DataStructures
/9_Algo_Kangaroo.py
807
3.6875
4
#!/bin/python import sys def calculate(x1,v1,x2,v2): jump1=1 jump2=1 distance1=x1+v1 distance2=x2+v2 if (x2>x1 and v2>v1) or (x1>x2 and v1>v2): return 'NO' while distance1!= distance2: distance1+= v1 jump1 = jump1+1 distance2+= v2 jump2= jump2+1 if x2>x1 and v1>v2 and distance1>distance2: return 'NO' if x1>x2 and v2>v1 and distance2>distance1: return 'NO' if (x1>x2 or x2>x1 ) and v1==v2: return 'NO' if jump1 == jump2: return 'YES' else: return 'NO' x1,v1,x2,v2 = raw_input().strip().split(' ') x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)] print calculate(x1,v1,x2,v2)
d3286c84e41c0e5a1f33ff470d6bf0f0e6d4e08b
Jcarlos0828/LeetCode-PracticeResults
/invertBinaryT.py
480
3.984375
4
""" EASY 226. Invert Binary Tree Invert a binary tree. Example: Input: 4 / 2 7 / / 1 3 6 9 Output: 4 / 7 2 / / 9 6 3 1 """ from TreeNodeClass import TreeNode class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root == None: return left = self.invertTree(root.left) right = self.invertTree(root.right) root.left, root.right = right, left return root
0e794119293e6215fc995a3bc968044e62216287
abhishek14anandDev/PieCharm
/StringDeepDive.py
152
3.9375
4
str1 = "Learning" str2 = "Python" print(str1[1]) print(str2[2:5]) #fetching the value between the string print(str2[:2] + 'le') #Updating the string
f0c6c8f61cd9e198b671d40d2bafaa9d6f1cf2f9
qmnguyenw/python_py4e
/geeksforgeeks/python/hard/8_7.py
2,675
4.6875
5
Python calendar module : yeardayscalendar() method Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. **yeardayscalendar()** method in Python is used to get the data for specified year. Entries in the week lists are day numbers. Day numbers outside this month are zero. **Syntax:** yeardayscalendar(year, width) **Parameter:** **year:** year of the calendar **width:** _[Default: 3]_ number of months in each row. **Returns:** list of day numbers. **Code #1:** __ __ __ __ __ __ __ # Python program to demonstrate working # of yeardayscalendar() method # importing calendar module import calendar obj = calendar.Calendar() year = 2016 # default value of width is 3 # priting with yeardayscalendar print(obj.yeardayscalendar(year)) --- __ __ **Output:** > [[[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, > 17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31]], [[1, 2, 3, > 4, 5, 6, 7]… > … > [[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, > 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]]] > > > > > > **Code #2:** iterating the list of weeks __ __ __ __ __ __ __ # Python program to demonstrate working # of yeardayscalendar() method # importing calendar module import calendar obj = calendar.Calendar() # iteratign with yeardayscalendar for day in obj.yeardayscalendar(2018, 1): print(day) --- __ __ **Output:** > [[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, > 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 0, 0, 0, 0]]] > [[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, > 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 0, 0, 0, 0]]] > … > [[[0, 0, 0, 0, 0, 1, 2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, > 16], [17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30], [31, 0, 0, > 0, 0, 0, 0]]] Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
dfaa036a9a7566ec87e3182c52c4d3eeea27a319
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/beer-song/d9572d70aa7748578f073a549bf7078e.py
1,032
3.734375
4
def capitaliseFirst(sentence): return sentence[0].upper() + sentence[1:] def getNumberRep(number): if number == 0: return "no more" else: return number def getBottlePlural(number): return "bottle" + "s" * (number != 1) class Beer: verseChunk1 = "{0} {1} of beer on the wall, {0} {1} of beer.\n" verseChunk2 = "Take {2} down and pass it around, {0} {1} of beer on the wall.\n" verseChunk3 = "Go to the store and buy some more, 99 bottles of beer on the wall.\n" def verse(self, number): bottleItemWord = "one" if number > 1 else "it" totalVerse = self.verseChunk1.format(getNumberRep(number), getBottlePlural(number)) totalVerse = capitaliseFirst(totalVerse) if (number > 0): totalVerse += self.verseChunk2.format(getNumberRep(number - 1), getBottlePlural(number - 1), bottleItemWord) else: totalVerse += self.verseChunk3 return totalVerse def sing(self, start, end = 0): return '\n'.join(self.verse(n) for n in range(start, end - 1, -1)) + '\n'
351b10779abbe5d2e37c023272d7e6cd6fcf188a
liampongracz/SimplePythonProjects
/StockPriceApp/myapp.py
646
3.515625
4
import streamlit as st import yfinance as yf import pandas as pd # simple header st.write(""" # Stock Price App Shown is closing price and volume of Google """) # init var w/ ticker i want to get tickerSymbol = 'GOOGL' # get data from ticker w/ yfinance tickerData = yf.Ticker(tickerSymbol) # retrieve historical price # period is how often to retrieve data inbetween start and end date tickerDf = tickerData.history(period='1d', start='2011-7-15', end='2021-7-15') # line charts of the dataframe close and volume st.write(""" ## Closing Price """) st.line_chart(tickerDf.Close) st.write(""" ## Volume """) st.line_chart(tickerDf.Volume)
9dfaae07ce29a491b11e252e6096f10f88b211af
narf1399/PythonExercise
/OOP Examples/Employee.py
668
3.671875
4
class Employee: # Class variable employeeCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.employeeCount += 1 def displayCount(self): print "There are %d employee(s)." % Employee.employeeCount def displayEmployee(self): print "I'm", self.name, "and make", self.salary @staticmethod def displayCountStatic(): print "There are %d employee(s)." % Employee.employeeCount myEmployee = Employee("Tim", 1000000) myEmployee.displayCount() myEmployee.displayEmployee() Employee.displayCountStatic()
5b5ef6c94b90046f73f15dc913a689bb4405399a
skpycoder786/HackerRank-s-Python-Problems
/numbersystem.py
1,071
3.9375
4
#numbersystem def print_formatted(number): for i in range(1,number+1) : a=oct(i) a=a[2:] b=hex(i) b=b[2:].upper() c=bin(i) c=c[2:] w=len(c) print("{} {} {} {}".format(i,a,b,c)) if __name__ == '__main__': n = int(input()) print_formatted(n) #exact method: def print_formatted(number): n=number space=len(bin(n))-2 for i in range(1,n+1): string='' for j in range(0,space-len(list(str(i)))): string+=' ' string+=str(i) string+=' ' for j in range(0,space-len(oct(i))+2): string+=' ' string+=str(oct(i))[2:] string+=' ' for j in range(0,space-len(hex(i))+2): string+=' ' string+=str(hex(i))[2:].upper() string+=' ' for j in range(0,space-len(bin(i))+2): string+=' ' string+=str(bin(i))[2:] print(string) if __name__ == '__main__': n = int(input()) print_formatted(n)
7908153788322c86ab42df398196d9d4812ca89a
seansio1995/MISC
/dfs.py
1,054
3.53125
4
graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} def dfs(graph, start): visited, stack=set(), [start] while stack: vertex=stack.pop() if vertex not in visited: visited.add(vertex) stack.extend(graph[vertex]-visited) return visited def dfs2(graph,start,visited=None): if visited is None: visited=set() visited.add(start) for nxt in graph[start]-visited: dfs2(graph,nxt,visited) return visited def dfs_paths(graph,start ,goal): stack=[(start,[start])] while stack: (vertex,path)=stack.pop() for nxt in graph[vertex]-set(path): if nxt==goal: yield path+[nxt] else: stack.append((nxt,path+[nxt])) # print(dfs2(graph,"A")) # print(dfs2(graph,"B")) # print(dfs2(graph,"C")) print(list(dfs_paths(graph,"A","C"))) print(list(dfs_paths(graph,"A","D")))
f5198982bbc676035b19d9c603a0f8ca345fbafa
mr-d-self-driving/Autonomous-Controls-and-Electrical
/RCCar/PathFollow/utilities.py
1,022
3.828125
4
def map_steer(x): #maps input values of (inmin, inmax) for our understood range of angles to output values of(outmin, outmax) that are used for the ChangeDutyCycle outmax = float(5) outmin = float(10) inmax = float(30) inmin = float(-30) A = float(outmax-outmin) B = float(inmax - inmin) C = float(x - inmin) D = float(outmin) return float(float(A/B)*C+D) def map_motor(x): outmax = float(8) outmin = float(7.5) inmax = float(1) inmin = float(0) A = float(outmax-outmin) B = float(inmax-inmin) C = float(x - inmin) D = float(outmin) return float(float(A/B)*C+D) def steer_to(theta): if theta>=-30 and theta <=30: pass# steerPin.ChangeDutyCycle(steerMap(theta)) else: print("That angle isn't in range") def motor_to(rev): if rev>0 and rev<=1000: pass #motorPin.ChangeDutyCycle(motorMap(rev)) elif rev == 0: pass # motorPin.ChangeDutyCycle(5) else: print("That speed isn't in range")
bcc4bdf6b0031c28f49b3b825341c1eba9fd512c
ceafagerlund/Labb1.py
/Del4.py
289
3.921875
4
n = int(input("Give me a number!! ")) a = 0 b = (n-(a**3))**(1/3) while (a**3 + b**3 != n): a = a + 1 print((a**3)+(b**3)) if ((a**3)+(b**3)==n): break print (n "is" a "to the power of three plus" b "to the power of three") elif ((a**3)>(n) break print ("Alas, it is impossible...")
ed7a1fb720ca5ea3356e2446a9c4789db16db2bc
qiaoyuxuan/python
/headlessTest/Test_headless/base/timeStamp.py
1,995
3.859375
4
# !/usr/bin/env python # -*- encoding: utf-8 -*- ''' Datetime:2020/11/6 9:12 author:乔誉萱 说明:封装时间方法,返回当前时间戳/偏差时间戳、时间转换为时间戳、时间戳转换为时间 :param day: :param ''' import time import datetime, logging def get_timedelta(day): '''返回当前或偏移时间的时间戳。参数:偏移天数,传0则返回当前时间戳,-1则是前一天,1则是后一天''' now = datetime.datetime.now() # print("当前时间:", now) # strptime:转换为时间格式,strftime格式化成年月日时分秒格式 d1 = datetime.datetime.strptime(now.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S') # print("格式化当前时间:", d1) delta = datetime.timedelta(days=day) # 获取当前时间的偏移时间 d2 = d1 + delta # 当前日期-偏移时间,获取偏移日期 # print("%s天前的日期为:" % day, d2) result_time = int(time.mktime(d2.timetuple())) # timetuple:将时间类型转换成时间数组,mktime:将时间数组转换成时间戳 # print(result_time) return result_time def times_to_stamp(date_time): '''时间转换为时间戳''' time_array = time.strptime(date_time, '%Y-%m-%d %H:%M:%S') # strptime:将str类型转换成时间数组 # print("time_array:", time_array) time_stamp = int(time.mktime(time_array)) # mktime:将时间数组转换成时间戳 # print(time_stamp) return time_stamp def stamp_to_times(date_stamp): '''时间戳转换为时间''' time_array = time.localtime(int(date_stamp)) # 将时间戳转换为时间 data_time = time.strftime("%Y-%m-%d %H:%M:%S", time_array) # 格式化时间格式 # print(data_time) return data_time '''测试:调用方法测试结果''' try: get_timedelta(0) times_to_stamp('2020-09-28 11:40:59') stamp_to_times("1601264459") except Exception as e: print("转换出错!") logging.exception(e)
242081ea43d80444b594a548ef5245750b30d92d
sumenko/contest_14
/contest_14B_combinations.py
510
3.515625
4
# Спринт 14 # B. Комбинации kbd = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs','8': 'tuv', '9': 'wxyz' } def generator(numbers, collection, txt='', idx=0): if idx == len(numbers): collection.append(txt) return seq = kbd[numbers[idx]] for ch in seq: generator(numbers, collection, txt + ch, idx + 1) def main(): collection = [] generator(input(), collection) print(*collection) if __name__ == '__main__': main()
4af8d546c608ceb80209e8ef8dd19fa521f960af
clicianaldoni/aprimeronpython
/chapter2/2.42-maxmin_list.py
314
4.125
4
""" Find the max/min elements in a list. """ def max(a): max_elem = a[0] for element in a[1:]: if element > max_elem: max_elem = element return max_elem def min(a): minimum = a[0] for elem in a[1:]: if elem < minimum: minimum = elem return minimum
2715a66847ff10382948d82f36622bc68bbbd65c
AnfisaAnisimova/Geekbrains_student
/Введение в Python/Dz_9/Task_9_4.py
1,270
3.90625
4
class Car: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print(f'The car {self.name} is moving!') def stop(self): print(f'The car {self.name} has stopped.') def turn(self, direction): print(f'The car {self.name} turned in the {direction} direction.') def show_speed(self): print(f'Speed of the car is {self.speed}.') class TownCar(Car): def show_speed(self): if self.speed > 40: print("You have exceeded the speed limit!") class SportCar(Car): pass class WorkCar(Car): def show_speed(self): if self.speed > 60: print("You have exceeded the speed limit!") class PoliceCar(Car): pass car_1 = TownCar(50, "red", "Kia Rio") car_1.go() car_1.stop() car_1.turn("left") car_1.show_speed() car_2 = WorkCar(70, "silver", "Toyota Yaris") car_2.go() car_2.stop() car_2.turn("right") car_2.show_speed() car_3 = SportCar(120, "black", "Jaguar F Type SVR") car_3.go() car_3.stop() car_3.turn("right") car_3.show_speed() car_4 = PoliceCar(80, "blue", "Ford Focus") car_4.go() car_4.stop() car_4.turn("right") car_4.show_speed()
6e64f4f6bdf2903f891680ce640800540d36aa0c
AjithPanneerselvam/Algo-Problems
/InterviewBit/Dynamic Programming/longestPath.py
2,082
3.578125
4
""" https://www.interviewbit.com/problems/largest-distance-between-nodes-of-a-tree/ A : [ -1, 0, 1, 1, 2, 0, 5, 0, 3, 0, 0, 2, 3, 1, 12, 14, 0, 5, 9, 6, 16, 0, 13, 4, 17, 2, 1, 22, 14, 20, 10, 17, 0, 32, 15, 34, 10, 19, 3, 22, 29, 2, 36, 16, 15, 37, 38, 27, 31, 12, 24, 29, 17, 29, 32, 45, 40, 15, 35, 13, 25, 57, 20, 4, 44, 41, 52, 9, 53, 57, 18, 5, 44, 29, 30, 9, 29, 30, 8, 57, 8, 59, 59, 64, 37, 6, 54, 32, 40, 26, 15, 87, 49, 90, 6, 81, 73, 10, 8, 16 ] Your function returned the following : 15 The expected returned value : 14 Asked In: Facebook Google """ class Solution: # @param A : list of integers # @return an integer def solve(self, A): dynArray = [0] * len(A) firstLargest = secondLargest = firstIndex = secondIndex = 0 for i in range(1, len(A)): depth = 0 j = i while(A[j] != -1): j = A[j] depth += 1 if(dynArray[j] != 0): break dynArray[i] = depth + dynArray[j] if(dynArray[i] > firstLargest): secondLargest = firstLargest firstLargest = dynArray[i] secondIndex = firstIndex firstIndex = i print (firstIndex, firstLargest, secondIndex, secondLargest) print(A[firstIndex], A[secondIndex]) print(dynArray) print(dynArray[35]) print(dynArray[34]) print(dynArray[15]) print(dynArray[14]) print(dynArray[12]) print(dynArray[3]) print(dynArray[1]) print(dynArray[0]) return firstLargest + secondLargest arr = [ -1, 0, 1, 1, 2, 0, 5, 0, 3, 0, 0, 2, 3, 1, 12, 14, 0, 5, 9, 6, 16, 0, 13, 4, 17, 2, 1, 22, 14, 20, 10, 17, 0, 32, 15, 34, 10, 19, 3, 22, 29, 2, 36, 16, 15, 37, 38, 27, 31, 12, 24, 29, 17, 29, 32, 45, 40, 15, 35, 13, 25, 57, 20, 4, 44, 41, 52, 9, 53, 57, 18, 5, 44, 29, 30, 9, 29, 30, 8, 57, 8, 59, 59, 64, 37, 6, 54, 32, 40, 26, 15, 87, 49, 90, 6, 81, 73, 10, 8, 16 ] sol = Solution() sol.solve(arr)
7da8dee3b2751cb81b3c948fbad374bdf624909f
Andrey-Liu/shiyanlou-code
/testhundred.py
154
4.28125
4
num = int(input("Enter an integer:")) if num < 100: print('Your number is less than 100') else: print('Your number is equal or greater than 100')
3291b09644a44be3a3937877fcdd9d69aa60adff
supriya1610190086/If-Else-Python
/middle number even or odd number.py
158
4.09375
4
num=int(input("enter the number")) middle_digit=(num//10)%10 if middle_digit%2==0: print("even number",middle_digit) else: ("odd number",middle_digit)
1efbe29fea56e2016a275e89096e155b4d471245
rafa3lmonteiro/python
/python3-course/aula12/aula12-desafio44.py
909
3.84375
4
# Elabore um programa que calcule o valor a ser pago por um produto, considerando: # O seu preço normal e condição de pagamento: # - à vista dinheiro/cheque: 10% de desconto # - à vista no cartão: 5% de desconto # - em até 2x no cartão: preço formal # - 3x ou mais no cartão: 20% de juros print('#--'*15) preco = float(input('Qual é o preço do produto ?: ')) print('-'*25) # Calculo das formas de pagamento dinheiro_cheque = preco - (preco * 0.10) avista_cartao = preco - (preco * 0.05) cartao2x = preco cartao3x = preco + (preco * 0.20) print('# Condições de Pagamento: ','\n','-'*25) print('Dinheiro ou Cheque - desconto de 10%: {:.2f}'.format(dinheiro_cheque)) print('A Vista no Cartão - desconto de 5%: {:.2f}'.format(avista_cartao)) print('Cartão em 2x - preço normal: {:.2f}'.format(cartao2x)) print('Cartão em 3x - Juros de 20%: {:.2f}'.format(avista_cartao))
d9c5bf465ac5a030ac3be73df93dd0a78cdb5f09
ilhammaulana28/Ilham-Maulana-Nur-Afani_I0320052_Tifffany-Bella_Tugas4
/I0320052_Soal4_Tugas4.py
759
3.890625
4
print('Soal No. 4\n') #untuk mendaftar kursus online, siswa harus berusia min. 21 th #telah lulus ujian kualifikasi #berapa usia kamu? #apakah anda sudah lulus ujian kualifikasi (Y/T)? #respons pertanyaan program sbg berikut. #1. Anda dapat mendaftar di kursus. #2. Anda tidak dapat mendaftar di kursus. print('Rencana pengujian kursus') print('Syarat : 1. Berusia minimal 21 tahun.') print(' 2. Telah lulus ujian kualifikasi.\n') usia = int(input('Berapa usia kamu?')) kualifikasi = str(input('Apakah anda sudah lulus ujian kualifikasi (Y/T)?')) if kualifikasi == 'Y' and usia >=21: print('Anda dapat mendaftar di kursus.') else: print('Anda tidak dapat mendaftar di kursus\n') input('Tekan enter untuk keluar..')
a88a7d7c1d8f2639a626791c8976d5be8c349308
vamshi-krishna-prime/Programming_Nanodegree
/6. Python, Part 2/Lesson 3 - Strings and Lists, Part 2/59-substring-exercise-is_substring.py
1,746
4.3125
4
# Udacity > Intro to the Programming Nanodegree > # Python part 2 > 3. Strings & Lists Part 2 > Section 12: # Finding substrings(2/4) # Writing an is_substring function ''' Our first goal will be to write a function, is_substring, that simply checks whether one string is a substring of another. If the first string is a substring of the other, it should return True; otherwise, it should return False. Like this: >>> is_substring('oo', 'book') True >>> is_substring('pony', 'abracadabra') False >>> is_substring('dab', 'abracadabra') True This is very similar to the starts_with function we wrote earlier, except that it will check the whole string—not just the beginning of it. ''' # Instructions: ''' 1. Define the function so it accepts two parameters (substring and string) 2. Loop over the index position of the string. 3. At each position, check if the current slice is equal to the target substring. If it is return 'True'. 4. If the loop finishes and the substring hasn't found, return 'False'. ''' # Approach 1 - using 'for loop' def is_substring1(substring, string): for index in range(len(string)): if string[index: index + len(substring)] == substring: return True index += 1 return False # Approach 2 - using 'while loop' def is_substring2(substring, string): index = 0 while index < len(string): if string[index: index + len(substring)] == substring: return True index += 1 return False print('is substring: ' + str(is_substring1('oo', 'book'))) print('is substring: ' + str(is_substring1('pony', 'abracadabra'))) print('is substring: ' + str(is_substring2('dab', 'abracadabra'))) print('is substring: ' + str(is_substring2('ff', 'waffles')))
748f220560f1574766dfc8408483f191c729b511
musasaleem/unit_three
/d4_unit_three_warmups.py
208
3.71875
4
def area_of_rectangle(length, width): """ finding area of rectangle by multiplying length by width :param length: :param width: :return: """ area = length * width return area
c0fdab26626d063d792982a124bea1952306d8db
jamesin4d/pyengine
/src/utilities/graphicaluserinterface.py
3,332
3.640625
4
# Created by a human # when: # 10/27/2015 # 9:31 AM # monkey number one million with a typewriter # # -------------------------------------------------------------------- import pygame def print_info(surface, msg, x=10, row=0): font = pygame.font.Font(None, 16) text = font.render(msg, 1, (254,254,254)) pos = [x,10+16*row] surface.blit(text, pos) # they are used to put text on a surface, message = 'whatever you want' def display_info(surface, message, font_size, x, y): near_white = (254,254,254) font = pygame.font.Font(None, font_size) text = font.render(message, 1, near_white) pos = [x,y] surface.blit(text, pos) def text_widget(r,g,b, text, size, x,y): screen = pygame.display.get_surface() col = pygame.Color((r,g,b)) class Button(object): def __init__(self, image, pos): self.image = image self.rect = self.image.get_rect() self.set_position(pos) self.position = pos self.screen = pygame.display.get_surface() self.mouse_in_x_bounds = False self.mouse_in_y_bounds = False self.mouse_in_bounds = False self.clicked_on = False def set_position(self, pos): self.rect.topleft = pos def get_position(self): return self.rect.topleft def check_mouse(self): self.mouse_in_x_bounds = False self.mouse_in_y_bounds = False self.mouse_in_bounds = False mos_pos = pygame.mouse.get_pos() if mos_pos[0] > self.rect.left: if mos_pos[0] < self.rect.right: self.mouse_in_x_bounds = True if mos_pos[1] > self.rect.top: if mos_pos[1] < self.rect.bottom: self.mouse_in_y_bounds = True if self.mouse_in_x_bounds and self.mouse_in_y_bounds: self.mouse_in_bounds = True if self.mouse_in_bounds and pygame.event.get(pygame.MOUSEBUTTONDOWN): self.clicked_on = True class Widget(pygame.Surface): def __init__(self, size, image=None): pygame.Surface.__init__(self, size) self.image = image self.size = size self.screen = pygame.display.get_surface() self.rect = self.get_rect() def set_position(self, pos): self.rect.topleft = pos def get_position(self): return self.rect.topleft def draw(self): if self.image is None: self.screen.blit(self, self.rect) else: self.screen.blit(self.image, self.rect) pygame.display.update(self.rect) class Score(Widget): def __init__(self, title="", digits=8, size=18): self.color = (183,0,0) self.font = pygame.font.Font(None,size) self.title = title self.score = 0 self.digits = digits self.text = title self.image = self.gen_image() Widget.__init__(self, self.image.get_size()) self.fill((0,0,0)) self.blit(self.gen_image(), (0,0)) def gen_image(self): score = str(self.score) zeroes = "0" * (self.digits - len(score)) msg = self.title + zeroes + score self.text = msg return self.font.render(msg, 0, self.color, (0,0,0)) def update(self, score): self.score = score self.fill((0,0,0)) self.blit(self.gen_image(), (0,0)) self.draw()
7e1e1e54042eff9a52161eb3ec74a81476f2f40f
MatthieuHernandez/exercises
/Trees/Tree.py
1,085
3.71875
4
class Node: Name = "" Nodes = [] def __init__(self, nodes, verbose = 0): try: if len(nodes) == 0: return self.Name = nodes[0] if verbose: print("Creating", self.Name, "...") if (isinstance(nodes, list) and len(nodes) > 1 and isinstance(nodes[0], str) and isinstance(nodes[1], list)): nodes.pop(0) for node in nodes: self.Nodes.append(Node(node, verbose)) if verbose: print("Node", self.Name, "created.") else : if isinstance(nodes, list): nodes.pop(0) self.Nodes.append(Node(nodes, verbose)) if verbose: print("Leaf", self.Name, "created.") except: print("Cannont create node, invalid input.") def ComputeDeep(self): return 0
c11612c1830a7b8e0902cbdd1bb40ef4733300e5
gistable/gistable
/dockerized-gists/b748c632bec0628c2419/snippet.py
2,255
3.84375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys BASE_TEN = { 1: ['One', 'Eleven', 'Ten'], 2: ['Two', 'Twelve', 'Twenty'], 3: ['Three', 'Thirteen', 'Thirty'], 4: ['Four', 'Fourteen', 'Forty'], 5: ['Five', 'Fifteen', 'Fifty'], 6: ['Six', 'Sixteen', 'Sixty'], 7: ['Seven', 'Seventeen', 'Seventy'], 8: ['Eight', 'Eighteen', 'Eighty'], 9: ['Nine', 'Nineteen', 'Ninety'] } def print_result(in_text): print "{}Dollars".format(in_text) def check_decimals_and_units(in_text, number, tens): if tens >= 2: in_text.append(BASE_TEN[tens][2]) if tens == 1: if number > 0: in_text.append(BASE_TEN[number][1]) else: in_text.append(BASE_TEN[tens][2]) if number > 0 and (tens == 0 or tens >= 2): in_text.append(BASE_TEN[number][0]) def break_hundreds(number, in_text, base): hundreds = 0 tens = 0 if number >= 100: hundreds = int(number / 100) number %= 100 if number >= 10: tens = int(number / 10) number %= 10 if hundreds > 0: in_text.append('{}Hundred'.format(BASE_TEN[hundreds][0])) check_decimals_and_units(in_text, number, tens) in_text.append(base) def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases.readlines(): try: number = int(test) except ValueError: continue billion = int(number / 1000000000) if billion > 0: continue number %= 1000000000 million = int(number / 1000000) number %= 1000000 thousands = int(number / 1000) number %= 1000 hundreds = int(number / 100) number %= 100 decimals = int(number / 10) number %= 10 unity = number % 10 in_text = [] if million: break_hundreds(million, in_text, 'Million') if thousands: break_hundreds(thousands, in_text, 'Thousand') if hundreds > 0: in_text.append('{}Hundred'.format(BASE_TEN[hundreds][0])) check_decimals_and_units(in_text, unity, decimals) if in_text: print_result(''.join(in_text)) test_cases.close() if __name__ == '__main__': main()
ea391887645db1fc0e8a62a20475bab7b0e33072
JcesarIA/learning-python
/EXCursoEmVideo/ex048.py
180
3.796875
4
n = 0 a = 0 for c in range(1, 501, 2): if c % 3 == 0: a += 1 n += c print('A soma dos {} numeros impares divisiveis por 3 entre 1 e 500 é de {}'.format(a, n))
857c3dc368119aac3c68e8f461f8dfe90f9b28bc
MarinoDuran/CoffeeMachine_Py
/coffeemachine_sim.py
3,683
3.8125
4
class CoffeeMachine: inventory = {"Water": 400, "Milk": 540, "Beans": 120, "Cups": 9, "Money": 550} state = "stand_by" coffee_type = "none_selected" def __init__(self, action): self.action = action def process_input(self): if self.action == "buy": CoffeeMachine.state = "buy" elif self.action == "take": take() elif self.action == "fill": self.state = "fill" elif self.action == "remaining": status() elif self.action == 'exit': exit() else: print("Invalid entry. Please try again:") start_machine() def reset_state(): CoffeeMachine.state, CoffeeMachine.coffee_type = "stand_by", "none_selected" def status(): current_status = ''' The coffee machine has: {0} of water. {1} of milk. {2} of coffee beans. {3} of disposable cups ${4} of money. ''' print(current_status.format(CoffeeMachine.inventory.get("Water"), CoffeeMachine.inventory.get("Milk"), CoffeeMachine.inventory.get("Beans"), CoffeeMachine.inventory.get("Cups"), CoffeeMachine.inventory.get("Money"))) reset_state() start_machine() def fill(add_to): parts = [int(add_to[0]), int(add_to[1]), int(add_to[2]), int(add_to[3]), 0] index = 0 for item in CoffeeMachine.inventory: CoffeeMachine.inventory[item] += parts[index] index += 1 reset_state() def enough(ingredients): enough_item = True virtual_machine = CoffeeMachine.inventory.copy() index = 0 for item in virtual_machine: virtual_machine[item] += ingredients[index] index += 1 for items in virtual_machine: if virtual_machine[items] < 0: print(f'Sorry not enough {items}!') enough_item = False if enough_item: print("\nI have enough resources, making you a coffee!") reset_state() return enough_item def take(): print(f"\nI gave you ${CoffeeMachine.inventory.get('Money')}\n") CoffeeMachine.inventory["Money"] = 0 reset_state() start_machine() def make(cafe): parts = [] if cafe == "1": parts = [-250, 0, -16, -1, 4] elif cafe == "2": parts = [-350, -75, -20, -1, 7] elif cafe == "3": parts = [-200, -100, -12, -1, 6] else: pass if enough(parts): index = 0 for item in CoffeeMachine.inventory: CoffeeMachine.inventory[item] += parts[index] index += 1 def start_machine(): prompt = CoffeeMachine(input("\nWrite action (buy, fill, take, remaining, exit): \n")) prompt.process_input() if prompt.state == "buy": coffee_type = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ") if coffee_type == "back": start_machine() elif coffee_type == "1" or coffee_type == "2" or coffee_type == "3": make(coffee_type) else: print("Invalid entry. Please try again:") start_machine() else: add = (input("Write how many ml of water do you want to add:"),) add += (input("Write how many ml of milk do you want to add:"),) add += (input("Write how many grams of coffee beans do you want to add:"),) add += (input("Write how many disposable cups of coffee do you want to add:"),) try: fill(add) except: print("\nInvalid amount type. Please try again or type back to start from main menu.") finally: start_machine() start_machine() start_machine()
1918b9803c511b6dda18d4a99d4f966398b9fb7b
Levitate-Git/g-petto-commandGenerator
/Smoothing_Modules/d2_smoothing.py
13,838
3.5
4
import numpy as np from scipy import interpolate from CustomModules import global_vars import math import main_smoothing from Smoothing_Modules import time_calculation def make_spline(path): """ Producing a cubic spline by using splprep method from scipy interpolate. Parameters ---------- path : list type Points on path that end effectors passed. Returns ------- tck : tuple type A tuple contains parameter of created spline. u : list type values between 0-1, corresponding to the user inputted frames. u value at zeroth frame is zero. u value at last frame is one. """ np_path = np.asarray(path) tck, u = interpolate.splprep([np_path[:, 0], np_path[:, 1]], s=0) # making a spline from given coordinates(x=path[:,0] and z=path[:,0]) by using splprep return tck, u def t_wrt_u(delta_t, u,stopped_frames): """ Projecting t values on u values (before populated) of spline helps us to divide spline into time intervals as user input. Parameters ---------- delta_t : list type Times that have been entered by user for each frames. u : list type List of values between 0-1, corresponding to the user inputted frames. u value at zeroth frame is zero. u value at last frame is one. stopped_frames: list type The frames that are stopped afterwards. Returns ------- time vs_u : list type Time values corresponding u values as user inputted. """ st_frames=[] s_frames = [] if len(stopped_frames) > 0: for frame in stopped_frames: st_frames.append(frame) for j in range(len(stopped_frames)): s_frames.append(stopped_frames[j]) temp = 0 i = 0 # u counter s = 0 # delta_t counter time_vs_u = [] while s < len(delta_t): if s == 0: temp = 0 time_vs_u.append((temp,u[i])) s += 1 if len(s_frames)>0 : while s_frames[0] == s-1: temp += delta_t[s] time_vs_u.append((temp,u[0])) s_frames.pop(0) s_frames.append(0) s += 1 if not len(s_frames) > 0: break else: if len(s_frames)>0: if s_frames[0] == s: temp += delta_t[s] time_vs_u.append((temp,u[i])) s+=1 while s_frames[0] == s-1: temp += delta_t[s] time_vs_u.append((temp,u[i])) s_frames.pop(0) s_frames.append(0) s += 1 if not len(s_frames) > 0: break else: temp += delta_t[s] time_vs_u.append((temp,u[i])) s += 1 else: temp += delta_t[s] time_vs_u.append((temp,u[i])) s += 1 i += 1 return time_vs_u def populate_spline(tck, u): """ In order to populate the spline inputted by user. Parameters ---------- tck : tuple type A tuple contains parameter of created spline. u : list type Values between 0-1, corresponding to the user inputted frames. u value at zeroth frame is zero. u value at last frame is one. Returns ------- xs : list type List of x values which are on the constructed splined path of end effector. zs : list type List of z values which are on the constructed splined path of end effector. u_values : list type List of u values which refer a sub_frame point on the constructed splined path of end effector. u values are between 0 and 1. """ xs = [] zs = [] u_values = [] k = 0 l = 0 m = 0 for i in range(len(u)-1): # Number of points taken from user -1 = number of intervals in spline. # Spline length approximation by calculating very small increments. spl_leng_pnt = np.linspace(u[i], u[i+1], 10000, endpoint=True) x, z = interpolate.splev(spl_leng_pnt, tck) total_length_of_spline_part = 0 for j in range(len(x)-1): length_of_small_piece = ( (x[j+1]-x[j])**2 + (z[j+1]-z[j])**2 )**0.5 total_length_of_spline_part += length_of_small_piece frame_div_factor = int(total_length_of_spline_part / global_vars.DELTA_LENGTH) # Dividing spline into approximately DELTA_LENGTH pieces. # Get samples from divided path temp = np.linspace(u[i], u[i+1], frame_div_factor + 1, endpoint=True) xs_spline, zs_spline = interpolate.splev(temp, tck) last_element_x = xs_spline[-1] last_element_z = zs_spline[-1] for u_temp in temp: if k == 0: u_values.append(u_temp) elif u_values[-1] != u_temp: u_values.append(u_temp) k +=1 # Remove last element when adding, to avoid duplicates. # Unless it is the last element, we need end point. l = 0 for x in xs_spline: if l == (len(xs_spline)-1): pass else: xs.append(x) l +=1 m = 0 for z in zs_spline: if m == (len(xs_spline)-1): pass else: zs.append(z) m +=1 xs.append(last_element_x) # adding last elements zs.append(last_element_z) # adding last elements del temp del xs_spline del zs_spline return xs, zs, u_values def conv_cart_to_conf(x_points, z_points, motor_coordinates): """ Converting cartesian coordinates to rope1(length of 1. motor) and rope2(length of 2. motor) configuration space coordinates. This method assumes that there is two motors in the system. Using basic hypotenuse formulation rope_i = ( ( x-Px(i) )^2 - ( z-Pz(i) )^2 )**0.5 where: rope_i : is the cable length of ith motor Px(i) : is the x value of ith motor. PZ(i) : is the z value of ith motor. Parameters ---------- x_points : list type List of x values corresponding to the divided path values values z_points : list type List of z values corresponding to the divided path values values motor_coordinates : list type List of lists of motor coordinates that will be used in 2D motion Return ------ configuration_coordinates : list type List of coordinates in configuration space """ rope_1=[] rope_2=[] temp = 0 horizontal_dist = 0 #for experimenting purpose /horizontal distance between rope connection points to center point # Configuration space coordinates for rope for i in range(len(x_points)) : temp1 = ( (x_points[i] - horizontal_dist - motor_coordinates[0][0] )**2 + (z_points[i] - motor_coordinates[0][1])**2 )**0.5 rope_1.append(temp1) temp1 = 0 for i in range(len(x_points)) : temp2 = ( (x_points[i] + horizontal_dist - motor_coordinates[1][0] )**2 + (z_points[i] - motor_coordinates[1][1])**2 )**0.5 rope_2.append(temp2) temp2 = 0 del temp return rope_1, rope_2 def project_t_on_populated_u(delta_ts,stopped_frames,rope_1_length_values,rope_2_length_values,time_vs_u, u_values, xs,zs): """ We need to find a relationship between u and t according to the movement of end-effectors equations. Doing this task involves velocity and time manupulations for every frame in a movement configuration """ time_calculate = time_calculation.TimeCalculations() # First we find the u values correponding to the t values that a user inputted list_position =[] for t_vs_u in time_vs_u: for i in range(len(u_values)): if t_vs_u[1] == u_values[i]: list_position.append(i) del i # To define the time intervals in a frame we do the steps below: average_speed_of_frames = time_calculate.calculating_average_end_effector_speed(list_position, time_vs_u,xs,zs) j = -1 #average velocity counter s = 0 #real frame counter including stop frames for pos in list_position: enter = True # If it is the zero numbered frame we just add a "0" to start time_of_intervals list if s == 0: time_calculate.zeroth_frame() enter = False elif average_speed_of_frames[j] == 0: times_and_velocities_for_end_effector = time_calculate.stopped_frame(time_vs_u) enter = False elif s+1 != len(list_position) and pos == list_position[-1]: # It means we have stopped frames at the end of the movement. if average_speed_of_frames[j] != 0: end_velocity = float(0) times_and_velocities_for_end_effector = time_calculate.solving_with_jerk_control(pos,list_position, end_velocity,time_vs_u,xs,zs) else: times_and_velocities_for_end_effector = time_calculate.stopped_frame(time_vs_u) enter = False elif s+1 == len(list_position): # It means we are at the last frame if average_speed_of_frames[j] == 0: times_and_velocities_for_end_effector = time_calculate.stopped_frame(time_vs_u) else: end_velocity = float(0) times_and_velocities_for_end_effector = time_calculate.solving_with_jerk_control(pos,list_position, end_velocity,time_vs_u,xs,zs) enter = False if enter: end_velocity = average_speed_of_frames[j] if abs((zs[pos]-zs[pos-1])/(xs[pos]-xs[pos-1]) - (zs[pos+1]-zs[pos])/(xs[pos+1]-xs[pos]))>1: end_velocity = float(0) if average_speed_of_frames[j+1] == 0: end_velocity = float(0) times_and_velocities_for_end_effector = time_calculate.solving_with_jerk_control(pos,list_position, end_velocity,time_vs_u,xs,zs) s += 1 j += 1 print("DUO_MODE FINISHED") return times_and_velocities_for_end_effector def project_time_and_velocities_on_rope(rope_point, time_vs_u, u_values, times_and_velocities_for_end_effector): time_of_intervals = [] velocities_of_end_effector = [] angles_of_end_effector = [] rope_point_vs_t =[] list_position =[] for i in range(len(times_and_velocities_for_end_effector)): time_of_intervals.append(times_and_velocities_for_end_effector[i][0]) velocities_of_end_effector.append(times_and_velocities_for_end_effector[i][1]) first_frame_control = True if velocities_of_end_effector[0] == "stop": for v in range(len(time_of_intervals)): if velocities_of_end_effector[v] == "stop": if v==0: time_of_intervals.insert(0,0) rope_point.insert(v,rope_point[v]) else: rope_point.insert(v,rope_point[v]) else: for v in range(len(time_of_intervals)): if velocities_of_end_effector[v] == "stop": if v==0: time_of_intervals.insert(0,0) rope_point.insert(v,rope_point[v]) else: rope_point.insert(v-1,rope_point[v-1]) for i in range(len(time_of_intervals)): rope_point_vs_t.append((rope_point[i],time_of_intervals[i])) max_t = max(time_of_intervals) max_length = max(rope_point) min_length = min(rope_point) return rope_point_vs_t, max_t, max_length ,min_length def rope_velocity_from_length_vs_time(rope_point_vs_t): #TODO: en son hız olarak neden 0 basmadığını bulmamız gerekiyor for_graph_rope_vel_vs_t =[(0,0)] for i in range(1,len(rope_point_vs_t)): rope_vel = (rope_point_vs_t[i][0] - rope_point_vs_t[i-1][0])/(rope_point_vs_t[i][1] - rope_point_vs_t[i-1][1]) for_graph_rope_vel_vs_t.append((rope_vel,rope_point_vs_t[i][1])) for_graph_rope_vel_vs_t draw_plot(for_graph_rope_vel_vs_t,200,0.4,-0.4,"Rope Velocity","Velocity") rope_vel_vs_t =[] for i in range(len(for_graph_rope_vel_vs_t)): if i==0: if for_graph_rope_vel_vs_t[i+1][0] == 0: pass else: temp = for_graph_rope_vel_vs_t[i] rope_vel_vs_t.append(temp) else: if for_graph_rope_vel_vs_t[i][0]==0: rope_vel_vs_t.append(("stop",for_graph_rope_vel_vs_t[i][1])) else: rope_vel_vs_t.append((for_graph_rope_vel_vs_t[i][0],for_graph_rope_vel_vs_t[i][1])) return rope_vel_vs_t def draw_plot(splined_paths, lim_x, lim_y, min_length = -0.1, title="title", y_label="Rope Length"): """ rope_list = [] time_list = [] for i in range(len(splined_paths)): rope_list.append(splined_paths[i][1]) time_list.append(splined_paths[i][0]) fig, ax = plt.subplots() ax.plot(rope_list, time_list, 'r-') plt.title(title) plt.xlabel("T") plt.ylabel(y_label) plt.xlim(min_length, lim_x+0.5) plt.ylim(min_length, lim_y+0.5) plt.show() """
4b13db178930c1c9679c7fc9092b756d0402fcf4
dhineshperiyasamyk/dhineshp
/exp2.py
114
3.828125
4
j=int(raw_input()) if(j<0): print ("invalid") elif(j%2==0): print ("Even") elif(j%2==1): print ("Odd")
30ef7ac3652e6cd9d3b5f14965fed114fb6ad1c4
88il/algo-comp-2022
/assignment1/main.py
3,374
3.546875
4
#!usr/bin/env python3 import json import sys import os from operator import itemgetter from collections import Counter INPUT_FILE = 'testdata.json' # Constant variables are usually in ALL CAPS class User: def __init__(self, name, gender, preferences, grad_year, responses): self.name = name self.gender = gender self.preferences = preferences self.grad_year = grad_year self.responses = responses # Takes in two user objects and outputs a float denoting compatibility def compute_score(user1, user2): # Initialize compatibility to 0 compatibility = 0 num_questions = len(users[0].responses) num_answer_choices = 5 # WEIGHT for gradYear compatibility year1 = user1.grad_year year2 = user2.grad_year # Smaller age gap results in larger gradYear_compatibility # Age gap of 0 corresponds to gradYear_compatibility of 1/4... age gap of 4 deducts 1/12 from overall compatibility gradYear_compatibility = (3 - abs(year1 - year2)) / 12 compatibility += gradYear_compatibility # WEIGHT for gender preferences–only add points if preferences agree mutually if (user1.preferences[0] == user2.gender and user2.preferences[0] == user1.gender): compatibility += 1 / 12 # WEIGHT responses based on frequency response is chosen # List of lists of length num_questions for response weights based on frequency of response response_weights = [[]] * num_questions for i in range(num_questions): # List of responses to question i responses_i = [] for j in range(len(users)): # List of responses to question i responses_i.append(users[j].responses[i]) for j in range(num_answer_choices): # Frequency of answer j for question i freq = Counter(responses_i)[j] # Weight is max 1, min 20/(20+12) = 5/8 weight = num_questions / (num_questions + freq) response_weights[i].append(weight) # Calculate response weights between two users sum_weights = 0 for i in range(num_questions): if (user1.responses[i] == user2.responses[i]): # If same answer, get corresponding response weight sum_weights += response_weights[i][user1.responses[i]] # Normalize sum to (0,1) compatibility += sum_weights / 20 # Max compatibility is 1 + 1/12 + 1/12 = 7 / 6. Normalize: compatibilitiy = 6 * compatibility / 7 return compatibility if __name__ == '__main__': # Make sure input file is valid if not os.path.exists(INPUT_FILE): print('Input file not found') sys.exit(0) users = [] with open(INPUT_FILE) as json_file: data = json.load(json_file) for user_obj in data['users']: new_user = User(user_obj['name'], user_obj['gender'], user_obj['preferences'], user_obj['gradYear'], user_obj['responses']) users.append(new_user) for i in range(len(users)-1): for j in range(i+1, len(users)): user1 = users[i] user2 = users[j] score = compute_score(user1, user2) print('Compatibility between {} and {}: {}'.format(user1.name, user2.name, score))
2ed3ba6cbc0b216e7cf5cda62ceba72d8d0ee94e
Deepika07121994/Python
/Assignments_On_Python/sumlist.py
180
3.5625
4
import functools a = list(map(int, input().split())) # def add(value): # return value + value sum = functools.reduce(lambda x, y: x+y, a) print("Sum of list element:", sum)
bc8dafa52f83f256f224e07c9d147a73c720e844
cesarvecchio/DIO-Python
/Introducao_Programacao_Python/aula11.py
578
3.5625
4
lista = [1, 10] try: arquivo = open("teste.txt", 'r') text = arquivo.read() divisao = 10 / 1 numero = lista[1] # x = a except ZeroDivisionError: print("Não é possivel realizar uma divisão por 0") except ArithmeticError: print("Houve um erro ao realizar uma operação aritmética") except IndexError: print("Erro ao acessar um indice inválidade da lista") except BaseException as ex: print(ex) else: print("Executa quando não ocorre exceção") finally: print("Sempre executa") print("Fechando arquivo") arquivo.close()
7a00d9367d974fa9feefe4c1a3cc0d6664545f65
domino14/euler
/10/sol.py
324
4.03125
4
from math import sqrt def isprime(num): """tests num for primality""" if num < 2: return False for n in range(2, int(sqrt(num))+1): if num % n == 0: return False else: return True sum = 2 for n in range(3, 2000000,2): if isprime(n): sum = sum + n print sum
a9f475975dcfc400d0f317143cc315d7c5b0491e
xcero/ciencia-datos
/Py/Ejemplo7 - For para agrupaciones.py
554
4.1875
4
#For para manejo de Listas fruits = ["apple", "banana", "cherry"] for value in fruits: print("Lista -", value) #For para manejo de Tuples fruits = ("apple", "banana", "cherry") for value in fruits: print("Tuples -",value) #For para manejo de Sets fruits = {"apple", "banana", "cherry"} for value in fruits: print("Set -",value) #For para manejo de Dictionary thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for value in thisdict: print("Diccionary -", value, " - ", thisdict[value])
be8e674bd0224be3dd94a5c3699723b1a554fc08
Python-lab-cycle/Aloshyajoshy
/difference8.py
185
3.65625
4
#print color from color-list1 not contained in color-list2 color_list_1=set(["White","Blue","Red"]) color_list_2=set(["White","Green"]) print(color_list_1.difference(color_list_2))
26b9473a0a622d6bb8fb848fb7754c63479a8dea
bellisonwright/hangman
/hangman.py
12,117
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 18 16:12:53 2021 @author: bertie """ import pandas as pd import numpy as np import string from random import randrange import os class Hangman(): ''' Game of hangman. ''' outputs_dict = { "correct": "Well done, \'{letter}\' is correct!", "won": "Congratulations, you win!\nThe word was \'{word}\'.", "incorrect": "Unlucky, \'{letter}\' is incorrect...", "lost": "Unlucky, \'{letter}\' is incorrect... and you just lost.\nThe word was \'{word}\', and you got {correct_letters} out of {total_letters} letters ({percent_score}%).", "already lost": "You already lost...", "already tried": "\'{letter}\' has already been guessed. Please choose another letter.", "not a letter": "\'{letter}\' is not a letter. Please try again." } length_of_picture = 12 def __init__(self, dictionary_array, print_outputs=True, difficulty="easy", end_screen_spacing=1): ''' :param dictionary_array: np array, wordlist scraped from Oxford Dictionary of English :param print_outputs: True/False, should outputs of each game be printed :param difficulty: "easy" or "hard", 11 attempts or 7 attempts :param end_screen_spacing: int, ''' self.dictionary = dictionary_array self.print_outputs = print_outputs self.difficulty = difficulty self.start_gallows_at = 0 if self.difficulty == "hard": self.start_gallows_at = 5 self.pictures = [] with open("gallows.txt", "r") as f: current_element = "" for num, line in enumerate(f): if num % self.length_of_picture != self.length_of_picture-1: current_element += line else: self.pictures.append(current_element) current_element = "" self.pictures = self.pictures[self.start_gallows_at:] self.incorrect_letters = [] self.guessed_letters = [] self.alphabet = list(string.ascii_lowercase) self.letters_left = self.alphabet self.is_word_guessed = False self.has_lost_game = False self.word_to_guess = None self.blanks = None self.end_screen = [] def initialise(self, word_to_guess): self.word_to_guess = word_to_guess.lower() self.blanks = ["_" for i in range(len(self.word_to_guess))] def create_end_screen(self, result, spacing=0): file_name = "gallows.txt" strings_to_add = [] with open("you-{}.txt".format(result), "r") as f: for line in f: strings_to_add.append(line) with open(file_name, 'r') as f: current_element = "" for num, line in enumerate(f.readlines()[(len(self.incorrect_letters)+self.start_gallows_at)*self.length_of_picture:(len(self.incorrect_letters)+self.start_gallows_at+1)*self.length_of_picture]): if num % len(strings_to_add) != len(strings_to_add)-1: current_element += line[:-1] + spacing*" " + strings_to_add[num % len(strings_to_add)] else: current_element += line[:-1] + spacing*" " + strings_to_add[num % len(strings_to_add)] self.end_screen.append(current_element) current_element = "" def print_update(self, letter, message, valid_guess=True): if self.print_outputs: print("\n" + "".join(["━" for i in range(43)]) + "\n") if valid_guess: os.system('cls||clear') print(self.outputs_dict[message].format(letter=letter.upper(), word=self.word_to_guess.upper(), correct_letters=len(self.word_to_guess)-self.blanks.count("_"), total_letters=len(self.word_to_guess), percent_score=round(100*(len(self.word_to_guess)-self.blanks.count("_"))/len(self.word_to_guess)))) if valid_guess: if not self.has_lost_game and not self.is_word_guessed: print("\n{}".format(self.pictures[len(self.incorrect_letters)])) print("\nWord to guess: "+" ".join(self.blanks)) elif self.is_word_guessed: self.create_end_screen("win", 2) print(self.end_screen[0]) print("Word to guess: "+" ".join(self.blanks)) elif self.has_lost_game: self.create_end_screen("lose", 2) print(self.end_screen[0]) print("Word to guess: "+" ".join(self.word_to_guess.upper())) if len(self.incorrect_letters) > 0: print("Incorrect guesses:", " ".join([i.upper() for i in self.incorrect_letters])) else: print("Incorrect guesses: None") def one_go(self, letter): letter = letter.lower() if letter in self.alphabet: if letter not in self.guessed_letters: self.guessed_letters.append(letter) if letter in self.word_to_guess and not self.has_lost_game: for i in [i for i, j in enumerate(self.word_to_guess) if j == letter]: self.blanks[i] = letter.upper() if "_" in self.blanks: self.print_update(letter, "correct") else: self.is_word_guessed = True self.print_update(letter, "won") elif letter not in self.word_to_guess and not self.has_lost_game: self.incorrect_letters.append(letter) if len(self.incorrect_letters) < len(self.pictures)-1: self.print_update(letter, "incorrect") else: self.has_lost_game = True self.print_update(letter, "lost") else: self.print_update(letter, "already lost", False) else: self.print_update(letter, "already tried", False) else: self.print_update(letter, "not a letter", False) def iterate(self, strategy="random"): self.letters_left = self.alphabet while not self.is_word_guessed and not self.has_lost_game: if strategy == "random": letter = self.letters_left[randrange(len(self.letters_left))] self.one_go(letter) if letter in self.letters_left: self.letters_left.remove(letter) def play_real_time(self): while True: word_to_guess = input("Please choose a word: ") if word_to_guess in dictionary: break else: os.system('cls||clear') warning_input = input("\nAre you sure? \'{}\' doesn't look like a real word... [Y/n] ".format(word_to_guess)) if "n" not in warning_input.lower(): break self.initialise(word_to_guess) print("\n" * 100) os.system('cls||clear') print("\n\n{}".format(self.pictures[0])) print("\nWord to guess: "+" ".join(self.blanks)) print("Incorrect guesses: None") while not self.has_lost_game and not self.is_word_guessed: game.one_go(input("\nGuess a letter: ")) def play_word(self, word_to_guess): self.initialise(word_to_guess) if self.print_outputs: os.system('cls||clear') print("\n\n{}".format(self.pictures[0])) print("\nWord to guess: "+" ".join(self.blanks)) print("Incorrect guesses: None") while not self.has_lost_game and not self.is_word_guessed: game.one_go(input("\nGuess a letter: ")) def autorun(self, num_runs=10000, word_length=None, strategy="random"): lang_freq = ["e", "t", "a", "o", "i", "n", "s", "r", "h", "l", "d", "c", "u", "m", "f", "p", "g", "w", "y", "b", "v", "k", "x", "j", "q", "z"] dict_freq = ["e", "a", "r", "i", "o", "t", "n", "s", "l", "c", "u", "d", "p", "m", "h", "g", "b", "f", "y", "w", "k", "v", "x", "z", "j", "q"] self.print_outputs = False success_counter = 0 for i in range(num_runs): dict_index = randrange(len(dictionary)) game.__init__(self.dictionary,difficulty=self.difficulty, print_outputs=False) game.initialise(str(dictionary[dict_index])) while not self.has_lost_game and not self.is_word_guessed: if strategy == "random": letter_index = randrange(26) if self.alphabet[letter_index] not in self.guessed_letters: game.one_go(self.alphabet[letter_index]) elif strategy == "language frequency": letter = lang_freq[len(self.guessed_letters)] game.one_go(letter=letter) elif strategy == "dictionary frequency": letter = dict_freq[len(self.guessed_letters)] game.one_go(letter=letter) if self.is_word_guessed: success_counter += 1 if i % int(num_runs/20) == int(num_runs/20)-1: # print("#{}:\t{},\t{}/{}\tletters guessed correctly ({}%).".format(i+1, self.word_to_guess, len(self.word_to_guess)-self.blanks.count("_"), len(self.word_to_guess), round(100*(len(self.word_to_guess)-self.blanks.count("_"))/len(self.word_to_guess))).expandtabs(20)) print("#{}:\t{:20} {}{}/{}{}letters guessed correctly ({}%).".format(i+1, self.word_to_guess+",", len(self.word_to_guess)-self.blanks.count("_"), " "*(2-len(str(len(self.word_to_guess)-self.blanks.count("_")))), len(self.word_to_guess), " "*(3-len(str(len(self.word_to_guess)))), round(100*(len(self.word_to_guess)-self.blanks.count("_"))/len(self.word_to_guess)))) return success_counter, num_runs if __name__ == "__main__": print("\n" * 100) os.system('cls||clear') difficulty_level = "easy" if "h" in input("Easy or hard mode? [E/h] ").lower(): difficulty_level = "hard" mode = input("Pick a mode:\n\n1. Single player\n2. Multiplayer\n3. Autorun (computer vs computer)\n\n[1/2/3]: ").lower() print("Loading dictionary...", end=" ", flush=True) import_csv = pd.read_csv("dictionary.csv", usecols=[0], header=None, names=["Words"]) dictionary = np.array(import_csv[~import_csv.Words.str.contains(r'[^a-z]', na=False)]).ravel() print("Done.\n") if "2" in mode: while True: game = Hangman(dictionary, difficulty=difficulty_level) game.play_real_time() if "y" not in input("\nPlay again? [y/N] ").lower(): break elif "1" in mode: while True: game = Hangman(dictionary, difficulty=difficulty_level) word_index = randrange(len(dictionary)) game.play_word(dictionary[word_index]) if "y" not in input("\nPlay again? [y/N] ").lower(): break elif "3" in mode: game = Hangman(dictionary, difficulty=difficulty_level) strat_key = {"1": "random", "2": "language frequency", "3": "dictionary frequency", "4": "all"} strat = strat_key[input("Choose a strategy:\n\n1. Random\n2. By language frequency\n3. By dictionary frequency\n4. All\n\n[1/2/3/4]: ")] n = input("How many runs? (default is 10000) ") if n == "": n = 10000 if strat != "all": results = game.autorun(int(n), strategy=strat) print("Computer was successful in {} out of {} games ({}%) using the {} strategy.".format(results[0], results[1], round(100*results[0]/results[1], 2), strat)) else: for i in range(3): results = game.autorun(int(n), strategy=strat_key[str(i+1)]) print("Computer was successful in {} out of {} games ({}%) using the {} strategy.\n\n".format(results[0], results[1], round(100*results[0]/results[1], 2), strat))
1cf3bc46e40633186649cd8b91366cef47121d2b
george-mammen/IEEE-Bootcamp.py-Hackerrank
/Divisible List.py
426
4.15625
4
""" Qs: Read a list and print the number of elements divisible by 3. Input Format First line contains n the number of elements in the list. The following n lines contains the elements of the list. Sample Input 0 5 1 7 3 6 5 Sample Output 0 2 """ Code: list= [] count=0 n=int(input()) for i in range(0, n): numbers= int(input()) list.append(numbers) if numbers % 3 ==0: count=count+1 print(count)
a8319c069551fc993a601432d6c20f7dcd67e2eb
jaggerkyne/learn_python_the_hard_way
/mystuff/exercise_42/ex42.py
4,134
4.5
4
# Another code written by Jagger Kyne # Copyright 2006 - 2014 Jagger Kyne <jagger.kyne@gmail.com> __author__ = 'Jagger Kyne' # What is the difference between a class and an object? # Is similar as the difference between a Fish and a Salmon? # A Salmon is a particular kind of Fish. # Example, a bucket of three salmon, named Joe, Mary, Ken. # What is the difference between Joe and Salmon? # Joe is an instance of of Salmon. # Fish is a class, -- not a real thing, but rather a word we attach to instances of things with similar attributes. # Salmon is a class, -- a particular kind of fish. # Joe is an object. -- a particular case of Salmon. # Use two catchy phrases: # 1. "is-a" ----> when you talk about objects and classes being # related to each other by a class relationship. # 2. "has-a"----> when you talk about objects and classes that are related # only because they reference each other. ## Animal is-a object (Yes, sort of confusing) look at the extra credit class Animal(object): def __init__(self,name,legs): self.name = name self.legs = legs def get_name(self): print "The name of animal is %s." % self.name class Book(): pass ## Dog is-an animal class Dog(Animal): def __init__(self,name,legs): ## Dog has a name super(Dog,self).__init__(name,legs) ## Cat is-an animal class Cat(Animal): def __init__(self,name,legs): super(Cat,self).__init__(name,legs) ## cat has-a name # self.name = name ## Person is-an object class Person(object): def __init__(self,name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None # make sure self.pet is set to default of None. ## Employee is-a person class Employee(Person): def __init__(self,name,salary): ## ?? hmm what is this strange magic? ## Employee has-a name. super(Employee,self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-an object class Fish(object): def swim(self): print "I am swimming in the ocean!" ## Salmon is-a Fish class Salmon(Fish): def jump(self): print "I am a Salmon and I can jump!" ## Halibut is-a Fish class Halibut(Fish): def sing(self): print "I am a Halibut and I can sing!" ## rover is-a Dog rover = Dog("Rover",4) print "My name is %s and I have %d legs." % (rover.name,rover.legs) ## satan is-a Cat satan = Cat("Satan",4) print "My name is %s and I have %d legs." % (satan.name,satan.legs) # print "Cat's name is %s" % satan.name ## mary is-a Person mary = Person("Mary") print "My name is %s." % mary.name ## mary has a pet called satan mary.pet = satan print "My name is %s and I have a pet named %s." % (mary.name,satan.name) ## frank is-an employee has salary of 120000 frank = Employee("Frank",120000) ## frank has-a pet called rover frank.pet = rover print "My name is %s and I make %d a year, I have a pet call %s." % (frank.name,frank.salary,rover.name) ## flipper is-a Fish flipper = Fish() flipper.swim() ## crouse is-a Salmon crouse = Salmon() crouse.swim() crouse.jump() ## harry is-a Halibut harry = Halibut() harry.swim() harry.sing() # Study Drills # 1. Research why Python added this strange object class and what that means. # a new way of declaring a class which inherits from object class. # 2. Is it possible to use a class like it's an object? # Yes. # 3. Fill out the animals, fish, and people in this exercise with functions that # make them do things. See what happens when functions are in a "base class" # like Animal versus Dog. # 4. Find other people's code and work out all the is-a and has-a relationships. # 5. Make some new relationships that are lists and dicts so you can also # have "has-many" relationships. # Read "is-many" relationship and try to avoid is-many relationship as possible. # read about multiple inheritance. # Search "python super" # A bit of formal # http://www.artima.com/weblogs/viewpost.jsp?thread=236275 # More clear: # http://blog.timvalenta.com/2009/02/understanding-pythons-super/
5f103afa6ec7b5570a1833a7cefec4bbba93d819
top16214/pytest
/search.py
1,046
3.75
4
import re #   正则表达式是极其强大的,利用正则表达式来提取想要的内容是很方便的事。 # 下面演示了在python里,通过正则表达式来提取符合要求的内容。有几个要注意 # 的地方就是: # [1] 要用()将需要的内容包含起来 # [2] 编号为0的group是整个符合正则表达式的内容,编号为1的是第一个(及对应 # 的)包含的内容 # @param regex: regular expression, use () to group the result # 正则表达式,用()将要提取的内容包含起来 # @param content: # @param index: start from 1, depends on the \p regex's () # 从1开始,可以通过数(来得到,其中0是全部匹配 # @return: the first match of the \p regex # 只返回第一次匹配的内容 def extractData(regex, content, index=1): r = '0' p = re.compile(regex) m = p.search(content) if m: r = m.group(index) return r regex = r'第(.*)场雪' content = '2002年的第一场雪' index = 1 print(extractData(regex, content, index))
76407ed60acf17b3a8fb09e61d8e3bc6d0580156
alastairng/mis3640
/session11/binary_search.py
397
3.5625
4
def binary_search(my_list, x): low = 0 high = len(my_list) - 1 while low <= high: mid = int((low + high) / 2) if x == my_list[mid]: return mid elif x < my_list[mid]: high = mid - 1 else: low = mid + 1 my_list = [1, 2, 4, -100, -60000, 123215145, 0, 6223] my_list.sort() print(binary_search(my_list, 4))
f07807c71f73a27503d0f8bacfe6825272b8c5f5
newsteinking/workspace_backup
/workspace_A/workspace_parkjj/Learn to Program with Minecraft Code실습/chapter4-strings/test.py
872
3.53125
4
from mcpi.minecraft import Minecraft logan=Minecraft.create() import time name="Juns" logan.postToChat("Your name is {}".format(name)) logan.postToChat("Your name is %s" %name) name='juns' print(name.upper()) a=name.upper() print(a) b=a.lower() print(b) spamstr="spam" print(spamstr *3) print(spamstr +spamstr +spamstr ) #=============================================================================== # #number1=int(input("input your number :")) # #number2=int(input("input your number2 :")) # sum=number1+number2 # print("{}+{}={}".format(number1,number2,sum)) # #logan.postToChat("{} + {} = {}".format(number1,number2,sum)) #=============================================================================== number3=float(input("input your number3 :")) root=int(number3**0.5) print(root) cute=input("what's your name? :") logan.postToChat("hello {}".format(cute))
ce4c200811d040c00796a757cad6160a0c34d1a4
RashadGhzi/Python-with-Anis
/anis44.py
112
3.578125
4
def fact(n): if (n == 1) | (n == 0): return 1 else: return n * fact(n-1) print(fact(5))
dbaead66a466857685289d958dbde52e311daf6f
Bennibraun/Project-Euler-Solutions
/5.py
411
3.6875
4
# Euler Problem 5 # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? num = 2520 def isDivisible(num): for i in range(1,20): if num%i != 0: return False return True while not (isDivisible(num)): num += 20 print(num)
924560831daef048bfa89003208e7d74c0736eba
LittlePox/Machine-Learning-Course
/machine-learning-ex2/ex2_python/gradient.py
225
3.609375
4
import numpy as np from sigmoid import sigmoid def gradient(theta, X, y): m, n = X.shape theta = theta.reshape((n, 1)) y_bar = sigmoid(X.dot(theta)) grad = (y_bar - y).T.dot(X) / m return grad.flatten()
fb9c4eed387c6dbf3df012636a95e31eb1370da8
Omar-Hosni/Classes-Objects_Python
/main.py
1,337
3.625
4
class Building: #constructor def __init__(self, season, apartmentNumber, apartmentSize): self.season = season self.apartmentNumber = apartmentNumber self.apartmentSize = apartmentSize def rent_calc(self): base = 1000 season_buffer = 0 if self.season == "summer": season_buffer = 1.5 elif self.season == "winter": season_buffer = 1.1 elif self.season == "spring": season_buffer = 1.4 elif self.season == "autumn": season_buffer = 1.3 else: season_buffer = None if self.apartmentSize > 130: season_buffer += 0.1 total = base + season_buffer #String formatting print('The buffer is: %s ' % season_buffer) print('The total is: %s ' % total) return total def monthly_maintainance(self , rent_price): maintainance = 0 if rent_price > 3000: maintainance = 100 else: maintainance = 50 return maintainance lease_contract_1 = Building("summer", 4, 135) lease_contract_2 = Building("spring", 6, 100) lease_contract_1.rent_calc() print('the maintainance costs: %s' % lease_contract_1.monthly_maintainance(lease_contract_1.rent_calc()))
6318ea9e2d9f4d45165b6d4f7de22ac11fbf4549
Aasthaengg/IBMdataset
/Python_codes/p03361/s027135204.py
654
3.578125
4
h, w = map(int, input().split()) board = [[i for i in input()] for _ in range(h)] def check(i, j): if (j-1 >= 0): if(board[i][j-1] == "#"): return False if (j+1 < w): if(board[i][j+1] == "#"): return False if (i-1 >= 0): if(board[i-1][j] == "#"): return False if (i+1 < h): if(board[i+1][j] == "#"): return False return True def main(): for i in range(h): for j in range(w): if (board[i][j] == "#"): if(check(i,j)): return "No" return "Yes" if __name__ == '__main__': print(main())
03e3d70ca4f3b9006637c246e8038707bb23c553
JohannesCoolen221101/Make1.2.1
/rekenmachine.py
653
3.734375
4
#!/usr/bin/env python """ info about project here """ ... __author__ = "Johannes Coolen" __email__ = "johannes.coolen@student.kdg.be" __status__ = "development" def main(): getal1 = int(input("geef een natuurlijk getal")) getal2 = int(input("nu nog een alstublieft")) operator = input("wil je optellen(+) aftrekken(-) delen(/) of vermenigvuldigen(*)") if operator == '+': print(getal1 + getal2) elif operator == '-': print(getal1 - getal2) elif operator == '*': print(getal1 * getal2) elif operator == '/': print(getal1 / getal2) if __name__ == '__main__': # code to execute if called from command-line main()
92dbe18a1f985cb2d1e435f1bd44b4f522ee2f1a
talesritz/Learning-Python---Guanabara-classes
/Exercises - Module I/EX015 - Aluguel de Carros.py
648
3.953125
4
#Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60,00 por dia e R$0.15 por Km rodado. print('-=-'*8) print(' Aluguel de Carros') print('-=-'*8) print('\n') km = float(input('Digite quantos Km o carro percorreu: ')) dias = int(input('Por quantos dias o carro foi alugado? ')) print('\n========== Valores ==========') print('Distância percorrida: R$ {:.2f} ' .format(km*0.15)) print('Dias alugados: R$ {:.2f}' .format(dias*60)) print('Total a pagar: R$ {:.2f}' .format((km*0.15) + (dias*60)))
c27682e21572d35623c055c7bf2e0a6b34b34d60
AndresAcosta08/ExamenFinal_Metodos
/ejercicio2.py
562
3.78125
4
# Ejercicio 2 # Complete el siguiente codigo para recorrer la lista `x` e imprima # los numeros impares y que pare de imprimir al encontrar un numero mayor a 800 import numpy as np #Creo un rango muy grande, para correr multiples veces el codigo. for i in range (100000) #Para cada iteracion del codigo calculo un x, que sera un numero aleatorio. x= np.int_(np.random.random(100)*1000) #Si el numero es impar entonces lo imprimo if (x%2!=0): print x #Si el numero es superior a 800 creo un break para romper el ciclo del for. if (x>800): break
5572f5e8dc754e8df486d4cb895a716e0b04dc41
BrendanStringer/CS021
/Exam 2.0/Exam2.1.py
350
4.15625
4
# Create the function times_ten. # This will allow the user to input a number and output the result of that number times 10 def times_ten(number): # The multiplier for this situation MULTIPLIER = 10 # Perform calculations result = number * MULTIPLIER # Return the result return result result = times_ten(10) print(result)
0b5bcc48450a7f9ba2fcda6bccd8d10b6f87263c
starschen/learning
/introduction_MIT/10_2排序算法.py
2,041
3.84375
4
#encoding:utf8 #10.2排序算法 #选择排序 原书代码有点问题,这一段是自己写的 def selsort(l): for i in range(len(l)): for j in range(i+1,len(l)): if l[i]>l[j]: l[i],l[j]=l[j],l[i] return l # print selsort([2,5,8,6,3,7]) #归并排序 def merge(left,right,compare): '''left 和right是两个有序列表,返回两个列表组成的新有序列表''' result=[] i,j=0,0 while i<len(left) and j<len(right): if compare(left[i],right[j]): result.append(left[i]) i+=1 else: result.append(right[j]) j+=1 while i<len(left): result.append(left[i]) i+=1 while j<len(right): result.append(right[j]) j+=1 return result import operator def mergesort(l,compare=operator.lt): '''l列表,compare定义了元素的顺序,返回一个排序后的列表''' if len(l)<2: return l[:] else: middle=len(l)//2 left=mergesort(l[:middle],compare) right=mergesort(l[middle:],compare) return merge(left,right,compare) # print mergesort([2,5,8,6,3,7]) #把函数当做参数 排序人名列表 import string def lastnamefirstname(name1,name2): name1=name1.split(' ') name2=name2.split(' ') if name1[1]!=name2[1]: return name1[1]<name2[1] else: return name1[0]<name2[0] def fistnamelastname(name1,name2): name1=name1.split(' ') name2=name2.split(' ') if name1[0]!=name2[0]: return name1[0]<name2[0] else: return name1[1]<name2[1] # l=['Chris Terman','Tom Brady','Eric Grimson','Gisele Bundchen'] # new1=mergesort(l,lastnamefirstname) # print 'sorted by last name=',new1 # new2=mergesort(l,fistnamelastname) # print 'sorted by first name=',new2 # l=[3,5,2] # d={'a':12,'c':5,'b':'dog'} # print sorted(l) # print l # l.sort() # print l # print sorted(d) # d.sort() #error:dict object has no attribute 'sort' l=[[1,2,3],(3,2,1,0),'abc'] print sorted(l,key=len,reverse=True)
8982e7f09067d4869a0e8a9d481eff01fc8e46e5
PsychoLeo/Club_Informatique
/5-TheorieNombres/EratostheneSieve.py
673
3.84375
4
import sys import time def sieve(N, tableau): for i in range(2, N//2): if tableau[i]:#Si on tombe sur un nombre premiers for multiple in range(2*i, N, i): #Alors tous ses mutlitples tableau[multiple] = False # Ne sont pas des nombres premiers def affichage(N, tableau): for i in range(N): if tableau[i]: print(i, end = " | ") if sys.argv[1]: print(sys.argv[1]) N=int(sys.argv[1]) else: N=int(input("Calculons les nombres premiers jusquà N")) tableau = [False]+[True]*(N-1) start = time.time() sieve(N, tableau) print(f"Calcultated in {time.time()-start} seconds") if input("Print ? (y/n)") == "y": affichage(N, tableau)
3bf82e31edc2d4734bc6cf7994df2e4147179d79
WU-UAV-LiKang/src
/Source_code_tools_used/01_prototype/libs/Mazify/maze.py
9,977
3.671875
4
import numpy as np from numpy.random import random_integers as rand from draw_maze import ascii_representation from constants import * class Maze: def __init__(self, rows, columns): assert rows >= 1 and columns >= 1 self.nrows = rows self.ncolumns = columns self.board = np.zeros((rows, columns), dtype=WALL_TYPE) self.board.fill(EMPTY) self.temporal = [] self.coordinate = [] self.obstacles = [] def set_borders(self): self.board[0, :] = self.board[-1, :] = WALL self.board[:, 0] = self.board[:, -1] = WALL def print_coordinate(self): for x, y, x2, y2 in self.coordinate: print(x, y, x2, y2) def is_wall(self, x, y): assert self.in_maze(x, y) return self.board[x][y] == WALL def is_temporal(self, x, y): assert self.in_maze(x, y) return self.board[x][y] == TEMP def place_obstables(self): # place three moving obstacles obs_count = 0 boundary = 2 while True: rand_x = rand(2, self.ncolumns - 3) rand_y = rand(2, self.nrows - 3) is_valid = True for x in range(-boundary, boundary + 1): for y in range(-boundary, boundary + 1): temp_x = rand_x + x temp_y = rand_y + y if self.board[temp_x][temp_y] == WALL: is_valid = False if is_valid: obs_count += 1 self.set_wall(rand_x, rand_y) self.obstacles.append((rand_x, rand_y)) if obs_count > 2: #for x, y in self.obstacles: # self.unset_wall(x, y) break def scale_coordinate(self, x, y, x_min, y_min): # x_min: -2.5, y_min: 2.5 # x: 12, y: 12 length = float(self.ncolumns-1) height = float(self.nrows-1) size_x = abs(x_min) * 2 size_y = abs(y_min) * 2 ratio_x = x / length ratio_y = y / height new_x = (size_x * ratio_x) + x_min new_y = -(size_y * ratio_y) + y_min return new_x, new_y def translate_coordinate(self, x1, y1, x2, y2): nx1, ny1 = self.scale_coordinate(x1, y1, -2.5, 2.5) nx2, ny2 = self.scale_coordinate(x2+1, y2+1, -2.5, 2.5) unit = 0.2 # rx1: left, rx2: right rx1 = min(nx1, nx2) rx2 = max(nx1, nx2) # ry1: bottom, ry2: top ry1 = min(ny1, ny2) ry2 = max(ny1, ny2) if rx1 == rx2: rx2 += 0.01 if ry1 == ry2: ry2 += 0.01 return np.array([[rx1, ry1], [rx1, ry2], [rx2, ry2], [rx2, ry1]]) def translate_obs(self, x, y): nx1, ny1 = self.scale_coordinate(x, y, -2.5, 2.5) nx2 = nx1 + 0.1 ny2 = ny1 + 0.1 return np.array([[nx1, ny1], [nx1, ny2], [nx2, ny2], [nx2, ny1]]) def maze_to_numpy(self): obs = [] # append fixed obstacles for x1, y1, x2, y2 in self.coordinate: # test = self.translate_coordinate(10, 10, 12, 12) # print(test) # exit() numpy_coordinate = self.translate_coordinate(x1, y1, x2, y2) obs.append(numpy_coordinate) # manually add the room (boundary of map) obs.append( np.array([[-2.5, -2.5], [2.5, -2.5], [2.5, -2.47], [-2.5, -2.47]])) obs.append( np.array([[-2.5, 2.47], [2.5, 2.47], [2.5, 2.5], [-2.5, 2.5]])) obs.append( np.array([[-2.5, -2.47], [-2.47, -2.47], [-2.47, 2.47], [-2.5, 2.47]])) obs.append( np.array([[2.47, -2.47], [2.5, -2.47], [2.5, 2.47], [2.47, 2.47]])) # moving obstacles for x, y in self.obstacles: numpy_obs = self.translate_obs(x, y) obs.append(numpy_obs) return obs def clear_temporal(self): self.temporal = [] def t_wall(self, x, y): assert self.in_maze(x, y) self.board[x][y] = TEMP self.temporal.append((x, y)) def temporal_to_wall(self): for x, y in self.temporal: self.board[x][y] = WALL if len(self.temporal) > 1: minx = 1000 maxx = -1 miny = 1000 maxy = -1 for x, y in self.temporal: if x < minx: minx = x if x > maxx: maxx = x if y < miny: miny = y if y > maxy: maxy = y for x in range(minx, maxx + 2): for y in range(miny, maxy + 2): self.board[x][y] = WALL self.coordinate.append((minx, miny, maxx, maxy)) def unset_wall(self, x, y): assert self.in_maze(x, y) self.board[x][y] = EMPTY def set_wall(self, x, y): assert self.in_maze(x, y) self.board[x][y] = WALL def remove_wall(self, x, y): assert self.in_maze(x, y) self.board[x][y] = EMPTY def in_maze(self, x, y): return 0 <= x < self.nrows and 0 <= y < self.ncolumns def in_maze_inner(self, x, y): if not self.in_maze(x + 2, y): return False if not self.in_maze(x - 2, y): return False if not self.in_maze(x, y + 2): return False if not self.in_maze(x, y - 2): return False return True def wall_near(self, x, y): if self.board[x + 2][y] == WALL: return True if self.board[x - 2][y] == WALL: return True if self.board[x][y + 2] == WALL: return True if self.board[x][y - 2] == WALL: return True return False def satisfy(self): boundary = 2 startx = int(self.ncolumns * 0.15) starty = int(self.nrows * 0.15) endx = int(self.ncolumns * 0.85) endy = int(self.nrows * 0.85) # there should not wall for x in range(-boundary, boundary + 1): for y in range(-boundary, boundary + 1): temp_x = startx + x temp_y = starty + y temp_ex = endx + x temp_ey = endy + y if self.board[temp_x][temp_y] == WALL: return False if self.board[temp_ex][temp_ey] == WALL: return False return True def write_to_file(self, filename): f = open(filename, 'w') f.write(ascii_representation(self)) f.close() @staticmethod def load_from_file(filename): with open(filename, 'r') as f: content = f.readlines() # remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] xss = [] for line in content: xs = [] for c in line: if c == ' ': xs.append(EMPTY) elif c == 'X': xs.append(WALL) else: raise ValueError('unexpected character found: ' + c) xss.append(xs) maze = Maze(len(xss), len(xss[0])) for xs in xss: assert len(xs) == maze.ncolumns for i in range(maze.nrows): for j in range(maze.ncolumns): if xss[i][j] == EMPTY: maze.remove_wall(i, j) else: maze.set_wall(i, j) return maze @staticmethod def complete_maze(rows, columns): maze = Maze(rows, columns) for i in range(rows): for j in range(columns): maze.board[i][j] = WALL return maze @staticmethod def create_maze(rows, columns, seed=None, complexity=.5, density=.2): while True: rows = (rows // 2) * 2 + 1 columns = (columns // 2) * 2 + 1 c_adjust = 1.2 d_adjust = 0.8 if seed is not None: np.random.seed(seed) # Adjust complexity and density relative to maze size comp = int(complexity * (c_adjust * (rows + columns))) dens = int(density * ((rows // 2) * (columns // 2)) * d_adjust) width = 2 maze = Maze(rows, columns) maze.set_borders() # Make aisles for i in range(dens): maze.clear_temporal() x, y = rand(0, rows // 2) * 2, rand(0, columns // 2) * 2 if maze.in_maze_inner(x, y): if maze.wall_near(x, y): continue maze.set_wall(x, y) for j in range(comp): neighbours = [] if maze.in_maze(x - width, y): neighbours.append((x - width, y)) if maze.in_maze(x + width, y): neighbours.append((x + width, y)) if maze.in_maze(x, y - width): neighbours.append((x, y - width)) if maze.in_maze(x, y + width): neighbours.append((x, y + width)) if len(neighbours): nx, ny = neighbours[rand(0, len(neighbours) - 1)] # if not maze.is_temporal(nx, ny) and\ if not maze.is_wall(nx, ny): if maze.wall_near(nx, ny): maze.t_wall(nx, ny) maze.t_wall( nx + (x - nx) // 2, ny + (y - ny) // 2) x, y = nx, ny maze.temporal_to_wall() if maze.satisfy(): break else: del maze return maze
1a45df12db8f5a5f6157d8d870f065cd70d1d83b
patsonev/Python_Basics_homeworks
/sravnqvane_na_chisla.py
121
3.75
4
number_a = int(input()) number_b = int(input()) if number_a > number_b: print(number_a) else: print(number_b)
d65639c205a1843e32a2ea931b293a5c3935b45d
Rahonam/algorithm-syllabus
/array/majority_element.py
2,177
4.4375
4
def majority_element(arr:list): """ Find the majority element(element appears more than n/2 times) in given array Majority Element: If an element appears more than n/2 times in array where n is the size of the array. using: iteration, dictionary, time O(n), space O(n) Args: arr: array of integers Returns: integer: majority element, if exists string: "No majority", otherwise """ occurence_map = {} for i in arr: if i in occurence_map: occurence_map[i] += 1 else: occurence_map[i] = 1 max_element = max(occurence_map, key=lambda x: occurence_map[x]) if max_element > int(len(arr) / 2): return max_element else: return "No majority" def boyer_moore_majority(arr:list): """ Find the majority element in given array Majority Element: If an element appears more than n/2 times in array where n is the size of the array. using: iteration, dictionary, Boyer–Moore majority vote algorithm, time O(n), space O(1) Boyer-Moore algorithm: First iteration – Find the candidate element which could be a majority element. Second iteration – check the element(found in first iteration) count is greater than n/2 Args: arr: array of integers Returns: integer: majority element, if exists string: "No majority", otherwise """ max_element = arr[0] max_element_count = 1 for i in range(1, len(arr) - 1): if arr[i] == max_element: max_element_count += 1 else: max_element_count -= 1 if max_element_count == 0: max_element = arr[i] max_element_count = 1 max_element_count = 0 for i in arr: if i == max_element: max_element_count += 1 if max_element_count > int(len(arr) / 2): return max_element else: return "No majority" print(majority_element([1,3,1,4,1,6])) print(majority_element([1,3,5,5,5,5,4,1,5])) print(boyer_moore_majority([1,3,1,4,1,6])) print(boyer_moore_majority([1,3,5,5,5,5,4,1,5]))