blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
428fd8714cd7c2542af1000822bf90da9dd58847
linleysanders/algorithms
/Homework Week One (Average of Averages)/Linley Sanders Week One Homework.py
2,609
4.28125
4
# coding: utf-8 # # Lede Algorithms -- Assignment 1 # # In this assignment you will use a little algebra to figure out how to take the average of averages. # In[1]: import pandas as pd import matplotlib.pyplot as plt import requests get_ipython().run_line_magic('matplotlib', 'inline') # First, read in the titanic.csv data set. # In[2]: df = pd.read_csv("titanic.csv") df.head() # Compute the average survival rate (mean of the `survived` column) # In[3]: df['survived'].mean() # Now compute the average survival rates of the male and female 1st, 2nd, and 3rd class passengers (six groups in total) # In[31]: df.groupby(by='gender')['survived'].count() # In[32]: df.groupby(by='gender')['survived'].value_counts() # ## Male Survival Rate: 16.70% # ## Female Survival Rate: 66.30% # In[35]: 142/850 # In[34]: 307/463 # In[37]: df.groupby(by='pclass')['survived'].count() # In[36]: df.groupby(by='pclass')['survived'].value_counts() # ## First Class Survival Rate: 59.93% # ## Second Class Survival Rate: 42.5% # ## Third Class Survival Rate: 19.26% # In[38]: 193/322 # In[39]: 119/280 # In[40]: 137/711 # Compute the average of these six averages. Is it the same as the the overall average? # In[43]: #It's not the same as the overall average—it is higher (34.19+16.70+66.30+59.93+42.5+19.26)/(6) # How would you compute the overall average from the average of averages? Start with the formulas # # $$mean = \frac{\sum_{i=1}^N x_i}{N}$$ # # for the overall mean, where $x_i$ is data value $i$ and $N$ is the total number of values, and # # $$mean_k = \frac{\sum_{i=1}^{N_k} xk_i}{N_k}$$ # # is the mean of group $k$, where $xk_i$ is value $i$ of group $k$ and $N_k$ is the number of values in group $k$, and # # $$N = \sum_{i=1}^M N_k$$ # # relates the total number of values $N$ to the number of values in each of the $M$ groups. # # Your task is to derive a formula that computes $mean$ using only $mean_k$, the $N_k$, and $N$. Note: this question is not asking you to write code! Rather, you must answer two questions: # # - What is the correct formula? # - How can we derive this formula starting from the formulas above? # ## Answer / Response: # # The first formula is the calculation overall for mean. The second formula is the calculation for a group (a column), as the extra variable K. Big N is equal to the sum of the values, and Nk would give the total number of people in a column. I think the solution would be to take 1/6 of each percentage and # Now use this formula to calculate the overall mean. Does it match?
cb01fa3f3fea34c85dd2373c6130478be7cbde25
SuprovoDas/Dream_Work
/multiple_iinheritance.py
1,022
4.03125
4
"""class father: def height(self): print('height is 6 feet') class mother: def color(self): print('color is dark') class child(father,mother): pass c = child() c.height() c.color()""" class A(object): def __init__(self): self.a = 'a' print(self.a) super().__init__() class B(object): def __init__(self): self.b = 'b' print(self.b) super().__init__() class D(object): def __init__(self): self.d = 'd' print(self.d) super().__init__() class E(object): def __init__(self): self.e = 'e' print(self.e) super().__init__() class C(A,B,D,E): def __init__(self): super().__init__() self.c = 'c' print(self.c) o = C() print(C.mro()) #MRO = Method Resolution Order) """ polymorphism :- If a variable,object,method exhibit deffent in diffent context then it is called polymorphism.
cafb9aeb9a9da703325dc2979a1e21a098e56bb7
D-Code-Animal/CTI110
/P2T1_SalesPrediction_EatonStanley.py
311
3.53125
4
# CTI-110 # P2TI-Sales Prediction # Stanley J. Eaton Sr. # June 15, 2018 # Get the projected total sales. total_sales = float (input ('Enter the projected sales:')) # Calculate the profit as 23 precent of total sales. profit = total_sales * 0.23 # Display the profit. print ('The profit is $', format (profit, ',.2f'))
080664c2e54275b4268edb64b140559fa4d07f57
LiouYiJhih/Python
/cheap01_ Basic_operations.py
2,344
3.9375
4
# 註解的重要性 hourly_salary = 125 # 設定時薪 annual_salary = hourly_salary * 8 * 300 # 計算年薪 monthly_fee = 9000 # 設定每月花費 annual_fee = monthly_fee * 12 # 計算每月花費 annual_savings = annual_salary - annual_fee # 計算每年儲存金額 print(annual_savings) # 列出每年儲存金額 print("=====================") print("認識底線開頭或結尾的變數") # 變數名稱有前單底線,例如: _test ### 一種私有變數、函數或方法,可能是在測試中或一般應用在不想直接被調用的方法可以使用。 # 變數名稱有後單底線,例如: dict_ ### 主要目的是避免與Python的關鍵字或內建函數有相同名稱。 ### 舉例: max是求較大值函數、min是求較小值函數,若想建立max和min變數可以命名為max_和min_。 # 變數名稱前後有雙底線,例如: __test__ ### 保留給Python內建的變數或方法使用。 # 變數名稱有錢雙底線,例如: __test ### 這也是私有方法或變數命名,無法直接使用本名存取。 print("=====================") # 基本運算 四則運算 a = 5 + 6 print(a) b = 80 -10 print(b) c = 5 * 9 print(c) d = 9 / 5 print(d) # 餘數和整除 x = 9 % 5 # 餘數設定給變數x print(x) y = 9 // 2 # 整數結果設定給變數y print(y) x = 3 ** 2 # 3的平方 print(x) y = 3 ** 3 # 3的次方 print(y) # 多重指定 x = y = z = 10 print(x, y, z) a, b, c = 10, 20, 30 print(a, b, c) # 變數交換 x, y = 70, 80 print("Before:",x, y) x, y = y, x print("After:",x, y) # divmod(): 一次獲得商和餘數 z = divmod(9, 5) # 獲得元組值(1, 4),元組(Tuple) print(z) x, y = z # 將元組值設定給x和y print(x, y) # 刪除變數 del x # print(x) # 將一個敘述分成多行 a = b = c = 10 x = a + b + c + 12 print(x) y = a + \ b + \ c + \ 12 print(y) z =( a + b + c + 12 ) print(z) print("=====================") # 複利計算 money = 50000 * (1 + 0.015) ** 5 print("本金合是:", money) # 計算園面積和圓周長 PI = 3.14159 r = 5 print("圓面積:單位是平方公分") area = PI * r * r print(area) circumference = 2 * PI * r print("圓周長:單位是公分") print(circumference) print("=====================")
ea09333e3af913cd33bd6df2ecaf7d4b84525a71
pradloff/analysis-framework
/common/node.py
1,290
3.640625
4
class node(): def __init__(self,parents,children,__item__): self.__item__ = __item__ self.parents = [] self.add_parents(*parents) self.children = [] self.add_children(*children) #self.__ancestor__ = {} #self.__decscendants__ = {} def add_parents(self,*parents): for parent in parents: if parent not in self.parents: self.parents.append(parent) parent.add_children(self) def add_children(self,*children): for child in children: if child not in self.children: self.children.append(child) child.add_parents(self) def __call__(self): return self.__item__ """ def getDescendants(self): descendants = {} for child in self.__children__: descendants[child]=0 descendants.update(dict((key,val) for key,val in child.getDescendants().items() if key not in descendants)) #descendants.update( dict((key,val) for key,val child.getDescendants().items() if key not in descendants) ) for descendant in descendants.keys(): descendants[descendant]+= 1 return descendants def getProgenitors(self): progenitors = {} for parent in self.__parents__: progenitors.update( parent.getProgenitors() ) progenitors[parent]=0 for progenitor in progenitors.keys(): progenitors[progenitor]-= 1 return progenitors """
f21fd0a9ca55cf2b6a0d298ff7b25390e3bb5e50
jboenawan/MIS3615
/src/calc.py
1,066
3.96875
4
# print(2017 - 1998) # print(2**10) # minutes = 42 # seconds = 42 # # print('The time duration is', minutes * 60 + seconds, 'seconds.') # # r = 5 # jess = (4 / 3) * r ** 3 * math.pi # print(jess) # len_of_number = len(str(2 ** 1000000)) # How many digits in a really BIG number? # print(len_of_number) # # import random # # print(random.random()) # # print(random.choice(['Jess', 'Andrea', 'Lucy'])) import math def quadratic(a, b, c): discriminant = b ** 2 - 4 * a * c # calculate the discriminant if discriminant >= 0: # equation has solutions x_1 = (-b + math.sqrt(discriminant)) / (2 * a) x_2 = (-b - math.sqrt(discriminant)) / (2 * a) return x_1, x_2 else: print('No real number solution.') return None # solutions = quadratic(1, -2, 5) # # if solutions is not None: # print(solutions) a = float(input('please enter a number:')) b = float(input('please enter a number:')) c = float(input('please enter a number:')) solutions = quadratic(a, b, c) if solutions is not None: print(solutions)
9ac9210e2616b578f13b22d03315cb473e5e0c61
globality-corp/microcosm-resourcesync
/microcosm_resourcesync/toposort.py
1,825
3.765625
4
""" Topological sort. """ from collections import defaultdict def toposorted(resources): """ Perform a topological sort on the input resources. Resources are first sorted by type and id to generate a deterministic ordering and to group resouces of the same type together (which minimizes the number of write operations required when batching together writes of the same type). The topological sort uses Kahn's algorithm, which is a stable sort and will preserve this ordering; note that a DFS will produce a worst case ordering from the perspective of batching. """ # sort resources first so we have a deterministic order of nodes with the same partial order resources = sorted( resources, key=lambda resource: (resource.type, resource.id), ) # build incoming and outgoing edges nodes = { resource.uri for resource in resources } incoming = defaultdict(set) outgoing = defaultdict(set) for resource in resources: for parent in resource.parents: if parent not in nodes: # ignore references that lead outside of the current graph continue incoming[resource.uri].add(parent) outgoing[parent].add(resource.uri) results = [] while resources: remaining = [] for resource in resources: if incoming[resource.uri]: # node still has incoming edges remaining.append(resource) continue results.append(resource) for child in outgoing[resource.uri]: incoming[child].remove(resource.uri) if len(resources) == len(remaining): raise Exception("Cycle detected") resources = remaining return results
d333b5c8fa654a867c5e54f599f2ca5a5c68746d
zhezhe825/api_test
/cases/test_1.py
1,297
4.5
4
''' unittest框架:单元测试框架,也可做自动化测试,python自带的 unittest:管理测试用例,执行用例,查看结果,生成 html 报告(多少通过,多少失败 ) 自动化:自己的代码,验证别人的代码 大驼峰命名:PrintEmployeePaychecks() 小驼峰:printEmployeePaychecks() 下划线命名:print_employee_paychecks() 类:大驼峰命名 其他:小驼峰,下划线命名 class:测试的集合,一个集合又是一个类 unittest.TestCase:继承 继承的作用:子类继承父类(TestExample 继承 TestCase),父类有的,子类都有 ''' ''' self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") 断言失败可用:msg="。。。" 给出提示信息 .通过 F 失败:开发的BUG E:你自己的代码的BUG ''' import unittest # print(help(unittest)) # help:查看帮助文档 class TestExample(unittest.TestCase): def testAdd(self): # test method names begin with 'test' self.assertEqual((1 + 2), 3) self.assertEqual(0 + 1, 1) # self.assertEqual(0 + 1, 2, msg="失败原因:0+1 不等于 2!") def testMultiply(self): self.assertEqual((0 * 10), 0) self.assertEqual((5 * 8), 40) if __name__ == '__main__': unittest.main()
3375441b180ccb3af8ed21c1dc59918f1a9ad339
AMANGUPTA2000/ML_Projects
/Assignment_2/sum_diagonal.py
240
3.546875
4
import numpy as nm arr=nm.array([[1,2,3,4],[3,4,5,6],[6,7,8,9],[9,0,1,2]]) print(arr) arr_diagonal_element = arr.diagonal() print("\nDiagonal element:",arr_diagonal_element) print("\nSum of Diagonal elements:",nm.sum(arr_diagonal_element))
488db3e736f5b837e0dda27689d60d167734a963
jcastiblanco/mintic2022memories
/Reto1.py
1,025
3.8125
4
#Importación de modulos necesarios para librerias matematicas import decimal import math #******************************** #**Código Principal de ejecucion #******************************** # main () #Variables salarioBase=176 pcthorasExtras=1.25 horasExtras=0 pctbonificacion=0.065 salarioBase=0 salarioExtras=0 salarioBonificaciones=0 planDeSalud=0.025 aportePension=0.025 cajaCompensacion=0.04 esbonificiacion=0 salarioBase,horasExtras,esbonificiacion=input().split() salarioBase = float(salarioBase ) horasExtras= int(horasExtras) esbonificiacion= int(esbonificiacion) #Operaciones salarioExtras=horasExtras * ((salarioBase/176) * pcthorasExtras) salarioBonificaciones=esbonificiacion*(salarioBase * pctbonificacion) salarioTotal=round((salarioBase + salarioExtras + salarioBonificaciones),1) salarioDespuesDescuentos=round((salarioBase + salarioExtras + salarioBonificaciones)-(salarioTotal*0.09),1) #Resultado print(f"{salarioTotal} {salarioDespuesDescuentos}") #1000000 5 0
1e77dfff1db0174ed2a6695864eefecae7e1326c
xwj0813/lectcode
/com/xwj/code/No17letterCombinations.py
736
3.6875
4
# -*- coding:utf-8 -*- ''' 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合 ''' def letterCombinations(digits): dict = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']} result = [''] for digit in digits: str_digit = [] for char in dict[digit]: str_digit += [x + char for x in result] result = str_digit return result if __name__ == '__main__': digits = '235' result = letterCombinations(digits) print(result)
a7f6a75f106e7d866e56d5f4f2b522d99390d1ee
xwj0813/lectcode
/com/xwj/code/No4_MedianTwoSortedArray.py
2,382
3.546875
4
# -*- coding:utf-8 -*- ''' 给出两个有序的数字列表,长度分别为m,n。找到这两个列表中的中间值 ''' import time def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ # 创建新列表,并将所有元素初始为0 nums3 = [0] * (len(nums1) + len(nums2)) # 指定三个列表的索引,初始值为0 l_i, r_i, i = 0, 0, 0 # 当输入两个列表都还存在元素没进行比较的时候,循环进行对比 # 并将较小值放入新列表,同时较小元素的列表和新列表索引加一 while(l_i < len(nums1)) and (r_i < len(nums2)): if nums1[l_i] < nums2[r_i]: nums3[i] = nums1[l_i] l_i += 1 else: nums3[i] = nums2[r_i] r_i += 1 i += 1 # 当存在某一个列表所有元素已经比较完,即拍好了序 # 剩下那个列表剩下的值直接放入新列表对应位置即可 if l_i != len(nums1): nums3[i:] = nums1[l_i:] else: nums3[i:] = nums2[r_i:] # 小詹有话说:注意‘/’和‘//’的区别 /得到的是float,//得到的是int # 前者结果为float类型,后者为整除,结果为int型 len_3 = len(nums3) #‘%’为取模运算,即看长度是否被2整除,即看偶数还是奇数 if len_3 % 2 != 0: return float(nums3[(len_3 - 1) // 2]) return (nums3[len_3 // 2 - 1] + nums3[len_3 // 2]) / 2 def findMedianSortedArrays_1(nums1, nums2): # 简单粗暴将两个列表合成一个 for i in range(len(nums1)): # if nums1[i] in nums2: # # 如果表1 在表中含有就跳过 # continue # else: nums2.append(nums1[i]) # 重新排序 nums3 = sorted(nums2) len_3 = len(nums3) if len(nums3) % 2 != 0: # 奇数 return float(nums3[(len(nums3) - 1) // 2]) else: return (nums3[len_3 // 2 - 1] + nums3[len_3 // 2]) / 2 if __name__ == '__main__': nums1 = [1, 1] nums2 = [1, 2] start = time.time() result = findMedianSortedArrays(nums1, nums2) end = time.time() print(result, end - start) start_1 = time.time() result_1 = findMedianSortedArrays_1(nums1, nums2) end_1 = time.time() print(result_1, end_1 - start_1)
cbd8f93e9f6e1adbeebe0d612865c3d306ada0a1
ritaly/python-6-instrukcje-warunkowe
/Odpowiedzi/2.py
988
4.125
4
# -*- coding: utf8 -*- """ Do kalkulatora BMI z lekcji "Python 1 zabawy w konsoli" dodaj sprawdzanie czy BMI jest prawidłowe Niedowaga | < 18,5 Waga normaln | 18,5 – 24 Lekka nadwaga | 24 – 26,5 Nadwaga | > 26,5 W przypadku nadwagi sprawdź czy występuje otyłość: Otyłość I stopnia | 30 – 35 Otyłość II stopnia | 30 – 40 Otyłość III stopnia | > 40 """ print("Podaj wagę w kg: ") weight = float(input()) print("Podaj wzrost w cm: ") height = float(input())/100 BMI = weight / (height ** 2) print("Twoje bmi wynosi:", round(BMI, 2)) if (BMI < 18.5): print("Niedowaga") elif (18.5 <= BMI < 24): print("Waga prawidłowa") elif (24 <= BMI < 26.5): print("Lekka nadwaga") else: print("Nadwaga") if (30 >= BMI > 35): print("Otyłość I stopnia") elif (35 >= BMI > 40): print("Otyłość II stopnia") else: print("Otyłość III stopnia")
b7fe479f010694f71b4dbc5df0e07cd3a3c08449
DMRathod/_RDPython_
/Simple_estimation_CrowdComputing.py
894
3.609375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 12:53:40 2019 @author: Dharmraj Rathod """ from statistics import mean #from scipy import stats #let we have the bottle filled with marbels and we have to guess how many number of marbles are #there in the bottle """total number of marbles in the bottle is 36""" #implementation of trim_mean function from scipy Guess = [30,35,20,15,40,45,38,45,50,50,70,37,15,55,25,28,26,28,20,30] #for guess we use the trimmed percentage%(should be in 100) def Rdtrim_mean(percentage,Guess): if(percentage > 100 or Guess == []): print("Please Enter the valid Arguments") percentage = percentage/100 Guess.sort() trimmed_value =int( percentage*len(Guess) ) #m = stats.trim_mean(Guess,0.1) Guess = Guess[trimmed_value:] Guess = Guess[:len(Guess)-trimmed_value] print("Actual Value May Near About = ",mean(Guess)) #print(m)
6f3c61f8c2d26f3e112b9853319633d0aa5c2cde
DMRathod/_RDPython_
/Coding Practice/Basic Maths/Factorial.py
179
4.09375
4
def fact(number): if(number <=1): return 1 else: return (number * fact(number-1)) number = int(input("Enter number for factorial:")) print(fact(number))
976f3ae5ea8e924d2fd0838cdfbf5981a0195e48
DMRathod/_RDPython_
/Coding Practice/Basic Maths/FindMeetingRoomlist.py
1,089
3.734375
4
# meeting room details which is dictionary of room number as key and value is list of two values starting and ending time of the meeting # OccupiedRoomDetails = {0 : ["9AM", "11AM"], 1: ["10AM", "12AM"], 2: ["11AM", "12AM"], 3: ["9AM", "10AM"]} # Assuming requested meeting is only of 1 hour. def FindMeetingRoomlist(starttime, endtime): arr = [[1, 1, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0]] hour_dict = {"9AM" : 0, "10AM" : 1, "11AM" : 2, "12AM" : 3, "1PM" : 4, "2PM" : 5, "3PM" : 6, "4PM" : 7, "5PM" : 8, "6PM" : 9} result = [] for i in range(len(arr)): cnt = 0 hours = (hour_dict[endtime] - hour_dict[starttime]) j = hour_dict[starttime] while(cnt < hours and (arr[i][j] == 0)): cnt += 1 if(j < 9): j += 1 else: break if(cnt == hours): result.append(i+1) return result print(FindMeetingRoomlist("1PM", "2PM")) #[3, 4, 6, 8]
61a496dde5f1d6faa1dfb14a79420f3730c0727f
DMRathod/_RDPython_
/Coding Practice/Basic Maths/LeapYear.py
441
4.21875
4
# leap year is after every 4 years, divisible by 4. # Every Century years are not leap years means if it is divisible by 100. # we need to confirm if it is divisible by 400 or not. year = int(input("Enter The Year :")) if(year%4 == 0): if(year%100 == 0): if(year%400 == 0): print(str(year) + "is Leap Year") else: print(str(year)+ "is Leap Year") else: print(str(year) + " is NOT Leap Year")
1d9d07543fdcded06e83687de0279e2660a3c53f
DMRathod/_RDPython_
/Coding Practice/Sorting/SS.py
532
3.671875
4
ns = [4, 5, 1, 22] # selection sort will just find the one element and put that element at its right position # here i have taken max element and putting at its right psition each time in each iteration def SSort(ns): for i in range(len(ns)): mx = ns[0] j = 1 k = 0 while(j < len(ns)-i): if(mx < ns[j]): mx = ns[j] k = j j += 1 temp = ns[j-1] ns[j-1] = ns[k] ns[k] = temp return ns print(SSort(ns))
4e2950045c5f2f36d9655585f48f5d9260ce1a6b
rwinklerwilkes/Python
/knn.py
2,210
3.703125
4
#A short messy implementation of a 2-dimensional kth nearest neighbor algorithm import math class Point: def __repr__(self): return "Point" def __str__(self): return "x1: %d\nx2: %d\ny1: %s\n" %(self.x1,self.x2,self.y1) def __init__(self, x1, x2, y1): self.x1 = x1 self.x2 = x2 self.y1 = y1 def dist(point1, point2): term1 = (point2.x2-point1.x1)**2 term2 = (point2.x2-point1.x1)**2 return math.sqrt(term1+term2) #make sure that I actually understand what's going on here #I mean, I wrote it, but the off-by-one error took a while to fix def knn(k, point, pointset): nnset = [0 for i in range(k)] to_fill = 0 for p in pointset: curdist = dist(point,p) #if the distance is less than the kth closest, put it in order if to_fill < len(nnset): #insert in the proper spot j = to_fill while j > 0 and curdist < nnset[j-1][1]: #shift up by one and decrement nnset[j] = nnset[j-1] j = j-1 nnset[j] = (p,curdist) to_fill = to_fill + 1 elif curdist < nnset[k-1][1]: insert((p,curdist),nnset) return nnset #this doesn't seem to be doing what I want it to def insert(point, pointset): #assume pointset is in decreasing order #assume the values in pointset are stored as (point, distance) #assume point is passed as (point,distance) hole = len(pointset) while hole > 0 and point[1] < pointset[hole-1][1]: hole = hole - 1 if hole > 0: pointset[hole] = pointset[hole - 1] pointset[hole] = point def guesstype(point,k,pointset): k_set = knn(k,point,pointset) types = {} for i in range(len(k_set)): curpoint = k_set[i][0] if curpoint.y1 in types: types[curpoint.y1] = types[curpoint.y1] + 1 else: types[curpoint.y1] = 1 alltypes = [(k,v) for (k,v) in types.items()] sorted(alltypes,key =lambda kv: kv[1]) return alltypes[len(alltypes)-1][0] points = [Point(1,4,"a"),Point(1,3,"a"),Point(-2,6,"b"),Point(3,5,"c"),Point(-1,7,"a"),Point(4,-3,"b")] p = Point(2,3,"u")
406a2927197d804de0300c98c678d44d90d8155d
cpowicki/Settlers-Of-Catan-Generator
/devcards.py
591
3.5
4
from random import shuffle class developmentCard: def __init__(self, type): self.type = type class deck: def __init__(self): self.cards = [] for i in range(19): self.cards.append(developmentCard('Knight')) for i in range(5): self.cards.append(developmentCard('Victory Point')) for i in range(2): self.cards.append(developmentCard('Year of Plenty')) self.cards.append(developmentCard('Monopoly')) self.cards.append(developmentCard('Road Builder')) shuffle(self.cards)
529ed8b188e4ecb5a05d28a5b431150aae425239
Sakina28495/Fashion
/demo.py
215
3.53125
4
def codemaker(urstring): output=list(urstring) print(output) for index,letter in enumerate(urstring): for vowels in 'aeiou': if letter==vowels: output[index]='x' return output print(codemaker('Sammy'))
3456da0d36a1771bce68108957a7e6713aea83b4
eltobito/devart-template
/project_code/test2.py
515
3.828125
4
import Image picture = Image.open("picture.jpg") # Get the size of the image width, height = picture.size() # Process every pixel for x in width: for y in height: current_color = picture.getpixel( (x,y) ) print current_color #################################################################### # Do your logic here and create a new (R,G,B) tuple called new_color #################################################################### picture.putpixel( (x,y), new_color)
7dd133e44d846b84c1cda13c84ff3dc50aed1148
jadynk404/CMPT120-Project
/dictionary.py
1,169
3.984375
4
#Worked with Emmanuel Batista def main(): title = "Interactive Dictionary" print(title) myFile = input("Please input the name of your file: ").strip() myFile = myFile.lower() with open(myFile, "r") as myFile: #reads file and assigns value to variables dictionary = myFile.readlines() word1 = dictionary[0].strip() def1 = dictionary[1].strip() word2 = dictionary[2].strip() def2 = dictionary[3].strip() inDictionary = { word1 : def1, word2 : def2 } x = 1 while x==1: #searches txt file for user input uinput = "Please input a word you would like to have defined: " prompt = input(uinput).strip() prompt = prompt.lower() if prompt == word1: print(inDictionary[word1]) elif prompt == word2: print(inDictionary[word2]) elif prompt == "": x = 0 else: invalid = "I'm sorry. This word is not stored in our dictionary." print(invalid) x = 1 def copyrightt(): c = "This file was created by Jadyn Kennedy 4/27/2020" main() copyrightt()
7db722bc3d5e417139bb055937e9315289f90b52
cgraaaj/PracticeProblems
/Add two numbers as a linked list/main.py
1,176
3.796875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution: result = None def addTwoNumbers(self, l1, l2, c=0): v1 = [] v2 = [] res = [] while l1: v1.append(l1.val) v2.append(l2.val) l1 = l1.next l2 = l2.next v1.reverse() v2.reverse() v1 = int("".join([str(integer) for integer in v1])) v2 = int("".join([str(integer) for integer in v2])) res = [int(i) for i in str(v1 + v2)] res.reverse() for v in res: self.insert(v) return self.result def insert(self,data): node = ListNode(data) if self.result is None: self.result = node return n = self.result while n.next is not None: n= n.next n.next = node l1 = ListNode(2) l1.next = ListNode(4) l1.next.next = ListNode(3) l2 = ListNode(5) l2.next = ListNode(6) l2.next.next = ListNode(4) result = Solution().addTwoNumbers(l1, l2) while result: print(result.val), result = result.next
fbb3938b667cba8afe5144c023cacbd833028f03
crashtack/exercism
/python/clock/clock.py
1,144
4.34375
4
class Clock(object): """ A Clock class that ignores date """ def __init__(self, hours=0, minutes=0): """ Initialize the Clock object """ self.hours = hours % 24 self.minutes = minutes self.time_min = (self.hours * 60) + self.minutes self.time_min = self.time_min % 1440 def add(self, minute=0): """ Add minutes to the time and check for overflow """ self.time_min += minute self.time_min = self.time_min % 1440 return self.__str__() def __eq__(self, other): """ Check if time_min is equal """ if isinstance(other, self.__class__): return self.time_min == other.time_min else: return False def __ne__(self, other): """ Check if time_min is not equal """ return not self.__eq__(other) def __hash__(self): """ Return a hash of the time value """ return hash(self.time_min) def __str__(self): """ Returns the hh:mm time format """ return '{:02d}:{:02d}'.format( int(self.time_min / 60) % 24, self.time_min % 60 )
11aad31a77cdbca35a0961b5cfb1c46d56c438c4
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/11-input-2.py
562
4.03125
4
# Formulamos los mandatos que debe cumplir el usuario pregunta = '\nAgrega un numero y te dire si es par o impar ' pregunta += '(Escribe "Cerrar o cerrar" para salir de la aplicacion) ' # Variable booleana que mantendra el while iterandose preguntar = True while preguntar: numero = input(pregunta) if numero == "Cerrar" or numero == "cerrar": preguntar = False else: numero = int(numero) if numero % 2 == 0: print(f'El numero {numero} es par') else: print(f'El numero {numero} es impar')
f877815460bf804c8756d2dbb49cbe2cea568e10
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/14-clases-5.py
2,681
3.9375
4
class Restaurante: def __init__(self, nombre, categoria, precio): # Por defecto estas variables estan publicas # self.nombre = nombre # self.categoria = categoria # self.precio = precio # Para hacerlas PROTECTED unicamente al inicio del nombre # del atributo le agregamos un guion bajo # self._nombre = nombre # self._categoria = categoria # self._precio = precio # Para hacerlas PRIVATE unicamente al inicio del nombre # del atributo le agregamos doble guion bajo self.__nombre = nombre self.__categoria = categoria self.__precio = precio # Getters def get_nombre(self): return self.__nombre def get_categoria(self): return self.__categoria def get_precio(self): return self.__precio # Setters def set_nombre(self, nombre): self.__nombre = nombre def set_categoria(self, categoria): self.__categoria = categoria def set_precio(self, precio): self.__precio = precio def mostrar_informacion(self): print( f'Nombre: {self.__nombre} \nCategoria: {self.__categoria} \nPrecio: {self.__precio}\n') # Polimorfismo es la habilidad de tener diferentes comportamientos # basado en que subclase se esta utilizando, relacionado muy # estrechamente con herencia. class Hotel(Restaurante): def __init__(self, nombre, categoria, precio, alberca): # Hacemos referencia a la clase padre super().__init__(nombre, categoria, precio) # Aqui se aplica el polimorfismo, ya que este atributo # unicamente existe y se utiliza al momento de utilizar # la clase Hotel self.__alberca = alberca # Agregamos un metodo que solo existe en el Hotel # Aqui se aplica el polimorfismo, ya que este comportamiento # unicamente existe y se utiliza al momento de utilizar # la subclase Hotel def get_alberca(self): return self.__alberca def set_alberca(self, alberca): self.__alberca = alberca # Reescribir un metodo (debe llamarse igual) def mostrar_informacion(self): # Se puede utilizar tanto self o super para hacer referencia a la clase padre: # super().get_nombre() o self.get_nombre() # super().get_categoria() o self.get_categoria() # super().get_precio() o self.get_precio() print( f'Nombre: {super().get_nombre()} \nCategoria: {self.get_categoria()} \nPrecio: {self.get_precio()} \nAlberca: {self.__alberca}\n') print('\n') hotel = Hotel('Cadena de Hoteles Dreams', '5 Estrellas', 250, 'Si') hotel.mostrar_informacion()
11743b0257a83b0df21ab3daadcb2483468eaa83
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/05-numeros-2.py
401
3.828125
4
def suma(a=0, b=0): print(a + b) suma(2, 3) suma(4, 1) suma(8, 12) suma() def resta(a=0, b=0): print(a - b) resta(2, 3) resta(4, 1) resta(8, 12) resta() def multiplicacion(a=0, b=0): print(a * b) multiplicacion(2, 3) multiplicacion(4, 1) multiplicacion(8, 12) multiplicacion() def division(a=0, b=1): print(a / b) division(2, 3) division(4, 1) division(8, 12) division()
87267ed67fb71ac07755fff6f81fb02f2f7b4a95
miguelencastillogar/SeleniumPythonGitJenkinsAllureReporting
/Ejemplos_Python/10-diccionarios-1.py
1,528
3.875
4
# Creando un diccionario (objeto) simple cancion = { # llave : valor (Para agregar mas valores los separamos por comas) 'artista': 'Metallica', 'cancion': 'Enter Sandman', 'lanzamiento': 1992, 'likes': 3000 } # Imprimir todos los valores print(cancion) # Acceder a los elementos del diccionario print(cancion['artista']) print(cancion['lanzamiento']) # Mezclar con un string y tomando en cuenta que si procedemos # de esta manera: print(f'Estoy escuchando {cancion['artista']}') # obtendremos un error y siendo la unica solucion asignar el # valor del diccionario (objeto) a una variable y luego # mezclarla con un String. artista = cancion['artista'] print(f'Estoy escuchando a {artista}') # Imprimir todos los valores antes de agregar nuevo valor print(cancion) # Agregar nuevos elementos # debido a que la nueva propiedad no existe, pues automaticamente la grega cancion['palylist'] = 'Heavy Metal' # Imprimir todos los valores despues de agregar nuevo valor print(cancion) # Imprimir todos los valores antes de modificacion print(cancion) # Agregar nuevos elementos # debido a que la propiedad existe, pues modifica su valor cancion['cancion'] = 'Seek & Destroy' # Imprimir todos los valores despues de modificacion print(cancion) # Imprimir todos los valores antes de eliminar propiedad print(cancion) # Agregar nuevos elementos # debido a que la propiedad existe, pues modifica su valor del cancion['lanzamiento'] # Imprimir todos los valores despues de eliminar propiedad print(cancion)
0f9b703805d7afabd6a9d0313076f003f0d16b3a
bobbyscharmann/flypy
/examples/main.py
714
3.796875
4
from flypy.neural_networks.activation_functions import Sigmoid, ReLU from flypy.neural_networks import NeuralNetworkTwoLayers import numpy as np l = ReLU() #l.plot(-10, 10, derivative=False) print("Hello world.") nn_architecture = [ {"input_dim": 2, "output_dim": 4}, #{"input_dim": 4, "output_dim": 6}, #{"input_dim": 6, "output_dim": 6}, #{"input_dim": 6, "output_dim": 4}, {"input_dim": 4, "output_dim": 1}, ] X = np.asarray([[0, 0], [0, 1], [1, 0], [1,1]]).T Y = np.asarray([[0], [1], [1], [0]]) nn = NeuralNetworkTwoLayers(X=X, Y=Y, nn_architecture=nn_architecture, activation=Sigmoid) nn.train(X, Y)
1210ad4c30493aefaa6585472991a79894bdae58
bobbyscharmann/flypy
/flypy/reinforcement_learning/cartpole/random_agent.py
783
3.5
4
"""Implementation of the OpenAI Gym CartPole exercise with a random sampling of the action space. In other words, a vey simplistic (or dumb) agent)""" import gym env = gym.make("CartPole-v0") env.reset() # Couple of variables for knowing when the episode is over done: bool = False # Keeping track of total aware and steps total_reward: float = 0 steps: int = 0 # Iterate until the episode is over while not done: # Step the environment choosing a random action from the Environment action space state, reward, done, info = env.step(action=env.action_space.sample()) # Accumulate steps and awards steps += 1 total_reward += reward env.render() # Print some general information about the episode print(f"Total Reward in {total_reward} in {steps} steps.")
a899cbea277c1183228ac5f7396dce5347c69279
numbertheory/nanogenmo
/verb.py
991
3.5
4
"""Get a random verb, from a given tense""" import random def get(tense): """ Get a verb in the right tense """ verbs = {'past': ['spoke', 'baked', 'competed', 'smoked', 'switched', 'unlocked'], 'present': ['speaks', 'bakes', 'competes', 'smokes', 'switches', 'unlocks'], 'future': ['speak', 'bake', 'compete', 'smoke', 'switch', 'unlock'], 'past_perfect': ['spoken', 'baked', 'competed', 'smoked', 'switched', 'unlocked'], 'future_perfect': ['spoken', 'baked', 'competed', 'smoked', 'switched', 'unlocked']} if tense == 'future': helper = ['will', ''] elif 'future_perfect': helper = ['will', 'have'] elif 'past_perfect': helper = ['had', ''] else: helper = ['', ''] return helper, random.choice(verbs[tense])
deb0106dadea39101d8c40357c3f41f9383a9937
GarryK97/Python
/Hashtable/Task5.py
2,715
4.4375
4
from Task3 import HashTable def read_file_removesp(file_name): """ Read a text file and convert it to a list of words without any special characters. :param file_name: File to read :return: the list of words """ f = open(file_name, 'rt', encoding='UTF8') file_list = [] for line in f: line = line.strip() # Remove whitespaces line = line.split(" ") # Split by words for i in range(len(line)): word_nosp = "" # String that will store word with no special character line[i] = line[i].lower() # Lower the word to make search easy for char in line[i]: # for each character in word, if char.isalpha(): # if the character is not special character (if it is alphabet), word_nosp += char # Add it to word_nosp if word_nosp != "": # To prevent adding white spaces and already existing words file_list.append(word_nosp) # Append the word with no special character f.close() return file_list book1 = read_file_removesp("Book1.txt") book2 = read_file_removesp("Book2.txt") book3 = read_file_removesp("Book3.txt") book_hashtable = HashTable(399989, 1091) # Making a hash table for books in [book1, book2, book3]: for word in books: try: count = book_hashtable[word] # if the word exists in hash table, count will store the value of it book_hashtable[word] = count + 1 # + 1 count except KeyError: book_hashtable[word] = 1 # If the word does not exist in hash table, it means a new word needs to be added # Making a non-duplicate words list words_list = [] for books in [book1, book2, book3]: for word in books: if word not in words_list: words_list.append(word) # Finding Maximum max_count = 0 max_word = "" for word in words_list: if book_hashtable[word] > max_count: # if word count > current maximum word count, max_count = book_hashtable[word] # Change to new max count and word max_word = word # Finding common, uncommon, rare words common_words = [] uncommon_words = [] rare_words = [] for word in words_list: # Zipf's law in simple python code if book_hashtable[word] > (max_count / 100): common_words.append(word) elif book_hashtable[word] > (max_count / 1000): uncommon_words.append(word) else: rare_words.append(word) print("Number of common words : " + str(len(common_words))) # Prints the result print("Number of uncommon words : " + str(len(uncommon_words))) print("Number of rare words : " + str(len(rare_words)))
0d471841786f140724e55f0452db3469f9043be7
GarryK97/Python
/Algorithms/Dijkstra&Bellman-Ford.py
13,153
3.640625
4
import heapq """ Graph implementation for best_trades """ class Trade_Graph: def __init__(self, num_vertices): """ Initialize Graph object :param num_vertices: Total number of vertices :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V) V = Total number of vertices in graph """ self.vertices = [None for x in range(num_vertices)] for i in range(num_vertices): self.vertices[i] = Trade_Vertex(i) def add_edge(self, edge): """ Adds edge to each vertex, by using Edge object :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ vertex = self.vertices[edge.u] vertex.add_edge(edge) """ Vertex implementation for best_trades """ class Trade_Vertex: def __init__(self, id): """ Initialize Vertex object :param id: id of vertex :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.id = id self.edges = [] # Stores all the edges of a vertex def add_edge(self, edge): """ adds an edge to this vertex :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.edges.append(edge) """ Edge implementation for best_trades """ class Trade_Edge: def __init__(self, u, v, w): """ Initialize Edge object :param u: Source Vertex (Start Vertex) id :param v: Destination Vertex (End Vertex) id :param w: Weight of the edge :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.u = u # Source self.v = v # Destination self.w = w # Exchange amount def best_trades(prices, starting_liquid, max_trades, townspeople): """ Calculates the best trade with the given max_trades, using Bellman-Ford algorithm :param prices: List of prices of each Liquid :param starting_liquid: Starting Liquid ID :param max_trades: Maximum number of trades :param townspeople: List of Lists, Trades offered by each people :return: the Optimal Profit found :Complexity: Best Time: O(TM), Worst Time: O(TM), Auxiliary Space: O(TM) T = Total number of Trade offers M = Max_trades """ a_graph = Trade_Graph(len(prices)) # Initialize Graph by number of liquids. So, vertex = each liquid # Adds all the trade offers as edges to the graph for people in townspeople: for offer in people: u = offer[0] v = offer[1] w = offer[2] a_graph.add_edge(Trade_Edge(u, v, w)) # Initialize a table for Bellman-Ford algorithm, the table will store the optimal amount of each liquid amount = [[float("-inf") for i in range(max_trades+1)] for j in range(len(prices))] amount[starting_liquid][0] = 1 # Starts Bellman-Ford algorithm, repeat Max_trades time for i in range(1, max_trades+1): for liquid in amount: # Copy the previous i liquid[i] = liquid[i-1] for vertex in a_graph.vertices: for edge in vertex.edges: # Relax all the edges price_stored = prices[edge.v] * (amount[edge.v][i-1]) price_new = prices[edge.v] * (amount[edge.u][i-1] * edge.w) if price_stored < price_new: # If new optimal price is found, replace the table. amount[edge.v][i] = amount[edge.u][i-1] * edge.w # Gets the maximum price using the table obtained. max_price = 0 for i in range(len(amount)): if max_price < amount[i][-1] * prices[i]: max_price = amount[i][-1] * prices[i] return round(max_price) # ============================= Q3 ============================ """ Graph implementation for opt_delivery """ class Graph: def __init__(self, num_vertices): """ Initialize Graph object :param num_vertices: Total number of vertices :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(V) V = Total number of vertices in graph """ self.vertices = [None for x in range(num_vertices)] for i in range(num_vertices): self.vertices[i] = Vertex(i) def add_edges_list(self, edges_list): """ Gets List of edges in (u, v, w) format and adds all the edge to this graph :param edges_list: List of edges in (u, v, w) format :Complexity: Best Time: O(E), Worst Time: O(E), Auxiliary Space: O(1) E = Total number of Edges """ for edge in edges_list: u = edge[0] v = edge[1] w = edge[2] vertex = self.vertices[u] vertex.add_edge(Edge(u, v, w)) # Adds Undirected edge, simply swap u and v vertex2 = self.vertices[v] vertex2.add_edge(Edge(v, u, w)) def get_vertex_byid(self, id): """ Gets the vertex by using its id :param id: Vertex id to get :return: a Vertex with matching id :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ return self.vertices[id] def reset_vertices(self): """ Reset the status of all the vertices in this graph :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(1) V = Total number of vertices in graph """ for vertex in self.vertices: vertex.previous = None vertex.cost = float("inf") """ Vertex implementation for opt_delivery """ class Vertex: def __init__(self, id): """ Initialize Vertex object :param id: the id of Vertex :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.id = id self.edges = [] self.previous = None self.cost = float("inf") def add_edge(self, edge): """ Adds an edge to this vertex, using Edge object :param edge: Edge object to add :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.edges.append(edge) """ Edge implementation for opt_delivery """ class Edge: def __init__(self, u, v, w): """ Initialize Edge object :param u: Source Vertex (Start Vertex) id :param v: Destination Vertex (End Vertex) id :param w: Weight of the edge :Complexity: Best Time: O(1), Worst Time: O(1), Auxiliary Space: O(1) """ self.u = u # Source self.v = v # Destination self.w = w # Exchange amount def opt_delivery(n, roads, start, end, delivery): """ Finds the optimal cost of going to 'end' city from 'start' city. :param n: Number of cities :param roads: List of tuples (u, v, w), which represents a road :param start: the starting city :param end: the destination city :param delivery: a tuple (u, v, p) represents a delivery. U = pick-up city, V = Delivery Destination, P = Profit of the delivery :return: (Optimal cost, Optimal Path) found :Complexity: Best Time: O(V^2), Worst Time: O(V^2), Auxiliary Space: O(V) V = Total number of vertices in graph """ def update_heap(graph, min_heap): """ Updates the heap when the costs of vertices are changed. :param graph: Graph object :param min_heap: heap to update :Complexity: Best Time: O(V), Worst Time: O(V), Auxiliary Space: O(1) V = Total number of vertices in graph """ for i in range(len(min_heap)): vertex_id = min_heap[i][1] vertex = graph.vertices[vertex_id] min_heap[i] = (vertex.cost, vertex.id) heapq.heapify(min_heap) def backtrack_path(graph, start, end): """ Backtrack the previous id of vertices and reconstruct the optimal path. :param graph: Graph object :param start: the source vertex id :param end: the destination vertex id :return: Reconstructed Path, using backtracking :Complexity: Best Time: O(1), Worst Time: O(V), Best Auxiliary Space: O(1), Worst Auxiliary Space: O(V) V = Total number of vertices in graph """ if start == end: # If same start and end, there will be no previous. So return directly to prevent error return [end] path = [] path.insert(0, end) previous_vertex_id = graph.vertices[end].previous previous_vertex = graph.vertices[previous_vertex_id] while previous_vertex_id != start: path.insert(0, previous_vertex_id) previous_vertex_id = graph.vertices[previous_vertex.id].previous previous_vertex = graph.vertices[previous_vertex_id] path.insert(0, start) return path def find_lowest_cost(graph, start, end): """ Finds the optimal path that requires the lowest travelling cost from start to end, using Dijkstra algorithm :param graph: Graph object :param start: the source vertex id :param end: the destination vertex id :return: Optimal cost and Optimal path found :Complexity: Best Time: O(V^2), Worst Time: O(V^2), Auxiliary Space: O(V) V = Total number of vertices in graph """ graph.reset_vertices() # Resets the status of all the vertices in the graph before computes minheap = [] # a list to implement min heap # Initialize the min heap. Each element is a tuple (cost, vertex_id) for vertex in graph.vertices: if vertex.id == start: minheap.append((0, start)) vertex.cost = 0 else: minheap.append((float("inf"), vertex.id)) heapq.heapify(minheap) # Make the list as min heap, O(V) time complexity while len(minheap) > 0: # = Visit every vertex in the graph, O(V) time complexity current_cost, current_vid = heapq.heappop(minheap) current_vertex = graph.get_vertex_byid(current_vid) for edge in current_vertex.edges: # Go every edge of a vertex discovored_vertex = graph.vertices[edge.v] discovored_cost = discovored_vertex.cost if current_cost + edge.w < discovored_cost: # if a new optimal cost is found, replace it discovored_vertex.cost = current_cost + edge.w discovored_vertex.previous = current_vertex.id # Store the previous vertex to reconstruct path later. update_heap(graph, minheap) # Updates the heap after the change of the costs of vertices. O(V) time complexity optimal_cost = graph.vertices[end].cost # Gets the optimal cost optimal_path = backtrack_path(graph, start, end) # Reconstruct the optimal path return optimal_cost, optimal_path # ====== Actual Codes for opt_delivery a_graph = Graph(n) # Initialize a graph. So, Cities = vertices a_graph.add_edges_list(roads) # Adds roads as edges. So, Roads = Edges # Calculates the optimal cost and path without delivery optimal_cost_nodelivery, optimal_path_nodelivery = find_lowest_cost(a_graph, start, end) # Calculates the optimal cost and path of going start to pick-up city optimal_cost_to_pickup, path1 = find_lowest_cost(a_graph, start, delivery[0]) # Calculates the optimal cost and path of going pick-up to delivery destination city optimal_cost_to_deliver, path2 = find_lowest_cost(a_graph, delivery[0], delivery[1]) # # Calculates the optimal cost and path of going delivery destination city to end city optimal_cost_to_end, path3 = find_lowest_cost(a_graph, delivery[1], end) # Sum up the cost and path of performing delivery optimal_cost_delivery = (optimal_cost_to_pickup + optimal_cost_to_deliver + optimal_cost_to_end) - delivery[2] optimal_path_delivery = path1[:-1] + path2 + path3[1:] # Slicing to prevent adding same path again # Compare optimal cost of performing delivery and no delivery. if optimal_cost_delivery >= optimal_cost_nodelivery: final_optimal_cost = optimal_cost_nodelivery final_optimal_path = optimal_path_nodelivery else: final_optimal_cost = optimal_cost_delivery final_optimal_path = optimal_path_delivery return final_optimal_cost, final_optimal_path
b0f1454101fcd2aa96d12bc55bfa6aebcd002103
VinceWu-bit/Decision-Chessboard-Puzzle
/env.py
2,181
3.515625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2021/6/12 18:15 # @Author: Vince Wu # @File : env.py import numpy as np class ChessBoardEnv: def __init__(self): self.chessboard = np.array([0, 0, 0, 0]) self.key_dic = {0: 1, 1: 1, 14: 1, 15: 1, # 4维立方体编码规则 6: 2, 7: 2, 8: 2, 9: 2, 4: 3, 5: 3, 10: 3, 11: 3, 2: 4, 3: 4, 12: 4, 13: 4} self.key = 0 def reset(self): self.chessboard = np.array([0, 0, 0, 0]) return self.state_to_obs() def step(self, action, player): if player == 1: # 监狱长1 assert 0 <= action <= 63 self.key = action // 16 action = action % 16 for i in range(4): self.chessboard[3-i] = action // 2 ** (3 - i) action -= self.chessboard[3-i] * 2 ** (3 - i) return self.key, self.state_to_obs() elif player == 2: # 囚犯1 assert 0 <= action <= 3 self.chessboard[action] = 1 - self.chessboard[action] return self.key, self.state_to_obs() elif player == 3 or player == 4: # 监狱长2、囚犯2 assert 0 <= action <= 5 if action <= 2: self.switch(action, action + 1) elif action == 3: self.switch(3, 0) else: self.switch(action - 4, action - 2) if player == 4: # 囚犯2,结束 # print(self.state_to_key(), self.key) return 1 if self.state_to_key() == self.key else -1, True else: return self.key, self.state_to_obs() def state_to_key(self): key = 0 for i in range(4): key += self.chessboard[i] * 2 ** i return self.key_dic[key]-1 def switch(self, a, b): self.chessboard[a], self.chessboard[b] = self.chessboard[b], self.chessboard[a] def state_to_obs(self): obs = 0 for i in range(4): obs += self.chessboard[i] * (2 ** i) # print(self.chessboard) # print(obs) return obs
606de1aa9e681af56f022880698088b3ea58904d
nidakhawar/PracticePythonExcercises
/AverageOfSubjects.py
510
4.1875
4
biology=float(input("Please input your Biology score:")) chemistry=float(input("Please input your Chemistry score:")) physics=float(input("Please input your Physics score:")) if biology<40: print("Fail") if chemistry<40: print("Fail") if physics<40: print("Fail") else: score=((biology+chemistry+physics)/3) if score >=70: print("first") elif score>=60: print("2.1") elif score>=50: print("pass") elif score>=40: print("pass") else: print("fail")
2fe1eb2779838cbd559241374b9f94d6b36bc413
KevinSilva11/Python_The_Huxley
/PH.py
145
3.546875
4
ph = float(input()) if ph < 7: print('Acida') else: if ph > 7: print('Basica') else: print('Neutra')
bc5650df61ac37eef9df8a63e2b7d0b147d512da
SuzaneFer/phyton-basico-graficos
/ComparandoGenomas.py
799
3.5
4
#Neste estudo de caso, faremos a comparação entre duas sequências de DNA: # (1) ser humano; vs. (2) bactéria. import matplotlib.pyplot as plt import random entrada = open("bacteria.fasta").read() saida = open("bacteria.html","w") cont = {} # Dicionário for i in ['A', 'T', 'C', 'G']: for j in ['A', 'T', 'C', 'G']: cont[i+j]=0 # Para tirar a quebra de linha entrada = entrada.replace("\n"," ") for k in range(len(entrada)-1): cont[entrada[k]+entrada[k+1]] += 1 # Printar em HTML i = 1 for k in cont: transparencia = cont[k]/max(cont.values()) #pegar o maior valor saida.write("<div style='width:100px; border:1px solid #111; height: 100px; float: left; background-color:rgba(0,0,255, "+str(transparencia)+"')></div>") saida.close()
976cc8ab3327128b679d3d205e8c2dc1b2daae0b
zacharykaczor/Small-Programs
/odd_numbers.py
535
4.1875
4
# Based on https://www.youtube.com/watch?v=LkIK8f4yvOU. # The Difference of Two Squares. number = int(input("Please enter a positive odd number: ")) while number % 2 == 0 or number < 0: number = int(input( "Please enter a positive number: " if number < 0 else "Please enter an odd number: " )) root_2 = number // 2 root_1 = root_2 + 1 print(f"The roots are { root_1 } and { root_2 }.") print(f"The squares are { root_1 ** 2 } and { root_2 ** 2 }.") print(f"{ root_1 ** 2 } - { root_2 ** 2 } = { number }.")
c2f1391ee6e1ce4aa1cca4a81314f323495dc655
ProspePrim/PythonGB
/Lesson 5/task_5_2.py
985
3.96875
4
#Создать текстовый файл (не программно), сохранить в нем несколько строк, #выполнить подсчет количества строк, количества слов в каждой строке. with open('test.txt', 'w') as my_f: my_l = [] line = input('Введите текст \n') while line: my_l.append(line + '\n') line = input('Введите текст \n') if not line: break my_f.writelines(my_l) with open('test.txt' , 'r') as f: i = 0 for el in f: i += 1 print(f"Строка {i}: {el}") count = len(el) - el.count("\n") print(f"Количество знаков: {count}") print(f"Количество слов в строке: {len(el.split())} ") print('_____________________________________') print('*'*20) print(f"Количество строк: {i}")
05da3490735523a90c3b6a6a206a5445ac6e8fa4
ProspePrim/PythonGB
/Lesson 2/task_2_4.py
524
4.03125
4
#Пользователь вводит строку из нескольких слов, разделённых пробелами. #Вывести каждое слово с новой строки. Строки необходимо пронумеровать. #Если в слово длинное, выводить только первые 10 букв в слове. a = input("введите строку ") list_a = [] i = 0 list_a = a.split() for _ in range(len(list_a)): print(f"{list_a[i][0:10]}") i += 1
cc84abe6637d76e56a7ac2c958ebd7c8a808c1c1
ProspePrim/PythonGB
/Lesson 2/task_2_1.py
628
4.125
4
#Создать список и заполнить его элементами различных типов данных. #Реализовать скрипт проверки типа данных каждого элемента. #Использовать функцию type() для проверки типа. #Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. list_a = [5, "asdv", 15, None, 10, "asdv", False] def type_list(i): for i in range(len(list_a)): print(type(list_a[i])) return type_list(list_a)
8ff0adfd4e67aa0a69a45ebda1eb30ec290dcd49
ProspePrim/PythonGB
/Lesson 7/task_7_1.py
1,162
3.65625
4
class Cell: cells: int def __init__(self, cells: int): self.cells = cells def __str__(self): return str(self.cells) def __int__(self): return self.cells def __add__(self, cells: 'Cell'): return Cell(self.cells + cells.cells) def __sub__(self, cells: 'Cell'): if (result := self.cells - cells.cells) < 0: return "Разница меньше нуля" else: return Cell(result) def __mul__(self, cells: 'Cell'): return Cell(self.cells * cells.cells) def __truediv__(self, cells: 'Cell'): return Cell(self.cells - cells.cells) @staticmethod def make_order(cell: 'Cell', n: int): fullrow, lastrow = divmod(cell.cells, n) return '\n'.join([str('*') * n for _ in range(0, fullrow)]) + '\n' + '*' * lastrow cell0 = Cell(5) cell1 = Cell(10) cell2 = Cell(12) print('cell0 + cell2', cell0 + cell2) print('cell1 - cell2', cell1 - cell2) print('cell2 - cell1', cell2 - cell1) print('cell0 * cell1', cell0 * cell1) print('cell1 / cell0', cell1 / cell0) print(cell1.make_order(cell1, 4))
bce8bf614aca3883f2ac618caa8f00bc32a5dd73
costacoz/python_design_patterns
/behavioral/iterator.py
1,296
4.5
4
# Iterators are built into Python. # It can be engaged, using 'iter(arg*)' function # arg* - can be list, tuple, dic, set and string. # Below is the example of using it. # fruits_tuple = {'apple', 'blueberry', 'cherry', 'pineapple'} # fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') # fruits_tuple = ['apple', 'blueberry', 'cherry', 'pineapple'] fruits_tuple = 'apples' fruits_iterator = iter(fruits_tuple) print(next(fruits_iterator)) print(next(fruits_iterator)) print(next(fruits_iterator)) print(fruits_iterator.__next__()) # Loop through an iterator fruits_tuple = ('apple', 'blueberry', 'cherry', 'pineapple') for f in fruits_tuple: print(f) # # To create an iterator manually we need to implement iter and next # in __iter__ we initialize iterator, same as in __init__, and return iterator class Iterator: def __iter__(self): self.a = 2 return self # must always return iterator object def __next__(self): if self.a < 10: x = self.a self.a += 1 return x else: raise StopIteration # to stop iterator in loop iterable_obj = Iterator() # iterator = iter(iterable_obj) # print(next(iterator)) # print(next(iterator)) # print(next(iterator)) for i in iterable_obj: print(i)
a387b981c804a8e38ba20ce58d2417d82bc4dd89
muhammadyou/PythonTutorial
/ThreadingExample.py
1,758
4.09375
4
import threading import time class Example(threading.Thread): def run(self): for _ in range(10): time.sleep(1) print(threading.current_thread().getName()) def example(): for _ in range(10): time.sleep(1) print("hELlo") def example1(name, x): print("From example1 function {}".format(x)) for _ in range(10): time.sleep(1) print("Hi") def one(): global y lock.acquire() try: y =5 print(y) except: pass finally: lock.release() def two(): global y lock.acquire() try: y =3 print(y) except: pass finally: lock.release() def main(): #-- LOCK global lock lock = threading.Lock() first = threading.Thread(target=one, name='Lock1 Thread') second = threading.Thread(target=two, name='Lock2 Thread') first.start() second.start() threading.Thread(target = example, name="Example Thread").start() t = threading.Thread(target = example1, args=("Example 1 Thread", 5), name='Example 1 Thread') t.start() t.join() # -- it doesnt allow all thread to run altogether, so this threads runs only before starts another threads print("The thread is {}".format(t.is_alive())) x = Example(name="Yousuf") y = Example(name="OMer") print("The thread is {}".format(t.is_alive())) x.start() y.start() print("The number of threads running are {}".format(threading.active_count())) # prints the number of threads running print(threading.enumerate()) # tells you the threads running such as their name print("The active thread is {}".format(threading.active_count())) if __name__ == '__main__': main()
717852b99833f1e2f9470bb7e906f0cb29d7874e
bjolley74/myTKfiles
/lesson1.py
255
3.859375
4
"""lesson1.py - message box: creates a tk message box""" from tkinter import * from tkinter import messagebox root = Tk() root.withdraw() messagebox.showinfo('Bobby\' World', 'Hello Y\'all! This is a message from Bobby\nThis is some really cool stuff')
9c47ecc06cd8e6525255f441528d9deae2655c9f
jgu13/Miscellaneous
/Python/ecosys_simulator/ecosystem_simulator.py
13,854
4.125
4
# Jiayao Gu # 260830725 import random import matplotlib.pyplot as plt class Animal: # Initializer method def __init__(self, my_species, row, column): """ Constructor method Args: self (Animal): the object being created my_species (str): species name ("Lion" or "Zebra") row (int): row for the new animal column (int): column for the new animal Returns: Nothing Behavior: Initializes a new animal, setting species to my_species """ self.species = my_species self.row = row self.col = column self.age = 0 self.time_since_last_meal = 0 def __str__(self): """ Creates a string from an object Args: self (Animal): the object on which the method is called Returns: str: String summarizing the object """ s= self.species+" at position ("+str(self.row)+","+str(self.col)+"):, age="+str(self.age)+", time_since_last_meal="+\ str(self.time_since_last_meal) return s def can_eat(self, other): """ Checks if self can eat other Args: self (Animal): the object on which the method is called other (Animal): another animal Returns: boolean: True if self can eat other, and False otherwise """ # WRITE YOUR CODE FOR QUESTION 3 HERE if self.species == "Lion" and other.species == "zebra": return True else: return False def time_passes(self): """ Increases age and time_since_last_meal Args: self (Animal): the object on which the method is called Returns: Nothing Behavior: Increments age and time_since_last_meal """ # WRITE YOUR CODE FOR QUESTION 4 HERE self.age += 1 self.time_since_last_meal += 1 return def dies_of_old_age(self): """ Determines if an animal dies of old age Args: self (Animal): the object on which the method is called Returns: boolean: True if animal dies of old age, False otherwise """ # WRITE YOUR CODE FOR QUESTION 5 HERE if (self.species == "Lion" and self.age >= 18) or (self.species == "Zebra" and self.age >= 7): return True else: return False def dies_of_hunger(self): """ Determines if an animal dies of hunger Args: self (Animal): the object on which the method is called Returns: boolean: True if animal dies of hunger, False otherwise """ # WRITE YOUR CODE FOR QUESTION 6 HERE if self.species == "Lion" and self.time_since_last_meal >= 6: return True else: return False def will_reproduce(self): """ Determines if an animal will reproduce this month Args: self (Animal): the object on which the method is called Returns: boolean: True if ready to reproduce, False otherwise """ # WRITE YOUR CODE FOR QUESTION 7 HERE if self.species=="Zebra": if self.age==3 or self.age==6 and self.dies_of_old_age()==False: return True else: return False elif self.species=="Lion": if self.age==7 or self.age==14 and self.age<18 and self.dies_of_hunger()==False: return True else: return False # end of Animal class def initialize_population(grid_size): """ Initializes the grid by placing animals onto it. Args: grid_size (int): The size of the grid Returns: list of animals: The list of animals in the ecosystem """ all_animals=[] all_animals.append(Animal("Lion",3,5)) all_animals.append(Animal("Lion",7,4)) all_animals.append(Animal("Zebra",2,1)) all_animals.append(Animal("Zebra",5,8)) all_animals.append(Animal("Zebra",9,2)) all_animals.append(Animal("Zebra",4,4)) all_animals.append(Animal("Zebra",4,8)) all_animals.append(Animal("Zebra",1,2)) all_animals.append(Animal("Zebra",9,4)) all_animals.append(Animal("Zebra",1,8)) all_animals.append(Animal("Zebra",5,2)) return all_animals def print_grid(all_animals, grid_size): """ Prints the grid Args: all_animals (list of animals): The animals in the ecosystem grid_size (int): The size of the grid Returns: Nothing Behavior: Prints the grid """ #get the set of tuples where lions and zebras are located lions_tuples = { (a.row,a.col) for a in all_animals if a.species=="Lion"} zebras_tuples = { (a.row,a.col) for a in all_animals if a.species=="Zebra"} print("*"*(grid_size+2)) for row in range(grid_size): print("*",end="") for col in range(grid_size): if (row,col) in lions_tuples: print("L",end="") elif (row,col) in zebras_tuples: print("Z",end="") else: print(" ",end="") print("*") print("*"*(grid_size+2)) def sort_animals(all_animals): """ Sorts the animals, left to right and top to bottom Args: all_animals (list of animals): The animals in the ecosystem Returns: Nothing Behavior: Sorts the list of animals """ def get_key(a): return a.row+0.001*a.col all_animals.sort(key=get_key) def my_random_choice(choices): """ Picks ones of the elements of choices Args: choices (list): the choices to choose from Returns: One of elements in the list """ if not choices: return None # for debugging purposes, we use this fake_random_choice function def getKey(x): return x[0]+0.001*x[1] return min(choices, key=getKey) # for actual random selection, replace the above this: #return random.choice(choices) def list_neighbors(current_row, current_col, grid_size): """ Produces the list of neighboring positions Args: current_row (int): Current row of the animal current_col (int): Current column of the animal grid_size (int): The size of the gride Returns: list of tuples of two ints: List of all position tuples that are around the current position, without including positions outside the grid """ # WRITE YOUR CODE FOR QUESTION 1 HERE i = current_row j = current_col List = [] for row_increment in range(-1,2): new_row = i + row_increment for col_increment in range(-1,2): new_col = j + col_increment if new_col == j and new_row == i: pass elif (new_row > 0 and new_row < grid_size) and (new_col > 0 and new_col < grid_size): List.append((new_row, new_col)) return List def random_neighbor(current_row, current_col, grid_size, only_empty=False, animals=[]): """ Chooses a neighboring positions from current position Args: current_row (int): Current row of the animal current_col (int): Current column of the animal size (int): Size of the grid only_empty (boolean): keyword argument. If True, we only consider neighbors where there is not already an animal animals (list): keyword argument. List of animals present in the ecosystem Returns: tuple of two int: A randomly chosen neighbor position tuple """ # WRITE YOUR CODE FOR QUESTION 2 HERE all_neighbors = [n for n in list_neighbors(current_row, current_col, grid_size)] next_cell = my_random_choice(all_neighbors) i = next_cell[0] j = next_cell[1] if not(only_empty): return next_cell else: for animal in animals: if animal.row == i and animal.col == j: all_neighbors.remove((animal.row,animal.col)) if len(all_neighbors) == 0: return None return next_cell #next_cell does not have an animal def one_step(all_animals, grid_size): """ simulates the evolution of the ecosystem over 1 month Args: all_animals (list of animals): The animals in the ecosystem grid_size (int): The size of the grid Returns: list fo str: The events that took place Behavior: Updates the content of animal_grid by simulating one time step """ sort_animals(all_animals) # ensures that the animals are listed # from left to right, top to bottom # run time_passes on all animals for animal in all_animals: animal.time_passes() # make animals die of old age events = [] dead = [] for animal in all_animals: if(animal.dies_of_old_age()): dead.append(animal) events.append("{} dies of old age at position {} {}".format(animal.species, animal.row, animal.col)) # make animals die of hunger elif(animal.dies_of_hunger()): dead.append(animal) events.append("{} dies of hunger at position {} {}".format(animal.species,animal.row, animal.col)) for a in all_animals: if a in dead: all_animals.remove(a) # move animals new_row, new_col = random_neighbor(animal.row, animal.col, grid_size, False, all_animals) eaten = [] for animal in all_animals: # search for animal that on the new cell present_animal = [n for n in all_animals if n.row == new_row and n.col == new_col and n not in eaten] #there is an animal in the new cell if present_animal != []: # search for the animal at the new_position #3 cases: # if a lion moves to a cell contains a zebra, lion eats zebra and lion moves to new_position, zebra is removed from the cel present_animal = present_animal[0] if animal.can_eat(present_animal): events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+" and eats a zebra") animal.row = new_row #update position animal.col = new_col animal.time_since_last_meal = 0 #update the time since last meal eaten.append(present_animal) # if a zebra moves to a cell contains a lion, zebra is eaten and removed from its position elif present_animal.can_eat(animal): events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+ " and is eaten by a lion") eaten.append(animal) present_animal.time_since_last_meal = 0 # if the same animals present, animals stay, nothing happens else: # two animals are the same species events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)+ " but there is an animal of the same species") #new cell does not contain an animal else: events.append(animal.species+" moves from "+str(animal.row)+" "+str(animal.col)+" to "+str(new_row)+" "+str(new_col)) animal.row = new_row animal.col = new_col for a in all_animals: if a in eaten: all_animals.remove(a) # since animals have moved, we sort the list of animals again, so that # we consider them for reproduction in the right order sort_animals(all_animals) babies = [] # reproduce animals for animal in all_animals: if animal.will_reproduce(): result = random_neighbor(animal.row, animal.col, grid_size, False, all_animals) if result == None: return; else: # new cell is empty baby_row, baby_col = result all_animals.append(Animal(animal.species, baby_row, baby_col)) #add baby to all_animals list events.append("A new baby {} is born at {} {}".format(animal.species, baby_row, baby_col)) def run_whole_simulation(grid_size = 10, simulation_duration = 20, image_file_name="population.png"): """ Executes the entire simulation Args: grid_size (int): Size of the grid simulation_duration (int): Number of steps of the simulation image_file_name (str): name of image to be created. Returns: Nothing Behavior: Simulates the evolution of an animal grid Generates graph of species abundance and saves it to populations.png """ # Do not change this; this initializes the animal population all_animals = initialize_population(grid_size) # WRITE YOUR CODE FOR QUESTION 9 HERE lions = [] zebras = [] for time in range(simulation_duration): num_of_lions = 0 num_of_zebras = 0 for animal in all_animals: if animal.species == "Lion": num_of_lions += 1 elif animal.species == "Zebra": num_of_zebras += 1 lions.append(num_of_lions) zebras.append(num_of_zebras) one_step(all_animals, grid_size) plt.plot(range(simulation_duration), lions, "b", label="Lions") plt.plot(range(simulation_duration), zebras, "r", label = "zebras") plt.xlabel("time") plt.ylabel("Number of individuals") plt.legend(loc = "best") plt.savefig(image_file_name)
0b602263ce8b46a900c767c974efcce4ca0b2984
JDWree/Practice
/Python/mastermind.py
3,436
4.1875
4
# Simple version of the game 'mastermind' #---------------------------------------- # Version 1.0 Date: 5 April 2020 #---------------------------------------- # Player vs computer # A random code gets initialized. The player has 10 guesses to crack the code. # The game tells the player when it has a right digit in the code but on the wrong # spot as 'd' (from digit). If a player as a correct digit on the correct spot, # the game returns a 'c'. # An example: # The code is 1234 # The player guesses 1359 # The game will return 'cd' on this guess since 1 is correct and there is a 3. #------------------------------------------------------------------------------- ### Packages ### from random import randint #------------------------------------------------------------------------------ # Explanation of the game to the player: print(""" You are about to play a simple version of 'Mastermind'. The computer will create a code of 4 unique digits from 0-9. So no 2 the same digits will be used in the code. You have to guess the code within 10 tries. After every guess the game will give you feedback. If you have a correct digit but not in the right place, it will return a 'd'. if you have a correct digit on the correct spot, it will return a 'c'. An example: The code is 1234. Your guess is 2538. The game will return 'cd' as feedback. Good luck! """) #------------------------------------------------------------------------------ # Initialization of the code to break: code = [] while len(code)<4: dgt = randint(0,9) if dgt not in code: code.append(dgt) else: pass print("The code has been initialized.") #------------------------------------------------------------------------------ # Function that prompts the player for its guess and returns the feedback def guess(): print("Make your guess:") g = input("> ") ges = g.strip() if len(ges) != 4 or not ges.isdigit(): print("You didn't make a proper guess?!") print("Type in your guess for the 4-digit code.") print("For example 1234 .") guess() else: feedback = "" for i in range(len(ges)): if int(ges[i]) == code[i]: feedback+='c' elif int(ges[i]) in code: feedback +='d' else: pass return feedback #------------------------------------------------------------------------------ # Looping over max ammount of guesses. # Prompting everytime the player for its guess. # When the player makes a correct guess, stop looping. found = False number_of_guesses = 0 while not found and number_of_guesses < 10: fdbck = guess() number_of_guesses+=1 #print(fdbck) print("\nFeedback on your guess: %s\n" % ''.join(sorted(list(fdbck)))) if fdbck == 'cccc': found = True else: print("You have %d guesses left." % (10 - number_of_guesses)) #------------------------------------------------------------------------------ if found: print("\n\t\t\t***CONGRATULATIONS!***\n\n") print("You have beaten the game with %d guesses left!" % (10 - number_of_guesses)) else: print("\n\t\t\t***FAIL***\n\n") print("Oh, bommer. You didn't manage to guess the correct code in time!") print("Better luck next time!") #------------------------------------------------------------------------------
059b163345985fdcfee9f3e410de39e001218782
gagaspbahar/prak-pengkom-20
/P02_16520289/P02_16520289_02.py
744
3.5625
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 4 November 2020 # Deskripsi: Problem 2 - Konversi basis K ke basis 10 #Kamus #int sm = jumlah bilangan dalam basis 10 #int n = jumlah digit #int k = basis awal #int i = counter #Inisialisasi variabel sm = 0 n = int(input("Masukkan nilai N: ")) k = int(input("Masukkan nilai K: ")) #Algoritma for i in range(n-1,-1,-1): #Loop dari n-1 sampai 0 digit = int(input("Masukkan digit ke " + str(n-i) + ": ")) #Input digit sm += k**i * digit #Kalikan basis dengan nilai digit ke-berapa lalu tambahkan ke sm #Output print("Bilangan dalam basis 10 adalah", sm)
885e989095d06495061674fe1e2696b815df9463
gagaspbahar/prak-pengkom-20
/H03_16520289/H03_16520289_01.py
436
3.609375
4
# NIM/Nama : 16520289/Gagas Praharsa Bahar # Tanggal : 15 November 2020 # Deskripsi: Problem 1 - Penulisan Terbalik # Kamus # int n = panjang array # int ar[] = array penampung angka #Algoritma #Input n = int(input("Masukkan N: ")) #Inisialisasi array dan memasukkan angka ke array ar = [0 for i in range(n)] for i in range(n): ar[i] = int(input()) #Pembalikkan array print("Hasil dibalik: ") for i in range(n-1,-1,-1): print(ar[i])
5966f2409f0998aa515f8f40b56f3339a2d4298a
plaer182/Python3
/test_random_symbol.py
1,575
3.546875
4
#!/usr/bin/env python3 from random_symbols import random_symbol import string def test_length_name(): """ Check length of element in list of results """ try: random_symbol(["Annannannannannannannannannannannannannannanna", "Boris", "Evgenia", "Viktor"]) except: pass else: raise Exception("incorrect input accepted or ignored") def test_correctness(): """ Check basic functionality using happy path """ list_of_names_1 = ["Anna", "Boris", "Evgenia", "Viktor"] name_plus_symbols = random_symbol(list_of_names_1) symbols = '$€₽₪' letters_counter = 0 symbols_counter = 0 for elem in name_plus_symbols: for char in elem: if char.isalpha(): letters_counter += 1 elif char in symbols: symbols_counter += 1 else: if char.isprintable(): raise Exception("Unknown type of char: ", char) else: raise Exception("Unknown type of char: unprintable ", hex(char)) assert symbols_counter == letters_counter def test_incorrectness(): """ Check basic functionality using unhappy path """ try: random_symbol(["Anna!!", "~Boris~", "Evge,,nia", "Vik/tor"]) except: pass else: raise Exception("incorrect input accepted or ignored") if __name__ == '__main__': test_length_name() test_correctness() test_incorrectness()
2724d92157d61f930c089931f2b55042dcfe9f0e
plaer182/Python3
/FizzBuzz(1-100)(hw2).py
354
4.15625
4
number = int(input('Enter the number: ')) if 0 <= number <= 100: if number % 15 == 0: print("Fizz Buzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number) elif number < 0: print("Error: unknown symbol") else: print("Error: unknown symbol")
df113dafcc1cf93b98304cc6f8f33efbe0a2e296
plaer182/Python3
/fahrenheit_to_celsius(hw1).py
158
4.125
4
celsius = float(input('Enter the temperature in degrees to Сelsius> ')) fahrenheit = celsius * 1.8 + 32 print(str(fahrenheit) + ' degrees to Fahrenheit')
08fe50d6f996a359bd2346667554abde47a94c47
Jamesbwwh/Minesweeper
/Minesweeper/Minefield.py
3,057
3.78125
4
import random def generate(difficulty): mineField = printMineField(difficulty) height = len(mineField) width = len(mineField[0]) ranges = width * height mines = random.randint(ranges // 8, ranges // 7) # mines = 4; # comment or remove this line. for testing only. print "Difficulty: ", difficulty, "Mines: ", mines, "Height: ", height, "Width: ", width ranges -= 1 for mine in range(mines): while(True): placeMine = random.randint(0, ranges) x = placeMine // width y = placeMine % width if mineField[x][y] != 9: mineField[x][y] = 9 if x - 1 >= 0: #Top if y - 1 >= 0: #Top-Left if mineField[x - 1][y - 1] != 9: mineField[x - 1][y - 1] += 1 if mineField[x - 1][y] != 9: mineField[x - 1][y] += 1 if y + 1 < width: #Top-Right if mineField[x - 1][y + 1] != 9: mineField[x - 1][y + 1] += 1 if y - 1 >= 0: #Left if mineField[x][y - 1] != 9: mineField[x][y - 1] += 1 if y + 1 < width: #Right if mineField[x][y + 1] != 9: mineField[x][y + 1] += 1 if x + 1 < width: #Bottom if y - 1 >= 0: #Bottom-Left if mineField[x + 1][y - 1] != 9: mineField[x + 1][y - 1] += 1 if mineField[x + 1][y] != 9: mineField[x + 1][y] += 1 if y + 1 < width: #Bottom-Right if mineField[x + 1][y + 1] != 9: mineField[x + 1][y + 1] += 1 break return mineField, mines def printMineField(difficulty): #easy difficulty if (difficulty == 1): minefield = [[0] * 9 for i in xrange(9)] return minefield #medium difficulty if (difficulty == 2): minefield = [[0] * 16 for i in xrange(16)] return minefield #hard difficulty if (difficulty == 3): minefield = [[0] * 20 for i in xrange(20)] return minefield #Very hard difficulty if (difficulty == 4): minefield = [[0] * 25 for i in xrange(25)] return minefield #custom difficulty if (difficulty == 0): width = input("Enter the width : ") height = input("Enter the height : ") minefield = [[0] * width for i in xrange(height)] return minefield def displayTestMineField(minemap, limiter): counter = 0 #prints until reach k value specified as the limiter for i in range(len(minemap)): if (counter != limiter): print minemap[i] counter +=1 #displayTestMineField(printMineField(1), 2) #for i in range(len(mineField)): # for j in range(len(mineField[i])): # print mineField[i][j], # print ""
f677307abacfa8b8c1e095bf3eeffaa1f94ffe0f
iman2008/first-repo
/random1.py
187
3.875
4
#defining 10 random number between 10 and 20 import random def random_numer(): i=0 while (i<=10): x = random.random() * 20 if 10 <= x <= 20: print (x) i=i+1 random_numer()
0f23631ef11d79a29889cb820371aa21ffaecde8
iman2008/first-repo
/lab4task1.py
336
3.765625
4
def sum_adder (mlist): """this will add up the content of the list""" total = 0 s_list = mlist for item in s_list: if isinstance(item,int): total = total + item elif isinstance (item,list): total=total+sum_adder (item) else: return "you have not select proper list" return total x = [90,10,11] print (sum_adder(x))
9b624ac6dee525b0da68baa1196f8b273486d237
Mentos15/Python_2
/paswords.py
691
3.5625
4
#! python3 # paswords.py PASWORDS = { 'email': 'vital2014','vk':'Vital2014','positive':'vital2014'} import sys,pyperclip if len(sys.argv)<2: print('Использование: python paswords.py[Имя учетной записи] - копирование пароля учетной записи') sys.exit() account = sys.argv[1] # первый аргумент командной строки - это имя учетной записи if account in PASWORDS: pyperclip.copy(PASWORDS[account]) print ('Пароль для'+ account+'скопирован в буфер.') else: print('Учетная запись'+account+'отсутствует в списке')
db6a67f488a152ccc2768d3d24728afb318f10de
CodecoolBP20172/pbwp-3rd-si-code-comprehension-kristofilles
/comprehension.py
2,101
4.3125
4
"""Its a bot what randomly choose a number between 1 and 20, and the user need to guess within 6 round what number was choosen by the bot.""" import random #import the random module guessesTaken = 0 #assign 0 to guessesTaken variable print('Hello! What is your name?') #print out this sentence myName = input() #assign a user input to myName variable number = random.randint(1, 20) #assign a randomly choosen integer(between 1 and 20) to number variable print('Well, ' + myName + ', I am thinking of a number between 1 and 20.') #printing out this sentence with the given name while guessesTaken < 6: #loop while the guessesTaken variable is less then 6 print('Take a guess.') #print out this sentence guess = input() #assign a user input to guess variable guess = int(guess) #making type conversion changing the value of the guess variable to integer from string guessesTaken += 1 #increasing the value of the guessesTaken by 1 if guess < number: #doing something if guess value is lower than number value print('Your guess is too low.') #if its true print out this sentence if guess > number: #doing something if the guess value is higher than the number value print('Your guess is too high.') #if its true print out this sentence if guess == number: #doing something if the guess value is equal with the number value break #if its true the loop is immediately stop if guess == number: #doing something if the guess value is equal with the number value guessesTaken = str(guessesTaken) #making type conversion changing the value of the guessesTaken variable to string from integer print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!') #print out how many try needed to the user to guess out if guess != number: #doing something if guess value is not equal with number value number = str(number) #making type conversion changing the value of the number variable to string from integer print('Nope. The number I was thinking of was ' + number) #print out the randomly choosen number
19a4a42767f001a14afeb4debed9ef26c6e69afe
rdugh/pythonds9
/pythonds9/trees/binary_tree.py
1,028
3.8125
4
class BinaryTree: def __init__(self, key): self.key = key self.left_child = None self.right_child = None def insert_left(self, key): if self.left_child is None: self.left_child = BinaryTree(key) else: # if there IS a left child t = BinaryTree(key) t.left_child = self.left_child self.left_child = t def insert_right(self, key): if self.right_child is None: self.right_child = BinaryTree(key) else: # if there IS a right child t = BinaryTree(key) t.right_child = self.right_child self.right_child = t def get_right_child(self): return self.right_child def get_left_child(self): return self.left_child def get_root_val(self): return self.key def set_root_val(self, new_key): self.key = new_key def __repr__(self): return f"BinaryTree({self.key!r})"
6ced4a96655281b60edd62a77ea9e76b6f79bd55
brentEvans/algorithm_practice
/Python/algo.py
2,264
3.640625
4
class Node: def __init__(self, value): self.val = value self.next = None class SLL: def __init__(self): self.head = None def addBack(self,value): new_node = Node(value) if self.head == None: self.head = new_node else: runner = self.head while runner.next != None: runner = runner.next runner.next = new_node return self def display_list(self): runner = self.head this_list = [] while runner != None: this_list.append(runner.val) runner = runner.next print(this_list) def removeNeg(self): if self.head == None: return "Empty" while self.head.val < 0: self.head = self.head.next runner = self.head while runner.next != None: if runner.next.val < 0: runner.next = runner.next.next else: runner = runner.next return self def move_to_front(self,value): if self.head == None: return "Empty List" runner = self.head start = self.head while runner.next != None: if runner.next.val == value: move = runner.next runner.next = runner.next.next self.head = move move.next = start runner = runner.next return self def partition(self, pivot): if self.head == None: return "Empty list" runner = self.head while runner.next != None: if runner.next.val == pivot: self.move_to_front(runner.next.val) else: runner = runner.next runner = self.head while runner.next != None: if runner.next.val < pivot: self.move_to_front(runner.next.val) else: runner = runner.next return self new_list = SLL() new_list.addBack(5) new_list.addBack(3) new_list.addBack(2) new_list.addBack(4) new_list.addBack(5) new_list.addBack(9) new_list.addBack(-7) new_list.addBack(8) new_list.display_list() new_list.partition(4) new_list.display_list()
07bd3a329eafee4c2398a08943aeb985a282b6f2
onionmccabbage/pythonTrainingMar2021
/using_ternary.py
474
4.40625
4
# Python has one ternary operator # i.e. an operator that takes THREE parts # all other operators are binary, i.e. they take TWO parts # e.g. a = 1 or 3+2 # the ternary operator works like this # 'value if true' 'logical condition' 'value if false' x = 6 y = 5 print("x" if x>y else "y") # alternative syntax for the ternary operator nice = False personality = ("horrid", "lovely")[nice] # spot the index 0 or 1 print("My cat is {}".format(personality)) #
8b08218eb70b47bfb0aa02cfacf775dcdb2a3089
onionmccabbage/pythonTrainingMar2021
/py2demo.py
242
3.859375
4
print "hello" # Python 2 print('also hello') # also works in Python 2 # division of ints 7/3 # is 2 in Py2 and 3 and a bit in Py 3 # py 2 has a 'long' data type - change it to 'float' # some py 2 functions were re-defined in py 3
8b888a5341335f8976cfc23b7ede527047886ec3
AnindKiran/N_Queen-s-Problem-Solution-in-Python
/Final N-Queens Project.py
3,087
4.28125
4
a="""This is a program used to display ALL solutions for the famous N-Queens Problem in chess. The N-Queens Problem is a problem where in an N-sized chess board, we have to place N Queens in such a way that no one queen can attack any other queen""" print(a) print() a="""This program will take your input and will generate the solutions for the board size of your input""" #This function generates an nxn board as a matrix def generateboard(n): try: n=int(n) board=[[0]*n for i in range(n)] return board except Exception as e: print("The following error has occured:",e) #This function displays the solution def FinalSolution(board): for i in board: for j in i: if j: print('Q',end=' ') else: print('.',end=' ') print() print() #This is the main algorithm of the program, and determines whether a queen can #be placed in a particular box or not. It considers a particular location in #a chessboard and sees if another queen can attack the location under #consideration. def safe(board,row,col): #TO CHECK IF THE CURRENT ROW IS SAFE c=len(board) for i in board[row]: if i: return 0 #TO CHECK IF THE CURRENT COLUMN IS SAFE for i in range(len(board)): if board[i][col]: return 0 a,b=row,col #TO CHECK IN THE BOTTOM-RIGHT DIRECTION while a<c and b<c: if board[a][b]: return 0 a=a+1 b=b+1 a,b=row,col #TO CHECK IN THE TOP-LEFT DIRECTION while a>=0 and b>=0: if board[a][b]: return 0 a=a-1 b=b-1 a,b=row,col #TO CHECK IN THE TOP-RIGHT DIRECTION while a>=0 and b<c: if board[a][b]: return 0 a=a-1 b=b+1 a,b=row,col #TO CHECK IN THE BOTTOM-LEFT DIRECTION while a<c and b>=0: if board[a][b]: return 0 a=a+1 b=b-1 return 1 #This function takes the generated board, and tries all possible combinations #of queens. It places the queens in all locations to see which is the correct #overall solution. The best part about this function is that it if it sees that #N-queens cannot be placed, it does not restart but instead continues from the #last value. Number=0 def solve(board,row=0): if board != None: global Number if row>=len(board): FinalSolution(board) Number+=1 return for col in range(len(board)): if safe(board,row,col): board[row][col]=1 solve(board,row+1)#The board is returned here when a solution #is found and the program is out of the function. board[row][col]=0 n=input("Enter the size 'n' of the board:") a=generateboard(n) solve(a) print("The number of solutions for the",n,"x",n,"board is:", Number)
04860c836937ba8bc594c64d7c9b752ea564269e
jeremy-robb/KnoxClassRecommender
/tools.py
3,239
4
4
from lists import * takeFrom = [] def chooseMajors(): print("") print("To choose a major, type the first 3 letters of the specialization, followed by the first 2 letters of the degree") print("Examples: CS BA (Computer Science BA) , MATBA (Math BA) , PHYMI (Physics minor)") print("Choose major one") while True: major1 = input() if isAdded(major1.upper()): break else: print("Choose any of the following: ", added) while True: print("Choose major two") major2 = input() if isAdded(major2.upper()) and major2.upper() != major1.upper(): break else: print("Choose any of the following (besides the first major): ", added) takeFrom.append(major1.upper()) takeFrom.append(major2.upper()) if "PHY" in major1.upper() or "PHY" in major2.upper(): takeFrom.append("MATBA") return major([major1.upper(), major2.upper()]) def getTranscript(): print("If you already have your transcript code (as given by this program), paste it here. If not, press enter to continue. If you do not have a transcript (incoming students), type 'new'") start = input() if len(start) > 0 and start[0] == "~": return list(start[1:].split("-")) print("To start, navigate to your unofficial transcript page (https://my.knox.edu/ICS/Registrar/Student_Tools/Unofficially_Transcript.jnz), and copy paste (ctrl a, ctrl c) the entire page here (ctrl v)") final = "~" trancount = 0 fileread = open("courses", "r") avail = [] while True: line = fileread.readline() if not line: break if line[5:8] not in avail: avail.append(line[5:8]) while True: word = input() trancount += 1 if trancount == 175: print("It looks like something went wrong, message Jeremy Robb (jarobb@knox.edu) to recieve instructions on how to properly paste in your transcript") if word == "Unofficial Transcript PDF ": break counter = 0 flag = False if not word[0:3] in avail: continue for x in word: if x.isdigit() and len(word) - counter - 3 > 0: flag = True break counter += 1 if not flag: continue # at this point we can assume it's a class I need to add if "N/A" in word: continue final += word[0:3] + " " + word[counter:counter+3] + "-" debug = input() # This is just to get rid of the final line if len(final) > 1: print("") print("Your code is: ") print(final) return list(final[1:].split("-")) else: print("It looks like something went wrong, message Jeremy Robb (jarobb@knox.edu) to recieve instructions on how to properly paste in your transcript") return [] def addStatus(transcript): if len(transcript) >= 27: transcript.append("SOP") transcript.append("JUN") transcript.append("SEN") elif len(transcript) >= 18: transcript.append("SOP") transcript.append("JUN") elif len(transcript) >= 9: transcript.append("SOP") return transcript
4a16ad732d79913225b5e89bc29acc27bf81937c
Lexical-Lad/Machine-Learning-Python-R-Matlab-codes
/Machine Learning A-Z Template Folder/Part 1 - Data Preprocessing/PreprocessingPractice.py
1,626
3.609375
4
import numpy as np import pandas as pd import matplotlib.pyplot as mlt import os #os.chdir(...) dataset = pd.read_csv("Data.csv") #splitting the dataset into the feature matrix and the dependent variable vector X = dataset.iloc[:,:-1].values y = dataset.iloc[:,-1].values #conpensating for the missing values, if any from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = "NaN", strategy = "mean", axis = 0) imputer = imputer.fit(X[:,(1,2)]) X[:,(1,2)] = imputer.transform(X[:,(1,2)]) #encoding the categorical features into numerical values from sklearn.preprocessing import LabelEncoder labelencoder_X = LabelEncoder() X[:,0] = labelencoder_X.fit_transform(X[:,0]) labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) #compensating for the numertical disparity betweeen the newly assigned numerical labels(only for model where the disparity is not a requisite), by creating dummy, binary features from sklearn.preprocessing import OneHotEncoder onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() #splitting the dataset into training and test set from sklearn.cross_validation import train_test_split X_train,X_test,y_train,y_test = train_test_split(X,y, test_size = 0.2) #not providing a seed(for random sampling each time) #scaling the features from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #scaling y only for regresiion problems sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train) y_test = sc_y.transform(y_test)
3d0d26f588dfeb0d23e179fbdf94a6b35f0388a8
lazyseals/crawler
/products/category_parser.py
18,232
3.671875
4
from products import items as d # Foreach shop a unique parser must be written that executes the following steps: # 1. Category name and product name to lower case # 2. Check if a product in category name needs to be replaced by a mister m category # 3. Determine mister m category based on a pattern in the product name # # In order to integrate a new shop into the parser # the following additional steps are required to make the previously defined steps working: # For step 2: Define a dict in items.py with the following naming scheme: toparse_<shopname> # -> This dict contains categories that hold product which belong at least into 2 different mister m categories # For step 3: Define a if/if structure with pattern matching in product name to determine the mister m category # -> Foreach mister m category define exactly 1 if or if case # -> Sort the if/if structure alphabetically # # If 1 shop is excluded from category matching based on product name, then mention it here with a short reason why # - Body and Fit: All categories that are parsed define a mister m category # Match categories from shop rockanutrition to mister m categories. # Matching based on product name. def parse_rocka(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category == 'vitamine & minerale' or category == 'drinks' or category == 'bake & cook': # Check product name for patterns in order to replace category with mister m category if 'vitamin b' in product: categories.append('Vitamin B') if 'vitamin d' in product: categories.append('Vitamin D') if 'essentials' in product or 'strong' in product: categories.append('Multivitamine') if 'magnesium' in product: categories.append('Magnesium') if 'milk' in product or 'whey' in product: categories.append('Protein Drinks') if 'swish' in product or 'work' in product: categories.append('Energy Drinks') if 'cino' in product: categories.append('Tee & Kaffee') if 'oil' in product: categories.append('Speiseöle') if 'bake' in product: categories.append('Backmischungen') # Return all categories a product is in return categories # Match categories from shop fitmart to mister m categories. # Matching based on product name. def parse_fitmart(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_fitmart: # Check product name for patterns in order to replace category with mister m category if 'brötchen' in product: categories.append('Brot') if 'brownie' in product or 'pancakes' in product or 'waffles' in product or 'mischung' in product: categories.append('Backmischungen') if 'candy' in product: categories.append('Süßigkeiten') if 'chips' in product or 'flips' in product or 'nachos' in product: categories.append('Chips') if 'crank' in product: categories.append('Trainingsbooster') if 'crispies' in product: categories.append('Getreide') if 'dream' in product or 'creme' in product or 'spread' in product or 'choc' in product or 'cream' in product or \ 'butter' in product or 'plantation' in product or 'walden' in product: categories.append('Aufstriche') if 'muffin' in product or 'cookie' in product: categories.append('Cookies & Muffins') if 'pasta' in product or 'pizza' in product: categories.append('Pizza & Pasta') if 'pudding' in product: categories.append('Pudding') if 'truffle' in product or 'riegel' in product or 'waffel' in product or 'snack' in product or \ 'bar' in product: categories.append('Schokolade') if 'sauce' in product or 'callowfit' in product: categories.append('Gewürze & Saucen') if 'zerup' in product or 'sirup' in product or 'syrup' in product: categories.append('Syrup') # Return all categories a product is in return categories # Match categories from shop myprotein to mister m categories. # Matching based on product name. def parse_myprotein(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_myprotein: # Check product name for patterns in order to replace category with mister m category if 'aakg' in product: categories.append('AAKG') if 'aufstrich' in product or 'butter' in product or 'dip pot' in product: categories.append('Aufstriche') if 'antioxidant' in product or 'maca' in product: categories.append('Antioxidantien') if 'bar' in product or 'rocky road' in product or 'carb crusher' in product or 'flapjack' in product: categories.append('Proteinriegel') if 'beeren' in product: categories.append('Beeren') if 'bcaa drink' in product or 'protein wasser' in product: categories.append('Protein Drinks') if 'beta-alanin' in product: categories.append('Beta Alanin') if 'bohnen' in product: categories.append('Bohnen') if 'casein' in product: categories.append('Casein Protein') if 'choc' in product or 'schokolade' in product: categories.append('Schokolade') if 'chromium' in product or 'electrolyte' in product or 'eisen' in product: categories.append('Mineralstoffe') if 'citrullin' in product: categories.append('Citrullin') if 'cla' in product: categories.append('CLA') if 'cookie' in product or 'keks' in product or 'brownie' in product: categories.append('Cookies & Muffins') if 'crisps' in product: categories.append('Chips') if 'curcurmin' in product: categories.append('Curcurmin') if 'eaa' in product: categories.append('EAA') if 'eiklar' in product: categories.append('Eiklar') if 'erbsenprotein' in product: categories.append('Erbsenprotein') if 'fat binder' in product or 'thermo' in product or 'diet aid' in product or 'thermopure boost' in product\ or 'glucomannan' in product or 'diet gel' in product: categories.append('Fatburner') if 'fiber' in product: categories.append('Superfoods') if 'flavdrop' in product: categories.append('Aromen und Süßstoffe') if 'gel' in product: categories.append('Weitere') if 'glucosamin' in product: categories.append('Glucosamin') if 'glucose' in product or 'dextrin carbs' in product or 'palatinose' in product: categories.append('Kohlenhydratpulver') if 'glutamin' in product: categories.append('Glutamin') if 'granola' in product or 'crispies' in product or 'oats' in product or 'hafer' in product: categories.append('Getreide') if 'hmb' in product: categories.append('HMB') if 'koffein' in product: categories.append('Koffein') if 'latte' in product or 'mocha' in product or 'kakao' in product or 'tee' in product: categories.append('Tee & Kaffee') if 'magnesium' in product: categories.append('Magnesium') if 'mahlzeitenersatz' in product: categories.append('Mahlzeitenersatz-Shakes') if 'maltodextrin' in product: categories.append('Maltodextrin') if 'mandeln' in product or 'samen' in product or 'nüsse' in product or 'nut' in product: categories.append('Nüsse & Samen') if 'öl' in product: categories.append('Speiseöle') if 'ornithin' in product: categories.append('Ornithin') if 'pancake' in product or 'cake' in product: categories.append('Backmischungen') if 'performance mix' in product or 'recovery blend' in product or 'collagen protein' in product or \ 'dessert' in product: categories.append('Protein Mischungen') if 'phosphatidylserin' in product or 'leucin' in product or 'tribulus' in product: categories.append('Planzliche Nahrungsergänzungsmittel') if 'pork crunch' in product: categories.append('Jerkey') if 'pre-workout' in product or 'pump' in product or 'pre workout' in product or 'preworkout' in product: categories.append('Trainingsbooster') if 'reis' in product: categories.append('Alltägliche Lebensmittel') if 'sirup' in product: categories.append('Syrup') if "soja protein" in product: categories.append("Sojaprotein") if 'soße' in product: categories.append('Gewürze & Saucen') if 'spaghetti' in product or 'penne' in product or 'fettuccine' in product: categories.append('Pizza & Pasta') if 'taurin' in product: categories.append('Taurin') if 'tyrosin' in product: categories.append('Tyrosin') if 'veganes performance bundle' in product: categories.append('Veganes Protein') if 'vitamin b' in product: categories.append('Vitamin B') if 'vitamins bundle' in product or 'multivitamin' in product or 'immunity plus' in product or \ 'the multi' in product: categories.append('Multivitamine') if 'vitamin c' in product: categories.append('Vitamin C') if 'vitamin d' in product: categories.append('Vitamin D') if 'waffel' in product or 'protein ball' in product: categories.append('Schokolade') if 'whey' in product: categories.append('Whey Protein') if 'zink' in product: categories.append('Zink') if 'bcaa' in product or 'amino' in product: # Many product with amino in -> Make sure this is the last categories.append('BCAA') # Return all categories a product is in return categories # Match categories from shop zecplus to mister m categories. # Matching based on product name. def parse_zecplus(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_zecplus: # Check product name for patterns in order to replace category with mister m category if "all in one" in product: categories.append("Multivitamine") if "antioxidan" in product: categories.append("Antioxidantien") if "arginin" in product: categories.append("Arginin") if "aroma" in product: categories.append("Aromen und Süßstoffe") if "arthro" in product: categories.append("Glucosamin") if "bcaa" in product: categories.append("BCAA") if "beta alanin" in product: categories.append("Beta Alanin") if "casein" in product: categories.append("Casein Protein") if "citrullin" in product: categories.append("Citrullin") if "creatin" in product: categories.append("Creatin") if "dextrose" in product: categories.append("Dextrose") if "eaa" in product: categories.append("EAA") if "fischöl" in product: categories.append("Omega-3") if "gaba" in product: categories.append("Gaba") if "gainer" in product: categories.append("Weight Gainer") if "glutamin" in product: categories.append("Glutamin") if "greens" in product: categories.append("Pflanzliche Nahrungsergänzungsmittel") if "kickdown" in product or "testosteron booster" in product: categories.append("Trainingsbooster") if "koffein" in product: categories.append("Koffein") if "kohlenhydrate" in product: categories.append("Kohlenhydratpulver") if "kokosöl" in product: categories.append("Speiseöle") if "liquid egg" in product: categories.append("Eiklar") if "maltodextrin" in product: categories.append("Maltodextrin") if "mehrkomponenten" in product: categories.append("Protein Mischungen") if "nährstoff optimizer" in product or "sleep" in product: categories.append("Probiotika") if "nudeln" in product or "pizza" in product: categories.append("Pizza & Pasta") if "oats" in product: categories.append("Getreide") if "proteinriegel" in product: categories.append("Proteinriegel") if "reis protein" in product: categories.append("Reisprotein") if "pulvermischung" in product or "pancakes" in product or 'bratlinge' in product: categories.append("Backmischungen") if "tryptophan" in product or "intraplus" in product or 'leucin' in product: categories.append("Aminosäuren Komplex") if "vitamin b" in product: categories.append("Vitamin B") if "vitamin c" in product: categories.append("Vitamin C") if "vitamin d" in product: categories.append("Vitamin D") if "whey" in product or "clean concentrate" in product: categories.append("Whey Protein") if "zink" in product: categories.append("Zink") # Return all categories a product is in return categories # Match categories from shop zecplus to mister m categories. # Matching based on product name. def parse_weider(category, product): # Categories a product can be in categories = [] # Product name to lower case for better string matching product = product.lower() # Category name to lower case for better string matching category = category.lower() # Check if product category needs to be placed into another category if category in d.toparse_weider: # Check product name for patterns in order to replace category with mister m category if "ace" in product or "mineralstack" in product or "megabolic" in product or "multi vita" in product\ or "joint caps" in product: categories.append("Multivitamine") if "amino blast" in product or "amino nox" in product or "amino egg" in product or "amino powder" in product\ or "amino essential" in product: categories.append("Aminosäuren Komplex") if "amino power liquid" in product or "bcaa rtd" in product or "eaa rtd" in product or "rush rtd" in product: categories.append("Aminosäuren Getränke") if "arginin" in product: categories.append("Arginin") if "bar" in product or "classic pack" in product or "riegel" in product or "wafer" in product: categories.append("Proteinriegel") if "bcaa" in product: categories.append("BCAA") if "glucan" in product: categories.append("Antioxidantien") if "casein" in product: categories.append("Casein Protein") if "cla" in product: categories.append("CLA") if "creme" in product: categories.append("Aufstriche") if "coffee" in product: categories.append("Tee & Kaffee") if "cookie" in product: categories.append("Cookies & Muffins") if "eaa" in product: categories.append("EAA") if "fresh up" in product: categories.append("Aromen und Süßstoffe") if "glucosamin" in product: categories.append("Glucosamin") if "glutamin" in product: categories.append("Glutamin") if "hmb" in product: categories.append("HMB") if "magnesium" in product: categories.append("Magnesium") if "omega 3" in product: categories.append("Omega-3") if "protein low carb" in product or "protein shake" in product or "starter drink" in product: categories.append("Protein Drinks") if "pump" in product or "rush" in product: categories.append("Trainingsbooster") if "soy 80" in product: categories.append("Sojaprotein") if "thermo stack" in product: categories.append("Fatburner") if "vegan protein" in product: categories.append("Veganes Protein") if "water" in product: categories.append("Ohne Kalorien") if "whey" in product or "protein 80" in product: categories.append("Whey Protein") if "zinc" in product: categories.append("Zink") # Return all categories a product is in return categories
653b56c505745fb2947589692c3a628d149d27ef
robertmplewis/playground
/wordquiz.py
649
3.921875
4
#!/usr/bin/env python import operator def main(): print word_count() def word_count(): word_totals = { } book_contents = f.read() book_contents = book_contents.replace('\n', ' ') book_contents = book_contents.replace(',', '') book_contents = book_contents.replace('.', '') book_contents = book_contents.replace('"', '') book_split = book_contents.split(' ') for word in book_split: if word not in word_totals: word_totals[word] = 1 word_totals[word] += 1 word_totals = sorted(word_totals.items(), key=operator.itemgetter(1)) return word_totals f = open('rob-book.txt','r') if __name__ == '__main__': main()
375b0579cdbe45e4a66d954f8d5e767f8ef70546
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 2/Task 5.py
261
4.28125
4
# Write a list comprehension which, from a list, generates a lowercased version of each string # that has length greater than five strings = ['Some string', 'Art', 'Music', 'Artifical Intelligence'] for x in strings: if len(x) > 5: print(x.lower())
a54b52aee8ebf3cf44dc050ee68699aa4c6ee011
justEhmadSaeed/ai-course-tasks
/Python Assignment 1/Part 3/Task 3.2.py
306
3.6875
4
# One line function for intersection # Uncomment below code to generate random lists intersection = lambda a, b: list(set(a) & set(b)) # import random # a = [] # b = [] # for i in range(0, 10): # a.append(random.randint(0, 20)) # b.append(random.randint(5, 20)) # print(intersection(a, b))
af2ca98dfba5c5fdf958422f55c0685bef3937e4
JanBednarik/micropython-matrix8x8
/examples/game_of_life.py
1,870
3.5
4
import pyb from matrix8x8 import Matrix8x8 def neighbors(cell): """ Yields neighbours of cell. """ x, y = cell yield x, y + 1 yield x, y - 1 yield x + 1, y yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y yield x - 1, y + 1 yield x - 1, y - 1 def advance(board): """ Advance to next generation in Conway's Game of Life. """ new_board = set() for cell in ((x, y) for x in range(8) for y in range(8)): count = sum((neigh in board) for neigh in neighbors(cell)) if count == 3 or (count == 2 and cell in board): new_board.add(cell) return new_board, new_board == board def generate_board(): """ Returns random board. """ board = set() for x in range(8): for y in range(8): if pyb.rng() % 2 == 0: board.add((x, y)) return board def board_to_bitmap(board): """ Returns board converted to bitmap. """ bitmap = bytearray(8) for x, y in board: bitmap[x] |= 0x80 >> y return bitmap def restart_animation(display): """ Shows restart animation on display. """ for row in range(8): display.set_row(row, 0xFF) pyb.delay(100) for row in range(8): display.clear_row(7-row) pyb.delay(100) display = Matrix8x8(brightness=0) board, still_life = None, False while True: # init or restart of the game if still_life or not board: board = generate_board() restart_animation(display) pyb.delay(500) display.set(board_to_bitmap(board)) pyb.delay(500) # advance to next generation board, still_life = advance(board) display.set(board_to_bitmap(board)) # finish dead if not board: pyb.delay(1500) # finish still if still_life: pyb.delay(3000)
c6324a495ce9b5cd11784e34e4da56c427482e1f
daniellopes04/uva-py-solutions
/list2/120 - Stacks of Flapjacks.py
1,011
3.5
4
# -*- coding: UTF-8 -*- def main(): while True: try: unsorted = list(map(int, input().split())) current = unsorted.copy() final = sorted(unsorted) N = len(final) steps = [] for i in range(len(current) - 1, -1, -1): index = current.index(final[i]) if index == i: continue if index == 0: current[0:i + 1] = current[0:i + 1][::-1] steps.append(N - i) else: current[0:index + 1] = current[0:index + 1][::-1] current[0:i + 1] = current[0:i + 1][::-1] steps.append(N - index) steps.append(N - i) steps.append(0) print(" ".join(map(str, unsorted))) print(" ".join(map(str, steps))) except(EOFError) as e: break if __name__ == '__main__': main()
0babe69773bebc354b6da02c83f1fd151b4034dc
daniellopes04/uva-py-solutions
/list3/902 - Password Search.py
943
3.5625
4
# -*- coding: UTF-8 -*- def main(): while True: try: line = input().strip() while line == "": line = input().strip() items = line.split() if len(items) == 2: n = int(items[0]) text = items[1] else: n = int(items[0]) text = input().strip() while text == '': text = input().strip() frequency = {} for i in range(len(text) - n + 1): substr = text[i:i+n] if substr in frequency: frequency[substr] += 1 else: frequency[substr] = 1 password = max(frequency.keys(), key=(lambda k: frequency[k])) print(password) except(EOFError): break if __name__ == '__main__': main()
8353125ae9724cfef90b738d8aad6998ca78f8fe
SpCrazy/crazy
/code/SpiderDay03/bs4_learn/hello.py
283
3.5
4
from urllib.request import urlopen from bs4 import BeautifulSoup response = urlopen("http://www.pythonscraping.com/pages/page1.html") bs = BeautifulSoup(response.read(),"html.parser") print(bs.h1) print(bs.h1.get_text()) print(bs.h1.text) print(bs.html.body.h1) print(bs.body.h1)
4788dd580886d9d056d2c5847cacda6b2a95628e
SpCrazy/crazy
/code/SpiderDay1_Thread/condition/concumer.py
821
3.78125
4
import time from threading import Thread, currentThread class ConsumerThread(Thread): def __init__(self, thread_name, bread, condition): super().__init__(name=thread_name) self.bread = bread self.condition = condition def run(self): while True: self.condition.acquire() if self.bread.count > 0: time.sleep(2) self.bread.consume_bread() print(currentThread().name + "消费了面包,当前面包数量为:", self.bread.count) self.condition.release() else: print("面包已消费完," + currentThread().name + ",请等待生产,当前面包数量为:", self.bread.count) self.condition.notifyAll() self.condition.wait()
8c0d380707fd8ed99cba1e6e44a13b63313bc0c7
whlg0501/2018_PAT
/1004.py
1,663
3.578125
4
""" 1004 成绩排名 (20)(20 分) 读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。 输入格式:每个测试输入包含1个测试用例,格式为 第1行:正整数n 第2行:第1个学生的姓名 学号 成绩 第3行:第2个学生的姓名 学号 成绩 第n+1行:第n个学生的姓名 学号 成绩 其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。 输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。 输入样例: 3 Joe Math990112 89 Mike CS991301 100 Mary EE990830 95 输出样例: Mike CS991301 Joe Math990112 """ class student(object): def __init__(self, name, id, points): self.name = name self.id = id self.points = points def main(): studentsList = [] n = int(input()) count = 0 while(count < n): input_string = input().split(" ") studentsList.append(student(input_string[0], input_string[1], int(input_string[2]))) count += 1 max = studentsList[0] min = studentsList[0] for i in range(0, len(studentsList)): if(studentsList[i].points > max.points): max = studentsList[i] if(studentsList[i].points < min.points): min = studentsList[i] print("{} {}".format(max.name, max.id)) print("{} {}".format(min.name, min.id)) main() # 注意format比%要好用的多
c9fd907f7db76ed478ad64875951242b3dcebf0f
whlg0501/2018_PAT
/1049.py
1,239
3.5625
4
""" 1049 数列的片段和(20)(20 分)提问 给定一个正数数列,我们可以从中截取任意的连续的几个数,称为片段。例如,给定数列{0.1, 0.2, 0.3, 0.4},我们有(0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4) 这10个片段。 给定正整数数列,求出全部片段包含的所有的数之和。如本例中10个片段总和是0.1 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0。 输入格式: 输入第一行给出一个不超过10^5^的正整数N,表示数列中数的个数,第二行给出N个不超过1.0的正数,是数列中的数,其间以空格分隔。 输出格式: 在一行中输出该序列所有片段包含的数之和,精确到小数点后2位。 输入样例: 4 0.1 0.2 0.3 0.4 输出样例: 5.00 """ # l = [1,2,3,4] # for i in range(0, len(l) + 1): # for j in range(0,i): # print(l[j:i]) def main(): result = 0.0 num = input() l = input().split(" ") l = [float(x) for x in l] for i in range(0, len(l) + 1): for j in range(0, i): # print(l[j:i]) result += sum(l[j:i]) print("%.2f" %result) main()
23d0b02ba64c2aca3becf467d88c692109aab9f8
patnaik89/string_python.py
/condition.py
1,696
4.125
4
""" Types of conditional statements:- comparision operators (==,!=,>,<,<=,>=) logical operators (and,or,not) identity operators (is, is not) membership operators (in, not in) """ x, y = 2,9 print("Adition", x + y) print("multiplication", x * y) print("subtraction", x - y) print("division", x/y) print("Modular", x%y) print("floor division", x//y) print("power: ", x ** y) # finding a 'number' is there in given list or not list1 = [22,24,36,89,99] if 24 in list1: print(True) else:print(False) # examples on if elif and else conditions if x>y: print("x is maximum") elif y>x: print("y is maximum") else: print("both are equal") # Finding the odd and even numbers in given list list1 = [1,2,3,5,6,33,24,67,4,22,90,99] for num in range(len(list1)): if num % 2 == 0: print("Even Numbers are:", num,end=", ") else: print("The Odd Numbers are:", num) # Dynamic list using loops list2 = [] for number in range(10): if number % 2 == 0: # finding Even numbers in given range list2.append(number) print("Even numbers are:", list2) # finding all odd numbers within range 40 list1=[] for num in range(40): if num % 2 != 0: list1.append(num) print("odd numbers are", list1) # Dynamic set set1 = set() for number in range(10): set1.add(number) print("numbers in given range are:",set1) # printing duplicate elements list1=[1,1,2,4,4,5,44,56,2,99,49,99] l=sorted(set(list1)) # removing duplicate elements print(l) dup_list=[] for number in range(len(l)): if (list1.count(l[number]) > 1): dup_list.append(l[number]) print("duplicate elements in a list are: ",dup_list)
c0bd2b9a856537ea24d75bc6e73ec5396c0a987b
seanjib99/pythonProject14
/python 1.py
954
4
4
#s.n students take k apples and distribute each student evenly #The remaining parts remain in the basket. #How many apples will each single student get? #How many apples will remain in the basket?The programs read the numbers N and k. N=int(input("enter the number of students in class")] K= int(input("enter the number of apple:")} apples_get(K//N) remaining_apples=(K%N) print(f"each student got {apples_get}") print (f"The remaining apples are {remaining_apples}") # 4.N Given the integer N - the number of minutes that is passed since midnight. # How many hours and minutes are displayed on the 24h digital clock? # The program should print two numbers: # The number of hours(between 0 and 23) and the number of minutes (between 0 and 59) N = int(input("Enter the number of minutes passed since midnight: ")) hours = N//60 minutes = N%60 print(f"The hours is {hours}") print(f"The minutes is {minutes}") print(f"It's {hours}:{minutes} now.")
59eb59d435bb953bdc73df7a5df3d285dbfd6c93
cmillecan/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
460
4.03125
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) last_digit = abs(number) % 10 if number < 0: last_digit = -last_digit if last_digit > 5: print("Last digit of {:d} is {:d} and is greater \ than 5".format(number, last_digit)) elif last_digit == 0: print("Last digit of {:d} is {:d} and \ is 0".format(number, last_digit)) else: print("Last digit of {:d} is {:d} and is \ less than 6 and not 0".format(number, last_digit))
65ec659dbb339de8bfbfe81ae2556dcc314c8f0c
cmillecan/holbertonschool-higher_level_programming
/0x0B-python-input_output/13-student.py
816
3.875
4
#!/usr/bin/python3 """ Task 13 """ class Student: """Defines a student""" def __init__(self, first_name, last_name, age): """ Instantiation """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self, attrs=None): """ Retrieves a dictionary representation of Student. """ if attrs is None: return self.__dict__ else: new = {} for key in attrs: if key in self.__dict__: new[key] = self.__dict__[key] return new def reload_from_json(self, json): """ Replaces all attributes of the Student instance. """ for key in json: setattr(self, key, json[key])
bb204dab03699a3aaa32f558c92fd8fc697449ab
arkkhanu/Final-Project-OCR
/Server/hough_rect.py
6,941
3.609375
4
""" Module for finding a rectangle in the image, using Hough Line Transform. """ import itertools from typing import Union import numpy as np import cv2 import matplotlib.pyplot as plt from scipy.spatial import distance import consts def find_hough_rect(img: np.ndarray) -> Union[None, np.ndarray]: """ Find the main rectangle in the image using Hough Line Transform. If a rectangle is found, returning the ordered four points that define the rectangle, else returning None. """ img = cv2.GaussianBlur(img, (7, 7), 0) edged = cv2.Canny(img, 50, 250, apertureSize=3) lines = cv2.HoughLinesP(edged, rho=1, theta=np.pi / 180, threshold=150, minLineLength=img.shape[0] // 10, maxLineGap=img.shape[0] // 10) if lines is None: return None lines = lines.reshape((len(lines), 4)) # remove unnecessary dimension # sort lines by their lengths, from longest to shortest lines = sorted(lines, key=lambda l: distance.euclidean((l[0], l[1]), (l[2], l[3])), reverse=True) longest_lines = lines[:10] # take the longest lines # debug_show_lines(longest_lines, img.shape) pts = get_lines_intersect(longest_lines, img.shape[1], img.shape[0]) if pts is None: # hasn't managed to find four points of intersection return None return order_points(np.array(pts)) def get_lines_intersect(lines: list, img_width: int, img_height: int) -> Union[None, list[tuple[int, int]]]: """ Get the intersection points of the lines, only if there are exactly four of them. Reduce mistakes by filtering close points and unwanted points of intersection. """ # get the line equation for each of the lines line_equations = [get_line_equation(*line) for line in lines] pts = set() # get combination of two lines at a time for (m1, b1), (m2, b2) in itertools.combinations(line_equations, 2): if pt := get_intersection_point(m1, b1, m2, b2, img_width, img_height): pts.add(pt) pts = filter_close_pts(list(pts), min_pts_dst=img_width // 10) if len(pts) != 4: return None return pts def get_intersection_point(m1: float, b1: float, m2: float, b2: float, img_width: int, img_height: int) \ -> Union[None, tuple[int, int]]: """ Get the intersection points of two lines. If the point-of-intersection is out of bounds or the angle between the two lines is too small, returning None. Otherwise, returning the point. """ if m1 == m2: # slopes equal, lines will never meet return None # if either line is vertical, get the x from the vertical line, # and the y from the other line if m1 == consts.INFINITY: x = b1 y = m2 * x + b2 elif m2 == consts.INFINITY: x = b2 y = m1 * x + b1 else: x = (b2 - b1) / (m1 - m2) # equation achieved by solving m1*x+b1 = m2*x+b2 y = m1 * x + b1 if x < 0 or x > img_width - 1 or y < 0 or y > img_height - 1: # point-of-intersection out of bounds return None # obtain the angle between the two lines if m1 * m2 == -1: alpha = np.pi / 2 # lines are perpendicular, cannot divide by zero else: alpha = np.arctan(np.abs((m1 - m2) / (1 + m1 * m2))) if alpha < np.pi / 16: # if the angle is too small, then the two lines are almost # parallel, discard point of intersection return None return int(x), int(y) def filter_close_pts(pts: list[tuple[int, int]], min_pts_dst: int = 100) -> list[tuple[int, int]]: """ Remove points that are too close one another (usually caused by duplicate lines or lines very close to each other). """ filtered_pts = pts[:] for i, pt1 in enumerate(pts): for j, pt2 in enumerate(pts[i + 1:]): if distance.euclidean(pt1, pt2) < min_pts_dst and pt2 in filtered_pts: filtered_pts.remove(pt2) return filtered_pts def get_line_equation(x1, y1, x2, y2) -> tuple[float, float]: """ Get line equation (of the form y=mx+b), defined by two points. Returning the slope and b. If the two dots are on the same vertical line, then the line passing between them cannot be represented by the equation y=mx+b, therefore in that case returning 'infinite' slope and the x value of the vertical line. """ if x1 == x2: return consts.INFINITY, x1 # can't divide by zero, returning 'infinite' slope instead m = (y2 - y1) / (x2 - x1) # slope = dy / dx b = -m * x1 + y1 # derived from y=mx+b return m, b def order_points(pts: np.ndarray) -> np.ndarray: """ Order the points of the rectangle according to the following order: top-left, top-right, bottom-right, bottom-left. """ # prepare an array to hold the ordered points rect = np.zeros((4, 2), dtype=np.float32) # the top-left point will have the smallest sum, whereas # the bottom-right point will have the largest sum s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] # compute the difference between the points, the # top-right point will have the smallest difference, # whereas the bottom-left will have the largest difference diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def rect_area(ordered_pts: np.ndarray) -> float: """Calculate the area of the quadrilateral defined by the ordered points.""" # get x and y in vectors x, y = zip(*ordered_pts) # shift coordinates x_ = x - np.mean(x) y_ = y - np.mean(y) # calculate area correction = x_[-1] * y_[0] - y_[-1] * x_[0] main_area = np.dot(x_[:-1], y_[1:]) - np.dot(y_[:-1], x_[1:]) return 0.5 * np.abs(main_area + correction) # ----------- FOR DEBUGGING ----------- def debug_show_lines(lines, img_shape): temp = np.ones(img_shape) * 255 for line in lines: x1, y1, x2, y2 = line pt1, pt2 = debug_extend_line(x1, y1, x2, y2, img_shape[1], img_shape[0]) cv2.line(temp, pt1, pt2, 0, 7) plt.imshow(temp) plt.show() def debug_extend_line(x1, y1, x2, y2, img_width, img_height): if x1 == x2: return (x1, 0), (x1, img_height) m = (y2 - y1) / (x2 - x1) b = -m * x1 + y1 # derived from y-y1 = m(x-x1) f = lambda x: m * x + b if b < 0: pt1 = (int(-b // m), 0) elif b > img_height: pt1 = (int((img_height - b) // m), img_height - 1) else: pt1 = (0, int(f(0))) if f(img_width) > img_height: pt2 = (int((img_height - b) // m), img_height - 1) elif f(img_width) < 0: pt2 = (int(-b // m), 0) else: pt2 = (img_width, int(f(img_width))) return pt1, pt2
b24585f353af5a15200c7c9ef10d920ed3862fc5
SuryaDeepthiR/competitive-programming
/competitive-programming/Week2/Day-6/InPlaceShuffle.py
449
3.9375
4
import random def random_number(floor,ceiling): return random.randint(floor,ceiling) def shuffle(the_list): # Shuffle the input in place length = len(the_list) for i in range(0,length-1): j = random_number(0,length-1) the_list[i],the_list[j] = the_list[j],the_list[i] sample_list = [1, 2, 3, 4, 5] print 'Sample list:', sample_list print 'Shuffling sample list...' shuffle(sample_list) print sample_list
834612676d77e7be218b1898422ba94fff11196f
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/minimum-ascii-delete-sum-for-two-strings.py
1,970
3.828125
4
""" Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. Example 1: Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. Example 2: Input: s1 = "delete", s2 = "leet" Output: 403 Explanation: Deleting "dee" from "delete" to turn the string into "let", adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. Note: 0 < s1.length, s2.length <= 1000. All elements of each string will have an ASCII value in [97, 122]. Source: https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/ """ class Solution: def minimumDeleteSum(self, s1: str, s2: str) -> int: l1, l2 = len(s1), len(s2) # dp_sums[i][j] means the minimum delete sum for string s1[i:] and s2[j:] dp_sums = [[0] * (l2 + 1) for _ in range(l1 + 1)] for i in range(l1 - 1, -1, -1): dp_sums[i][l2] = dp_sums[i+1][l2] + ord(s1[i]) for i in range(l2 - 1, -1, -1): dp_sums[l1][i] = dp_sums[l1][i+1] + ord(s2[i]) for i in range(l1 - 1, -1, -1): for j in range(l2 - 1, -1, -1): if s1[i] == s2[j]: dp_sums[i][j] = dp_sums[i+1][j+1] else: dp_sums[i][j] = min(dp_sums[i+1][j] + ord(s1[i]), dp_sums[i][j+1] + ord(s2[j])) return dp_sums[0][0] if __name__ == "__main__": s1 = "sea" s2 = "eat" s12 = "delete" s22 = "leet" print(Solution().minimumDeleteSum(s1, s2)) print(Solution().minimumDeleteSum(s12, s22))
38ca97cf3452797e9460b01dcf61559d53643669
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/number_of_longest_increasing_subsequence.py
1,446
3.984375
4
""" 673. Number of Longest Increasing Subsequence source: https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/ Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5. Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int. """ class Solution: def findNumberOfLIS(self, nums: List[int]) -> int: result, max_len = 0, 0 dp = [[1, 1] for _ in range(len(nums))] # {length, number} pair for i in range(len(nums)): for j in range(i): if nums[i] > nums[j]: if dp[i][0] == dp[j][0]+1: dp[i][1] += dp[j][1] elif dp[i][0] < dp[j][0]+1: dp[i] = [dp[j][0]+1, dp[j][1]] if max_len == dp[i][0]: result += dp[i][1] elif max_len < dp[i][0]: max_len = dp[i][0] result = dp[i][1] return result if __name__ == "__main__": nums = [1, 3, 5, 4, 7] assert Solution().findNumberOfLIS(nums) == 2, "result is not correct"
f21b75948484cc34cea7d9d166dc47e72611749d
liadbiz/Leetcode-Solutions
/src/python/degree_of_array.py
1,373
4.15625
4
""" Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums. Example 1: Input: [1, 2, 2, 3, 1] Output: 2 Explanation: The input array has a degree of 2 because both elements 1 and 2 appear twice. Of the subarrays that have the same degree: [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So return 2. Example 2: Input: [1,2,2,3,1,4,2] Output: 6 Note: nums.length will be between 1 and 50,000. nums[i] will be an integer between 0 and 49,999. """ class Solution: def findShortestSubArray(self, nums): """ :type nums: List[int] :rtype: int """ import collections import operator fre_dict = collections.Counter(nums).most_common() max_fre = max(fre_dict, key = operator.itemgetter(1))[1] def fre_sub(i): return len(nums) - nums.index(i) - nums[::-1].index(i) return min(fre_sub(i[0]) for i in fre_dict if i[1] == max_fre) if __name__ == "__main__": nums1 = [1, 2, 2, 3, 1] nums2 = [1,2,2,3,1,4,2] print(Solution().findShortestSubArray(nums1)) print(Solution().findShortestSubArray(nums2))
7859a42286274f9710a439def03707787e93641b
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/jump_game_2.py
2,740
3.984375
4
""" Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. Note: You can assume that you can always reach the last index. """ class Solution: # 思路1: 时间复杂度为O(n),空间复杂度为O(n) # 第一步:求出每一个点能跳到的最远的地方 # 第二步:求出能到达每一个点的最小的坐标 # 第三步:从最后一个点出发,依次原则能到达该点的最小的点为jump经过的点。 # 可以证明此贪心过程为最优。 # 实际上还是保留了很多没有用的信息,显然比第二个方法编程要复杂一些。 def jump(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 reachs = [i + nums[i] for i in range(n)] min_reach_index = [float('inf')] * (n + 1) m = 0 for i,r in enumerate(reachs): min_reach_index[m:r + 1] = [min(i, _) for _ in min_reach_index[m:r + 1]] if r == n: break m = r + 1 res = 0 while n != 0: n = min_reach_index[n] res += 1 return res # 思路2: 时间复杂度为o(n),空间复杂度为O(1) # 遍历nums,维护变量max_index表示当前遍历过的点能跨到的最远的地方,变量 # crt_max_index表示我现在所在的点能跳到的最远的地方,当i大于crt_max_index的时候 # 说明我不能一次就跳到i,所以我要作出一次jump的选择,很明显,应该跳到max_index # 对应的那个位置,但是这个位置并不重要,我们只需要将次数加一即可,然后更新 # crt_max_index为max_index即可。 def jump(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 max_index = 0 crt_max_index = 0 for i, l in enumerate(nums): if i > crt_max_index: crt_max_index = max_index res += 1 max_index = max(max_index, i + l) return res if __name__ == "__main__": nums1 = [2,3,1,1,4] nums2 = [2, 0, 2, 0, 1] nums3 = [1, 1, 1, 1] nums4 = list(range(1, 25001))[::-1] + [1, 0] print(Solution().jump(nums1)) print(Solution().jump(nums2)) print(Solution().jump(nums3)) print(Solution().jump(nums4))
56ea95418a0ec5e08e1b85a87c7cd257e38754d4
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/Palindromic_string.py
1,191
4
4
""" #647 palindromic string https://leetcode.com/problems/palindromic-substrings/ Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Note: The input string length won't exceed 1000. """ class Solution: def countSubstrings(self, s: str) -> int: n = len(s) result = [[0] * n for _ in range(n)] # each char in s is a palindromic string for i in range(n): result[i][i] = 1 for i in range(n - 2, -1, -1): for j in range(n): if j - i > 2: result[i][j] = 1 if s[i] == s[j] and result[i+1][j-1] else 0 else: result[i][j] = 1 if s[i] == s[j] else 0 return sum(sum(l) for l in result) if __name__ == "__main__": s = 'abc' print(Solution().countSubstrings(s))
426bcfbcc836cd23ca4f5e00057781bf180f22e1
liadbiz/Leetcode-Solutions
/src/python/validate_binary_search_tree.py
763
4.0625
4
""" Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. source: https://leetcode.com/problems/validate-binary-search-tree/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: 'TreeNode') -> 'bool': pass if __name__ == "__main__": print(Solution().isValidBST())
3d6ff3e1c81878b956d537ba48a19df178ee55a5
liadbiz/Leetcode-Solutions
/src/python/dynamic_programming/mininum_cost_for_tickets.py
2,204
4.0625
4
""" In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways: + a 1-day pass is sold for costs[0] dollars; + a 7-day pass is sold for costs[1] dollars; + a 30-day pass is sold for costs[2] dollars. The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8. Return the minimum number of dollars you need to travel every day in the given list of days. problem source: https://leetcode.com/problems/minimum-cost-for-tickets/ """ from functools import lru_cache class Solution: # complexity: O(365) # space: O(365) # dp via days def mincostTickets(self, days: 'List[int]', costs: 'List[int]') -> 'int': days = set(days) durations = [1, 7, 30] # return the cost of traveling from day d to 365 def dp(i): if i > 365: return 0 elif i in days: return min(dp(i + d) + c for c, d in zip(costs, durations)) else: return dp(i + 1) return dp(1) # complexity: O(N) # space: O(N) # N is the length of `days` # dp via window def mincostTickets2(self, days: 'List[int]', costs: 'List[int]') -> 'int': durations = [1, 7, 30] N = len(days) def dp(i): if i >= N: return 0 res = float('inf') j = i for c, d in zip(costs, durations): while j < N and days[j] < days[i] + d: j += 1 res = min(res, c+dp(j)) return res return dp(0) if __name__ == "__main__": days =[1,4,6,7,8,20] costs = [2, 7, 15] days2 = [1,2,3,4,5,6,7,8,9,10,30,31] costs2= [2,7,15] print(Solution().mincostTickets(days, costs)) print(Solution().mincostTickets(days2, costs2)) print(Solution().mincostTickets2(days, costs)) print(Solution().mincostTickets2(days2, costs2))
498b0478db6e99d4bb321585b4c4fce7f2a9e269
liadbiz/Leetcode-Solutions
/src/python/largest_common_prefix.py
3,031
4.15625
4
""" description: Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. Issues: 1. The basic idea is: step1: find the min length of all str in the input list strs. step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice [min_index, max_index] of all In step 2, we can iterate the length from 1 to max_len. We can also iterate the length from max_len to 1. Obviously, the first one has the greatercomplexity. 2. difference between ' is not ' and ' != ': ' is not ' means the same object, ' != ' means the equal object, so we can not use ' is not ' is 'if' expression for judging if two prefix from different str are the same. see https://stackoverflow.com/questions/2209755/python-operation-vs-is-not for more information 3. ' else ' statement after ' for ' loop means: if the for loop exit normally, the code in 'else' will be excuted. """ class Solution: def longestCommonPrefix1(self, strs): """ :type strs: List[str] :rtype: str """ # handle empty list case if not strs: return "" # if not empty # step 1: find the min length of all string in list min_len = min([len(s) for s in strs]) # step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice # [min_index, max_index] of all for i in range(min_len, 0, -1): for j in range(len(strs) - 1): if strs[j][:i] != strs[j + 1][:i]: break else: return strs[0][:i] return "" def longestCommonPrefix2(self, strs): """ :type strs: List[str] :rtype: str """ # handle empty list case if not strs: return "" # if not empty # step 1: find the min length of all string in list min_len = min([len(s) for s in strs]) # step2: fix min_index at 0, increase max_index by 1 each iteration, check if the slice # [min_index, max_index] of all common_str = "" for i in range(1, min_len + 1): for j in range(len(strs) - 1): if strs[j][:i] != strs[j + 1][:i]: return strs[0][:(i - 1)] else: common_str = strs[0][:i] return common_str if __name__ == "__main__": strs1 = ["flower","flow","flight"] strs2 = ["dog","racecar","car"] # test solution1 print(Solution().longestCommonPrefix1(strs1)) print(Solution().longestCommonPrefix1(strs2)) # test solution2 print(Solution().longestCommonPrefix2(strs1)) print(Solution().longestCommonPrefix2(strs2))
36afe84aaa377106aa8a4eb6706c015a88fa7a49
liadbiz/Leetcode-Solutions
/src/python/reverse_integer.py
920
3.96875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example1: Input: 123 output: 321 Example2: Input: -123 Output: -321 Example3: Input: 120 Output: 21 Notes: what if the result overflow? what have learned: 1. in python 2, we can use cmp() function to get sign of the difference of two number a and b, in python 3, we can use (a > b) - (a < b) 2. str() function: int number to string """ class Solution: def reverse1(self, x): """ :type x: int :rtype: int """ if x < 0; return -self.reverse1(-x) result = 0 while x: result = result * 10 + x % 10 x //= 10 return result if result < 2 ** 31 else 0 def reverse2(self, x): """ :type x: int :rtype: int """ s = (x > 0) - (0 < x) r = int(str(s * x)[::-1]) return s * r * (r < 2**31)
6aac68ffc80dba1f5c76492a7dc37016f632556d
liadbiz/Leetcode-Solutions
/src/python/power_of_four.py
963
4
4
""" Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? """ class Solution: def isPowerOfFour(self, num): """ :type num: int :rtype: bool """ if num < 0: return False mask = 1 while mask < num: mask <<= 2 return True if mask & num else False def isPowerOfFour2(self, num): """ :type num: int :rtype: bool """ return True if num > 0 and not num & (num - 1) and num & 0x55555555 else False if __name__ == "__main__": print(Solution().isPowerOfFour(1)) print(Solution().isPowerOfFour(16)) print(Solution().isPowerOfFour(218)) print(Solution().isPowerOfFour2(1)) print(Solution().isPowerOfFour2(16)) print(Solution().isPowerOfFour2(218))
8cab006e87d608bdce1899e00044e13f8f09c3f2
liadbiz/Leetcode-Solutions
/src/python/minimum_moves2.py
990
4.03125
4
""" Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1. You may assume the array's length is at most 10,000. Example: Input: [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Idea: The minimum moves only occur when all the element moves to the median. """ class Solution: def minMoves2(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() return sum(nums[~i] - nums[i] for i in range(len(nums) // 2)) # solution2, same idea. """ median = sorted(nums)[len(nums) / 2] return sum(abs(num - median) for num in nums) """ if __name__ == "__main__": case1 = [1, 2, 3] print(Solution().minMoves2(case1))
26715c6de77437da8a9084c3aea2db86910a527d
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/split_array_into_consecutive_subsequences.py
2,647
4.09375
4
""" You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split. Example 1: Input: [1,2,3,3,4,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3 3, 4, 5 Example 2: Input: [1,2,3,3,4,4,5,5] Output: True Explanation: You can split them into two consecutive subsequences : 1, 2, 3, 4, 5 3, 4, 5 Example 3: Input: [1,2,3,4,4,5] Output: False Note: The length of the input is in range of [1, 10000] """ class Solution: # 思路:第一个函数是我一开始的想法,遍历nums中的元素,然后如果不能添加到之前 # 出现的连续序列的话,就算作是重新调整开始一个连续序列,如果能的话,添加到 # 最近的一个序列(长度最短),但是复杂度比较高,所以不能AC(超时) def isPossible1(self, nums): """ :type nums: List[int] :rtype: bool """ import collections dq = collections.deque() for n in nums: for i in reversed(dq): if i[1] == n - 1: i[1] += 1 break else: dq.append([n, n]) print(dq) return all(True if p[1] - p[0] >= 2 else False for p in dq ) # 这个方法复杂度就小很多,O(n)。 # 因为其实保留具体的连续子序列的信息是没有必要的,上一个函数之所以会超时, # 就是因为保留了无用信息。而该方法很好的解决了这个问题 # 来自: https://leetcode.com/problems/split-array-into-consecutive- # subsequences/discuss/106514/Python-esay-understand-solution def isPossible2(self, nums): """ :type nums: List[int] :rtype: bool """ import collections left = collections.Counter(nums) end = collections.Counter() for i in nums: if not left[i]: continue left[i] -= 1 if end[i - 1] > 0: end[i - 1] -= 1 end[i] += 1 elif left[i + 1] and left[i + 2]: left[i + 1] -= 1 left[i + 2] -= 1 end[i + 2] += 1 else: return False return True if __name__ == '__main__': nums1 = [1, 2, 3, 4, 5] nums2 = [1,2,3,3,4,4,5,5] nums3 = [1,2,3,4,4,5] print(Solution().isPossible(nums1)) print(Solution().isPossible(nums2)) print(Solution().isPossible(nums3))
49ebb1d0c3806b92ab6c158447171ceca908da42
liadbiz/Leetcode-Solutions
/src/python/greedy_algorithm/course_schedule_3.py
2,124
3.859375
4
""" There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day. Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken. Example: Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] Output: 3 Explanation: There're totally 4 courses, but you can take 3 courses at most: First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day. Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date. Note: The integer 1 <= d, t, n <= 10,000. You can't take two courses simultaneously. """ class Solution: # 思路:按照结束时间排序,依次遍历courses,维护一个变量start,表示当前学习的课程 # 花费的总时间,也是下一个课程的开始时间,如果不能学习当前遍历课程,说明之前某个 # 课程花费时间太长了,因此去掉该课程,进而学习当前遍历课程,这样只会让start变小 # 因此不会降低课程安排的最优性。这也证明了贪心法能得到最优解。 def scheduleCourse(self, courses): """ :type courses: List[List[int]] :rtype: int """ import heapq courses.sort(key=lambda x:x[1]) hq = [] start = 0 for t, e in courses: start += t heapq.heappush(hq, -t) while start > e: start += heapq.heappop(hq) return len(hq) if __name__ == "__main__": courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] print(Solution().scheduleCourse(courses))
893104e3a4ade89aa31e82a18df0695a040fbd9e
liadbiz/Leetcode-Solutions
/src/python/range_sum_query.py
771
3.71875
4
""" # 303 Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function. Accepted 128,904 Submissions 350,101 source: https://leetcode.com/problems/range-sum-query-immutable/ """ class NumArray: def __init__(self, nums: List[int]): self.nums = nums self.cache = dict() def sumRange(self, i: int, j: int) -> int: if not self.cache.get((i,j)): result = sum(self.nums[i:j+1]) self.cache[(i, j)] = result return result return self.cache[(i,j)]
be8da5d6998ab0d7cde8a800612dbabe81830c77
liadbiz/Leetcode-Solutions
/src/python/onebit_twobit.py
2,948
4.03125
4
""" 717. 1-bit and 2-bit Characters We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Example 1: Input: bits = [1, 0, 0] Output: True Explanation: The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. Example 2: Input: bits = [1, 1, 1, 0] Output: False Explanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1. Idea: + My thought: Iterate the `bits`, and check each two element pair, if the the pair equals to [1, 1] or [1, 0], increase `index` to `index + 2`, else `index + 1`. Stop the iteration if the index reach to `len(bits) - 2` or `len(bits) - 1`. If the `index` equals to the former, return False, and return True if it equals to the latter. + Increament pointer: When reading from the i-th position, if bits[i] == 0, the next character must have 1 bit; else if bits[i] == 1, the next character must have 2 bits. We increment our read-pointer i to the start of the next character appropriately. At the end, if our pointer is at bits.length - 1, then the last character must have a size of 1 bit. + Greedy The second-last 0 must be the end of a character (or, the beginning of the array if it doesn't exist). Looking from that position forward, the array bits takes the form [1, 1, ..., 1, 0] where there are zero or more 1's present in total. It is easy to show that the answer is true if and only if there are an even number of ones present. """ class Solution: def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ index = 0 l = len(bits) while index < l - 2: b = bits[index: (index + 2)] if b == [1, 0] or b == [1, 1]: index += 2 elif b == [0, 1] or b == [0, 0]: index += 1 print(index) return False if index == l - 2 else True def isOneBitCharacter2(self, bits): i = 0 while i < len(bits) - 1: i += bits[i] + 1 return i == len(bits) - 1 def isOneBitCharacter3(self, bits): parity = bits.pop() while bits and bits.pop(): parity ^= 1 return parity == 0 if __name__ == "__main__": case1 = [1, 0, 0] case2 = [1, 1, 1, 0] case3 = [0, 1, 0] print(Solution().isOneBitCharacter(case1)) print(Solution().isOneBitCharacter(case2)) print(Solution().isOneBitCharacter(case3))
04d56f4cfc176ede74a148b901dad5120b4b1270
Calico888/First-Steps---Quiz
/quiz 2.py
6,549
4.25
4
# Strings for the different difficulties easy_string = """I have a __1__ that one day this __2__ will rise up, and live out the true meaning of its creed: We hold these truths to be self-evident: that all men are created equal. Martin Luther King jr The greatest __3__ in living lies not in never falling, but in __4__ every time we fall. Nelson Mandela That is one small __5__ for a man, one giant leap for __6__. Neil Armstrong""" answer_list1 = ["dream", "nation", "glory", "rising", "step", "mankind" ] medium_string = """Do not __1__ the chickens before they are __2__. An eye for an __3__, a tooth for a __4__. Accept that some days you are the __5__, and some days you are the __6__.""" answer_list2 = ["count", "hatched", "eye", "tooth", "pigeon", "statue"] hard_string = """Judge your __1__ by what you had to give up in __2__ to get it. Dalai Lama In the end, it is not the __3__ in your life that count. It is the __4__ in your years. Abraham Lincoln Be the __5__ that you wish to see in the __6__ Mahatma Gandhi""" answer_list3 = ["success", "order", "years", "life", "change", "world"] def string_to_difficulty(difficulty): """ The method gets the difficulty as a string and returns the string, which belongs to the choosen difficulty and return and print it. parameters: input is the difficulty as a string. return: Is the string which belongs to difficulty. """ if difficulty == "easy": print easy_string return easy_string elif difficulty == "medium": print medium return medium_string else: print hard_string return hard_string def answer_list_to_difficulty(difficulty): """ The method gets the difficulty as string and returns the answers, which are strings and they are stored in a list parameters: input is the difficulty as a string return: the strings in a list. """ if difficulty == "easy": return answer_list1 elif difficulty == "medium": return answer_list2 else: return answer_list3 def difficulty(): """ The method has no input, the user is asked to choose the difficulty, also there is a check a while loop to make sure that the user chooses a difficulty, which is available. parameters: User input which is stored as string. return: the difficulty as a string """ difficult_grade = raw_input("Please enter your difficulty: easy, medium, hard: ") if difficult_grade == "easy" or difficult_grade == "medium" or difficult_grade == "hard": return difficult_grade while difficult_grade != "easy" or difficult_grade != "medium" or difficult_grade != "hard": difficult_grade = raw_input("Invalid Input, please enter easy, medium or hard: ") return difficult_grade def find_the_gaps(number, text_with_gaps): """ The method gets the number,as a int, which shows the gaps which we currently searching for. Also the method gets the text as a string. Then the methode is searching in the text for the number, which is transformed into a string, with a for loop. And if the number is found, the part of the text is returned. parameters: input is a number as int and the text as a string. return: None, when the number isn't found or the part of the text with the number in it as a string. """ number = str(number) for pos in text_with_gaps: if number in pos : return pos return None def answer_is_right(quiz_string, replacement, controll_answer): """ The method gets three inputs: the text as List with strings in it, replacement, which is a string and the right answer as string. First the text is transformed into a string and after that the replacement is replaced through the right answer. After that the the new text is printed. The next is to transform the string into a list again and return it. parameters: quiz string as list filled with strings, replacement is a string and the controll answer is a string,too. return: text with the right answer in it as list. """ quiz_string = " ".join(quiz_string) quiz_string = quiz_string.replace(replacement, controll_answer) print quiz_string quiz_string = quiz_string.split() return quiz_string def play_the_game(difficulty): """ The input for this method is the difficulty as a string. First the answer and the text as a string, which are belonging to the difficulty is defined to the methods string_to_difficulty and answer_list_to_difficulty. After that, there is a for loop which is going through the answer list to make sure every gap is filled. In the next step the the method find_the_gaps is used to find the gap which belongs to the actual number. Then the user has to fill in the first gap. if the answer is wrong, a while starts until the user entered the right answer or the countdown has reached 0. The method answer_is_right starts then. When every gap is filled the method returns a string. parameters: input is difficulty as string, in the method number as a int is used to show on which gap is searched for at the moment return: string when the quiz is solved or the countdown has reached 0. """ quiz_string = string_to_difficulty(difficulty) quiz_string = quiz_string.split() answer_list = answer_list_to_difficulty(difficulty) number = 1 countdown = 3 for element in answer_list: replacement = find_the_gaps(number,quiz_string) if replacement != None: user_answer = raw_input("Please enter your answer: ") if user_answer.lower() == answer_list[number - 1].lower(): quiz_string = answer_is_right(quiz_string, replacement, answer_list[number - 1]) number += 1 else: while user_answer.lower() != answer_list[number - 1].lower() or countdown > 0: user_answer = raw_input("Try again! You have " +str(countdown)+ " more tries: ") countdown = countdown - 1 if countdown == 0: return "Game Over" if user_answer.lower() == answer_list[number - 1].lower(): quiz_string = answer_is_right(quiz_string, replacement, answer_list[number - 1]) number += 1 break return "You win! Quiz solved!" print play_the_game(difficulty())
a060b33270c6c736e397f22f81ebab6f68b1a4e8
arcae/git_lesson-1
/data/portcsv.py
626
3.671875
4
#using csv module import csv def portfolio_cost(filename): ''' Computes total shares*proce for a CSV file with name,shares,price data' ''' total = 0.0 with open(filename,'r') as f: rows = csv.reader(f) headers = next(rows) #skip first row for headers for rowno, row in enumerate(rows,start=1): try: row[2] = int(row[2]) row[3] = float(row[3]) except ValueError as err: print('Row:',rowno, 'Bad row:',row) print('Row:',rowno, 'Reason:', err) continue #skip to the next row total += row[2]*row[3] return total total = portfolio_cost('Mydata1.csv') print('Total cost:', total)
a849d96ef408d998a3ec1b17ce74d6b02f7992ad
saurabhc123/unsupervised
/source/Ops.py
630
4.09375
4
from abc import ABC, abstractmethod class Ops(ABC): def __init__(self, name): self.name = name pass @abstractmethod def perform_op(self): print ("Performing op:" , self.name) pass class Addition(Ops): def __init__(self, name="Addition"): Ops.__init__(self, name) def perform_op(self): Ops.perform_op(self) print ("Performed op:"+ self.name) class Subtraction(Ops): def __init__(self, name="Subtraction"): Ops.__init__(self, name) def perform_op(self): print ("Performed op:"+ self.name) op = Addition() op.perform_op()