blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
51407405fde33bf260053b5950891ac72af7ab2f
sean578/advent_of_code
/2015/17/17.py
1,313
3.640625
4
# import numpy as np # container_sizes = [1,2,3,4,5,6,7,8,9] # eggnog_total = 10 container_sizes = [ 33, 14, 18, 20, 45, 35, 16, 35, 1, 13, 18, 13, 50, 44, 48, 6, 24, 41, 30, 42 ] eggnog_total = 150 # print(container_sizes[0]) # print(np.array([] + [container_sizes[0]])) def recursive_combinations(sizes, target, comb, count, min_size): if sum(comb) == target: if len(comb) <= min_size: min_size = len(comb) print('a combination is:', comb, sum(comb)) count = count + 1 return count, min_size # Found a combination if sum(comb) > target: return count, min_size # No way to sum to target # Now we create a new combination to try for i in range(len(sizes)): partial = comb + [sizes[i]] rest_of_array = sizes[i+1:] # print(partial) # print(rest_of_array) count, min_size = recursive_combinations(rest_of_array, target, partial, count, min_size) return count, min_size if __name__ == "__main__": count, min_size = recursive_combinations(container_sizes, eggnog_total, [], 0, 999) count, min_size = recursive_combinations(container_sizes, eggnog_total, [], 0, min_size) print(count, min_size)
9be85856d86283513d6a6e5c4c24caddea318313
pedrolgcs/curso_python
/world_03/exerc/007.py
476
3.9375
4
numbers = [] for i in range(0, 5): numbers.append(int(input(f'Digite um valor para posição {i}: '))) print('=-=' * 11) print(f'O maior valor digitado foi: {max(numbers)} nas posições: ', end =' ') for i, v in enumerate(numbers): if v == max(numbers): print(f'{i}', end = ' ') print(f'\nO menor valor digitado foi: {min(numbers)} nas posições: ', end = ' ') for i, v in enumerate(numbers): if v == min(numbers): print(f'{i}', end = ' ') print(numbers)
0f2cc76b8e6fd6218bb60be0c8d744f90c5a1075
devionncode/projetos_poo
/Produto/produto_regra.py
398
3.640625
4
from produto import Produto class ProdutoRegra: def cadastrar(self): print('\n=========CADASTRO PRODUTO===========') nome = input('Informe o nome: ') marca = input('Informa a marca: ') quantidade = float(input('Informe a quantidade: ')) valor = float(input('Informe o valor: ')) produto_novo = Produto(nome, marca, quantidade, valor)
bb83ef35310b96c8f8c682f16253f42aa5ec832e
cwjshen/dailycodingproblems
/python/12-staircase-climb.py
2,108
4.28125
4
# This problem was asked by Amazon. # There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. # Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. # For example, if N is 4, then there are 5 unique ways: # 1, 1, 1, 1 # 2, 1, 1 # 1, 2, 1 # 1, 1, 2 # 2, 2 # What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? # For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. # Global caches memo_dict = {1:1,2:2} memo_dict_var = {} def staircase_ways_rec(n): if n < 1: return 0 elif n == 1: return 1 elif n == 2: return 2 else: return staircase_ways_rec(n-1) + staircase_ways_rec(n-2) def staircase_ways_dp(n): if n < 1: return 0 else: if n-2 not in memo_dict: memo_dict[n-2] = staircase_ways_dp(n-2) if n-1 not in memo_dict: memo_dict[n-1] = staircase_ways_dp(n-1) return memo_dict[n-1] + memo_dict[n-2] def staircase_ways_variable_steps_rec(n, xs): if xs == None: return 0 if n < 1: return 0 elif n < min(xs): return 0 else: sum = 0 if (n in xs): sum += 1 for x in xs: sum += staircase_ways_variable_steps_rec(n-x, xs) return sum def staircase_ways_variable_steps_dp(n, xs): if xs == None: return 0 if n < 1: return 0 elif n < min(xs): return 0 else: sum = 0 if (n in xs): sum += 1 for x in xs: if n-x not in memo_dict_var: memo_dict_var[n-x] = staircase_ways_variable_steps_dp(n-x, xs) sum += memo_dict_var[n-x] return sum # print(staircase_ways_rec(35)) # print(staircase_ways_dp(7)) print([staircase_ways_variable_steps_dp(x, [1,3,5]) for x in range(20)]) # print(staircase_ways_variable_steps_rec(35, [1,3,5])) # print(staircase_ways_variable_steps_dp(4, [1,3,5]))
cbfccff814c8d4226fe30b28feda59450d2dcca8
bibongbong/pythonCookBook
/src/8.13.ImplimentDataModelTypeConstraint.py
1,906
3.890625
4
''' 想定义某些在属性赋值上面有限制的数据结构。 所以需要自定义属性赋值函数,可以使用描述器 ''' class Descriptor: def __init__(self, name=None, **opts): print(name) print(opts) self.name = name for key , value in opts.items(): setattr(self, key, value) def __set__(self, instance, value): instance.__dict__[self.name] = value # Descriptor for enforcing types class Typed(Descriptor): expected_type = type(None) def __set__(self, instance, value): if not isinstance(value, self.expected_type): raise TypeError('expected' + str(self.expected_type)) super().__set__(instance, value) # Descriptor for enforcing values class Unsigned(Descriptor): def __set__(self, instance, value): if value < 0: raise ValueError('Expected >=0') super().__set__(instance, value) class Integer(Typed): expected_type = int class Float(Typed): expected_type = float class UnsignedFloat(Float, Unsigned): pass class UnsignedInteger(Integer,Unsigned): pass ''' 也有8.9的装饰器,来完成这个功能。更灵活更高明 ''' #Decorator for applying type checking def Typed(expected_type, cls=None): print('1') if cls is None: print('2') return lambda cls: Typed(expected_type, cls) print('3') super_set = cls.__set__ def __set__(self, instance, value): print('4') if not isinstance(value, expected_type): raise TypeError('expected ' + str(expected_type)) super_set(self, instance, value) print('5') cls.__set__ = __set__ return cls # Decorator for unsigned values def Unsigned(cls): super_set = cls.__set__ def __set__(self, instance, value): if value < 0: raise ValueError('Expected >= 0') super_set(self, instance, value) cls.__set__ = __set__ return cls # Specialized descriptors @Typed(int) class Integer(Descriptor): pass @Unsigned class UnsignedInteger(Integer): pass a = Integer(1.0)
a13e974be88e7e397bfc6385b697d639ccf020f1
gayathrimahalingam/interview_code
/check_if_btree_is_bst.py
747
3.9375
4
# Implement a function to check if a binary tree is a valid binary search tree # BST - left <= root < right # An in-order traversal array should be sorted # recursively check if BST property is maintained # more optimal: have a min and max variable and check while you traverse to get a O(N) solution import os def isValidBST(root): return checkValidBST(root, None, None) def checkValidBST(root, mins, maxes): if root is None: return True if (((mins is not None) and root.data <= mins) or ((maxes is not None) and root.data > maxes)): return False if (not(checkValidBST(root.left, mins, root.data) or not(checkValidBST(root.right, root.data, maxes)))): return False return True
05ef03b1a91a1f88e959b4d320850da02d8c5224
vprusso/toqito
/toqito/state_props/sk_vec_norm.py
2,328
3.53125
4
"""Compute the S(k)-norm of a vector.""" from __future__ import annotations import numpy as np from toqito.state_ops import schmidt_decomposition def sk_vector_norm(rho: np.ndarray, k: int = 1, dim: int | list[int] = None) -> float: r""" Compute the S(k)-norm of a vector [NJDK09]_. The :math:`S(k)`-norm of of a vector :math:`|v \rangle` is defined as: .. math:: \big|\big| |v\rangle \big|\big|_{s(k)} := \text{sup}_{|w\rangle} \Big\{ |\langle w | v \rangle| : \text{Schmidt-rank}(|w\rangle) \leq k \Big\} It's also equal to the Euclidean norm of the vector of :math:`|v\rangle`'s k largest Schmidt coefficients. This function was adapted from QETLAB. Examples ======== The smallest possible value of the :math:`S(k)`-norm of a pure state is :math:`\sqrt{\frac{k}{n}}`, and is attained exactly by the "maximally entangled states". >>> from toqito.states import max_entangled >>> from toqito.state_props import sk_vector_norm >>> import numpy as np >>> >>> # Maximally entagled state. >>> v = max_entangled(4) >>> sk_vector_norm(v) 0.5 References ========== .. [NJDK09] "A Family of Norms With Applications In Quantum Information Theory" Nathaniel Johnston, David W. Kribs https://arxiv.org/abs/0909.3907 :param rho: A vector. :param k: An int. :param dim: The dimension of the two sub-systems. By default it's assumed to be equal. :return: The S(k)-norm of :code:`rho`. """ dim_xy = rho.shape[0] # Set default dimension if none was provided. if dim is None: dim = int(np.round(np.sqrt(dim_xy))) # Allow the user to enter in a single integer for dimension. if isinstance(dim, int): dim = np.array([dim, dim_xy / dim]) if np.abs(dim[1] - np.round(dim[1])) >= 2 * dim_xy * np.finfo(float).eps: raise ValueError("If `dim` is a scalar, it must evenly divide the length of the state.") dim[1] = int(np.round(dim[1])) # It's faster to just compute the norm of `rho` directly if that will give # the correct answer. if k >= min(dim): nrm = np.linalg.norm(rho, 2) else: coef, _, _ = schmidt_decomposition(rho, dim, k) nrm = np.linalg.norm(coef) return nrm
21cf5e52be746b766794ce5288fb94a153ca0d32
mgoldey/hackerrank
/ai/botclean.py
1,056
3.625
4
#!/usr/bin/python # Head ends here def next_move(posr, posc, board): def count_dirty(board): c=0 for i in board: for j in i: if j=="d": c+=1 return c def get_next(r,c,b): scope=[i for i in range(5)] for n in range(1,5): for i in range(r-n,r+n+1): for j in range(c-n,c+n+1): if i in scope and j in scope: if b[i][j]=='d': return [i,j] return -1 while count_dirty(board)!=0: dx,dy=get_next(posr,posc,board) while posr!=dx or posc!=dy: if posr>dx: posr-=1 yield("UP") elif posr<dx: posr+=1 yield("DOWN") if posc>dy: posc-=1 yield("LEFT") elif posc<dy: posc+=1 yield("RIGHT") yield("CLEAN") board[posr][posc]='-' return "" # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] print(next(next_move(pos[0], pos[1], board)))
b20b247d5da4954765473dc86624d2fce7516b33
NiceToMeeetU/ToGetReady
/Demo/DataStructre/sort_methods.py
11,544
3.5
4
# coding : utf-8 # @Time : 21/02/16 19:23 # @Author : Wang Yu # @Project : ToGetReady # @File : sort_methods.py # @Software: PyCharm import random from _TOOL import cal_time import copy class SortMethods: """ 手写排序算法 为利于不同方法对比,每种方法先设置对待排序数组的深拷贝 """ def __init__(self, nums_in): self.nums_in = nums_in @cal_time def inside_sort(self): """ python内置排序API """ nums = copy.deepcopy(self.nums_in) return sorted(nums) @cal_time def bubble_sort(self): """ 冒泡排序 遍历整数数组,如果前面的数比后面的大,则交换两个数 代码关键:趟,无序区范围 前面无序,后面有序 存在问题: 若数组本身有序,会浪费时间 """ nums = copy.deepcopy(self.nums_in) for i in range(len(nums)): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] return nums @cal_time def bubble_sort_better(self): """ 冒泡排序可以优化的点: 如果一趟中完全没有发生交换,说明数组已经有序,可直接break """ nums = copy.deepcopy(self.nums_in) exchange = False for i in range(len(nums)): for j in range(len(nums) - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] exchange = True if not exchange: return nums return nums @cal_time def select_sort(self): """ 选择排序 一趟中最小的数放首位,多趟循环 注意有序区和无序区 """ nums = copy.deepcopy(self.nums_in) for i in range(len(nums)): min_loc = i for j in range(i + 1, len(nums)): if nums[j] < nums[min_loc]: min_loc = j if min_loc != i: nums[i], nums[min_loc] = nums[min_loc], nums[i] return nums @cal_time def insert_sort(self): """ 插入排序 每次迭代从无序区挑一个数放入有序区的合适位置 """ nums = copy.deepcopy(self.nums_in) for i in range(1, len(nums)): tmp = nums[i] j = i - 1 while j >= 0 and tmp < nums[j]: nums[j + 1] = nums[j] j = j - 1 nums[j + 1] = tmp return nums @cal_time def quick_sort(self): """ 快速排序 分治策略 从左到右,从小到大 """ nums = copy.deepcopy(self.nums_in) def partition(li, left, right): tmp = li[left] while left < right: while left < right and li[right] >= tmp: # 右侧的小元素放到左侧 right -= 1 li[left] = li[right] while left < right and li[left] <= tmp: # 左侧的大元素放到右侧 left += 1 li[right] = li[left] li[left] = tmp return left def _quick_sort(li, left, right): """ 排序内迭代函数,直接按照形参传递 :param li: :param left: :param right: :return: """ if left < right: mid = partition(li, left, right) _quick_sort(li, left, mid - 1) _quick_sort(li, mid + 1, right) _quick_sort(nums, 0, len(nums) - 1) return nums @cal_time def heap_sort(self): """ 堆排序 从小到大排序构建大根堆 从大到小排序构建小根堆 """ nums = copy.deepcopy(self.nums_in) n = len(nums) def _siftdown(data, low, high): """ 向下调整函数, :param data: 整数数组 :param low: 堆根节点 :param high: 堆最后一个叶节点 :return: """ i = low j = 2 * i + 1 tmp = data[i] while j <= high: # 构建一个大根堆 if j < high and data[j] < data[j + 1]: # 单独的if切换必要的左右子节点 j += 1 if tmp < data[j]: # 只要子节点比父节点大,就交换 data[i] = data[j] i = j j = 2 * i + 1 else: # tmp>=data[j],j也已经到最下面了,说明已经是大根堆了 break # 跳出循环后i是某个可用节点,要么是已经到最后的叶节点使得j越界跳出,要么是tmp放这里可以使堆有效 data[i] = tmp # 开始排序,1-建堆,2-取数 for idx in range(n // 2 - 1, -1, -1): # (n-1)是最后一个子节点,(n-1-1)//2即最后一个有效父节点 # 从最后一个有效父节点开始往上遍历,依次调整 _siftdown(nums, idx, n - 1) for idx in range(n - 1, -1, -1): # 取数,将大根堆的根节点依次挪到数组最后,不断缩短堆的顶 nums[0], nums[idx] = nums[idx], nums[0] _siftdown(nums, 0, idx - 1) return nums @cal_time def heap_sort_inside(self): """ python内置了heapq模块,可以快速建堆 用堆实现的优先队列 :return: """ pass import heapq nums = copy.deepcopy(self.nums_in) heapq.heapify(nums) res = [heapq.heappop(nums) for _ in range(len(nums))] return res @cal_time def merge_sort(self): """ 归并排序 先考虑有序的两个数组如何归并 :return: """ nums = copy.deepcopy(self.nums_in) n = len(nums) def _merge(data, left, mid, right): i = left j = mid + 1 tmp = [] while i <= mid and j <= right: if data[i] < data[j]: tmp.append(data[i]) i += 1 else: tmp.append(data[j]) j += 1 while i <= mid: tmp.append(data[i]) i += 1 while j <= right: tmp.append(data[j]) j += 1 data[left: right+1] = tmp def _merge_sort(data, left, right): if left < right: mid = (left + right) // 2 _merge_sort(data, left, mid) _merge_sort(data, mid + 1, right) _merge(data, left, mid, right) _merge_sort(nums, 0, n - 1) return nums @cal_time def shell_sort(self): """ 简单选择gap的希尔排序示意 实际就是将插入排序加入了gap因素 :return: """ nums = copy.deepcopy(self.nums_in) d = len(nums) // 2 while d >= 1: for i in range(d, len(nums)): tmp = nums[i] j = i - d while j >= 0 and tmp < nums[j]: nums[j + d] = nums[j] j -= d nums[j + d] = tmp d //= 2 return nums @cal_time def count_sort(self, max_count = 100): """ 计数排序 即字面意思,构建一个O(n)的map映射,统计各个元素的出现次数 必须提前知道数的大小范围,且限制数据类型,空间浪费太多 :return: """ nums = copy.deepcopy(self.nums_in) counts = [0 for _ in range(max_count)] for val in nums: counts[val] += 1 nums.clear() for idx, x in enumerate(counts): for i in range(x): nums.append(idx) return nums @cal_time def bucket_sort(self, n = 100, max_num = 10000): """ 桶排序 严重取决于数据分布 :return: """ nums = copy.deepcopy(self.nums_in) buckets = [[] for _ in range(n)] for val in nums: i = min(val // (max_num//n), n - 1) buckets[i].append(val) for j in range(len(buckets[i]) - 1, 0, -1): if buckets[i][j] < buckets[i][j - 1]: # 直接在桶内排序 buckets[i][j], buckets[i][j-1] = buckets[i][j-1], buckets[i][j] else: break res = [] for bin in buckets: res.extend(bin) return res class TopK: """ TopK 问题 所有方法都需要掌握: 1、全局排序切片,O(nlogn+k) 2、局部排序,O(n*k) 3、堆方法,O(n*logk) 4、分治法 5、减治法 6、随机法 """ def __init__(self, nums_in, k): self.nums_in = nums_in self.k = k def qsort_top_k(self): """ 全局快排后取切片 :return: """ pass @cal_time def heap_top_k(self): """ 堆排序解决TopK问题 先选k个选择构建一个小根堆,然后遍历原数组更新小根堆,遍历完成即得 """ pass nums = copy.deepcopy(self.nums_in) n = len(nums) def _upsift(data, low, high): i = low j = 2 * i + 1 tmp = data[i] while j <= high: if j < high and data[j] > data[j + 1]: j += 1 if tmp > data[j]: data[i] = data[j] i = j j = i * 2 + 1 else: break data[i] = tmp heap_nums = nums[:self.k] # 构建k个元素的大根堆 for idx in range(self.k // 2 - 1, -1, -1): _upsift(heap_nums, idx, self.k - 1) # 此时栈顶已经是这k个元素的最大值了 # 遍历剩余n-k的原数组,只要比堆顶大就加入,否则略过 for idx in range(self.k, n): if nums[idx] > heap_nums[0]: heap_nums[0] = nums[idx] _upsift(heap_nums, 0, self.k - 1) # 按照从大到小输出结果 for idx in range(self.k - 1, -1, -1): heap_nums[0], heap_nums[idx] = heap_nums[idx], heap_nums[0] _upsift(heap_nums, 0, idx - 1) return heap_nums def test01(): li1 = list(range(1, 10000)) random.shuffle(li1) # print(li1) sorts = SortMethods(li1) ans0 = sorts.inside_sort() # ans1 = sorts.quick_sort() # ans2 = sorts.heap_sort() # ans3 = sorts.merge_sort() # ans4 = sorts.shell_sort() ans5 = sorts.bucket_sort(100, 10000) print(ans5[:20]) # print(ans4) if __name__ == '__main__': test01()
e17a80959d131234eb2e393b659365a94158e3fc
IanPaulDaniels/Python_CrashCourseBook
/c10 - Files and Exceptions/1004_guest_book.py
235
3.625
4
filename = 'Chapter10/guest_book.txt' while (True): user_name = input('Please enter your name: ') if user_name == 'exit': break with open(filename, 'a') as file_object: file_object.write(user_name + '\n')
b29643f293397c06496d7c672dc33430887f43c7
A-Alexander-code/150-Python-Challenges--Solutions
/Ejercicio_N049.py
422
3.859375
4
compnum = 50 cont = 1 guess = int(input("Adivina el número. Prueba ingresando uno\n")) while guess != compnum: if guess < compnum: print("El número es muy bajo. Intenta de nuevo") else: print("El número es muy alto. Intenta de nuevo") cont = cont + 1 guess = int(input("Adivina el número. Prueba ingresando uno\n")) print("¡Has adivinado el número! Te ha tomado",cont,"intentos")
6311380eaee8aa96a95b4d00e10f2eb974bdcc03
Jamye/algos_py
/misc_algo/anagram.py
837
3.796875
4
def show(str1, str2): list1 = list(str1) list2 = list(str2) list1.sort() list2.sort() pos = 0 matches = True while pos <len(str1) and matches: if list1[pos] == list2[pos]: pos = pos + 1 else: matches = False return matches def anagram_solution1(s1,s2): a_list = list(s2) pos1 = 0 still_ok = True while pos1 < len(s1) and still_ok: pos2 = 0 found = False while pos2 < len(a_list) and not found: if s1[pos1] == a_list[pos2]: found = True else: pos2 = pos2 + 1 if found: a_list[pos2] = None else: still_ok = False pos1 = pos1 + 1 return still_ok print(anagram_solution1('abcd','dcba')) print(show('dog','heart'))
7fc87241f663577c635ecd3cc7d1e471b2c389c3
Indra24710/Implementation-of-Algorithms
/Linkedlist.py
2,513
4
4
# coding: utf-8 # In[3]: class Node(): def __init__(self,value=0,next=None): self.value=value self.next=next class linked_list(): def __init__(self,head=Node(),tail=None): self.head=head self.tail=tail def addnode(self,value): node=Node() node.value=value if(self.tail!=None): self.tail.next=node self.tail=node self.tail.next=None else: self.head.next=node self.tail=node self.tail.next=None def printnode(self): q=Node() q=self.head while(q!=None): print(q.value) q=q.next def insertnode(self,value,pos): node=Node() node.value=value i=0 q=self.head while(i<pos): if i==pos-1: print("in") if q.next!=None: p=q.next q.next=node q.next.next=p break else: q.next=node q.next.next=None break elif q==None and i!=pos-1: print("Position not available") break elif q!=None: q=q.next i+=1 def deletenode(self,pos): i=0 q=self.head while(i<pos): if i==pos-2: print("in") if q.next!=None: p=q.next.next q.next.next=None q.next=None q.next=p break else: print("Position not available") break elif q==None and i!=pos-1: print("Position not available") break elif q!=None: q=q.next i+=1 def reversenode(self): prev=self.head curr=prev.next prev.next=None while curr.next!=None: nex=curr.next curr.next=prev prev=curr curr=nex continue curr.next=prev self.head=curr head=Node() head.value=1 lis=linked_list(head) lis.addnode(5) lis.addnode(6) lis.printnode() lis.insertnode(2,1) lis.printnode() lis.deletenode(2) lis.printnode() lis.reversenode() lis.printnode()
316f54bd985b3439085b85eb8017506412176f1e
BuragaIonut/SoftUni
/SoftUni Exercices/arrayrotation.py
161
3.53125
4
arr = list(map(int, input().split())) n = int(input()) for i in range(n, len(arr)): print(arr[i], end = ' ') for i in range(n): print(arr[i], end = ' ')
71c4ae5acbf348e5392556d796078ad73cbb71b6
acadien/projecteuler
/p35.py
1,358
3.75
4
#!/usr/bin/python from math import * def check_prime(x,primes): sqt=int(sqrt(x)) for i in primes: if x%i==0: return False if i>sqt: break return True def circ(x): return x[1:]+x[0] primes=list() primes.append(2) for i in range(3,1000000,2): if check_prime(i,primes): primes.append(i) newprimes=list(primes) tot=0 for i in primes: val=str(i) if len(val)>1: try: list(val).index("0") continue except ValueError: pass try: list(val).index("2") continue except ValueError: pass try: list(val).index("4") continue except ValueError: pass try: list(val).index("5") continue except ValueError: pass try: list(val).index("6") continue except ValueError: pass try: list(val).index("8") continue except ValueError: pass fnd=True for j in range(len(val)): if not(int(val) in newprimes): fnd=False break val=circ(val) if fnd: tot+=1 print tot,i #newprimes.pop(0) exit print tot
79602bd8821f8481f94372c5e33158612ce3566b
Armanious/codiff-demo
/fizzbuzz.py
345
4.0625
4
''' For all numbers in [1, n], if the number is divisible by 3, print "<number> fizz", if the number is divisible by 5, print "<number> buzz", if the number is divisible by both 3 and 5, print "<number> fizzbuzz", otherwise print "<number>" ''' def fizzbuzz(n): pass def main(): fizzbuzz(100) if __name__ == '__main__': main()
ff074451e92f4af60852bd6fde0677113512d9d3
Aniruddha019/Python_Training
/Batches/2021-Aug-22/AnanyaSaikia/Exercise_001_Python_basics.py
266
4.46875
4
""" Practice using the Python interpreter as a calculator: 1. The volume of a sphere with radius r is 4/3 * π(r^3) . What is the volume of a sphere with radius 5? """ # Write your program below radius=5 PI = 3.14 volume=4/3 * PI*(radius**3) print("output",volume)
ba16dfbf9dcce52cbb638e70c6cc0b6fb1014c1a
santhosh790/competitions
/hackerrank/decodeString.py
767
4.15625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'decodeString' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. INTEGER numberOfRows # 2. STRING encodedString # def decodeString(numberOfRows, encodedString): # Write your code here nRows = 3 value = "mnei_ya_s__m" #nRows=2 #value = "hlowrd_el_ol" rowLength = len(value)//nRows #for each in range(nRows): # print(each) final = "" for i in range(rowLength): for each in range(nRows): print(str(i+(each*rowLength)+each)) if i+(each*rowLength)+each < len(value): final = final + value[i+(each*rowLength)+each] print(final) return newVal if __name__ == '__main__':
84e84c4df3a9e4afa5eba4ed8de2b66d6971da6d
buridiaditya/Machine-Learning
/assignment1/assignment1_3.py
5,824
3.53125
4
import numpy as np import matplotlib.pyplot as pl import csv import math import pandas as pd # Linear Regression Model class LinearRegression: def __init__(self): self.W = None def predict(self,X): y_predict = X.dot(self.W) return y_predict def L2Cost(self, X, y_target,reg): cost = 0.0 N,M = X.shape grads = np.zeros(self.W.shape) scores = X.dot(self.W) cost = np.sum(np.square(scores - y_target))/N + reg * np.sum(self.W*self.W) grads = 2*X.T.dot(scores - y_target)/N + 2*self.W*reg return cost, grads def train(self,X_train, y_target,X_test,y_test, epochs=20000, learning_rate=0.05,lr_decay = 1,reg = 0.0): N,M = X_train.shape self.W = np.random.randn(M) old_cost = 0.0 for i in range(epochs): cost, dW = self.L2Cost(X_train,y_target,reg) self.W = self.W - learning_rate*dW if(math.fabs(old_cost-cost)<0.01): break; if i%100 == 0: learning_rate *= lr_decay #print("\nAccuracy after %d epochs : %f\n" %(i,np.sqrt(np.sum(np.square(self.predict(X_test)-y_test))/N)) ) print("Cost difference after %d epochs : %f" %(i,np.abs(cost-old_cost)) ) old_cost = cost # Load Data and create Training and Test data # filename = 'kc_house_data.csv' data = pd.read_csv(filename) X_y = data.as_matrix().astype('float') N,M = X_y.shape X = X_y[:,0:M-1] y_target = X_y[:,M-1] print("Shape of X : ",X.shape) print("Shape of y_target : ",y_target.shape) # Adds quadratic cubic features N,M = X.shape X_temp = np.ones((N,3*M)) X_temp[:,0:M] = X X_l = X_temp[:,0:M] X_temp[:,M:2*M] = X*X X_qa = X_temp[:,0:2*M] X_temp[:,2*M:3*M] = X*X*X X_cu = X_temp # Split data into train and test data # size_of_train = int(N*0.8) X_train_l = X_l[0:size_of_train] X_test_l = X_l[size_of_train:N] y_train = y_target[0:size_of_train] y_test = y_target[size_of_train:N] print("Shape of X_train : ", X_train_l.shape) print("Shape of X_test : ", X_test_l.shape) print("Shape of y_train : ", y_train.shape) print("Shape of y_test : ", y_test.shape) X_train_qa = X_qa[0:size_of_train] X_test_qa = X_qa[size_of_train:N] print("Shape of X_train_qa : ", X_train_qa.shape) print("Shape of X_test_qa : ", X_test_qa.shape) X_train_cu = X_cu[0:size_of_train] X_test_cu = X_cu[size_of_train:N] print("Shape of X_train_cu : ", X_train_cu.shape) print("Shape of X_test_cu : ", X_test_cu.shape) # Data Preprocessing # Zero centering and Normalizing data X_mean_l = np.mean(X_train_l,axis=0) X_max_l = np.max(X_train_l,axis=0) X_min_l = np.min(X_train_l,axis=0) X_std_l = np.std(X_train_l,axis=0) X_train_l -= X_mean_l #X_train_l /= (X_max_l-X_min_l) X_train_l /= X_std_l X_test_l -= X_mean_l X_test_l /= X_std_l #X_test_l /= (X_max_l-X_min_l) X_mean_qa = np.mean(X_train_qa,axis=0) X_max_qa = np.max(X_train_qa,axis=0) X_min_qa = np.min(X_train_qa,axis=0) X_std_qa = np.std(X_train_qa,axis=0) X_train_qa -= X_mean_qa #X_train_qa /= (X_max_qa-X_min_qa) X_train_qa /= X_std_qa X_test_qa -= X_mean_qa X_test_qa /= X_std_qa #X_test_qa /= (X_max_qa-X_min_qa) X_mean_cu = np.mean(X_train_cu,axis=0) X_max_cu = np.max(X_train_cu,axis=0) X_min_cu = np.min(X_train_cu,axis=0) X_std_cu = np.std(X_train_cu,axis=0) X_train_cu -= X_mean_cu #X_train_cu /= (X_max_cu-X_min_cu) X_train_cu /= X_std_cu X_test_cu -= X_mean_cu X_test_cu /= X_std_cu #X_test_cu /= (X_max_cu-X_min_cu) # Append column of ones to X N,M = X_train_l.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_train_l X_train_l = X_temp N,M = X_test_l.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_test_l X_test_l = X_temp N,M = X_train_qa.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_train_qa X_train_qa = X_temp N,M = X_test_qa.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_test_qa X_test_qa = X_temp N,M = X_train_cu.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_train_cu X_train_cu = X_temp N,M = X_test_cu.shape X_temp = np.ones((N,M+1)) M += 1 X_temp[:,1:M] = X_test_cu X_test_cu = X_temp model = LinearRegression() j = 0.05 lr_list = [] rmse_linear = [] rmse_sq = [] rmse_cubic = [] for i in range(15): model.train(X_train_l,y_train,X_test_l,y_test,epochs=20000,learning_rate=j) print("Trained Model Values - Linear features with %.12f lr: "%(j),model.W) rmse_linear.append(np.sqrt(np.sum(np.square(model.predict(X_test_l)-y_test))/N)) model.train(X_train_qa,y_train,X_test_qa,y_test,epochs=20000,learning_rate=j) print("Trained model values - Quadratic features with %.12f lr: "%(j),model.W) rmse_sq.append(np.sqrt(np.sum(np.square(model.predict(X_test_qa)-y_test))/N)) model.train(X_train_cu,y_train,X_test_cu,y_test,epochs=20000,learning_rate=j) print("Trained Model Values - Cubic features with %.12f lr: "%(j),model.W) rmse_cubic.append(np.sqrt(np.sum(np.square(model.predict(X_test_cu)-y_test))/N)) lr_list.append(j) j /= 2 pl.semilogx(lr_list,rmse_linear,'-',label="Linear") pl.semilogx(lr_list,rmse_sq,'-',label="Quadratic") pl.semilogx(lr_list,rmse_cubic,'-',label="Cubic") pl.xlabel("learning rate") pl.ylabel("RMSE") pl.title("RMSE-Performance of various features vs learning rates") pl.legend() pl.show() """ cost_data = np.array(model.train(X_train_l,y_train,X_test_l,y_test)) cost_data_sq = np.array(model.train(X_train_qa,y_train,X_test_qa,y_test)) cost_data_cu = np.array(model.train(X_train_cu,y_train,X_test_cu,y_test)) axes = pl.gca() #axes.set_ylim(0,1000) pl.plot(range(cost_data.shape[0]),cost_data,'-',label="Linear") pl.plot(range(cost_data_sq.shape[0]),cost_data_sq,'-',label="Square") pl.plot(range(cost_data_cu.shape[0]),cost_data_cu,'-',label="Cubic") pl.title("cost vs epochs") pl.legend() pl.show() """
81749fdc9e50110f8c38100775cd348e72fdae44
southpawgeek/perlweeklychallenge-club
/challenge-156/eric-cheung/python/ch-2.py
2,501
4.125
4
## Remarks ## https://www.geeksforgeeks.org/weird-number/ ## Python 3 Program to Check if the Number is Weird or not from math import sqrt ## Code to Find all the Factors of the Number Excluding the Number itself def factors(n): ## Vector to Store the Factors v = [] v.append(1) ## Note that this Loop runs till sqrt(n) for i in range(2, int(sqrt(n)) + 1, 1): ## if the value of i is a factor if (n % i == 0): v.append(i); ## Condition to Check the Divisor is not the Number itself if (int(n / i) != i): v.append(int(n / i)) # return the vector return v ## Function to check if the number is Abundant or not def checkAbundant(n): sum = 0 ## Find the Divisors Using Function v = factors(n) ## Sum All the Factors for i in range(len(v)): sum = sum + v[i] ## Check for Abundant or Not if (sum > n): return True return False ## Function to Check if the Number is Semi-Perfect or not def checkSemiPerfect(n): ## find the divisors v = factors(n) ## sorting the vector v.sort(reverse = False) r = len(v) ## subset to check if no is semiperfect subset = [[0 for i in range(n + 1)] for j in range(r + 1)] ## initialising 1st column to true for i in range(r + 1): subset[i][0] = True ## Initialing 1st Row Except Zero Position to 0 for i in range(1, n + 1): subset[0][i] = False ## Loop to Find Whether the Number is Semiperfect for i in range(1, r + 1): for j in range(1, n + 1): ## Calculation to check if the Number can be made by Summation of Divisors if (j < v[i - 1]): subset[i][j] = subset[i - 1][j] else: subset[i][j] = (subset[i - 1][j] or subset[i - 1][j - v[i - 1]]) ## If not possible to make the Number by any combination of Divisors if ((subset[r][n]) == 0): return False return True ## Function to check for Weird or Not def checkweird(n): if (checkAbundant(n) and not checkSemiPerfect(n)): return True return False # Driver Code if __name__ == '__main__': ## n = 12 ## Example 1: n = 70 ## Example 2: if (checkweird(n)): print("Weird Number") else: print("Not Weird Number") ## This code is contributed by Surendra_Gangwar
d2863b70f2656b166522b682921b8a886c5b3b1f
daniel-reich/turbo-robot
/cvA35yPFAggr7rtve_3.py
2,459
4.25
4
""" This is a sequel to [part #1](https://edabit.com/challenge/9yk63KrKDHzNFWKBJ), with the same setup, but a different goal. A folder system on a computer might look something like the picture below: ![](https://edabit-challenges.s3.amazonaws.com/folders_smaller.png) In this challenge, folder systems will be represented by dictionaries where the keys are folders `X` and the value at `X` is the list of subfolders of `X`. For example, the picture above becomes the dictionary: { "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] } The inputs for this challenge will be: * A dictionary representing a folder system. * Two folders `X` and `Y`. Write a function that finds the "smallest" folder containing both `X` and `Y` (in the illustration, this is the lowest folder for which you can travel down to both `X` and `Y`; or, if you view the system as a "family tree", this is the last common ancestor). ### Examples last_ancestor({ "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] }, "B", "C") ➞ "A" last_ancestor({ "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] }, "I", "J") ➞ "G" last_ancestor({ "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] }, "I", "K") ➞ "D" last_ancestor({ "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] }, "D", "I") ➞ "D" last_ancestor({ "A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G", "H"], "G": ["I", "J"], "H": ["K"] }, "G", "G") ➞ "G" ### Notes * All the examples above use the folder system in the illustration, but the tests will use other folder systems as well. * For the purposes of this challenge, any folder is inside itself, as in the last two examples. """ def last_ancestor(folders, X, Y): parents = {u:k for k,v in folders.items() for u in v} u = [v for v in parents.values() if v not in parents.keys()][0] parents[u] = "#" print(parents) while X in parents.keys(): y = Y while y in parents.keys(): if parents[y] == X or y == X: return X y = parents[y] X = parents[X]
779ea6c55e24de7efe2ae621f4cd4ab7e9f758d2
daniel-reich/ubiquitous-fiesta
/PYEuCAdGJsRS9AABA_6.py
1,121
3.703125
4
class CoffeeShop: orders=[] def __init__(self, name, menu, orders): self.name=name self.menu=menu self.orders=orders def add_order(self, item): M=[x['item'] for x in self.menu] if item in M: self.orders.append(item) return "Order added!" else: return "This item is currently unavailable!" def fulfill_order(self): if self.orders: return "The {} is ready!".format(self.orders.pop(0)) else: return "All orders have been fulfilled!" def list_orders(self): return self.orders def due_amount(self): s=0 for x in self.orders: for y in self.menu: if y['item']==x: s+=y['price'] return round(s,2) def cheapest_item(self): A=[] for y in self.menu: A.append((y['item'],y['price'])) if A: return sorted(A, key=lambda x: x[1])[0][0] def drinks_only(self): B=[] for y in self.menu: if y['type']=="drink": B.append(y['item']) return B def food_only(self): B=[] for y in self.menu: if y['type']=="food": B.append(y['item']) return B
94636b52579ddef3e7e2fb499f019ea6445131cb
destefano1986/ClassLearning
/ClassLearning.py
1,838
3.71875
4
# 1. Class/Instance/Attribute/self/property # 2. Hook/Magic method => Operator Override/__init__/__str__/__call__ # 3. Inherit/多根/单根 class A(object): aField = ['TestAField'] def aMethod(self): print(self.aField) print('TestAMethod') birthday = 1983 @property def age(self): return 2018 - self.birthday # # aInstance = A() # bInstance = A() # aInstance.aField.append('test') # aInstance.aField = 'test' # # print(id(A), id(aInstance), id(aInstance.__class__)) # print(A.aField) # print(aInstance.aField) # print(bInstance.aField) # # aInstance.aMethod() # aInstance.__class__.aMethod(aInstance) # A.aMethod(aInstance) # # aInstance.aField = 'NewField' # aInstance.aMethod() # A.aMethod(aInstance) # bInstance.aMethod() # A.aMethod(bInstance) # # print(aInstance.age) # # print(3 + 5) # print((3).__class__.__add__(3, 5)) # # class Person(object): # def __init__(self, name, age): # self.name = name # self.age = age # def __str__(self): # return '<Person::%s>' % self.name # def greeting(self): # print('[%s]:: Hi~' % self.name) # # zhangsan = Person() # zhangsan.name = 'Zhang San' # lisi = Person() # lisi.name = 'Li Si' # zhangsan = Person('Zhang San', 42) # lisi = Person('Li Si', 23) # print(str(zhangsan), lisi) # zhangsan.greeting() # lisi.greeting() # # def addN(n): # def add(x): # return x+n # return add # # class addN(object): # def __init__(self, n): # self.n = n # def __call__(self, x): # return x+self.n # # add3 = addN(3) # add4 = addN(4) # print(add3(42)) # print(add4(42)) # # class Name(str): # def getLastName(self): # return self.split()[-1] # # zhangsan = Name('Zhang San') # print(len(zhangsan)) # print(zhangsan.getLastName()) # print(zhangsan.split())
2c1b3fd327c5b326fd66ba5eb8dc5657f3865913
ChocolatePadmanaban/Learning_python
/Day7/part_11.py
401
3.890625
4
# milti dimenstional element finding(find the location of first occurance) A= [[1,2],[2,[5,6]],3] def Extract(a, e): for i in a: b = [a.index(i)] if i == e: print(i) break elif type(i) == list and Extract(i,e) != None: c = Extract(i,e) b = b + Extract(i,e) else: break return b print(Extract(A, 1))
8fe1fa799fd5cfba0909da8dd7bc787c1ccd8938
Houchaoqun/Daily-Coding
/python_numpy/timer.py
1,018
4.0625
4
# -*- encoding: utf-8 -*- ''' author: hcq date: 20170713 what is it for: 1. To calculate time that the program cost. 2. To know how the class works. 1) timer = ElapsedTimer() // class ElapsedTimer(object): 2) def __init__(self): // __init__ function run once you new an object of class ElapsedTimer() 3) other funciton(elapsed or elapsed_time) run when you called them. ''' import numpy as np import time class ElapsedTimer(object): def __init__(self): self.start_time = time.time() def elapsed(self,sec): if sec < 60: return str(sec) + " sec" elif sec < (60 * 60): return str(sec / 60) + " min" else: return str(sec / (60 * 60)) + " hr" def elapsed_time(self): print("Elapsed: %s " % self.elapsed(time.time() - self.start_time) ) if __name__ == '__main__': timer = ElapsedTimer() step_num = 100 _sum = 1 for i in range(step_num): _sum *= 2 print(_sum) timer.elapsed_time()
687e2a96ae9118d248e2d084d18af0cfb1b3771b
mattjp/leetcode
/practice/easy/0069-Sqrt.py
598
3.65625
4
class Solution: """ SLOW BUT PASSES: def mySqrt(self, x: int) -> int: y = 1 while y * y <= x: y += 1 return y-1 """ def mySqrt(self, x: int) -> int: def binarySearch(l, r, x): if l > r: return r m = (l + r) // 2 if (m * m) > x: return binarySearch(l, m-1, x) elif (m * m) < x: return binarySearch(m+1, r, x) else: return m return binarySearch(0, x, x)
fbb10a91a8efddf7a6ca32532ab4e88cacd1c5f5
ivanromanv/manuales
/Python/DataCamp/Intro to Python for Data Science/Excercises/E23_Familiar functions.py
793
4.4375
4
# Out of the box, Python offers a bunch of built-in functions to make your life as a data scientist easier. You already know two such functions: print() and type(). You've also used the functions str(), int(), bool() and float() to switch between data types. These are built-in functions as well. # Calling a function is easy. To get the type of 3.0 and store the output as a new variable, result, you can use the following: # result = type(3.0) # The general recipe for calling functions and saving the result to a variable is thus: # output = function_name(input) # # Create variables var1 and var2 var1 = [1, 2, 3, 4] var2 = True # Print out type of var1 print(type(var1)) # Print out length of var1 print(len(var1)) # Convert var2 to an integer: out2 out2 = int(var2) print(out2)
f6f6cfcd9256c0ff0b8a348433a8b3f808187733
m-sterling/Advent-of-Code-2020
/code/day12.py
2,505
3.71875
4
def main(): with open('../inputs/day12', 'r') as f: src = [line.strip() for line in f.read().split('\n') if line] print(part1(src)) print(part2(src)) def part1(src): # ship x, ship y: east/south = positive, west/north = negative # ship direction: N = 0, E = 1, S = 2, W = 3 x, y, d = 0, 0, 1 for line in src: # separate the instruction from the value letter = line[0] number = int(line[1:]) # N/S/E/W are direct coordinate translations if letter == 'N': y -= number elif letter == 'S': y += number elif letter == 'E': x += number elif letter == 'W': x -= number # L/R rotate the ship; 90deg clockwise = one direction increase # also, Python always makes negative numbers positive when used as the dividend elif letter == 'L': d -= int(number / 90) % 4 elif letter == 'R': d += int(number / 90) % 4 # use the direction to move that way elif letter == 'F': if d%4 == 0: y -= number elif d%4 == 1: x += number elif d%4 == 2: y += number elif d%4 == 3: x -= number # Manhattan distance = absolute value of x plus absolute value of y return abs(x) + abs(y) def part2(src): # ship x and y - signs are the same as in part 1 sx, sy = 0, 0 # waypoint x and y - again, signs are same wx, wy = 10, -1 for line in src: letter = line[0] number = int(line[1:]) # these four remain unchanged, though they affect the waypoint instead if letter == 'N': wy -= number elif letter == 'S': wy += number elif letter == 'E': wx += number elif letter == 'W': wx -= number # L/R rotates the waypoint around the ship; rotating clockwise = swapping x/y and swapping sign of the new y elif letter == 'L': for i in range(int(number / 90) % 4): wx, wy = wy, -wx elif letter == 'R': for i in range(int(number / 90) % 4): wx, wy = -wy, wx # F teleports the ship to the waypoint's position `number` times elif letter == 'F': sx += wx*number sy += wy*number # again, get Manhattan distance return abs(sx) + abs(sy) main()
a6500c12434556b37545f32fb06322fab575a845
shomayon/Twitter
/Sentiment Analysis2/sentiment_ANA.py
3,000
3.5
4
from textblob import TextBlob import re from credentials import * import tweepy import pandas as pd import numpy as np # For plotting and visualization: from IPython.display import display import matplotlib.pyplot as plt #import seaborn as sns #%matplotlib inline def twitter_setup(): # Authentication and access using keys: auth = tweepy.OAuthHandler('GwpuXi1ZMyc0ATSb3FEPaTyOU', '0Y1jaPrDOa0uGsxQc4DSDphRWPPYCtVZ0TtvgZorAvzywIZtXJ') auth.set_access_token('220846580-ZUElx1lLAd5XRxrL9hYVG6CBkbjLUl3ftvCGIMqE', 'WEFkSeH59z92ptB76tGKnh8l6mMKmWN1fVKqV6dYCuc77') # Return API with authentication: api = tweepy.API(auth) return api extractor = twitter_setup() # create a tweet list as follows: tweets = extractor.user_timeline(screen_name="shideh66", count=50) print(tweets) # We print the most recent 100 tweets: print("100 recent tweets:\n") for tweet in tweets[:10]: print(tweet.text) print() # create a pandas dataframe as follows: data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets']) # display the first 100 elements of the dataframe: display(data.head(100)) data['len'] = np.array([len(tweet.text) for tweet in tweets]) data['ID'] = np.array([tweet.id for tweet in tweets]) data['Date'] = np.array([tweet.created_at for tweet in tweets]) data['Source'] = np.array([tweet.source for tweet in tweets]) data['Likes'] = np.array([tweet.favorite_count for tweet in tweets]) data['RTs'] = np.array([tweet.retweet_count for tweet in tweets]) display(data.head(100)) # extract the mean of lenghts: mean = np.mean(data['len']) print("The lenght's average in tweets: {}".format(mean)) tlen = pd.Series(data=data['len'].values, index=data['Date']) tlen.plot(figsize=(16,4), color='r') plt.show() # def clean_tweet(tweet): ''' clean the text in a tweet by removing links and special characters using regex. ''' return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split()) def analize_sentiment(tweet): ''' Utility function to classify the polarity of a tweet using textblob. ''' analysis = TextBlob(clean_tweet(tweet)) if analysis.sentiment.polarity > 0: return 1 elif analysis.sentiment.polarity == 0: return 0 else: return -1 # create a column with the result of the analysis: data['SA'] = np.array([ analize_sentiment(tweet) for tweet in data['Tweets'] ]) # display the updated dataframe with the new column: display(data.head(100)) # construct lists with classified tweets: pos_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] > 0] neu_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] == 0] neg_tweets = [ tweet for index, tweet in enumerate(data['Tweets']) if data['SA'][index] < 0] print("Percentage of positive tweets: {}%".format(len(pos_tweets)*100/len(data['Tweets']))) print("Percentage of neutral tweets: {}%".format(len(neu_tweets)*100/len(data['Tweets']))) print("Percentage de negative tweets: {}%".format(len(neg_tweets)*100/len(data['Tweets'])))
3fdaed348fb61dd811312395ae63d685b5b920a9
AdamZhouSE/pythonHomework
/Code/CodeRecords/2419/60628/267143.py
218
3.5
4
def differenceOfProductAndSum(n): s = 0 prod = 1 while (n > 0): r = n % 10 n //= 10 prod *= r s += r return prod - s n = int(input()) print(differenceOfProductAndSum(n))
7e3cbb65613d5a9d7446da7e8fe8e59ef9268900
bendog/shecodes_RonakReyhani_shecodes-week-6-task-1
/survey.py
2,166
3.6875
4
from question import Question from section import Section from keep_answers import answer_dictionary class Survey: # define survey parameters : title, description, sections def __init__(self, title, description, qualify_questions, survey_sections): self.title = title self.description = description self.qualify_questions = qualify_questions # self.survey_sections = [] self.survey_sections = survey_sections # @bendog - survey sections were never assigned, this might have caused some troubles def ask_if_wants_to_continue(self): while True: user_answer = input('Do you want to continue with survey?Enter yes/no to continue. ').lower() # Check if answer if user_answer == 'yes': return True # @bendog return True to end the loop elif user_answer == 'no': print('Appreciate you time.\nExiting.') return False # @bendog return False to end the loop in the negative else: print('Invalid input.') # check if user answer for qualify question is yes then make a list of questions and compare with section qualify question list. def survey_introduction(self): print(f'============================ {self.title} ============================\n') print(f'{self.description}\n\n') if self.ask_if_wants_to_continue(): # @bendog this is now an if statement to check if the user wants to continue for section in self.survey_sections: if section.ask_qualify_question(): # has error # ask how can I get the qualify list of section in servey??? # @bendog - i've moved the ask_qualifying_question to the section, i did this because the qualifying question is part of the section. # also the reason you might have been having trouble is that there is only one qualifying_question, and so it is not in a list. # the code here was expecting it to be a list, so it wasn't working. section.run_section()
f50f1b6b127eb4b225b698d76e96ff59b418d964
jkbstepien/ASD-2021
/graphs/bfs_adj_list.py
799
3.96875
4
from queue import Queue def bfs(graph, s): """ Breadth First Seach algorithm. Prints vertexes in visited order. :param graph: representation of a graph as adjacency list. :param s: starting vertex. """ visited = [] queue = Queue() visited.append(s) queue.put(s) i = 0 while not queue.empty(): u = queue.get() print(u, end=" ") for neigh in graph[i]: if neigh not in visited: visited.append(neigh) queue.put(neigh) i += 1 if __name__ == "__main__": neigh_list = [[1, 2, 7], [3, 4, 0], [5, 6, 0], [1], [1], [2], [2], [0]] bfs(neigh_list, 0)
bfc1ca63e41c9261dd6917265ba200eae503e55d
amalietm/exam_coding_1
/Amalie_M_week_7_2.py
362
3.921875
4
# Implement a Random Walker using Turtle Graphics from turtle import Turtle from random import choice t = Turtle() t.hideturtle() t.pensize(6) t.speed(7) directions = [0, 90, 180, 270] #angles turtle can rotate i = 0 while i < 200: t.setheading(choice(directions)) #direction of turtle - default right, if 90 then up t.forward(20) i += 1
dea29a16200741d8fb6275cfc9428a8452cdee54
tinselcity/experiments
/lc/find_duplicate_number.py
542
3.71875
4
#!/usr/bin/env python3 class Solution: @staticmethod def findDuplicate(nums: list[int]) -> int: slow = 0 fast = 0 while True: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break slow2 = 0 while True: slow = nums[slow] slow2 = nums[slow2] if slow == slow2: break return slow l_list = [1,3,4,2,2] l_res = Solution.findDuplicate(l_list) print('{}: result: {}'.format(l_list, l_res)) l_list = [3,1,3,3,2] l_res = Solution.findDuplicate(l_list) print('{}: result: {}'.format(l_list, l_res))
8d64e2d957ede9616426698fa47cf59e5a52b195
filius-fall/py_prac
/python/test1.py
124
3.59375
4
# def f(*args): # k = list(args) # print(k) # f(1,2,3,4,5) d = {2:["a","b","c"],"3":["d","e","f"]} print(d[2][0])
e58f586e9a2d761b16919288982efa919136ab5d
andytwigg/algorithms
/mergesort.py
428
3.84375
4
import utils # mergesort def mergesort(A): n=len(A) if (n<=1): return A L=mergesort(A[0:n/2]) R=mergesort(A[n/2:n]) return merge(L,R) def merge(L,R): A = [] i=0 j=0 while (i<len(L) and j<len(R)): if (L[i] <= R[j]): A.append(L[i]) i=i+1 else: A.append(R[j]) j=j+1 # check for any leftovers if (i<len(L)): for k in L[i:]: A.append(k) if (j<len(R)): for k in R[j:]: A.append(k) return A
90469d839453703257937a60a98e96d415f0e465
ammedmar/simplicial_operators
/simplicial_operators/_utils.py
1,485
3.625
4
from itertools import combinations, product, chain, permutations from math import floor def partitions(n, k, smallest_value=1, largest_value=None, ordered=False): '''n is the integer to partition and k is the length of partitions. It returns all k tuples of integers greater or equal to smallest_value and less than or equal to largest_value that add to to n. If ordered == True it returns all tuples if False it returns those in non-decreassing order ''' if largest_value == None: largest_value = n def unordered_partitions(n,k,l=smallest_value, m=largest_value): if k == 1: if l <= n <= m: yield (n,) return for i in range(l,m+1): for result in unordered_partitions(n-i,k-1,i,m): yield (i,)+result if ordered: return chain.from_iterable(set(permutations(p)) for p in unordered_partitions(n,k)) if not ordered: return unordered_partitions(n,k) def harmonic_partitions(n,k,smallest_value=1): '''returns tuple (a_1,...,a_k) of non-negative integer greater than or equal to smallest_value such that a_1 + 2a_2 + ... + ka_k = n''' if k == 1: if n >= smallest_value: yield (n,) return for i in range(smallest_value, floor(n/k)+1): for result in harmonic_partitions(n-(k*i), k-1, smallest_value): yield (i,)+result
64f64f36d0f5bef400e59ae80900dc29d56b7521
DudkoMatt/PhysicsProjectSpring2021
/mixing.py
3,374
3.546875
4
import math import scipy.optimize import numpy as np def mix_it_2(first_color: list[float], second_color: list[float], first_color_part, second_color_part) -> list[float]: """ :param first_color: first color to be mixed :param second_color: second color to be mixed color list represents normalised from 0 to 1 intensity of wavelength :param first_color_part: part of first color :param second_color_part: part of second color Part are numbers, so that mixing will be in first_color_part : second_color_part proportion :return: list of intensity normalised from 0 to 1 of mixed color """ _all = first_color_part + second_color_part first = first_color_part / _all second = second_color_part / _all result = [] assert len(first_color) == len(second_color) for i in range(0, len(first_color)): mixed = (first_color[i] ** first) * (second_color[i] ** second) result.append(mixed) return result def mix_it(colors: list[list[float]], colors_parts: list[float]) -> list[float]: """ :param colors: list of colors to mix color list represents normalised from 0 to 1 intensity of wavelength :param colors_parts: list of parts of each color For example colors = ['red', 'green', 'blue'], colors_parts = [1, 2, 3] In the result will be 1/6 of red 2/6=1/3 of green 3/6=1/2 of blue :return: list of intensity normalised from 0 to 1 of mixed color """ for idx in range(len(colors_parts)): if colors_parts[idx] <= 0: colors_parts[idx] = 0 total = sum(colors_parts) part_coefficients = list(map(lambda _x: _x / total, colors_parts)) result = [1] * len(colors[0]) # Check all lengths of colors for color_idx in range(len(colors) - 1): assert len(colors[color_idx]) == len(colors[color_idx + 1]), "Lengths of specters does not match" for _i in range(0, len(colors)): for _j in range(0, len(colors[_i])): result[_j] *= colors[_i][_j] ** part_coefficients[_i] return result def spectrum_diff(first_spectrum: list[float], second_spectrum: list[float]) -> float: assert(len(first_spectrum) == len(second_spectrum)) return math.sqrt(sum([(first_spectrum[_i] - second_spectrum[_i]) ** 2 for _i in range(len(first_spectrum))])) def analyze_color(base_colors_spectrum: list[list[float]], color_to_analyze: list[float]) -> list[float]: """ Main function to analyze unknown color :param base_colors_spectrum: spectrum of base colors to mix :param color_to_analyze: spectrum of color to analyze :return: proportion coefficients to mix base colors """ colors_parts_coefficients = np.array([1] * len(base_colors_spectrum)) def function_to_optimize(k_coefficients: np.array): current_calculated_color = mix_it(base_colors_spectrum, k_coefficients) return spectrum_diff(current_calculated_color, color_to_analyze) * len(list(filter(lambda _x: _x > 0, k_coefficients))) result = scipy.optimize.minimize(function_to_optimize, colors_parts_coefficients, bounds=scipy.optimize.Bounds([0] * len(base_colors_spectrum), [np.inf] * len(base_colors_spectrum))) minimum = min(filter(lambda _x: _x > 0, result.x)) return list(map(lambda element: round(element / minimum, 5), result.x))
74985a14ebffad1cad5be8d1e781ee67b36564b4
jdrnd/CTCI
/ch1/1-7.py
495
3.765625
4
def rotate_90_right(matrix): size = len(matrix) print(size) new_matrix = [[0 for x in range(size)] for y in range(size)] for i in range(0, size): row = matrix[i] for j in range(0, size): new_matrix[j][size - 1 - i] = matrix[i][j] return new_matrix def rotate_90_right_inplace(matrix): size = len(matrix) test_matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] print(rotate_90_right(test_matrix))
289e0394891ad5c7c706664abf31daa621278276
vishrutjai/Codechef
/TSORT.py
92
3.5
4
a = input() l = [] for x in range(a): l.append(input()) l.sort() for y in l: print y
c4a9c608bca90daa3c56336b5d50cc0a20fa2f2e
developyoun/AlgorithmSolve
/solved/16727.py
253
3.6875
4
p1, s1 = map(int, input().split()) s2, p2 = map(int, input().split()) if [p1, p2] == [s2, s1]: print("Penalty") elif p1+p2 == s1+s2: print('Persepolis' if s1 < p2 else 'Esteghlal') else: print('Esteghlal' if p1+p2 < s1+s2 else 'Persepolis')
4970ca102bc967e7f3d6e3ea98ec71daa8bba5e5
GabrielSalazar29/Exercicios_em_python_udemy
/Exercicios Seção 07 parte 1/ex016.py
943
4
4
""" Faça um programa que leia um vetor de 5 posições para números reais e, depois, um código inteiro. Se o código for zero, finalize o programa; se for 1, mostre o vetor na ordem direta; se for 2, mostre o vetor na ordem inversa. Caso, o código for diferente de 1 e 2 escreva uma mensagem informando que o código é inválido. """ vetor = [] for c in range(5): vetor.append(float(input(f"Digite o numero da posição {c}: "))) while True: print("=" * 20) op = int(input("Digite 0 para sair.\n" "Digite 1 para mostrar o vetor na ordem direta.\n" "Digite 2 para mostrar o vetor na ordem inversa.\n" "OPÇÃO: ")) print("=" * 20) if op == 0: print("Encerrando...") break elif op == 1: vetor.sort() print(vetor) elif op == 2: vetor.reverse() print(vetor) else: print("O código é inválido")
7c7b67dbf65d83a989c1850aa232f3a97d152964
jbaker8935/analyzing-the-new-york-subway-dataset
/ProjectFiles/project_4/exercise_2/data_visualization.py
2,730
4.4375
4
import pandas as pd from ggplot import * import pandasql import datetime def plot_weather_data(turnstile_weather): ''' Use ggplot to make another data visualization focused on the MTA and weather data we used in assignment #3. You should make a type of visualization different than you did in exercise #1, and try to use the data in a different way (e.g., if you made a lineplot concerning ridership and time of day in exercise #1, maybe look at weather and try to make a histogram in exercise #2). You should feel free to implement something that we discussed in class (e.g., scatterplots, line plots, or histograms) or attempt to implement something more advanced if you'd like. Here are some suggestions for things to investigate and illustrate: * Ridership by time of day or day of week * How ridership varies based on Subway station * Which stations have more exits or entries at different times of day If you'd like to learn more about ggplot and its capabilities, take a look at the documentation at: https://pypi.python.org/pypi/ggplot/ You can check out: https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv To see all the columns and data points included in the turnstile_weather dataframe. However, due to the limitation of our Amazon EC2 server, we are giving you about 1/3 of the actual data in the turnstile_weather dataframe ''' #plot = ggplot(turnstile_weather, aes('EXITSn_hourly', 'ENTRIESn_hourly')) + stat_smooth(span=.15, color='black', se=True)+ geom_point(color='lightblue') + ggtitle("MTA Entries By The Hour!") + xlab('Exits') + ylab('Entries') df=turnstile_weather df.is_copy = False df['DOW']=df['DATEn'].apply(lambda x: datetime.datetime.strptime(x,'%Y-%m-%d').weekday()) df.rename(columns = lambda x: x.replace(' ', '_').lower(), inplace=True) q = """ select dow, hour, sum(entriesn_hourly) as entries from df Group By dow, hour order by entries desc; """ dr = pandasql.sqldf(q, locals()) plot = ggplot(dr,aes(x='hour',y='entries', fill='dow'))+geom_histogram(stat='bar') return plot if __name__ == "__main__": image = "plot.png" input_filename = r'D:\Users\johnbaker\Desktop\NanoDegree\P1-AnalyzingTheNYCSubwayDataset\intro_to_ds_programming_files\project_4\exercise_1\turnstile_data_master_with_weather.csv' with open(image, "wb") as f: turnstile_weather = pd.read_csv(input_filename) turnstile_weather['datetime'] = turnstile_weather['DATEn'] + ' ' + turnstile_weather['TIMEn'] gg = plot_weather_data(turnstile_weather) ggsave(f, gg, format='png')
6d89785ee00387c05b6a1f1e0e1c10cd1e2f7e17
JieFrye/leetcode
/StackandQueue/OnlineStockSpan.py
1,268
3.96875
4
# Write a class StockSpanner which collects daily price quotes for some stock, # and returns the span of that stock's price for the current day. # The span of the stock's price today is defined as the maximum number of # consecutive days (starting from today and going backwards) # for which the price of the stock was less than or equal to today's price. from collections import deque class StockSpanner: def __init__(self): ''' use stack to order prices in DESC, (price, span) ''' self.s = deque() def next(self, price: int) -> int: ''' return: the maximum number of consecutive days [100, 80, 60, 70, 60, 75, 85] [1, 1, 1, 2, 1, stack = [(100,1), (80,1), (70,2), (60,1)] at 75, 1+1+2 = 4 then stack = [(100,1), (80,1), (75,4)] ''' span = 1 # min span (price itself) while self.s and price >= self.s[-1][0]: span += self.s[-1][1] self.s.pop() self.s.append((price,span)) return span # Your StockSpanner object will be instantiated and called as such: S = StockSpanner() prices = [100, 80, 60, 70, 60, 75, 85] L = [] for p in prices: L.append(S.next(p)) print(L) print(L == [1, 1, 1, 2, 1, 4, 6])
c76fb2cfb6d627ef8234a1380536a4632d2de528
aditya-doshatti/Leetcode
/check_if_it_is_a_straight_line_1232.py
1,271
4.0625
4
''' 1232. Check If It Is a Straight Line Easy You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true https://leetcode.com/problems/check-if-it-is-a-straight-line/ ''' class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: try: slope = (coordinates[-1][1] - coordinates[0][1])/(coordinates[-1][0] - coordinates[0][0]) except: return False for point in coordinates: if (point[1] - coordinates[0][1]) == slope * (point[0] - coordinates[0][0]): continue else: return False return True # try: # slope = (coordinates[-1][1] - coordinates[0][1])/(coordinates[-1][0] - coordinates[0][0]) # except: # return False # intercept = (-1 * ( slope * coordinates[0][0])) + coordinates[0][1] # for point in coordinates: # if (slope * point[0]) + intercept == point[1]: # continue # else: # return False # return True
86cec6c5c0db98fb78728e358cd1facbc348bd24
alpsilva/PG-2020.2
/projeto0/structures/vetor.py
943
3.859375
4
class Vetor: def __init__(self, x1, x2, x3): self.x1 = x1 self.x2 = x2 self.x3 = x3 # Igualdade entre vetores. def __eq__(self, outro): return self.x1 == outro.x1 and self.x2 == outro.x2 and self.x3 == outro.x3 # Multiplicacao por numero real. def __mul__(self, num): return Vetor(self.x1 * num, self.x2 * num, self.x3 * num) # Divisão por numero real. def __truediv__(self, num): if (num != 0): return Vetor(self.x1 / num, self.x2 / num, self.x3 / num) else: return Vetor(0, 0, 0) # Adicao entre vetores. def __add__(self, outro): return Vetor(self.x1 + outro.x1, self.x2 + outro.x2, self.x3 + outro.x3) # Subtracao entre vetores. def __sub__(self, outro): return Vetor(self.x1 - outro.x1, self.x2 - outro.x2, self.x3 - outro.x3) def print(self): print(self.x1, self.x2, self.x3)
550dc1b59c2315f1171050827b93f5664852253d
Dom88Finch/RecipeScraper
/util.py
341
3.765625
4
import statistics def remove_outliers(arr): if (len(arr) < 3): return arr avg = statistics.mean(arr) std_dev = statistics.stdev(arr) for a in arr: if (a > avg + std_dev or a < avg - std_dev): arr.remove(a) avg = statistics.mean(arr) std_dev = statistics.stdev(arr) return arr
dfdd71a95486533cd79323aee8ebcc93e200d759
SiddhiPevekar/Python-Programming-MHM
/prog29.py
320
4.0625
4
#to remove duplicate from a list lst=[] n=int(input("enter the number of elements:\n")) for i in range(n): x=input("enter elements:\n") lst.append(x) lst=(dict.fromkeys(lst)) print(lst) lst=list(dict.fromkeys(lst))#this prints in list form print(lst) #print(set(lst)) this prints in the form of set
81e982958b29e6bbf6137de796cacb99f11bd793
jod35/coding-challenges
/011.py
167
3.859375
4
x=int(input("Enter a number greater than 100 ")) y=int(input("Enter a number less than 10: ")) number_of_times=x/y print(f"{x} enters {y} {number_of_times} times")
c18a6bbd673bac4d82d3e695ee141c83caee5993
o-hill/utilities
/pdf_scraper.py
4,019
3.65625
4
import requests import re import sys import os ''' This is a python file that will download all PDFs that are linked to by a provided URL. It can be run like this: python pdf_scraper.py <URL> <OPTIONAL DIRECTORY NAME> If a directory name is specified, it will create a directory with that name that branches off of the current directory. Otherwise, it will create a directory named 'pdf_download' that will contain all of the downloads. Dependencies: python requests library. Function synopsis: new_dir: Creates the given path and changes to that directory. Will just move to the directory if the path already exists. find: Finds all of the strings matching the given regular expression in the given text. Works specifically with HTML in this context, but would work with any string. download: Downloads whatever lies at the given source URL with a pretty progress bar :) Made by: Oliver Hill <oliverhi@umich.edu> ''' # Creates a new directory with the # specified path and goes to that directory, # attempting to handle exceptions along the way. def new_dir(path): try: os.makedirs(path) except: pass # Go to the directory. os.chdir(path) '''Returns a list of found matches for a regular expression in a file. Inputs: expr - a regular expression to search with. html - text to search. ''' def find(expr, html): # Find all the instances of the # provided regular expression. found = re.findall(expr, html) result = [] # Iterate over the found instances # and return the full paths from each. for tup in found: if tup[0] != '' and tup[1] != '': result.append(tup[0] + tup[1]) return result # Download the given PDF file with a status bar. def download(source): print("Downloading: " + source + "...") # Get the name of the file. O(n) :( path = source.split('/') dest = path[-1] # Get the response from the url request. response = requests.get(source, stream = True) length = response.headers.get('content-length') length = int(length) # Open the file and download whatever lies there. with open(dest, 'wb') as destination: progress = 0 # Download the data. for data in response.iter_content(chunk_size = 10): progress += len(data) destination.write(data) # Format a progress bar. done = int(50 * (progress / length)) sys.stdout.write('\r[%s%s]' % ('#' * done, '-' * (50 - done))) sys.stdout.flush() print('\n') # Main function! if __name__ == '__main__': try: url = sys.argv[1] page = requests.get(url).text except: print("Error! Usage: 'python pdf_scraper.py <URL>' Exiting... \n\n\n") sys.exit() # Find all of the matches for a file path that ends with # a pdf file, relative or absolute. Examples: # https://eecs.umich.edu/handouts/lecture1.pdf # handouts/umich/lecture1.pdf pdfs = find('"([0-9A-Za-z:/]*/)*(.*?.pdf)"', page) # Create a new directory branching off of the # current directory, name it with the URL, # and navigate to it so that we can download # all the files into this directory. if len(sys.argv) == 3: new_dir(os.getcwd() + '/' + sys.argv[2]) else: new_dir(os.getcwd() + '/pdf_download') # Iterate over the results and download each PDF. for result in pdfs: # If the file path is a URL, download it # with a get request. if result[:4] == 'http': source = result # Otherwise append the result onto the # base URL given when the program started. else: source = url + result download(source)
36203225d36c72a9a65e85bc519d08d210114678
BlueBlueSkyZZ/LeetCode
/Python/145Binary_Tree_Postorder_Traversal.py
771
3.921875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from typing import List class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: result = [] def recursion(root: TreeNode): if root is None: return None recursion(root.left) recursion(root.right) result.append(root.val) recursion(root) return result if __name__ == '__main__': left3 = TreeNode(3, None, None) right2 = TreeNode(2, left3, None) root1 = TreeNode(1, None, right2) solution = Solution() print(solution.postorderTraversal(root1))
f646550090ea0a37ab64cc1c42f8f439ba43cd53
rithinark/arkfile
/stone,paper,scissor_game.py
2,094
3.859375
4
import random lists = ["stone", "paper", "scissor"] ai_points, user_points = 0, 0 def chance(ai_choice, user_choice): global ai_points, user_points if ai_choice == user_choice: print("\t\t\t\tboth are same") elif ai_choice == "paper" and user_choice == "stone": ai_points = ai_points + 1 elif ai_choice == "paper" and user_choice == "scissor": user_points = user_points + 1 elif ai_choice == "stone" and user_choice == "paper": user_points = user_points + 1 elif ai_choice == "stone" and user_choice == "scissor": ai_points = ai_points + 1 elif ai_choice == "scissor" and user_choice == "paper": ai_points = ai_points + 1 elif ai_choice == "scissor" and user_choice == "stone": user_points = user_points + 1 return ai_points, user_points def initialize(): ai_choice = random.choice(lists) user_choice = input("you choose:") print("ai choosed:{}".format(ai_choice)) return ai_choice, user_choice def takeoff(): global ai_points, user_points match_fix = int(input("\t\t\t\t\tMatch fix:")) counter = 0 while counter < match_fix: ai_choice, user_choice = initialize() ai_points, user_points = chance(ai_choice, user_choice) counter += 1 print("\t\tai points:{}\t\tuser points:{}\n".format(ai_points, user_points)) print("End of game") if user_points > ai_points: print("Hurray!!! you won the game") elif user_points == ai_points: print("draw!!!!") else: print("ohhh!! The AI won the game") print("\t\t\tFinal score\nuser points={}\tAI points={}".format(user_points, ai_points)) return def mains(): takeoff() global ai_points, user_points ai_points, user_points = 0, 0 print("To try again press 1 or 0 to exit") a = int(input()) if a == 1: mains() else: print("exiting........") return print("\t\t\t\t\t\t\t\t\t\t############################# Lets play....Stone....Paper....Scissors " "#############################") mains()
bc9fe8f8deb2b3f0fde2fc2829481f710efe54f6
Gabriela-Santos/study_python
/1-basics/05-functions.py
273
4.125
4
# print the type of an object - escrevendo o tipo de um objeto print(type(1)) print(type(1.0)) print(type('a')) print(type(True)) # use brackets to declare a list - use colchetes para declarar uma lista print(type([1, 2, 3])) print(len('Gabriela')) print(len([10, 11, 12]))
970e0538ac63f783738dd974f0e0ed5f8a1a4b10
qzylinux/Python
/filter.py
633
3.84375
4
#filter(函数,序列),使用惰性计算,只有取filter得结果时才会返回值 #生成器生成序列,然后用生成器(generator)和过滤器(filter)返回新的序列 #其中新序列的生成原则是:序列每一个元素除以序列的第一个元素,整除的过滤掉 def odd_iter(): n=1 while True: n=n+2 yield n def prime_filter(n): return lambda x : x%n>0 def primenumber(): yield 2 t=odd_iter() while True: n=next(t) yield n t=filter(prime_filter(n),t) def main(): for x in primenumber(): if x<1000: print(x) else : break if __name__ == '__main__': main()
623c064dd80b90d337b7a618cb0f1a9706e33919
john-ko/project-euler
/3.py
866
3.84375
4
""" Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from math import sqrt def is_prime(number): for i in range(int(sqrt(number))): if i + 1 < 2: continue if number % (i + 1) == 0: return False return True def largest_prime_factor(number): # keep a list of prime # smaller n number_range = sqrt(number) / 2 numbers = [] # only looping through odd numbers for i in range(int(number_range)): # using only odd numbers j = i * 2 + 1 if is_prime(j) and number % (j) == 0: numbers.append(j) return numbers[-1] assert(largest_prime_factor(13195) == 29) # this one takes like 9s ... theres probably a better way to check print(largest_prime_factor(600851475143))
4582a1c69b0949376d4885a2dbce19c1a11d71ac
JakeEdm/CP1404Practicals
/prac_02/files.py
547
3.8125
4
# # 1. # # out_file = open('name.txt', "w") # # name = input("What is your name: ") # # print(name, file=out_file) # # out_file.close() # # # 2. # # in_file = open('name.txt', 'r') # # name = in_file.read() # # print(f'Your name is {name}') # # in_file.close() # 3. # in_file = open('numbers.txt', 'r') # # line1 = int(in_file.readline()) # line2 = int(in_file.readline()) # # print(line1 + line2) # # in_file.close() # 4. in_file = open('numbers.txt', 'r') total = 0 for line in in_file: total += int(line) print(total) in_file.close()
80c99537af382296bed6fb832a6197c2bbd89da8
imsamuel/pcc
/exercises/chapter-5/5.7.py
806
4.375
4
""" 5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a series of independent if statements that check for certain fruits in your list. • Make a list of your three favorite fruits and call it favorite_fruits. • Write five if statements. Each should check whether a certain kind of fruit is in your list. If the fruit is in your list, the if block should print a statement, such as You really like bananas! """ fruits = ["mango", "grapes", "lychee", "rambutan"] if "mango" in fruits: print("you really like mangos!") if "grapes" in fruits: print("you really like grapes!") if "lychee" in fruits: print("you really like lychees!") if "rambutan" in fruits: print("you really like rambutans!") if "guava" in fruits: print("you really like guavas!")
8975d1a0db28d952721747d232c7aa043106649e
orlewilson/lab-programacao-tin02s1
/aulas/exemplo5.py
1,518
4.25
4
""" Disciplina: Laboratório de Programação Professor: Orlewilson B. Maia Autor: Orlewilson B. Maia Data: 31/08/2016 Descrição: Exemplos com condições (if). """ """ Sintaxe if (condição): bloco verdadeiro else: bloco falso if (condição): bloco verdadeiro else: if (condição): bloco verdadeiro if (condição): bloco verdadeiro elif (condição): bloco verdadeiro else: bloco falso """ # Exemplos com if x = int(input("Digite um valor para x: ")) y = int(input("Digite um valor para y: ")) if (x < y): print("%d é menor que %d" %(x,y)) if (x >= y): print("%d é maior ou igual a %d" %(x,y)) if (x < y): print("%d é menor que %d" %(x,y)) else: print("%d é maior ou igual a %d" %(x,y)) # -------------------------------- categoria = int(input("Digite a categoria do produto: ")) preco = 0.0 # Solução 1 if (categoria == 1): preco = 10.0 if (categoria == 2): preco = 18.0 if (categoria == 3): preco = 23.0 if (categoria == 4): preco = 26.0 if (categoria == 5): preco = 31.0 # Solução 2 if (categoria == 1): preco = 10.0 else: if (categoria == 2): preco = 18.0 else: if (categoria == 3): preco = 23.0 else: if (categoria == 4): preco = 26.0 else: if (categoria == 5): preco = 31.0 # Solução 3 if (categoria == 1): preco = 10.0 elif (categoria == 2): preco = 18.0 elif (categoria == 3): preco = 23.0 elif (categoria == 4): preco = 26.0 elif (categoria == 5): preco = 31.0 print("O preço da categoria %d é R$ %2.2f. " %(categoria, preco))
7a1c1f40ad98a930b4419e2263ecc1d8418405c3
cylinder-lee-cn/LeetCode
/LeetCode/371.py
902
3.609375
4
""" 371. 两整数之和 不使用运算符 + 和 - ​​​​​​​,计算两整数 ​​​​​​​a 、b ​​​​​​​之和。 示例 1: 输入: a = 1, b = 2 输出: 3 示例 2: 输入: a = -2, b = 3 输出: 1 """ class Solution: def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ maxmask = 0x7fffffff mask = 0xffffffff while (b != 0): a, b = (a ^ b) & mask, ((a & b) << 1) & mask return a if a <= maxmask else (a | ~mask) s = Solution() print(s.getSum(-2, 3)) """ 此题解法,使用二进制的位运算,a xor b 是位相加,不考虑进位,1+1 =0 0+0 = 0 1+0=1 (a and b) << 1 是进位 a+b 就是 (a xor b)+ ((a and b) << 1),如果(a and b) << 1 不为零就递归调用 也可以不用递归。 """
8eefc12f190a8ba388c8c5d5e69fedd596f4dbfb
hopekbj33/python20200322
/st01.Python기초/py07선택문/py07_01ex1_if홀짝.py
787
3.84375
4
# 정수를 입력을 받습니다. # 입력 받은 문자열을 정수로 바꿉니다. # 숫자로 변환하기 ####################################### # 홀수, 짝수 판별법 # 방법1. 나머지를 사용하는 방법 # 방법2. 문자열을 사용하는 방법 ####################################### a=int(input("정수를 입력하세요")) if a%2==0: print("짝수") else: print("홀수") ####################################### # 방법1. 나머지를 사용하여 짝수 , 홀수 판별하는 방법 ####################################### # 짝수 확인 # 홀수 확인 ####################################### # 방법2. 문자열을 사용하는 방법 ####################################### # 마지막 자리 숫자를 추출 # 숫자로 변환하기
7236ed2fa8502de5461aec7ce249eebbc36cbbd8
adusachev/Algorithms-and-Data-structures
/Algorithms/Graphs/BFS.py
1,885
3.765625
4
def bfs(G, start_vertex, n): """ Обход графа в ширину. :param G: невзвешенный неориентированный граф(вершины - числа от 1 до n) :param start_vertex: начальная вершина :param n: кол-во вершин в графе :return: список distances: distances[i] = кратчайшее расстояние от start_vertex до i-ой вершины графа """ from collections import deque distances = [None] * n # список расстояний distances[start_vertex] = 0 queue = deque([start_vertex]) # очередь создаем сразу с нач эл-том while queue: # <=> пока очередь не пуста vertex = queue.popleft() for neighbour in G[vertex]: if distances[neighbour] is None: # <=> вершина еще не посещена(расстояние до нее не вычислено) distances[neighbour] = distances[vertex] + 1 queue.append(neighbour) print(distances) def main(): n, m = map(int, input().split()) G = {i: set() for i in range(n)} for i in range(m): v1, v2 = map(int, input().split()) G[v1].add(v2) G[v2].add(v1) print(G) start_vertex = int(input()) bfs(G, start_vertex, n) def test(): n, m = 15, 16 G = {0: {1, 10, 11, 12}, 1: {0, 7}, 2: {6}, 3: {11}, 4: {10}, 5: {8, 13}, 6: {2, 10}, 7: {1, 13}, 8: {12, 5}, 9: {11}, 10: {0, 4, 6}, 11: {0, 3, 9, 12, 14}, 12: {0, 8, 11}, 13: {5, 7}, 14: {11}} start_vertex = 0 bfs(G, start_vertex, n) if __name__ == '__main__': test()
6e131621d1e442626c075f63a755e8f119e4ef07
imqishi/HardToSay
/147. Insertion Sort List.py
912
3.84375
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ newHead = ListNode(0) cur = head while cur is not None: newPtr = ListNode(cur.val) insertPos = self.findPos(newHead, cur.val) newPtr.next = insertPos.next insertPos.next = newPtr cur = cur.next return newHead.next def findPos(self, head, val): while head.next is not None: if head.next.val > val: return head head = head.next return head a = ListNode(4) b = ListNode(3) c = ListNode(2) a.next = b b.next = c obj = Solution() rtn = obj.insertionSortList(a) print rtn.val
ae4f55af470af7f88647af099be8d85757b5e343
sunilpedada/htmlANDjavascripts
/timeMatplot.py
423
3.609375
4
import time import matplotlib.pyplot as pt validating=0 seconds=[] while(len(seconds)<5): print(len(seconds)) start=time.time() a=input("type") end=time.time() time_lape=end-start seconds.append(round(time_lape)) if a!="words": validating+=1 print("no of mistake",validating) print(len(seconds)) x=[1,2,3,4,5] labels=['1','2','3','4','5'] pt.xticks(x,labels) pt.plot(x,seconds) pt.show()
1a86519f7e2a914318ac4d66d21ec1e8f4d673c6
jpch89/picpython
/pp_047_多线程同步之Event.py
1,492
3.625
4
from threading import Thread, Event, current_thread import time event = Event() # 用于判断 event 对象管理的内部标志是否被设置为 True print(event.is_set()) # 刚开始是 False def do_sth(): print('%s开始等待' % current_thread().getName()) # 当 event 对象管理的内部标志为 False 时调用 wait() 方法 # 会将调用方法的线程阻塞 event.wait() print('%s结束等待' % current_thread().getName()) for i in range(3): Thread(target=do_sth).start() time.sleep(2) event.set() """ False Thread-1开始等待 Thread-2开始等待 Thread-3开始等待 Thread-1结束等待 Thread-2结束等待 Thread-3结束等待 """ """ 小结 标准库模块 threading 中提供了一个类对象 Event,也可以实现多线程间的同步。 Event 实例对象管理着一个内部标志。 通过改变这个内部标志的值,可以让一个线程给其它处于阻塞状态的线程发送一个事件信号。 从而唤醒这些线程,让它们转为运行状态。 Event 的方法: set() 方法:用于将内部标志设置为 True。 is_set() 方法:用于判断内部标志是否被设置为 True。 clear() 方法:将内部标志设置为 False,与 set() 方法对应。 wait() 方法:当内部标志位 False 时,调用该方法的线程会被阻塞。 直到另外一个线程调用了方法 set() 将内部标志设置为 True, 被阻塞的线程才会转为运行状态。 """
839fc0d06eae5d57c2cf1da1c51fa54bda2cbd5a
ntmoore/phys150_fall20
/01e_snore_carl.py
1,221
3.890625
4
# Carl Ferkinhoff # starting from from adafruit example # https://learn.adafruit.com/welcome-to-circuitpython/creating-and-editing-code # import board import digitalio import time # set up the (red) LED led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT while True: num_repeats=2 #sets how long at each brightness length = 180 #sets the length of the snore j=0 brightness = .1 # initial brightness is measured out of a max of 1.0 T_fast = 0.01 while (j<length): #brightness increases i=0 T_on = brightness*T_fast T_off = (1.0-brightness)*T_fast while (i<num_repeats): led.value = True time.sleep(T_on) led.value = False time.sleep(T_off) i++ j++ brightness = brightness+(T_fast*90.0)/length while (j>0): #brightness decreases i=0 T_on = brightness*T_fast T_off = (1-brightness)*T_fast while (i<num_repeats): led.value = True time.sleep(T_on) led.value = False time.sleep(T_off) i++ j-- brightness = brightness-(T_fast*90.0)/length
6dbb3718b4f863c51c19a18bcdf122f67da6b941
bd52622020/appSpaceUmer
/task5 python/pointsCalculate.py
803
4.03125
4
''' Created on 9 Jun 2020 @author: umer ''' def point(team ='unknown',games =0, wins =0, loss =0, draw = 0): Points = 0 if wins ==0: wins = games -loss - draw Points = Points + (wins * 3) elif loss ==0: loss = games -wins - draw Points = Points + 0 elif draw ==0: wins = games -loss - wins Points = Points + draw else: Points = Points + (wins * 3) Points = Points + 0 Points = Points + draw if Points > 30: print('Points:', Points ) print('good ! keep it up') elif Points >20 & Points <30: print('Points:', Points ) print('they are gonna lose') else: print('Points:', Points ) print('what a bunch of pathetic players') point('Man UTD', 30, 8, 6, 5)
03d7a424c1345826d848b2c829aae11707fafc03
jkane002/TCS-python
/U2/lesson17/stack.py
764
4.03125
4
class Stack(): #Constructor def __init__(self,list): # __ means private (our __stack attribute is private) self.__stack = [] for value in list: self.__stack.append(value) def push(self,value): print(" < PUSH < " + str(value)) self.__stack.append(value) def pop(self): if len(self.__stack)>0: index = len(self.__stack) - 1 print(" > POP > " + str(self.__stack[index])) return self.__stack.pop(index) #pop() Returns the value of the item that has been removed else: print("Stack is empty.") return False def output(self): st = "" for value in self.__stack: st = st + " > " + str(value) print(st)
1f1741f0ac28c326795a1f0599f771f4086a4d35
djarufes/Python_Crash_Course
/Excercises/HW07/car.py
731
3.75
4
######################################################## # Author: David Jarufe # Date: April. 19 / 2019 # This program is a Class that can be imported # for later use ######################################################## #The Car class (car.py) class Car: def __init__(self, yearMod, carMake): self.__year_model = yearMod self.__make = carMake self.__speed = 0 #Method that adds 5 from the speed data attribute each time its called def accelerate(self): self.__speed += 5 #Method that subtracts 5 from the speed data attribute each time its called def brake(self): self.__speed -= 5 #This method returns the value of the __speed field def get_speed(self): return(self.__speed)
8b9199f3521a6c8277054c82d6a9b405cbfafd53
jackyng88/Queens-College-Projects
/Logistic Regression/Classification.py
7,673
3.609375
4
import numpy as np from sklearn import datasets import scipy.optimize as opt import math as math import random from random import randrange from numpy import linalg as la import copy import matplotlib.pyplot as plt import time def sigmoid (x): return 1 / (1 + np.exp(-x)) def cost_function(w, x, y): ''' w = np.matrix(w) x = np.matrix (x) y = np.matrix (y) ''' first = sigmoid(np.dot(x, w)) final = (-y) * np.log(first) - (1 - y) * np.log(1 - first) return np.mean(final) def calculate_gradient (w,x,y): first = sigmoid(np.dot(x, w)) error = first - y gradient = np.dot(error, first) / y.size #print (gradient.shape) return gradient def steepest_descent (w, x, y, alpha): threshold = 0.0001 #rows = x.shape[0] #params = x.shape[1] #theta_values = np.zeros(1, params) #theta_values = copy.copy(w) theta_values = w #theta_values = np.array(theta_values) #theta_values = np.matrix(theta_values) #theta_values = w.shape[0] current_cost = cost_function (w, x, y) cost_iterations = np.array([]) cost_iterations = np.append(cost_iterations, current_cost) step_increase = alpha * 1.01 print ("W's values") print (w) print ("Theta_Values") print (theta_values) print ("Shape of Theta Values " + str(theta_values.shape)) #w = w - alpha * gradient #final_calc = first_calc.T.dot(x) #gradient_one = sigmoid(x @ w.T) - y #gradient = gradient_one.T.dot(x) #gradient = np.matrix(gradient) #print ("Shape of Gradient " + str(gradient.shape)) iteration = 0 cost_difference = 100 iteration_performance = np.array([]) while (current_cost != 0 and cost_difference > threshold and alpha != 0): #iteration += 1 st = time.time() #theta_values = theta_values - (alpha * gradient_function(theta_values, x, y)) print (theta_values) #current_cost = cost_function (theta_values, x, y) previous_cost = current_cost previous_theta = theta_values previous_alpha = alpha #cost_iterations = np.append(cost_iterations, current_cost) current_cost = cost_function(theta_values, x, y) theta_values = theta_values - (alpha * calculate_gradient(theta_values, x, y)) next_cost = cost_function (theta_values, x, y) cost_difference = abs(current_cost - next_cost) print ("Iteration # " + str(iteration)) print ("Current Cost = " + str(current_cost)) print ("Next Cost = " + str(next_cost)) print ("Difference in Cost = " + str(cost_difference)) print ("Current Value of Alpha = " + str(alpha)) if (current_cost >= next_cost): iteration += 1 alpha *= 1.01 #cost_difference = abs(current_cost - next_cost) #cost_iterations = np.append(cost_iterations, current_cost) #cost_iterations = np.append(cost_iterations, next_cost) current_cost = next_cost cost_iterations = np.append(cost_iterations, current_cost) theta_values = theta_values - (alpha * calculate_gradient (theta_values, x, y)) et = time.time() total_time = et - st iteration_performance = np.append(iteration_performance, total_time) #theta_values = theta_values - (alpha * gradient_function(theta_values, x, y)) elif current_cost < next_cost: alpha = previous_alpha alpha *= 0.5 theta_values = previous_theta #theta_values = theta_values - (alpha * calculate_gradient (theta_values, x, y)) current_cost = previous_cost et = time.time() total_time = et - st iteration_performance = np.append(iteration_performance, total_time) #theta_values = theta_values - (alpha * calculate_gradient (theta_values, x, y)) #theta_values = theta_values - (alpha * gradient_function(theta_values, x, y)) #cost_iterations = np.array(cost_iterations) return theta_values, cost_iterations, iteration, iteration_performance def predict (w, x): m,n = x.shape probability = np.zeros(shape=(m, 1)); h = sigmoid(x.dot(w.T)) #probability = 1 * (h >= 0.5) probability = np.where (h >= 0.5, 1, 0) return probability def k_folds_cv (w,x,y, n): blockSize = len(x) / n #100 / 5 = 20. #LOADING INPUT DATA iris = datasets.load_iris() x = iris.data[:100, :4] y = iris.target[:100] initial_w = np.random.normal (loc = 0.0, scale = 0.66, size = (len(x[0]))) #initial_w = np.array(initial_w) print ("Initial values of W = " + str(initial_w)) print ("Y's shape = " + str(y.shape)) #cost_values = [] trained_w, cost_values, num_iterations, iteration_performance = steepest_descent (initial_w, x, y, 5) #print ("Shape of Trained Weights = " + str(trained_w.shape)) print ("Trained W values = ") #trained_w = trained_w[0] print(trained_w) #trained_w = np.insert (trained_w, 0, values = np.random.normal (loc = 0.0, scale = 0.77),axis = 0) trained_w = np.insert (trained_w, 0, values = 0, axis = 0) test_x = x test_x = np.insert(test_x, 0, values=np.random.normal(loc = 0.0, scale = 0.77), axis=1) #np.random.shuffle(test_x) #test_x = np.insert(test_x, 0, values = 1, axis=1) print("Shape of Test X = " + str(test_x.shape)) print("Shape of Trained W = " + str(trained_w.shape)) start_time = time.time() prediction = predict (trained_w, test_x) end_time = time.time() steep_total_time = end_time - start_time print (steep_total_time) ''' correct = [1 if a == b else 0 for (a, b) in zip(prediction, y)] accuracy = (sum(map(int, correct)) / float(len(correct))) print ('accuracy = {0}%'.format(accuracy * 100)) ''' print ('Accuracy: %f' % ((y[np.where(prediction == y)].size / float(y.size)) * 100.0)); print (cost_values) print (num_iterations) quasi_newton_weights = np.zeros (shape = len(x[0])) optimized_qn_weights = opt.fmin_bfgs(cost_function, quasi_newton_weights, args=(x, y)); optimized_qn_weights = np.insert(optimized_qn_weights, 0, values=np.random.normal(loc = 0.0, scale = 0.77), axis=0) qn_test_x = x qn_test_x = np.insert(qn_test_x, 0, values=np.random.normal(loc = 0.0, scale = 0.77), axis=1) start_time = time.time() quasi_newton_prediction= predict (optimized_qn_weights, qn_test_x) end_time = time.time() quasi_total_time = end_time - start_time print ('Accuracy: %f' % ((y[np.where(quasi_newton_prediction == y)].size / float(y.size)) * 100.0)); print ("Optimized Steepest Descent Weight Vector" , trained_w) print ("Optimized Quasi-Newton Weight Vector", optimized_qn_weights) print (len(x)) #kfold_weights = cross_validate_kfold (trained_w, test_x, y, 10) #kfold_predictions = predict (kfold_weights, x) #print ('Accuracy: %f' % ((y[np.where(kfold_predictions == y)].size / float(y.size)) * 100.0)); #kfold_data = k_folds_split(test_x, 5) #print (kfold_data) #scores = evaluate_algorithm(trained_w, test_x, y, 1.01) plt.plot(range(len(cost_values)), cost_values, 'ro') plt.axis([0, len(cost_values), 0, 5]) plt.savefig('Cost Iterations.pdf') print ("Steepest Prediction took ", steep_total_time, " seconds") print ("Quasi Prediction took ", quasi_total_time, " seconds") print ("Iteration Time Vector" , iteration_performance) print ("Average Time of Iterations ", np.mean(iteration_performance)) #print (sigmoid(5))
3bcea6be445a02097536ac80000d029020a3c058
devAbdifetah/python_dev
/deletegaree1.py
1,195
4.0625
4
##for i in range(1,11): ## print("the value is {:03}".format(i)) ## ##pi = 3.14159265 ##sentence = 'Pi is equal to {:.2f}'.format(pi) ##print(sentence) ## ## class BankAcc: def __init__(self): self.balance=0 print("Hello,!!! Welcome to the deposit and withdrawn machine") def deposit(self): amount = float(input("Enter amount to be deposited: ")) if amount <=0: print("please Enter valid amount") else: self.balance+=amount print("you deposited ",amount,'Rubees') def withdraw(self): amount = float(input("Enter the Amout to be withdrawn: ")) if self.balance > amount: if amount < 0: print("please Enter valid amount") else: self.balance-=amount print("you withdrawn ",amount,'Rubees') else: print("insificient money") def display(self): print("the net availabe balance = ",self.balance,'rubees') #creating an object of the class s = BankAcc() s.deposit() s.withdraw() s.display() #s.withdraw()
f3694cc1ed5e677b77e302d781bfeb8ca0b2178f
collenjones/genetic_algorithm
/genetic.py
3,737
4.125
4
from operator import add from random import random, randint def individual(length, min, max): """Create a member of the population. :length int: the number of values for an individual to contain :min int: the minimum possible value :max int: the maximum possible value """ return [randint(min, max) for x in xrange(length)] def population(count, length, min, max): """Create a umber of individuals (i.e. a population). :count int: the number of individuals in the population :length int: the number of values per individuals :min int: the min possible value in an individual's list of values :max int: the max possible value in an individual's list of values """ return [individual(length, min, max) for x in xrange(count)] def fitness(individual, target): """Determine the fitness of an individual. Lower is better. :individual list: the individual to evaluage :target int: the sum of numbers that individuals are aiming for """ sum = reduce(add, individual, 0) return abs(target - sum) def grade(population, target): """Find average fitness for a population. :population list: a list of individuals :target int: the target for an individual """ summed = reduce(add, (fitness(individual, target) for individual in population), 0) return summed / (len(population) * 1.0) def evolve(population, target, retain=0.2, random_select=0.05, mutate=0.01): """Evolve the population to try to reach the target. :population list: a list of individuals :target int: the best possible result for an individual :retain float: the percentage of individuals to retain from a population for parents :random_select float: the percentage chance of randomly selecting an individual to be a parent for genetic diversity :mutate float: the percentage chance of mutating an individual """ graded = [(fitness(individual, target), individual) for individual in population] graded = [fit_score[1] for fit_score in sorted(graded)] retain_length = int(len(graded)*retain) parents = graded[:retain_length] # randomly add other individuals to promote genetic diversity for individual in graded[retain_length:]: if random_select > random(): parents.append(individual) # mutate some individuals for individual in parents: if mutate > random(): pos_to_mutate = randint(0, len(individual) - 1) # this mutation is not ideal because it # restricts the range of possible values # but the function is unaware of the min/max # values used to create the individuals individual[pos_to_mutate] = randint(min(individual), max(individual)) # crossover parents to create children parents_length = len(parents) desired_length = len(population) - parents_length children = [] while len(children) < desired_length: male = randint(0, parents_length - 1) female = randint(0, parents_length - 1) if male != female: male = parents[male] female = parents[female] half = len(male) / 2 child = male[:half] + female[:half] children.append(child) parents.extend(children) return parents target = 371 population_count = 100 individual_length = 5 individual_min = 0 individual_max = 100 pop_instance = population(population_count, individual_length, individual_min, individual_max) fitness_history = [grade(pop_instance, target),] for i in xrange(100): population = evolve(pop_instance, target) fitness_history.append(grade(pop_instance, target)) for datum in fitness_history: print datum
d7f79a8235a355a9b26066779ed1ac653d31e3ce
aaronbushell1984/Python
/Day 3/working.py
247
3.96875
4
def calculateFactorial(N): factorialN = 0 if N == 0: factorialN = 1 return factorialN else: for number in range(1, N+1): factorialN += number return factorialN print(calculateFactorial(0))
ce2a7084134cbbfc11019ca5f42afd04fdbf6edc
SvetlanaD/Python_practice
/Day2.py
1,471
3.65625
4
import json class Day2: def text_func(text: str, max_len: int): symbols_with_spaces = len(text) symbols_no_spaces = len(text.replace(' ', '')) symbols_even = symbols_with_spaces % 2 == 0 print(f'Kоличество символов в тексте {symbols_with_spaces}') print(f'Kоличество символов без учета пробелов {symbols_no_spaces}') if symbols_even: print('Kоличество символов в тексте четное') else: print('Kоличество символов в тексте нечетное') if symbols_with_spaces > max_len: print(f'Длина текста превышает длину {max_len} символов') def text_processor(text: str, max_len: int, forbidden_words: list): pure_text = text for word in forbidden_words: pure_text = pure_text.replace(word, '***') pure_short_text = pure_text[:max_len] if len(pure_text) > max_len: pure_short_text = pure_short_text + '...' result = {"length": len(text), "pure_length": len(text.replace(' ', '')), "origin_text": text, "pure_text": pure_text, "pure_short_text": pure_short_text } print(str(result).replace(',', ',\n')) Day2.text_processor("Буська", 6, ["усь"])
9dd161ce41b136e05e37be5d12accdee63cb647f
joaogehlen91/calculo_numerico
/Trabalho2/questao1/questao_1_a.py
258
3.625
4
# -*- coding:utf-8 -*- import numpy as np from math import * h = 0.125 a = -3.0 b = 3.0 n = int(((b-a)/h)+1) x = np.linspace(-3.0, 3.0, n) y = 2.71828182846**-(x**2) for i in range(1, n-1): y[i] = 2*y[i] AT = (h/2)*sum(y) AT = AT*(2/sqrt(pi)) print AT
77b0e749b02694d95b434906f1f9b27b4badc24e
JobsDong/leetcode
/problems/349-1.py
428
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ['"wuyadong" <wuyadong311521@gmail.com>'] class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ s1 = set(nums1) s2 = set(nums2) res = [] for c in s1: if c in s2: res.append(c) return res
68cd81952afbe80a51c33f54c409d77a3711ac15
MOHAMMADSHAIBAZQAISAR/Hactoberfest-2021
/Programming_Languages/PYTHON BASIC PROGRAMS/tuple.py
231
3.828125
4
numbers = (1,2,3,4) #numbers[0] = 10 print(numbers[0]) #unpacking coordinates = (1,2,3) coordinates[0] * coordinates[1] #x = coordinates[0] #y = coordinates[1] ##z = coordinates[2] #x * y x,y,z = coordinates print(x)
93618796b9a7e185cd111468884dc2fd3739c452
hfujima/rssreader
/bin/hfujima/lib/functions.py
1,193
3.953125
4
# -*- coding: utf-8 -*- def truncate(text, max_length, suffix=u'…', return_none=False): """ 一定文字数を超えた文字列を「…」などで置換する。 suffixがmax_lengthより長い場合、suffixをmax_lengthまで切り詰めた文字を返却する。 :param text: 整形対象のテキスト :param max_length: 表示する文字数(suffix込) :param suffix: max_lengthを超えた文字列を置換する文字列 :param return_none: Trueの場合はtextがNoneだった場合にNoneを返却する。Falseの場合は空文字列を返却する :return: unicode >>> print truncate(u'aaaaa', 3) aa… >>> print truncate(u'漢字です', 1) … >>> print truncate(u'漢字', 2) 漢字 >>> print truncate(u'漢字です', 2) 漢… >>> print truncate(u'あいうえお', 5, u'・・・') あいうえお >>> print truncate(u'あいうえお', 4, u'・・・') あ・・・ """ if text is None: if return_none: return None else: return u'' if max_length < len(text): return text[:max_length - len(suffix)] + suffix return text
1cd539e0aa7d1a46bf272816f694a75dad375dd0
richardsun-voyager/SentimentAnalysis
/tools/text_hier_split.py
5,382
3.765625
4
######Split texts into sentences############## import re import nltk import nltk.data import string from time import time from nltk.tokenize import WordPunctTokenizer from nltk.stem import WordNetLemmatizer import spacy class text2words: ''' Using spacy tool to tokenize texts into sentences or words ''' def __init__(self, texts): ''' texts: a list of strings, utf-8 encoding ''' self.__nlp__ = spacy.load('en') self.__texts__ = texts def __text2sents__(self, text): ''' Split a text into sentences ''' text = self.__nlp__(text) #SPlit into sentences sents = list(text.sents) sents_words = list(map(self.__sent2words__, sents)) return sents_words def __sent2words__(self, sent): ''' Split spacy sentence into spacy tokens ''' sent_words = list(map(self.__to_lower__, sent)) return sent_words def __text2words__(self, text): ''' Split a text into words ''' text = self.__nlp__(text) words = list(map(self.__to_lower__, text)) return words def __to_lower__(self, word): ''' Word: spacy token ''' return word.lemma_.lower() def proceed(self, is_hierarchical=False): ''' Execute the task ''' print('Tokenization starting...') start = time() tokens = [] if is_hierarchical: tokens = map(self.__text2sents__, self.__texts__) else: tokens = map(self.__text2words__, self.__texts__) end = time() print('Tokenization Finished! Timing: ', round(end-start, 3)) return tokens class text2sents: ''' Split a text into sentences ''' def __init__(self, texts): ''' Args: texts: a list of texts ''' assert isinstance(texts, list) == True self.__tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') self.__texts = texts def __preprocess__(self, text): ''' Remove email address and digits ''' pattern1 = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,5}' regex1 = re.compile(pattern1, flags=re.IGNORECASE) text = regex1.sub('email', text) pattern2 = '[|#$@><=+-]' regex2 = re.compile(pattern2) text = regex2.sub(' ', text) pattern3 = r'\n' regex3 = re.compile(pattern3) text = regex3.sub(' ', text) pattern4 = r'[0-9]' regex4 = re.compile(pattern4) text = regex4.sub(' ', text) pattern5 = r'[ ]+' regex5 = re.compile(pattern5) text = regex5.sub(' ', text) return text.lower() def __split_text__(self, text): #text = self.__preprocess__(text) sents = self.__tokenizer.tokenize(text) return sents def __split_sent__(self, sents): s2w = sent2words(sents) sent_words = s2w.proceed() return sent_words def proceed(self, is_hierarchical=True): #sents = [self.__split__(text) for text in self.__texts] print('Start tokenizing....') start = time() #Split sentences into words if is_hierarchical: text_sents = list(map(self.__split_sent__, text_sents)) else: text_sents = list(map(self.__split_text__, self.__texts)) end = time() print('Processing Finished! Timing: ', round(end-start, 3)) return text_sents class sent2words: ''' Split a sentence into sequences of words ''' def __init__(self, sents, punctuation=None): ''' Args: texts: a list of sentences punctuation: a list of symbols that will be removed ''' assert isinstance(sents, list) == True self.__tokenizer = WordPunctTokenizer().tokenize self.__lemmatizer = WordNetLemmatizer().lemmatize self.__sents = sents self.__punctuation = punctuation def __preprocess__(self, sent): ''' Remove punctuation and digits ''' if self.__punctuation is None: return sent #remove punctuation s = re.sub('['+self.__punctuation+']', ' ', sent) #remove digits s = re.sub('['+string.digits+']', ' ', s) #remove foreign characters s = re.sub('[^a-zA-Z]', ' ', s) #remove line ends s = re.sub('\n', ' ', s) #turn to lower case s = s.lower() s = re.sub('[ ]+',' ', s) s = s.rstrip() return s def __split__(self, sent): ''' Split a sentence into words Lemmatize words ''' #sent = self.__preprocess__(sent) words = self.__tokenizer(sent) words = list(map(self.__lemmatizer, words)) return words def proceed(self): #self.__texts = self.__preprocess__(self.__texts) #print('Start tokenizing....') #start = time() sent_words = list(map(self.__split__, self.__sents)) end = time() #print('Processing Finished! Timing: ', round(end-start, 3)) return sent_words def splitList(self, sents): sents_words = list(map(self.__split__, sents)) return sents_words
3ef8b812e3ab07a71e41e4c73479e66d080b8c27
Ys-Zhou/leetcode-medi-p3
/201-300/229. Majority Element II.py
1,147
3.53125
4
# Runtime: 44 ms, faster than 100.00% of Python3 online submissions class Solution: def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] num_1, num_2 = nums[0], nums[0] votes_1, votes_2 = 0, 0 for num in nums: if num == num_1: votes_1 += 1 continue if num == num_2: votes_2 += 1 continue if votes_1 == 0: num_1 = num votes_1 = 1 continue if votes_2 == 0: num_2 = num votes_2 = 1 continue votes_1 -= 1 votes_2 -= 1 votes_1, votes_2 = 0, 0 for num in nums: if num == num_1: votes_1 += 1 continue if num == num_2: votes_2 += 1 res = [] if votes_1 > len(nums) // 3: res.append(num_1) if votes_2 > len(nums) // 3: res.append(num_2) return res
c455766e61398aada0323dc5095ec41bf3d4d37a
joybangla71/atomisticdomains
/atomistic_domains/lattice.py
1,576
3.734375
4
import numpy as np from typing import List from atomistic_domains import Atom class Lattice: """ The class "lattice" defines methods which manipulate lattice structures. Lattice structures have the following attributes: :param type: Lattice type: e.g. fcc, hcp, bcc, etc. :param box: Unit cell box dimensions (including tilt) :param basis_atoms: List of atoms (of object class: atom) which make up the primitive unit cell (in relative coordinates) :param chem: List of chemical elements in alloy :param num_el: Number of different elements present :param num_atoms: number of atoms per each element (dictionary type) :param tot_atoms: Total number of atoms in unit cell """ def __init__( self, x_vector: np.ndarray = np.zeros(shape=(1, 3)), y_vector: np.ndarray = np.zeros(shape=(1, 3)), z_vector: np.ndarray = np.zeros(shape=(1, 3)), basis_atoms: List[Atom] = None, ): self.x_vector = x_vector self.y_vector = y_vector self.z_vector = z_vector if not basis_atoms: basis_atoms = [] else: self.basis_atoms = basis_atoms return def create( x_vector: np.ndarray = np.zeros(shape=(1, 3)), y_vector: np.ndarray = np.zeros(shape=(1, 3)), z_vector: np.ndarray = np.zeros(shape=(1, 3)), basis_atoms: List[Atom] = None, ) -> Lattice: return Lattice( x_vector, y_vector, z_vector, basis_atoms, )
333ce1437d366239f44a096e0c1b156eab0cd9e7
shuklaham/python_progs_think
/e5.4.py
347
4.21875
4
import math def is_triangle(a,b,c): if (a > (b+c)) or (b > (a+c)) or (c > (b+a)): print "No" else: print "Yes" print "Type your 1st side - a \n" first_num = int(raw_input()) print "Type your 2nd side - b \n" sec_num = int(raw_input()) print "Type your 3rd side - c \n" third_num = int(raw_input()) is_triangle(first_num,sec_num,third_num)
2e8fd0ec0d49fb0dbc796b7c91af41f2451b1320
alisher0v/MeFirstPrograms
/sum.py
283
3.921875
4
number = int(input()) def sum(number): answer = 0 if number == 0: return 1 if number < 0: for i in range(number, 1): answer += i else: for i in range(1, number+1): answer += i return answer print(sum(number))
9d6c4a43459a2ac3cdc8bd28b0b4a8cdf2bcc5d6
abhayshekhar/PythonPrograms
/isPhoneNumber.py
817
4.15625
4
def isPhoneNumber(text): if len(text)!=12: return False for i in range(0,3): if not text[i].isdecimal(): return False if text[3]!='-': return False for i in range(4,7): if not text[i].isdecimal(): return False if text[7]!='-': return False for i in range(8,12): if not text[i].isdecimal(): return False return True print('222-325-2541 :is this a phone number') print(isPhoneNumber('222-325-2541')) print('mos-mos-mosi :is this a phone number') print(isPhoneNumber('mos-mos-mosi')) message='Call me at 415-555-6541 tommorow. 415-541-6656 is my office' for i in range(0,len(message)): check=message[i:i+12] if isPhoneNumber(check): print('phone number found :'+check) print('over,Done')
7572d0270b7ad6f91473b2680e5c96a87c2ecfbc
souravs17031999/100dayscodingchallenge
/strings/check_binary_codes_substring.py
2,943
3.984375
4
# Program to check if given "k", and string "s", if s contains all possible binary codes of length k as substring in s. # Example 1: # # Input: s = "00110110", k = 2 # Output: true # Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 respectively. # Example 2: # # Input: s = "00110", k = 2 # Output: true # Example 3: # # Input: s = "0110", k = 1 # Output: true # Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. # Example 4: # # Input: s = "0110", k = 2 # Output: false # Explanation: The binary code "00" is of length 2 and doesn't exist in the array. # Example 5: # # Input: s = "0000000001011100", k = 4 # Output: false # -------------------------------------------------------------------------------------------------- # Like , k = 2, all possible binary codes : '00', '01', '10', '11' # and k = 3, '000', '001', '010', '011', '100', '101', '110', '111' # total binary codes for a given k = 2^(k) # Now, also what we can do here is we are not going to generate all the binary codes, because that would be too inefficient, # so, we will use sliding window approach (similar to other substirng problems using a count var), and then when we get the desired window, # we simply add the substring taken from start to k steps further from that point to a hashtable, so that all unique binary codes possible in the given string, can be maintained # in a hashtable. # Now, we can simply check the size of the hashtable if it matches with the required binary codes (2 ^ k). # So, basically, all we do is we maintain a set of all unique binary codes of length k taken from the string (as a substring) and then check if its length matches with the # required binary code number. # ------------------------------------------------------------------------------------------------- # TIME : 0( N * K), SPACE : 0(N * K), N IS LENGTH OF STRING, K IS THE NUMBER OF BINARY CODE LENGTH REQUIRED. # -------------------------------------------------------------------------------------------------- # Follow up - can we do more better ? # Yes, we can actually, design our hash function (without using built-in set function), and using rolling hash function # we can get it done in 0(1) time. # But premature optimization is not good, and hence, we should first run the above approach, and then check if custom defined hash function if it gives better runtime. # -------------------------------------------------------------------------------------------------- class Solution: def hasAllCodes(self, s: str, k: int) -> bool: count = 0 visited = set() start = 0 for i in range(0, len(s)): count += 1 if count == k: visited.add(s[start:start + k]) start += 1 count -= 1 return pow(2, k) == len(visited)
a6eae747fe32b3e9c3b662c39dbfa5bd214030eb
Cekurok/codes-competition
/hackerrank/python/Date and Time/python-time-delta-English.py
444
3.84375
4
import time import datetime monthDict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12} testcase = int(input()) for i in range(testcase): date1 = datetime.datetime.strptime(str(input()), "%a %d %b %Y %H:%M:%S %z") date2 = datetime.datetime.strptime(str(input()), "%a %d %b %Y %H:%M:%S %z") difftime = int(abs((date2-date1).total_seconds())) print (difftime)
7899f9a83b1e3df468278a3bec043a07762c136e
Sibyl233/LeetCode
/src/LC/81.py
1,948
3.6875
4
from typing import List """解法1:两次二分查找。先找分界(LC154),再找target。 """ class Solution: def search(self, nums: List[int], target: int) -> int: lo, hi = 0, len(nums)-1 while lo < hi: mid = (lo + hi) // 2 if nums[mid] > nums[hi]: lo = mid + 1 elif nums[mid] < nums[hi]: hi = mid else: hi = hi - 1 if target >= nums[0] and nums[-1] < nums[0]: lo, hi = 0, lo else: lo, hi = lo, len(nums)-1 while lo < hi: mid = (lo + hi) // 2 if target > nums[mid]: lo = mid + 1 else: hi = mid return nums[lo] == target """解法2:递归。 - 时间复杂度: - 空间复杂度: """ class Solution: def search(self, nums: List[int], target: int) -> bool: def dfs(l,r): if l>r: return -1 if r-l+1 <= 2: if nums[l] == target: return l if nums[r] == target: return r return -1 m = (l+r)//2 if nums[m] == target: return m if nums[m] > nums[l]: if nums[l] <= target < nums[m]: return dfs(l,m-1) else: return dfs(m+1,r) elif nums[m] < nums[l]: if nums[m] < target <= nums[r]: return dfs(m+1,r) else: return dfs(l,m-1) else: lres = dfs(l,m-1) rres = dfs(m+1,r) if lres != -1: return lres return rres return dfs(0,len(nums)-1) != -1 if __name__=="__main__": nums = [2,5,6,7,0,0,1,2] target = 0 print(Solution().search(nums, target)) # true
adb077a552563ff04bd40e3645ec43c7231b2623
nomura-takahiro/study
/loop/for_while.py
1,669
4.0625
4
################ ### ループ ### ################ #for text = "Nomura" #デフォルトで in XXXに指定したものから1要素ずつを取り出すっぽい for char in text: print(char) tmp = ["Nomura","Baz","Jista"] #リストの1要素ずつを出力 for li in tmp: print(li) #ミュータブルなものなら更新ができる i = 0 for li in tmp: new = tmp[i] new = new.upper() tmp[i] = new i += 1 print(tmp) #上記方法でもいいが、下の方式がメジャーらしい tmp = ["Nomura","Baz","Jista"] for i, new in enumerate(tmp): #こうすることでindex値のインクリメントが不要 new = tmp[i] new = new.upper() tmp[i] = new print(tmp) tmp2 = {"Red":"Apple", "Yello":"Banana", "Green":"Melon" } #辞書の場合、キーを取り出す for fruit in tmp2: print(fruit) #range #for i in range(10): for i in range(0,10): #本来range()は引数2つらしい print(i) for i in range(len(tmp)): print(tmp[i]) #======================================================================================================================== ################ ### while ### ################ x = 10 while x > 0: print(x) x-= 1 print("End.") x = 10 while x > 0: print(x) break x-= 1 print("End.") #ある処理を繰り返す qs = ["What your name? >> ", "What your age? >> ", "What your birth? >>" ] """ idx = 0 print("Type [q] to stop.") while True: ans = input(qs[idx]) if ans == "q": break # %演算で右辺より左辺が小さい場合は、結果は左辺が使われる idx = (idx + 1) % len(qs) """ index = 0 for index in range(10): if index == (5): continue print(index)
dfa0faec7b6d7df384e9cb2d6aac2a855f55dfa7
jhanvi-shingala/linear_regression
/linear_regression.py
867
3.78125
4
#Linear regression import numpy as np import csv2array import matplotlib.pyplot as plt infile = input("Enter a csv filename: ") ar = csv2array.csvar(infile) # Training X = ar[:,0] Y = ar[:,1] m = X.shape[0] #number of training examples epoch = 150000 #number of iterations t0 = 0.9999 t1 = 0.9999 alpha = 0.00009 i = 0 while (i<epoch): h = float(t0) + (float(t1)*X) #hypothesis dif = h - Y #cost function #gradient descent t0 = t0 - alpha*(1/(m) * (sum(dif))) t1 = t1 - alpha*(1/(m) * (sum(dif*X))) print("epoch=",i,"t0=",t0,"t1=",t1) i += 1 ################# #Testing data testf = input("Enter test filename: ") ar2 = csv2array.csvar(testf) x = ar2[:,0] y = ar2[:,1] h1 = float(t0) + (float(t1)*x) plt.scatter(ar2[:,0],ar2[:,1],s = 5) plt.title("Linear Regression Testing") plt.xlabel("x") plt.xlabel("y") plt.plot(x,h1,color = 'black') plt.show()
ede2f4b7b5fe4b1214ececb6f047e4833fe570b4
Travis-ugo/pythonTutorial
/while loop,for loop.py
663
3.875
4
call = 0 while call < 3: name = input('User name :') call += 1 if name == 'Travis': print('Hey ' + name) break else: print('try again') for cap in range(3): other = input('Other name :') if other == 'Okonicha': print('Hello ' + name + ' ' + other) break else : print('try again') for love in range(3): try: password = str(int(input('pass word :'))) if password == str(int('4422')): print('Here you Go Boss') break else: print('fake') except ValueError : print('wrong password')
6d2c3167c570e4b8dbee58462ab874f758fa3579
reshma-jahir/GUVI
/set18.py
67
3.5
4
val=int(input()) sat=0 for i in range(val): sat=sat+i print(sat)
c1590abf4f311e7b0e1bc7edea0f35b9b4704d6b
mikaevnikita/algorithms-and-data-structures
/algorithms/quick_sort.py
550
3.921875
4
def quickSort(array, beg, end): pivot = array[(beg+end)//2] left = beg right = end while(left <= right): while(array[left] < pivot): left+=1 while(array[right] > pivot): right-=1 if(left <= right): array[left],array[right] = array[right],array[left] left+=1 right-=1 if(beg < right): quickSort(array, beg, right) if(end > left): quickSort(array, left, end) l = [1,2,3,2,2,10,3,3,-1,-100,-500] quickSort(l,0,len(l)-1) print(l)
777356dd2d0ff5ceb6eee0f9e3ca49d5e3dee7e2
themillipede/data-structures-and-algorithms
/algorithmic_toolbox/PA3_greedy_algorithms/3_car_fueling.py
2,092
4.0625
4
# python3 """ 3. Car fueling Introduction: You are going to travel to another city that is located d miles away from your home city. You can travel at most m miles on a full tank and you start with a full tank. Along your way, there are gas stations at distances stop_1, stop_2, ..., stop_n from your home city. What is the minimum number of refills needed? Input: The first line contains an integer d. The second line contains an integer m. The third line contains an integer n. Finally, the last line contains integers stop_1, stop_2, ..., stop_n. Constraints: 1 <= d <= 10^5; 1 <= m <= 400; 1 <= n <= 300; 0 < stop_1 < stop_2 < ... < stop_n < m. Output: Assuming that the distance between the cities is d miles, a car can travel at most m miles on a full tank, and there are gas stations at distances stop_1, stop_2, ..., stop_n along the way, output the minimum number of refills needed to reach the destination. Assume that the car starts with a full tank. If it is not possible to reach the destination, output -1. """ import sys def compute_min_refills(end_position, tank_capacity, stops): stops = [0] + stops stop_num = 0 num_refills = 0 current_position = 0 while current_position < end_position: max_position = current_position + tank_capacity if max_position >= end_position: return num_refills # If we can reach the end we are done. if stop_num + 1 < len(stops): if stops[stop_num + 1] > max_position: return -1 # If we can't reach the next stop, we give up. elif end_position > max_position: return -1 # We're at the last stop; if we can't reach the end, we give up. # Determine next furthest stop. while stop_num < len(stops) - 1 and stops[stop_num + 1] <= max_position: stop_num += 1 num_refills += 1 current_position = stops[stop_num] return num_refills if __name__ == '__main__': d, m, _, *stops = map(int, sys.stdin.read().split()) print(compute_min_refills(d, m, stops))
d45bfb2f42a0ed486a8cfad278fa2f079a05f8f7
AllysonKapers/2143-Object-Oriented-Programming
/Resources/10-PyGame/02_pygame_example.py
1,243
4.3125
4
#!/usr/bin/env python3 # Import and initialize the pygame library import pygame import random """ This version simply changes the color of the ball using the random library in python. """ pygame.init() # Set up the drawing window screen = pygame.display.set_mode([500, 500]) # Run until the user asks to quit running = True count = 0 while running: # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Fill the background with white screen.fill((255, 255, 255)) # Change the color of the ball randomly # we slow down the change rate by creating a counter # and modding by some value (1000 in this case) # otherwise it will change too fast if count % 100 == 0: red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) # set counter to zero so it doesn't grow to super large count = 0 # Draw a solid blue circle in the center pygame.draw.circle(screen, (red, green, blue), (250, 250), 75) # Flip the display pygame.display.flip() # increment our counter count += 1 # Done! Time to quit. pygame.quit()
b98d9ded2b1f33b1249b61fc35e6e9c3cd12bda6
lazydroid/pgn-tactics-generator
/modules/investigate/investigate.py
1,676
3.59375
4
# # Check if the position is worth trying for a puzzle: # 1. there's a sufficient drop in evaluation # 2. there's enough material # 3. the possibility of mate # import chess def sign(a): if a > 0: return 1 elif a < 0: return -1 else: return 0 def material_value(board): return sum(v * (len(board.pieces(pt, True)) + len(board.pieces(pt, False))) for v, pt in zip([0,3,3,5.5,9], chess.PIECE_TYPES)) def material_count(board): return chess.popcount(board.occupied) def investigate(a, b, board): # determine if the difference between position A and B is worth investigating for a puzzle if a.mate is not None and b.mate is not None : return sign(a.mate) == sign(b.mate) # actually means that they're opposite if a.mate is not None and b.cp is not None : # missed giving mate #if abs(b.cp) < 300 : # playable within 3 pawns lost? return True if a.cp is not None and b.mate is not None : # blundered a mate #if a.cp < -850 : # already a lost cause, mate won't make it worse #if abs(b.mate) < 5 : # less than 5 moves, otherwise it's a torture return True if a.cp is not None and b.cp is not None : if material_value(board) > 3 and material_count(board) > 6 : #if (((-110 < a.cp < 850 and 200 < b.cp < 850) # this is strange looking # or (-850 < a.cp < 110 and -850 < b.cp < -200)) if abs(a.cp + b.cp) > 300 : # evaluation changed by more than 3 pawns if a.cp > -b.cp : return True # blunder move -- do we need this check???? # elif (a.cp is not None # and b.mate is not None # and material_value(board) > 3): # if ((a.cp < 110 and sign(b.mate) == -1) or (a.cp > -110 and sign(b.mate) == 1) ): # return True return False
e27f2583e6c3015153cefa43efad46d6f24f0598
DanilaDz/2020-CS50-Work
/MyCS50 code/DanilaDz-cs50-problems-2020-x-sentimental-cash/cash.py
656
3.890625
4
# I used some examples from cash in C from cs50 import get_float import math def main(): # keeps prompting user for input while True: change = get_float('Change owed: ') cents = round(change * 100) if change > 0: break # does all the math to get the remainder coins # the double slash removes the float part of the number and leaves the integer quarters = cents // 25 dimes = (cents % 25) // 10 nickels = ((cents % 25) % 10) // 5 pennies = ((cents % 25) % 10) % 5 # adds all coins together and prints them print(quarters + dimes + nickels + pennies) main()
925788aa60eca2365f44f3722225cf60126df30a
cuviengchai/Programming
/0001.py
452
3.84375
4
score1 = int(input().strip()) score2 = int(input().strip()) score3 = int(input().strip()) sum = score1 + score2 + score3 if sum >= 80 and sum <= 100: print("A") elif sum >= 75 and sum < 80: print("B+") elif sum >= 70 and sum < 75: print("B") elif sum >= 65 and sum < 70: print("C+") elif sum >= 60 and sum < 65: print("C") elif sum >= 55 and sum < 60: print("D+") elif sum >= 50 and sum < 55: print("D") else: print("F")
e2d955891b70084c3e3ce185681593915abee8e0
AUTHENTICGIT/PC
/function_varargs.py
558
3.8125
4
def func(a, b, *c, **d): print(a) print(b) for x in c: print(x) for k,v in d.items(): print(k, v) func('a', 10, 'single_item 1', 'single_item 2', 'single_item 3', Inge=1560, John=2231, Jack=1123) #案例 def total(a=5, *numbers, **phonebook): print('a', a) #遍历元祖中的所有项目 for single_item in numbers: print('single_item', single_item) for first_part, second_part in phonebook.items(): print(first_part, second_part) print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
3d73f7ca9fa3735490926beb496c38d7e9d9105c
princeofpython/UCSD-DSA-specialization
/1. Algorithmic ToolBox/week2_algorithmic_warmup/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py
1,049
3.828125
4
# Uses python3 import sys def fibonacci_partial_sum_naive(from_, to): sum = 0 current = 0 next = 1 for i in range(to + 1): if i >= from_: sum += current current, next = next, current + next return sum % 10 def pisano_period(m): previous=0 current=1 for i in range(m*m): previous, current = current, (previous + current)%m if previous==0 and current==1: return (i+1) def fibonacci_sum_last_digit_fast(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, (1+previous + current)%10 return current if __name__ == '__main__': period=pisano_period(10) sum_over_period=fibonacci_sum_last_digit_fast(period) #input = sys.stdin.read(); m, n = map(int, input().split()) print(((fibonacci_sum_last_digit_fast(n%period)+(sum_over_period*(n//period))%10)-(fibonacci_sum_last_digit_fast((m-1)%period)+(sum_over_period*((m-1)//period))%10))%10) #num_periods
193fbb483798d00bc8a965e116cdfc7e5f3f6a01
pschafran/Notes
/scripts/trimFastaBases.py
1,227
3.515625
4
#!/usr/bin/python # 2020 April 30 (C) Peter W Schafran ps997@cornell.edu # # Trims a range of bases out of a single sequence in FASTA format. Base range is inclusive (start and end positions are removed). # Usage: trimFastaBases.py singleSequence.fasta startBasePosition endBasePosition import sys openSeqFile = open(sys.argv[1], "r") openOutFile = open("%s_trimmed.fasta" % sys.argv[1], "w") startPos = int(sys.argv[2]) endPos = int(sys.argv[3]) if startPos > endPos: print("ERROR: Start position is after end position!") exit(1) seqList = [] for line in openSeqFile: if line.startswith(">"): seqName = line.strip("\n") else: seqList.append(line.strip("\n")) if len(seqList) > 1: seq = "".join(seqList) else: seq = seqList[0] if endPos > len(seq): print("ERROR: End position is beyond end of sequence!") exit(1) if startPos == 1 and endPos == len(seq): print("ERROR: Whole sequence selected to be trimmed!") exit(1) baseCount = 0 writeCount = 0 openOutFile.write("%s\n" % seqName) for base in seq: baseCount += 1 if baseCount < startPos or baseCount > endPos: openOutFile.write(base) writeCount += 1 if writeCount % 80 == 0: openOutFile.write("\n") openOutFile.write("\n") openSeqFile.close() openOutFile.close()
2a98c8dfead68665cd5f9f3f0e8d3685b3b3a719
wendrewdevelop/Estudos
/Python/python_logging/aula/format.py
752
3.578125
4
''' Formatando a mensagem do log. ''' import logging # DateTime:Level:Arquivo:Mensagem log_format = '%(asctime)s:%(levelname)s:%(filename)s:%(message)s' logging.basicConfig(filename='exemplo.log', filemode='w', level=logging.DEBUG, format=log_format) # Instancia do objeto getLogger() logger = logging.getLogger('root') def add(x: int, y: int) -> int: """ Função que efetua a soma de dois numeros inteiros. """ if isinstance(x, int) and isinstance(y, int): logger.info(f'x: {x} - y: {y}') return x + y else: logger.warning( f'x: {x} type: {type(x)} - y: {y} type: {type(x)}' ) add(7, 7) add(7, 7.5)