blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0462f0285f69a38d99d4f17b114472fd05844464
h-j-13/Algorithms-Soulution
/剑指offer/斐波那契数列.py
993
4.375
4
# -*- coding:utf-8 -*- import functools class Solution: """斐波那契数列""" # 最入门的递归问题 # 可以用pyhon3的 @functools.lru_cache() 或者 python的默认参数只初始化一次的特性设置个cache # python3 - @functools.lru_cache() LRU 装饰器 # @functools.lru_cache() # def Fibonacci(self, n): # if n <= 2: # return 1 #...
cf684414a6a918932d2404f2b39cd4dd023ecd1b
h-j-13/Algorithms-Soulution
/剑指offer/左旋转字符串.py
543
3.640625
4
# -*- coding:utf-8 -*- class Solution: """ 题目描述 汇编语言中有一种移位指令叫做循环左移(ROL), 现在有个简单的任务,就是用字符串模拟这个指令的运算结果。 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果, 即“XYZdefabc”。是不是很简单?OK,搞定它! """ def LeftRotateString(self, s, n): return s[n:] + s[:n]
35d0e9708a60e288495269f60e8bf454aa14288b
h-j-13/Algorithms-Soulution
/剑指offer/顺时针打印矩阵.py
6,071
4.03125
4
# -*- coding:utf-8 -*- class Solution: """ 题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. """ # matrix类型为二维列表,需要返回列表 def __init__(self): self.result = [] def printMatrixItem(self, mat...
5c9b05adbef6a285bdfb9f04a11b5b94e60030ac
h-j-13/Algorithms-Soulution
/剑指offer/字符串的排列.py
1,410
3.71875
4
# -*- coding:utf-8 -*- class Solution: """ 题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列。 例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 输入描述: 输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。 """ def Permutation(self, ss, start_index=0): # 全排列 = 第一位依次与后面交换(并固定) + 后面字符串全排列 # 边界 ...
5067e8bb078ef2f1402964fa74dccf54089a3195
h-j-13/Algorithms-Soulution
/剑指offer/矩阵覆盖.py
1,022
3.953125
4
# -*- coding:utf-8 -*- class Solution: """ 题目描述 我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?。 """ def __init__(self): # 加个缓存提高速度 self.cache = {'0': 0, '1': 1, '2': 2} # 想了一下 实际上和跳台阶问题是一模一样的 # 问题可以简化为 使用一个 1*2...
5a6ba05006505202427a8bc66cb879c39458e973
h-j-13/Algorithms-Soulution
/剑指offer/二进制中1的个数.py
951
3.640625
4
# -*- coding:utf-8 -*- class Solution: """ 题目描述 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 """ # 还有一个隐藏条件,2进制长为32位 def NumberOf1(self, n): # 第一个思路,使用bin() # bin() | n -> str:'0b10101...' # if n < 0: # 根据补码的性质 2^32 = 11111111 # return list(bin(2**32+(n)))[2:].coun...
9cc856fa3a102c12eed34076635179a4e203003b
h-j-13/Algorithms-Soulution
/剑指offer/最小的K个数.py
686
3.5
4
# -*- coding:utf-8 -*- import heapq class Solution: """ 题目描述 输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。 """ def GetLeastNumbers_Solution(self, tinput, k): # TOP N 问题 - 堆 # 自己写了挺多遍了,去网上找了一下python竟然有内置的堆实现 >> heapq # 边界处理 if k > len(tinput): ...
0b93ac1d2910f037beb008f87b731a41b2a07fec
CleverParty/containers
/algos/squareConvergents.py
1,022
3.96875
4
import sys from fractions import Fraction sys.setrecursionlimit(10000) a = 2 root = a**2 def convergent(num): base = 1 if num == 0: return False elif num > 1000 : return None num -= 1 sumCon = base +1/(1/2 + convergent(num)) # this just calculates the convergence recursively, for fu...
7e3770fa948dd8970bebba499210a90bd8bebbcb
CleverParty/containers
/algos/concealedSquare.py
1,015
3.5
4
import os,math import re stringtocompare = "1_2_3_4_5_6_7_8_9_0" xCount = 0 yCount = 0 zCount = 0 def squared(num): temp = 1 for i in range(0,num): temp = i*i # sq = i**2 xCount += 1 yCount += 1 zCount += 1 x = re.findall(r"\b2", str(temp)) y = re.findall...
0ec2d4773b2627fb645fdf99913579a54ebe7dec
wlmgithub/awesome
/phone.py
1,794
3.640625
4
from pprint import pprint import itertools DIGIT_TO_LETTERS = { '2': ['A','B','C'], '3': ['D','E','F'], '4': ['G','H','I'], '5': ['J','K','L'], '6': ['M','N','O'], '7': ['P','Q','R','S'], '8': ['T','U','V'], '9': ['W','X','Y','Z'], } def gen_phone_numbers(): phone_numbers_iter = i...
db0a4fd5611d0123fdc02012f22294909a926e58
Shakzhaf/Harrisburg-AI
/Lec 3/garbage.py
385
3.75
4
def bs(list,num): mid=int(len(list)/2) if num==list[mid]: return mid if len(list)==1: return -1 elif num<list[mid]: return bs(list[0:mid],num) elif num>list[mid]: return bs(list[mid:],num) list=[1,2,3,4,5,6,7,8,9,10]...
49732b11f9a79b45d939d6efff8e6c6f0fb17f53
claudiopacheco/projeto_p1
/trends.py
28,859
3.890625
4
"""Visualizing Twitter Sentiment Across America""" #run_doctests('nome_funcao') -> verifica se função está funcionando #para verificar todas as funções de uma vez, rode o programa e digite no idle os seguintes comandos: #import doctest #doctest.testmod() from data import word_sentiments, load_tweets from datetime i...
4b2b23d5fe60bd69ca7ec3c9dac3d6a9a8e986dc
yogi-25/LetsUpgrade_py_Assignment
/Day1.py
6,369
4.4375
4
#Q1 List and it default methods and functions #append(X) a = ["amruta", "yogita"] print(a) a.append("srushti")#Adds an item (x i.e srushti) to the end of the list. print(a) #extend([x,y]) a.extend(["srushti S", "alisha"])#Extends the list by appending all the items from the iterable. This allows you to join two lists ...
0069dce6078cdcd2b97db49f45f35ee6dd597f9e
clarkr28/tic-tac-toe-rl
/player_rule.py
566
3.515625
4
from player_base import PlayerBase from constants import CELL_EMPTY class PlayerRule(PlayerBase): ''' pick the first available slot on the board arguments: board: Board - the tic tac toe board marker: string - the marker that is assigned to this player return: (row, col) tuple where ro...
e2408ba40c1fac9836d3c219cae496119888d859
ms0695861/random_guess
/r.py
635
3.890625
4
#Generate ramdom integers (1~100) #Let user to guess the number #If right, print "Good Job" #If wrong, tell them it is bigger or smaller than anwser. import random start = input('Please enter the initial value: ') end = input('Please enter the end value: ') s = int(start) e = int(end) r = random.randint(s, e) print...
fd7e01f8918c8a578f04a86c11697bbf2ecf344d
lukeaparker/SPD2.3
/other_refactoring/extract_class.py
2,437
3.5625
4
# by Kami Bigdely # Extract Class class Food: def __init__( self, name, prep_time, vegitarian, food_type, cuisine, ingredients, preparation ): self.name = name self.prep_time = prep_time self.vegitarian = vegitarian self.type = food_type self.cuisine = cuisine ...
6da3b95370be373a2bf5df4c4fa071b0db601df9
JacksonxCribar/cribar_jackson_python_data_vis
/data/bar2.py
389
3.8125
4
import matplotlib.pyplot as plt hfont = {'fontname':'codec cold' } Years = [1956, 1972, 1980, 1984, 1988, 1992, 1994, 1998, 2002, 2006, 2010, 2014] Medals = [1, 3, 1, 1, 1, 12, 10, 13, 2, 1, 7, 11] plt.bar(Years, Medals, color=(0/255, 100/255, 100/255), linewidth=5.0) plt.ylabel("Medals") plt.xlabel("Years") p...
859dc4bac7adac1c83e1460dd06decb4f788e1a9
katzjeff/Webscraping
/venv/webscraper_twitter.py
773
3.65625
4
import pandas as pd import GetOldTweets3 as got import csv username="MOH_Kenya" text_query="COVID-19 UPDATE" start="2020-04-01" stop="2020-08-01" count=1000 #creation of query object tweetCriteria = got.manager.TweetCriteria().setUsername(username).setQuerySearch(text_query).setSince(start).setUntil(stop).setMaxTweet...
c44897dfb7cf5a9335bb40fa5e77dc17b1fc9e97
mocmeo/algorithms
/keep-multiplying-found-values-by-two.py
226
3.859375
4
from collections import Counter def findFinalValue(nums, original): count = Counter(nums) while original in count: original *= 2 return original print(findFinalValue([5,3,6,1,12], 3)) print(findFinalValue([2,7,9], 4))
549e2a4cad3d783d32f7d2f4069f13715ec989ab
mocmeo/algorithms
/word-pattern.py
523
3.734375
4
def wordPattern(pattern, str): strs = str.split(' ') if (len(pattern) != len(strs)): return False strDict = {} for i in range(0, len(pattern)): if (strDict.get(pattern[i]) is None): strDict[pattern[i]] = strs[i] elif strDict.get(pattern[i]) != strs[i]: r...
52aa606ca47eb48dfef540c4ed5eb3d7d34747c8
mocmeo/algorithms
/maximum-twin-sum.py
491
3.65625
4
class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next def pairSum(head): nums = [] res = 0 while head: nums.append(head.val) head = head.next for i in range(len(nums)/2): res = max(res, nums[i] + nums[len(nums)-i-1]) return res head = Lis...
deb581a654447b3f5015868a57a7ebc092b54105
mocmeo/algorithms
/merge-string-alternatively.py
290
3.78125
4
def mergeAlternately(word1, word2): i = 0 j = 0 res = "" while i < len(word1) or j < len(word2): if i < len(word1): res += word1[i] i += 1 if j < len(word2): res += word2[j] j += 1 return res print(mergeAlternately("abc", "pqr")) print(mergeAlternately("ab", "pqrs"))
0bcfd181a20c5cafdb004b2ec680df0d82d757cb
mocmeo/algorithms
/k-largest-elements.py
1,404
3.640625
4
# class MaxHeap: # def __init__(self): # self.heap = [] # def push(self, data): # self.heap.append(data) # self.heapifyUp() # def parent(self, i): # return (i-1)//2 # def heapifyUp(self): # i = len(self.heap) - 1 # while i != 0 and self.heap[i] > self.heap[self.parent(i)]: # self.heap[i], self.he...
14ba55af774aaa03442883ea153193431b8861f2
mocmeo/algorithms
/search-in-rotated-sorted-array-ii.py
547
3.703125
4
def findPivot(nums): l = 0 r = len(nums)-1 res = len(nums) while l <= r: mid = (l + r) // 2 if nums[mid] >= nums[0]: l = mid + 1 else: res = min(res, mid) r = mid - 1 return res def search(nums, target): pivot = findPivot(nums) l = pivot r = pivot + len(nums) - 1 while l <= r: mid = (l + ...
99b392b8aa0749762d5a050cf9c53e361a50069c
mocmeo/algorithms
/sliding-window-median.py
619
3.5
4
import heapq def medianSlidingWindow(nums, k): small, large = [], [] if k % 2 == 0: small_cnt, large_cnt = k/2, k/2 else: small_cnt, large_cnt = k//2+1, k//2 res = [] large_cnt = 2 for i in range(len(nums)): heapq.heappush(small, -nums[i]) heapq.heappush(large, nums[i]) if len(large) > large_cnt: h...
c235316aebb27519e36eb814471707c153f8307a
mocmeo/algorithms
/shortest-unsorted-continous-array.py
513
3.859375
4
def findUnsortedSubarray(nums): sortedArr = nums[:] sortedArr.sort() left = 0 right = len(nums) - 1 while (left < right): isContinue = False if sortedArr[left] == nums[left]: left += 1 isContinue = True if sortedArr[right] == nums[right]: ...
d18b958700405f27bf43cb9d36bc540ae9620993
mocmeo/algorithms
/find-pivot-index.py
237
3.625
4
def pivotIndex(nums): sum_arr = sum(nums) x = 0 for i in range(len(nums)): x += nums[i] if sum_arr - x == x - nums[i]: return i return -1 print(pivotIndex([1,7,3,6,5,6])) print(pivotIndex([1,2,3])) print(pivotIndex([2,1,-1]))
f062fe741679d4299fecffe16fe22d65328cc697
mocmeo/algorithms
/permutations.py
402
3.6875
4
def permute(nums): arr = [] res = [] visited = set({}) def generate(arr, visited, nums): if len(arr) == len(nums): res.append(arr[:]) return for num in nums: if num not in visited: arr.append(num) visited.add(num) generate(arr, visited, nums) arr.pop() visited.remove(num) generat...
ccd70341746d0f22242876f2a1e1cf29beef2e9a
mocmeo/algorithms
/search-insert-position.py
422
4.09375
4
def searchInsert(nums, target): left = 0 right = len(nums) - 1 result = 0 while (left <= right): mid = int((left + right)/2) if nums[mid] == target: return mid elif nums[mid] < target: result = max(result, mid+1) left = mid + 1 elif num...
626bb2331d139fb290cef416b616f924080fa000
mocmeo/algorithms
/backspace-string-compare.py
440
3.59375
4
def process(myStr): i = 0 result = [] while i < len(myStr): if (myStr[i] == '#' and len(result) > 0): del result[-1] else: if (myStr[i] != '#'): result.append(myStr[i]) i += 1 return ''.join(result) def backspaceCompare(S, T): S = pro...
f9f3d121b7710ba4b14c092ae18b150e31333965
mocmeo/algorithms
/array-partition-1.py
179
3.640625
4
def arrayPairSum(nums): nums.sort() n = int(len(nums)/2) result = 0 for i in range(n): result += nums[i*2] return result print(arrayPairSum([1, 1]))
8b886ed03a0a2fe440827bdfc0960970e9230684
mocmeo/algorithms
/invert-binary-tree.py
524
4.0625
4
class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None def invertTree(root): def invert(root): if root: root.left, root.right = root.right, root.left if root.left: invert(root.left) if root.right: invert(root.right) invert(root) return root root = Tree...
fbff0c4e2259f16d7c15285a71d5e01fa9bd5487
mocmeo/algorithms
/count-words-obtained-after-adding-a-letter.py
538
3.78125
4
from collections import Counter def wordCount(startWords, targetWords): nums = [] res = 0 for word in startWords: x = 0 for ch in word: x |= 1 << (ord(ch) - ord('a')) nums.append(x) count = Counter(nums) for word in targetWords: x = 0 for ch in word: x |= 1 << (ord(ch) - ord('a')) for ch in wor...
8bc27586d809adedc5f4ec7911af0a49ef8f7449
mocmeo/algorithms
/goat-latin.py
456
3.609375
4
def toGoatLatin(S): words = S.strip().split() suffix = "" result = [] for word in words: suffix += "a" if word.lower()[0] in "ueoai": result.append(word + "ma" + suffix) else: result.append(word[1:] + word[0] + "ma" + suffix) return " ".join(result) ...
ed0b8a3d19de377b815eaabc922d37603521fbac
mocmeo/algorithms
/range-sum-query.py
571
3.546875
4
class NumArray(object): def __init__(self, nums): if (len(nums) == 0): self.sumList = [] else: self.sumList = [0 for i in range(-1, len(nums))] self.sumList[0] = nums[0] for i in range(1, len(nums)): self.sumList[i] = self.sumList[i-1...
7716202a51cc96a86eeeec9053465488abc9e5a0
mocmeo/algorithms
/house-robber-ii.py
546
3.6875
4
def rob(nums): if len(nums) <= 3: return max(nums) # case 1 res = 0 arr = [0]*len(nums) arr[0] = nums[0] for i in range(1, len(nums)-1): if i >= 2: arr[i] = max(arr[i-1], arr[i-2] + nums[i]) else: arr[i] = max(arr[i-1], nums[i]) res = max(res, arr[i]) # case 2 arr2 = [0]*len(nums) arr2[0] = 0 ...
ccb3ab66ee4dcdeacc9031c17595a7548f694d6d
mocmeo/algorithms
/longest-mountain-in-array.py
589
3.765625
4
def longestMountain(arr): left = [0]*len(arr) right = [0]*len(arr) res = 0 count = 1 left[0] = 1 for i in range(1, len(arr)): if arr[i] > arr[i-1]: count += 1 left[i] = count else: count = 1 left[i] = 1 count = 1 right[-1] = 1 for i in range(len(arr)-2, -1, -1): if arr[i] > arr[i+1]: cou...
5ba1caebc43393d60f26871f196b56b3763f7ee9
mocmeo/algorithms
/count-primes.py
353
3.71875
4
def countPrimes(n): prime = [True for i in range(0, n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p*2, n+1, p): prime[i] = False p += 1 result = 0 for i in range(2, n): if (prime[i]): result += 1 return res...
122b54ee5330cccd4b67eb35f359e43bc1d5b674
mocmeo/algorithms
/contain-duplicate-2.py
407
3.53125
4
def containsNearbyDuplicate(nums, k): # numDict: (key, value) => (number, index) numDict = {} for x in range(0, len(nums)): currentNumber = nums[x] if (numDict.get(currentNumber) is not None): if (abs(x - numDict[currentNumber] <= k)): return True numDict...
5af92aec1f625282e42c044f188c5c1d5032a484
mocmeo/algorithms
/number-of-visible-persons-in-a-queue.py
464
3.625
4
def peek(seq): return seq[len(seq)-1] def canSeePersonsCount(heights): seq = [] res = [] for i in range(len(heights)-1, -1, -1): count = 0 while len(seq) > 0 and peek(seq) < heights[i]: seq.pop() count += 1 if len(seq) > 0: count += 1 seq.append(heights[i]) res.append(count) return res[::-1]...
6f0d8a3f081ee30f2847bd9037fa933888d0b102
mocmeo/algorithms
/longest-common-prefix.py
714
3.875
4
def checkValidPrefix(strs, length): firstStr = strs[0] prefix = firstStr[0:int(length) + 1] for indexStr in strs: if (not indexStr.startswith(prefix)): return False return True def binarySearch(strs): left = 0 right = len(strs[0]) - 1 result = -1 while left <= rig...
5d6b60b73b766819ecdd2dd96c6280c9b7838371
douniakahilia/document-classification
/Classification_RF.py
6,501
3.609375
4
# In[1]: #so as to minimize typing strokes. import nltk import pandas as pd import numpy as np from sklearn.metrics import classification_report import sklearn.metrics from pandas import DataFrame,Series from sklearn.feature_extraction.text import TfidfVectorizer from time import time import matplotlib.pyplot as plt ...
1679896d83e931f602949e43cef00461675b719c
nhatquangdang/CP1404_practicals
/Prac_03/Broken_score.py
418
3.515625
4
import random def main(): score = random.randint(0,100) print(final(score)) def final(score): out_file = open('results.txt', 'w') if score < 0 or score > 100: print("Invalid score",file=out_file) elif score >= 90: print("Execelent",file=out_file) elif score >= 50: print("...
4997e1cdafd9e38399313131a9cc79a5bb975ba1
nhatquangdang/CP1404_practicals
/Prac_05/word_occurrences.py
248
3.890625
4
text = input("Enter a sentence: ") sentence = {} words = text.split() for word in words: sentence[word] = sentence.get(word, 0) +1 words = list(sentence.keys()) words.sort() for word in words: print("{:5} : {}".format(word, sentence[word]))
5d41cacf96b2a14ef5f41e14ec7ac36e25528b69
taniagdn/Python-Fundamentos
/24_08_2021/laboratorio_Errores.py
604
3.84375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 24 09:09:17 2021 @author: taniagualli """ #Laboratorio Manejo de errores def readint(promt, min, max): try: number=int(input(promt)) assert(number>=min and number<=max) return number except AssertionError: ...
e8df981b236799b7ebe7464f58df013e4f780582
taniagdn/Python-Fundamentos
/20_08_2021/funcion_lamba.py
192
3.59375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 20 23:39:51 2021 @author: taniagualli """ a=[0, 1, -1, -2, 3, -4, 5, 6, 7] b=list(filter(lambda x: x>0, a)) b print(b)
a52d1af9158488ae5d6fedada26e305287883c4c
MorozovaY/basic_exercises
/for_challenges.py
2,349
3.6875
4
# Задание 1 # Необходимо вывести имена всех учеников из списка с новой строки names = ['Оля', 'Петя', 'Вася', 'Маша'] for names_list in names: print(names_list) # Задание 2 # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём # Пример вывода: # Оля: 3 # Петя: 4 names...
505d8a4b4cbf14f931386907d4b6f7b7b90c1069
stanilevitch/python_06102018
/zjazd_3/Zadanie2.py
3,562
3.796875
4
class Employee: def __init__(self, imie, nazwisko, stawka): self.imie = imie self.nazwisko = nazwisko self.stawka = stawka self.worked_hours = 0 def pay_salary(self): if self.worked_hours <= 8: to_pay = self.worked_hours * self.stawka else: ...
78ddd79437822dee5a294fd88090448caf445d99
stanilevitch/python_06102018
/zjazd_1/zadanie_13.py
614
3.515625
4
LICZBA_DNI_TYGODNIA = 7 numer_dnia = 1 suma_temperatur = 0 min_ = None max_ = None while numer_dnia <= LICZBA_DNI_TYGODNIA: temp = int(input(f"Podaj temp z dnia {numer_dnia}: ")) suma_temperatur += temp if numer_dnia == 1: min_ = temp max_ = temp else: if temp < min_: ...
f3d02f5367d8f12beceaba43df8ef5e7c16cc152
stanilevitch/python_06102018
/zjazd_5/Zad1_numpy.py
1,075
3.578125
4
import numpy as np # zadania z pliku numpy.ipynb # Indeksowanie, wycinanie, iterowanie - Indexing, Slicing and Iterating # Stwórz liste sześcianów liczb od 0 do 9 a = np.arange(10) ** 3 print(a) # wybierz z listy zaznaczone elementy a[2:5] a[:5:2] # przekształć by otrzymać wynik # [-1000, 1, -1000, 27, -1000, 125,...
b90166d4a635cca78d802e83dcd7151db4094e26
stanilevitch/python_06102018
/snippets/ms.py
1,554
3.875
4
# sprintNo = int(input("Podaj numer sprintu: ")) # print(sprintNo) # # # ######### pusty napis - konstruktor str() # # a = str() # print(a) # # b = str(123) # print(b) # print(f"Wartość pusty napis: {a} -tak, przed my slnikiem jest pusty napis") # # liczba_1 = 3 # liczba_2 = 9 # print(f"Wynik dodawania {liczba_1} + {l...
89adf9a00a6879b9630d48e3ede383d55f1429fa
stanilevitch/python_06102018
/zjazd_2/funkcje/przerobienie_zadan_na_funkcje/zadanie_10.py
1,077
3.59375
4
def podaj_liczby_i_operacje(): liczba_1 = int(input("Podaj liczbę pierwszą")) liczba_2 = int(input("Podaj liczbę druga")) operacja = input("Rodzaj operacji: ") return liczba_1, liczba_2, operacja def kalkulator(liczba_1, liczba_2, operacja): wynik = "nieustalony wynik" if operacja == "+": ...
0679f70c05ffb0365af5010da70db44a546fcfaa
Vivkthkre/NPTEL-Python-Programs
/primepartition.py
885
4.15625
4
'''A positive integer m can be partitioned as primes if it can be written as p + q where p > 0, q > 0 and both p and q are prime numbers. Write a Python function primepartition(m) that takes an integer m as input and returns True if m can be partitioned as primes and False otherwise. (If m is not positive, your functi...
c6d3681938e30926f54777564932f8fd3a1978f9
zhaopufeng/python_scrawler
/src/bs_css_selector/kugou_music_spider.py
1,382
4.03125
4
''' 项目实战:抓取酷狗音乐榜 requests Beautiful Soup CSS Selector https://www.kugou.com/yy/rank/home/6-8888.html?from=rank 1. 排名 2. 歌手 3. 歌曲名 4. 时长 pip install requests ''' import requests from bs4 import BeautifulSoup import time headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/...
7028567403eae37320a2460f71e3dd29ca41574d
quaxsze/flask-file-system
/flask_file_system/images.py
1,856
3.578125
4
""" This module handle image operations (thumbnailing, resizing...) """ import logging import io from PIL import Image log = logging.getLogger(__name__) def make_thumbnail(file, size, bbox=None): """ Generates a thumbnail for a given image file. :param file file: The source's image file to thumbnail ...
c710be63569b2fcf63729623989b0c77a66f7cb6
OliverosA/PracticaPython
/Ejercicio2.py
245
4.03125
4
print("Leer 2 numeros y mostrar el producto de ellos") num1 = int(input("Ingrese un numero entero: ")) num2 = int(input("Ingrese otro numero entero: ")) def Producto(num1, num2): producto = num1*num2 print(producto) Producto(num1,num2)
dde625f8555f3ef4e830eb4a2373530b70c1a687
5um4n7h/python_basic_programs
/vote.py
142
4.03125
4
age = int(input("Enter Age : ")) if age>=18: status="Eligible" else: status="Not Eligible" print("You are ",status," for Vote.")
78750701470d2d50eed56aa35432ed1a3bf07710
5um4n7h/python_basic_programs
/Area_of_triangle.py
256
4.0625
4
import math side1 = int(input("Eneter side 1: ")) side2 = int(input("Eneter side 2: ")) side3 = int(input("Eneter side 3: ")) pm = (side1+side2+side3)/2 area = round(math.sqrt(pm*(pm-side1)*(pm-side2)*(pm-side3)),4) print("Area of the triangle is",area)
fea3247d3da8d328d809fb4c2cf3c863637f3622
smarko1983/Mojeee
/Message Encription - Begining.py
1,009
4.0625
4
# This is just started. The design needs to improve, as well as functionality import time # examples of ord and chr functions # print(ord("A")) # print(chr(65)) def message_encrypted(): '''THis function just accepts the message and encrypts it''' message_unencrypted = input("Please enter a message that you wo...
edbd4a7b8658f1d7e30950e8ae2c59186f69544d
smarko1983/Mojeee
/input validation loop examples.py
603
4.09375
4
# This is what I have been talking about...inpud validation loop examples # input validation loop 1 name = input("What is your name: ") while name != "John": print("go on, guess again") name = input("Please enter a name again: ") if name == "John": print("bye byeee...") else: print(...
6948e67e8d01b1e14c35431d30a3aa76290a1384
smarko1983/Mojeee
/shutdown a computer.py
482
3.875
4
import os import time ask = input("If you want to shutdown your computer, type yes ").lower() if ask == "yes": os.system("shutdown /s /t 0") # shutdown is the program, /s is the argument for shuting it down, # /t is the argument for time, 0 is for time. If you entered 30, it would shutdown the compute...
7317cbcda4ca61d8adbfdedb3a545faf88181d56
smarko1983/Mojeee
/AUTO CLICKER.py
4,593
3.734375
4
# MYP 4 students showed me this website where we were testing our # click speed. The website is: https://cpstester.com/5-seconds/ # It is basically how many left mouse click can you produce in 5 seconds. # The score were from 34 to 39 # So I wanted to use a program which could help me achieve better results # It t...
e05c01a204f7560430b17d6cf7a30bb5d42394cc
smarko1983/Mojeee
/Prime Number Factorization.py
479
4.15625
4
def prime_factorization_func(num): res = [] divisor = 2 if num < 2: return "That number does not have prime factorization" while divisor < num: if num % divisor == 0: num = num / divisor res.append(divisor) else: divisor = divisor + 1 res....
e5fba3039b2b1d3d22a8bcc2fdcd3a4c17ea3cdb
smarko1983/Mojeee
/Conditionals - Check if a number has 4 digits .py
380
3.9375
4
num = int(input("please enter a number between 9 to 9999")) num1 = num //10 num2 = num //100 num3 = num //1000 num4 = num //10000 if num < 9 or num > 9999: print("please try again") elif num1 == 0: print("it is one digit") elif num2 == 0: print("it is two digit") elif num3 == 0: print("it is...
d02e61ea4608bc5a742ed82b67864e77bd693c83
yvonneonu/test1
/test1.py
519
3.984375
4
# Python program to find out # Sum of elements at even and # odd index positions seperately # Function to calculate sum def EvenOddSum(a, n): even = 0 odd = 0 for i in range(n): # Loop to find even, odd Sum if i % 2 == 0: even += a[i] else: odd += a[i] ...
1d7cdf6e93e20398f80667442e4ab1d3c022988b
pconerly/internet-programming-assignments
/a02/print_time.py
444
3.75
4
from datetime import * def print_time(): monthBuff = "" dayBuff = "" theDate = datetime.today() if theDate.month < 10: monthBuff = '0' if theDate.day < 10: dayBuff = '0' today = '%d/%s%d/%s%d'%(theDate.year,monthBuff,theDate.month,dayBuff,theDate.day) #add some html! ...
15872f2947836a75712b700625ff84d9739b2af6
paulaandrezza/URI-Solutions
/2685.py
362
3.890625
4
while True: try: m = int(input()) if (m >= 0 and m < 90 or m == 360): print("Bom Dia!!") elif (m >- 90 and m < 180): print("Boa Tarde!!") elif (m >= 180 and m < 270): print("Boa Noite!!") else: print("De Madrugada!...
bb6b6a70cd620bdb9e7c869b3cec962028c3f459
paulaandrezza/URI-Solutions
/1546.py
202
3.75
4
dic = {1: "Rolien", 2: "Naej", 3: "Elehcim", 4: "Odranoel"} n = int(input()) for e in range(n): k = int(input()) for f in range(k): entrada = int(input()) print(dic[entrada])
da33120e8219f02a1687b995f959a819b12f84ba
paulaandrezza/URI-Solutions
/2454.py
112
3.578125
4
a = input().split() if a[0] == '0': print("C") elif a[1] == '0': print("B") else: print("A")
8aa870f20157e02b37700549cbfe8353fa217f6e
chamdodari2/python_study
/chap04/dict/dict01.py
608
3.609375
4
# 딕셔너리 선언 dictionary={ "name":"7D 건조 망고", "type" :"당절임", "ingredient" : ["망고","설탕","메중아황산나트륨","치자황색소"], "origin":"필리핀" } # 출력한다 print("name:",dictionary["name"]) print("type:",dictionary["type"]) for ingredient in dictionary["ingredient"]: print("ingredient:",ingredient) # print("ingredient:",dicti...
64413046c4af12c94f33737a808f86ad9efd91f3
jotaeo/school-assignment-
/turn based combat.py
2,183
3.703125
4
import random playerhp = int (1000) alienhp = int (1000) playeralive = True alienalive = True bullets = int (3) name = "jota" print (name , "encounters a weird being") print (" does",name,"...") print ("A. fight") print ("B. run away") answer = input ("answer... :") if answer == "A" or "a": print ("[COMMENCIN...
dddad05d0c97b556f1effaaa198acee272069f44
compressionmonkey/ImageClassifierProject
/NaiveBayesClassifier.py
1,175
3.75
4
#The first step is to handle the data by loading it into a CSV file and import csv def loadCsv(filename): lines = csv.reader(open(filename, 'rb'))# read in binary mode dataset = list(lines) for i in range(len(dataset)):# we start the condition dataset[i] = [float(x) for x in dataset[i]]#ok data will...
3bb8e0fbd8f1b7f318fe475e76507129d925d0e0
Sayan-Manna/HyperSkill_Python_CoffeeMachine
/Problems/Stack class/task.py
349
3.609375
4
class Stack(): def __init__(self): self.table = [] def push(self, el): self.table.append(el) def pop(self): return self.table.pop(-1) def peek(self): return self.table[len(self.table) - 1] def is_empty(self): if self.table == []: return "True"...
5f58d0370d248bd2a64a66216a6720d3786725a2
AlisaNi123/Pystu
/Andvanced/Regular/TrySearch4.py
378
3.984375
4
#!/usr/bin/env python #coding=utf-8 import re # str2 = "Hi~ The quick brown fox jumps over the lazy dog." # searchObj = re.search(r'(.*) fox (.*?) .*', str2) # print (searchObj.group()) # print (searchObj.groups()) # print (searchObj.group(1)) # print (searchObj.group(2)) str1 = "In Beijing test is No22 school." obj...
bf96bb801f36d10ecf48c24624a9a4296c777c41
AlisaNi123/Pystu
/Basic/Loop/TryFor1.py
114
3.640625
4
#!/usr/bin/env python #coding=utf-8 for i in range(1, 10, 1): # for(int i=1; i<10; i++) { //xxxxx } print (i)
646f74d1638f8f2ffd8afff37cd0d3268128c9aa
AlisaNi123/Pystu
/Andvanced/random/dictrevert.py
129
4
4
#!/usr/bin/env python #coding=utf-8 dict1 = {'a':1, 'b':2, 'c':3} print dict1 dict2 = {v:k for k,v in dict1.items()} print dict2
ba6ec1afcf86466f3b9a557df8e9f2ae435fce1c
AlisaNi123/Pystu
/Andvanced/Regular/TrySearch.py
203
3.671875
4
#!/usr/bin/env python #coding=utf-8 import re str1 = "www.testfan.cn" obj1 = re.search("www", str1) obj2 = re.search("cn", str1) print (obj1) print (obj2) if re.search("cn", str1): print "xxxxxxx"
a89a2ec5b3773156b869c74553a8eac306b8fc83
AlisaNi123/Pystu
/Basic/Loop/9times9.py
138
3.625
4
#!/usr/bin/env python #coding=utf-8 for i in range(0,10): for j in range(1, i+1): print ("%d*%d = %2d "%(j,i,j*i)), print
43785393287829617db407c965959c92374340de
AlisaNi123/Pystu
/Andvanced/Regular/TryMatch.py
182
3.640625
4
#!/usr/bin/env python #coding=utf-8 import re str1 = "www.testfan.cn" str2 = "cnwww.testfan.cn" obj1 = re.match("www", str1) obj2 = re.match("cn", str2) print (obj1) print (obj2)
eb97806eb7bbb3f63e3839593aaa4851f7515013
navaneethyv/sparks
/checkbalance.py
754
3.5625
4
import urllib2 from BeautifulSoup import * mdn = raw_input("Enter Your Reliance MDN!!") request = urllib2.Request("http://www.rcom.co.in/rcom/Netconnect/Netconnect_Authentication.jsp?MDN=+"mdn) try: response = urllib2.urlopen(request) soup = BeautifulSoup(response) #soup.tag gives the content of that tag:) I want ...
927036899603e759123a6941f36a443d886cf86a
DorRon/DataMiner
/facebook.py
682
3.640625
4
#!/usr/bin/env python from urllib2 import urlopen import ast ############################### ######### FACEBOOK ############ ############################### def getAll(fb_user_name): #fb_user_name = raw_input("Enter your facebook username here: ") fb_url = "http://graph.facebook.com/" + fb_user_name #to obtain specif...
af5c0d1bd7f66bacd4c2e13a8fd35de3356ba57e
the-isf-academy/homework_01_01
/homework_01_01.py
2,116
4.6875
5
# Unit 1 Lesson 1 # Author: Your name # Each of these functions has a multi-line string (starts and ends with """) called a # docstring, which describes what it does and gives an example of how it should work. # You should just leave the docstrings alone--your job is to replace the incorrect # return value with a co...
6dd0130ac81235d883134df70a561e0d7109834d
KirsanKifat/Lodoss_team_task
/task1/Turtle.py
1,839
4.65625
5
'''Координатное поле представим массивом из с 2 перменными: высотой и шириной. Левый верхний край имеет координаты 0 0, первая координата - высота, увеличивается вниз, вторая - ширина увеличивается вправо''' import random class Turtle(): def __init__(self, field_size, start_position=[0,0]): self._position...
68c21bd0a90b682c33e6096fe6854e76816ded80
wycgi520/learning-algorithm
/Archer/98. Validate Binary Search Tree/98. Validate Binary Search Tree.py
2,235
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 方法一 中序遍历,然后判断 class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ ...
c6333f072d3132c86dd851a69e897f668b75bdcc
PyDrummer/cryptography
/tests/test_code.py
795
3.5
4
from caesar_cipher.caesar_cipher import encrypt, decrypt, crack test = "Ravenala" test2 = 'It was the best of times, it was the worst of times.' key = 2 key2 = 6 def test_encrypt(): actual = encrypt(test, key) expected = 'Tcxgpcnc' assert actual == expected def test_decrypt(): tester = encrypt(test, ...
01284972e85dae3fd6a1fb0c837c1a69684ab67c
11jacky11/python_HW
/hw4/interface/situation/getPersonnel.py
337
3.65625
4
# -*- coding: utf-8 -*- employees = [] class Employee(): def __init__( self, n, i, p, s): self.name = n self.id = i self.payment = p self.status = s def printEmployees(): print("人事資訊:") for e in employees : print( "姓名:", e.name, "\t員工ID:", e.id, "\t薪資:", e.payment, "\t狀態:", e.status)
a18c5686a199778f1d65f195fbda4ddcfb04c5d0
isabellapepke/SpotifyMatch
/statistics.py
1,030
3.546875
4
class Statistics: """Class to calulate similarity scores between two profiles""" def profileMetric(self, profile, sharedSongs, sharedArtists): """ Should not be called outside class definition""" numerator = sharedSongs + 0.5*(sharedSongs-sharedArtists) return numerator/profile de...
08ba52d08bac2334c676e416f73d8cfdc65bc4a2
iliruslanili/python
/lesson2_task4.py
505
4.125
4
# Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки # нужно пронумеровать. Если слово длинное, выводить только первые 10 букв в слове. words = [word[:10] for word in input('Введите текст: ').split(' ')] for num, word in enumerate(words): print(f'{num:...
4fe34cce358e6ae9e11a0b913f5c215e6922bd69
infopartha/Python
/ClockHandAngles.py
470
4.125
4
# -*- coding: utf-8 -*- ip = '3:27' #ip = input('Enter Time (hh:mm): ') try: hrs, mins = map(int, ip.split(':')) except: print('Please enter a valid time') if hrs > 24 or mins > 59: raise Exception('Please enter a valid time') if hrs > 12: hrs -= 12 hrs *= 30 mins *= 6 hrs += (mins/12) # This will gi...
aa771a8f43d58ad0616e84976264f69ea50d36d6
dylanswaters/chocolateDataScience
/chocolate.py
11,254
3.609375
4
#Dylan Waters #Assignment 3 #CS 3580 with Dr. Ball #imports import numpy import csv import matplotlib.pyplot as plt import pandas # from scipy import stats from random import randint #print my name! print("Dylan Waters") print("") #lists to hold various data for later sections countryList = [] chocolateRating = [] c...
c8b2422c4a7ced3bdea8f6bf968b2e39bfb531b3
jwoo9928/CareerPass
/CNU-secondgrade/알고리즘/1주차 실습/controlflow.py
188
3.921875
4
n = int(input()) if n%3 == 0 and n>=3: print('Hello, Coding Test!') elif n%4 == 0 and n>=4: print('2020 Algorithm') else: for i in range(n): print('01 Code Test Basic')
2716e9c9c38579c8d0b3a68924063683ef1cffc4
sunnysyed/python_sorting
/mergeSort.py
3,109
3.6875
4
def readfile(fname): content =[] with open(fname) as f: for line in f: content.append(int(line)) return content def merge(left,right): global comparisons result=[] i=0 j=0 while i<len(left) and j<len(right): if (left[i] <= right[j]): comparisons+=...
8b6abace084e45020e5793b5bf78d3255a2e6570
HaraldNordgren/sandbox
/stackoverflow/35257795/test.py
276
3.625
4
#!/usr/bin/env python3 data = ["Germany",3,2,10,"Italy",7,9,1,"canada",4,5,3,"china",4,3,9] data_grouped = [] for i in range(0, len(data), 4): data_grouped.append(data[i:i+4]) data_sorted = sorted(data_grouped, key=(lambda x: x[1]), reverse=True) print(data_sorted)
f47dd187a957f2646abc6dd526d422d6b49f1a23
HaraldNordgren/sandbox
/python/betalo-productivity/ratios.py
871
3.59375
4
#!/usr/bin/env python def redact(username): if username != "harald.nordgren" and username != "haraldnordgren": return "REDACTED" return username class Ratio: def calculate_ratios(counter): total_prs = sum(counter.values()) ratios = {} for username, prs in counter.items(): ...
877aeed23d94c85bae1904088b60cfb3a6c252bc
HaraldNordgren/sandbox
/gcj/2016/coin-jam/funcs.py
427
3.671875
4
#!/usr/bin/env python3 import sys, math def smallestPrimeFactor(nbr): for factor in range(2, math.floor(math.sqrt(nbr)) + 1): if nbr % factor == 0: return factor return -1 def toBase(string, base): string = string[::-1] result = 0 for i in range(len(string)): print...
72d007a96b618e150f209eab5ba73cfd10efc6f5
yangc8128/PracticeProblems
/ProjectEuler/src/PE_5.py
729
3.578125
4
import math def LCM_Range(upperBound): retVal = [1,2,3]; # Prime Factors of [4,upperBound + 1] for i in range(4, upperBound + 1): temp = primeFactors(i); # Compare counts in retVal and in temp of J for j in temp: countJ = temp.count(j); countJ_LCM = retVal.co...
fddda3481f771360aa3ab5e853a4867930faab93
mrbmadrid/Flask_Color_Picker
/Intro_Simple_Functions/Names.py
526
4
4
def printNames(list): for element in list: print element["first_name"],element["last_name"] def printStudentsAndInstructors(obj): print "Students" count = 1 for element in obj["Students"]: print str(count),element["first_name"],element["last_name"],str(len(element["first_name"])+len(element["last_name"])) co...
c99d53e4a2e31a67ad2a2168665de9c86fac1c71
mrbmadrid/Flask_Color_Picker
/Intro_Simple_Functions/Foo_and_Bar.py
882
3.8125
4
primes = [2] output = [] def fooBar(floor, ceil): base = 2 while(base*base < floor): base += 1 for count in range(floor, ceil): if base*base == count: #Perfect squares output.append([count, 'Bar']) base += 1 elif isPrime(count): #primes primes.append(count) output.append([count, 'Foo']) else: #...
3470d4d35ecd115846f1c6bf14e9405526221e26
LaurentStar/MOD3_Project
/scripts/methods.py
2,998
3.90625
4
def region_maker(state, regions): """ When given a state of the United States, this function return the region it belong to if given a region to check. Parameters ---------- state : string of state name EG:('Texas'). regions : A dictionary of regions for a country. the regions values are li...
525b016c0ae22189d6e144557a6524fb6e349773
pepesan/machine-learning-python
/04_01_01_algortimos_regresion_linear.py
3,245
3.90625
4
# -*- coding: utf-8 -*- # pip instalador de bibliotecas python # $ pip install pandas matplotlib sklearn # biblioteca de manejo de datos import pandas as pd # biblioteca de presentación de datos import matplotlib.pyplot as plt # biblioteca de ML from sklearn.linear_model import LinearRegression from sklearn.model_selec...