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
f3532d2e768187aa39d756f763755bdf3ebf4f75
pilot-github/programming
/leetcode/rotateRight.py
1,646
3.984375
4
########################################################### ## Given a linked list, rotate the list to the right by k places, where k is non-negative. ## ## Example 1: ## ## Input: 1->2->3->4->5->NULL, k = 2 ## Output: 4->5->1->2->3->NULL ## Explanation: ## rotate 1 steps to the right: 5->1->2->3->4->NULL ## rotate 2 steps to the right: 4->5->1->2->3->NULL ## ########################################################### def my_rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None or head.next is None or k == 0: return head length = 1 curr_node = head while curr_node.next: curr_node = curr_node.next length += 1 curr_node.next = head k = k%length for i in range(length-k): curr_node = curr_node.next head = curr_node.next curr_node.next = None return head def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return None if head.next == None: return head pointer = head length = 1 while pointer.next: pointer = pointer.next length += 1 rotateTimes = k%length if k == 0 or rotateTimes == 0: return head fastPointer = head slowPointer = head for a in range (rotateTimes): fastPointer = fastPointer.next while fastPointer.next: slowPointer = slowPointer.next fastPointer = fastPointer.next temp = slowPointer.next slowPointer.next = None fastPointer.next = head head = temp return head
d80e7ee5b9580fc2ac5978eef24763447b87f820
pilot-github/programming
/Sorting Algorithms/insertion_sort.py
299
3.890625
4
def insertion_sort(num): for i in range(1, len(num)): next = num[i] j = i-1 while num[j] > next and j>=0: num[j+1] = num[j] j = j-1 num[j+1] = next return num num = [19,2,31,45,6,11,121,27] print (insertion_sort(num))
82a55c0b7128beec9f63e1ffe47b1ce9ba78e26a
PabloMtzA/cse-30872-fa20-assignments
/challenge18/program.py
1,198
3.875
4
#!/usr/bin/env python3 ## Challenge 18 ## Pablo Martinez-Abrego Gonzalez ## Template from Lecture 19-A import collections import sys # Graph Structure Graph = collections.namedtuple('Graph', 'edges degrees') # Read Graph def read_graph(): edges = collections.defaultdict(set) degrees = collections.defaultdict(int) for line in sys.stdin: l = [char for char in line.rstrip()] for t, s in enumerate(l): if t + 1 < len(l) and l[t + 1] not in edges[s]: edges[s].add(l[t + 1]) degrees[l[t + 1]] += 1 degrees[s] return Graph(edges, degrees) # Topological Sort def topological_sort(graph): frontier = [v for v, d in graph.degrees.items() if d == 0] visited = [] while frontier: vertex = frontier.pop() visited.append(vertex) for neighbor in graph.edges[vertex]: graph.degrees[neighbor] -= 1 if graph.degrees[neighbor] == 0: frontier.append(neighbor) return visited # Main Execution def main(): graph = read_graph() vertices = topological_sort(graph) print(''.join(vertices)) if __name__ == '__main__': main()
6ff19bcd3f99699c58fa6b659b9840126591e386
willianresille/Learn-Python-With-DataScience
/DSA-Python-Capitulo2-Numeros.py
773
3.84375
4
# Operações Básicas # Soma 4 + 4 # Subtração 4 - 3 # Multiplicação 3 * 3 # Divisão 3 / 2 # Potência 4 ** 2 # Módulo 10 % 3 # Função Type type(5) type(5.0) a = 'Eu sou uma String' type(a) # Operações com números float # float + float = float 3.1 + 6.4 # int + float = float 4 + 4.0 # int + int = int 4 + 4 # int / int = float 4 / 2 # int // int = int 4 // 2 # int / float = float 4 / 3.0 # int // float = float 4 // 3.0 # Conversão float(9) int(6.0) int(6.5) # Hexadecimal e Binário hex(394) hex(217) bin(236) bin(390) # Funções abs, round e pow # Retorna o valor absoluto abs(-8) # Retorna o valor absoluto abs(8) # Retorna o valor com arredondamento round(3.14151922,2) # Potência pow(4,2) # Potência pow(5,3) # FIM
2a21f0fda2b30dc18f20e798182d285ab7f4b9e1
lepoidev/blossom
/blossom/structures.py
2,796
3.5
4
from helpers import sorted_pair # represents an undirected edge class Edge: def __init__(self, start, end, num_nodes): self.start, self.end = sorted_pair(start, end) self.id = (self.start * num_nodes) + self.end def __hash__(self): return hash(self.id) def __eq__(self, other): return other.id == self.id def __repr__(self): return '{start=' + str(self.start) + ' end=' + str(self.end) + '}' def __contains__(self, item): return item == self.start or item == self.end class Tree: def __init__(self, root): self.root = root self.edges = set() self.nodes = {root} self.dists = {root : 0} self.parent_map = {root : None} def __repr__(self): return self.nodes.__repr__() def add(self, edge): if edge.start in self.nodes: new_node = edge.end old_node = edge.start else: new_node = edge.start old_node = edge.end self.nodes.add(new_node) self.edges.add(edge) self.dists[new_node] = self.dists[old_node] + 1 self.parent_map[new_node] = old_node def has_node(self, node): return node in self.nodes def has_edge(self, edge): return edge in self.edges def dist_from_root(self, node): return self.dists[node] def path_to_root(self, node): path = [] cur = node while cur is not None: path.insert(0, cur) cur = self.parent_map[cur] return path def contract_edges(num_nodes, edges, B, blossom_root): contracted = set() B = set(B) for edge in edges: start = edge.start end = edge.end if start in B and end in B: continue if start in B and end not in B: start = blossom_root elif end in B and start not in B: end = blossom_root contracted.add(Edge(start, end, num_nodes)) return contracted class Matching: def __init__(self, num_nodes): self.num_nodes = num_nodes self.edges = set() def __repr__(self): return self.edges.__repr__() def augment(self, path): add = True for i in range(0, len(path) - 1): j = i + 1 start = path[i] end = path[j] edge = Edge(start, end, self.num_nodes) if add: self.edges.add(edge) elif edge in self.edges: self.edges.remove(edge) add = not add def get_contraction(self, B, blossom_root): contraction_M = Matching(self.num_nodes) contraction_M.edges = contract_edges(self.num_nodes, self.edges, B, blossom_root) return contraction_M
0eb37e3ffbd4addfa7e642bfd5fe0c39032285af
gingerComms/gingerCommsAPIs
/utils/metaclasses.py
870
3.609375
4
import types class DecoratedMethodsMetaClass(type): """ A Meta class that looks for a "decorators" list attribute on the class and applies all functions (decorators) in that list to all methods in the class """ def __new__(cls, class_name, parents, attrs): if "decorators" in attrs: decorators = attrs["decorators"] # Iterating over all attrs of the class and applying all of the # decorators to all attributes that are methods for attr_name, attr_value in attrs.items(): if isinstance(attr_value, types.FunctionType): method = attr_value for decorator in decorators: method = decorator(method) attrs[attr_name] = method return type.__new__(cls, class_name, parents, attrs)
5b0ab335563146599a579b204110ff11d6b70604
DragonWolfy/hw7
/hw8.py
1,143
3.984375
4
def get_words(filename): words=[] with open(filename, encoding='utf8') as file: text = file.read() words=text.split(' ') return words def words_filter(words, an_input_command): if an_input_command==('min_length'): print('1') a=('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') for word in words: if len(word)<len(a): a=word print(len(a)) elif an_input_command==('contains'): print('1') the_contained=input('What is contained? ') for word in words: for letter in word: if the_contained==letter: print(word) else: continue else: print('0') print('Can not work with', '"',an_input_command, '"') def main(): words = get_words('example.txt') a=input('input second variable: ') filtered_words = words_filter(words, a) __name__=input('input command: ') if __name__ == '__main__': main()
70917209c731ea36c0df05a94def58233f28a736
dendilz/30-Days-of-Code
/Day 6: Let's Review
356
3.84375
4
#!/usr/bin/env python x = int(input()) for _ in range(x): string = input() new_string = '' for index in range(len(string)): if index % 2 == 0: new_string += string[index] new_string += ' ' for index in range(len(string)): if index % 2 != 0 : new_string += string[index] print(new_string)
41c20076d3e9ba1433191c4f267605ccb6b351bf
zha0/punch_card_daily
/第二期-python30天/day2 变量/基础.py
554
4.15625
4
#coding: utf-8 #pring print("hello,world") print("hello,world","my name is liangcheng") #len #输出5 print(len("hello")) #输出0 a = "" print(len(a)) #输出3,tuple b = ("a","b","c") print(len(b)) # list 输出5 c = [1,2,3,4,5] print(len(c)) # range 输出9 d = range(1,10) print(len(d)) # dict 字典 输出1 e = {"name":"liangcheng"} print(len(e)) # set 输出5 f = {1,2,3,4,"laohu"} print(len(f)) # str ## 输出<type 'str'> print(type(str(10))) # int ## 输出:<type 'int'> print(type(int('123'))) #float ## print(type(float(10)))
21007e7b568b8ec5c39231759d282ec9d77f2f49
zha0/punch_card_daily
/第二期-python30天/day4 字符串/strings.py
5,298
4.5625
5
#coding: utf-8 #创建字符串 letter = 'P' print(letter) print(len(letter)) greeting = 'Hello World' print(greeting) print(len(greeting)) sentence = "this is a test" print(sentence) # 创建多行字符串 multiline_string = '''I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.''' print(multiline_string) multiline_string = """I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.""" print(multiline_string) # 字符串连接 first_name = 'liang' last_name = 'cheng' space = ' ' full_name = first_name + space + last_name print(full_name) print(len(first_name)) print(len(last_name)) print(len(first_name) > len(last_name)) print(len(full_name)) # 转义字符 print('I hope everyone is enjoying the python challage.\n Are you?') print('Days\tTopics\tExercises') print('Day 1\t3\t5') print('Day 2\t3\t5') print('Day 3\t3\t5') print('Day 4\t3\t5') print('This is a backslash symbol (\\)') print('this is a \"test\".') #output ''' I hope everyone is enjoying the python challage. Are you? Days Topics Exercises Day 1 3 5 Day 2 3 5 Day 3 3 5 Day 4 3 5 This is a backslash symbol (\) this is a "test". ''' # 格式化字符串 # 字符串 first_name = 'liang' last_name = 'cheng' language = 'python' format_sting = 'I am %s %s. I teach %s' %(first_name, last_name, language) print(format_sting) #字符串和数字 radius = 10 pi = 3.14 area = pi * radius ** 2 format_sting = 'The area of circle with a radius %d is %.2f.' %(radius, pi) print(format_sting) python_libraries = ['Django', 'Flask', 'NunPy', 'Matplotlib', 'Pandas'] format_sting = 'the following are python libraries: %s' %(python_libraries) print(format_sting) first_namem = 'liang' last_name = 'cheng' language = 'python' format_sting = 'i am {} {}. i study {}'.format(first_name,last_name,language) print(format_sting) # num运算 a = 4 b = 3 print('{} + {} = {}'.format(a, b, a + b)) print('{} - {} = {}'.format(a, b, a - b)) print('{} * {} = {}'.format(a, b, a * b)) print('{} / {} = {:.2f}'.format(a, b, a / b)) # 保留小数点后两位 print('{} % {} = {}'.format(a, b, a % b)) print('{} // {} = {}'.format(a, b, a // b)) print('{} ** {} = {}'.format(a, b, a ** b)) # output # 4 + 3 = 7 # 4 - 3 = 1 # 4 * 3 = 12 # 4 / 3 = 1.00 # 4 % 3 = 1 # 4 // 3 = 1 # 4 ** 3 = 64 # string and num radius = 10 pi = 3.14 area = pi * radius ** 2 format_sting = '半径为 {} 圆的面积为:{:.2f}'.format(radius, area) print(format_sting) #f-sting , 报语法错误 # a = 4 # b = 3 # print(f'{a} + {b} = {a + b}') # print(f'{a} - {b} = {a - b}') # print(f'{a} * {b} = {a * b}') # print(f'{a} / {b} = {a / b}') # print(f'{a} % {b} = {a % b}') # print(f'{a} // {b} = {a // b}') # print(f'{a} ** {b} = {a ** b}') # unpacking characters language = 'python' a,b,c,d,e,f = language print(a) print(b) print(c) print(d) print(e) print(f) # strings by index language = 'python' first_letter = language[0] print(first_letter) # p second_letter = language[1] print(second_letter) #y last_index = len(language) - 1 last_letter = language[last_index] print(last_letter) # n print('-------------------') last_letter = language[-1] # n second_letter = language[-2] # o print(last_letter,second_letter) # 切割字符串 language = 'python' first_three = language[0:3] # pyt print(first_three) last_three = language[3:6] print(last_three) #hon last_three = language[-3:] print(last_three) #hon last_three = language[3:] print(last_three) #hon # 反转字符串 greeting = 'hello, world' print(greeting[::-1]) # dlrow ,olleh # 切割时跳过字符 ## 通过向切片方法传递步骤参数,可以在切片时跳过字符。 language = 'python' pto = language[0:6:2] print(pto) #pto # capitalize challenge = 'thirty days of python' print(challenge.capitalize()) # Thirty days of python #count challenge = 'thirty days of python' print(challenge.count('y')) # 3 print(challenge.count('y',7,14)) #1 print(challenge.count('th')) #2 #endswith challenge = 'thirty days of python' print(challenge.endswith('on')) # True print(challenge.endswith('tion')) # False # expandtabs() challenge = 'thirty\tdays\tof\tpython' print(challenge.expandtabs()) # thirty days of pytho print(challenge.expandtabs(10)) # thirty days of python # find challenge = 'thirty days of python' print(challenge.find('on')) # 19 print(challenge.find('th')) # 0 # rfind challenge = 'thirty days of python' print(challenge.rfind('y')) # 16 print(challenge.rfind('th')) # 17 #format first_name = 'liang' last_name= 'cheng' age = 230 job = 'teacher' country = 'Findlan' sentence = 'I am {} {}. I am a {}. I am {} years old. I live in {}.'.format(first_name,last_name,age,job,country) print(sentence) # index challenge = 'thirty days of python' sub_string = 'da' print(challenge.index(sub_string)) # 7 # print(challenge.index(sub_string, 9)) # ValueError print(challenge.index('th')) # 0 print(challenge.index('o')) # 12 # rindex challenge = 'thirty days of python' sub_string = 'da' print(challenge.rindex(sub_string)) # 7 # print(challenge.rindex(sub_string, 9)) # ValueError print(challenge.rindex('th')) # 0 print(challenge.rindex('o')) # 12
d29c3d2cbfc84a08e26f7128431b91a9ddacd489
zha0/punch_card_daily
/第二期-python30天/day17 异常处理(exception handling)/day17_ Unpacking.py
2,542
3.53125
4
# coding: utf-8 def sum_of_five_nums(a,b,c,d,e): return a + b + c + d + e lst = [1,2,3,4,5] # TypeError: sum_of_five_nums() missing 4 required positional arguments: 'b', 'c', 'd', and 'e' # print(sum_of_five_nums(lst)) def sum_of_five_nums(a,b,c,d,e): return a + b + c + d + e lst = [1,2,3,4,5] print(sum_of_five_nums(*lst)) # 15 numbers = range(2, 7) print(list(numbers)) # [2, 3, 4, 5, 6] args = [2, 7] numbers = range(*args) print(list(numbers)) # [2, 3, 4, 5, 6] countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] fin, sw, nor, *rest = countries print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] numbers = [1,2,3,4,5,6,7] one, *middle, last = numbers print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7 def unpacking_person_info(name, country, city, age): return f'{name} lives in {country}, {city}. he is {age} year old.' dct = {'name':'liang', 'country':'china', 'city':'beijing', 'age':28} print(unpacking_person_info(**dct)) # liang lives in china, beijing. he is 28 year old. # packing list def sum_all(*args): s = 0 for i in args: s += i return s print(sum_all(1,2,3)) # 6 print(sum_all(1,2,3,4,5,6,7)) # 28 def packing_person_info(**kwargs): for key in kwargs: print(f"{key} = {kwargs[key]}") return kwargs # {'name': 'liang', 'country': 'china', 'city': 'shanghai', 'age': 18} print(packing_person_info(name='liang',country='china',city='shanghai',age=18)) # Spreading in Python lst_one = [1,2,3] lst_two = [4,5,6] lst = [0, *lst_one, *lst_two] print(lst) # [0, 1, 2, 3, 4, 5, 6] country_lst_one = ['Finland', 'sweden', 'norway'] country_lst_two= ['denmak', 'icelang', 'china'] nordic_country = [*country_lst_one, * country_lst_two] # ['Finland', 'sweden', 'norway', 'denmak', 'icelang', 'china'] print(nordic_country) # enumerate for index, item in enumerate([20, 30, 40]): print(index, item) # 0 20 # 1 30 # 2 40 for index, i in enumerate(countries): print('hi') if i == 'Finland': print(f'the country {i} has been found at index {index}') # zip fruits = ['banana', 'orange', 'mango', 'lemon','lime'] vegetables = ['tomato','potato', 'cabbage', 'onion','carrot'] fruits_and_vegetables = [] for f,v in zip(fruits, vegetables): fruits_and_vegetables.append({'fruit':f, 'veg':v}) # [{'fruit': 'banana', 'veg': 'tomato'}, {'fruit': 'orange', 'veg': 'potato'}, {'fruit': 'mango', 'veg': 'cabbage'}, {'fruit': 'lemon', 'veg': 'onion'}, {'fruit': 'lime', 'veg': 'carrot'}] print(fruits_and_vegetables)
d5f417eb2376e467d58c96d9d31fc10a2379dff6
LakshmiSaicharitha-Yallarubailu/TSF_TASKS
/Exploratory Data Analysis-Retail.py
3,181
3.8125
4
#!/usr/bin/env python # coding: utf-8 # # THE SPARKS FOUNDATION # NAME: Y.LAKSHMI SAICHARITHA # # # 1.Perform ‘Exploratory Data Analysis’ on dataset ‘SampleSuperstore’ 2.As a business manager, try to find out the weak areas where you can work to make more profit. # In[34]: #Importing the libraries import numpy as np import pandas as pd import seaborn as sb import matplotlib.pyplot as plt # In[2]: #loading dataset ds=pd.read_csv(r"C:\Users\Saicharitha\Downloads\SampleSuperstore.csv") ds # In[3]: ds.head(6) # In[4]: ds.tail(3) # In[5]: ds.info() # In[6]: ds.describe() # In[7]: ds.isnull().sum() # In[8]: ds.isna().sum() # In[9]: ds.drop(['Postal Code'],axis=1,inplace=True) # In[10]: ds # In[11]: sales_ds = ds.groupby('Category', as_index=False)['Sales'].sum() subcat_ds = ds.groupby(['Category','Sub-Category'])['Sales'].sum() subcat_ds['Sales']=map(int,subcat_ds) sales_ds # # Exploratory Data Analysis # In[12]: ds.plot(x='Quantity',y='Sales',style='.') plt.title('Quantity vs Sales') plt.xlabel('Quantity') plt.ylabel('Sales') plt.grid() plt.show() # In[13]: ds.plot(x='Discount',y='Profit',style='.') plt.title('Discount vs Profit') plt.xlabel('Discount') plt.ylabel('Profit') plt.grid() plt.show() # In[14]: sb.pairplot(ds) # In[15]: sb.pairplot(ds,hue='Category',diag_kind='hist') # In[16]: sb.pairplot(ds,hue='Region') # In[17]: ds['Category'].value_counts() sb.countplot(x=ds['Category']) # In[18]: ds.corr() # In[21]: sb.heatmap(ds.corr(), annot=True) # In[32]: fig,axs=plt.subplots(nrows=2,ncols=2,figsize=(10,7)); sb.countplot(ds['Category'],ax=axs[0][0]) sb.countplot(ds['Segment'],ax=axs[0][1]) sb.countplot(ds['Ship Mode'],ax=axs[1][0]) sb.countplot(ds['Region'],ax=axs[1][1]) axs[0][0].set_title('Category',fontsize=20) axs[0][1].set_title('Segment',fontsize=20) axs[1][0].set_title('Ship Mode',fontsize=20) axs[1][1].set_title('Region',fontsize=20) # In[35]: fig, axs = plt.subplots(ncols=2, nrows = 2, figsize = (10,10)) sb.distplot(ds['Sales'], color = 'red', ax = axs[0][0]) sb.distplot(ds['Profit'], color = 'green', ax = axs[0][1]) sb.distplot(ds['Quantity'], color = 'orange', ax = axs[1][0]) sb.distplot(ds['Discount'], color = 'blue', ax = axs[1][1]) axs[0][0].set_title('Sales Distribution', fontsize = 20) axs[0][1].set_title('Profit Distribution', fontsize = 20) axs[1][0].set_title('Quantity distribution', fontsize = 20) axs[1][1].set_title('Discount Distribution', fontsize = 20) plt.show() # In[22]: plt.title('Region') plt.pie(ds['Region'].value_counts(),labels=ds['Region'].value_counts().index,autopct='%1.1f%%') plt.show() # In[23]: plt.title('Ship Mode') plt.pie(ds['Ship Mode'].value_counts(),labels=ds['Ship Mode'].value_counts().index,autopct='%1.1f%%') plt.show() # In[24]: ds.groupby('Segment')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various Segments") # In[25]: ds.groupby('Region')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various Regions") # In[26]: plt.figure(figsize=(14,6)) ds.groupby('State')['Profit'].sum().sort_values().plot.bar() plt.title("Profits on various States")
8764b0e4ca1d4a8ca5c3995bddb193f959204385
skyworksinc/ACG
/ACG/VirtualObj.py
865
3.859375
4
import abc class VirtualObj(metaclass=abc.ABCMeta): """ Abstract class for creation of primitive objects """ def __init__(self): self.loc = {} def __getitem__(self, item): """ Allows for access of items inside the location dictionary without typing .loc[item] """ return self.export_locations()[str(item)] def export_locations(self): """ This method should return a dict of relevant locations for the virtual obj""" return self.loc @abc.abstractmethod def shift_origin(self, origin=(0, 0), orient='R0'): """ This method should shift the coordinates of relevant locations according to provided origin/transformation, and return a new shifted object. This is important to allow for deep manipulation in the hierarchy """ pass
6085c6ada49aeee0f84a290d490cf12dd683f5f3
cw2yuenberkeley/w205-fall-17-labs-exercises
/exercise_2/extweetwordcount/scripts/finalresults.py
810
3.546875
4
import sys import psycopg2 from tcount_db import TCountDB if __name__ == "__main__": if len(sys.argv) > 2: print "Please input only one or zero argument." exit() # Get DB connection c = TCountDB().get_connection() cur = c.cursor() # Check if there is exactly one argument if len(sys.argv) == 2: word = sys.argv[1] cur.execute("SELECT count FROM tweetwordcount WHERE word = '%s'" % word) results = cur.fetchall() c.commit() count = 0 if len(results) == 0 else results[0][0] print 'Total number of occurrences of "%s": %d' % (word, count) # Check if there is no argument elif len(sys.argv) == 1: cur.execute("SELECT word, count FROM tweetwordcount ORDER BY word") results = cur.fetchall() for r in results: print "(%s, %d)" % (r[0], r[1]) c.commit() c.close()
feffbb540e544c11f4ff843f19f81fb5171c4de3
xuwei1997/CNN
/convelution3.py
2,227
3.53125
4
from keras.models import Sequential from keras.layers import Dense, Activation,convolutional,pooling,core import keras from keras.datasets import cifar10 if __name__ == "__main__": (X_train,Y_train),(X_test,Y_test)=cifar10.load_data() Y_train=keras.utils.to_categorical(Y_train) Y_test=keras.utils.to_categorical(Y_test) print (X_train.shape, Y_train.shape, X_test.shape, Y_test.shape) model=Sequential() model.add(convolutional.Conv2D(filters=32,kernel_size=3,strides=1,padding="same",data_format="channels_last",input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2,strides=2,padding="same",data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(convolutional.Conv2D(filters=48, kernel_size=3, strides=1, padding="same", data_format="channels_last", input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2,strides=2,padding="same",data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(convolutional.Conv2D(filters=128, kernel_size=3, strides=1, padding="same", data_format="channels_last",input_shape=X_train.shape[1:])) model.add(Activation("relu")) model.add(pooling.MaxPool2D(pool_size=2, strides=2, padding="same", data_format="channels_first")) model.add(core.Dropout(0.2)) model.add(core.Flatten()) model.add(Dense(units=512)) model.add(Activation("relu")) model.add(core.Dropout(0.2)) model.add(Dense(units=10)) model.add(Activation("softmax")) opt=keras.optimizers.Adam(lr=0.0001,decay=1e-6) model.compile(loss="categorical_crossentropy",optimizer=opt,metrics=['accuracy']) for i in range(15): print (i) print ("...........................................................................") for k in range(0,50000,32): X_data=X_train[k:k+32]/255 Y_data=Y_train[k:k+32] l_a=model.train_on_batch(X_data,Y_data) print (k) print (l_a) print (model.metrics_names) loss_and_metrics = model.evaluate(X_test, Y_test) print ("") print (loss_and_metrics) model.save('my_model_1.h5')
172253e3166a026da90af4c7b3d4896dc3b705e3
CeriseGoutPelican/ISEN
/Python/Séance 1/Exercice 1/liste.py
2,134
3.90625
4
import sys def min_value(liste): """Permet de recuperer le plus petit element (nombre) d'une liste""" # Pour rechercher le premier element first = False # Parcours la liste list element par element for e in liste: if isinstance(e, (int, float, bool)): if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e if first: return min else: return "/!\ Erreur" #raise Exception("Il n'y a pas de valeurs numeriques dans la liste") def min_value_rec(liste): """Permet de recuperer le plus petit element (nombre) d'une liste""" # Pour rechercher le premier element first = False # Parcours la liste list element par element for e in liste: if isinstance(e, (int, float, bool)): if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e elif isinstance(e, list): e = min_value_rec(e) if first == False: # Valeure minimale min = e # Premier element trouve first = True else: # Substitue l'element le plus petit if e <= min: min = e return min # map et filter sont deux éléments interessants en pythons print(sys.version) print('-'*50) list1 = ["hello", -5, False, 1.2323, {"a", 10, "c"}, [-18,45, "abcd"]] list2 = [1.1, "hello", 10, -True, 1.2323, {"a", 10, "c"}, [18,45, "abcd"]] list3 = [False] list4 = ["hello", [-18,45,"abcd"]] print(min_value_rec(list1)) print(min_value_rec(list2)) print(min_value_rec(list3)) print(min_value_rec(list4))
8e862b30b7af63b3110f0ce4efcf683f35d2bf5f
bertmclee/ML_Foundation_Techniques
/ml_foundation_hw3_pa/hw3_q8.py
3,714
3.828125
4
import numpy as np from scipy.special import softmax from collections import Counter import matplotlib.pyplot as plt import math from scipy.linalg import norm # Logistic Regression """ 19. Implement the fixed learning rate gradient descent algorithm for logistic regression. Run the algorithm with η=0.01 and T=2000, what is Eout(g) from your algorithm, evaluated using the 0/1 error on the test set? 20. Implement the fixed learning rate stochastic gradient descent algorithm for logistic regression. Instead of randomly choosing n in each iteration, please simply pick the example with the cyclic order n=1,2,…,N,1,2,… Run the algorithm with η=0.001 and T=2000. What is Eout(g) from your algorithm, evaluated using the 0/1 error on the test set? 8. (20 points, *) For Questions 19 and 20 of Homework 3 on Coursera, plot a figure that shows Eout(wt) as a function of t for both the gradient descent version and the stochastic gradient descent version on the same figure. Describe your findings. Please print out the figure for grading. """ def sigmoid(x): return 1 / (1 + math.exp(-x)) def logisticRegressionGD(x, y, eta, t, w): # compute gradient Ein and Ein N, dim = x.shape gradientEinSum = np.zeros(dim) gradientEin = np.zeros(dim) EinSum = 0 Ein = 0 for i in range(N): gradientEinSum += sigmoid(-y[i]*np.dot(w,x[i]))*(-y[i]*x[i]) EinSum += np.log(1+np.exp(-y[i]*np.dot(w,x[i]))) gradientEin = gradientEinSum/N Ein = EinSum/N # print(t, Ein) # update weight vector w -= eta * gradientEin # print(w) return w, Ein def logisticRegrssionSGD(x, y, eta, t, w): N, dim = x.shape gradientEin = np.zeros(dim) Ein = np.zeros(dim) # compute gradient Ein and Ein i = t % len(y) gradientEin = sigmoid(-y[i]*np.dot(w,x[i]))*(-y[i]*x[i]) Ein = np.log(1+np.exp(-y[i]*np.dot(w,x[i]))) # print(t, Ein) # update weight vector w -= eta * gradientEin # print(w) return w, Ein def calculateError(x, y, w): # calculate prediction accuracy testSize = len(y) yPredict = np.zeros(testSize) error = 0 for i in range(testSize): yPredict[i] = np.dot(w, x[i]) # print(yPredict[i]) if yPredict[i] > 0 and y[i] == -1: error += 1 elif yPredict[i] < 0 and y[i] == 1: error += 1 errorRate = error/testSize return errorRate # ------------------------- if __name__ == '__main__': # Read training and tesing data dataTrain = np.loadtxt('hw3_train.dat') N, dim = dataTrain.shape xTrain = dataTrain[:,:-1] xTrain = np.insert(xTrain, 0, 0, axis=1) yTrain = dataTrain[:,-1] dataTest = np.loadtxt('hw3_test.dat') xTest = np.insert(dataTest[:,:-1],0,0,axis=1) yTest = dataTest[:,-1] # training parameters T = 2000 eta = 0.001 Eout01ArrGD = [] Eout01ArrSGD = [] # Initialize weight vector w = np.zeros(dim) # print(w) for t in range(T): wGD, EoutGD = logisticRegressionGD(xTrain, yTrain, eta, t, w) # print(wGD) errorGD = calculateError(xTest, yTest, wGD) # print('GD',t, errorGD) Eout01ArrGD.append(errorGD) print('-------------------------') print('update t: {}, GD error: {:.1f}%'.format(t+1, errorGD*100)) w = np.zeros(dim) for t in range(T): wSGD, EoutSGD = logisticRegrssionSGD(xTrain, yTrain, eta, t, w) #print(wSGD) errorSGD = calculateError(xTest, yTest, wSGD) #print('SGD', t, errorSGD) Eout01ArrSGD.append(errorSGD) print('-------------------------') print('update t: {}, SGD error: {:.1f}%'.format(t+1, errorSGD*100)) t = list(range(0,T)) plt.plot(t, Eout01ArrSGD, label='Stochastic Gradient Descent') plt.plot(t, Eout01ArrGD, label='Gradient Descent') plt.title("Eout(wt)(0/1 error) vs t") plt.xlabel("t") plt.ylabel("Eout(wt)(0/1 error)") plt.legend(loc='lower left') plt.show()
9446b95ea3cb2f71014a9197aa934f03dbb12c5a
JiaoPengJob/PythonPro
/src/_instance_.py
2,780
4.15625
4
#!/usr/bin/python3 # 实例代码 # Hello World 实例 print("Hello World!") # 数字求和 def _filter_numbers(): str1 = input("输入第一个数字:\n") str2 = input("输入第二个数字:\n") try: num1 = float(str1) try: num2 = float(str2) sum = num1 + num2 print("相加的结果为:%f" % sum) except ValueError: print("请输入数字!") _filter_numbers() except ValueError: print("请输入数字!") _filter_numbers() # 判断奇偶数 # 0:偶数 # 1:奇数 def _odd_even(num): if num.isdigit(): if (float(num) % 2) == 0: return 0 else: return 1 else: print("这不是一个数字!") num = input("奇偶--请输入一个数字:\n") print(_odd_even(num)) # 判断闰年 # 如果一年是闰年,它要么能被4整除但不能被100整除;要么就能被400整除 # True:是闰年 # False:是平年 def _leap_year(year): if (year % 4) == 0 and (year % 100) != 0 or (year % 400) == 0: return True else: return False year = input("闰年--请输入一个年份:\n") print(_leap_year(int(year))) # 判断质数 # 一个大于1的自然数,除了1和它本身外,不能被其他自然数(质数)整除(2, 3, 5, 7等),换句话说就是该数除了1和它本身以外不再有其他的因数。 import math # 0:既不是质数,也不是合数 # 1:是质数 # 2:是合数 def _prime(num): if num > 1: square_num = math.floor(num ** 0.5) for i in range(2, (square_num + 1)): if (num % i) == 0: return 2 break else: return 1 else: return 0 num = int(input("质数--输入一个数字:\n")) print(_prime(num)) # 阶乘 # 整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,0的阶乘为1。即:n!=1×2×3×...×n。 def _factorial(num): if num < 0: # 负数是没有阶乘的 return num else: return math.factorial(num) num = int(input("阶乘--输入一个数字:\n")) print(_factorial(num)) # 阿姆斯特朗数 # 如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。 # 当n=3时,又称水仙花数,特指一种三位数,其各个数之立方和等于该数。 def _armstrong(num): sum = 0 n = len(str(num)) temp = num while temp > 0: digit = temp % 10 sum += digit ** n temp //= 10 if num == sum: return True else: return False print(_armstrong(int(input("阿姆斯特朗--输入一个数字:\n"))))
15d7ba4a79abd8f79d4349d310eae243a9191960
alecordev/web-screenshotter
/web_screenshotter.py
4,034
3.546875
4
""" Module to automate taking screenshots from websites. Current features: - URLs list from file (one URL per line) given from command line - Specify one URL from command line """ import os import sys import logging import datetime import argparse from selenium import webdriver from bs4 import BeautifulSoup import requests logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) logger.addHandler(console_handler) logger.info('Logging initialized') visited = set() to_visit = set() HEADERS = {'User-Agent': 'Mozilla/5.0'} navigate = False def save_screenshot(driver, url): """ Saves screenshot from URL under screenshots/YYYY-MM-DD directory. :param driver: Selenium webdriver instance :type driver: webdriver instance :param url: Web address :type url: str """ try: driver.get(url) dt = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d') file_name = url.replace('http://', '').replace('/', '-').replace(':', '-').replace('.html', '') + '.png' path = os.path.join(os.path.abspath(os.curdir), 'screenshots/{}'.format(dt)) os.makedirs('screenshots/{}'.format(dt), exist_ok=True) f = os.path.join(path, file_name) logger.info(f) driver.get_screenshot_as_file(f) except Exception as e: logger.error(e) def take_screenshot(): """ Goes to every filtered link within the given URL, taking screenshots. """ try: driver = webdriver.Firefox() for url in list(to_visit): save_screenshot(driver, url) visited.add(url) to_visit.remove(url) except Exception as e: logger.error(e) finally: driver.quit() def fix_url(url): """ Ensures url format is valid, fixes it if necessary :param url: The web address to verify :type url: str """ if 'http://' not in url and 'https://' not in url: url = 'http://' + url return url def process(base_url): """ Collects all 'filtered' links within an URL :param base_url: Main web address to parse :type base_url: str """ logger.info('Processing {}'.format(base_url)) exceptions = ['.css', '.js', '.zip', '.tar.gz', '.jar', '.txt', '.json'] logger.info('Ignoring links containing: {}'.format(exceptions)) soup = BeautifulSoup(requests.get(base_url).content, 'lxml') urls = [href['href'] for href in soup.find_all(href=True) if href['href'] not in exceptions] for url in urls: if base_url in url: to_visit.add(url) def process_url(url): """ Wraps functionality & logic to take screenshots for every 'filtered link' in URL :param url: Web address to take screenshots from :type url: str """ process(url) while to_visit: take_screenshot() logging.info('No urls left to process from {}. Finishing...'.format(url)) if __name__ == '__main__': try: parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', help='URL of the website to screenshot') parser.add_argument('-f', '--file', help='Filename path of list of URLs to screenshot (one URL per line)') args = parser.parse_args() if len(sys.argv) < 2: parser.print_help() sys.exit() if args.url: process_url(args.url) elif args.file: with open(args.file) as urls: try: driver = webdriver.Firefox() for url in urls: save_screenshot(driver, url) except Exception as e: logger.error(e) finally: driver.quit() except Exception as e: logger.error(e)
1be8d27189ffd3e447915108db7618325189afe4
MrClub/Poker
/dealer.py
1,427
3.53125
4
# This is a place to add all my functions # Todo Full House detection # TODO betting import random deck_of_cards = [] def deck_builder(list): # builds the deck because I'm too lazy to type everything out suit_list = ["Diamonds","Hearts","Clubs","Spades"] for suit in suit_list: for n in range(2, 15): list.append([n, suit]) random.shuffle(list) return list # test def deal(howmany, deck, list): # deals how many cards you want to a selected list for n in range(0, howmany): list.append(deck.pop()) return list def show_player_hand(hand_list, player): # show the player's hand if player == "hero": print("Your hand".center(22, "-")) else: print("Villian's hand".center(22, "-")) for card in hand_list: print(str(card[0]) + " of " + card[1]) print() def show_the_board(board_list): # shows the board i.e. community cards print("The board".center(22, "-")) for card in board_list: print(str(card[0]) + " of " + card[1]) print() def state_of_game(player_hand, villian_hand, board,show_villian): # combines show_the_board and show_player_hand_function into one # show villians hand if show_villian is set to "y" show_player_hand(player_hand, "hero") if show_villian == "y": show_player_hand(villian_hand,"villian") else: pass show_the_board(board)
52a59e02d585be6d7a6deaaa9cf9fab5b9a7277e
R-N/lmfit-py
/examples/example_use_pandas.py
801
3.953125
4
""" Fit with Data in a pandas DataFrame =================================== Simple example demonstrating how to read in the data using pandas and supply the elements of the DataFrame from lmfit. """ import matplotlib.pyplot as plt import pandas as pd from lmfit.models import LorentzianModel ############################################################################### # read the data into a pandas DataFrame, and use the 'x' and 'y' columns: dframe = pd.read_csv('peak.csv') model = LorentzianModel() params = model.guess(dframe['y'], x=dframe['x']) result = model.fit(dframe['y'], params, x=dframe['x']) ############################################################################### # and gives the plot and fitting results below: result.plot_fit() plt.show() print(result.fit_report())
51bbbaab98e42f9dab3090417103cdaf23200f40
LSSalah/Coding-dojo-Python
/basics/Forloob2.py
1,494
3.90625
4
#Biggie Size def biggie(l): for i in range(len(l)): if l[i] > 0: print("big") else: print(l[i]) print (biggie([-1,5,5,-3])) #Count Positives def countpos(l): sum = 0 for i in range(len(l)): if l[i] > 0: sum += 1 l[-1] = sum return l print (countpos([-1,5,5,-3])) #Sum Total def sum(l): sum = 0 for i in range(len(l)): sum += l[i] return sum print (sum([2,3,5,1])) #Average def avg(l): sum= 0 for i in l: sum += i avg = sum/len(l) return avg print (avg([1,2,3,4])) #Length def length(l): x = len(l) return x print (length([1,2,3,4])) #Minimum def min(l): min = l[0] for i in range(len(l)): if l[i] < min: min = l[i] return min print (min([6,1,3,4])) #Maximum def max(l): max = l[0] for i in range(len(l)): if l[i] > max: max = l[i] return max print (max([6,1,3,4])) #Ultimate Analysis def max_min_avg_length (l): sum = 0 min = l[0] max = l[0] x = len(l) for i in l: sum += i if i < min: min = i if i > max: max = i return {"sum":sum , "avg":sum/len(l), "min":min , "max":max , "length": x} print (max_min_avg_length([4,5,6,7,8])) #Reverse List def reverse(l): return l[::-1] print (reverse([4,5,6,7,8]))
b35f6f1d51bcaa483d71640b77687d6860edaba3
ChaseSnapshot/algorithms
/python/src/ChainedHashTable.py
1,756
3.6875
4
class ChainedHashTable: """ A hash table implementation that uses chaining to resolve collisions TODO: Implement this with support for providing custom hash functions """ ''' Initializes the hash table ''' def __init__(self, numBuckets): self.buckets = [] for bucketIter in range(numBuckets): self.buckets.append([]) ''' Inserts the provided item into the hash table ''' def insert(self, item): bucket = item % len(self.buckets) # Determine which bucket it goes into self.buckets[bucket].insert(0, item) # Put the item in the front of the bucket ''' Returns whether or not the provided item exists in the hash table ''' def hasElement(self, item): bucket = item % len(self.buckets) # Determine which bucket it goes into bucketContents = self.buckets[bucket] # Search the bucket's contents for the item for bucketContent in bucketContents: if bucketContent == item: # If this bucket content equals the item return True # Found the item in the hash table return False # Did not find the item in the hash table ''' Removes the provided item from the hash table if it exists ''' def remove(self, item): bucket = item % len(self.buckets) # Determine which bucket the item would be in bucketContents = self.buckets[bucket] # Search the bucket's contents for the item for contentIter in range(len(bucketContents)): if bucketContents[contentIter] == item: # If this bucket content equals the item return bucketContents.pop(contentIter) # Remove the item from the hash table return None # Item did not exist in the hash table
b58b216d3a3b02e7e6e237c250e792d993baa384
ChaseSnapshot/algorithms
/python/src/Sort.py
10,629
4.4375
4
''' Calculates into which bucket an item belongs ''' def whichBucket(item, maxItem, numBuckets): bucket = int(float(item) * float(numBuckets - 1) / float(maxItem)) print "Item: ", item print "MaxItem: ", maxItem print "NumBuckets: ", numBuckets print "Bucket: ", bucket return bucket ''' Sorts the provided list of items using a generalized form of bucket sort (aka slower) TODO: Do the performance analysis for the generalized form. Good practice! ''' def bucketSort(items): buckets = [] for bucketIter in range(len(items)): # Initialize the buckets buckets.append([]) maxItem = -1 for item in items: # Find the max item value, read: generalized form of bucket sort if item > maxItem: maxItem = item while len(items) > 0: # Put each item in its bucket item = items.pop(0) buckets[whichBucket(item, maxItem, len(buckets))].append(item) for bucket in buckets: # Sort each bucket using insertion sort and put it back in the main list print "Bucket Before Sort: ", bucket insertionSort(bucket) print "Bucket After Sort: ", bucket items.extend(bucket) print "Items: ", items ''' Sorts the provided items using the bubble sort algorithm ''' def bubbleSort(items): for itemIter in range(0, len(items)): # For each item in the list stride = -1 for reverseIter in range(len(items) - 1, itemIter, stride): # Search in reverse # If the current item is smaller than the item before it if items[reverseIter] < items[reverseIter - 1]: # Swap it with the item before it items[reverseIter], items[reverseIter - 1] = items[reverseIter - 1], items[reverseIter] ''' Builds a legal heap by iteratively applying heapify. Runtime: O(n) ''' def _buildHeap(items): print "__buildHeap()..." print "\titems: ", items firstNonLeafNode, rootNode = (len(items) - 1) / 2, 0 print "\tFirstNonLeafNode: ", firstNonLeafNode print "\tRootNode: ", rootNode # For each node starting with the first non-leaf node up to and including the root print "\tRange[", firstNonLeafNode, ",", rootNode - 1, ")" step = -1 for nodeIter in range(firstNonLeafNode, rootNode - 1, step): # Make the current node's _heapify(items, nodeIter, len(items)) ''' Sorts a given node into the correct position by recursively sifting it down the heap. Runtime: O(lg n) ''' def _heapify(items, pos, heapSize): print "__heapify()..." print "\titems: ", items print "\theapSize: ", heapSize leftChild = pos * 2 + 1 rightChild = pos * 2 + 2 largestNode = pos print "\tRoot Pos: ", pos print "\tRoot Value: ", items[pos] print "\tLeftChild Pos: ", leftChild if leftChild < heapSize: print "\tLeftChild Value: ", items[leftChild] else: print "\tLeftChild Value: N/A" print "\tRightChild Pos: ", rightChild if rightChild < heapSize: print "\tRightChild Value: ", items[rightChild] else: print "\tRightChild Value: N/A" # If the left child exists and is greater than the parent node if (leftChild < heapSize) and (items[leftChild] > items[largestNode]): largestNode = leftChild # Save it as the largest node so far # If the right child exists and is greater than the current largest value if (rightChild < heapSize) and (items[rightChild] > items[largestNode]): largestNode = rightChild # Save it as the largest node print "\tLargestNodePos: ", largestNode print "\tLargestNodeValue: ", items[largestNode] # If at least one of the children nodes is larger than the parent node if largestNode != pos: # Swap the parent node with its larger child items[pos], items[largestNode] = items[largestNode], items[pos] print "\tItems after swap: ", items # Continue sifting the node down the heap _heapify(items, largestNode, heapSize) ''' Sorts the provided items using the heap sort algorithm Runtime: O(n lg n) ''' def heapSort(items): # Initialize the items into a legal, but unsorted, heap _buildHeap(items) print "Done building heap: ", items heapSize = len(items) # Starting with the last node and working up to the root of the heap print "Range: ", len(items) - 1, ",", 0 step = -1 for nodeIter in range(len(items) - 1, 0, step): print "Items: ", items rootPos = 0 # Swap the current root with the last node in the heap items[rootPos], items[nodeIter] = items[nodeIter], items[rootPos] print "Items After Swap: ", items # Mark the node now last in the heap as correctly sorted heapSize = heapSize - 1 # Sort the new root value in order to maintain the state of being a heap _heapify(items, rootPos, heapSize) ''' Sorts the provided items using the insertion sort algorithm Runtime: Theta(n^2) ''' def insertionSort(items): # For each item in past the first for itemIter in range(1, len(items)): currentItem = items.pop(itemIter) searchPos = itemIter - 1 # Search backwards for the correct position to place the current item while searchPos >= 0: searchItem = items[searchPos] # If the current item is greater than the search item if currentItem > searchItem: # The correct position has been found so stop searching break # Move back another item searchPos = searchPos - 1 # Insert the current item into the selected location items.insert(searchPos + 1, currentItem) ''' Merges the two sub-arrays together in order ''' def _merge(items, subArrayStart, pivot, subArrayEnd): leftSubArrayLength = pivot - subArrayStart + 1 # Determine the lengths of each sub-array rightSubArrayLength = subArrayEnd - pivot # Merge sort cannot sort in place so created two sub-array working spaces leftSubArray = [] # Copy the left sub array items into the working space for item in items[subArrayStart:subArrayStart+leftSubArrayLength]: leftSubArray.append(item) # Add it to the working space rightSubArray = [] # Copy the right sub array items into the working space for item in items[pivot+1:pivot+1+rightSubArrayLength]: rightSubArray.append(item) # Add it to the working space leftSubArray.append(9999999) # Add sentinel values to the end of each sub-array rightSubArray.append(9999999) # TODO Find type safe way of defining sentinel leftPos = 0 # Initialize the sub-array search positions rightPos = 0 print "Range: [", subArrayStart, ",", subArrayEnd + 1, ")" for itemIter in range(subArrayStart, subArrayEnd + 1): # For each position in the arrayi print "==========================" print "Items: ", items print "ItemIter: ", itemIter print "Left: ", leftSubArray print "LeftPos: ", leftPos print "Right: ", rightSubArray print "RightPos: ", rightPos if leftSubArray[leftPos] <= rightSubArray[rightPos]: # If the next left sub-array item is smaller items[itemIter] = leftSubArray[leftPos] # Add it to the sorted list leftPos = leftPos + 1 # Move to the next left sub-array item else: # If the next righ sub-array item is smaller items[itemIter] = rightSubArray[rightPos] # Add it to the sorted lsit rightPos = rightPos + 1 # Move to the next righ sub-array item print "Final Items: ", items ''' Sorts the provided items by recursively merge sorting ''' def _mergeSort(items, subArrayStart, subArrayEnd): if subArrayStart < subArrayEnd: # If the sub-array is not empty pivot = (subArrayStart + subArrayEnd) / 2 # Split the array into two sub-array halfs _mergeSort(items, subArrayStart, pivot) # Recursively sort the sub-arrays _mergeSort(items, pivot + 1, subArrayEnd) _merge(items, subArrayStart, pivot, subArrayEnd) # Merge the sub-arrays together ''' Sorts the provided items using the merge sort algorithm ''' def mergeSort(items): _mergeSort(items, 0, len(items) - 1) ''' Sorts the sub array such that all items below the pivot position are less than or equal to the item at the pivot position and all values in positions past the pivot position are greater than or equal to the pivot value. ''' def _partition(items, subArrayStart, subArrayEnd): # Validate the input parameters assert (0 <= subArrayStart) and (subArrayStart < len(items)) assert (subArrayStart <= subArrayEnd) and (subArrayEnd < len(items)) print "Items: ", items print "Sub Array Start: ", subArrayStart print "Sub Array End: ", subArrayEnd # Pick the last item in the sub-array as the pivot value pivotValue = items.pop(subArrayEnd) pivotPos = subArrayStart - 1 print "Pivot Value: ", pivotValue print "Pivot Pos: ", pivotPos # For each item in the sub-array except the pivot value at the end print "Range[", subArrayStart, ",", subArrayEnd, ")" for itemIter in range(subArrayStart, subArrayEnd): currentItem = items[itemIter] print "Items: ", items print "Current Item: ", currentItem if currentItem <= pivotValue: # If the current item is <= the pivot value pivotPos = pivotPos + 1 # Move the pivot position forward currentItem = items.pop(itemIter) items.insert(pivotPos, currentItem) # Put the pivot value into the selected pivot position pivotPos = pivotPos + 1 items.insert(pivotPos, pivotValue) print "Items: ", items return pivotPos ''' Internal recursive quick sort implementation ''' def _quickSort(items, subArrayStart, subArrayEnd): assert subArrayStart >= 0 # Validate the input parameters assert subArrayEnd < len(items) if subArrayStart < subArrayEnd: # If the sub-array to be sorted is not empty # Calculate the pivot point along which to split the sub-array pivotPos = _partition(items, subArrayStart, subArrayEnd) # Recursively quick-sort the two sub-array _quickSort(items, subArrayStart, pivotPos - 1) _quickSort(items, pivotPos + 1, subArrayEnd) ''' Sorts the provided items using the quicksort algorithm ''' def quickSort(items): _quickSort(items, 0, len(items) - 1)
fd1257e7e33b27e828b1b67d1aac686b4fd1ef9b
Coohx/python_work
/python_base/python_class/car_old.py
2,288
4.34375
4
# -*- coding: utf-8 -*- # 使用类模拟现实情景 # Car类 class Car(): """模拟汽车的一个类""" def __init__(self, test_make, test_model, test_year): """初始化汽车属性""" self.make = test_make self.model = test_model self.year = test_year # 创建属性odometer_reading,并设置初始值为0 # 指定了初始值的属性,不需要为它提供初始值的形参 self.odometer_reading = 0 def get_descriptive(self): """返回整洁的描述信息""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """打印一条指出汽车里程的消息""" print("This car has " + str(self.odometer_reading) + " miles on it.") # 用于在内部更新属性值的方法 def update_odometer(self, mileage): """ 将里程表的读数设置为指定的值 禁止将里程表的读书调小 """ # 只有新指定的里程数大于当前里程数时,才允许修改这个属性值 if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") # 用于递增属性值的方法 def increment_odometer(self, miles): """将里程表读书增加制定的量""" if miles > 0: self.odometer_reading += miles else: print("You can't roll back an odometer!") # 创建一个实例 my_new_car = Car('audi', 'A4', 2016) # 调用类中的方法 print(my_new_car.get_descriptive()) my_new_car.read_odometer() # 直接修改实例的属性值 my_new_car.odometer_reading = 23 my_new_car.read_odometer() # 调用类内部编写的方法修改属性值 my_new_car.update_odometer(32) my_new_car.read_odometer() # 23小于当前属性值32,禁止修改 my_new_car.update_odometer(23) # 创建实例——二手车 my_used_car = Car('subaru', 'outback', 2013) print("\n" + my_used_car.get_descriptive()) # 二手车已经跑的里程数 my_used_car.update_odometer(23500) my_used_car.read_odometer() # 我又行驶了100英里 my_used_car.increment_odometer(100) my_used_car.read_odometer()
0ae8cd1cdf3d35d0ba6fd20293d5c235a405cc43
Coohx/python_work
/python_base/python_unittest/name_function.py
646
3.578125
4
# -*- coding: utf-8 -*- # Date: 2016-12-23 def get_formatted_name(first, last, middle=''): """General a neatly formatted full name""" if middle: full_name = first + ' ' + middle + ' ' + last else: full_name = first + ' ' + last return full_name.title() def custom_info(city, country, population=''): """统计游客所在的国家和城市""" if population: customer_info = city + ", " + country customer_info = customer_info.title() return customer_info + " - population " + population else: customer_info = city + ", " + country return customer_info.title()
79bd1b686f72927ad2c94a8c27449e78e4a0fde9
Coohx/python_work
/python_base/python_class/dog.py
2,117
4.125
4
# -*- coding: utf-8 -*- # Date: 2016-12-16 r""" python class 面向对象编程 类:模拟现实世界中的事物和情景,定义一大类对象都有的通用行为 对象:基于类创建,自动具备类中的通用行为 实例:根据类创建对象被称为实例化 程序中使用类的实例 """ # 创建Dog类 # 类名首字母大写 class Dog(): # Python2.7中的类创建:class Dog(object): """一次模拟小狗的简单尝试""" # 创建实例时方法__init__()会自动运行 # self 形参必须位于最前面,创建实例时,自动传入实参self # 每个与类相关联的方法都会自动传递实参self def __init__(self, name, age): """初始化属性names和age""" # 两个属性names和age都有前缀self self.name = name self.age = age def sit(self): """模拟小狗被命令蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗被命令打滚""" print(self.name.title() + " rolled over!") # 创建一条特定小狗的实例 # 调用Dog类中的方法__init__()自动运行,创建一个表示特定小狗的实例 # 使用‘Willie’和6来设置属性name和age # 方法__init__()自动返回一个实例存储在变量my_dog中,包含类中的所有'行为' my_dog = Dog('Willie', 6) # 访问实例的属性——句点表示法 # 但在Dog类内部引用这个属性时,使用self.name # 实例名.属性名 print("My dog's name is " + my_dog.name.title() + ".") print("My dog is " + str(my_dog.age) + " years old.") # 调用方法——创建实例后,使用句点表示法访问Dog类中定义的方法 # 语法: 实例名.方法 # Python在Dog类中查找方法sit()并运行其代码 my_dog.sit() my_dog.roll_over() # 创建多个实例 # 每个实例(小狗)都有自己的一组属性(姓名、年龄) your_dog = Dog('lucy', 7) print("\nYour dog's name is " + your_dog.name.title() + ".") print("Your dog is " + str(your_dog.age) + " years old.") your_dog.sit() your_dog.roll_over()
428b6201575083154aed82d01c1d7e5825d26745
Coohx/python_work
/python_base/python_if&for&while/do_if.py
2,123
4.3125
4
# -*- coding: utf-8 -*- # if 语句进行条件判断 # Python用冒号(:)组织缩进,后面是一个代码块,一次性执行完 # if/else 简单判断 age = 17 if age >= 18: print('you are a adult.') print('Welcome!') else: print('You should not stay here, Go home!') # if/elif/else 多值条件判断 age = 3 if age >= 18: print('adult!') elif age > 6: print('teenager!') else: print('kid! Go home!') # if 从上往下判断,若某个判断是True,就忽略后面的判断。 age = 20 if age >= 6: print('teenager!') elif age > 18: print('adult!') else: print('kid! Go home!') # if 支持简写 tmp = 12 if tmp: print('The bool is True.') # input() 返回字符串, if进行数值判断时要转为整数 age = int(input('Please enter your age: ')) if age > 18: print('Welcome!') else: print('Go home!') # 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数 # 低于18.5:过轻 # 18.5-25:正常 # 25-28:过重 # 28-32:肥胖 # 高于32:严重肥胖 # 计算小明的BMI指数,用if-elif判断并打印 height = 1.75 weight =80.5 bmi = weight / (height ** 2) if bmi < 18.5: status = '过轻' elif bmi < 25: status = '正常' elif bmi < 28: status = '过重' elif bmi <= 32: status = '肥胖' else: status = '严重肥胖' print('Xiao Ming BMI is: %.2f,%s!' % (bmi, status)) # 关键字in requested_toppings = ['mushroom', 'onions', 'pineapple'] print('mushroom' in requested_toppings) # if-elif 省略 else代码块 age = 12 price = 0 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5 print('Your admission cost is $' + str(price) + '.') # 多个并列的if,检查所有条件 requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print('Adding mushrooms.') if 'pepperoni' in requested_toppings: print('Adding pepperoni.') if 'extra cheese' in requested_toppings: print ('Adding extra pepperoni.') print('\nFinished making your pizza!')
1554c10f9378b8010c8b886bd28b61c912baeef2
Coohx/python_work
/python_base/python_function/quadratic_root.py
828
4.03125
4
# -*- coding: utf-8 -*- import math # 求解一元二次方程 def quadratic(a, b, c): # 参数类型检查 if not isinstance(a, (int, float)): raise TypeError('bad operand type') elif not isinstance(b, (int, float)): raise TypeError('bad operand type') elif not isinstance(c, (int, float)): raise TypeError('bad operand type') elif a == 0: print('a can\'t be 0!') else: if b ** 2 - 4 * a * c < 0: print('no real roots') else: x1 = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) x2 = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) return x1, x2 # x1 x2 被放在一个元组中输出 x1, x2 = quadratic(4, 4, 1) # 格式化输出时,两个以上的输出要用括号扩起 print('x1 = %s x2 = %s' % (x1, x2))
df77a4970641d56ba65fc04971e9baf61e3914c2
naveenr414/neon-rider
/geometry.py
1,694
3.859375
4
class Rectangle: def __init__(self,x,y,width,height): self.x = x self.y = y self.width = width self.height = height def getSize(self): return (self.x,self.y,self.width,self.height) def __str__(self): return str(self.x) + " "+str(self.y) + " "+str(self.width)+ " "+str(self.height) class Vector: def __init__(self,x,y): self.x = x self.y = y def __add__(self,other): return Vector(self.x+other.x,self.y+other.y) def __sub__(self,other): return Vector(self.x-other.x,self.y-other.y) def __mul__(self,other): return Vector(self.x*other,self.y*other) def __str__(self): return str(self.x) + " "+str(self.y) def __eq__(self,other): return self.x==other.x and self.y==other.y def __str__(self): return "("+str(self.x) + ","+str(self.y)+")" def cross(self, other): return (self.x*other.y - self.y*other.x) def toArray(self): return [self.x,self.y] class Line: def __init__(self,start,direction,length): self.start = start self.direction = direction self.length = length def __str__(self): return str(self.start) + " " +str(self.direction) + " "+str(self.length) def intersect(point,rect): return rect.x<=point[0]<=rect.x+rect.width and rect.y<=point[1]<=rect.y+rect.height def colinear(p1,p2,p3): v1 = p2-p1 v2 = p3-p1 if(v1.cross(v2)==0): return True else: return False def dot(v1,v2): return v1.x*v2.x + v1.y*v2.y right = Vector(1,0) left = Vector(-1,0) up = Vector(0,-1) down = Vector(0,1) directions = [right,left,up,down]
ad26bc261c977e74bba5990a2fe1aafc1d7b86b0
ameenmanna8824/PYTHON
/Day 3/Classes/Classes/p2-constructor.py
235
4.0625
4
class Car: def __init__(self,x,y): # This is a constructor self.x=x self.y=y def forward(self): print(" Left Motor Forward") print(" Right Motor Forward") bmw=Car(2,3) bmw.x=10 print(bmw.x) print(bmw.y)
8c26a4ded7c2f5c936cc4031d134db4f773f60cd
aaaadai/algorithm
/insertionSort.py
547
4.09375
4
def insertionSort(sortingList): j = 1 while (j<len(sortingList)): i = j - 1 while (i >= 0): if (sortingList[j]>sortingList[i]): break i = i - 1 insert(sortingList, j, i + 1) j = j + 1 def insert(insertingList, insertingIndex, insertedIndex): temp = insertingList[insertingIndex] j = insertingIndex - 1 while(j>=insertedIndex): insertingList[j+1]=insertingList[j] j = j - 1 insertingList[insertedIndex] = temp if __name__ == '__main__': exampleList = [5,4,6,2,1,8,9,8] insertionSort(exampleList) print(exampleList)
6af698873e2e251755da7a1986981ad48926b909
dashuncel/gb_algorithm
/bda2_4.py
444
3.734375
4
#4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... # Количество элементов (n) вводится с клавиатуры. num = int(input('Введите число элементов ряда: ')) my_list = [1] for i in range(1, num): my_list.append(my_list[i-1] * -1 / 2) print(my_list) print(f'Сумма чисел ряда: {sum([i for i in my_list])}')
c76db21aebb23ceb1342e4fa4edbc0c10a0639e3
dashuncel/gb_algorithm
/byankina1_8.py
378
3.984375
4
# 8. Определить, является ли год, который ввел пользователем, високосным или невисокосным. year = (int(input("Введите год: "))) if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): print(f'Год {year} високосный') else: print(f'Год {year} не високосный')
eca11f026deccf03ba63fbd946be4219101d4395
dashuncel/gb_algorithm
/byankina1_7.py
1,042
4.1875
4
#7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, # составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, # равнобедренным или равносторонним. len1 = float(input("Длина 1: ")) len2 = float(input("Длина 2: ")) len3 = float(input("Длина 3: ")) if len1 + len2 > len3 and len2 + len3 > len1 and len1 + len3 > len2: print("Это треугольник") else: print("Это не треугольник") exit(0) if len1 == len2 == len3: print("Треугольник равноcторонний") elif len1 == len2 or len1 == len3 or len2 == len3: print("Треугольник равнобедренный") else: print("Треугольник разносторонний")
737320858a090ad0c06074353d8260bebe3f0c27
dashuncel/gb_algorithm
/byankina2_9.py
497
3.84375
4
# 9. Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. # Вывести на экран это число и сумму его цифр. COUNT = 3 my_list = [] def counter(num): summa = 0 while num >= 1: summa += num % 10 num = num // 10 return summa for i in range(COUNT): my_list.append(int(input(f'Число {i + 1}: '))) print(max(counter(i) for i in my_list))
37f140d1772315b7e81152858360c9ca89801555
danvk/march-madness-data
/one_seeds_eliminated.py
828
3.71875
4
#!/usr/bin/env python3 """What's the earliest round in which all 1 seeds were eliminated""" import sys from utils import get_flattened_games def count_one_seeds(games): count = 0 for g in games: if g[0]['seed'] == 1 or g[1]['seed'] == 1: count += 1 return count def main(): game_years = get_flattened_games(sys.argv[1:]) years = set([gy[1] for gy in game_years]) for year in years: for rnd in (64, 32, 16, 8, 4, 2): games = [game for game, y in game_years if game[0]['round_of'] == rnd and y == year] num_one_seeds = count_one_seeds(games) if num_one_seeds == 0: print('In %d, no one seeds remained in the round of %d' % (year, rnd)) break if __name__ == '__main__': main()
b4792f0558ad038836d308eedd1df18d1da3e0a8
ckoller/secretsharing
/mpc_framework/tests/arithmeticCircuits/arithmetic_circuits.py
1,595
3.5
4
from tests.circuit import ArithmeticCircuitCreator # Arithmetic circuit are created with the gates: add, mult and scalar_mult. # The gates can take gates as inputs. # c.input(3), means that we create and input gate with the id 3. class ArithmeticCircuits: def add_1_mult_2_3(self): # fx. 8+8*8 c = ArithmeticCircuitCreator() c.add(c.mult(c.input(1),c.input(2)), c.input(3)) circuit = c.get_circuit() return circuit def mult_add_5_people_where_one_person_has_multiple_inputs(self): # fx. 8*8+(8+8+8)*8) = 256 c = ArithmeticCircuitCreator() c.add(c.mult(c.input(5), c.input(3)), c.mult(c.add(c.add(c.input(3), c.input(5)), c.input(1)), c.input(1))) circuit = c.get_circuit() return circuit def add_mult_scalarmult_where_some_player_has_no_input(self): # fx. (8*8 + 8*8)*2) = 256 c = ArithmeticCircuitCreator() c.scalar_mult(c.add(c.mult(c.input(7), c.input(1)), c.mult(c.input(8), c.input(4))), scalar=2) circuit = c.get_circuit() return circuit def add_mult_scalarmult_with_multiple_outputs(self): # fx. (8*8 + 8*8)*2) * 8 = 2048 # (8*8 + 8*8)*2) * 8 = 2048 c = ArithmeticCircuitCreator() c.mult(c.scalar_mult(c.add(c.mult(c.input(2), c.input(1)), c.mult(c.input(3), c.input(4))), scalar=2), c.input(1)) c.output() c.mult(c.scalar_mult(c.add(c.mult(c.input(2), c.input(1)), c.mult(c.input(3), c.input(4))), scalar=2), c.input(1)) circuit = c.get_circuit() return circuit
f37a3a22ad3f2272e65ba5077308a6bfb5364429
ItaloPerez2019/UnitTestSample
/mymath.py
695
4.15625
4
# make a list of integer values from 1 to 100. # create a function to return max value from the list # create a function that return min value from the list # create a function that return averaga value from the list. # create unit test cases to test all the above functions. # [ dont use python built in min function, write your own # python script to test the list] def max_num(a): myMax = a[0] for num in a: if myMax < num: myMax = num return myMax def min_num(a): myMin = a[0] for num in a: if myMin > num: myMin = num return myMin def avg_num(a): for num in a: average = sum(a)/len(a) return average
e6b6e203bd5d2eb7fdc8cfe07a7ee45c57b74879
Dorsv/Blackjack_game_python
/scripts.py
4,735
3.890625
4
from random import randint from time import sleep class Card(): ''' creates card object takes in: face name (number and suit) and value/s ''' def __init__(self, face, value1, value2=0): self.name = face self.value1 = value1 self.value2 = value2 def __str__(self): ''' Returns face and it's value ''' if self.value2 == 0: return f"{self.name} value: {self.value1}" else: return f"{self.name} value: {self.value1} or {self.value2}" class Player(): ''' creates player object takes in name and optional cash amount ''' def __init__(self, name, cash=500): self.cash = cash self.name = name def __str__(self): ''' returns player's name and balance ''' return f"Player: {self.name}\nBalance: {self.cash}$" def double_cash(self): self.cash = self.cash*2 def create_hand(self, card1, card2): ''' creates hand attribute takes in 2 card object from Card class ''' self.hand = list((card1, card2)) def hit(self, card): self.hand.append(card) def show_hand(self): ''' prints out hand and it's value ''' self.han_val = 0 self.han_val2 = 0 for card in self.hand: if card.value2 == 0: self.han_val += card.value1 self.han_val2 += card.value1 else: self.han_val += card.value1 self.han_val2 += card.value2 for card in self.hand: print("\n") print(card) sleep(0.5) if self.han_val == self.han_val2: print("\n") print("--------------------------") print(f"Total value: {self.han_val}") else: print("\n") print("--------------------------") print(f"Total value: {self.han_val}/{self.han_val2}") class Dealer(): ''' creates dealer object ''' def __init__(self): pass def create_hand(self, card1, card2): ''' creates hand attribute takes in 2 card object from Card class ''' self.hand = list((card1, card2)) def hit(self, card): self.hand.append(card) def show_hand(self): ''' prints out hand and it's value ''' self.han_val = 0 self.han_val2 = 0 for card in self.hand: if card.value2 == 0: self.han_val += card.value1 self.han_val2 += card.value1 else: self.han_val += card.value1 self.han_val2 += card.value2 for card in self.hand: print("\n") print(card) sleep(0.5) if self.han_val == self.han_val2: print("\n") print("--------------------------") print(f"Total value: {self.han_val}") else: print("\n") print("--------------------------") print(f"Total value: {self.han_val}/{self.han_val2}") def card_pick(deck): ''' takes in a deck and removes random card returning it ''' card_num = randint(0, len(deck)-1) return deck.pop(card_num) # DEFINING STANDARD DECK OF 52 CARDS suits = ["clubs", "diamonds", "hearts", "spades"] faces = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"] values = [1,2,3,4,5,6,7,8,9,10,11] card_names = [] for suit in suits: for face in faces: name = face + ' of ' + suit card_names.append(name) cards = [] for name in card_names: try: if int(name[0]) in values and int(name[:2]) != 10: card = (name, int(name[0])) cards.append(card) elif "10" in name: card = (name, 10) cards.append(card) except: if "King" in name: card = (name, 10) cards.append(card) elif "Queen" in name: card = (name, 10) cards.append(card) elif "Jack" in name: card = (name, 10) cards.append(card) elif "Ace" in name: card = (name, 11, 1) cards.append(card) else: continue deck = [] for card in cards: if len(card) == 2: deck.append(Card(card[0], card[1])) else: deck.append(Card(card[0], card[1], card[2]))
28d199190b36dc864a26c83201d563d84a802b74
leleh5/curso_intro_python
/aula5_lista_tupla.py
812
3.828125
4
lista = [1, 3, 5, 7] lista_animal = ['cachorro', 'gato', 'elefante', 'lobo', 'arara'] tupla = (0, 2, 5, 10) #print(len(tupla)) #print(len(lista_animal)) # tupla_animal = tuple(lista_animal) # print(tupla_animal) # lista_animal_novo = list(tupla_animal) # print(lista_animal_novo) lista_animal.insert(0, 'h') print(lista_animal) # lista_animal.sort() # print(lista_animal) # lista_animal.reverse() # print(lista_animal) #print(lista_animal[1]) #nova_lista = lista*3 #print(nova_lista) # if 'lobo' in lista_animal: # print('tem lobo na lista') # else: # print('não tem lobo na lista. Será incluído') # lista_animal.append('lobo') # print(lista_animal) #lista_animal.pop() #print(lista_animal) #lista_animal.pop(1) #print(lista_animal) #lista_animal.remove('elefante') #print(lista_animal)
377097ce553b010a48e42f9f82c09652d5c4e746
leleh5/curso_intro_python
/aula4_lacos_repeticao.py
750
3.75
4
# a = int(input('digite um número: ')) # div = 0 # # for x in range(1, a+1): # resto = a % x # if resto == 0: # div += 1 # if div == 2: # print('O número {} é primo.'.format(a)) # # else: # print('O número {} não é primo.'.format(a)) # Números primos de 0 a 100: # for a in range(101): # div = 0 # for x in range(1, a+1): # resto = a % x # if resto == 0: # div += 1 # if div == 2: # print('{} é um número primo.'.format(a)) # Notas: media = 0 for i in range(1, 5): nota = int(input('Nota {}: '.format(i))) while nota > 10: print('nota inválida.') nota = int(input('Nota {}: '.format(i))) media += nota print('Média: {}'.format(media/4))
7b45da984eb491ba4ad63bff772688b927c6e7ef
rajasree-r/Array-2
/minMax_array.py
962
3.875
4
# Time Complexity : O(N) # Space Complexity : O(1) # Did this code successfully run on Leetcode : not in Leetcode, executed in PyCharm # Any problem you faced while coding this : no def minMax(arr): num = len(arr) # edge case if num == 0: return if num % 2 == 0: # array with even elements max_num = max(arr[0], arr[1]) min_num = min(arr[0], arr[1]) i = 2 else: max_num = min_num = arr[0] # array with odd elements i = 1 # pair elements and compare with min and max numbers while i < num - 1: if arr[i] < arr[i + 1]: max_num = max(max_num, arr[i + 1]) min_num = min(min_num, arr[i]) else: max_num = max(max_num, arr[i]) min_num = min(min_num, arr[i + 1]) i += 2 return max_num, min_num arr = [100, 300, 2, 20, 1000, 1] max_num, min_num = minMax(arr) print("Maximum is", max_num, "\nMinimum is", min_num)
39d2934b985efd9bc61b931bbebcd2e3fa853b87
DFYT42/Python---Beginner
/Python_Turtle_Fruitful_Function_Pattern_Gui.py
7,638
3.5625
4
##Using Python Turtle Module and user input parameters with gui dialogue boxes, ##open screen to width of user monitor and ##create repeated pattern, centered on screen, based on user input ##User parameter options: pattern size, ##pattern speed, and pattern colors. ############################################################################### ##############################'''import module'''############################## ############################################################################### import turtle ############################################################################### #################################'''window'''################################## ############################################################################### wn = turtle.Screen() wn.setup (width=1.00, height=1.00, startx=None, starty=None) wn.title("Repeated Turtle Pattern") wn.bgcolor('black') ############################################################################### #################################'''turtle'''################################## ############################################################################### tess = turtle.Turtle() tess.home() ##Starts turtle at coordinates (0,0) ############################################################################### ###############################'''user inputs'''############################### ############################################################################### sz = wn.numinput("Size","What size would you like the pattern? ",5,.5,1000) turtspd = wn.textinput("Turtle Speed","How fast would you like the turtle to draw the pattern: fast or slow? ") a = wn.textinput("1st Color","What is your first color? ") b = wn.textinput("2nd Color","What is your second color? ") ############################################################################### ##############################'''simple shapes'''############################## ############################################################################### def square(sz): '''make square''' tess.begin_fill() for i in range(4): tess.forward(sz) tess.left(90) tess.end_fill() tess.forward(sz) def triangle(sz,c): '''make triangle''' tess.begin_fill() tess.color('',c) tess.forward(sz) tess.left(90) tess.forward(sz) tess.left(135) tess.forward(hypot(sz)) tess.end_fill() def trisqre(sz,a,b): '''makes square with diagonal hypot & fill''' triangle(sz,a) hypmove(sz) triangle(sz,b) hypmove(sz) tess.forward(sz) def hypmove(sz): '''moves turt and neatens up trsq code''' tess.backward(hypot(sz)) tess.right(45) def hypot(sz): '''create diagonal(hypot) for trsq''' a = sz**2 b = sz**2 c = (a + b)**(.5) return float(c) ############################################################################### ############################'''panel rows'''################################## ############################################################################### def tessmovebk(sz): '''move tess for repositioning to start next row''' tess.backward(sz*4) tess.right(90) tess.forward(sz) tess.left(90) def row_1(sz,a,b): '''create row 1 in pattern panel''' for i in range(4): if i <=2: tess.color('',a) square(sz) else: tess.color('',b) square(sz) tessmovebk(sz) def row_2(sz,a,b): '''create row 2 in pattern panel''' for i in range(4): if i == 0: tess.color('',a) square(sz) elif i == 1 or i == 2: tess.color('',b) square(sz) else: trisqre(sz,a,b) tessmovebk(sz) def row_3(sz,a,b): '''create row 3 in pattern panel''' for i in range(4): if i != 1: tess.color('',a) square(sz) else: tess.color('',b) square(sz) tessmovebk(sz) def row_4(sz,a,b): '''create row 4 in pattern panel''' for i in range(4): if i == 0: tess.color('',b) square(sz) elif i == 1: trisqre(sz,a,b) else: tess.color('',a) square(sz) ############################################################################### ####################'''panel--1/4th if pattern quadrant'''##################### ############################################################################### def panel(sz,a,b): row_1(sz,a,b) row_2(sz,a,b) row_3(sz,a,b) row_4(sz,a,b) ############################################################################### ################'''turtle moves/turns within panels/quadrants'''############### ############################################################################### def panelmove(sz,a,b): '''move tess for repositioning to start next panel''' tess.left(90) tess.forward(sz*4) tess.right(90) tess.forward(sz*3) tess.right(90) panel(sz,a,b) def Quadmove(sz): '''move turtle to make quadrant''' tess.left(90) tess.backward(sz*7) tess.right(90) tess.backward(sz*72) tess.left(90) tess.backward(sz) tess.right(180) tess.forward(sz) tess.left(90) def QuadPatternMove(sz): '''move turtle to make quadrant pattern''' tess.forward(sz*3) tess.right(90) tess.forward(sz*5) def TurtleDrawingStart(sz): '''start turtle so center of drawing is at (0,0)''' tess.home() tess.backward(sz*32) tess.left(90) tess.forward(sz*28) tess.right(90) ############################################################################### #############################'''pattern building'''############################ ############################################################################### def QuadPattern_1(sz,a,b): '''creates one square''' for i in range(4): if i == 0: panel(sz,a,b) else: panelmove(sz,a,b) QuadPatternMove(sz) def fillpattern1(sz,a,b): '''sets colors based on user imputs''' for i in range(8): if i == 0 or i == 1 or i == 4 or i == 5: QuadPattern_1(sz,b,a) else: QuadPattern_1(sz,a,b) Quadmove(sz) def fillpattern2(sz,a,b): '''flips user color inputs''' for i in range(8): if i == 0 or i == 1 or i == 4 or i == 5: QuadPattern_1(sz,a,b) else: QuadPattern_1(sz,b,a) Quadmove(sz) def QuadPattern_row_1(sz,a,b): '''creates first row of 4 X 4 pattern''' ##add range(start,stop,step) for i in range(8): if i == 0 or i == 1 or i == 4 or i == 5: fillpattern1(sz,a,b) else: fillpattern2(sz,a,b) def TurtleDrawing(sz,turtspd,a,b): '''final function to draw 4X4 pattern of quadrants''' tess.pu() if turtspd == "fast" or turtspd == "Fast": turtle.tracer(0,0) TurtleDrawingStart(sz) QuadPattern_row_1(sz,a,b) else: turtle.tracer(5,0) TurtleDrawingStart(sz) QuadPattern_row_1(sz,a,b) ############################################################################### ###############################'''calls'''##################################### ############################################################################### TurtleDrawing(sz,turtspd,a,b) wn.mainloop()
ae197e0c4a9273828a15a773428038fe1b5abab0
AErenzo/Python_course_programs
/ranNum.py
854
3.8125
4
import random def ranNum(): N = random.randint(1, 10) guess = 0 tries = 0 print('Im thinking of a number \nbetween 1 and 10.') while guess != N and tries < 5: guess = int(input('What do you think it might be? ')) if guess < N: print('Your guess is too low') elif guess > N: print('Your guess is to high') else: break tries += 1 if guess == N: print('You guessed it, well done! It took you', tries, 'tries to guess the correct number') else: print('Sorry you lost, you didnt guess the number within 5 tries.') retry = input('Would you like to play again? (y/n) ') if retry == 'y' or retry == 'Y': ranNum() else: exit ranNum()
77eaea810b5029891e8743479f0285675104897b
AErenzo/Python_course_programs
/timeTable.py
179
3.609375
4
def timesTables(): tt = int(input('Please enter the timetable you would like to veiw: ')) for i in range(1, 11): print(tt, 'x', i, '=', tt*i) timesTables()
fb04abbc101deaa7fcbca077676d3484952f959d
AErenzo/Python_course_programs
/gradeCal.py
361
4.03125
4
def gradeCal(): grade = int(input('Please enter your grade from the test: ')) if grade >= 70: print('Your score an A+') elif grade >= 60: print('You scored an A') elif grade >= 50: print('You scored a B') elif grade >= 40: print('You socred a C') else: print('You failed') gradeCal()
4d6cdd8085636c356181b0b859827bb7fe109009
AErenzo/Python_course_programs
/usernamePasswordCheck.py
431
3.875
4
'''p u''' while True: U = input('Please enter your username: ') if U.isalnum(): break else: print('Username must consist of alphanumeric values') while True: P = input('Please enter your password: ') if P.isnumeric() and len(P) < 11: break else: print('Incorrect password. Maximum length is 10 and must contain numbers only') print('Access Granted')
abd6d1be349ee7042e1e2e2c3e5be88f6e98acaf
AErenzo/Python_course_programs
/reversePyramid.py
212
3.859375
4
for i in range(1, 7): # below determines the spaces for each new line, to create the reverse pyramid affect print(" " * (7 - (8 - i))) for j in range(1, 8 - i): print(j, end = " ")
cf53362a8c3de1db8106e18d29e6c642a2a2dc13
AErenzo/Python_course_programs
/studentSubjectMatrix.py
4,706
3.875
4
students = ['maaz', 'farooq', 'maria', 'aslam'] subjects = ['math', 'physics', 'chemistry', 'biology'] matrix = [[0]*4 for i in range(4)] total = 0 for i in range(4): for j in range(4): matrix[i][j] = int(input('Please enter student marks for the matrix: ')) for i in matrix: for j in i: print(j, end = ' ') print() # print(matrix[students.index('Farooq')][subjects.index('Biology')]) while True: print('-'*20) print('Options') print('1. Veiw student record for specific subject' '\n' '2. Find all marks for a single student' '\n' '3. Find total marks of a student' '\n' '4. Find the average marks for a single student') print('-'*20) O = int(input('Using the menu list above, please select on of the options using the index: ')) if O == 1: print('Students stored in matrix', students) print() stu = (input('Using the list above please enter, exactly displayed above, the student you wish to veiw: ')) stu.lower() print() print('Subjects stored in matrix', subjects) sub = (input('Please enter the subject you wish to veiw: ')) sub.lower() print(matrix[students.index(stu)][subjects.index(sub)]) break elif O == 2: print('Students stored in matrix') for i in students: print(i, end = '\n') print() stu = int(input('Input the number at which student you wish to see (1-4): ')) if stu == 1: for i in matrix[0]: print(i, end = ' ') print() elif stu == 2: for i in matrix[1]: print(i, end = ' ') print() elif stu == 3: for i in matrix[2]: print(i, end = ' ') print() elif stu == 4: for i in matrix[3]: print(i, end = ' ') print() else: print('Invalid input') continue elif O == 3: print('Students stored in matrix') for i in students: print(i, end = '\n') print() stu = int(input('Input the number at which student you wish to see (1-4): ')) if stu == 1: for i in matrix[0]: total += i print('Maaz total overall score is', total) total = 0 elif stu == 2: for i in matrix[1]: total += i print('farooq total overall score is', total) total = 0 elif stu == 3: for i in matrix[2]: total += i print('Marias total overall score is', total) total = 0 elif stu == 4: for i in matrix[3]: total += i print('Aslam total overall score is', total) total = 0 else: print('Invalid input') continue elif O == 4: print('Students stored in matrix') for i in students: print(i, end = '\n') print() stu = int(input('Input the number at which student you wish to see (1-4): ')) if stu == 1: for i in matrix[0]: total += i avg = total // 4 print('Maaz average score is', avg) total = 0 elif stu == 2: for i in matrix[1]: total += i avg = total // 4 print('farooq average score is', avg) total = 0 elif stu == 3: for i in matrix[2]: total += i avg = total // 4 print('Marias average score is', avg) total = 0 elif stu == 4: for i in matrix[3]: total += i avg = total // 4 print('Aslam average score is', avg) total = 0 else: print('Invalid input') continue again = input('Do you want to veiw more data? (y/n): ') again.lower() if again == 'y' or 'yes': continue else: break
f289bd52b2eaf19d4e34ec72b37345af0f747d05
AErenzo/Python_course_programs
/acronym.py
640
4.21875
4
phrase = input('Please enter a phrase: ') # strip white spacing from the phrase phrase = phrase.strip() # change the phrase to upper case phrase = phrase.upper() # create new variable containing the phrase split into seperate items words = phrase.split() # create empty list for first letter of each item in words letters = [] # for loop going through each item in words, extracting the first letter and adding it to letters for i in words: letters.append(i[0]) # create new vaiable - joining each item in the letters list using no space. Saved as a new vairbale avb = ''.join(letters) print(avb)
554862cc48f286e7707a456f21794f69972ff7e3
AErenzo/Python_course_programs
/List.py
367
4.0625
4
List = [] Sum = 0 for i in range(5): item = int(input('What would you like to add to your list? ')) List.append(item) if len(List) == 5: print('Your list contains', List) for j in range(len(List)): Sum = List[j] + Sum print('The sum of your list is ', Sum) print('The average of your list is ', Sum / len(List))
b63899e121f4b30e778a5b630a0768af218ea707
julianalvarezcaro/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/101-remove_char_at.py
194
3.71875
4
#!/usr/bin/python3 def remove_char_at(str, n): posn = 0 new = '' for pos in range(0, len(str)): if pos == n: continue new = new + str[pos] return new
136a6aa0c778ac61364395fc5ccc046994d1a2c5
julianalvarezcaro/holbertonschool-higher_level_programming
/0x02-python-import_modules/iwasinalpha.py
125
3.765625
4
#!/usr/bin/python3 def alpha(): for letter in range(65, 91): print("{}".format(chr(letter)), end='') print()
ea71e69d6846d08c7cbb47cd6c37c0b6ef533f35
julianalvarezcaro/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
277
3.5
4
#!/usr/bin/python3 """4-inherits_from module""" def inherits_from(obj, a_class): """Checks if an object is and instance of a class that inherited from a_class""" if issubclass(type(obj), a_class) and type(obj) is not a_class: return True return False
f028bde75c24f7d2eec83ee24a638d0240b5628c
julianalvarezcaro/holbertonschool-higher_level_programming
/0x06-python-classes/6-square.py
1,780
4.40625
4
#!/usr/bin/python3 """6-square module""" class Square: """Square class""" def __init__(self, size=0, position=(0, 0)): """Class constructor""" self.size = size self.position = position def area(self): """Returns the area of the square""" return self.__size * self.__size @property def size(self): """Getter for the attribute 'size'""" return self.__size @size.setter def size(self, size): """Setter for the attribute 'size'""" if type(size) is not int: raise TypeError('size must be an integer') if size < 0: raise ValueError('size must be >= 0') self.__size = size def my_print(self): """Prints a square of __size size with caracter #""" if self.__size == 0: print() return for y in range(self.__position[1]): print() for fil in range(self.__size): for x in range(self.__position[0]): print(' ', end='') for col in range(self.__size): print("#", end='') print() @property def position(self): """Getter for position""" return self.__position @position.setter def position(self, position): """Setter for position""" if type(position) is not tuple or len(position) != 2: raise TypeError('position must be a tuple of 2 positive integers') if any(type(val) is not int for val in position): raise TypeError('position must be a tuple of 2 positive integers') if any(val < 0 for val in position): raise TypeError('position must be a tuple of 2 positive integers') self.__position = position
839885965d7d384e0e645c5f54d7d870c0614e42
julianalvarezcaro/holbertonschool-higher_level_programming
/0x03-python-data_structures/5-no_c.py
247
3.65625
4
#!/usr/bin/python3 def no_c(my_string): new = "" if len(my_string) == 0: return new for pos in range(len(my_string)): if my_string[pos] != 'c' and my_string[pos] != 'C': new += my_string[pos] return new
80439397baa335d5433916eb296174eca263d8c1
ieshaan12/Interview-Prep
/LeetCode/Problems-Python/543 Diameter of a Binary Tree.py
666
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inOrder(self,root): if not root: return 0 right = self.inOrder(root.right) left = self.inOrder(root.left) path = left + right self.dia = max(self.dia,path) return max(left,right) + 1 def diameterOfBinaryTree(self, root: TreeNode) -> int: self.dia = 0 self.inOrder(root) return self.dia
1cbf67a80aae5b7491a9c948526447f37f1a809c
ieshaan12/Interview-Prep
/LeetCode/Problems-Python/166 Fraction to Recurring Decimal.py
1,013
3.5
4
class Solution: def fractionToDecimal(self, numerator: int, denominator: int) -> str: ans = "" if numerator == 0: return "0" if (numerator<0 and not denominator<0) or (not numerator<0 and denominator<0): ans += "-" numerator = abs(numerator) denominator = abs(denominator) ans += str(numerator//denominator) if numerator % denominator == 0: return ans ans+= "." numerator %= denominator i = len(ans) store = dict() while numerator: if numerator not in store.keys(): store[numerator] = i else: i = store[numerator] ans = ans[:i] + "(" + ans[i:] + ")" return ans numerator *= 10 ans+=str(numerator//denominator) numerator%=denominator i+=1 return ans
2bfd45022f083535fbd56167c016c9252367ca1e
ieshaan12/Interview-Prep
/LeetCode/Problems-Python/199 Binary Tree Right Side View.py
769
3.703125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inOrder(self,root,depth): if root: self.lists.append((root.val,depth)) self.inOrder(root.left,depth+1) self.inOrder(root.right,depth+1) def rightSideView(self, root: TreeNode) -> List[int]: self.lists = [] self.inOrder(root,0) ans = dict() for k,d in self.lists: ans[d] = k return list(ans.values())
4eed791e27a4f5ca9c6a45625d41113b3d38e701
ieshaan12/Interview-Prep
/LeetCode/Problems-Python/344 Reverse String.py
250
3.703125
4
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ t = len(s) for i in range(t//2): s[i],s[t-i-1] = s[t-i-1],s[i]
dc4b0a658270447c6907b32b892c3965402a1fcb
DhavalLalitChheda/class_work
/Programs/ConvertCelsiusToFahreneit.py
211
4.1875
4
def convertToFahreneit(temp_Celsius): return temp_Celsius * 9 / 5 + 32 temp_Celsius = float(input("Please enter temp in celsius: ")) print("The temperature in Fahreneit is: ", convertToFahreneit(temp_Celsius))
62197b8a530277f020699d7dafcfb06c5d97e5ad
DhavalLalitChheda/class_work
/Programs/ReturnMiddleList.py
116
3.8125
4
def middle(list): return list[1 : len(list) - 1] letters = ['a', 'b', 'c', 'd', 'e','f'] print(middle(letters))
c093d77031e4dcb7058ad3823203a23ab3641ba0
DhavalLalitChheda/class_work
/Programs/ReadInsertList.py
323
3.953125
4
file = input('Please enter valid file: ') try: fHandle = open(file) except: print('File does not exist') exit() try: list = [] for line in fHandle: words = line.split() for i in words: if i in list: continue; list.append(i) list.sort() print(list) except: print('File contains no data') exit()
73823a8daba83bbeeeb5c1c34e25283ccb0f0c28
aleix214/Bucles-white
/mayorK05.py
279
3.8125
4
#coding: utf­8 num1 = int(input("Escribe un número: ")) suma=0 while num1 > 0: suma+=num1 num1 = int(input("Escribe otro: ")) print "El total de la suma de los numeros positivos es:", str(suma) + "."
415f457124953e2159fad841f84d986103145636
putonsky/jb_loan_calculator
/creditcalc.py
4,318
4.0625
4
import math import argparse # Creating a function calculating nominal interest rate (i) def nominal_interest_rate(interest): i = interest / (12 * 100) return i # Creating the function for calculating the number of payments def calculate_payments_number(p, a, interest): i = nominal_interest_rate(interest) n = math.log(a / (a - i * p), 1 + i) total = math.ceil(n) years = total // 12 months = total % 12 overpay = total * a - p if years > 1: if months > 1: print(f"It will take {years} years and {months} months to repay this loan!") elif months == 1: print(f"It will take {years} years and {months} month to repay this loan!") elif months <= 0: print(f"It will take {years} years to repay this loan!") elif years < 1: if months > 1: print(f"It will take {months} months to repay this loan!") elif months == 1: print("It will take 1 month to repay this loan!") elif years == 1: if months > 1: print(f"It will take 1 year and {months} months to repay this loan!") elif months == 1: print(f"It will take 1 year and {months} month to repay this loan!") elif months < 1: print("It will take 1 year to repay this loan!") print(f"Overpayment = {overpay}") # Creating function for calculating annuity payment: def calculate_annuity(p, n, interest): i = nominal_interest_rate(interest) a = math.ceil(p * ((i * math.pow(1 + i, n)) / (math.pow(1 + i, n) - 1))) overpay = a * n - p print(f"Your monthly payment = {a}!") print(f"Overpayment = {overpay}") # Creating function for calculating loan principal: def calculate_principal(a, n, interest): i = nominal_interest_rate(interest) p = math.floor(a / ((i * math.pow(1 + i, n)) / (math.pow(1 + i, n) - 1))) overpay = a * n - p print(f"Your loan principal = {p}!") print(f"Overpayment = {overpay}") # Creating a function for differential calculation: def calculate_differentiated(p, n, interest): i = nominal_interest_rate(interest) total = 0 for j in range(1, n + 1): d = math.ceil(p / n + i * p * (1 - (j - 1) / n)) total += d print(f'Month {j}: payment is {d}') overpay = total - p print(f'Overpayment = {overpay}') # Initialization parser = argparse.ArgumentParser(description="Loan calculator made with JetBrains") # Creating the script arguments parser.add_argument('--type', help="Loan payment type, Differential of Annuity") parser.add_argument('--payment', help="Monthly Payment amount", type=int) parser.add_argument('--principal', help="Credit principal", type=int) parser.add_argument('--periods', help="The number of desired periods to repay the loan", type=int) parser.add_argument('--interest', help="The loan interest rate", type=float) # Arguments parser: args = parser.parse_args() # Error catcher: if args.type not in ['annuity', 'diff']: print("Incorrect parameters!") exit(0) elif args.payment is not None and args.payment < 0 and args.principal is not None and args.principal < 0 and args.periods\ is not None and args.periods < 0 and args.interest is not None and args.interest < 0: print("Incorrect parameters!") # Main app flow: if args.type == "annuity" and args.payment is not None and args.principal is not None and args.interest is not None \ and args.periods is None: calculate_payments_number(args.principal, args.payment, args.interest) elif args.type == "annuity" and args.payment is None and args.principal is not None and args.periods is not None \ and args.interest is not None: calculate_annuity(args.principal, args.periods, args.interest) elif args.type == "annuity" and args.payment is not None and args.principal is None and args.periods is not None \ and args.interest is not None: calculate_principal(args.payment, args.periods, args.interest) elif args.type == "diff" and args.payment is None and args.principal is not None and args.periods is not None and \ args.interest is not None: calculate_differentiated(args.principal, args.periods, args.interest) else: print("Incorrect parameters! Use --type=annuity or type=diff for type you need to check")
de46edfe66ee6a76c0827d4957b4b720fb71b1a3
wmcknig/Advent-of-Code-2020
/day5.py
2,028
4.03125
4
from sys import argv """ Advent of Code Day 5 Part 1 You are given a list of strings where each string consists of the characters F, B, L, or R, meaning front, back, left, or right, respectively. The strings consist of 10 characters, the first seven of them being F or B and the latter three being L or R. The first seven progressively narrow down the halves of an array of 128 elements, front indicating the lower half and back indicating the upper half of the given partition; said partition is the entire array for the first character, the front or back for the second, the front or back of one of those for the third, and so on. This is likewise with the last three characters and an array of 8 elements, with the left being the lower half and the right being the upper half. Taken as a whole the string indicates an element from 0 to 127 and an element from 0 to 7. Given such an element pair, multiply the first element by 8 and add the second element to get a unique ID. Find the largest such ID from the list Part 2 The strings make up a contiguous range of integers with the exception of one skipped character in that range; find that missing integer. """ """ Parses a string into a seat id Equivalent to parsing an unisgned binary integer where B and R correspond to 1 and F and L correspond to 0 (this is obvious from the problem statement but was not made explicit there to keep up a practice of restating the problem) """ def parse_string(s): binary_string = "0b" for i in s: if i in "FL": binary_string += "0" elif i in "BR": binary_string += "1" return int(binary_string, 2) if __name__ == "__main__": f = open(argv[1], 'r') strings = [i.strip() for i in f] f.close() #made a list so it's reusable idlist = list(map(parse_string, strings)) print(max(idlist)) #find the missing element from the contiguous range print(set(range(min(idlist), max(idlist))).difference(set(idlist)))
6d84ceebf81c8d7df78041d4a6a063b0a77cd651
wmcknig/Advent-of-Code-2020
/day14.py
3,725
4.375
4
from sys import argv """ Advent of Code Day 14 Part 1 You are given a series of instructions either of the form "mask = STRING" or "mem[ADDR] = VAL", where STRING is a 36-element string of X, 1, or 0, ADDR is a decimal integer, and VAL is a decimal string, both expressible as 36-bit unsigned integers. These instructions manipulate an array of 36-bit integers and a bitmask. The bitmask is set by the mask instruction, and when applied to any 36-bit integer sets its bits to 1 or 0 where they are 1 or 0 in the bitmask, and leaves its bits unchanged where they are X in the bitmask. The mem instruction has its VAL (converted to binary representation) manipulated accordingly by the current bitmask and the result assigned to element ADDR of the array. Find the sum of every element in the array after all instructions are executed (all elements in the array are initially 0). Part 2 The mask modifies the address and not the value in mem instruction. It also modifies the address differently: -0 bits mean the corresponding address bit is unchanged -1 bits mean the corresponding address bit is changed to 1 -X "bits" mean the corresponding address bit can be set to 0 or 1 The X bits mean that every possible combination of 0 and 1 values, for all address bits corresponding to the X bits of the mask, is an address that is written to Find the sum of every element in the array after all instructions are executed (all elements in the array are initially 0). """ """ Applies the mask (of the form specified in the problem description) to the given integer """ def apply_mask(mask, i): #construct AND and OR masks to set 0 and 1 bits as appropriate and_mask = int(mask.replace('X', '1'), 2) or_mask = int(mask.replace('X', '0'), 2) return (i & and_mask) | or_mask """ Generates a set of addresses from a mask and value according to the part 2 rules """ def generate_addresses(mask, address): address = format(address, "036b") #current list of partial addresses prefixes = [""] for i, bit in enumerate(mask): if bit == '0': prefixes = [prefix + address[i] for prefix in prefixes] elif bit == '1': prefixes = [prefix + '1' for prefix in prefixes] elif bit == 'X': prefixes = [prefix + b for b in ['0', '1'] for prefix in prefixes] return list(int(i, 2) for i in prefixes) """ Executes an instruction to update the mask or write to memory It can be assumed that a valid mask value is provided for every mem instruction """ def execute(mem, mask, i): if "mask" in i: return i.split(" = ")[1] if "mem" in i: decompose = i.split(" = ") address = int(decompose[0][4:-1]) value = int(decompose[1]) mem[address] = apply_mask(mask, value) return mask """ Executes an instruction to update the mask or write to memory with the rules for part 2 """ def execute_floating(mem, mask, i): if "mask" in i: return i.split(" = ")[1] if "mem" in i: decompose = i.split(" = ") address = int(decompose[0][4:-1]) value = int(decompose[1]) address_list = generate_addresses(mask, address) for a in address_list: mem[a] = value return mask if __name__ == "__main__": f = open(argv[1], 'r') instructions = [i.strip() for i in f] f.close() mem = {} mask = "X" * 36 for i in instructions: mask = execute(mem, mask, i) print(sum(mem.values())) mem = {} mask = "X" * 36 for i in instructions: mask = execute_floating(mem, mask, i) print(sum(mem.values()))
042ccd0b5581f59ed89b021382c6aebee009c1fc
wmcknig/Advent-of-Code-2020
/day12.py
4,700
4.3125
4
from sys import argv """ Advent of Code Day 12 Part 1 You are given a series of instructions for navigating along a grid of the following forms: -NC, SC, EC, WE for north, south, east, or west C units (C is a non-negative integer) -LD, RD for turning left or right by D degrees (D is non-negative multiple of 90) -FC means move in the currently faced direction C units (C is a non-negative integer) You are initially facing east. Your facing direction only changes from L or R instructions, any N, S, E, or W instruction (along with F) will not change your facing. You are considered to start at the coordinates (0, 0). Find the Manhattan distance from the starting position after following all given instructions Part 2 The instructions are now interpreted to refer to a waypoint, always defined relative to the ship. N, S, E, and W mean moving the waypoint in the given directions by the given amount relative to the ship, similarly to how they meant moving the ship in part 1. L and R mean rotating the waypoint around the ship. F, however, moves the ship by the waypoint the given number of times; for instance, if the waypoint is (1, 2), F10 moves the ship 10 units east and 20 units north. The waypoint starts at 10 units east and 1 unit north. Find the Manhattan distance from the starting position after following all given instructions """ """ Updates a given position and heading according to the instruction given for part 1 """ def update_pos(instruction, position, heading): prefix, value = instruction[0], int(instruction[1:]) #handle cardinal directions if prefix == 'N': return (position[0], position[1] + value), heading if prefix == 'S': return (position[0], position[1] - value), heading if prefix == 'E': return (position[0] + value, position[1]), heading if prefix == 'W': return (position[0] - value, position[1]), heading #handle forward direction if prefix == 'F': return (position[0] + value * heading[0], position[1] + value * heading[1]), heading #handle turning if prefix == 'L': if value == 90: return position, (-heading[1], heading[0]) if value == 180: return position, (-heading[0], -heading[1]) if value == 270: return position, (heading[1], -heading[0]) if prefix == 'R': if value == 90: return position, (heading[1], -heading[0]) if value == 180: return position, (-heading[0], -heading[1]) if value == 270: return position, (-heading[1], heading[0]) #default case (not expected to ever be reached return position, heading """ Updates a given position and waypoint according to the instruction given for part 2 """ def update_waypoint(instruction, position, waypoint): prefix, value = instruction[0], int(instruction[1:]) #handle cardinal directions if prefix == 'N': return position, (waypoint[0], waypoint[1] + value) if prefix == 'S': return position, (waypoint[0], waypoint[1] - value) if prefix == 'E': return position, (waypoint[0] + value, waypoint[1]) if prefix == 'W': return position, (waypoint[0] - value, waypoint[1]) #handle forward direction if prefix == 'F': return (position[0] + value * waypoint[0], position[1] + value * waypoint[1]), waypoint #handle turning if prefix == 'L': if value == 90: return position, (-waypoint[1], waypoint[0]) if value == 180: return position, (-waypoint[0], -waypoint[1]) if value == 270: return position, (waypoint[1], -waypoint[0]) if prefix == 'R': if value == 90: return position, (waypoint[1], -waypoint[0]) if value == 180: return position, (-waypoint[0], -waypoint[1]) if value == 270: return position, (-waypoint[1], waypoint[0]) #default case (not expected to ever be reached return position, heading if __name__ == "__main__": f = open(argv[1], 'r') instructions = [i.strip() for i in f] f.close() position, heading = (0, 0), (1, 0) for i in instructions: position, heading = update_pos(i, position, heading) #print Manhattan distance print(abs(position[0]) + abs(position[1])) position, waypoint = (0, 0), (10, 1) for i in instructions: position, waypoint = update_waypoint(i, position, waypoint) #print Manhattan distance print(abs(position[0]) + abs(position[1]))
280d9f887fd4f0d898dc5974adea5e9bb625c329
alewand78/Python
/Calculator.py
545
3.9375
4
def doMath(a, b, operation): if operation == 1: return str(a + b) elif operation == 2: return str(a - b) elif operation == 3: return str(a * b) elif operation == 4: return str(round(a / b, 2)) else: return str(a % b) a = int(input("Enter first number : ")) b = int(input("Enter second number : ")) print("Sum : " + doMath(a,b,1)) print("Difference : " + doMath(a,b,2)) print("Product : " + doMath(a,b,3)) print("Quotient : " + doMath(a,b,4)) print("Modulo : " + doMath(a,b,5))
b2e9bd595ba9f8be888acef9ddc95f77166b403b
fredcommo/datasci_course_materials
/assignment3/solutions/friend_count.py
681
3.546875
4
import MapReduce import sys """ Count friends If personA is linked to personB: personB is a friend of personA, but personA can be not a friend of personB. """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: personA # value: 1 is as a friend mr.emit_intermediate(record[0], 1) def reducer(key, value): # key: personA # value: numbrer of friends total = 0 for v in value: total += v mr.emit((key, total)) # Do not modify below this line # ============================= if __name__ == '__main__': inputdata = open(sys.argv[1]) mr.execute(inputdata, mapper, reducer)
2aca9b20394221e74b27da128aafd95ff4455ccc
capt-alien/alien_refactor
/strings.py
1,781
3.859375
4
def life(count, secret_word): """Gives life count after guess""" if count == 7: print("V") print("O") if count == 6: print("V") print("O") print("|") if count == 5: print(" V") print(" O") print(" |") print("/") if count == 4: print(" V") print(" O") print(" |") print("/ \ ") if count == 3: print(" V") print(" O") print("-|") print("/ \ ") if count == 2: print("| V |") print("| O |") print("| -|- |") print("| / \ |") if count == 1: print(" ___ ") print(" / \ ") print("| V |") print("| O |") print("| -|- |") print("| / \ |") print(" \___/") if count == 0: print("Ahhhhh NOoooooOoooOOo!!!!") print("***___*** ") print("**/***\**") print("*|**V**|*") print("*|**O**|*") print("*|*-|-*|*") print("*|*/*\*|*") print("**\___/**") print("*********") print("AIRLOCK ACTIVATED! YOU LOSE") print(" NooooOOoOooOo00oooo!!!\n The passcode was {}".format(secret_word)) text = [ "Welcome to the Spaceman's Airlock", "I come in peace, GET ME OUT OF THIS AIRLOCK!", "Please Help me hack the passcode, by guessing the letters:", "The passcode has {} charictors ", "You have 7 guesses before the airlock automatically opens.", "Guess a Letter HotShot ", "So far, you have guessed:{}", "Revealed Password: {}", "Correct!", "Airlock Countdown: {}", "incorrect", "AIRLOCK ACTIVATED. NooooOOoOooOo00oooo!!! The passcode was {}", "Im in!! Thank you human! Take me to your leader!" ]
c40ca095e76f7040ef231e426975e22d4c3bd26d
pylangstudy/201711
/22/00/4.py
833
3.515625
4
import argparse # sub-command functions def foo(args): print(args.x * args.y) def bar(args): print('((%s))' % args.z) # create the top-level parser parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # create the parser for the "foo" command parser_foo = subparsers.add_parser('foo') parser_foo.add_argument('-x', type=int, default=1) parser_foo.add_argument('y', type=float) parser_foo.set_defaults(func=foo) # create the parser for the "bar" command parser_bar = subparsers.add_parser('bar') parser_bar.add_argument('z') parser_bar.set_defaults(func=bar) # parse the args and call whatever function was selected args = parser.parse_args('foo 1 -x 2'.split()) args.func(args) # parse the args and call whatever function was selected args = parser.parse_args('bar XYZYX'.split()) args.func(args)
31e3e267e80cad6472c1ae0fa969f988c88dec89
pylangstudy/201711
/19/01/6.py
221
3.515625
4
import argparse import textwrap parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') parser.add_argument('+f') parser.add_argument('++bar') print(parser.parse_args('+f X ++bar Y'.split())) parser.print_help()
b0bea18fc3d48dd1bda2e83ff52e589c7f54d1bf
kshitijgupta/all-code
/python/A_Byte_Of_Python/objvar.py
1,130
4.375
4
#!/usr/bin/python #coding=UTF-8 class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name Person.population += 1 def __del__(self): '''I am dying''' print '%s syas bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % \ Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population''' if Person.population == 1: print "I am the only person here" else: print 'We have %d persons here.' % Person.population _luolei = Person('luolei') _luolei.sayHi() _luolei.howMany() print 'hi luolei.population', _luolei.population xiaoming = Person('Xiao Ming') xiaoming.sayHi() xiaoming.howMany() xiaoming.population = 199 print 'hi xiaoming.population', xiaoming.population print 'hi luolei.population', _luolei.population _luolei.sayHi() _luolei.howMany()
d72f79ad097f5eace2fcb22d0471c0d3424290ac
elYaro/Codewars-Katas-Python
/8 kyu/Convert_number_to_reversed_array_of_digits.py
320
4.21875
4
''' Convert number to reversed array of digits Given a random number: C#: long; C++: unsigned long; You have to return the digits of this number within an array in reverse order. Example: 348597 => [7,9,5,8,4,3] ''' def digitize(n): nstr = str(n) l=[int(nstr[i]) for i in range(len(nstr)-1,-1,-1)] return l
ae32fe698d8afb7b31a70999c9875af162c2dbe6
elYaro/Codewars-Katas-Python
/8 kyu/Is_it_a_number.py
582
4.28125
4
''' Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not. Valid examples, should return true: isDigit("3") isDigit(" 3 ") isDigit("-3.23") should return false: isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero") ''' def isDigit(string): print(type(string), string) try: if abs(float(string)): return True else: if float(string) == 0.0: return True else: return False except: return False
3a50733a988cee4b84b30465185774de479efee3
elYaro/Codewars-Katas-Python
/8 kyu/Sum_of_positive.py
352
4.09375
4
''' You get an array of numbers, return the sum of all of the positives ones. Example [1,-4,7,12] => 1 + 7 + 12 = 20 Note: if there is nothing to sum, the sum is default to 0. ''' def positive_sum(arr): if arr!=[]: suma=0 for i in arr: if i >0: suma=suma+i return suma else: return 0
8b34ef774c1f41255d399714c2792da64f291fcb
elYaro/Codewars-Katas-Python
/8 kyu/You_only_need_one_Beginner.py
290
3.59375
4
''' You will be given an array (a) and a value (x). All you need to do is check whether the provided array contains the value. Array can contain numbers or strings. X can be either. Return true if the array contains the value, false if not. ''' def check(seq, elem): return elem in seq
ba06a43362449d7f90a447537840c42b591b8adf
elYaro/Codewars-Katas-Python
/8 kyu/String_cleaning.py
955
4.125
4
''' Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. For example: string_clean('! !') == '! !' string_clean('123456789') == '' string_clean('This looks5 grea8t!') == 'This looks great!' Your harried co-workers are looking to you for a solution to take this garbled text and remove all of the numbers. Your program will take in a string and clean out all numeric characters, and return a string with spacing and special characters ~#$%^&!@*():;"'.,? all intact. ''' # 2nd try - after refactor def string_clean(s): return "".join(x for x in s if not x.isdigit()) # 1st try def string_clean(s): l = list(s) ll = [] for i in l: if not i.isdigit(): ll.append(i) return "".join(ll)
ca9334b0325fdbe0e9d4505dd4ab89649d0628f3
elYaro/Codewars-Katas-Python
/8 kyu/Find_Multiples_of_a_Number.py
708
4.59375
5
''' In this simple exercise, you will build a program that takes a value, integer, and returns a list of its multiples up to another value, limit. If limit is a multiple of integer, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limit will always be higher than the base. For example, if the parameters passed are (2, 6), the function should return [2, 4, 6] as 2, 4, and 6 are the multiples of 2 up to 6. If you can, try writing it in only one line of code. ''' def find_multiples(integer, limit): output = [] i = 1 while integer * i <= limit: output.append(integer * i) i = i + 1 return output
0e771ee2e4afebdcb615e419c37779f44776ae0f
elYaro/Codewars-Katas-Python
/7 kyu/Find_twins.py
490
3.796875
4
''' Agent 47, you have a new task! Among citizens of the city X are hidden 2 dangerous criminal twins. You task is to identify them and eliminate! Given an array of integers, your task is to find two same numbers and return one of them, for example in array [2, 3, 6, 34, 7, 8, 2] answer is 2. If there are no twins in the city - return None or the equivilent in the langauge that you are using. ''' def elimination(arr): for i in arr: if arr.count(i) > 1: return i
79d418430029288067984d7573880866b3e43328
elYaro/Codewars-Katas-Python
/7 kyu/KISS_Keep_It_Simple_Stupid.py
1,093
4.34375
4
''' KISS stands for Keep It Simple Stupid. It is a design principle for keeping things simple rather than complex. You are the boss of Joe. Joe is submitting words to you to publish to a blog. He likes to complicate things. Define a function that determines if Joe's work is simple or complex. Input will be non emtpy strings with no punctuation. It is simple if: the length of each word does not exceed the amount of words in the string (See example test cases) Otherwise it is complex. If complex: return "Keep It Simple Stupid" or if it was kept simple: return "Good work Joe!" Note: Random test are random and nonsensical. Here is a silly example of a random test: "jump always mostly is touchy dancing choice is pineapples mostly" ''' # 2nd try - after refactor def is_kiss(words): return "Good work Joe!" if max(len(word) for word in words.split(" ")) <= len(words.split(" ")) else "Keep It Simple Stupid" # 1st try def is_kiss(words): if max(len(word) for word in words.split(" ")) <= len(words.split(" ")): return "Good work Joe!" else: return "Keep It Simple Stupid"
0dccf695f2c3a3b8db544619fdb07159eb250847
hacker653/Hash-Cracker
/Hash- cracker/crack.py
1,291
3.828125
4
import hashlib print(""" _ _ _ _____ _ | | | | | | / ____| | | | |__| | __ _ ___| |__ ______ | | _ __ __ _ ___| | _____ _ __ | __ |/ _` / __| '_ \ |______| | | | '__/ _` |/ __| |/ / _ \ '__| | | | | (_| \__ \ | | | | |____| | | (_| | (__| < __/ | |_| |_|\__,_|___/_| |_| \_____|_| \__,_|\___|_|\_\___|_| """) flag = 0 pass_hashes = input ("Enter Hash: ") wordlist = input ("Enter The Path of Password File: ") print("."*50) try: pass_file = open (wordlist, "r") except: print("password file not found") quit() for word in pass_file: enc_wrd = word.encode('utf-8') digest = hashlib.md5(enc_wrd.strip()).hexdigest() print(word) print(digest) print(pass_hashes) print("."*50) if digest == pass_hashes: print("[+]password found") print("[+]password is >>> " + word) flag = 1 break if flag == 0: print("password is not in the list:")
c35fc57fec26636282eba11ea122628c8a07c0a3
ericaschwa/code_challenges
/LexmaxReplace.py
1,192
4.34375
4
""" LexmaxReplace By: Erica Schwartz (ericaschwa) Solves problem as articulated here: https://community.topcoder.com/stat?c=problem_statement&pm=14631&rd=16932 Problem Statement: Alice has a string s of lowercase letters. The string is written on a wall. Alice also has a set of cards. Each card contains a single letter. Alice can take any card and glue it on top of one of the letters of s. She may use any subset of cards in this way, possibly none or all of them. She is not allowed to glue new letters in front of s or after s, she can only replace the existing letters. Alice wants to produce the lexicographically largest possible string. You are given the String s. You are also given a String t. Each character of t is a letter written on one of the cards. Compute and return the lexicographically largest string Alice can produce on the wall while following the rules described above. """ def get(s, t): """ Executes the solution to the problem described in the problem statement """ x = list(t) y = list(s) x.sort() for i in xrange(len(y)): if len(x) == 0: break if y[i] < x[-1]: y[i] = x.pop() return "".join(y)
9bd2566b812d15348a25c877936fe84716989ba6
jupiny/PythonPratice
/code/print_star.py
1,079
3.5625
4
def print_star1(count): """ 첫번째 별찍기 함수 """ for i in range(count): print("*" * (i+1)) def print_star2(count): """ 두번째 별찍기 함수 """ for i in range(count): print(" " * (count - i - 1) + "*" * (i + 1)) def print_star3(count): """ 세번째 별찍기 함수 """ for i in range(count): print("*" * (count-i)) def print_star4(count): """ 네번째 별찍기 함수 """ for i in range(count): print("" * i + "*" * (count - i)) print_star1(int(input("크기를 입력하세요 : "))) print_star2(int(input("크기를 입력하세요 : "))) print_star3(int(input("크기를 입력하세요 : "))) print_star4(int(input("크기를 입력하세요 : "))) # input.txt파일의 입력을 받아 print_star3 함수 실행 with open("./input.txt","r") as f: input_array = f.readlines() for i in range(len(input_array)): print("<input이 {test_number}일 경우>".format(test_number=int(input_array[i]))) print_star3(int(input_array[i])) print('\n')
f8ea64652ce06b2f434a7cb2499365f06a0b3f0b
limingrui9/1803
/1.第一个月/07day/3.计算器.py
313
4
4
print("*****这是一个神奇的计算器*****") a = float(input("请输入一个心仪数字")) b = float(input("请输入一个数字")) fuhao = input("请输入+-×/") if fuhao == "+": print(a+b) elif fuhao == "-": print(a-b) elif fuhao == "×": print(a*b) elif fuhao == "/": print(a/b)
4874333b6f5467713260714f07fd1ba357881dbe
limingrui9/1803
/1.第一个月/20day/2-wangzhe.py
1,266
3.65625
4
list = [] def register(): account = int(input("请输入账号")) pwd = input("请输入密码") #判断账号存在不存在 flag = 0 for i in list: if account == i["account"]: print("账号已经存在") flag = 1 break if flag == 0: dict = {} dict["account"] = account dict["pwd"] = pwd list.append(dict) print("注册成功") def login(): account = input("请输入账号") pwd = input("请输入密码") flag = 0 for i in list: if account == i["account"]: if i.get("status") == 1: print("账号在登陆着") else: if pwd == i["pwd"]: print("登录成功") i["status"] = 1#1代表登录 0代表未登录 else: print("登录失败") flag = 1 break if flag == 0: print("账号不存在,请先注册") def loginout(): account = input("请输入账号") pwd = input("请输入密码") flag = 0 for i in list: if account == i["account"]: if i.get("status") == 0: print("账号退出成功") else: print("账号根本就没登录") flag == 1 break if flag == 0 : print("账号不存在") while True: fun = int(input("请选择功能 1注册 2 登录 3 登出 4 退出")) if fun ==1: register() elif fun == 2: login() elif fun == 3: loginout()
7f2150fa8cb19d1dd0c6b87bc5274bc0f1648418
limingrui9/1803
/2-第二个月/16day/1-多线程非全局变量.py
317
3.5
4
from threading import Thread import time import threading def work(): name = threading.current_thread().name print(name) numm = 1 if name == "Thread-1" num+=1 time.sleep(1) print("呵呵呵%d"%num) else: time.sleep(1) print("哈哈哈%d"%num) t1 = work()
3a1efb41dab0012141e77237084d0b11337fce7d
limingrui9/1803
/1.第一个月/08day/8-三角形.py
128
3.765625
4
count = 1 while count<=5: if count<=5: print("*"*count) if count>10: print("*"*(10-count)) count+=1
d78887854013f18fe02f258ae8adf75929244c41
limingrui9/1803
/1.第一个月/07day/1.微信登录.py
135
3.5
4
a_passwd = "123" passwd = input("请输入密码") if passwd == a_passwd: print("密码正确") else: print("请从新输入")
7df8dee9fddf614952305e829d0a0e45f159f534
LiYingbogit/pythonfile1
/03_面向对象/ustc_04_家具类.py
1,326
3.96875
4
class HouseItem: def __init__(self, name, area): self.name = name self.area = area # print("初始化") def __str__(self): return "[%s]占地[%s]平米" % (self.name, self.area) class House: def __init__(self, house_type, area): self.house_type = house_type self.area = area self.free_area = area self.item_list = [] def __str__(self): # python 能够自动将一对括号内部的代码连接在一起 return ("户型%s\n总面积:%.2f\n[剩余:%.2f]\n家具:%s" % (self.house_type, self.area, self.free_area, self.item_list)) def add_item(self, item): print("要添加%s" % item) # 1.判断家具的面积 if item.area > self.free_area: print("%s的面积太大,无法添加" % item.area) return # 2.将家具的名称添加到列表中 self.item_list.append(item.name) # 3.计算剩余面积 self.free_area -= item.area # 1.创建家具 bed = HouseItem("席梦思", 4) chest = HouseItem("衣柜", 2) table = HouseItem("餐桌", 1.5) print(bed) print(chest) print(table) # 2.创建房子 my_home = House("三室一厅", 100) my_home.add_item(bed) my_home.add_item(chest) # my_home.add_item(table) print(my_home)
906cc9e6a8d5aa97f6d0327c73d58fb2a8a14a21
LiYingbogit/pythonfile1
/05_文件操作/ustc_01_读取文件.py
582
3.84375
4
# _*_coding:utf-8_*_ # 1.打开文件 # file = open("README", encoding='UTF-8') # with open("README", 'r', encoding='UTF-8') as file: # # 2.读取文件 # text = file.read() # print(text) file = open("README", 'r', encoding='UTF-8') text = file.read() print(text) # 文件指针的概念,当第一次打开文件时,通常文件指针会指向文件的开始位置,当执行read方法后,文件指针会移动到读取内容的末尾 print(len(text)) print("-" * 50) text = file.read() print(text) print(len(text)) print("-" * 50) # 3.关闭文件 file.close()
f41130f09592bc6201cc088b49ee2ddab0f8deae
lintgren/EDA132
/src/LAB2/Tree.py
1,043
3.8125
4
class Tree(object): "Generic tree node." def __init__(self, name='root',values =[] ,children=None): self.name = name self.values = values self.children = [] if children is not None: for child in children: self.add_child(child) def __repr__(self): return self.name def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) def print(self): if(self.name == "leaf"): '''''' else: print(self.name) if self.children.__len__()>0: for child in self.children: child.print() def __str__(self, level=0): # ret = "" # if(self.name.lower() != 'leaf'): ret = "\t" * level + repr(self.name) + "\n" for child in self.children: ret += child.__str__(level + 1) return ret def check_if_leaf(self): if self.children.__len__()>0: return False return True
a10242f6ed3268cad16740d2a072e5851cff7816
Bhaney44/Intro_to_Python_Problems
/Problem_1_B.py
1,975
4.28125
4
#Part B: Saving, with a raise #Write a program that asks the user to enter the following variables #The starting annual salary #The semi-annual raise #The portion of the salary to be saved #The total cost of the dream home #Return the number of months to pay for the down payment. starting_annual_salary = int(input('Enter your starting annual salary: ')) portion_saved = float(input('Enter the portion of your salary to save as a decimal: ')) semi_annual_raise = float(input('Enter your semi-annual raise as a decimal: ')) total_cost = int(input('Enter the cost of your dream home: ')) down_payment = total_cost * 0.25 #Initialize variables months = 0 current_savings = 0 investment_rate = 0.04 annual_salary = starting_annual_salary def savings_calculator(starting_annual_salary, semi_annual_raise, portion_saved): #Global variables global current_savings global months global annual_salary #Exit loop when savings equals or exceeds down_payment while current_savings < down_payment: #In Python += adds a value to variable and assigns the result to the that variable #Monthly_savings monthly_savings = ((annual_salary/12)*portion_saved) #Add monthly savings to current savings every month current_savings += monthly_savings #Add investment income to current savings every month current_savings += (current_savings*investment_rate)/12 #Add month months += 1 #Add semi-annual raise to salary and adjust monthly savings accordingly #In Python == is a test for equality #In Python % is a modulus #Returns the remainder when the first operancd is divided by the second if (months % 6 == 0): annual_salary += annual_salary*semi_annual_raise savings_calculator(starting_annual_salary, semi_annual_raise, portion_saved) number_of_months = print('Number of months: ', months)
2cac2a4335a4e564c4a40868555a1e763488ae32
francis95-han/python-study
/algorithm/data_structure/热土豆问题.py
1,294
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' 热土豆问题也称作 Josephus 问题。这个故事是关于公元 1 世纪著名历史学家Flavius Josephus 的,传说在犹太民族反抗罗马统治的战争中, Josephus 和他的 39 个同胞在一个洞穴中与罗马人相对抗。当注定的失败即将来临之时,他们决定宁可死也不投降罗马。于是他们围成一个圆圈,其中一个人被指定为第一位然后他们按照顺时针进行计数, 每数到第七个人就把他杀死。传说中 Josephus 除了熟知历史之外还是一个精通于数学的人。他迅速找出了那个能留到最后的位置。最后一刻,他没有选择自杀而是加入了罗马的阵营。这个故事还有许多不同的版本。有些是以三为单位进行计数,有些则是让最后一个留下的骑马逃走。但不管是哪个版本,其核心原理都是一致的 ''' from pythonds.basic.queue import Queue def HotPotato(namelist,num): simqueue=Queue() for name in namelist: simqueue.enqueue(name) while simqueue.size()>1: for i in range(num): simqueue.enqueue(simqueue.dequeue()) simqueue.dequeue() return simqueue.dequeue print(HotPotato(["Bill","David","Susan","Tom","Amy","ken"],8133222))
b5200bfe1c433f011bdd4a73e54343ccc6e0c129
francis95-han/python-study
/algorithm/sort/希尔排序.py
805
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 算法复杂度O(n^(3/2)) def shellSort(alist): sublist_count = len(alist)//2 while sublist_count > 0: for start_position in range(sublist_count): gapInsertionSort(alist,start_position,sublist_count) print("After increments of size",sublist_count, "The list is",alist) sublist_count = sublist_count // 2 def gapInsertionSort(alist,start,gap): for i in range(start+gap,len(alist),gap): current_value = alist[i] position = i while position>=gap and alist[position-gap]>current_value: alist[position]=alist[position-gap] position = position-gap alist[position]=current_value alist = [54,26,93,17,77,31,44,55,20] shellSort(alist) print(alist)
61fca1a552524037498739e3ca02c1f34a1af459
LutherCS/aads-class-pub
/src/exercises/binheapmax/binheapmax.py
1,274
3.5625
4
#!/usr/bin/env python3 """ Binary Heap implementation @authors: @version: 2022.9 """ from typing import Any class BinaryHeapMax: """Heap class implementation""" def __init__(self) -> None: """Initializer""" self._heap: list[Any] = [] self._size = 0 def _perc_up(self, cur_idx: int) -> None: """Move a node up""" # TODO: Implement this function ... def _perc_down(self, cur_idx: int) -> None: """Move a node down""" # TODO: Implement this function ... def add(self, item: Any) -> None: """Add a new item to the heap""" # TODO: Implement this function ... def remove(self) -> Any: """Remove an item from the heap""" # TODO: Implement this function ... def heapify(self, not_a_heap: list) -> None: """Turn a list into a heap""" # TODO: Implement this function ... def _get_max_child(self, parent_idx: int) -> int: """Get index of the greater child""" # TODO: Implement this function ... def __len__(self) -> int: """Get heap size""" return self._size def __str__(self) -> str: """Heap as a string """ return str(self._heap)
00d06440311ac21983118a1cd26aeac53fb79679
PanDeBatalla94/AT06_API_Testing
/MariaCanqui/session_4/practice4/regular_expressions.py
1,302
4.03125
4
import re #Add a method that is going to ask for a username : def ask_username(): username = verify_username(input("enter username(a-z1-9 ): ")) return username #Need to be write with lowercase letter (a-z), number (0-9), an underscore def verify_username(name): while True: if re.fullmatch("([a-z0-9_ ]*)", name): return name else: name = input("Not valid user name, try again: ") #Add a method that is going to ask for a password def ask_password(): password = verify_password(input("enter password (a-z),(0-9),(A-Z){8,16} : ")) return password #Need to be write with lowercase letter (a-z), number (0-9), # letter (A-Z) and the length have to be between 8 and 16 characters def verify_password(password): while True: if re.fullmatch("([a-zA-Z-0-9]{8,16})", password): return password else: password = input("Not valid password, try again: ") #Add a method that is going to ask for email def ask_email(): email = verify_email(input("enter a valid email: ")) return email def verify_email(email): while True: if re.fullmatch("(\w+\@\w+\.\w{3}\.\w{2}|\w+\@\w+\.\w{3})", email): return email else: email = input("Not valid password, try again: ") print(ask_username()) print(ask_password()) print(ask_email())
22bcd98ec42268d83ffa618ca9931f36b9582353
TroyJJeffery/troyjjeffery.github.io
/Computer Science/Data Structures/Week 3/CH3_EX10.py
2,066
4.0625
4
""" Implement a radix sorting machine. A radix sort for base 10 integers is a mechanical sorting technique that utilizes a collection of bins, one main bin and 10 digit bins. Each bin acts like a queue and maintains its values in the order that they arrive. The algorithm begins by placing each number in the main bin. Then it considers each value digit by digit. The first value is removed and placed in a digit bin corresponding to the digit being considered. For example, if the ones digit is being considered, 534 is placed in digit bin 4 and 667 is placed in digit bin 7. Once all the values are placed in the corresponding digit bins, the values are collected from bin 0 to bin 9 and placed back in the main bin. The process continues with the tens digit, the hundreds, and so on. After the last digit is processed, the main bin contains the values in order. """ import random from Stack import Stack def fill(bin): random.seed(1) for n in range(10): bin.append(random.randint(100,999)) def get_digit(digit, num): li = list(str(num)) rev = [] for i in reversed(li): rev.append(i) return int(rev[digit-1]) def repeat(bin1,bin2,digit): bin1=bin1 bin2=bin2 d=digit d=0 while i < d: bin2=sort(bin1,d) bin1=bin2 bin2.clear() i=i+1 return bin1 def sortbin(bin,digitqty): fbin=bin sbin=[] d=digitqty i=0 while i < 10: #Add items into bin2 that end with 0,1,2....) for num in fbin: if get_digit(d,num) == i: #If the last digit is equal to 0,1,2.... sbin.append(num) #add that number to list 2 i=i+1 #Otherwise increase the number of the item you are looking for. return sbin def test(digitsToSort): d = digitsToSort bin1=[] fill(bin1) bin2=sortbin(bin1,d) print("Before ") print(bin1) print("After ") print(bin2) if __name__ == '__main__': test(3) #print(get_digit(1,140)==0)