blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
40e61935f2a38f9532e3bc08522732b5132fa327
gngoncalves/cursoemvideo_python_pt2
/desafio73.py
646
3.734375
4
brasileirao = ('Atlético-MG', 'Palmeiras', 'Flamengo', 'RB Bragantino', 'Fortaleza', 'Corinthians', 'Internacional', 'Fluminense', 'Cuiabá', 'América-MG', 'Atlético-GO', 'São Paulo', 'Ceará', 'Athletico-PR', 'Santos', 'Bahia', 'Sport', 'Juventude', 'Grêmio', 'Chapecoense') p...
aa6778d2e3e85d0164370a82e86f57eba3d38abe
gngoncalves/cursoemvideo_python_pt2
/desafio86.py
345
3.84375
4
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for linha in range(0, 3): for coluna in range(0, 3): num = int(input(f'Digite um número para a posição [{linha}, {coluna}]: ')) matriz[linha][coluna] = num for linha in range(0, 3): for coluna in range(0, 3): print(f'[{matriz[linha][coluna]:^4}]...
16efeaaca77e9d858b9b4bec0cdcefa3d728ab08
gngoncalves/cursoemvideo_python_pt2
/desafio77.py
302
3.78125
4
palavras = ('Abobora', 'Abacate', 'Mamao', 'Paralelepipedo', 'Piao', 'Calendula') for i in range(0, len(palavras)): print(f'A paravra {palavras[i].upper()} possui as seguintes vogais: ', end='') for p in palavras[i].lower(): if p in 'aeiou': print(p, end=' ') print('')
371d3130e8726532306c01eaaa4a4bb1c14552d9
gngoncalves/cursoemvideo_python_pt2
/desafio61.py
235
3.796875
4
primeiro_termo = int(input('Insira o primeiro termo da PA: ')) razao = int(input('Insira a razão da PA: ')) n = 1 while n <= 10: termo = primeiro_termo + (n - 1) * razao print(termo, end= ' >> ') n += 1 print('Finalizado')
dd4f24615b62383513057bf3c5be4cc50b87face
gngoncalves/cursoemvideo_python_pt2
/desafio85.py
322
3.75
4
lista = [[], []] for i in range(1, 8): num = int(input(f'Digite o {i}º valor: ')) if num % 2 == 0: lista[0].append(num) else: lista[1].append(num) lista[0].sort() lista[1].sort() print(f'Os valores pares digitados foram: {lista[0]}.') print(f'Os valores ímpares digitados foram: {lista[1]}.')
54d248cecc21db4aeb9ab920ae456880be27ae6c
hroest/spellcheck-data
/code/reparse_composite.py
9,016
3.796875
4
""" Generate hunspell composite entries by parsing a list of known good words. This script tries to extract composite words by checking each combination of suffix and prefix in the list of good words against the current hunspell database. """ import sys f = open(sys.argv[1], "rb") hs = sys.argv[2] FILEENCODING = ...
a0cf9af3ef78950f8c3ce2985f6e3a1bdc6756db
ProjetoPythonA/PyQuest5
/Questão4.py
543
3.6875
4
listnome = [] listnota = [] soma = media= 0 turma = 3 traço = 40 for ind in range(turma): listnome.append(input('Digite o nome: ')) listnota.append(float(input('Digite a nota: '))) soma += listnota[ind] media = soma/turma print('-'* traço) print('A média da turma é {:.2f}' .format(media)) prin...
7ed5cd0cded26f18db02006615e5dacf99308011
eugenewyj/eugene-python-samples
/python_crash_course/section_3_1.py
937
3.78125
4
# -*- coding: utf-8 -*- list_samples = ['元素1', '元素2', '元素3', '元素4'] print(list_samples) # 获取列表指定元素 print(list_samples[0].title()) print(list_samples[-1].title()) # 修改元素 list_samples[0] = '修改后的元素1' print(list_samples) # 末尾添加元素 list_samples.append("末尾添加元素") print(list_samples) # 插入元素 list_samples.insert(0, "新插入元素") ...
a1ebe3107421b41998c8b82e43bc2e71fd800123
eugenewyj/eugene-python-samples
/algorithm/binary_search.py
487
3.9375
4
# -*- coding: utf-8 -*- def binary_search(list1, item): """ 二分查找 :param list1: 查找的数组 :param item: 待查找项 :return: 查找项在数组中的索引 """ low = 0 high = len(list1) - 1 while low <= high: mid = (low + high) // 2 guess = list1[mid] if guess == item: return mid if guess < item: low = mid + 1 else: high...
654ffad81bc765818450259d060aa2fd80ff66f6
bongjour/effective_python
/part1/ch9.py
410
3.71875
4
words_count = [len(word) for word in open("./tmp/words.txt")] print(words_count) it = (len(word) for word in open("./tmp/words.txt")) # for each in it: # print(each) # # print("done") # for each in it: # 에러는 나지 않지만 it는 이미 소비 되었다. # print(each) roots = ((x, x ** 0.5) for x in it) print(type(roots)) print(t...
ad96b449267f2c830b6ebc0f6f0d8f13a1300f0a
bongjour/effective_python
/part1/zip.py
672
4.15625
4
from itertools import zip_longest names = ['dante', 'beerang', 'sonic'] letters = [len(each) for each in names] longest_name = None max_letter = 0 # for i, name in enumerate(names): # count = letters[i] # # if count > max_letter: # longest_name = name # max_letter = count for name, count i...
4f1ee7021d8707fcf351345b18d164ecc0ccd3db
aFuzzyBear/Python
/python/mystuff/ex24.py
1,953
4.28125
4
# Ex24- More Python Practicing #Here we are using the escape \\ commands int eh print statement. print "Let's practice everything." print "You\'d need to know \'bout dealing with \\escape statements\\ that do \n newlines and \t tabs" #Here we have made the poem a multilined print statement poem = """ \tThe lovely wor...
09f90dc3135c90b4e3a62d3ef3553f160c621f4a
aFuzzyBear/Python
/python/mystuff/ex33.py
1,228
4.375
4
#While Loops """A While loop will keep executing code if the boolean expression is True. It is a simple If-Statement but instead of running a block of code once if True, it would keep running through the block untill it reaches the first False expression. The issue with while-loops is that they sometimes dont stop. Th...
1766f40560f8a404a0c964a89198d185304c20c7
aFuzzyBear/Python
/python/mystuff/ex20.py
606
4.15625
4
#Functions and Files from sys import argv scrit, input_file = argv def print_all(f): print f.read() def rewind (f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file: \n" print_all(current_file) print "Now let's ...
2852d37c8d2ae4dbd5543642967f13d5d421398e
Teresawithoutah/tipcalculator
/tipcalculatorclasses.py
1,444
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 14 20:36:54 2021 @author: teresawithoutah """ def calculation(total_bill,guests): tip = float(0.15/100)*float(total_bill) #calculates final amount of bill with the tip included bill_with_tip = tip+total_bill return bill_with_...
3eaf372be32c3e268e205300e3354a4ee7662cf3
abhijitkrishna98/calculator-using-python-gui
/calculator.py
2,521
3.921875
4
from tkinter import * root = Tk("Simple Calculator") root.title=("Simple Calculator") e=Entry(root,width=35,borderwidth=5) e.grid(row=0,column=0,columnspan=3,padx=10,pady=10) count=0 def b_click(num): #e.delete(0,END) global count e.insert(count,num) count+=1 def clrfn(): e.delete(0,END) def btn_add(): n1=e...
7ec7ef4ff6009d48631bdb409658efe5922d67c0
Batyrsultan/WebDevelopment
/week9/informatics/3/1/342.py
61
3.59375
4
sum=0; for x in range(0,100): sum+= int(input()) print(sum)
f0b5e5d2dba2be185d90eeee5b028223532d27c8
Code4Blessings/Sherlock-And-Anagrams
/Sherlock.py
825
3.671875
4
#Use a helper function to slice the strings def get_substrings(str, n): rv = [] left = 0 right = left + n while right <= len(str): rv.append(str[left:right]) left += 1 right += 1 return rv # Complete the sherlockAndAnagrams function below. def sherlockAndAnagrams(s): h...
1e500e0639af52210e3a4424f0d139bbd24ed91e
ccdunn/euler
/e028.py
1,515
3.59375
4
""" Project Euler Problem 28 ======================== Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 ...
219857952deb7369d26f5e1af2560cdec94f677a
ccdunn/euler
/e014.py
2,669
3.8125
4
""" Project Euler Problem 14 ======================== The following iterative sequence is defined for the set of positive integers: n->n/2 (n is even) n->3n+1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13->40->20->10->5->16->8->4->2->1 It can be seen ...
540f74fe366848b09e83066d7acf7917e187f21d
ccdunn/euler
/e021.py
894
3.796875
4
""" Project Euler Problem 21 ======================== Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a =/= b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of...
47d5bfd30e7235c77ec5f0dec0326dc9102eabc6
ccdunn/euler
/e016.py
332
3.6875
4
""" Project Euler Problem 16 ======================== 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ import numpy as np import utils def solve(N): return np.sum(utils.basify10(2**N)) # print(solve(15)) # assert(solve(15) == 26) print(s...
fc81f7a65ff882b5fc5c31ded677de74c00d2cde
szhongren/leetcode
/453/main.py
499
3.921875
4
""" Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1. """ class Solution(object): def minMoves(self, nums): """ :type nums: List[int] :rtype: int """ ...
d14d761c03e00923a27b42cb8c0057fc84d9bfdd
szhongren/leetcode
/203/main.py
1,380
3.78125
4
""" Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5 """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = N...
849d44e8f0f1b8c89a77ee8cfe238ee4288f99bc
szhongren/leetcode
/18/main.py
1,664
3.6875
4
""" Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: The solution set must not contain duplicate quadruplets. For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solu...
e606a9053287de577971efd88d380379880e088c
szhongren/leetcode
/397/main.py
1,765
4.09375
4
""" Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2. If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of replacements needed for n to become 1? Example 1: Input: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1 Example ...
ed63ed849f6b7538d2deff1915b11188706e1cd8
szhongren/leetcode
/504/main.py
670
3.96875
4
""" Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Note: The input will be in range of [-1e7, 1e7]. """ class Solution(object): def convertToBase7(self, num): """ :type num: int :rt...
d37e27a702a74af02dce7b41c3a6a368f714ba2e
szhongren/leetcode
/129/main.py
1,697
4.15625
4
""" Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3 The root-to-leaf path 1->2 represents t...
631eefd55017f5489f3ab88ad8d3265bee4140bf
szhongren/leetcode
/216/main.py
1,167
3.78125
4
""" Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Example 1: Input: k = 3, n = 7 Output: [[1,2,4]] Example 2: Input: k = 3, n = 9 Output: [[1,2,6], [1,3,5], [2,3,4]...
3e1da2057f676cc84b88a2722cb5f9e229b40ef0
szhongren/leetcode
/223/main.py
876
3.890625
4
""" Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure. """ class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int ...
6873d908d5d7454fbebc15c2ae7072e7bb395836
szhongren/leetcode
/380/main.py
3,546
4.03125
4
""" Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each element must have the same p...
24c80dec8419342c615011e2615ddffc48b1522c
szhongren/leetcode
/38/main.py
1,048
3.90625
4
""" The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represent...
1a1a9e775108be74c02d4e90c42bf1928f94ca4f
szhongren/leetcode
/337/main.py
2,378
4.15625
4
""" The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the p...
c03eab4f2e5a9c81df1b3f7bda8a7f326e70976f
szhongren/leetcode
/236/main.py
3,250
4.09375
4
""" Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of i...
2144034f70b67b2a5e8cd156f86b6f530c43b7a4
szhongren/leetcode
/507/main.py
1,004
3.8125
4
""" We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself. Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not. Example: Input: 28 Output: True Explanation: 28 = 1 + 2 + 4 + 7 + 14 ...
7888b8f00d767d389631c8245b1a307fb4ddf4aa
szhongren/leetcode
/109/main.py
1,709
3.890625
4
""" Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): return "[" + str(self.va...
522b1b01a64b08202f162b7fae780dbf2219066e
szhongren/leetcode
/473/main.py
1,692
4.3125
4
""" Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Your input w...
6fc6258cfd47669961d8269a6eab4c538a431318
szhongren/leetcode
/204/main.py
935
3.90625
4
""" Count the number of prime numbers less than a non-negative number, n. """ import math class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ primes = [True for _ in range(n)] count = 0 seived = eratosthenes(primes)...
61be857662343abf10a4858ae9afb178ba1e48c5
szhongren/leetcode
/69/main.py
679
4.09375
4
""" Implement int sqrt(int x). Compute and return the square root of x. """ class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ root = 0 while root * root <= x: root += 1 return root - 1 def mySqrtRecur(self, x, lo,...
8c4a94b638357bc57e40f37f881a21103d32e5fd
szhongren/leetcode
/functional.py
764
3.71875
4
class animal(object): def __init__(self, number_of_legs, has_fur): self.number_of_legs = None self.has_fur = None def get_num_legs(self): return self.number_of_legs class cat(animal): def __init__(self): self.number_of_legs = 4 self.has_fur = True clas...
c5213f71a0091d8d138ae239f0bded93a0831e5d
szhongren/leetcode
/147/main.py
1,641
4.03125
4
""" Sort a linked list using insertion sort. """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): return str(self.val) + " => " + str(self.next) def make_list(ls): if len(ls) == 0: ...
21e4d7833cc352e22be5033f91b64268f194f8f6
szhongren/leetcode
/657/main.py
963
4.09375
4
""" Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D...
0be861e3827d357a585311333420797276b0bc84
szhongren/leetcode
/513/main.py
1,109
3.984375
4
""" Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 3 Output: 1 Example 2: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7 Note: You may assume the tree (i.e., the given ro...
e0eacf555251db7ff620ddd09b1ffaa0161c5c82
szhongren/leetcode
/172/main.py
709
3.8125
4
""" Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity. """ def fact(n): results = [i for i in range(n + 1)] results[0] = 1 for i in range(1, n + 1): results[i] *= results[i - 1] return results[-1] class So...
a2291d48126dba1b6a628a33ace0ce6d2d25b560
szhongren/leetcode
/117/main.py
2,020
4.0625
4
""" Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra space. For example, Given the following binary tree, 1 / \ 2 3 / \ \ ...
ca7e3e0996a95878818e9152af70117a6d930f9f
szhongren/leetcode
/152/main.py
1,449
3.953125
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. """ class Solution(object): def maxProduct(self, nums): """ :type nums: Lis...
399b7084aebfc8ba71fa500a23725e33b2fff9ab
zipeiwei123/interview_questions
/leetcode_124.py
1,013
3.65625
4
"""????""" # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxPathSum(self, root: TreeNode) -> int: #initial the max gain variable max_gain = float("-inf") #call get ...
5df943af63521de1d9010bef32fdd92093edc745
zipeiwei123/interview_questions
/leetcode_5.py
1,827
3.765625
4
"""Define the longest substring a condition to check if substring is a panlindrone Use a N by N matrix to check if the index is palindrome""" class Solution: def longestPalindrome(self, s: str) -> str: #special case if not s: return "" iAns, jAns = 0, 0 #create a m...
db3df0778708c76daea3bca20cc053f874e43dcc
zipeiwei123/interview_questions
/leetcode_128_longest_sequence.py
1,149
3.859375
4
"""Union find is most likely to detect cycles, looks similar to dfs with backtracking""" class Solution: def longestConsecutive(self, nums: List[int]) -> int: #set nums to set nums = set(nums) #use a dictionary to track each correspondence continous sequence tracking = {} #cr...
50d96580cd19a69136dd0107faf698bde9636533
zipeiwei123/interview_questions
/trie.py
365
3.921875
4
""" A tree like structure , used in key word search""" """ A / \ p c """ #Build the trie longest_word_len = 26 class Node(): def __init__(self, key): self.next = [None]*longest_word_len #check if this is the end self.end_word = False class Trie(): def __init__(self): self.ro...
3427618d0c6c2af91840cc4c9e38bc26939e5493
dfki-ric/movement_primitives
/movement_primitives/plot.py
6,422
3.9375
4
"""Tools for plotting multi-dimensional trajectories.""" import matplotlib.pyplot as plt # extracted from seaborn to get rid of dependency: # https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py PALETTE = ["#4C72B0", "#DD8452", "#55A868", "#C44E52", "#8172B3", "#937860", "#DA8BC3", "#8C8C8C",...
4191e3df6e5d944561e92b478c547641a3ad8c95
AI-System/ai-learning-material-old
/Basic-Python/code/test_str.py
1,860
3.546875
4
''' 字符串类型 s='abc' type(s) # <class 'str'> s2='10' type(s2) # <class 'str'> # 在字符串中输入特殊值需要转义 s3='ab\'cd' print(s3) # ab'cd # 换行举例 print("asd\nfas") # asd # fas # 屏蔽特殊符号 使用 r print(r"asd\nfas") # asd\nfas # 关于字符串下标与切片的使用 name='abcde' print(name[-1]) # e 取倒数第一个字符 print(name[-2]) # d 取倒数第二个字符 print(name[0]) # a print...
3c45b4ab5409c608a1b43758a39e3428514df0d5
AI-System/ai-learning-material-old
/Basic-Python/code/test_list.py
2,356
3.890625
4
''' list 可以完成大多数集合类的数据结构实现 列表中元素类型可以不相同,支持数字、字符串、甚至可包含列表(嵌套) 索引值从0开始,-1表示从末尾开始的位置 +是列表连接运算符, * 是重复操作 举例: a=[10,20,30] # 定义一个列表 type(a) # <class 'list'> a[0] # 10 a[1] # 20 a[-1] # 30 a[1]=100 # 修改某一项的值 print(a) # [10,100,30] a[1:2] # [100] a[1:] # [100, 30] b=[8,9] print(a + b) # [10,100,30,8,9] print(b * 2) # [...
284c9e0fdddd2de7d6dd5257f565c3e3dca501d2
AI-System/ai-learning-material-old
/Basic-Python/code/test_staticmethod&classmethod/1.py
1,448
4.03125
4
# 最简单的调用 class A: def fun(self): print('aaaaaa') a = A() a.fun() # aaaaaa print('⭐️ ' * 20) class B: def fun(): print('bbb') fun = staticmethod(fun) # 将fun方法设置为【静态方法】,注:静态方法无参数 def demo(self): print('demo') demo = classmethod(demo) # 类成员方法定义 和静态方法的区别是 一个无参数,一个有参数 B.fun() # bbb B.demo() # de...
10c13ace9bc8e87cf08e9f5a4947808deb630506
AI-System/ai-learning-material-old
/Basic-Python/code/test_oop/2.py
814
4.125
4
### 类的构造方法 __init__ class A: def __init__(self): # 实例化时自动调用,一般用于初始化 print('init ...') def fun(self): print('class A...') a = A() # 实例化 A 时, 如果内部有 __init__ 方法, 那么会调用该方法 print('✨' * 20) class Person: name="" age=0 def __init__(self): pass def getInfo(self): print(self.name, " : ", s...
ae558f0ad17d4b57950974c1f6a5e5fd2449cf5f
romainroehrig/DEPHY-SCM
/utils/thermo.py
5,344
3.640625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on 27 November 2019 @author: Romain Roehrig """ import sys import math import numpy as np import constants as cc def rt2qt(rt,units='kg kg-1'): if units == 'kg kg-1': return rt/(1+rt) elif units == 'g kg-1': return rt/(1.+rt/1000....
ee6889d2292beb4a52e3439f4c2167208cf499c0
MifengbushiMifeng/pyanalyze
/pyvar/param_py.py
344
3.671875
4
class Person(object): def __init__(self, name, age): self._name = name self._age = age def get_person_info(self): return self._name + ' / ' + str(self._age) def func(some_one: Person): str = some_one.get_person_info() print(str) if __name__ == '__main__': p = Person('Jon...
6f52a20ceeec2cb248a3a3c578b2878b7ad2fc51
MifengbushiMifeng/pyanalyze
/multi_process/method_param.py
423
3.984375
4
def func(flag=False): if flag: print('The func will run.') else: print('The func will not actually run.') if __name__ == '__main__': func() func(True) a_str = '' print(a_str.replace('-', '??')) a_str = 'a-b' print(a_str.replace('-', '??')) a_str = '' if a_str: ...
7201bd29470331df66b7b4f0ca13edd1be6cad9c
NathanDeMaria/spider
/model/__init__.py
1,170
3.625
4
class Config(object): """ A configuration object set by command line, for now. """ def __init__(self): self._base_dir = None self._verbosity = 5 # defaults to debug mode @property def base_dir(self): return self._base_dir @base_dir.setter def base_dir(self, va...
22b7c295aae50e57a080d6067fbd132a87fe8167
AstinCHOI/book_algo-strategy
/3_disign-paradigm/10_mergesort.py
1,904
3.8125
4
# http://interactivepython.org/runestone/static/pythonds/SortSearch/TheMergeSort.html def mergeSort(alist): print("Splitting ", alist) if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) ...
681acc05222ab3c86ede7b62f57300355c7f6dde
AstinCHOI/book_algo-strategy
/2_analyse-algo/3_pigeonhole.py
402
3.8125
4
import sys # fraction a/b to decimal # suppose a>=0, b>0 def printDecimal(a, b): it = 0 inf = [] while a > 0: if it == 1: sys.stdout.write('.') sys.stdout.write(str(a/b)) a = (a % b) * 10 if it >= b + 1: sys.stdout.write('..') break ...
00a6a4e6127fc21ce1bea97f65dd3e57303af769
Taher-Dohadwala/cs490vis_final
/map.py
2,341
3.59375
4
""" This script is for testing the plotly mapping. The counties variable holds the mapping layout plotly needs for BOTH counties and states If we create bins for the covid cases/deaths we can create a discrete color theme """ import pandas as pd import plotly.express as px import numpy as np from datetime import d...
8f9b2add430e5bffc9b01e609d81c77d31c32032
ptabis/pp1
/02-ControlStructures/29.py
193
3.765625
4
tab = [15, 8, 31, 47, 2, 19] print("tab: ", end="") for el in tab: print(el, end=" ") print("\ntab in reverse: ", end="") for i in range(1, len(tab)+1): print(tab[len(tab)-i], end=" ")
e8e357c47cb7aa60257386eaedc137cd8fb232e7
ptabis/pp1
/01-TypesAndVariables/29.py
180
3.609375
4
from random import randint l = randint(1,6) a = int(input("Podaj, ile oczek wyrzucił komputer: ")) print("Komputer wyrzucił: {}".format(l)) print("Zgadłeś: {}".format(l == a))
ea5f6018a0b17e3a60afe681c2e6d66e235e758f
ptabis/pp1
/02-ControlStructures/19.py
122
3.9375
4
N = int(input("Podaj ostatni element: ")) print("Ciąg arytmetyczny różnicy 3:") for i in range(1, N+1, 3): print(i)
2ec5f2538c9911bba18c8a40a3554980756a8b0f
lucypeony/stanford_algs
/count_inversions.py
1,444
3.890625
4
# -*- coding: utf-8 -*- """ Inversions Count Given an array containing the numbes 1,2,3... in some arsitary order Output the number of inversions inversion means : number of pairs (i,j) of array ,where i<j & a[i]>a[j] Created on Wed Aug 10 15:56:07 2016 @author: Lucy """ def merge_sort_count_inversions(arr): #...
31da67b1d3370357b831095d1e5519f290d58852
lucypeony/stanford_algs
/dijkstra_algo.py
1,123
3.78125
4
# -*- coding: utf-8 -*- """ Dijkstra's Algorithm Created on Wed Sep 7 19:45:33 2016 @author: Lucy """ def dijkstra_basic(graph,s): #constants INFINITE = 1000000 #A[] : store shortest path , to minimise the a[v]+l[v,w] A={} X =set(s) Y =set(graph.keys()) for node in Y : A[node] = INFINITE ...
f60e5a3b14c5d9844808dc5a418d7f1d2a1937d7
Jules-NC/OOC-Segmentation
/QBT.py
2,794
3.59375
4
import Tree from Image import * def generate_leafs(boundary, IMSIZE): """ IS = b = ImageSize(4,2) b = Boundary(0,0,1,1) generate_leafs(b, IS) will return: 0 1 3 4 """ return [Tree.Node(name=int_coords_ibloc_to_iimage(i, IMSIZE, boundary), altitude=0) for i ...
f0ddb41605d2004c1c556065213dec104bffc8ec
hyhplus/Pythonic
/myString/stringFrequency2.py
714
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 编写一个Python程序来计算字符串中的字符个数(字符频率) 方法二: 简单判断, 原理还是调用了Python内置函数str.count(i) """ currentStr = input("input a sentence: ").replace(' ', '') # 输入字符串并去掉空格 newStr = '' for i in currentStr: if currentStr.count(i) <= 1: # 如果字符数为1 newStr += i newStr += ':...
180a18f1ea7c6d9ec933f1bf2218ff240cf0d480
t1610427/100knock
/chapter2/q18.py
1,584
3.578125
4
col3=[] i=0 with open('hightemp.txt',encoding="utf-8_sig") as f: f_list=f.readlines() col3=sorted(f_list, key=lambda x:x.split("\t")[2]) #sortedは昇順、#lambda無名関数 col3.reverse() #逆順にする print(col3) ''' 実行結果 ['高知県\t江川崎\t41\t2013-08-12\n', '岐阜県\t多治見\t40.9\t2007-0...
4671c9f8d366e45e97a92920d6190e1d7c65d894
tdongsi/effective_python
/ep/item13b.py
1,973
4.15625
4
NUMBERS = [8, 3, 1, 2, 5, 4, 7, 6] GROUP = {2, 3, 5, 7} def sort_priority(numbers, group): """ Sort the input numbers but put those in "group" first. :param numbers: list of input numbers. :param group: set of numbers in priority group. :return: True if any number in priority is found. """ f...
6c73b0dade33e1a6dfbd3bfc1bb9e43ec21dabbf
tdongsi/effective_python
/ep/item13.py
924
4.46875
4
meep = 23 def enclosing(): """ Variable reference in different scopes. When referring to a variable not existing in the inner scope, Python will try to look up in the outer scope. """ foo = 15 def my_func(): bar = 10 print(bar) # local scope print(foo) # e...
17e629126132dee9b9cf6c8cd2e9949fb542d1c6
Mehdierli/PyhtonTemplate
/pickle_t.py
566
3.703125
4
# -*- coding: utf-8 -*- """ The pickle module: It translates almost any type of object into a string suitable for storage in a database, and then translates strings back into objects. pickle.dumps: takes an object as a parameter and returns a string representation (dumps is short for “dump string”) ...
324386ad053d7baf2e6b0549d5f085b217fbb67e
subrata-cloud/projects
/projects/Python_Drills/test_branching_and_looping.py
1,211
3.71875
4
import unittest from branching_and_looping import * class TestBranchingAndLooping(unittest.TestCase): def test_integers_from_start_to_end_using_range(self): inputs_and_outputs = [ ((0, 4, 1), [0, 1, 2, 3]), ((5, 8, 2), [5, 7]), ((8, 5, -1), [8, 7, 6]), ((8...
80ab95e2f3fac83e29c69610c1cd679c5f39ba3e
subrata-cloud/projects
/projects/Python_Drills/test_functions.py
969
3.84375
4
import unittest from functions import * class TestBranchingAndLooping(unittest.TestCase): def test_is_prime(self): inputs_and_outputs = [ (2, True), (3, True), (4, False), (63, False), (97, True), ] for n, expected_output in inp...
3d8fa1d96a89e06299f099b1f4ccc88cf33b5d97
oigwe/learning_data_analyzing
/python/Step 1/2.Python Data Analysis Basics: Takeaways.py
1,229
4.1875
4
#Python Data Analysis Basics: Takeaways #by Dataquest Labs, Inc. - All rights reserved © 2020 #Syntax #STRING FORMATTING AND FORMAT SPECIFICATIONS #Insert values into a string in order: continents = "France is in {} and China is in {}".format("Europe", "Asia") #Insert values into a string by position: squares = "{0}...
0a4042a5c22e529574bc1ccb8f1f6bbfad9c7894
oigwe/learning_data_analyzing
/python/Step 1/Lists and For Loops: Takeaways.py
1,567
4.375
4
#Lists and For Loops: Takeaways #by Dataquest Labs, Inc. - All rights reserved © 2020 #Syntax #Creating a list of data points: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5] #Creating a list of lists: data = [row_1, row_2] #Retrieving an element of a list: first_row ...
42869cb6c8eea536ec66700c992a32f34531caa4
tanghulu9312/mygithub_testrepro
/pytest1/day10/红绿灯.py
979
3.515625
4
#!/usr/bin/env python #-*- coding:utf-8 -*- ''' @author:Administrator @file:红绿灯.py @time:2018-08-30 14:49 ''' import threading import time event=threading.Event() def light(): event.set() count=0 while True: if count > 5 and count < 10: event.clear()#把标志位清了 print("\033[41;1...
623b99aed62ef6f023450b1597c0ba8ad0872309
tanghulu9312/mygithub_testrepro
/pytest1/day3/mall_cart.py
3,604
4
4
#!/usr/bin/env python #Author:TangHu #-*购物车程序*- ''' 需求: 1.启动程序后,让用户输入自己的工资,然后打印商品列表 2.允许用户根据商品编号购买商品 3.用户选择商品后,检测余额是否够,够就直接付款,不够就提醒 4.可随时退出,退出时打印已购买商品和余额 用户入口: 1.商品信息存在文件里 2.已购商品,余额记录 商家入口: 2.可以添加商品,修改商品价格 ''' #打开登录次数文件 def openTimeFile(): file=open(r'c:\Python\practice\times.t...
181db0358ccffb5976e169fe42daf6332fd480e7
tannernickels/Portfolio
/RFID_Encryption/traverse.py
4,764
3.796875
4
#!/usr/bin/env python3 import subprocess, os, sys '''Return to root directory (cd .) via chdir()''' def returnToRoot(): os.chdir(rootDirectory) '''Checks the rwx permissions for a file and adds them to the dictionary p''' def addPermissions(filename, p): r = os.access(filename, os.R_OK) w = os.access(fil...
872e05c35f251fa812a189381fdc5b68ff2391f7
Emilcrafter/Runescape-music
/snake.py
1,608
3.734375
4
"""The first line of input contains a single integer 𝑛 n (1≤𝑛≤100 1 ≤ n ≤ 100 ) representing the number of polygons to be painted. Following this are 𝑛 n lines each describing a painted polygon. Each polygon description starts with an integer 𝑚 m (3≤𝑚≤20 3 ≤ m ≤ 20 ) indicating the number of sides in the polygo...
bb3a93103fe04282e54714a15308feb4147d0c8e
aitorcalero/PracticePython
/OddOrEven.py
153
4.15625
4
num = input("Enter a number:") mod = int(num)%2 if mod == 1: print("You've entered an odd number") else: print("You've entered and even number")
5dcc59a0e09fc7f7e95db9da4cb2ed7c073ee5d2
anil-gurbuz/Stylometric-Analyser
/main.py
9,697
3.78125
4
# Anil Gurbuz - 29628792 # 16.05.2018 - 27.03.2018 # This module is the module that contains all other tasks to # create the whole program # get_input() function prompts the user to enter the names/paths of text files # that will be analysed then in the main() function all other classes' instances # are created and use...
25cf42c70ad691893aa86e8cd6c5f8ca4cf7dce5
edselc/Py-Rice-Vending
/RiceVending.py
2,076
4.03125
4
line_sep = '----------------------' rice = float(500) price = 40 add = 1 buy = 2 buy_kilos = 0 aRice = float(0) admin = {'username' : 'edselcalanoga', 'password' : 'Calanoga'} print('RICE VENDING MACHINE') print(line_sep) print('In stock', rice , 'kilos') print(line_sep) c = input('Enter 1 if you want to add ...
4a320a45f4fa121a21093e6741794e537d26a638
OrangeFina/FrontEnd-FinApp-SIMPLIFI
/backend/Risk/risk_api/stockexplorer.py
12,331
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[30]: import time import requests from bs4 import BeautifulSoup from bs4.element import Tag import csv import json import pandas as pd import random #prompt user for input - fixed for now #user_name = input("What is your name?") #user_age = input("What is your age?") #user_...
1d3cf490dccbe2d9cf89d2eb638409715597bc0c
Raza403/workspace
/pset6/sentiments/analyzer.py
1,495
3.640625
4
import nltk import re class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" #loading positive.txt as dict self.positives = [] #opening file for reading as fpos with open('positive-words.txt', 'r') as f...
c84cb5c7981a8ebcd1d35c17ff4b9843d078beed
Stephen-Kamau/beginning
/filetestinginput.py
704
4.0625
4
print("Please Enter the name of your file you wish to write on:") x=input() yourfile=open(x+".txt","w+") names=[]#declare an empty list for the names to be filled. prices=[]#declare an empty list for the prices to be filled. x=input("Please enter the number of items you wish to purchse") while len(names)<int(x): ...
49875063ce362f968f60f8ef71cdea5fdd36283d
Team-Afro-Dog/Last-Run
/Modules/colors.py
672
3.9375
4
from __future__ import print_function ''' Creates dictionary with color names matched to their RGB tuple values. Color names are capitalized. ''' def colors (): clrs = open("colors.txt", 'r') clr = {} #Dictionary that will be returned name = "" i = 0 for line i...
f44528c29da72cecfa1610c730a9ec97be806e8a
mohammedrafi1997/mohammedrafi1997
/ses2prog3.py
180
4
4
a=[1,2,3,4] print(a) print(a[2]) for i in a: print("num is printed") if(i>5): print("i is greater than 2") else: print("all the num are lesser than 5")
2006c12ed1035dd7834e0d4f465d534cd54097d2
meena29/Python_Assignments
/arrays/binary_duplicate.py
500
3.765625
4
def binary(arr,val): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] < val : low = mid + 1 elif arr[mid] > val: high = mid - 1 else: #check for array bounds if mid - 1 < 0: return mid #if the index is the first occurence if arr[mid - 1] != val: ...
ac61edd25ba36bd293fdcfe05ed2b36c176227c5
meena29/Python_Assignments
/generators/readfile_gen.py
144
3.6875
4
def readfile(path): with open(path, 'r') as f: for line in f : yield line for item in readfile("ex.txt"): print(item)
2d7390e02f15eafa0942fddb5b5263003393e237
StijnVanE/python-2
/hangman.py
2,247
3.6875
4
import random from woorden import woorden_lijst alfabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] print("type \"?\" in om een woord te raden") def speel(): woord = random.choice(woorden_lijst) print("het woord hee...
a7f820d036694c143ad5950b5e58abdccac4aca5
margonjo/Lists
/attemptOfListsWithoutLists.py
5,628
4.3125
4
#Marc Gonzalez #9/12/14 #list RnR 1.1 studentA = input("please enter the name of the first student: ") studentB = input("please enter the name of the second student: ") studentC = input("please enter the name of the third student: ") studentD = input("please enter the name of the fourth student: ") studentE = ...
67357b1f0538c96503cc11ca5692dab5db3640cf
NataliaVelasquez18/Election_Analysis
/Practice/Python_practice.py
7,690
4.34375
4
print ("Hello World!") #Conditionals #counties counties = ["Arapahoe","Denver","Jefferson"] if counties[1] == 'Denver': print(counties[1]) if counties[2] != 'Jeffersion': print(counties[2]) #temperature temperature = int(input("What is the temperature outside?")) if temperature > 80: ...
944bb6d2186578064201689ef454527acbf8eddb
nima-siboni/narrow-corridor-ai
/narrow-corridor.py
2,827
3.546875
4
import numpy as np np.random.seed(0) import matplotlib.pyplot as plt from RL_library import return_pointwise_A from RL_library import Bellmann_iteration from RL_library import Q_estimation_for_state_s # In this code the optimal policy is found for: # two agents who want to go to their desired places which are at the t...
b24d72c5597a6e03e72c96882c4a40a744eb1e4f
garaged/codechallenges
/adventofcode/4/pass-b.py
609
3.890625
4
def check_pass(pp): words=pp for i in range(len(words)): for j in range(i+1, len(words)): if ( words[i] == words[j] or is_anagram(words[i], words[j]) ): print(pp, "no pasa") return False print(pp, "si pasa") return True def is_anagram(w1, w2): print("is", w1, w2) list_str1 = list(...
d7012b0dd731e0f1374276801a7a6cb2b024ad10
prey99/Practicas
/exerciseDisplayInventory02alphaSorted.py
3,098
4.21875
4
# You are creating a fantasy video game. The data structure # to model the player’s inventory will be a dictionary where # the keys are string values describing the item in the inventory # and the value is an integer value detailing how many of # that item the player has. For example, the dictionary # value {'rope...
c9455d7e334e5b872160ada2fdb3e85564531050
nefeithu/udacity-python
/001/rename_files.py
554
3.796875
4
import os def rename_files(): # (1)get file names saved_path = os.getcwd() print saved_path # 字符串前加“r”,字符串不会被转义 file_list = os.listdir(r''+saved_path+'\prank') print file_list # (2)for each file, rename filename os.chdir(r''+saved_path+'\prank') for file_name in file_list: ...
251c0b619c768755c7fce6e52c3e19bfbaa24d71
hasnatosman/python_documentation
/fib_func2.py
196
3.703125
4
def fibo(n): fibo_list = [] a, b = 0, 1 while a < n: fibo_list.append(a) a, b = b, a + b return fibo_list x = fibo(100) print('Fibonacci series: ', x)
ca16c591db0eabea6b67b742beba71b2de76c8e8
alex-piccione/CryptocurrenciesMonitor
/src/utils/FileWriter.py
796
3.640625
4
class FileWriter: def __init__(self, file): self.file = file self.stream = None def __del__(self): if self.stream and not self.stream.closed: self.stream.flush() self.stream.close() def write(self, text: str): if not self.stream: self._open_file()...