blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
efdf2c9e99d32e24ba5db7f4e5beeb96bf89131c
yaolizheng/leetcode
/236/lca.py
608
3.859375
4
from tree import TreeNode def lca(root, a, b): if not root or root.value == a or root.value == b: return root l = lca(root.left, a, b) r = lca(root.right, a, b) if l and r: return root return l if r is None else r if __name__ == '__main__': root = TreeNode(3) root.left = TreeNode(5) root.right = TreeNode(1) root.left.left = TreeNode(6) root.left.right = TreeNode(2) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(4) root.right.left = TreeNode(0) root.right.right = TreeNode(8) print lca(root, 4, 5).value
45207aafb93e656a25202e61fc18a0bd5660ca84
garandria/bijective-image-transformation
/src/imageT.py
3,552
3.640625
4
""" """ from math import gcd from PIL import Image from transformation import * class imageT: """ Image processing for bijective transformation class """ def __init__ (self, image, fct_transformation, fname="transformated"): """ Builds the object :parameter: an image :type: str """ self.__img = Image.open(image) self.__name = image self.__width = self.__img.size[0] self.__height = self.__img.size[1] self.__transfo = fct_transformation self.__dest = fname def __period(self, coord): """ Computes the step needed by the pixel to come back at its original position :parameter: coordinate of the pixel :type: tuple :return: a period and every pixel that has the same period :rtype: tuple """ cpt = 1 x, y = coord res = set() x1, y1 = self.__transfo((x, y), (self.__width, self.__height)) res.add((x, y)) while (x1, y1) != (x, y): cpt += 1 # Adding the pixels that are in the same cycle to avoid # computing them again. res.add((x1, y1)) x1, y1 = self.__transfo((x1, y1), (self.__width, self.__height)) return (res, cpt) def __cycle_l(self): """ Computes the period of every pixel of the image """ l = [[-1 for i in range (self.__width)]\ for j in range (self.__height)] for y in range(self.__height): for x in range(self.__width): if l[y][x] == -1: coords, p = self.__period((x, y)) for c in coords: x1, y1 = c l[y1][x1] = p return l @staticmethod def lcm(n, m): """ Computes the least common divisor of two integers :parameter: an integer :type: int :parameter: an integer :type: int :return: least common divisor :rtype: int """ return n * m // gcd(n, m) def stepsToOriginal(self): """ Computes the steps to transform the image to come back to the original image with a transformation :return: steps to have the original image back :rtype: int """ tmpl = self.__cycle_l() periods = {tmpl[y][x] for y in range(self.__height)\ for x in range(self.__width)} res = 1 for e in periods: res = imageT.lcm(res, e) return res def __transform(self, steps): l = self.__cycle_l() for y in range(self.__height): for x in range(self.__width): tmp = (x, y) nb_t = steps % l[y][x] for c in range (nb_t): tmp = self.__transfo(tmp, (self.__width, self.__height)) l[y][x] = tmp return l def draw(self, steps): nimage_l = self.__transform(steps) img1 = Image.new(self.__img.mode, self.__img.size) if self.__img.mode == 'P': img1.putpalette(self.__img.getpalette()) for y in range(self.__height): for x in range(self.__width): img1.putpixel( nimage_l[y][x], self.__img.getpixel((x, y))) img1.save(self.__dest + ".png") img1.show() img1.close()
8c76a4049565ca4f345e9e9034ff1391455f5055
Aye-Aye-Dev/AyeAye
/lib/ayeaye/pinnate.py
8,903
3.6875
4
import json class Pinnate: """ Dictionary or attribute access to variables loaded either from a JSON string or supplied as a dictionary. >>> a = Pinnate({'my_string':'abcdef'}) >>> a.my_string 'abcdef' >>> a['my_string'] 'abcdef' >>> a.as_dict() {'my_string': 'abcdef'} objects within lists- >>> from ayeaye.pinnate import Pinnate >>> d={'my_things' : [1,2,{'three':3}]} >>> a = Pinnate(d) >>> a.my_things [1, 2, <ayeaye.pinnate.Pinnate object at 0x108526e10>] >>> a.my_things[2].three 3 """ def __init__(self, data=None): """ :param data: mixed can be dictionary or list or set or dictionary/list encoded in json or instance of Pinnate """ # this is the 'payload', it's type is decided on first use. It's typically a dictionary because # the attribute nature of Pinnate is the most useful feature. It can also be a list or set. self._attr = None if isinstance(data, self.__class__): self._attr = data._attr elif data: self.load(data) @property def payload_undefined(self): """ No data has been set @return: boolean No data has been provided so _attrib's type hasn't yet been determined """ return self._attr is None def is_payload(self, *payload_type): """ :class:`Pinnate` can hold mixed data types. Inspect current payload type. e.g. >>> p = Pinnate({1:2}) >>> p.is_payload(dict) True @param *payload_type: type e.g. dict, set or list when multiple payload types are given just one has to match @return: boolean """ return any([type(self._attr) == pt for pt in payload_type]) def __unicode__(self): as_str = str(self._attr) return f"<Pinnate {as_str}>" def __str__(self): return self.__unicode__().encode("ascii", "replace").decode() def keys(self): if self.payload_undefined or not self.is_payload(dict): raise TypeError("Payload data isn't a dictionary") return self._attr.keys() def values(self): if self.payload_undefined: raise TypeError("Payload data hasn't been set") if self.is_payload(dict): return self._attr.values() if self.is_payload(list, set): return self._attr raise TypeError("Unknown payload data type") def items(self): if self.payload_undefined or not self.is_payload(dict): raise TypeError("Payload data isn't a dictionary") return self._attr.items() def __contains__(self, key): if self.payload_undefined: return False if self.is_payload(dict, set): return key in self._attr raise TypeError("Operation not possible with current payload data type") def __iter__(self): """ return a generator For lists and sets the generator yields each item. For dictionaries it yield (key, value) """ if self.is_payload(set, list): return iter(self._attr) if self.is_payload(dict): as_key_pairs = [(k, v) for k, v in self._attr.items()] return iter(as_key_pairs) def as_dict(self, select_fields=None): """ @param select_fields: (list of str) to only include some fields from model. @return: (dict) with mixed values """ if not self.is_payload(dict): raise TypeError(f"as_dict() can only be called when the payload data is a dictionary") if select_fields is not None: r = {} for k in select_fields: if isinstance(self._attr[k], self.__class__): v = self._attr[k].as_dict() else: v = self._attr[k] r[k] = v return r else: return { k: v.as_native() if isinstance(v, self.__class__) else v for k, v in self._attr.items() } def as_native(self): """ @return: (mixed) representation of the payload (as children elements) comprised of native python data types. """ if self.payload_undefined: return None if self.is_payload(dict): return self.as_dict() if self.is_payload(list): r = [] for item in self._attr: value = item.as_native() if isinstance(item, self.__class__) else item r.append(value) return r if self.is_payload(set): r = set() for item in self._attr: value = item.as_native() if isinstance(item, self.__class__) else item r.add(value) return r raise TypeError("Unsupported type") def as_json(self, *args, **kwargs): """ @see :method:`as_dict` for params. @returns (str) JSON representation """ return json.dumps(self.as_native(*args, **kwargs), default=str) def __getattr__(self, attr): if attr not in self._attr: raise AttributeError( "{} instance has no attribute '{}'".format(self.__class__.__name__, attr) ) if isinstance(self._attr[attr], list): def list_recurse(item): r = [] for s in item: if isinstance(s, dict): r.append(self.__class__(s)) elif isinstance(s, list): r.append(list_recurse(s)) else: r.append(s) return r return list_recurse(self._attr[attr]) elif isinstance(self._attr[attr], dict): return self.__class__(self._attr[attr]) else: return self._attr[attr] def __setattr__(self, attr, val): super(Pinnate, self).__setattr__(attr, val) if attr != "_attr": if self.payload_undefined: self._attr = {} self._attr[attr] = val def __getitem__(self, key): return self._attr[key] def __setitem__(self, key, value): if self.payload_undefined: # if key is an integer the datatype *could* also be list self._attr = {} self._attr[key] = value def get(self, key, default=None): return self._attr.get(key, default) def load(self, data): """ :param data: dict, list, set or json string :param merge: bool see :method:`update` if False or :method:`merge` when True. """ if isinstance(data, str): data = json.loads(data) self.update(data) def update(self, data): """ Extend the Pinnate with further payload values. If a setting with an existing key is supplied, then the previous value is overwritten. If the payload is a - - list - it will be extended - set - added to - dict - merged :param data: dictionary or list or set or json string """ if not isinstance(data, (dict, list, set)): raise TypeError("Unsupported type") if self.payload_undefined: if isinstance(data, dict): self._attr = {} elif isinstance(data, set): self._attr = set() elif isinstance(data, list): self._attr = [] if not self.is_payload(type(data)): p_type = str(type(self._attr)) d_type = str(type(data)) msg = ( f"The type of the update data '{d_type}' doesn't match current payload's " f"type: '{p_type}'" ) raise TypeError(msg) if self.is_payload(dict): for k, v in data.items(): if isinstance(v, dict): self._attr[k] = Pinnate(v) else: self._attr[k] = v elif self.is_payload(list): for v in data: if isinstance(v, dict): self._attr.append(Pinnate(v)) else: self._attr.append(v) elif self.is_payload(set): for v in data: if isinstance(v, dict): self._attr.add(Pinnate(v)) else: self._attr.add(v) def append(self, item): """ Can be used to add item when the payload is a list. """ self.update([item]) def add(self, item): """ Can be used to add item when the payload is a list. """ self.update(set([item]))
3f71b3a13c5765c742a4055f6f7e6f37248052ca
OsAlex/algo_python
/lesson_6/2.py
3,063
3.75
4
# 1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков. # Проанализировать результат и определить программы с наиболее эффективным использованием памяти. # Примечание: Для анализа возьмите любые 1-3 ваших программы или несколько вариантов кода для одной и той же задачи. # Результаты анализа вставьте в виде комментариев к коду. # Также укажите в комментариях версию Python и разрядность вашей ОС. # Python 3.7.2 # OS - Windows 64 import random @profile def get_sum_between_min_max_1(a): min_num = 10 max_num = 0 min_pos = 0 max_pos = 0 i = 0 for x in a: if x < min_num: min_num = x min_pos = i if x > max_num: max_num = x max_pos = i i = i + 1 if min_pos < max_pos: range_y = range(min_pos + 1, max_pos) else: range_y = range(max_pos + 1, min_pos) summa = 0 for y in range_y: summa = summa + a[y] return summa if __name__ == '__main__': a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] get_sum_between_min_max_1(a) # python -m memory_profiler 2.py # Filename: 2.py # Line # Mem usage Increment Line Contents # ================================================ # 13 14.426 MiB 14.426 MiB @profile # 14 def get_sum_between_min_max_1(a): # 15 14.426 MiB 0.000 MiB min_num = 10 # 16 14.426 MiB 0.000 MiB max_num = 0 # 17 14.426 MiB 0.000 MiB min_pos = 0 # 18 14.426 MiB 0.000 MiB max_pos = 0 # 19 14.426 MiB 0.000 MiB i = 0 # 20 # 21 14.426 MiB 0.000 MiB for x in a: # 22 14.426 MiB 0.000 MiB if x < min_num: # 23 14.426 MiB 0.000 MiB min_num = x # 24 14.426 MiB 0.000 MiB min_pos = i # 25 14.426 MiB 0.000 MiB if x > max_num: # 26 14.426 MiB 0.000 MiB max_num = x # 27 14.426 MiB 0.000 MiB max_pos = i # 28 14.426 MiB 0.000 MiB i = i + 1 # 29 # 30 14.426 MiB 0.000 MiB if min_pos < max_pos: # 31 14.426 MiB 0.000 MiB range_y = range(min_pos + 1, max_pos) # 32 else: # 33 range_y = range(max_pos + 1, min_pos) # 34 # 35 14.426 MiB 0.000 MiB summa = 0 # 36 # 37 14.426 MiB 0.000 MiB for y in range_y: # 38 summa = summa + a[y] # 39 # 40 14.426 MiB 0.000 MiB return summa
9ce26ed28f29934ddf846c65d0b8e640cb1155c3
maxechterling/qbb2017-answers
/day3-lunch/sort.py
439
3.640625
4
#!/usr/bin/env python import random nums = [x for x in range(3, 100)] print nums key = 14 checked = [] for i, n in enumerate(nums): checked.append([i, n]) while True: midInt = len(checked)/2 - 1 mid = checked[midInt][1] if mid == key: print 'Found it at index %d!' % checked[midInt][0] break elif key > mid: checked = checked[mid:] elif key < mid: checked = checked[:mid]
372d1d7963dcf64b6a0913690af7ab8425b644f2
QAMilestoneAcademy/PythonForBeginners
/Quizzes/Quiz_BasicConcepts.py
732
4.59375
5
# 1. What does this code output? print(1 + 2 + 3) #2. What does this code output? print((4 + 8) / 2) #3.What is the result of this code? print(7%(5 // 2)) #4.Complete the code to create a string containing a double quote. print("__") #5.Fill in the missing part of the output. print("""First line second line""") print('First line __second line') #6.Which line of code produces an error? print('5' + 6) print(3 + 4) print("7" + 'eight') print("one" + "2") # What is the output of this code? print(3 * '7') # What is the output of this code? spam = "eggs" print(spam * 3) # What is the output of this code? print(int("3" + "4")) # # What is the output of this code? print(float("210" * int(input("Enter a number:" ))))
6ffe8f344087d58cf95c02373c18bb264f7aee3d
BooYang-CS/python3_code
/11/11_2.py
2,499
4.46875
4
#collections #collections是python内建的一个集合模块,提供了许多有用的集合类 #1.namedtuple p=(1,2)#用一个元组tuple表示不变集合,很难看出这个tuple是用来表示一个坐标的 from collections import namedtuple Point=namedtuple('Point',['x','y']) p=Point(1,2) print(p.x) print(p.y) print(p[1])#但是p还是一个元组tuple只不过是一个定制版的tuple print(isinstance(p,tuple)) #namedtuple是一个函数,它用来创建一个自定义的tuple对象,并规定tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素 #这样可以用namedtuple可以定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用。 #类似地,也可以用坐标半径表示一个园 Circle=namedtuple('Circle',['x','y','r']) #2.deque #使用list存储数据时,按索引访问数据很快,但是插入和删除就很慢,因为list是线性存储,数据量大时,插入和删除效率很低 #deque是为了高效实现插入和删除的双向列表,适合用于队列和栈 from collections import deque q=deque(['a','b','v']) q.append('x') q.appendleft('y') print(q) q.pop()#删除尾部元素 q.popleft()#删除头部元素 print(q) #deque实现 list的append()和pop(),还支持appendleft()和popleft(),这样可以非常高效的向头部和尾部添加或删除元素。 #3.defaultdict #使用dict时,如果引用的Key不存在,就会抛出KeyError。如果希望key不存在时,返回一个默认值,就可以用defaultdict from collections import defaultdict dd=defaultdict(lambda:'N/A') dd['key1']='abc' print(dd['key1']) print(dd['key2'])#key2不存在,返回默认值 N/A #defaultdict的其他行为跟dict是完全一样的 #4.OrderedDict #使用dict时,Key是无序的,在对dict做迭代时,我们无法确定key的顺序。 #要保持key的顺序,可以使用OrderedDict from collections import OrderedDict d=dict([('a',1),('f',3),('t',5)]) print(d)#dict的key是无序的 od=OrderedDict([('a',1),('c',4),('r',0)]) print(od)#OrderedDict的key是有序的 #OrderedDict的key会按照插入的顺序排列,而不是Key本身排序 od1=OrderedDict() od1['x']=1 od1['r']=2 od1['w']=4 print(list(od1.keys()))#按照插入的Key的顺序返回,将keys按list格式返回 #5. Counter #Counter是一个简单的计数器,例如,统计字符出现的个数 from collections import Counter c=Counter() for ch in 'Programming': c[ch]=c[ch]+1 print(c) print(c)
f1551bfb4edc0e99fe23ee0505b10b2ff8dc8b36
devinlimit/Clarusway_aws_devops_workshop
/python/coding-challenges/vowels.py
295
3.703125
4
text1 = input("Please enter a string: ") text = text1 + " " textlist = list(text) vowelslist = ["a", "e", "o", "ö", "ı", "i", "u", "ü"] result = "negative" j = 0 for i in textlist: if (textlist [j] and textlist [j+1]) in vowelslist: result = "positive" j += 1 print(result)
e9f2135bb11cf02ca6e3da7766151f3323aa1a6d
Claudio911015/StockPriceCrawler
/WebLinkedList.py
4,402
3.84375
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 7 09:21:31 2018 @author: zerow """ import datetime class WebNode: def __init__(self, WebPage, Time): """ Initialize class """ self.WebPage = WebPage self.Time = Time self.pNext = None class WebList: def __init__(self): """ Initialize linked list """ self.length = 0 self.head = None def IsEmpty(self): """ Check if linked list is empty """ return self.length == 0 def Clear(self): """ Clear the whole linked list """ self.head = None self.length = 0 print("Clear the linked list finished.") def Append(self, NewWebNode): """ Append the web node to the last """ if isinstance(NewWebNode, WebNode): pass else: print ('Input node is not valid') print (exit) # Deal with empty list if self.IsEmpty(): self.head = NewWebNode else: node = self.head while node.pNext: node = node.pNext node.pNext = NewWebNode self.length += 1 def Insert(self, WebPage, Time, Index): """ Insert a node into the list """ # First judge if the insertion position is valid if type(Index) is int: if Index > self.length: print("Input index value is out of range.") return else: NewWebNode = WebNode(WebPage, Time) CurrentNode = self.head # Deal with index if Index == 0: self.head = NewWebNode NewWebNode.pNext = CurrentNode else: # Locate the node attached to the index while Index - 1: CurrentNode = CurrentNode.pNext Index -= 1 # Insert the new node NewWebNode.pNext = CurrentNode.pNext CurrentNode.pNext = NewWebNode self.length += 1 return else: print ("Input index value is invalid.") def Delete(self, Index): """ Delete the element of certain index position """ if type(Index) is int: if Index > self.length: print ("Input index value is out of range.") return else: CurrentNode = self.head if Index == 0: self.head = self.head.pNext else: while Index - 1: CurrentNode = CurrentNode.pNext Index -= 1 CurrentNode.pNext = CurrentNode.pNext.pNext self.length -= 1 return else: print ("Input index value is invalid.") def GetWebPage(self, Index): """ Extract the web page stored in the position """ if type(Index) is int: if Index > self.length: print ("Input index value is out of range.") return else: CurrentNode = self.head if Index == 0: return [self.head.WebPage, self.head.Time] else: while Index - 1: CurrentNode = CurrentNode.pNext Index -= 1 return [CurrentNode.pNext.WebPage, CurrentNode.pNext.Time] else: print ("Input index value is invalid.") def GetLength(self): """ Return the length of the linked list """ CurrentNode = self.head if CurrentNode: i = 1 while CurrentNode.pNext: CurrentNode = CurrentNode.pNext i += 1 return i else: return 0 def PrintLinkedList(self): """ Print all the elements in the linked list """ if self.IsEmpty(): print ("The web list is empty.") else: CurrentNode = self.head print (CurrentNode.WebPage) while CurrentNode.pNext: CurrentNode = CurrentNode.pNext print (CurrentNode.WebPage) if __name__ == '__main__': ### Main ### print ('Completed construction of linked list.')
fcb3ebc3606d20dcf9648e57067bd708060b7230
rafaelperazzo/programacao-web
/moodledata/vpl_data/29/usersdata/123/9688/submittedfiles/atividade.py
161
3.765625
4
# -*- coding: utf-8 -*- from __future__ import division import math n= int(input('Insira um número:')) cont=0 while n>0: n=n//10 cont=cont+1 print cont
7e00f12c4a1a34fda744ed990095ba90616b948d
tinoking63/Projects
/submission_001-toy-robot/try.py
324
4.09375
4
# print("* Move Forward " + str(size)) # print("* Turn Right " + str(degrees) + " degrees") for j in range(4): degrees = 90 for k in range(360): # print("* Move Forward " + str(length)) # print("* Turn Right " + str(degrees) + " degrees")
59a7c5a9e4fcd0c8151f11a755c000fe9187b10e
UtileHomme/Programming_Codes
/Python_by_mosh/app5.py
2,153
4.46875
4
# How to get input from a user - 18.67 # name = input('What is your name? ') # # print('Hi ' + name) # How to get age from birth year # birth_year = input('Birth year: ') # gives the datatype # print(type(birth_year)) # # age = 2019 - int(birth_year) # gives the datatype of age # print(type(age)) # print(age) # How to get weight in kgs from lbs # weight_lbs = input('Weight (lbs): ') # weight_kg = int(weight_lbs) * 0.45 # print(weight_kg) # course = 'Python for "Beginners"' # print(course) # Three quotes are used for defining strings that span multiple lines # course = ''' # Hi John, # Thank you for mail # ''' # course = 'Python' # this will give us the character of the first index # print(course[0]) # this will give the last character # print(course[-1]) # starts the character from first index upto the second index # print(course[0:3]) -> prints pyt # print(course[1:]) -> print yt till the end # Print the name backwards # name = 'Jatin' # starts from index 1 and leaves out the last index # print(name[1:-1]) # first = 'John' # last = 'Smith' # # message = first + ' [' + last + '] is a coder' # Formatted string # msg = f'{first} [{last}] is a coder' # print(msg) # print(message) # course = 'Python for Beginners' # print(len(course)) # print(course.upper()); # print(course.lower()); # Used for finding character indices - returns -1 when the character isn't found # print(course.find('o')) # Used for replacing a substring # print(course.replace('Beginners', 'Absolute Beginners')) # Checks whether a substring exists in a string - returns boolean value # print('Python' in course) # Gives float value # print(10/3) # Gives int value # print (10 // 3) # Gives remainder # print(10 % 3) # Gives exponential value # print(10 ** 3) # For rounding the number # x = 2.9 # print(round(x)) # Returns positive representation of the value # print(abs(-2.9)) # for importing math module # import math # print(math.ceil(2.9)) # print(math.floor(2.9)) # If statements is_hot = False is_cold = True if is_hot: print("It's a hot day") elif is_cold: print("It's cold") else: print("Enjoy your day")
fb86d67007c2e4d205545e7c83831ff784361698
BITMystery/leetcode-journey
/334. Increasing Triplet Subsequence.py
777
3.578125
4
import sys class Solution(object): def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ stack = [] minSecondNum = sys.maxint for num in nums: if num > minSecondNum: return True if not stack: stack.append(num) else: if num > stack[-1]: stack.append(num) if len(stack) == 3: return True else: tmp = stack.pop() if len(stack) == 1: if num <= stack[-1]: stack.pop() if tmp < minSecondNum: minSecondNum = tmp stack.append(num) return False s = Solution() print s.increasingTriplet([4, 2, 1, 3, 2, 1, 5])
57a8e8180dc136fadbf0e8171f8f9a2aa0ff342c
lizzzcai/leetcode
/python/string/1297_Maximum_Number_of_Occurrences_of_a_Substring.py
2,458
3.734375
4
''' 13/06/2020 1297. Maximum Number of Occurrences of a Substring - Medium Tag: String, Bit Manipulation Given a string s, return the maximum number of ocurrences of any substring under the following rules: The number of unique characters in the substring must be less than or equal to maxLetters. The substring size must be between minSize and maxSize inclusive. Example 1: Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4 Output: 2 Explanation: Substring "aab" has 2 ocurrences in the original string. It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize). Example 2: Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3 Output: 2 Explanation: Substring "aaa" occur 2 times in the string. It can overlap. Example 3: Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3 Output: 3 Example 4: Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3 Output: 0 Constraints: 1 <= s.length <= 10^5 1 <= maxLetters <= 26 1 <= minSize <= maxSize <= min(26, s.length) s only contains lowercase English letters. ''' from typing import List import collections # Solution class Solution1: ''' Time complexity : O(n) Space complexity : O(n) ''' def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int: ''' https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/462213/Python-2-lines-Counter If a string have ocurrences x times, any if its substring must appear at least x times. There must be a substring of length minSize, that has the most ocurrences. So that we just need to count the ocurrences of all subtring with length minSize. ''' count = collections.defaultdict(int) for k in range(len(s)-minSize+1): word = s[k:k+minSize] count[word] += 1 res = 0 for w in count: if len(set(w)) <= maxLetters: res = max(res, count[w]) return res # Unit Test import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_testCase(self): for Sol in [Solution1()]: func = Sol.maxFreq self.assertEqual(func("aaaa", 1, 3, 3), 2) self.assertEqual(func("aababcaab", 2, 3, 4), 2) if __name__ == '__main__': unittest.main()
d1f759a8af11320ef39b2ff6809655108f761dbf
IMDCGP105-1819/text-adventure-Barker678
/AoA-chapter-2.py
9,822
3.640625
4
import time import random class WEAPONS(object): def __init__(self): self.WEAPONS = { 'Fist': (3,8), 'stick': (4,9), 'pulse_baton': (5,10), 'alien_blaster': (5,12), } self.current_weapon = WEAPONS['Fist'] def add_WEAPONS(self,name, weapon): self.WEAPONS[name] = weapon print ('You have picked up {} to your inventory').format(name.upper()) def __str__(self): for WEAPONS in self.WEAPONS.values(): print ('\t'.join([str(x)for x in [WEAPONS.name]])) if not WEAPONS.inventory: print ('You Have Nothing!') class player(object): def __init__(self): self.health = { 'health': (16) } def game(): def print_alien(): time.sleep(2) print(" dMMMb._ .adOOOOOOOOOba. _,dMMMb_ ") print(" dP' ~YMMb dOOOOOOOOOOOOOOOb aMMP~ `Yb") print(" V ~MMb dOOOOOOOOOOOOOOOOOb dM~ V") print(" `Mb. dOOOOOOOOOOOOOOOOOOOb ,dM' ") print(" `YMb._ |OOOOOOOOOOOOOOOOOOOOO| _,dMP' ") print(" __ `YMMM| OP'~0OOOOOOOOOOO0~`YO |MMMP' __ ") print(" ,dMMMb. ~~' OO `YOOOOOP' OO `~~ ,dMMMb ") print(" _,dP~ `YMba_ OOb `OOO' dOO _aMMP' ~Yb._") print(" <MMP' `~YMMa_ YOOo @ OOO @ oOOP _adMP~' `YMM>") print(" `YMMMM\`OOOo OOO oOOO'/MMMMP' ") print(" ,aa. `~YMMb `OOOb._,dOOOb._,dOOO'dMMP~' ,aa ") print(" ,dMYYMba._ `OOOOOOOOOOOOOOOOO' _,adMYYMb. ") print(" ,MP' `YMMba._ OOOOOOOOOOOOOOOOO _,adMMP' `YM.") print(" MP' ~YMMMba._ YOOOOPVVVVVYOOOOP _,adMMMMP~ `YM") print(" YMb ~YMMMM\`OOOOI`````IOOOOO'/MMMMP~ dMP") print(" `Mb. `YMMMb`OOOI,,,,,IOOOO'dMMMP' ,dM' ") print(" `' `OObNNNNNdOO' `' ") print(" `~OOOOO~' ") def fight_enemy(enemy_name, min_enemy_damage, max_enemy_damage, min_player_damage, max_player_damage): enemy_damage_dealt = random.randint(min_enemy_damage, max_enemy_damage) player_damage_dealt = random.randint(min_player_damage, max_player_damage) if enemy_damage_dealt > player_damage_dealt: print("Uh-oh! You died!") elif enemy_damage_dealt < player_damage_dealt: print("You killed the {enemy_name}".format(enemy_name=enemy_name)) else: print("You walk away unscathed, but the {enemy_name} still lives.".format(enemy_name=enemy_name)) def chapter_2(inventory): print("after finding the corpse of the woman, you see") time.sleep(1) print("there is a sort of alien map with parts of the ship,") time.sleep(1) print("with where you are, which seems to be the holding cells") time.sleep(1) print('\nwhoooosh') time.sleep(1) # NOTE: chapter 2 has more in the way of things to do at the moment print('....') # NOTE: 6 rooms which is on a elevator so easy access for user time.sleep(1) def start(inventory): print('an elevator opens up in the room your in') print('\n[-MAIN ELEVATOR-]') print('\n1.) deck 1 - Holding deck') print('2.) deck 2 - Maintenance') print('3.) deck 3 - Cargo Hold - Airlock') print('4.) deck 4 - Docking Port') print('5.) deck 5 - Helm') print('6.) deck 6 - Observation\n') cmdlist = ['1', '2', '3', '4', '5', '6',] cmd = cmdlist if cmd == '1': game(inventory) elif cmd == '2': print('\n- DECK 2 - MAINTENANCE LOCKED -') time.sleep(2) chapter_2(inventory) elif cmd == '3': cargo_hold(inventory) elif cmd == '4': if 'Docking Port keycard' in inventory: print('\n- Docking Port - Docking Port LOCKED -') time.sleep(2) docking_port(inventory) elif cmd == '5': helm(inventory) elif cmd == '6': print('\n- DECK 6 - OBSERVATION LOCKED -') time.sleep(2) observatory(inventory) else: observatory(inventory) def cargo_hold(inventory): time.sleep(1) print('....') time.sleep(1) print('''\nYou enter the Cargo Hold, two militarised aliens with big laser guns unload a barrage of laser fire at you. Their fire is very accurate and you take a direct hit to your lungs''') print("you take 3 damage") player.health - 3 print(''' .-. .-. _..--'`;;`-..-';;'`--.._ .';, _ `;;' _ ,;`. ;;' `;;' `;.`;;'.;' `;;' `;; .;;._.;'`;. `;;' .;'`;._.;;. ;' '`;;` `;;' ';;'` `; ;: .:. `;;. `--' .;;' .:. :; ;. .:|:. `;;;;' .:|:. .; `; `:|:' .;;'`;;. `:|:' ;' `;. `:' .;;'.::::.`;;. `:' .;' `;._.;;' .:`::::':. `;;._.;' .::::. `:: (:._.::._.:) ::' .::::. .:::::' `::.`:_.--.`:::::. .--._:'.::' `:::::. .::' `:MJP `::-.:::"""":::.-::' PJM`:: `::. .::' .::' | /.^^^..^^^.\ | `:: `:. ::: .:'::. \( `;;;..;;;' )/ .:::: ::: :: : .:':. `::. \ / .::' .: . :: : :: . : `::. .::' : : :: : .: : `.::. `:. .:' .::.' : :. :: : : : :::. `:. .:' .::: : : : :: :: : :' `:. :. .: .:' `: : :: ::: : :: `:. :. .: .:' :: : ::: ' : :::' :. `::' .: `::: : `''') print('\n[-CARGO HOLD - AIRLOCK-]') print('....') time.sleep(1) print('....') time.sleep(1) print("you have died") playagain exit(0) def observatory(inventory): time.sleep(1) print('....') time.sleep(1) print('''\nThe observatory is filled with debris. There is laser scoring everywhere and there are corpses everywhere, human and alien. In the corner there is an injured human still alive but close to death. You can try to talk to him\n''') print('[-Observatory-]') print('\n1.) talk to human') print('2.) Return to Main Elevator') cmdlist = ['1', '2'] cmd = cmdlist if cmd == '1': 'docking_port_keycard'(inventory) elif cmd == '2': start(inventory) def docking_port(inventory): time.sleep(1) print("....") time.sleep(1) def helm(inventory): time.sleep(1) print('....') time.sleep(1) print('''\nYou enter the helm where all navigation takes place. A bigger alien Enemy which looks in Command is posted here. This alien is extremely powerfull.''') print('\n[-Helm-]') print('\n1.) Attack the Alien') print('2.) Retreat to Main Elevator') cmdlist = ['1', '2'] cmd = cmdlist if cmd == '1': print('\n....') time.sleep(1) print('\n....') print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print (" Fighting... ") print (" YOU MUST HIT ABOVE A 5 TO KILL THE ALIEN ") print ("IF THE ALIEN HITS HIGHER THAN YOU, YOU WILL DIE") print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print_alien() fight_enemy('BIG-ALIEN', 5, 8, 4, 20) time.sleep(2) if cmd == '2': print('''\nThe bigger alien is now alert and has you locked on. You try to retreat back to the elevator but its to late..''') print('....') time.sleep(1) print('....') time.sleep(1) print('\nGAME OVER\n') exit(0) chapter_2 def playagain(): if playagain == ['y', 'Y', 'Yes', 'YES', 'yes']: chapter_2 if playagain in ['n', 'N', 'No', 'NO', 'no']: print("Thank you for playing, hope you enjoyed the adventure!") exit() game()
fa6062263065f4a29e61692354f90cd3c7e2ac24
why1679158278/python-stu
/python资料/day8.21/day16/demo02.py
157
3.796875
4
""" 内置生成器 zip """ list01 = ["张无忌", "赵敏", "周芷若"] list02 = [1001, 1002] for item in zip(list01, list02): print(item)
d979a8dfa4bd1e6a2da3f03083b1c19c87078946
aman1310verma/TWOC-day4-
/program4.py
449
4.21875
4
m_dict={} size = int(input("\nEnter number of keys in the dictionary:")) for i in range(size): print("Key-Value #{}".format(i+1)) key=input("Enter name of key:") value = input("Enter key value:") m_dict[key] = value print() print("\nOriginal dictionary is:", m_dict) copy_dict={} for key,value in m_dict.items(): if value not in copy_dict.values(): copy_dict[key] = value print("\n New Dictionary :",copy_dict)
e6334378d185f20330bcb68936c01bebda65c953
go2bed/python-oop
/oop/oop/Main.py
465
3.71875
4
from oop.oop.Book import Book class Dog(object): species = 'mammal' def __init__(self, breed, name): self.breed = breed self.name = name def area(self): return self.species def set_name(self, name): self.name = name def get_name(self): return self.name sam = Dog('Lab', 'Sam') print(sam.breed) sam.set_name('bublik') print(sam.get_name()) book = Book("Python Rocks!", "Jose Portilla", 159) print(book)
93889dc5074765f96533494079c439df270b6cba
FunkGG/Leetcode
/day2/25_reverseKGroup_95.64%.py
661
3.71875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: out = l = ListNode(0) nodelist = [] while head: nodelist.append(head) head = head.next if len(nodelist) == k: nodelist.reverse() for node in nodelist: l.next = node l = l.next nodelist = [] l.next =None if nodelist: l.next = nodelist[0] return out.next
d3e45a5677184a3c8a8929bf5eef3457f0080baf
Animesh0515/Library-Management-System
/display.py
763
3.703125
4
def display(list_2d): print("\t\t\t"," ","Welcome to the Library") print("\t\t\tHere are the list of the Books ","\n") dash='-'*95 print(dash) print("S.NO\t\t","Book Available\t\t\t","Author\t\t\t","Quantity\t","Price") print(dash) for i in range(len(list_2d)): print(i+1,end="\t\t ") for j in range(len(list_2d[i])): if(len(list_2d[i][j])>22): print(list_2d[i][j],end="\t ") elif(len(list_2d[i][j])>14 and len(list_2d[i][j])<22): print(list_2d[i][j],end="\t\t ") else: print(list_2d[i][j],end="\t\t ") if(j==0): print(end="\t ") print("\n") print(dash)
58ed036871c38b34a0552b31a2f354ed3bc44374
i-syang/AutomateTheBoringStuffWithPython
/chapter_8/8_2_3_write_file.py
458
3.5
4
#!/usr/bin/python3.5 filename = "/home/isyang/Code/AutomateTheBoringStuffWithPython/chapter_8/8_2_3_write_file.txt" baconFile = open(filename, 'w') # 创建写 baconFile.write('hello world\n') baconFile.close() baconFile = open(filename, 'a') # 加, append baconFile.write('aaaaaaaaaaaaaaaaaaaaaaaaaa') baconFile.close() baconFile = open(filename, 'r') # 读 content = baconFile.read() baconFile.close() print(content)
5905d05acc28165b79ee5bfc328e019b6c47ea69
vbuzato/Exercises-Python
/ex016.py
304
4
4
from math import floor, ceil num = float(input('Digite um número: ')) print('O número {:.2f} tem a parte inteira {}.'.format(num, floor(num))) print('O número {:.3f} arredondado para cima é {}.'.format(num,ceil(num))) # O comando floor arredonda para baixo # O comando ceil arredonda para cima
d38253d1a41cc9ee3c08267a31c13b9f373266d3
samensah/Pattern-Avoidance
/pattern_distribution.py
7,628
4.03125
4
__author__ = 'samuel' from itertools import permutations import numpy as np from itertools import * #import sys #sys.stdout = open('/home/samuel/Dropbox/Files/Essay Combinatorics/AIMSEssay/myoutput.txt', 'w') mesh_pattern = np.array([[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]]) def word(n): """ List all permutations of Order n @param n: Length/Order of number sequence @return: List of permutations of order n >>> word(2) ... (('1','2'),('2','1')) """ perm_list=[] for i in range(1,n+1): perm_list.append(i) perms = (p for p in permutations(perm_list)) return perms def alternate(perms_n): """ Listing all Alternating Permutations @param perms_n: List of permutations of Order n @return: List of all alternating permutations of order n >>> alternate(word(3)) ... [[1,3,2], [2,1,3], [2,3,1], [3,1,2]] """ alternate_list = [] for perm in perms_n: statement = perm[0] < perm[1] count = 0 for i in range(1, len(perm) - 1): if statement == (perm[i] < perm[i + 1]): break count += 1 statement = not statement if count == len(perm)-2: alternate_list.append(list(perm)) return alternate_list def up_alternate(alternate_perms): up_alt_list = [] for term in alternate_perms: if term[0] < term[1]: up_alt_list.append(term) return up_alt_list def down_alternate(alternate_perms): down_alt_list = [] for term in alternate_perms: if term[0] > term[1]: down_alt_list.append(term) return down_alt_list def permutation_diagram(term): """ @param term: permutation @return: returns permutation diagram of permutation """ old_perm_matrix = [[0 for _ in range(len(term))] for _ in range(len(term))] for i,v in enumerate(term): old_perm_matrix[i][v-1] = v new_perm_matrix = zip(*old_perm_matrix) return np.array(new_perm_matrix) def locate_all_indices(perm, pattern): """ Output all the lists of indices where pattern occurs in permutation @param perm: permutation @param pattern: pattern of length 3 @return: a list of lists containing index corresponding to pattern and a list of index value >>> locate_all_indices([3,2,1], [3,2,1]) ... [[[0, 1, 2], [3, 2, 1]]] """ indices_of_perm = [] count = 0 for i in range(len(perm)-2): for j in range(i+1, len(perm)-1): for k in range(j+1, len(perm)): if (pattern == [1, 2, 3]) and (perm[i] < perm[j]) and (perm[j] < perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 elif (pattern == [2, 3, 1]) and (perm[i] < perm[j]) and (perm[j] > perm[k]) and (perm[i] > perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 elif (pattern == [3, 1, 2]) and (perm[i] > perm[j]) and (perm[j] < perm[k]) and (perm[i] > perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 elif (pattern == [1, 3, 2]) and (perm[i] < perm[j]) and (perm[j] > perm[k]) and (perm[i] < perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 elif (pattern == [2, 1, 3]) and (perm[i] > perm[j]) and (perm[j] < perm[k]) and (perm[i] < perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 elif (pattern == [3, 2, 1]) and (perm[i] > perm[j]) and (perm[j] > perm[k]): indices_of_perm.append([[i, j, k], [perm[i], perm[j], perm[k]]]) count += 1 if count != 0: return indices_of_perm return [] def mesh_pattern_coordinate(mesh_pattern): """ @param mesh_pattern: 4x4 list showing prohibited areas in pattern @return: coordinates of prohibited areas labelled as 1 >>> mesh_pattern_coordinate([[0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0]]) ... [(0, 2), (2, 2), (3, 2)] """ coordinate_list = [] for rownum, row in enumerate(mesh_pattern): for colnum, value in enumerate(row): if value == 1: coordinate_list.append((rownum, colnum)) return coordinate_list def prohibited_area(mesh_pattern, perm, pattern): """ @param mesh_pattern: 4x4 matrix showing prohibited areas labelled as 1 @param perm: permutation @param pattern: pattern @return: x & y ranges of prohibited areas in permutation diagram >>> prohibited_area([[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]], [3,1,2,4], [3, 1, 2]) ... [[(1, 2), (0, 1)], [(1, 2), (1, 2)], [(1, 2), (2, 3)]] """ xy_ranges = [] #horizontal range for prohibited area in perm diagram for term1,term2 in locate_all_indices(perm, pattern): for coordinate in mesh_pattern_coordinate(mesh_pattern): a = coordinate[0] b = coordinate[1] if b== 0: (c, d) = [0, term1[b]] elif b==3: (c, d) = [term1[b-1], len(perm)-1] else: (c, d) = [term1[b-1], term1[b]] #vertical range for prohibited area in perm diagram term02 = sorted(term2, key=int) if a == 0: (e, f) = (0, int(term02[a])-1) elif a == 3: (e, f) = (int(term02[a-1])-1, len(perm)-1) else: (e, f) = (int(term02[a-1])-1, int(term02[a])-1) xy_ranges.append([(c,d),(e,f), term2]) return xy_ranges def inclusion_test(area, perm): return [x for x in area if x in perm] == [] def check_prohibit_area(mesh_pattern, perm, pattern): if locate_all_indices(perm, pattern) == []: return 0 else: prohibited = [] prohibited_new = [] for terms in prohibited_area(mesh_pattern, perm, pattern): prohibited.append(terms) for key, group in groupby(prohibited, lambda t: t[2]): prohibited_new.append(list(group)) count = 0 for term in prohibited_new: check_local = [] for hori, vert, term2 in term: for i, j in enumerate(permutation_diagram(perm)): if i > (vert[0]-1) and i < (vert[1]+1): section = j[hori[0]:hori[1]+1] #print(section) a = [x for x in perm if x not in term2] statement = inclusion_test(section, a) check_local.append(statement) check_local = list(set(check_local)) if True in check_local and len(check_local) == 1: count += 1 return count def occurences(tokens,words): count = 0 for i in range(0,len(words),1): if (words[i] == tokens): count += 1 return count if __name__ == '__main__': mesh_pattern = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]) pattern = [3,1,2] mylist = [] for i in down_alternate(alternate(word(7))): #for i in up_alternate(alternate(word(2))): #for i in alternate(word(7)): mylist.append(check_prohibit_area(mesh_pattern, i, pattern)) for num in list(set(mylist)): print(occurences(num, mylist), 'permutations contains', num , 'occurrences of pattern',pattern)
8b00e6626dc7cf34e6a14304175b870cb6813362
carisatinie/emotion_bias
/classifiers/masc/graphs.py
1,378
3.53125
4
from matplotlib import pyplot as plt import numpy as np ''' MASC Graphs ''' ''' Graphs the F1 scores of each feature set as a bar chart. Outputs 3 graphs: one for male, female, and both genders. Uses the results from running model on the test set after tuning on training and validation sets. ''' objects = ('Tukey', 'Acoustic', 'MFCC', 'MFCC+Ac', 'RF') x_pos = np.arange(len(objects)) # Male f1_male = [0.4308, 0.3701, .4948, .5109, .3548] plt.bar(x_pos, f1_male, align='center', alpha=0.5) plt.xticks(x_pos, objects) plt.ylabel("F1 score") plt.title("MASC Male F1 Scores on Different Feature Sets") plt.ylim((0, 0.55)) for i, v in enumerate(f1_male): plt.text(x_pos[i] - 0.25, v, str(v)) plt.show() # Female f1_female = [.4436, .3592, .4884, .5111, .3448] plt.bar(x_pos, f1_female, align='center', color=(0.6, 0, 1, 0.5)) plt.xticks(x_pos, objects) plt.ylabel("F1 score") plt.title("MASC Female F1 Scores on Different Feature Sets") plt.ylim((0, 0.55)) for i, v in enumerate(f1_female): plt.text(x_pos[i] - 0.25, v, str(v)) plt.show() # Both f1_both = [.4307, .3668, .4855, .4943, .3397] plt.bar(x_pos, f1_both, align='center', color=(0, 0.5, 0)) plt.xticks(x_pos, objects) plt.ylabel("F1 score") plt.title("MASC Both F1 Scores on Different Feature Sets") plt.ylim((0, 0.55)) for i, v in enumerate(f1_both): plt.text(x_pos[i] - 0.25, v, str(v)) plt.show()
e051aa47441e92302a3d848a6bbe28b63ae53ca3
szbrooks2017/holbertonschool-higher_level_programming
/0x06-python-classes/1-square.py
218
3.828125
4
#!/usr/bin/python3 """ a Square with size, private instance attriute size, no type/value""" class Square: """a class that creates a single attribute""" def __init__(self, size): self.__size = size
d6728ed091a933e18fd3315f1d8f185917883ca7
CoderPrabal/Datastructure
/anti_diagnol.py
457
3.640625
4
def solve(A): length_of_array = len(A) no_of_anti_diagnol = (2 * length_of_array) - (1) empty_lists = [[] for _ in range(no_of_anti_diagnol)] print(empty_lists) for i in range(0, length_of_array): for j in range(0, length_of_array): value = A[i][j] sum_index = i + j empty_lists[sum_index].append(value) print(empty_lists) A = [[1, 2, 3], [3, 4, 5], [7, 8, 9]] solve(A)
e89286410630a0a1abdb45a1c155d824db4e7731
itsjunqing/fit1008-introduction-to-computer-science
/source_code/dp/dp_fib.py
1,623
3.65625
4
# using normal recursive method def fib_normal(n): return fib_aux_normal(n) def fib_aux_normal(n): if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2) # using tail recursion where it passes the base case into the auxilary method def fib(n): return fib_aux(n, 0, 1) def fib_aux(n, before_last, last): if n == 0: return before_last else: return fib_aux(n-1, last, before_last+last) # using dynamic programming def dp_fib(n): memo = [0] * (n + 1) memo[0] = 0 memo[1] = 1 for i in range(2, n + 1): memo[i] = memo[i - 1] + memo[i - 2] return memo[n] def coins(coins): coins_value = [0] * (len(coins) + 1) coins_value[1] = coins[0] for i in range(2, len(coins)+1): coins_value[i] = max(coins_value[i-1], coins_value[i-2] + coins[i-1]) return coins_value[-1] # using normal recursive way def binomial(n, k): # assumes that k <= n so no checking is done # base case starts here, where k = 0 or k = n, like 3C0 = 3C3 = 1 if k == 0 or k == n: return 1 else: return binomial(n-1, k-1) + binomial(n-1, k) # using dp approach def dp_binomial(n, k): table = [0] * (n+1) for i in range(len(table)): table[i] = [0] * (k+1) for i in range(1, n+1): for j in range(k+1): # base case if i == j or j == 0: table[i][j] = 1 else: table[i][j] = table[i-1][j] + table[i-1][j-1] return table[n][k] if __name__ == '__main__': print(dp_fib(5)) print(fib(5)) print(fib_normal(5)) print(coins([7, 2, 10, 12, 5])) print(binomial(3, 1)) print(binomial(3, 2)) print(dp_binomial(3, 0)) print(dp_binomial(3, 1)) print(dp_binomial(3, 2)) print(dp_binomial(3, 3))
854845a12251ecd26f1b77b24e79c5ac979f2bd3
anaskhan28/Python-practice-codes
/Chapter 12/01_try.py
350
4.09375
4
while(True): print("Press q to Quit the match") a = input("Enter the number\n") if a == 'q': break try: print("Trying.....") a = int(a) if a > 6: print("Your number is greater than 6") except Exception as e: print(f"The value should be number: {e}") print("Thanks for playing")
5543387fdb324c11046c107d41b0fe8f81a4ab31
BuddhaRandom/yars-revenge
/ship.py
1,975
3.578125
4
#import pygame from asprite import ASprite from animated_facing_sprite import AnimatedFacingSprite import options class Ship(AnimatedFacingSprite): """The player's sprite ship Moves in eight directions with screen wraparound -- see move() docstring """ def __init__(self, sprite_sheet, height, width, delay, speed): """delay is the time (in frames) spent on each image sprite_sheet is the filename of the sprites height, width are the dimensions of the sprite """ AnimatedFacingSprite.__init__(self, sprite_sheet, height, width, delay, speed) def move(self, direction): """can't move off left or right edges and loops around top and bottom otherwise moves same as AnimatedFacingSprite """ AnimatedFacingSprite.move(self, direction) #if ship is off left or right edges, "nudge" back to the edge if self.rect.left < 0: self.rect.left = 0 if self.rect.right > options.width: self.rect.right = options.width #if ship is off top or bottom edges, teleport to opposite edge if self.rect.top < 0: self.rect.bottom = options.height if self.rect.bottom > options.height: self.rect.top = 0 class Bullet(ASprite): """The player's bullet Moves in a single direction until offscreen """ def __init__(self, sprite_filename, speed, position, direction): ASprite.__init__(self, sprite_filename, speed) self.rect.center = position self.direction = direction def update(self): ASprite.move(self, self.direction) if (self.rect.left < 0 or self.rect.top < 0 or self.rect.right > options.width or self.rect.bottom > options.height): self.kill()
032f542201f2bc8f61877290055e0f271cb932d1
giladmishne/bf
/spell_checker.py
1,498
3.78125
4
import re import sys from os.path import isfile from bf.bloom_filter import BloomFilter DEFAULT_WORD_LIST = '/usr/share/dict/words' # A simple application of the bloom filter: load a word list, store it in a filter, and spell-check # a different file against it. def tokenize(in_file): """Iterates over words in `in_file`. Returns continuous alphanumeric strings, lowercased.""" if not isfile(in_file): raise RuntimeError(f"Can't open {in_file}") with open(in_file) as fp: for line in fp: for word in re.sub(r'[^a-z0-9_]', ' ', line).split(): yield word.lower() def spellcheck(in_file, word_list_file): # TODO: consider first counting the number of words in the file, to better estimate the filter parameters. bf = BloomFilter(50000, 0.001) for word in tokenize(word_list_file): bf.add(word) for word in tokenize(in_file): if word not in bf: print(word) if __name__ == '__main__': if len(sys.argv) < 2: print(f"Usage: {sys.argv[0]} <file-to-spellcheck> [word-list] (default: {DEFAULT_WORD_LIST})") print("Both file-to-spellcheck and word-list are assumed case-insensitive, whitespace-delimited") print("Outputs to stdout every word in <file-to-spellcheck> that is not found in word-list, one word per line.") raise RuntimeError word_list_file = DEFAULT_WORD_LIST if len(sys.argv) < 3 else sys.argv[2] spellcheck(sys.argv[1], word_list_file)
10065cf452ddc6ef9d99bf9da8d8811f99bc03fe
DilyanTsenkov/SoftUni-Software-Engineering
/Python Fundamentals/Mid exams/01_Spring_Vacation_Trip.py
1,031
3.90625
4
days_trip = int(input()) budget = float(input()) group = int(input()) fuel_price_km = float(input()) food_expenses_person_day = float(input()) hotel_person_night = float(input()) hotel = group * hotel_person_night * days_trip if group > 10: hotel *= 0.75 food = group * food_expenses_person_day * days_trip total = hotel + food continue_the_trip = True for day in range(1, days_trip + 1): travel_distance = float(input()) fuel = travel_distance * fuel_price_km total += fuel if total > budget: continue_the_trip = False break if day % 3 == 0 or day % 5 == 0: total *= 1.4 if total > budget: continue_the_trip = False break if day % 7 == 0: total -= total / group difference = abs(budget-total) if continue_the_trip: print(f"You have reached the destination. You have {difference:.2f}$ budget left.") else: print(f"Not enough money to continue the trip. You need {difference:.2f}$ more.")
9642c099a7f4222e1315b3dbc8ae36915764c44a
zihuaweng/leetcode-solutions
/leetcode_python/1056.Confusing_Number.py
885
3.71875
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() # https://leetcode.com/problems/confusing-number/ class Solution: def confusingNumber(self, a: int) -> bool: src = a sub = {0: 0, 1: 1, 9: 6, 8: 8, 6: 9} b = 0 while a > 0: if a % 10 not in sub: return False b = b * 10 + sub[a % 10] a //= 10 return src != b class Solution: def confusingNumberII(self, n: int) -> int: sub = {0: 0, 1: 1, 9: 6, 8: 8, 6: 9} def dfs(num, flip_num, digit): res = 0 if num != flip_num: res += 1 for d, val in sub.items(): if 0 < num * 10 + d <= n: res += dfs(num * 10 + d, val * digit + flip_num, digit * 10) return res return dfs(0, 0, 1)
02d28f6b0677a66fd8466f7fe40f79cb651a7ea8
guilhermeaugusto9/100daysofpython
/Day 17/main.py
709
4.1875
4
class User: """User class""" def __init__(self, id=None, username=None): """Constructor to initialize attributes""" self.id = id self.username = username self.followers = 0 self.following = 0 def follow(self, user): self.following += 1 user.followers += 1 # Creating object without setting attributes user_1 = User() user_1.id = "001" user_1.username = "ashutoshkrris" print(user_1.id, user_1.username) # Creating object and setting attributes at the same time user_2 = User('002', 'ashutosh') print(user_2.id, user_2.username) user_1.follow(user_2) print(user_1.followers, user_1.following) print(user_2.followers, user_2.following)
1d31176ffb345a6444a1333e101bdc6f632ce322
Rxdxxn/Rezolvare-If-While-For
/RB2.py
126
3.796875
4
n=eval(input("introduceti un numar:")) s=0 y=1 for n in range(1, n+1): y*=n s+=y print("Suma este egala cu:", s)
317f9684750d001b48d1768b06f67652cf2ffb81
zhix9767/Leetcode
/code/Word Search.py
1,169
3.546875
4
class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if not self.preCheck(board, word): return False for i in range(len(board)): for j in range(len(board[0])): if self.dfs(i,j,board,word): return True return False def dfs(self, i, j, board, word): if len(word) == 0: return True if i >= len(board) or j >= len(board[0]) or i < 0 or j < 0 or board[i][j]!=word[0]: return False temp = board[i][j] board[i][j] = ' ' result = self.dfs(i+1,j,board,word[1:]) or self.dfs(i-1,j,board,word[1:]) or self.dfs(i,j-1,board,word[1:]) or self.dfs(i,j+1,board,word[1:]) board[i][j] = temp return result def preCheck(self,board,word): dic={} for i in word: dic[i]=dic.get(i,0)+1 for i in board: for j in i: if j in dic and dic[j]>0: dic[j]-=1 for i in dic.values(): if i>0: return False return True
3422db15e2995bf71ae47b5321c72f001b2a0f06
almacro/snippets
/python/libvirt/basic/using_getHostname.py
437
3.59375
4
''' Example 8. Using getHostname This example demonstrates the getHostname() method. This can be used to obtain the hostname of the virtualization host as returned by gethostname(). ''' import sys import libvirt uri = 'qemu:///system' conn = libvirt.open(uri) if conn is None: print(f"Failed to open connection to {uri}", file=sys.stderr) exit(1) host = conn.getHostname() print(f"Hostname: {host}") conn.close() exit(0)
6a92b02fcfa0df1a3030243c03582c0ca0100b58
c-machado/DataStructuresPython
/ArraySequences/ArrayExample.py
906
4.25
4
import copy student_name_list = ['Rene', 'Joseph', 'Janet', 'Jonas', 'Helen', 'Virginia'] # temp has a reference to the same element that exists on student_name_list temp = student_name_list[2:3] #print(temp) primes = [2, 3, 5, 7, 11, 13, 17, 19] # copy to reference the same objects of primes list temp = primes[3:6] # print(temp) # update the reference to a new object temp[2] = 15 # print(temp) # print(primes) # new list with copy the new elements temp_deep_copy = copy.deepcopy(primes) temp_deep_copy[2] = 88 print(temp_deep_copy) print(primes) # eight cells references to the same object counters = [0] * 8 print(counters) # it does not change the default value(0), it computes as a new integer counters[2] += 1 print(counters) # 'primes' is just receives references to the values on list 'extras' extras = [23, 29, 31] primes.extend(extras) print(primes) primes.append(99) print(primes)
f3762d4e767dffec3fbc715801250e7125a8c7e7
Felipe0042/mineracao-dados-complexos-unicamp
/INF-0617/TrabalhoFinal/ex1/reducer.py
788
4
4
#!/usr/bin/env python import sys import calendar cur_temp = -999 month_with_max = None city_with_max = None def get_month_name(month_number): return calendar.month_name[int(month_number)] def print_out(month_param, city_param): print("('%s', '%s')" % (get_month_name(month_param), city_param)) for line in sys.stdin: month, city, temperature = line.strip().split("\t") temperature = int(temperature) if month_with_max is not None and month_with_max != month: print_out(month_with_max, city_with_max) cur_temp = -999 if temperature > cur_temp: cur_temp = temperature month_with_max = month city_with_max = city # Print do ultimo registro if month_with_max is not None: print_out(month_with_max, city_with_max)
abb95c292e64c01df017b75abb825ca84687644b
ma7salem/python-fundamentals
/#8 user input/demp.py
217
3.75
4
x = int(input("Enter First Number")) y = int(input("Enter Secont Numper")) z = x + y print("the result:", z) ch = input("Enter a Char")[0] print("Your Char is", ch) val = eval(input("Enter an exper")) print(val)
6cae7b819c249cfac49373123fa74a81fc7cb008
vick-hub/week2
/problem8.py
396
4.0625
4
import os import sys import random def main(): t = random.randint(0, 9) y = int(input("Enter a number: ")) # we're to apply what we learned; this has not been introduced if y < t: print("The number is less than random number") else: print("The number is not less than random number") return os.EX_OK if __name__ == "__main__": sys.exit(main())
0093b1a1c510b4d364f28469a1568153b2c729cc
jay-trivedi/greyatomlib
/greyatomlib/descreptive_analysis/q03_pearson_correlation/build.py
541
3.546875
4
# Default Imports from greyatomlib import pandas as pd dataframe_1 = pd.read_csv('data/house_prices_multivariate.csv') house_price = dataframe_1.loc[:, 'SalePrice'] dataframe_2 = pd.read_csv('data/house_prices_copy.csv').loc[:, 'SalePrice'] weight_of_nasa_space_shuttle = dataframe_2.loc[:, 'SalePrice'] # Return the correlation value between the SalePrice column for the two loaded datasets def correlation(): '''Enter code here''' return dataframe_1.SalePrice.corr(dataframe_2.SalePrice, method='pearson') print(correlation())
5d83d9fae27793c4c90a6bc05b00b18044c429c0
backslash112/python-practices
/list_to_tree/list_to_tree_1.py
1,472
3.765625
4
# # 问题:将一个排序好的数组转化成一个搜索二叉树? # 思路:二叉树最好情况下是一棵平衡二叉树,所以,从已排序的数组的中间位置开始往两边取数据进行构建二叉树。 # 所以第一步是将排序好的数组转换顺序,从中间开始往外取数的顺序,例如,[1,2,3,4,5] -> [3,2,4,1,5] # 思路不对,正确思路查看 list_to_tree_3.py # import sys def getMiddleIndex(n): if n % 2 == 1: return int((n - 1) / 2) else: return int(n / 2) middleIndex = -1 prevIndex = -1 nextIndex = -1 b = False def getNextIndex(n): global middleIndex global prevCursorIndex global nextCursorIndex global b if middleIndex == -1: middleIndex = getMiddleIndex(n) prevCursorIndex = middleIndex nextCursorIndex = middleIndex return middleIndex else: b = not b if b: prevCursorIndex = prevCursorIndex - 1 return prevCursorIndex else: nextCursorIndex = nextCursorIndex + 1 return nextCursorIndex def list_to_treelist(myList): newList = [] n = len(myList) index = 1 for _ in range(0, n): item = myList[getNextIndex(n)] newList.append(item) return newList def main(): if __name__ == "__main__": myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] treeList = list_to_treelist(myList) print(treeList) main()
f58d44a0d57aa9292e65f8da3f3dbedc00788e56
Spiderjockey02/CodeSnippets-Python
/files/quick_sort.py
1,140
3.984375
4
#array declaration arr=[] n=int(input("Enter the array size: ")) #getting the array size #function to get user inputs def userinputs(arr): for i in range(n): v= int(input("Enter a number: "))#add the elements to the array arr.append(v) #function for partition def partition(arr,start,end): i=start-1#getting the index of the smallest element pivot=arr[end] #get an elemt to check for j in range(start,end): if arr[j]<=pivot: #if current element <=pivot i+=1 #increment the index of smallest element arr[i],arr[j]=arr[j],arr[i] #swap the elements #exchanging arr[i+1],arr[end]=arr[end],arr[i+1] return(i+1) #function for quicksort def quickSort(arr,start,end): if (start<end): #partition index q q=partition(arr,start,end) #sorting the elements left & right partition quickSort(arr,start,q-1) #left partition quickSort(arr,q+1,end)#right partition #----main prog--- #calling quick sort userinputs(arr) print("entered arraylist\n", arr) partition(arr,0,n-1) quickSort(arr,0,n-1) print("sorted arraylist\n", arr)
175a6b864a4d9b1e6dfe6680f8f5d2e87580000f
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/shodges/lesson09/cli_main.py
6,284
3.546875
4
#!/usr/bin/env python3 from donor_models import DonorCollection import atexit marmots_ledger = DonorCollection('marmots') def send_thank_you(): """ User interface allowing the user to: * Enter a donor - Special values: list to list all donors, quit to return to main menu * If the donor does not exist, the user is given the option to create it * If the donor exists or is created, the user is given the option to add a donation * If a previous donation exists for the donor, the formatted letter is printed """ while True: donorname = input('Please enter a donor name: ') if donorname == 'quit': break elif donorname == 'list': for item in marmots_ledger.donors: print(item) else: donor = donor_management_fetch(donorname) if donor is None: break while True: newdonation = input('Process new donation? (y/n) ') if newdonation == 'y': donor_management_process(donor.name) break elif newdonation == 'n': break try: print(marmots_ledger.donor(donor.name).format_letter(True)) except IndexError: print('{} has no donation history.\n'.format(donor.name)) break def print_report(): """ Print a report of all donors' names, donation totals, count of donations, and average gift. """ print('{:24} | {:10} | {:10} | {:12}'.format('Donor Name', 'Total Given', 'Num Gifts', 'Average Gift')) print('-'*68) tmp_report = marmots_ledger.generate_report() for item in tmp_report: print('{:24} ${total:10.2f} {count:10d} ${average:12.2f}'.format(item, **tmp_report[item])) print() def save_all_letters(): """ Save thank you letters for all donors who have a donation on file in the user's specified directory. """ results = marmots_ledger.save_letters( input('Please specify a directory to save letters in: ')) if results[0] == False: print('Error creating letter directory.') else: print(results[0]) for i, file in enumerate(results[1]): print('{}-- {}'.format(('`' if i == len(results[1]) - 1 else '|'), file.name)) if len(results[2]) > 0: print() print('Failed to save letters for:') for file in results[2]: print(' * {}'.format(file)) def donor_management(): """ User interface allowing the user to: * Enter a donor - Special values: list to list all donors, quit to return to main menu * View the user's donations quantity and totals * Allow the user to delete donor record or process a donation """ while True: donorname = input('Enter the name of the donor to manage: ') if donorname == 'quit': break elif donorname == 'list': for item in marmots_ledger.donors: print(item) else: donor = donor_management_fetch(donorname) if donor is None: break else: print() print('Donor record for: {}'.format(donor.name)) print('Number of Donations: {}'.format(donor.count)) print('Total Donations: ${:.2f}'.format(donor.donations)) print() print("""Actions: 1 Delete Donor Record 2 Process Donation Enter anything else to return to main menu. """) option = input('Please enter an option: ') donor_management_dispatch = {1: donor_management_del, 2: donor_management_process} try: donor_management_dispatch.get(int(option))(donor.name) except (TypeError, ValueError): # This will catch all manner of bad things, but we always want to pass # e.g., non-called out options, donor_management_process bad input, etc. pass break def donor_management_del(donor): """ Delete the specified user from the DonorCollection class and print confirmation. """ marmots_ledger.del_donor(donor) print('Deleted donor {}\n'.format(donor)) def donor_management_process(donor): """ Prompt the user for a donation amount and attempt to process. Re-raise an exception if the donation is invalid; calling methods are expected to catch this. This is passed through as the implementing method may have cleanup to perform. """ amount = input('Please enter a donation amount: ') try: marmots_ledger.donor(donor).process(amount) print('Recorded donation of {}\n'.format(amount)) except ValueError: print('Invalid donation amount {}\n'.format(amount)) # re-raise the exception so that calling methods can clean up if necessary raise def donor_management_fetch(donorname): """ Return donorname's Donor object. If donorname is not in the database, prompt the user to create it; if successfully created, return the object. Else return None. """ try: return marmots_ledger.donor(donorname) except KeyError: while True: create = input('Donor {} does not exist. Create it? (y/n) '.format(donorname)) if create == 'n': return None elif create == 'y': marmots_ledger.add_donor(donorname) return marmots_ledger.donor(donorname) if __name__ == '__main__': atexit.register(marmots_ledger.db_close) menu_dispatch = {1: send_thank_you, 2: print_report, 3:save_all_letters, 4: donor_management, 5: quit} while True: print("""Mailroom -- Main Menu Options: 1 Send a Thank You 2 Generate a Report 3 Send letters to all donors 4 Donor Management 5 Quit """) option = input('Please select an option (1, 2, 3, 4, 5): ') try: menu_dispatch.get(int(option))() except (TypeError, ValueError): print('Invalid option {}\n'.format(option))
3961cf8fa94638c66a1df37308ee6330f449480a
luisalejandrojaramillo/NxU_Fundamentos-de-Programaci-n-en-Python
/2. Tipos de Datos e Instrucciones Básicas/Leccion4/Ejercicio1.py
407
3.84375
4
from datetime import datetime def main(): nombreC=input("Nombre de la Criptomoneda: ") cantCripto=float(input("Cantidad acumulada de la Criptomoneda: ")) cotizacion=float(input("Cotización por US$ del día de la Criptomoneda: ")) fecha = datetime.now() print("La fecha completa y hora en la que obtuvo la información fue:"+fecha.strftime("%A, %d de %B de %Y a las %I:%M:%S%p")) main()
485c5b87eda60bdc39eb791ae3c1a0154ee55ae4
UjjwalJain02/Turtle-Race
/main.py
954
4.1875
4
import random from turtle import Turtle, Screen screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make your bet", prompt="Which turtle win the race? Select the color:") print(f"You made a bet on {user_bet} color turtle") is_race_on = False turtles = [] colors = ["red", "orange", "yellow", "green", "blue", "purple"] for i in range(0, 6): tim = Turtle(shape="turtle") tim.penup() tim.color(colors[i]) tim.goto(x=-230, y=(2.5 - i) * 50) turtles.append(tim) if user_bet: is_race_on = True while is_race_on: for turtle in turtles: if turtle.xcor() > 230: is_race_on = False if turtle.pencolor() == user_bet: print(f"You won! {turtle.pencolor()} win the race.") else: print(f"You lost! {turtle.pencolor()} win the race.") random_distance = random.randint(1, 10) turtle.forward(random_distance)
f031b9e0bcdadcea8170aaee244eae3f96118de4
georgewashingturd/leetcode
/No_493_Reverse_Pairs.py
3,379
4.34375
4
############################################################################### # 493. Reverse Pairs ############################################################################### # this is similar to count number smaller than self problem No 315 however # when we do the merge we want to separate the counting of smaller elements # from the right sub array and the actualy merging of the arrays themselves # because of the multiplicative factor of 2 if you merge and count at the same time # it becomes very confusing very fast not to mention that you'll get the wrong answer # this is because you want to count by multiplying the right sub list by 2 but you # still want to merge the usual way without the factor of 2 why? because think about it # say you have two sub arrays you want to merge, you want each sub array to be sorted # if it's sorted by involving the factor of 2 you'll get something weird for example # [2] and [1,3] you'll get [2 ,1, 3] as a merged result because you multiply the right sub list by 2 # during the merge comparison and when you go up in the recursion stacks this will cause all sorts of # weird problems # and it turns out that in python instead of merging it manually calling the sort function is a lot faster # around 38% faster class Solution(object): def merge(self, left, right): count = 0 # ls is left start and le is left end ls = 0 le = len(left) # rd is right start and re is right end rs = 0 re = len(right) # first we count and then we merge while (ls < le and rs < re): if (left[ls] <= 2*right[rs]): self.d += count ls += 1 else: count += 1 rs += 1 self.d += (le - ls)*count # it's much faster to just vcall the sorted function # now we merge # ls is left start and le is left end #ls = 0 #le = len(left) # rd is right start and re is right end #rs = 0 #re = len(right) #t = [] #while (ls < le and rs < re): # if (left[ls] <= right[rs]): # t.append(left[ls]) # ls += 1 # else: # t.append(right[rs]) # rs += 1 #t += left[ls:] + right[rs:] t = sorted(left + right) return t def mergeSort(self, nums, st, ed): if (ed - st <= 1): return nums[st:ed] mid = (st + ed) >> 1 left = self.mergeSort(nums, st, mid) right = self.mergeSort(nums, mid, ed) return self.merge(left, right) def reversePairs(self, nums): """ :type nums: List[int] :rtype: int """ # this is how you time python execution, it is only accurate to roughly 10 ms #import time #start_time = time.time() # we don't need a dictionary here because we a re not keeping track the number smaller for each # number we are just interested in the total count self.d = 0 self.mergeSort(nums, 0, len(nums)) #print("--- %s seconds ---" % (time.time() - start_time)) return self.d
0715d659e82909f712004a997efcce2450fb9424
rohitrnath/EPAi3
/Session-11-Iterators/polygon_sequence.py
1,536
3.8125
4
from polygon import Polygon class Polygon_sequence: def __init__( self, largest_num_edges, circumradius): if largest_num_edges < 3: raise ValueError("Polygon require atleast 3 or more edges/vertices!") self.largest_num_edges = largest_num_edges self.circumradius = circumradius self.sequence = [ Polygon( num_edges, self.circumradius) for num_edges in range( 3, self.largest_num_edges+1)] def __repr__( self) -> str: return f'Polygon sequence< number of polygons:{self.largest_num_edges-2}, largest polygon edges:{self.largest_num_edges}, common circumradius:{self.circumradius} >' def __len__( self): return self.largest_num_edges-2 def __getitem__( self, vertex): if isinstance( vertex, int): if vertex < 3 or vertex > self.largest_num_edges: raise IndexError("Vertex index is out of sequence") else: return self.sequence[ vertex] else: start, stop, step = vertex.indices(self.largest_num_edges) rng = range( start, stop, step) return [ self.sequence[i] for i in rng] @property def max_efficiency(self): area_perimeter_ratio = [ p.area/p.perimeter for p in self.sequence] max_efficient = max(area_perimeter_ratio) vertex = area_perimeter_ratio.index(max_efficient)+3 return f'Maximum efficint polygon having {vertex} edges and area to perimeter ratio is {max_efficient}'
eef335dccf1ab2a8156c6996032fe13cf30e0dc7
zspatter/network-simulation
/network_simulator/BloodType.py
3,116
3.5625
4
from __future__ import annotations from network_simulator.compatibility_markers import BloodTypeLetter, BloodTypePolarity class BloodType: """ A class representing a given blood type. Possible blood types: O-, O+, A-, A+, B-, B+, AB-, AB+ """ def __init__(self, blood_type_letter: BloodTypeLetter, blood_type_polarity: BloodTypePolarity) -> None: self.blood_type_letter: BloodTypeLetter = blood_type_letter self.blood_type_polarity: BloodTypePolarity = blood_type_polarity def is_compatible_donor(self, blood_type: BloodType) -> bool: """ Determines if this blood type can donate to the parameter's blood type. This simply calls the is_compatible_recipient function on the parameter and passes itself as an argument. :param BloodType blood_type: blood type of potential recipient :return: bool indicating whether self can donate to the passed BloodType """ return blood_type.is_compatible_recipient(self) def is_compatible_recipient(self, blood_type: BloodType) -> bool: """ Determines if this blood type can receive a donation from the parameter's blood type using bitwise operations :param BloodTyp blood_type: blood type of potential donor :return: bool indicating whether self can receive a donation from the passed BloodType """ return ((self.blood_type_letter.value | blood_type.blood_type_letter.value) == self.blood_type_letter.value) \ and self.blood_type_polarity.value >= blood_type.blood_type_polarity.value def __str__(self) -> str: """ Builds a string representing blood type (ex: 'AB+') :return: str representing blood type """ polarity = '' if self.blood_type_polarity.value == 0: polarity = '-' elif self.blood_type_polarity.value == 1: polarity = '+' return f'{self.blood_type_letter.name}{polarity}' def __eq__(self, other) -> bool: """ Rich comparison returns true iff all attributes are equal :param BloodType other: other object to compare :return: bool indicating if the objects are equivalent """ if isinstance(other, BloodType): return self.blood_type_letter.value is other.blood_type_letter.value \ and self.blood_type_polarity.value is other.blood_type_polarity.value return NotImplemented def __ne__(self, other) -> bool: """ Rich comparison returns true if any of the attributes differ :param BloodType other: other object to compare :return: bool indicating if the objects are not equivalent """ if isinstance(other, BloodType): return not (self.blood_type_letter.value is other.blood_type_letter.value and self.blood_type_polarity.value is other.blood_type_polarity.value) return NotImplemented
22167fb4feba0501a29c0f11af5e7d3472f46ffa
MapleStory-Archive/maplestory2_autofarmer
/Keys.py
2,249
3.671875
4
import time import C #Wait Function is for the beginning of the program def Wait(timeIn): time.sleep(timeIn) def upLeft(timeIn): C.PressKey(0xC8) C.PressKey(0xCB) time.sleep(timeIn) C.ReleaseKey(0xC8) C.ReleaseKey(0xCB) time.sleep(0.1) def upRight(timeIn): C.PressKey(0xC8) C.PressKey(0xCD) time.sleep(timeIn) C.ReleaseKey(0xC8) C.ReleaseKey(0xCD) time.sleep(0.1) def downLeft(timeIn): C.PressKey(0xD0) C.PressKey(0xCB) time.sleep(timeIn) C.ReleaseKey(0xD0) C.ReleaseKey(0xCB) time.sleep(0.1) def downRight(timeIn): C.PressKey(0xD0) C.PressKey(0xCD) time.sleep(timeIn) C.ReleaseKey(0xD0) C.ReleaseKey(0xCD) time.sleep(0.1) def Up(timeIn): C.PressKey(0xC8) time.sleep(timeIn) C.ReleaseKey(0xC8) time.sleep(0.1) def Down(timeIn): C.PressKey(0xD0) time.sleep(timeIn) C.ReleaseKey(0xD0) time.sleep(0.1) def Right(timeIn): C.PressKey(0xCD) time.sleep(timeIn) C.ReleaseKey(0xCD) time.sleep(0.1) def Left(timeIn): C.PressKey(0xCB) time.sleep(timeIn) C.ReleaseKey(0xCB) time.sleep(0.1) def jumpUpRight(timeIn): C.PressKey(0x2E)#Key: c time.sleep(0.15) C.ReleaseKey(0x2E) time.sleep(0.1) C.PressKey(0xC8)#Up C.PressKey(0xCD)#Right time.sleep(timeIn) C.ReleaseKey(0xC8) C.ReleaseKey(0xCD) time.sleep(0.1) def jumpUpLeft(timeIn): C.PressKey(0x2E)#Key: c time.sleep(0.15) C.ReleaseKey(0x2E) time.sleep(0.1) C.PressKey(0xC8)#Up C.PressKey(0xCB)#Left time.sleep(timeIn) C.ReleaseKey(0xC8) C.ReleaseKey(0xCB) time.sleep(0.1) def jumpDownLeft(timeIn): C.PressKey(0x2E)#Key: c time.sleep(0.15) C.ReleaseKey(0x2E) time.sleep(0.1) C.PressKey(0xD0)#Down C.PressKey(0xCB)#Left time.sleep(timeIn) C.ReleaseKey(0xD0) C.ReleaseKey(0xCB) time.sleep(0.1) def Spacebar(timeIn): C.PressKey(0x39) time.sleep(timeIn) C.ReleaseKey(0x39) time.sleep(3) def Enter(timeIn): C.PressKey(0x1C) time.sleep(timeIn) C.ReleaseKey(0x1C) time.sleep(0.1) def keyT(timeIn): C.PressKey(0x14) time.sleep(timeIn) C.ReleaseKey(0x14) time.sleep(0.1)
551c60d9afc09af7f738e0165717d7cfd703a00e
CobaltGoldCS/loginSystem
/Login.py
2,358
4.03125
4
from pathlib import Path from TestText import * print('Welcome to my super secret password holder') User = input('First, my program has to make sure its me: ' ) filepath = "C:\\Users\\dylan\\Python\\Login system\\" PassWD = input('Next, the password of course, this is the password to end all passwords: ') Password = input('Reenter password: ') filename = User + '.txt' filenameText = User +'1.txt' filenamePath = filepath+filename fileTextPath = filepath+filenameText def Login(): txt = Path(filenamePath).read_text() #Password Checker for passwords that are too short if Password != txt: print('Wrong password there buddy') return 0 if PassWD == Password: #Defines full text print('Getting variable...\n\n\n') myfile = open(filenamePath, 'r') for line in myfile: #If the password (PassWD) matches the line in myFile, then activate the text file holding the passwords if (PassWD) in line: myfile.close print('Activating password file...\n\n\n') textFile = open(fileTextPath, 'r') print(textFile.read()) textFile.close return 0 else: print('failure') myfile.close return 0 def reg(): choice = input("Do you really want to create a new file[y/n]: ") if choice == 'y': newFile = open(filenameText, 'w+') passwordFile = open(filename, 'w+') passwordFile.write(Password) passwordFile.close newFile.close elif choice == 'n': return 0 def add(): #Lets you look at the file content appendFile = open(fileTextPath, 'r') print(appendFile.read()) appendFile.close #Then lets you append whatever you want to it appendFile = open(fileTextPath, 'a') add = input("Add whatever you want to the file: ") #Final check if you messed up choice = input("Are you sure you want to add this[y/n]: ") if choice == "y": appendFile.append(add) appendFile.close elif choice == "n": appendFile.close return 0 #Choice at start of program loginish = input('Are you logging in[a], registering?[b], or adding to a file[c]?: ') if loginish == "a": Login() elif loginish == "b": reg() elif loginish == "c": add()
ceb0c1fbe584fa90420d89086f7d0f1327fd32e5
freddimsc/geekbrains_python
/lesson2/hw_2_5.py
773
4.21875
4
#. Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. # У пользователя необходимо запрашивать новый элемент рейтинга. # Если в рейтинге существуют элементы с одинаковыми значениями, # то новый элемент с тем же значением должен разместиться после них. my_list = [7, 5, 3, 3, 2] number = int(input("Ведите новый элемент рейтинга: ")) for i in my_list: my_list.append(number) my_list = sorted(my_list, reverse=True) break print(my_list)
6880f432aaf73ab74b874bf7e71ee06a10f80da1
kayjayk/algorithm-solution
/Exam3009.py
441
3.6875
4
from collections import defaultdict def filter_only_one(n_list): n_dic = defaultdict(int) for i in n_list: n_dic[i] += 1 for key in n_dic.keys(): if n_dic[key] == 1: only_one = key break return only_one x_list = [] y_list = [] for i in range(3): x, y = map(int, input().split()) x_list.append(x) y_list.append(y) print(filter_only_one(x_list), filter_only_one(y_list))
8e1da71537181ff8234592f8bc747c904326d8d3
Maaaatts/Pandas
/Problem_1.py
345
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 22:53:42 2019 @author: Matthew Rabanes """ import pandas as pd cars = pd.read_csv('cars.csv') first = cars[0:5] last = cars[27:32] print('The first five cars are: \n \n' +str(first)) print('--------------------------------------------') print('The last five cars are: \n' +str(last))
af606ed6908eb3af22d7547a8cd0a40dbd51d381
PatNicholson/DeepUno
/objects.py
7,401
3.90625
4
""" This file defines all the major classes that will be used: Card: represents an UNO card in the deck Deck: represents a list of cards Player: treated as an abstract or super class that each AI player will implement Game: represents the state of a single game (the one that is currently being played) Weights on cards for scoring: Card : weight for score 0 : 0 1 : 1 2 : 2 3 : 3 4 : 4 5 : 5 6 : 6 7 : 7 8 : 8 9 : 9 skip/reverse : 10 draw 2 : 12 wild : 14 wild draw 4 : 16 """ import numpy as np import random random.seed() """ Represents current state of the game that is being played. """ class UNO_Game: def __init__(self, new_deck, player1 = None, player2 = None): self.player1 = player1 self.player2 = player2 self.turn = player1 self.deck = new_deck self.recent_played_card = self.deck.cards.pop(0) i = 1 while self.recent_played_card.flag >= 4: self.deck.add(self.recent_played_card) self.recent_played_card = self.deck.cards.pop(i) i += 1 self.discard_pile = Deck(0) self.discard_pile.add(self.recent_played_card) self.wild_color = None def uno(self,player): if player.hand.size_of_deck == 1: return True return False def game_over(self,player): if len(player.hand.cards) == 0: return True return False """ Represents a player """ class Player: def __init__(self, game, name): self.name = name self.game = game self.hand = Deck(0) for i in range(7): self.draw() def draw(self): card_drawn = self.game.deck.draw() self.hand.add(card_drawn) if self.game.deck.empty(): self.game.recent_played_card = self.game.discard_pile.draw() self.game.discard_pile.shuffle() self.game.deck = self.game.discard_pile self.game.discard_pile = Deck(0) self.game.discard_pile.add(self.game.recent_played_card) return card_drawn def discard(self, card): self.hand.discard(card) self.game.recent_played_card = card self.game.discard_pile.add(card) return card """ 0 if discard, 1 if draw""" def discard_or_draw(self): raise NotImplementedError("discard_or_draw not implemented") """ returns 3 values: - 0 if discard, 1 if draw - the discarded or drawn card - the chosen color if a wildcard is played, 'None' otherwise """ def play(self): raise NotImplementedError("play not implemented") def possible_card(self): for card in self.hand.cards: if (card.flag >= 4): return True if (card.flag >= 1) and (card.flag == self.game.recent_played_card.flag): return True if (card.value == self.game.recent_played_card.value) and (card.flag == 0): return True if card.color == self.game.recent_played_card.color: return True if card.color == self.game.wild_color: return True return False def all_possible_cards(self): all_possible_cards = Deck(0) for card in self.hand.cards: if (card.flag >= 4): all_possible_cards.add(card) elif (card.flag >= 1) and (card.flag == self.game.recent_played_card.flag): all_possible_cards.add(card) elif (card.value == self.game.recent_played_card.value) and (card.flag == 0): all_possible_cards.add(card) elif card.color == self.game.recent_played_card.color: all_possible_cards.add(card) elif card.color == self.game.wild_color: all_possible_cards.add(card) return all_possible_cards.cards """ Represents an UNO card. value: numerical value of a regular (non-special or non-wild) card between 0 and 9 for regular cards; 10 for non-regular color: color of a non-wild card red, blue, green, yellow, or None (if wild) flag: indicates if a card is special or wild 0: regular 1: reverse 2: skip 3: draw 2 4: wild 5: wild draw 4 """ class Card: def __init__(self, value, color, flag): self.value = value self.color = color self.flag = flag self.index = None def __eq__(self, other): if (self.value == other.value) and (self.color == other.color) and (self.flag == other.flag): return True else: return False def __ne__(self, other): return not self.__eq__(other) def __str__(self): if self.color is not None: return 'Card(' + str(self.value) + ',' + self.color + ',' + str(self.flag) + ')' else: return 'Card(' + str(self.value) + ',wild,' + str(self.flag) + ')' """Represents a list of cards. The first card in the list represents the top of the deck, or the card that can be drawn""" class Deck: def __init__(self, deck_size = 108): self.cards = [] colors = ["red", "blue", "green", "yellow"] nums = range(1,10) if deck_size == 108: for color in colors: self.cards.append(Card(0,color,0)) for n in nums: self.cards.append((Card(n,color,0))) self.cards.append((Card(n,color,0))) self.cards.append(Card(10,color,1)) self.cards.append(Card(10,color,1)) self.cards.append(Card(10,color,2)) self.cards.append(Card(10,color,2)) self.cards.append(Card(10,color,3)) self.cards.append(Card(10,color,3)) for i in range(4): self.cards.append(Card(10,None,4)) self.cards.append(Card(10,None,5)) self.shuffle() for ind, card in enumerate(self.cards): card.index = ind self.weights = self.set_weights() def set_weights(self): # set the weights for the cards in deck based on the score # index of weights corresponds to the weights = np.zeros(len(self.cards)) for c in self.cards: if c.flag == 5: weights[c.index] = 16 elif c.flag == 4: weights[c.index] = 14 elif c.flag == 3: weights[c.index] = 12 elif c.flag == 1 or c.flag == 2: weights[c.index] = 10 elif c.flag == 0: weights[c.index] = c.value return weights def get_weights(self): return self.weights def shuffle(self): random.shuffle(self.cards) def size_of_deck(self): return len(self.cards) def draw(self): return self.cards.pop(0) def add(self,card): self.cards = [card] + self.cards def empty(self): if len(self.cards) == 0: return True return False def discard(self, card): if card in self.cards: self.cards.remove(card) else: for c in self.cards: if (c.value==card.value) and (c.flag==card.flag) and (c.color==card.color): self.cards.remove(c) break Deck()
288b4250c17ff8b85234181cbefb326163b8a385
ctsan/powersets
/powerset.py
379
3.625
4
#!/usr/bin/env python from itertools import combinations from sys import argv def set_printer(name,s): l = list(s) print(name, " = " ,sorted(l, key=len)) initial_set = set(argv[1:]) final_set = set() for i in range( len(initial_set) + 1 ): final_set |= set ( combinations( initial_set, i) ) set_printer("S",initial_set) set_printer("P(S)",final_set)
4f35816e4bab38ff4d161d9edb9877c00b53f162
lajanugen/errata_analysis_eecs573
/src/text_processing.py
2,475
3.765625
4
''' This file will include all general text processing functions. ''' import csv import re import string import sys from nltk import sent_tokenize from nltk.tokenize import word_tokenize import errata ''' Take in a string and split into sentences; strip all non-ascii characters and lower-case all text; then tokenize into words. @args text - string of text sent_tokenize - if True, try to split the text into sentences before tokenizing into words if False, just split the text into words @return tokenized_sents - list of lists of words (i.e. [['this', 'is', 'first', 'sentence'], ['this', is', 'second', 'sentence']]) ''' def process_text(text, sent_tokenize=True): text = re.sub(r'[^\x00-\x7f]',r'', text) if sent_tokenize: sents = sent_tokenize(text) tokenized_sents = [word_tokenize(sent.encode('ascii', 'ignore').lower()) for sent in sents] tokenized_sents = [sent for sent in tokenized_sents if sent != []] else: tokenized_sents = word_tokenize(text.encode('ascii', 'ignore').lower()) return tokenized_sents ''' Take in a file and extract the text from the specified fields. @args filename - filename of the tsv/csv file fields - list of the names of the columns that text should be extracted from delimiter - delimiter character of the file @return tokenized_sents - list of lists of words (i.e. [['this', 'is', 'first', 'sentence'], ['this', is', 'second', 'sentence']]) ''' def extract_text(filename, fields=['Details'], delimiter='\t'): all_text = [] with open(filename, 'rb') as infile: reader = csv.DictReader(infile, delimiter=delimiter) for row in reader: all_text.extend([row[field] for field in fields if field in row]) tokenized_sents = [] for text in all_text: tokenized_sents.extend(process_text(text)) return tokenized_sents def extract_errata(filename, delimiter='\t'): seen_failures = {} all_errata = [] with open(filename, 'rb') as infile: reader = csv.DictReader(infile, delimiter=delimiter) for row in reader: curr_error = errata.Error(row) curr_failure = curr_error.get_field('Failure') if curr_failure in seen_failures: continue else: seen_failures[curr_failure] = True all_errata.append(curr_error) return all_errata if __name__ == '__main__': filename = sys.argv[1] #print extract_text(filename, ['Details'])[:10] print [error.fields for error in extract_errata(filename)[:10]]
880fade70977ebf10bc4498eb9252f83f0e95bed
pngisnotgif/python
/Core Python Programming/6-10.py
478
3.8125
4
# 6-10 def capital_reverse(s): new_s = '' for i in s: if i.islower() : new_s += i.upper() elif i.isupper() : new_s += i.lower() else: new_s += i print s,'==>',new_s def capital_reverse_v2(s): print s,'==>',s.swapcase() if __name__=='__main__': testcases = ['Mr.Ed', 'mR.eD', 'abc', '', ' ', 'aBc', 'A', 'AB'] for i in testcases: capital_reverse(i) capital_reverse_v2(i)
5e33078802633b25084a29a92fe7fb080bb9ecd6
cuiboautotest/learnpython3
/算法练习/面试/数字前后加符号.py
158
3.515625
4
s='Jkdi234klowe90a3' s1='' for i in s: if i.isdigit(): s1+='*'+ i +'*' else: s1+=i print(s1) s2=s1.replace('**','') print(s2)
bd4c59d3c0f6e22833f64f99b096c7bc29792fc0
IvanChavez1997/Modelos-y-Simulaciones
/Movimiento Ondulatorio.py
1,373
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 14 17:58:54 2020 @author: Ivan """ import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation ####### SIMULACIÓN DE MOVIMIENTO ONDULATORIO #### ### CREAMOS LA GRAFICA CON TRES SUBGRAFICAS### fig = plt.figure(figsize=(10,10)) ax1 = fig.add_subplot(311,autoscale_on=True,title="Q=Asen(wt)") ax2 = fig.add_subplot(312,autoscale_on=True,title="Q=Asen(kx)") ax3 = fig.add_subplot(313,autoscale_on=True,title="Q=Asen(kx+wt)") ### INGRESAMOS LOS DATOS DEL MOVIMIENTO ## #AMPLITUD A= 5 #FRECUENCIA ANGULAR w= 5 #NUMERO DE ONDA k= 3 ### GENERAMOS LOS ARREGLOS DETIEMPO Y POSICION ## t= np.arange(0, 2*np.pi, 0.01) x= np.arange(0, 2*np.pi, 0.01) ### GENERAMOS LAS TRES LINEAS QUE DESCRIBEN UN CASO DIFERENTE ### ### K=0 line1, = ax1.plot(t, A*np.sin(w*t)) ### w=0 line2, = ax2.plot(x, A*np.sin(k*x)) ### k Y w DIFERENTE DE CERO line3, = ax3.plot(t, A*np.sin(w*t+k*t)) ###DEFINIMOS NUESTRA FUNCIÓN PARA LOS FRAMES ### def animate(i): line1.set_ydata(A*np.sin(w*t+i/50)) # update the data. line2.set_ydata(A*np.sin(k*x+i/50)) line3.set_ydata(A*np.sin(w*t+k*t+i/50)) return line1, line2 , line3 ### CREAMOS LA ANIMACIÓN ### ani = animation.FuncAnimation( fig, animate, interval=10, blit=bool, repeat_delay=25) plt.show()
2fe4935a8b2ba511e7c26177fd3e6fbbc4694b2f
dspolyar/Main
/Library_CopyFunction.py
4,263
4.125
4
""" SOURCE: http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python **Cannot find the official documentation for `types.FunctionType` Must have named arguments somehwere, and cannot find with google DESCRIPTION: Makes a deep copy of a function in python return a function with same code, globals, defaults, closure, and name (or provide a new name) #STILL DOES NOT TRUELY DEEP COPY A FUNCTION # -> THE DEFAULT ARGS DON'T GET COPIED OVER # -> THEY REMAIN REFERENCES/POINTERS ARGS: Function The function to copy NewName The new name for the function's copy NewDefaults Description: New default values for the function arguments This enables copying some data to private scope for the new function copy Especially useful in parallel processing type python `None` OR python `tuple` OR `Type_HashTable` allowed if `CheckArguments==True` RETURNS: FunctionCopy """ import types import copy import pprint import inspect import Type_HashTable def Main( Function = None, NewName = None, NewDefaults = None, CheckArguments = True, PrintExtra = False ): if (CheckArguments): ArgumentErrorMessage = "" if (type(NewDefaults) == type(None)): pass elif ( type(NewDefaults) is tuple): pass elif( Type_HashTable.Main(NewDefaults) ): #Cast the dictionary values into a tuple FunctionArgumentInformation = inspect.getargspec(Function) FunctionArgumentNamesInOrder = FunctionArgumentInformation.args if (PrintExtra): print 'FunctionArgumentNamesInOrder', FunctionArgumentNamesInOrder #TODO: Hybridizaion of any partial NewDefaults, with the original function defaults #FunctionDefaultValues = FunctionArgumentInformation.defaults #Tuple starts from the first Named Argument #print 'FunctionDefaultValues', FunctionDefaultValues #Generate a list of new default values in order: NewDefaultsValueList = [] for FunctionArgumentName in FunctionArgumentNamesInOrder: NewDefaultsValueList.append(NewDefaults[FunctionArgumentName]) NewDefaults = copy.deepcopy( tuple(NewDefaultsValueList) ) if (PrintExtra): print 'NewDefaults', NewDefaults #TODO: We will ignore **kwards, and *args for now #FunctionSpecialArgsName = FunctionArgumentNamesInOrder[1] #print 'FunctionSpecialArgsName', FunctionSpecialArgsName #FunctionSpecialKwarsName = FunctionArgumentNamesInOrder[2] #print 'FunctionSpecialKwarsName', FunctionSpecialKwarsName else: ArgumentErrorMessage += 'NewDefaults must be of type `None`, `tuple`, or `Type_HashTable`' if (len(ArgumentErrorMessage) > 0 ): if(PrintExtra): print "ArgumentErrorMessage:\n", ArgumentErrorMessage raise Exception(ArgumentErrorMessage) if (PrintExtra): #All function property information: FunctionProperties = dir(Function) print 'FunctionProperties' pprint.pprint(FunctionProperties) #Create a new function by invoking the python function `types.FunctionType` # Documentation for this function is thus unfound # TODO: Find the documentation for this FunctionCopy = types.FunctionType( Function.__code__, Function.__globals__, copy.deepcopy(NewName) or Function.__name__, NewDefaults or Function.__defaults__ , Function.__closure__ ) # in case Function was given attrs # Note: # * The original version of this dict copy was a shallow copy): # * It is unknown if using the copy.deepcopy method fixes this to be a true deep copy # TODO: find out the deep copy `Goodness` of this line of code FunctionCopy.__dict__.update(copy.deepcopy( Function.__dict__) ) return FunctionCopy
bcbaa0f4ed5a8be1b395d313c3cd7dc67803c7ee
miAndreev/Programming101-2
/w0/f6-count_cars_words_or_lines/solution.py
794
3.90625
4
from sys import argv, exit def count_chars(file_name): file = open(file_name, 'r') content = file.read() words = content.split(" ") count = 0 for el in content: count = count + len(el) file.close() return count def count_words(file_name): file = open(file_name, 'r') count = len(file.read().split()) file.close() return count def count_lines(file_name): file = open(file_name, 'r') content = file.read() num_lines = content.count("\n") + 1 file.close() return num_lines def main(): if argv[1] == 'chars': print(count_chars(argv[2])) elif argv[1] == 'words': print(count_words(argv[2])) elif argv[1] == 'lines': print(count_lines(argv[2])) if __name__ == '__main__': main()
986b6776f87a895044b3acd0ea1233eabfb3f3a6
agatanyc/RC
/algorithms_DS/python/collatz_2.py
913
4.3125
4
!/usr/bin/env python # The following iterative sequence is defined for the set of positive integers: # # n -> n/2 (n is even) # n -> 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 # # It can be seen that this sequence (starting at 13 and finishing at 1) # contains 10 terms. Although it has not been proved yet (Collatz Problem), it # is thought that all starting numbers finish at 1. # # Which starting number, under one million, produces the longest chain? # # NOTE: Once the chain starts the terms are allowed to go above one million. def collatz_len(n): """Returns the length of the Collatz chain from `n` to 1.""" r = 1 while n != 1: r += 1 n = n / 2 if n % 2 == 0 else 3 * n + 1 return r if __name__ == '__main__': print max(range(1, 100), key=collatz_len)
c04e861e8c74d785041168b3f795fe5239d3eba7
zhujunzhujunzhu/Python001-class01
/week04/practice/demo1.py
3,181
3.9375
4
''' https://blog.csdn.net/qq_38251616/article/details/84752080 1 写csv文件 2 读csv文件 3 DataFrame 遍历 合并 4 行 查找 删除 5 重复项 6 元素 7 排序 ''' import os import pandas as pd ''' 写文件: 关于这里可以看到的是 任意多组列表 可以利用字典映射索引 可以设置mode 是否加上索引 可以添加上分隔符sep mode = a 代表不覆盖原有的内容的 practice/csv/test0.csv 当写路径时 如果csv不存在时会报错 ''' # a = [1, 2, 3] # b = [4, 5, 6] # data_dict = {"a_name": a, "b_name": b} # df = pd.DataFrame(data_dict, columns=['a_name', "b_name"]) # df.to_csv('practice/csv/test0.csv', index=True) # df.to_csv('practice/csv/test1.csv', index=False, sep="|") # df.to_csv('practice/csv/test2.csv', mode="a", index=False, sep="#") ''' 读csv文件 __file__ 这个代表的是当前目录 但是需要注意在交互模式下不可以的 os.path.join() 进行地址的拼接 os.path.dirname(__file__) 当前文件所在的目录 pd.read_csv open(file_path,encoding="utf-8") 数据的遍历 data.iterrows iterrows是行进行迭代的生成器 for column, row in data.iterrows() 关于python中的这一段 column row 这两个是固定的命名还是只是因为它们的位置? 需要记住的对于data.iterrows 来说进行迭代的话 有两个值 一个是索引 另一个是行 肯定这里还有关于列的迭代 ''' # file_path = os.path.join(os.path.dirname(__file__), 'csv/test0.csv') # # print(os.path.abspath(__file__)) # # print(os.path.dirname(__file__)) # # print(file_path) # data = pd.read_csv(open(file_path, 'r', encoding='utf-8')) # print(data) # a_name_list = [] # for index, row in data.iterrows(): # print(index, row) # a_name_list.append(row['a_name']) # print(a_name_list) ''' DataFrame 数据合并 concat 有纵向的合并 有横向的合并 行向的合并就会有主次之分的 axis为1时是横向的 concat传入的参数是 列表 元素类型为dp.DataFrame 当axis=1 为横向拼接 0 或者不写 为纵向的拼接 此外还有join关键字 inner是得到交集 outer并集 交并 目前join 并没有看出加与不加的区别的 ''' a = [1, 2, 3] b = [4, 5, 6] data_dict = {'name': a, 'title': b} pf = pd.DataFrame(data_dict, columns=['name', 'title']) c = [7, 8, 9] d = [9, 8, 7] data_dict1 = {'name': c, 'title': d} pf1 = pd.DataFrame(data_dict1) c_pf = pd.concat([pf, pf1]) # print(c_pf) c_pf1 = pd.concat([pf, pf1], axis=1) # print(c_pf1) c_pf2 = pd.concat([pf, pf1], axis=1, join="inner") c_pf3 = pd.concat([pf, pf1], join="inner") # print(c_pf2, c_pf3) ''' 基本的行列的查找 看到的方法是 loc iloc ix https://blog.csdn.net/qq_38251616/article/details/84752080 loc 进行行定位 pf.loc(index) 依赖的是索引 进行列定位 pf.loc(:,'name') 依赖的是列名 进行多行 定义多列 添加 : iloc 利用自然行数来进行定位(依旧是从0开始的) 可以认为它是一个二维矩阵的定位 可以认为它是根据行索引来的 ix 进行混合的定位 这个ix现在是不能使用了的?? 被弃用的 ''' c_pf4 = c_pf3.loc['name'] print(c_pf4)
76955f23e5f4befe9c55a230425d6be8296f5f42
RGMishan/flaskPython
/practicePython/dictionary.py
201
4.03125
4
#python dictionary #Key Values Pair ages = {"Mishan": 20, "Regmi": 21} #ages is a dictionary ages["Nishan"] = 50 # Adding in dictionary ages["Mishan"] += 1 #Changing values in dictionary print(ages)
8b9526bd7d0b8a1beb897333c393d7542377d445
Seorimii/PythonStudy2019
/mar_24/0324_71.py
233
3.5625
4
def getPrime(x): if x%2==0: return for i in range(3,int(x/2),2): if x%i==0: break else: return x listdata = [17, 19, 113, 1113, 1119] ret = filter(getPrime,listdata) print(list(ret))
35d919b0e00afaddc160d91d8c6e2816ca30835a
atakanozguryildiz/HackerRank
/time_conversion.py
320
3.8125
4
s = input() is_am = "AM" in s first_two_digits = s[:2] if is_am: if first_two_digits == "12": print(("00" + s[2:-2])) else: print(s[:-2]) else: if first_two_digits == "12": print(s[:-2]) else: pm_hour = str(int(first_two_digits) + 12) print((pm_hour + s[2:-2]))
3a171f0270fba11c89cc79a853b6cd7370ec9e03
RoslinErla/ekki
/ordered_insetion.py
377
3.546875
4
import random from random import * class rand: gen = Random() def switch(lis,index): temp = lis[index] lis[index] = lis[index + 1] lis[index + 1] = temp def ordered_insertion(lis,value): index = len(lis) -1 lis.append(value) while index >= 0 and lis[index] > value: switch(lis,index) index -= 1 #O(n) linear time in size of list
42f50ba634f2422627db6c0d52b95b74105859c9
poojamadan96/code
/dict/list-set-dict.py
192
4.0625
4
#Make set and list from Dictionary dict={'a':1,'b':2,'c':3,'d':4,'e':5} li=[] sets=set() for x,y in dict.items(): li.append(x) sets.add(y) print("List = ",li) print("sets = ",sets /
353ed9f761dca29a31891c2e2d070380f357d687
papermerge/hocron
/hocron/line_pattern.py
2,630
3.984375
4
import re class LinePattern: """ line_pattern is a list with at least two elements - a string, which is a label and a regular expression compiled pattern (instance of re.Pattern) - the value to extract. String and regular expression can be in any order. The order matters for correct matching. If a documents has something like (price in Euro): EUR 10.23 to extract 10.23 value - use: get_labeled_value(['EUR', re.compile('\d\d\.\d\d')]) # noqa If on the other hand, to extract value from: SUMME 10.23 EUR order is label value label, use: get_labeled_value(['SUMME', re.compile('\d\d\.\d\d'), 'EUR']) # noqa line_pattern list may contain any number of strings - but just one compiled regular expression. """ def __init__(self, line_pattern): self._line_pattern = line_pattern @property def line_pattern(self): return self._line_pattern def exact_match(self, line_of_words): if len(line_of_words) != len(self.line_pattern): return False counter = 0 for index, value in enumerate(line_of_words): pattern = self.line_pattern[index] if isinstance(pattern, str): if pattern != value: return False if isinstance(pattern, re.Pattern): if not re.match(pattern, value): return False counter += 1 return counter == len(self.line_pattern) def match(self, random_line_of_words): if len(random_line_of_words) < 2: return False if len(random_line_of_words) < len(self.line_pattern): return False for word_index, word in enumerate(random_line_of_words): segment = slice(word_index, word_index + len(self.line_pattern)) matched = self.exact_match( list(random_line_of_words[segment]) ) if matched: return list(random_line_of_words[segment]) return False def get_value(self, same_length_line_of_words, delim=''): result = [] if len(same_length_line_of_words) != len(self.line_pattern): return False for index, value in enumerate(same_length_line_of_words): pattern = self.line_pattern[index] if isinstance(pattern, re.Pattern): matched = re.match(pattern, value) if matched: result.append(value) if len(result) > 0: return delim.join(result) return False
26a8e7b9ded3c7785895e08fa2eb2a8c228a4ab9
cuiboautotest/learnpython3
/10_hanshu/args_dif_kwargs.py
376
3.640625
4
def function1(*args): print(args, type(args))#用来将参数打包成tuple给函数体调用 def function2(**kwargs): print(kwargs, type(kwargs))#打包关键字参数成dict给函数体调用 def function3(arg,*args,**kwargs):#顺序必须是固定的 print(arg,args,kwargs) function1(1) function2(a=2) function3(6,7,8,9,a=1,b=2,c=3) function1() function2()
3feea041c00e9679cf399d90785656fad195cf02
tenkgrow/conceptual-backup-system
/backup_system.py
5,271
3.546875
4
#!/usr/bin/python3 import subprocess import linecache import os def stripend(strip): mod = strip.replace('\n','') return mod def ynchoice(user_input): while ((user_input is 'y' == False) or (user_input is 'n' == False)): print("The character you entered could not be recognized!") user_input = input("Please try again! (y/n) ") def setpath(old_path, new_path): print("You may choose a work directory where the list of your devices can be found.") print("The work directory is also the place where the backup process files will be stored.") print("If you haven't done this already - name your list 'pclist', or else the program WON'T recognize it!") yn = input("Would you like to set a new work directory? (y/n) ") ynchoice(yn) if (yn == 'y'): print("Remember: as of right now this only works with '/' paths!") new_path = input("Define the path: ") while ((os.path.exists(new_path + "pclist") == False)): if ((new_path[-1:] != '/')): print("The path was not set correctly!") print("Did you put a '/' at the end? Or missed a space from the end?") new_path = input("Define the path again: ") continue else: print("New path exists!") print("The 'pclist' file was not found!") newlist = input ("Would you like to copy the current 'pclist' to the new path? (y/n) ") ynchoice(newlist) if (newlist is 'y'): while (os.path.exists(new_path) == False): print("The new path could not be found! Please try again!") new_path = input ("Define an existing path: ") cmd = "cp pclist "+new_path+"pclist" subprocess.call(cmd, shell=True) print("Success! 'pclist' copy completed!") else: new_path = input("OK! Define the path again: ") if (old_path == new_path): print("The new path that was defined is the same as the current one!") print("No changes occured!") else: cmd = "echo $(date) >> old_paths" subprocess.call(cmd, shell=True) open("old_paths", 'a').write(old_path) open("path_file", 'w').write(new_path) print("The given path is compatible and the new path is set:" + new_path) else: print("The path remained the main folder of the program!") return new_path def createlist(path): open(path+"queue", 'w').close() open(path+"finished", 'w').close() print("Define the devices with their position in the list file!") print("Press <ENTER> to finish the list!te") var = 0 while (var is not None): with open(path+"queue", 'a') as w: w.write(linecache.getline(path+"pclist", var)) try: var = int(input("Device that needs backup: ")) except ValueError: var = None print("Backup list complete!") def backup(path): crash = '' with open(path+"queue", 'r') as f: for i in f: open(path+"finished", 'a').write(i) with open(path+"queue", 'r') as get: data = get.read().splitlines(True) with open(path + "queue", 'w') as rem: rem.writelines(data[1:]) if (crash is not 'x'): crash = input("Would you like to interrupt the process now? (y/n) ") ynchoice(crash) if (crash == 'y'): print("Backup process interrupted!") return else: crash = input("Should the process finish without interruption? (y/n) ") ynchoice(crash) if (crash == 'y'): crash = 'x' else: continue else: continue open(path + "queue", 'w').close() print("Backup process successful!") return def start(def_path): def_path = setpath(def_path, def_path) createlist(def_path) yn = input("Would you like to run the backup process? (y/n) ") ynchoice(yn) if (yn == 'y'): open(def_path + "finished", 'w').close() backup(def_path) else: print("Backup process denied!") return print("Welcome to the early stage of this experimental backup sytem!") if ((os.path.exists("backup_system.py")) == False): print("You are not in the program's main folder.") print("Please navigate to the folder where 'backup_system.py' is located!") else: org_path = linecache.getline("path_file",1) org_path = stripend(org_path) if (os.path.exists(org_path+"queue")): if (os.stat(org_path+"queue").st_size != 0): yn = input("You have an unfinished backup process! Would you like to continue? (y/n) ") ynchoice(yn) if (yn == 'y'): backup(org_path) else: start(org_path) else: start(org_path) else: start(org_path)
20a482ce543102caafd9995e22317b9182a46130
nishahiremani18/python
/python2.py
4,525
3.8125
4
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> #Araays and lists >>> a='hello python' >>> a[0] 'h' >>> a[1:2] 'e' >>> a[2:6] 'llo ' >>> a[-1] 'n' >>> a[-3] 'h' >>> a[-4] 't' >>> a[0:6] 'hello ' >>> #slicing-range(start,end) >>> a[2:4,5:9] Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> a[2:4,5:9] TypeError: string indices must be integers >>> len(a) 12 >>> a 'hello python' >>> #function of strings- find,split,format >>> #pattern-str.func_name(argument) >>> "hello python".find("python") 6 >>> #find func helps us to find the argument exists in the string or no >>> #with the index number >>> "hello".find("suhr") -1 >>> #shows the string is not present in the string >>> "python hello python".find("python",2) 13 >>> "python python python helo".find("python",5) 7 >>> a="nisha hiremani" >>> b=[32,21,23,56,67] >>> b[-1] 67 >>> c=["nisha","hiremani"] >>> a 'nisha hiremani' >>> "nisha hiremani".split() ['nisha', 'hiremani'] >>> #if you do not write the arg then it will split the string from space >>> a.split() ['nisha', 'hiremani'] >>> a.split(a) ['', ''] >>> a.split("a") ['nish', ' hirem', 'ni'] >>> #a will be removed from the list >>> q=a.split("a") >>> q[1] ' hirem' >>> c=a.split >>> a 'nisha hiremani' >>> c <built-in method split of str object at 0x03081278> >>> c=a.split() >>> a 'nisha hiremani' >>> c ['nisha', 'hiremani'] >>> c[0][1] 'i' >>> c[0][0] 'n' >>> q=c[0] >>> q[0] 'n' >>> q 'nisha' >>> ## format >>> a="today is good day:" >>> a="today is good day: {} and tommorow will be {} and after month {}" >>> t=22 >>> t=221 >>> to=43 >>> one=19 >>> A=a.split("{}") >>> A ['today is good day: ', ' and tommorow will be ', ' and after month ', ''] >>> A1=A[0]+str(t)+A[1]+str(to)+A[2]+str(one) SyntaxError: unexpected indent >>> A1=A[0]+str(t)+A[1]+str(to)+A[2]+str(one) >>> A1 'today is good day: 221 and tommorow will be 43 and after month 19' >>> #this is take so much time and efforts >>> a.format(t,to,one) 'today is good day: 221 and tommorow will be 43 and after month 19' >>> # {} are replaced with the values >>> a.format(6,5,5) 'today is good day: 6 and tommorow will be 5 and after month 5' >>> a.format("happy","sad or happy","sad") 'today is good day: happy and tommorow will be sad or happy and after month sad' >>> >>> ##playing with lists and arrays >>> x=[1,2,3,4,5,5,6,7] >>> y=[2,4,5,6,7,8,9] >>> z=[1,3,4,5,"hello",5.6,90] >>> type(x) <class 'list'> >>> type(y) <class 'list'> >>> type(z) <class 'list'> >>> ## array can save only one type of data and list can save all types of data like - strings ,int float >>> ##func of list-append,index,pop >>> #pattern-list.func(arg) -optional >>> ##append-add value in last position >>> x.append(100) >>> x [1, 2, 3, 4, 5, 5, 6, 7, 100] >>> a.index(1,67) Traceback (most recent call last): File "<pyshell#77>", line 1, in <module> a.index(1,67) TypeError: must be str, not int >>> a.insert(1,67) ##a.insert(loc,value) Traceback (most recent call last): File "<pyshell#78>", line 1, in <module> a.insert(1,67) ##a.insert(loc,value) AttributeError: 'str' object has no attribute 'insert' >>> a.insert(1,67) Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> a.insert(1,67) AttributeError: 'str' object has no attribute 'insert' >>> a.insert(1, 67) Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> a.insert(1, 67) AttributeError: 'str' object has no attribute 'insert' >>> x.insert(2,67) >>> x [1, 2, 67, 3, 4, 5, 5, 6, 7, 100] >>> x.index(2) 1 >>> ##searching index of the value index is used >>> ##pop >>> x.pop() 100 >>> x.pop(2) 67 >>> x [1, 2, 3, 4, 5, 5, 6, 7] >>> x.pop('4') Traceback (most recent call last): File "<pyshell#89>", line 1, in <module> x.pop('4') TypeError: 'str' object cannot be interpreted as an integer >>> x.pop(,4) SyntaxError: invalid syntax >>> x.index(6) 6 >>> x.pop(6) 6 >>> x [1, 2, 3, 4, 5, 5, 7] >>> x.index(5) 4 >>> x.pop(4) 5 >>> x [1, 2, 3, 4, 5, 7] >>> x.append(5) >>> x [1, 2, 3, 4, 5, 7, 5] >>> x.removed(5) Traceback (most recent call last): File "<pyshell#99>", line 1, in <module> x.removed(5) AttributeError: 'list' object has no attribute 'removed' >>> x.remove(5) >>> x [1, 2, 3, 4, 7, 5] >>> >>> ##dict
df4f63d50f4d4786f8f0d760fbd83198b84b4c6c
fukenist/learn_hard_way
/test6.py
782
4
4
print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print('Yak') elif bear == "2": print('Dark') else: print(f'Goody {bear} not eating anyone') elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input('> ') if insanity == "1" or insanity == "2": print('You are happy') else: print('You are broken') else: print('Smth went wrong and you woke up')
6189417113c869bfd4ab70defeae2ebed2a22adc
f904/my-lesson-python
/домашка.py
259
3.890625
4
while True: a = int(input()) b = int(input()) v = input() if v =='*': print(a*b) if v =="+": print(a+b) if v =="-": print(a-b) if v =="/": if b!=0: print(a/b) l
842983102cd8d2f8555cfd50a426eebc03acc085
pauloalwis/python3
/leia.um.numero.inteiro.e.mostre.sua.tabuada.py
193
4.03125
4
numero = int(input('Digite um número para ser apresentado sua tabuada!')) print(20 * '=') for i in range(0, 11): print('{} x {:2} = {}'.format(numero, i, (numero * i))) print(20 * '=')
2fb9bf701114f9c68980ad246a5ef38b4afc82ad
mananjay19/p109
/p109.py
1,409
3.671875
4
import pandas as pd import csv import statistics df = pd.read_csv('StudentsPerformance.csv') datalist = df ['reading score'].tolist() datamean=statistics.mean(datalist) datamedian=statistics.median(datalist) datamode=statistics.mode(datalist) datastd=statistics.stdev(datalist) print('mean,meadian,mode,stdev for reading score are',datamean,datamedian,datamode,datastd) data_first_std_start,data_first_std_end = datamean - datastd, datamean + datastd data_second_std_start,data_second_std_end = datamean - datastd*2, datamean + datastd*2 data_third_std_start,data_third_std_end = datamean - datastd*3, datamean + datastd*3 datalistofdatawithinfirststd = [result for result in datalist if result > data_first_std_start and result < data_first_std_end] datalistofdatawithinsecondstd = [result for result in datalist if result > data_second_std_start and result < data_second_std_end] datalistofdatawithinthirdstd = [result for result in datalist if result > data_third_std_start and result < data_third_std_end] print('{} % of data for reading score lies within first std range'.format(len(datalistofdatawithinfirststd)*100.0/len(datalist))) print('{} % of data for reading score lies within second std range'.format(len(datalistofdatawithinsecondstd)*100.0/len(datalist))) print('{} % of data for reading score lies within third std range'.format(len(datalistofdatawithinthirdstd)*100.0/len(datalist)))
5ef0369db81ade386b8208358f2b8e1d39bed1ea
liuperic/automate_the_boring_stuff_with_python_solutions
/ch_19/practice_projects/custom_seating_cards.py
1,051
3.625
4
#!/usr/bin/env python3 # custom_seating_cards.py - From practice project in ch 15, add image to custom card # Extension of ch 15 project. import os from PIL import Image, ImageDraw, ImageFont def seating_card(guest_list): """Custom invitation card for each guest""" os.makedirs('custom_cards', exist_ok=True) flower_img = Image.open('flower.png') with open(guest_list) as f: for line in f: guest = line[:-1] card = Image.new('RGBA', (288, 360), 'white') # Paste flower into card image card.paste(flower_img, (0,0)) # Create border border = Image.new('RGBA', (291, 363), 'black') border.paste(card, (3, 3)) draw_obj = ImageDraw.Draw(border) card_font = ImageFont.truetype('Arial Unicode.ttf', 20) draw_obj.text((120, 100), guest, fill='purple', font=card_font) border.save(os.path.join('custom_cards', '{}.png'.format(guest))) if __name__ == "__main__": seating_card('guests.txt')
afe78628f7063002ce4d243cb917c45a9fad1b5a
Iongtao/learning-python3
/learning/base8_input.py
1,861
3.75
4
# !/usr/bin/env python3 # coding=utf-8 qanda = [ { "q": "1+1等于几?", "a": "2" }, { "q": "你是几号入职的?例如:9月24号", "a": "11月2号" }, { "q": "我和你认识多久了", "a": "不知道" } ] # 声明一个变量作为 提示信息 question = '请输入你想回答的问题序号,例如:1\n' # indexs用来去得到序号列表 indexs = [] # 把问题遍历出来 # += 运算: a += b 与 a = a + b 运算形式是一致的 for i in range(0, len(qanda)): # 向indexs列表添加索引值 indexs.append(i + 1) # 进行字符串拼接操作 遍历出问题列表 question += str(i + 1) + ':' + qanda[i]['q'] + '\n' # 额外的提示输入 question += '请输入序号:' # 开始提出问题 # print(question) # message 接收输入的内容 message的类型为字符串 # input返回用户输入的类型默认为字符串 message = input(question) # 如果想要接收的类型是整数型 需要使用int()去强转 message = int(message) # 得到输入内容 后 进行校验输入内容的正确性 if message in indexs: if message == 1: answer = input('请输入你的回答: ') if answer != int(qanda[message - 1]['a']): print('你回答错误了,正确答案是:' + qanda[message - 1]['a']) else: print('恭喜你,回答正确') if message == 2: answer = input('请输入你的回答:') if answer != qanda[message - 1]['a']: print('你可能记错你的入职时间噢') else: print('哎哟,不错哦') if message == 3: answer = input('请输入你的回答:') print(answer) else: print('\n你输入的序号' + '[' + str(message) + ']' + '不在以下列表中哦:' + str(indexs))
b712570b9d650553562fbcac43a17e65bae817c3
maomao905/algo
/maximum-length-of-repeated-subarray.py
4,242
3.921875
4
""" N: A length, M: B length brute-force O(NM*min(N,M)) space: O(1) iterate A's letter and check if it exists in B one by one and it matches, continue expanding until unmatched A = [1,2,3,2,1] B = [3,2,1,4,7] """ from typing import List class Solution: def findLength(self, A: List[int], B: List[int]) -> int: max_cnt = 0 N, M = len(A), len(B) for i in range(N): for j in range(M): _i = i _j = j while _i < N and _j < M and A[_i] == B[_j]: _i += 1 _j += 1 max_cnt = max(_i-i, max_cnt) return max_cnt """ (TLE) binary search O(log(min(N,M)) * (N+M)*min(N,M)) space: O(M^2) for example, if the max length is in fact, 3, then we never find more than 3 length of common subarray and we must be able to find less than 3 length of common subarray A: [3,2,1] B: [3,2,1] -> A[3,2] B[3,2] must exist we do binary search and every time, check if the specific length of common subarray exists how do we check given length k of subarray exists? simply take all possible k length of A subarray and store in hash map then, we iterate all possible k length of B subarray and check if it matches A's subarray in hash map time complexity: binary search O(log(min(N,M))) building k-length A's subarray hash map over N-k times O(N-k * k) hashing k-length B's subarray over M-k times O(M-k * k) maximum of k is min(N,M) space complexity hash map length is O(M) and each size is O(M) -> O(M^2) """ class Solution: def check_length(self, A, B, k): hs = set() for i in range(len(A)-k+1): hs.add(tuple(A[i:i+k])) for j in range(len(B)-k+1): if tuple(B[j:j+k]) in hs: return True return False def findLength(self, A: List[int], B: List[int]) -> int: l = 0 r = min(len(A), len(B)) while l < r: mid = l + (r-l) // 2 if self.check_length(A, B, mid): l = mid else: r = mid-1 return l """ DP O(NM) space: O(NM) A = [1,2,3,2,1] B = [3,2,1,4,7] if A[i] and B[j] matches and common subarray length is k, if A[i+1] and B[j+1] matches, length will be k+1 """ class Solution: def findLength(self, A: List[int], B: List[int]) -> int: max_len = 0 dp = [[0] * len(B) for _ in range(len(A))] for i in range(len(A)): for j in range(len(B)): if A[i] == B[j]: if i < 1 or j < 1: dp[i][j] = 1 else: dp[i][j] = dp[i-1][j-1] + 1 max_len = max(max_len, dp[i][j]) return max_len """ binary search with rabin karp we can do better when hashing the subarray in the binary search solution not hashing entire subarray each time, only the first and last element using rabin karp O(M+N) * log(min(M,N)) A = [1,2,3,2,1] B = [3,2,1,4,7] """ class Solution: def check_length(self, A, B, k): W = 100 h = 0 for i in range(k): h = W * h + A[i] hs = set([h]) for i in range(len(A)-k): h -= A[i] * (W ** (k-1)) h *= W h += A[i+k] hs.add(h) h = 0 for j in range(k): h = W * h + B[j] if h in hs: return True for j in range(len(B)-k): h -= B[i] * (W ** (k-1)) h *= W h += B[i+k] if h in hs: return True return False def findLength(self, A: List[int], B: List[int]) -> int: l = 0 r = min(len(A), len(B)) while l < r: mid = l + (r-l) // 2 if self.check_length(A, B, mid): l = mid+1 else: r = mid-1 # print(mid,l,r) return l s = Solution() print(s.findLength(A = [1,2,3,2,1], B = [3,2,1,4,7])) print(s.findLength([0,0,0,0,1],[1,0,0,0,0]))
dad8a73ce62f291d6572423d0d718172a7b5e5ef
BrentLittle/WebDevPython
/Sec 2 - Python Refresher/10_Loops/loop.py
622
3.8125
4
number = 7 while True: userIn = input("Would you like to play? (Y/n): ") if userIn == "n": break usernum = int(input("Guess our number: ")) if usernum == number: print("You guessed correctly") elif abs(number - usernum) == 1: print("You were one off.") else: print("You guessed incorrectly") friends = ["Rolf", "Jen", "Bob", "Anne"] for name in friends: print(f"{name} is my friend") grades = [35,67,98,100,100] total = 0 amount = len(grades) for grade in grades: total += grade total = sum(grades) print(f"The average was: {total/amount}%")
2359f8ea0aa6fc905cbaefb9a466c866f8cbfffb
Everfighting/leetcode-problemset-solutions
/valid-parentheses.py
1,169
3.5625
4
#给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # #有效字符串需满足: # #左括号必须用相同类型的右括号闭合。 #左括号必须以正确的顺序闭合。 #注意空字符串可被认为是有效字符串。 # #示例 1: # #输入: "()" #输出: true #示例 2: # #输入: "()[]{}" #输出: true #示例 3: # #输入: "(]" #输出: false #示例 4: # #输入: "([)]" #输出: false #示例 5: # #输入: "{[]}" #输出: true # 法一 class Solution: def isValid(self, s: str) -> bool: while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == '' # 法二 class Solution: def isValid(self, s: str) -> bool: stack = [] mapping = {'(':')', '{':'}', '[':']', '#':'$'} for char in s: if char not in mapping: top_element = stack.pop() if stack else '#' if mapping[top_element] != char: return False else: stack.append(char) return not stack
bbf55624dc3f7737deca1f1f0d6f320d81558d6d
yaodecheng0217/Fengbian-
/练习/9-1.py
664
3.78125
4
''' @Author: Yaodecheng @Date: 2019-12-06 20:14:52 @LastEditors: Yaodecheng ''' #定义两个函数:第一个函数功能为根据工作月数返回奖金额, def reward(month): if month<5: return 500 elif 6<=month<=12: return 120*month else: return 180*month #第二个函数功能为打印出'该员工来了XX个月,获得奖金XXX元'。 def printall(name,month): print ('{}来了{}个月,获得奖金{}元'.format(name,month,reward(month))) #最后传入参数('大聪',14)调用第二个函数,打印结果'大聪来了14个月,获得奖金2520元' if __name__ == "__main__": printall('大聪',14)
d89177817be2a664fb12d476001a3a52f0c8ac6d
yangjiahao106/LeetCode
/Python3/1206_设计跳表.py
1,753
3.6875
4
import random class Node: def __init__(self, val=0): self.val = val self.right = None self.down = None class Skiplist: def __init__(self): left_nodes = [Node(-1) for i in range(16)] for i in range(15): left_nodes[i].down = left_nodes[i + 1] self.lefts = left_nodes def search(self, target: int) -> bool: cur = self.lefts[0] while cur: if cur.right and cur.right.val == target: return True elif cur.right and cur.right.val < target: cur = cur.right else: cur = cur.down return False def add(self, num: int) -> None: cur = self.lefts[0] stack = [] while cur: if cur.right and cur.right.val <= num: cur = cur.right else: stack.append(cur) cur = cur.down pre = None while stack: cur = stack.pop() newNode = Node(num) newNode.right = cur.right cur.right = newNode newNode.down = pre pre = newNode if random.randint(0, 1): break def erase(self, num: int) -> bool: cur = self.lefts[0] find = False while cur: if cur.right and cur.right.val == num: cur.right = cur.right.right cur = cur.down find = True elif cur.right and cur.right.val < num: cur = cur.right else: cur = cur.down return find if __name__ == '__main__': s = Skiplist() s.add(1) s.add(2) s.add(3) print(s.search(1))
9a209abe218f68ba7077e33d8baa0fb63f5b9836
dinosaurz/ProjectEuler
/id007.py
740
3.9375
4
import time def isPrime(num): ''' Return whether a number is prime Using Joah Gestenberg's algorithm from www.koding.com num: number to be tests ''' if num % 2 == 0: return False for p in xrange(3, int(num ** 0.5) + 1, 2): if num % p == 0: return False return True def main(): """takes numbers and checks for primality.""" number, primes = 1, 0 while True: if isPrime(number): primes += 1 if primes == 10001: break number += 2 print number, if __name__ == '__main__': start = time.time() main() elapsed = time.time() - start print "found in %s seconds" % (elapsed)
b8d4e0cbd4132b7f0ff1cdb3081defad00eb37e0
kimsappi/website-status
/src/classes/IntervalParser.py
1,105
3.875
4
allowedIntervals = ['second', 'seconds', 'minute', 'minutes', 'hour', 'hours'] class IntervalParser: """ Returns number of seconds interval given as string (e.g. '5 seconds', '1 hour'). """ def __new__(cls, interval: str) -> int: try: arr = interval.split(' ') except: raise Exception('Time interval in invalid format') if len(arr) != 2: raise Exception('Time interval in invalid format (e.g. \'5 seconds\')') if arr[1] not in allowedIntervals: raise Exception(' '.join([ 'Disallowed time interval. Allowed values:', ', '.join(allowedIntervals) ])) try: timeUnit = int(arr[0]) except: raise Exception('Time interval must be in the format \'integer unit\'') arrPos = allowedIntervals.index(arr[1]) secondMultiplier = 1 if arrPos > 1: secondMultiplier *= 60 if arrPos > 3: secondMultiplier *= 60 return timeUnit * secondMultiplier """ There must be packages for this, but this is quite a limited application and I'd prefer to know how it works in all situations. """
a9fda6c1c22bd32f312109327ed53ed4df84a6e2
Chairmichael/ProjectEuler
/Python/Complete/0006b - Sum square difference.py
703
3.84375
4
''' The sum of the squares of the first ten natural numbers is, 1**2 + 2**2 + ... + 10**2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)**2 = 55**2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' # sum_of_squares = sum(x**2 for x in range(1,101)) # sum_squared = sum(x for x in range(1,101))**2 # print(sum_squared-sum_of_squares) # Why do that when you can do this... print( (sum(x for x in range(1,101))**2) - sum(x**2 for x in range(1,101)))
62d0f88f2a7efceff3878180dc57b667ac27eda6
deskninja/Various
/temp.py
1,363
3.71875
4
def main(): getKey = list1, players = getScores() numbers = [] highlow = list1.sorted() def getScores(): nameandScores = [] total = 0 nameandScore = "start" nameandScore = str(input("Enter the name and score of the next player: ")) if nameandScore == "": #Checks to see if the first entry is more than nothing input("You did not enter anything. Press enter to exit.") sys.exit() players = 0 while nameandScore != "": try: #This checks to see if values will work for future sorting int(nameandScore.split()[-1]) total += int(nameandScore.split()[-1]) except: print("Your name and score was not entered in the correct way.") input("Press enter to exit.") sys.exit() if int(nameandScore.split()[-1]) > 300 or int(nameandScore.split()[-1]) < 0: print("That score is not a possible bowling score.") input("Press enter to exit.") sys.exit() nameandScores.append(nameandScore) players += 1 if players >= 2: #I assume that at least two players will be entered print("If there are no more players press enter.") nameandScore = str(input("Enter the name and score of the next player: ")) return nameandScores, players main()
89e81c34cb0da39b696a6fdc842368f60e681612
TechHouse-rj/Mini_Projects
/Fluid Simulaor/script.py
7,551
3.71875
4
import sys import pygame from math import sqrt from random import random as rand from math import pi class Particle(object): def __init__(self, pos): # Scalars self.density = 0 # Forces self.position = pos self.velocity = Vec2(0,0) self.pressure_force = Vec2(0,0) self.viscosity_force = Vec2(0,0) class ParticleGraphics(object): def __init__(self, window_size): pygame.init() self.window = pygame.display.set_mode(window_size) self.radius = 5 def draw(self, particles, H, scale): scale = 500 // scale self.window.fill((0,0,0)) for particle in particles: # Color based on pressure just for fun color = particle.density*50 if particle.density*50 < 255 else 255 # Area of influence (H) pygame.draw.circle(self.window, (color, 0, 255), ( int(particle.position.x*scale), int(particle.position.y*scale)), H*scale//2, 1) # Particles pygame.draw.circle(self.window, (255, 255, 255), ( int(particle.position.x*scale), int(particle.position.y*scale)), self.radius) # Velocity vectors pygame.draw.line(self.window, (255, 255, 0), # start (int(particle.position.x*scale), int(particle.position.y*scale)), # end (int((particle.position.x+particle.velocity.x)*scale), (int((particle.position.y+particle.velocity.y)*scale)))) # Enable to step through the sim by entering newlines in the console ### getch = input() # Draw to screen pygame.display.flip() graphics = ParticleGraphics((500, 500)) Num = float, int # Numeric classes class Vec2(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vec2(self.x+other.x, self.y+other.y) def __sub__(self, other): return Vec2(self.x-other.x, self.y-other.y) def __iadd__(self,other): self.x += other.x self.y += other.y return self def __eq__(self, other): if self.x == other.x and self.y == other.y: return True else: return False def __mul__(self, scalar): # vec * scalar return Vec2(self.x*scalar, self.y*scalar) def __rmul__(self, scalar): # scalar * vec return Vec2(self.x*scalar, self.y*scalar) def length(v): return sqrt(v.x**2 + v.y**2) #MAIN # Constants SCALE = 15 MASS = 5 # inversly proportional Particle mass DENSITY = 1 # Rest density GRAVITY = Vec2(0, 0.5) H = 1 # Smoothing cutoff- essentially, particle size k = 20 # Temperature constant- higher means particle repel more strongly eta = 1 # Viscosity constant- higher for more viscous def W(r, h): # :: Num ''' A weighting function (kernel) for the contribution of each neighbor to a particle's density. Forms a nice smooth gradient from the center of a particle to H, where it's 0 ''' if 0 < length(r) <= h: ret= 315/(64 * pi * h**9) * (h**2 - length(r)**2)**3 else: ret= 0 # Typecheck return ret def gradient_Wspiky(r, h): # :: Vec2 ''' Gradient ( that is, Vec2(dx, dy) ) of a weighting function for a particle's pressure. This weight function is spiky (not flat or smooth at x=0) so particles close together repel strongly ''' len_r = length(r) if 0 < len_r <= h: ret = -1 * r * (45/(pi * h**6 * len_r)) * (h - len_r)**2 else: ret = Vec2(0, 0) return ret def laplacian_W_viscosity(r, h): # :: Num ''' The laplacian of a weighting function that tends towards infinity when approching 0 (slows down particles moving faster than their neighbors) ''' len_r = length(r) if 0 < len_r <= h: ret = 45/(2 * pi * h**5) * (1 - len_r/h) else: ret = 0 return ret # Instantiate particles! width = 20 height = 10 particles = [] for x in range(10): for y in range(10): particles.append(Particle(Vec2(x+1+rand()*0.1, y+5))) # random distribution # particles = [Particle(Vec2(rand()*SCALE, rand()*SCALE)) # for p in range(NUM_PARTICLES)] time = 0 delta_time = 0.1 while True: # Clear everything for particle in particles: particle.density = DENSITY particle.pressure_force = Vec2(0,0) particle.viscosity_force = Vec2(0,0) # Calculate fluid density around each particle for particle in particles: for neighbor in particles: # If particles are close together, density increases distance = particle.position - neighbor.position # A vector if length(distance) <= H: # Particles are close enough to matter particle.density += MASS * W(distance, H) # Calculate forces on each particle based on density for particle in particles: for neighbor in particles: distance = particle.position - neighbor.position if length(distance) <= H: # Temporary terms used to caclulate forces density_p = particle.density density_n = neighbor.density assert(density_n != 0) # Dividing by density later # Pressure derived pressure_p = k * (density_p - DENSITY) pressure_n = k * (density_n - DENSITY) # Navier-Stokes equations for pressure and viscosity # (ignoring surface tension) particle.pressure_force += (-1 * MASS * (pressure_p + pressure_n) / (2 * density_n) * gradient_Wspiky(distance, H)) particle.viscosity_force += ( eta * MASS * (neighbor.velocity - particle.velocity) * (1/density_n) * laplacian_W_viscosity(distance, H)) # Apply forces to particles- make them move! for particle in particles: total_force = particle.pressure_force + particle.viscosity_force # 'Eulerian' style momentum: # Calculate acceleration from forces acceleration = total_force * (1/particle.density) \ * delta_time + GRAVITY # Update position and velocity particle.velocity += acceleration * delta_time particle.position += particle.velocity * delta_time # Make sure particles stay in bounds # TODO: Better boundary conditions (THESE ARE BAD) if particle.position.x >= SCALE - 0.01: particle.position.x = SCALE - (0.01 + 0.1*rand()) particle.velocity.x = 0 elif particle.position.x < 0.01: particle.position.x = 0.01 + 0.1*rand() particle.velocity.x = 0 if particle.position.y >= SCALE - 0.01: particle.position.y = SCALE - (0.01+rand()*0.1) particle.velocity.y = 0 elif particle.position.y < 0.01: particle.position.y = 0.01 + rand()*0.1 particle.velocity.y = 0 graphics.draw(particles, H, SCALE) time += delta_time
afa44b3a9572bdc79c4b69faf1d6de6c9288c3e4
vikassry/pyWorkspace
/rovers.py
1,350
3.671875
4
DIRECTIONS = { 'N' : {'L':'W', 'R':'E'}, 'W' : {'L':'S', 'R':'N'}, 'S' : {'L':'E', 'R':'W'}, 'E' : {'L':'N', 'R':'S'} } MOVE_COORDINATES = { 'N' : [0, 1], 'S' : [0,-1], 'W' : [-1,0], 'E' : [1, 0] } def move(rover, moves): for move in moves: if (move=='L') or (move=='R'): rover['direction'] = DIRECTIONS[rover['direction']][move] elif(move=='M'): rover['start_point'][0] = int(rover['start_point'][0]) + int(MOVE_COORDINATES[rover['direction']][0]) rover['start_point'][1] = int(rover['start_point'][1]) + int(MOVE_COORDINATES[rover['direction']][1]) def toString(rover): return ' '.join(map(str, rover['start_point']))+ " "+ rover['direction'] end_coordinates = raw_input().split() first_rovers_points = raw_input().split() first_rovers_start_point = first_rovers_points[:2] first_rover = { 'start_point' : first_rovers_start_point, 'direction' : first_rovers_points[2], } first_rovers_moves = raw_input() move(first_rover, first_rovers_moves) second_rovers_point = raw_input().split() second_rovers_start_point = second_rovers_point[:2] second_rover = { 'start_point' : second_rovers_start_point, 'direction' : second_rovers_point[2], } second_rovers_moves = raw_input() move(second_rover, second_rovers_moves) print('\n') print(toString(first_rover)) print(toString(second_rover))
868f525d4c792a1936420fba2918e3ba446b3faf
poponzu/atcoder1
/LeetCode/permutations.py
260
3.828125
4
# itertoolsなかったらきつい? # import itertools class Solution: def permute(self, nums):# List[List[int]]: per = list(itertools.permutations(nums)) return per num = [1,2,3] per = list(itertools.permutations(num)) print(per)
dca28ddb8c14ff5a810415a2890112994f3e0ac9
skebix/think-python-implementation
/Exercises/Chapter 4/e5.py
606
4.53125
5
__author__ = 'skebix' ''' Make a more general version of circle called arc that takes an additional parameter angle, which determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc should draw a complete circle. ''' from swampy.TurtleWorld import * from math import pi world = TurtleWorld() turtle = Turtle() turtle.delay = 0.01 def arc(t, r, angle): arc_size = 2 * pi * r * angle / 360 sides = 80 length = arc_size / sides angle = float(angle) / sides for i in range(sides): fd(t, length) lt(t, angle) arc(turtle, 80, 180)
c6236ea2edaa217061d66a0b03020c5c8d898fcb
yuuhei340/sample-streamlit-yuhei
/Greeting.py
487
3.625
4
class Student: def __init__(self,name): self.name=name def calculate_avg(self,date): sum=0 for num in date: sum+=num avg=sum/len(date) return avg def judge(self,avg): if(avg>=60): result="passed" else: result="failed" return result a001=Student("sato") date=[70,65,50,90,30] avg=a001.calculate_avg(date) result=a001.judge(avg) print(avg) print(a001.name+""+result)
d1453cbfb092465a9acd31c3394d82829a43473c
huezune2000/Learn-Python-Offline
/PYTHON/Learn Python/Level_0/8) While 1.py
643
4.53125
5
#### #Now that you know a little about how variables #can be defined and redefined we'll cover our first #type of loop. The 'while' loop #### #the 'while' loop says that as long as something #that you define is true, it should perform an #operation #For Example x = 0 while (x<10): print (x) x += 1 #using += can save time programming when ################you want to add a number to a variable ########you could also format it like below ######## x = x + 1 ########but this takes more time (so why do it) #First, predict what you think this will do. #Run this program to see what it does. #did you think right?
fc055d418b2df7407722048c251cf47790916727
vash050/start_python
/lesson_2/shcherbatikh_vasiliy/z_2.py
1,150
3.90625
4
# Для списка реализовать обмен значений соседних элементов, # т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. # При нечетном количестве элементов последний сохранить на своем месте. # Для заполнения списка элементов необходимо использовать функцию input(). my_list = [1, 2.2, 'str', [1, 'str'], {'key': 'value'}, {"a", "b"}, True, (5, 'el'), 5] # вариант первый не правельный # my_list = [] # i = 0 # while i < 10: # element = input('введите 10 значений по очереди:') # my_list.append(element) # i += 1 # вариант правельный # my_list = [] # for i in range(1, 10): # element = input('введите 10 значений по очереди:') # my_list.append(element) for idx, value in enumerate(my_list[:]): if (idx + 1) % 2 == 0: my_list[idx - 1], my_list[idx] = my_list[idx], my_list[idx - 1] print(my_list)
69565f9b222dcd8b4b546344cf4ec81bb67d977a
SarthakRana/Machine-Learning-A-Z
/Data Preprocessing/Data_preprocessing.py
2,014
3.796875
4
#Dataset Preprocessing #----------------Importing Libraries--------------# import pandas as pd # For importing datasets and managing datasets import matplotlib.pyplot as plt import numpy as np # contains mathematical tools which helps in calculations #--------------- Importing the Dataset---------------# #csv- comma separated values #tsv- tab separated values dataset = pd.read_csv('Data.csv') #Creating matrix of dataset. #X is an array of independent features #y is an array of dependent results X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 3].values #------------------Taking care of missing values---------------------# #Imputer is a class which takes care of missing data. from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN',strategy='mean', axis = 0) #Fit this imputer data to matrix X. imputer = imputer.fit(X[:, 1:3]) X[:, 1:3] = imputer.transform(X[:, 1:3]) #---------------- Encoding categorical data(String -> Numbers) ---------------------# #One object converts only one column of categorical data. from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X = LabelEncoder() X[:, 0] = labelencoder_X.fit_transform(X[:, 0]) #OneHotEncoder is used for dummy encoding onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) #----------------------- Splitting dataset into training set and testing set. ----------------------------# from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #----------------------- Feature Scaling ----------------------# #Must for accuracy and when our algo is dealing with Euclidean Distance. from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test)
4be56b99065ff64d097864899a9738881738eedf
luuuumen/algorithm013
/Week_02/hw.py
2,876
3.515625
4
# coding:utf-8 from collections import deque import heapq class Solution(object): # 两数之和 def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # dic = dict(zip(nums, range(len(nums)))) dic = {} for i, n in enumerate(nums): if target - n in dic: return [i, dic[target - n]] else: dic[n] = i return False # 树的前-中-后序遍历 def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) # 前序 # return self.preorderTraversal(root.left) + [root.val] + self.preorderTraversal(root.right) #中序 # return self.preorderTraversal(root.left) + self.preorderTraversal(root.right) + [root.val] #后序 # 多叉树的层序遍历 def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ if not root: return [] result = [] queue = deque([root]) while queue: layer = [] for _ in range(len(queue)): node = queue.popleft() layer.append(node.val) queue.extend(node.children) result.append(layer) return result # 最小的K个数 def getLeastNumbers(self, arr, k): if k == 0: return list() hp = [-x for x in arr[:k]] heapq.heapify(hp) for i in range(k, len(arr)): if -hp[0] > arr[i]: heapq.heappop(hp) heapq.heappush(hp, -arr[i]) ans = [-x for x in hp] return ans # 盛最多的水 def maxArea(self, height): """ :type height: List[int] :rtype: int """ res, l, r = 0, 0, len(height) - 1 while l < r: if height[l] < height[r]: res = max(res, height[l] * (r - l)) l += 1 else: res = max(res, height[r] * (r - l)) r -= 1 return res # K个一组反转 def reverseKGroup(self, head, k): cur = head count = 0 while cur and count != k: cur = cur.next count += 1 if count == k: cur = self.reverseKGroup(cur, k) while count: tmp = head.next head.next = cur cur = head head = tmp count -= 1 head = cur return head
0daf860d687880c51d8d9e892368bacee9f4db09
icurious/Automate-The-Boring-Stuff-With-Python
/Chapter 4/Comma Code.py
236
3.828125
4
def comma_code(user_list): string_with_and = ",".join(user_list[:-1]) + " and " + user_list[-1] print((string_with_and)) user_input = input("Enter your list: ") user_list = user_input[1:-1].split(",") comma_code(user_list)
20323f546afbb48c5f632db6ed39a0fce315c005
geraldo-sousa/Francisco-Vieira
/p1-lp1/Teste-de-conhecimento-inicial/intersecaoentrelistas.py
546
3.78125
4
''' Interseção entre listas ''' lista1 = [] lista2 = [] intersecao = [] tamanho = 40 i = 0 while(i < tamanho): value = input() if(value != ''): if(i < 20): lista1.append(int(value)) else: lista2.append(int(value)) i += 1 for value1 in lista1: for value2 in lista2: if(value1 == value2 and value1 not in intersecao): intersecao.append(value1) if(intersecao == []): print('VAZIO') else: intersecao.sort() for value in intersecao: print(value)
acf9308b0b83aabc60c9032e8942394d19727fc9
sbudax/Python
/basics/basicsModule.py
1,836
3.859375
4
#Using Builtin Modules #Usage: import sys # sys.builtin_module_names # import time # import os # while True: # if os.path.exists("file.txt"): # with open("file.txt") as file: # print(file.read()) # else: # print("file does not exist") # time.sleep(5) #Third-Party Modules # # pip/pip3 library in python used to install third-party modules # # usage: pip3 install pandas import time #Builtin library import os #Standard library import pandas #Third-party library while True: if os.path.exists("temp.csv"): data = pandas.read_csv("temp.csv") print(data.mean()["st1"]) else: print("file does not exist") time.sleep(5) # In this section you learned that: # Builtin objects are all objects that are written inside the Python interpreter in C language. # Builtin modules contain builtins objects. # Some builtin objects are not immediately available in the global namespace. They are parts of a builtin module. To use those objects the module needs to be imported first. E.g.: # import time # time.sleep(5) # A list of all builtin modules can be printed out with: # import sys # sys.builtin_module_names # Standard libraries is a jargon that includes both builtin modules written in C and also modules written in Python. # Standard libraries written in Python reside in the Python installation directory as .py files. You can find their directory path with sys.prefix. # Packages are a collection of .py modules. # Third-party libraries are packages or modules written by third-party persons (not the Python core development team). # Third-party libraries can be installed from the terminal/command line: # Windows: # pip install pandas # Mac and Linux: # pip3 install pandas