blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7ff943626f8fbc54005d074f7af59e7b7a4f3975
Litianyi123/INST326_Final
/importing.py
4,047
3.53125
4
"""importing data from a excel file""" import openpyxl import sys import argparse class Import: """Import data from excel file Attributes: path(string): path of the excel fiel file(object)" : workbook active sheet object """ def __init__(self, path): """Import data from ...
a2c6a535fa8edd3f10734726affa1070057bf92a
sandeep-varma8029/cs657
/hw1/hydra_files/\
6,420
3.578125
4
#!/usr/bin/env python import sys, numpy from math import sqrt word2count = {} year_count = {} totalCount = 0 rangecount = {} includeMinMax = False for line in sys.stdin: line = line.strip() word,count, year = line.split() totalCount +=1 try: count = int(count) except ValueError: c...
275f282e17fbc54b8b46cd84a714fbcfa48d2844
mladuke/Algorithms
/pybites107.py
564
4.0625
4
def filter_positive_even_numbers(numbers): """Receives a list of numbers, and returns a filtered list of only the numbers that are both positive and even (divisible by 2), try to use a list comprehension.""" return [i for i in numbers if (int(i) % 2 == 0 and int(i)>0)] numbers = list(range(-10...
824834ec018fb533b5e36bd04f3e60e4488d7713
Igor-Victor/PythonExercicios
/ex062.py
514
3.828125
4
from rich import print print('[bold blue]Exercício 62: P.A turbinado!![/bold blue]') primeirotermo = int(input('Primeiro termo da P.A: ')) razao = int(input('Razão da P.A: ')) primeiro = primeirotermo contador = 1 total = 0 repeat = 10 while repeat != 0: total += repeat while contador <= total: print(pr...
66109d368fa67dfa09cc3909a70c4e4799c5fb1b
sidaker/dq
/pythonconcepts/functprgram/gl_local_nlocal.py
302
4.125
4
x = "outer variable" y = "global variable" def foo(): # UnboundLocalError: local variable 'x' referenced before assignment #x = x * 2 global y print(f'y inside is {y}') y = "update global" print(f'x inside is {x}') foo() print(f'y outside is {y}') print(f'x outside is {x}')
3443b3a71e70ee14902cf77ae0842b14a00422e2
stefanobozicek/python
/py-h1.py
554
3.96875
4
wlc = "welcome to the mood checker!" print(wlc) mood = input("What is your mood today Sir? (choose between good, sad, excited and relaxed): ") if mood == "good": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep breath 3 times.") elif mood == "sad": print("Take...
2057326205e39c27b6f96b6718983578a90425b4
yang4978/LeetCode
/Python3/0143. Reorder List.py
1,046
3.890625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverse_list(self,head): if not head: return head temp = head new_head = None while temp: tt = ...
62b08bd75ab73ee725585e160caa7445f1297abd
SunmiYoonDev/python_team_notes
/1_greedy_algorithm/CoinChange.py
237
4.09375
4
change = 3.56 count = 0 # The coins arranged in ascending order coin_types = [2, 1, 0.25, 0.1, 0.05, 0.01] for coin in coin_types: # Count a maximum number of coins to make change count += n // coin n %= coin print(count)
518b98083e78902d56a62361d382f2590a4a7b90
jchwenger/Learning
/nltk/sentdex/nltkTutorial2.py
810
3.796875
4
# Tutorial bz SentDex creator here : https://www.youtube.com/watch?v=FLZvOKSCkxY&list=PLQVvvaa0QuDf2JswnfiGkliBInZnIC4HL import nltk # Lesson 2 - stop words from nltk.corpus import stopwords from nltk.tokenize import word_tokenize example_text = "Hullo hullo, Mrs. Father Mucker! What's up in Trumplandia? Here the...
4121cde5ce99b3e975d5a589f554682730964214
yabur/LeetCode_Practice
/Trees/DFS_PreOrderEx.py
1,492
4.1875
4
# PreOrder Example # 144. Binary Tree Preorder Traversal # Given a binary tree, return the preorder traversal or its nodes' values. # Input : [1,null,2,3] # Output : [1,2,3] # # class TreeNode: # Node Constructor def __init__(self, val=0, left=None, right=None): ...
bd028289de75b42c8cca2137051fc4371aac0d4a
stayari/informationsteori
/handin2/alice.py
444
3.671875
4
import regex import re from collections import Counter text = open('Alice29.txt', 'r').read() words = re.findall(r'\w+', text.lower()) word_count = Counter(words) def make_word_string(input_string): word_string = '' for word in input_string: word_string = word_string + word return word_string def...
5a421bbe25322d9b7f2c0da931e03fb6e087c755
vmirisas/Python_Lessons
/lesson16/part12/exercise11.py
768
4.09375
4
class Author: def __init__(self, full_name, email): self.full_name = full_name self.email = email class Book: def __init__(self, title, authors, price, copies): self.title = title self.authors = authors self.price = price self.copies = copies def print_full...
b43fdb54d8a33f426141230aec36e7898198238d
nicolastobon09/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/101-remove_char_at.py
222
3.671875
4
#!/usr/bin/python3 def remove_char_at(str, n): dest_str = [] for idx in range(len(str)): if idx is n: continue else: dest_str.append(str[idx]) return (''.join(dest_str))
a2600492af2913dcadf7ace7bb7b4dfcf67b4743
zzzfight200/PythonPractice
/password.py
255
3.515625
4
import random length = int(input("enter the length of password:")) list = ["a","b","c","d","e","f","g","h","i","j","k","l","1","2","3","4","5","6","7","8","9","0","!","@","$","%","^","&","#"] password = "".join(random.sample(list, length)) print(password)
450e57650244bfec009267dc7961714cfc297815
nielschristiank/DojoAssignments
/Python/python_fundamentals/scoresGrades/scoresGrades.py
504
3.828125
4
'''SCORES AND GRADES''' import random def scoresGrades(num): score = 0 grade = "" for i in range(num): randNum = random.randint(0,100) score = randNum if randNum >= 90: grade = "A" elif randNum >= 80: grade = "B" elif randNum >= 70: ...
67410eea5b5723e1db71f14743a4748f014daeb7
csikosdiana/Project-Euler
/problem_0079.py
2,208
4.03125
4
''' Passcode derivation A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317. The text file, keylog.txt, contains fifty successful lo...
553f2df51e788b9bbe843f8e3a0ca0ce86cffcc3
Banana-zhang/Python_Doc_Learn
/mokuai_lei/shengchengqi.py
531
3.875
4
def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] for char in reverse('golf'): print(char) output2 = sum(i*i for i in range(10)) # sum of squares print(output2) xvec = [10, 20, 30] yvec = [7, 5, 3] output3 = sum(x*y for x,y in zip(xvec, yvec)) # dot...
3be70735c73fec6ba77c02a3867152abe95fecf9
Hugomguima/FEUP
/1st_Year/1st_Semestre/Fpro/RE's/RE11/sort_by_f.py
203
3.890625
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 12 11:45:59 2018 @author: Hugo """ def sort_by_f(l): return sorted(l,key = lambda x: x if x < 5 else 5-x) #print(sort_by_f([-1, -2, 2, 15, 99]))
65134755d372c4acbf6e7c4af0eb8297e4222007
eye-of-dev/algo_and_structures_python
/Lesson_3/2.py
871
4.21875
4
""" 2. Во втором массиве сохранить индексы четных элементов первого массива. Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа. """ from ...
699d220f09c78d1d4c3de2ea11faef82a7c1956e
elliot4711/excercises
/excercise_4.py
111
3.5625
4
def angry(phrase): phrase = str(phrase) phrase = phrase.upper() print(phrase + "!!!") angry("hej")
1ac2701dd5423c39769445826e3b110659936750
HyunsuChoi-git/Python
/basic05/algo/Algo04.py
359
3.84375
4
def gcd(a, b): i = min(a, b) while True: if a % i == 0 and b % i == 0: return i i -= 1 def gcd2(a, b): print("gcd:", a, b) if b == 0: return a return gcd2(b, a % b) def fibonacci(n): print(n-2, n-1) if n <= 1: return n return fibonacci(n-2) +...
8fbcb61527112c75a2dd83946aafc47d4510484f
dalv0911/dalv0911.github.io
/code/hash_table.py
1,235
3.859375
4
class Item(object): def __init__(self, key, value): self.key = key self.value = value class HashTable(object): def __init__(self, size): self.size = size self.table = [[] for _ in range(self.size)] def _hash(self, key): return key % self.size def set(self, key...
01edf8bcad1bd0934dbf5f0ecd96d940ec091938
moon0331/baekjoon_solution
/programmers/Level 1/행렬의 덧셈.py
223
3.515625
4
def solution(arr1, arr2): return [[x+y for x, y in zip(row1, row2)] for row1, row2 in zip(arr1, arr2)] print(solution([[1,2], [2,3]], [[3,4], [5,6]]) == [[4,6],[7,9]]) print(solution([[1],[2]], [[3],[4]]) == [[4],[6]])
3c9ae0b070b46fc6471a8452472410b409afab01
dyanfee/code
/25.k-个一组翻转链表.py
1,125
3.546875
4
# # @lc app=leetcode.cn id=25 lang=python3 # # [25] K 个一组翻转链表 # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: ...
de437be8ff2cbe6c509146d72cad7d720f99d2fe
AnthonyArmour/holbertonschool-higher_level_programming
/0x0B-python-input_output/12-pascal_triangle.py
708
3.625
4
#!/usr/bin/python3 """returns list of integers representing pascals triangle""" def pascal_triangle(n): """pascals triangle method""" if n <= 0: return list() matrix = list() lst = list() x = 1 idx = 0 matrix.append([1]) for nn in range(n - 1): lst.append(1) if ...
203e7b8c205771d22c60b1934857a4d8c3a94ec7
alisuki/hechi
/Python/workspace/Kevien/第5篇/类.py
617
4.03125
4
#!/usr/bin/env python # coding=utf8 ''' Created on 2016-12-19 @author: hechi ''' #class 创建类 class Person(object): ''' 类的注释 ''' # def __init__ 实例初始化类的函数,包含:name,age,sex,job def __init__(self, name,age,sex,job): ''' Constructor ''' self.name = name self.age =...
0436c0696018d4466a75431ad073e27095dc41a9
sindrimt/TDT4110
/Python Øvinger/Øving 5/Oving5_4.py
356
3.921875
4
alder = int(input("Hva er din alder? \n")) if alder < 5: print("Småbarn") print("Gratis") elif alder >=5 and alder <=20: print("Barn") print("20kr") elif alder >=21 and alder <=25: print("Student") print("50kr") elif alder >=26 and alder <=60: print("Voksen") print("80kr") else: prin...
1825248fd79c65eb59f5619a97e5cf939727ac7e
marcoludd/text-adventure
/controller.py
5,530
3.5
4
#!/usr/bin/env python '''Controlling it all''' import view import game import os import sys from time import sleep class Controller: def __init__(self): self.view = view.View() self.game = game.Game() self.clear_screen() # Clear terminal - works on windows and linux def clear_scree...
d8dcc4258b936dfb8f409a0c9ebcbec737f83a77
childen/JetteCoefficient
/main.py
896
3.640625
4
import sys name1 = sys.argv[1] name2 = sys.argv[2] def countLetters(str): counts = list() str = str.lower() str = str.replace(" " , "") seen = list() for letter in list(str): if letter not in seen: seen.append(letter) print(seen) counts.append(str.count(...
7a77f9958b59ed138ae2b2b6f9de309c709da913
code-drops/hackerrank
/Algorithms/01. Warmup/01. Solve Me First.py
245
3.75
4
''' Complete the function solveMeFirst to compute the sum of two integers. ''' if __name__ == '__main__': n = int(input()) l = input().strip().split() l = [int(i) for i in l] for i in l[-1::-1]: print(i,end=' ')
696e7dec1cc619b42d25a078f92be843d5482d5d
onlymezhong/Surrogate-Model
/surrogate/sorting/utils/splitA.py
888
3.578125
4
from operator import itemgetter from .median import median def splitA(fitnesses, obj): """Partition the set of fitnesses in two according to the median of the objective index *obj*. The values equal to the median are put in the set containing the least elements. """ median_ = median(fitnesses, it...
f314eefd36a71c9964a186d5d7a56407490e6c50
Demirose41/basic_python_scrape
/webscrape_introduction.py
1,274
3.90625
4
from bs4 import BeautifulSoup ## What is beautiful soup? # A library that lets us navigate through HTML with Python # It does NOT download HTML - for this, we need to requests module! html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>First HTML Page</title> </head> <body> <div id="...
23edb5b2bf6f97dfecaa9516078d24a0d82c013c
chlos/UCSD-Data-Structures-and-Algorithms
/course_01_algorithmic_toolbox/w05/3_edit_distance/edit_distance.py
1,260
3.859375
4
#!/usr/bin/env python3 def test(): s1 = 'ab' s2 = 'ab' result = edit_distance(s1, s2) expected = 0 print(f'{s1} {s2} dist: {result} (expected: {expected}') assert result == expected s1 = 'short' s2 = 'ports' result = edit_distance(s1, s2) expected = 3 print(f'{s1} {s2} dis...
4a395a59bcea47678215df308a235e8d10622a80
wtrnash/LeetCode
/python/167两数之和 II - 输入有序数组/167两数之和 II - 输入有序数组.py
923
3.734375
4
""" 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明: 返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 """ # 解答:双指针法 class Solution: def twoSum(s...
541dca3f5c0723dd7dd44799a13da87900d57ab1
Benedict0819/ECNU-computer-test
/1.经典入门/1.排序/2896. 随机排序.py
2,500
3.71875
4
""" @Time:2018/2/8 17:56 @Author:qingliu @Source:ECNU Online Judge @Problem:2896 @Website:http://acm.ecnu.edu.cn/problem/2896/ """ """ 给定一组以一个空格分隔的只含大小写字母的字符串。与普通字典序不同,按照给定的字母顺序对这组字符串排序。设两个字符串的字母不会完全相同。如:Hat、hat、HAt 等不会同时出现。 例如:字母顺序为 QWERTYUIOPASDFGHJKLZXCVBNM 时,一组字符串 hat cat bat book bookworm Dallas Austin Houston fi...
27c0ac21b376e60dc49bb74c85f61a5122e7bf12
OlderTree/study01
/python/prog05.py
197
3.671875
4
IList=[] I=raw_input("please input a number:") #IList.append(I) while (I<>""): IList.append(int(I)) I=raw_input("please input a number again(enter exit):") print IList IList.sort() print IList
1f594719db6efe2885ee336daf6057f4a8910bb0
HeyOkGo/courses
/stepik/python/beginner/part1/lesson11.py
123
3.75
4
n = int(input()) if ((n % 4 == 0) and (n % 100 != 0)) or (n%400 == 0): print("leap year") else: print("usual year")
fbafb11df26f139838c6dc83b0b42e62fda269fa
Thinginitself/EulerProject
/euler045.py
314
3.53125
4
#Euler Project 45 #Thinginitself SIZE = 200000 triangle = [n*(n+1)/2 for n in xrange(SIZE)] pentagon = [n*(3*n-1)/2 for n in xrange(SIZE)] hexagon = [n*(2*n-1) for n in xrange(SIZE)] triangleSet = set(triangle) pentagonSet = set(pentagon) for x in hexagon: if x in triangleSet and x in pentagonSet: print x
4baf7311fc97864153063d28c644a44aa0ef0bb9
rattanar/pythonbasic
/p003_if.py
1,318
3.984375
4
#########if############## if (<Condition>): <Block 1> else: <Block 2> ################# if (<Condition 1>): <Block 1> elif (<Condition 2>): <Block 2> else: <Block 3> ################# if (<Condition 1>): <Block 1> elif (<Condition 2>): <Block 2> elif (<Condition 3>): <Block 3> else: <Block 4> next_word = ...
7b54575dda5e8f1c71d84ce8ac8b4219d01346b3
hackerpriya/Python_Tutorial
/Function and Modules/coding_challenge4.py
482
4.4375
4
""" Create a BMI calculator, BMI which stands for Body Mass Index can be calculated using the formula: BMI = (weight in Kg)/(Height in Meters)^2. Write python code which can accept the weight and height of a person and calculate his BMI. note: Make sure to use a function which accepts the height and weight values and ...
11dc2e4c5c6f2d7713d69efad98f737853d07797
MobyAtTheo/Wi2018-Classroom
/students/shawn/class_03/list_lab.py
2,633
4.0625
4
## Class 03: Series 1 & 2 def list_series1(fruits=["Apples", "Pears", "Oranges", "Peaches"]): print(fruits) more_fruit=input("Add some fruit > ") if more_fruit: fruits.append(more_fruit) print(fruits) # prompt for a valid position in the fruit list position=0 raw="" whi...
f5e1f5f486d404e210ec199c77ff8d9a55f8557d
fahim0120/leetcode
/2 Add Two Numbers.py
1,356
3.71875
4
""" fahim0120@gmail.com """ # https://leetcode.com/problems/add-two-numbers/ # Medium # Amazon # Most Liked # Top Interviews # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def...
449fe0ab439d085d1d4691e2d294238c0d40a67c
Arwen0905/Python_Test
/TQC_考題練習/b0620_TQC證照_807_ex.py
922
4.0625
4
# 1. 題目說明: # 請開啟PYD807.py檔案,依下列題意進行作答,計算數字加總並計算平均, # 使輸出值符合題意要求。作答完成請另存新檔為PYA807.py再進行評分。 # 2. 設計說明: # 請撰寫一程式,要求使用者輸入一字串,該字串為五個數字,以空白隔開。 # 請將此五個數字加總(Total)並計算平均(Average)。 # 3. 輸入輸出: # 輸入說明 # 一個字串(五個數字,以空白隔開) # 輸出說明 # 總合 # 平均 (輸出浮點數到小數點後第一位) # 輸入輸出範例 # 範例輸入 # -2 34 18 29 -56 # 範例輸出 # Total = 23 # Average = 4.6 s = ...
6317520604527030d2cf7ca65d7c377e843bdf47
diboy2/Coding-Practice
/Python/recursion.py
243
3.5
4
def listsum1(numList): theSum = 0 for i in numList: theSum = theSum + i return theSum def listsum2(numList): if(len(numList)>1): total = numList[0] + listsum2(numList[1:]) else: total = numList[0] return total
2bf7f9d5722964c4027582c4ae1fffebe630bf71
stephenlind/538Riddler
/160318 Trenchcoat.py
1,294
3.65625
4
# Solution to FiveThirtyEight's Riddler problem: # http://fivethirtyeight.com/features/can-you-best-the-mysterious-man-in-the-trench-coat/ lowest = 1 highest = 1000 highest_winnings = 0 winningest_guess = 0 # try each starting number for starting in range(lowest, highest + 1): total_winnings = 0 # for each start...
928e2f4c165c88e2638768336d3ca3b641a899de
zimkjh/algorithm
/leetcode/12.py
1,077
3.53125
4
answerSheet = ["a", "aa", "aaa", "ab", "b", "ba", "baa", "baaa", "ac"] # 1, 2, 3, 4, 5, 6, 7, 8, 9 def getResult(num, digit): # 3000 -> 3, 3 if digit == 0: return answerSheet[num].replace("a", "I").replace("b", "V").replace("c", "X") elif digit == 1: return answerSheet[num].replace("a", "...
130bdaf3793aee3c0c12d35c0dd6bfdc53c5c08e
shincap8/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/12-roman_to_int.py
582
3.8125
4
#!/usr/bin/python3 def roman_to_int(roman_string): value = 0 result = 0 roval = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} if type(roman_string) is not str or roman_string == "": return 0 else: for i in roman_string: if result == 0: ...
9349d150ce694bc2bdb4ada57e29975e4e416ab3
elbuo8/codeEval
/DoubleSquares.py
406
3.578125
4
import sys, math file = open(sys.argv[1]) file.readline() #pichea la primera for line in file: x = int(line.strip()) possibleValues = range(int(math.floor(math.sqrt(x))), -1, -1) counter = 0 for i in possibleValues: y = math.sqrt(x - i*i) z = int(y) if (z == y and z in possibleValues): #pri...
435ab0688ee754d7a534e5561362cfe928ca6dc7
samkjay/AFS505_U1
/assignment4/ex33studydrills.py
889
4.21875
4
#Q1: converting while loop to a function all_numbers = [] i= 0 def number_formula(i, number): if i < number: print(f"At the top i is {i}") all_numbers.append(i) print("Numbers now: ", all_numbers) i=i+1 print(f"At the bottom i is {i}") return number_formu...
56d1883e7a930672adea628a224a45731ddbf71d
ZahraFazel/Compiler-Project
/symbol_table.py
1,960
3.5
4
class SymbolTableEntry: def __init__(self, name, address, scope, length, starts_at, type): self.name = name self.address = address self.scope = scope self.length = length self.starts_at = starts_at self.type = type def __str__(self): output = '{}\t{}\t{}\...
2c3ad2b2038a799f4cd98c61843774460fabe90d
tkss007/cs519
/HW2/msort.py
622
4.0625
4
#!/usr/bin/env python def mergesort(lst): if (len(lst) <= 1): return lst left = mergesort(lst[:len(lst) / 2]) right = mergesort(lst[len(lst) / 2:len(lst)]) result = [] while len(left) > 0 and len(right) > 0: if (left[0] > right[0]): result.append(right.pop(0)) ...
f1a94855375b11dbba1455afdb5d27cac0332831
MiguelANunes/Exercicios_Uri
/Python/1140.py
245
3.9375
4
Tautograma = input() while Tautograma != '*': Palavras = Tautograma.split(" ") Inicio = [] for Palavra in Palavras: Inicio.append(Palavra[0].lower()) if Inicio[1:] == Inicio[:-1]: print("Y") else: print("N") Tautograma = input()
e6b97221470a6edde7d66f515009c3d69f4cc026
Bwh50h3n/Year9designpythonLJ
/Exercise 1 console work/CCC Problem J1.py
457
4.0625
4
limit = input("what is the speed limit?") speed = input("what is the speed of the car?") difference = float(speed) - float(limit) if difference <= 0: print("Congratulations, you are within the speed limit!") if difference >0 and difference <21: print("You are speeding and your fine is $100") if difference > 20 an...
e505a1e0099b10596124acb45088072125b0e710
bporcel/DataStructures
/dataStructures/hashTables/classHashtable.py
1,717
3.65625
4
class Hashtable: def __init__(self): self.data = [] def __str__(self): string = '' for d in self.data: string += str(d)+', ' return '{}'.format(string) def add(self, key, value): address = self._hash(key) tmp = [] tmp.append(key) ...
96453771a32b1b39aaf808518c603f97c0b1b119
derivadiv/advent2020
/day02/day02.py
1,384
3.53125
4
readfilename = 'input2.txt' def valid(minchar, maxchar, repchar, password): n = password.count(repchar) if n >= minchar and n <= maxchar: return 1 return 0 def part1(filename): rows = [] validcount = 0 with open(filename, 'r') as f: for line in f: parts = line.strip...
27e2a3c76ab5c0a511bf07780ecb31cce74e2d56
SigitaD/pyhon_dna
/dna.py
2,056
3.65625
4
import csv from sys import argv, exit import re # Eina per is csv failo padarytus listus ir kiekviename is ju tikrina, kad kiekvenas segmento pasikartojimu skaicius atitinka txt faile rasta segmentu pasikartojimu skaiciu. def main(): validate_files(argv) str_list = read_csv() repeats_list = find_max_str...
e715ac568ec3a1d592794ad255982c75cc1b078c
DeanHe/Practice
/LeetCodePython/NumberOfWaysToEarnPoints.py
3,133
3.953125
4
""" There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points. Return the number of ways you can earn exactly target point...
814b5c93dcaa4323dbe2a15ef5033de37f5f743b
nithintech/thinkpython
/17classes&methods/kangaroo.py
560
3.5
4
class kangaroo(object): def __init__(self): self.pouchcontents=[] def putinpouch(self,x): if isinstance(x,kangaroo): for i in x.pouchcontents: self.pouchcontents.append(i) else: self.pouchcontents.append(x) def __str__...
d084d6845299e095e310459f1f91101b13066750
Windsooon/LeetCode
/Flatten Binary Tree to Linked List.py
1,083
3.890625
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 flatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place...
140e6a317e4ac703be902a28e422ebccd55915ee
theGreenJedi/Path
/Python Books/Introduction-to-Programming-Python/pybook/FutureTuition.py
256
3.796875
4
year = 0 # Year 0 tuition = 10000 # Year 1 while tuition < 20000: year += 1 tuition = tuition * 1.07 print("Tuition will be doubled in", year, "years") print("Tuition will be $" + format(tuition, ".2f"), "in", year, "years")
524ae4631c665c58c358848206fc0576b79cd750
tanmaysankhe/hangman-py
/allFunctions.py
657
4.09375
4
import random def getWord(): words = [ 'apple', 'mango', 'banana', 'tiger', 'lion' ] return random.choice(words).upper() def check(word, guesses, guess ): status = '' matches = 0 for letter in word: if letter in guesses: status += ...
b3411650a7e0d9738d68ff8395baf7187d3d7a7c
agiuse/sudoku-svn
/sudoku_1/trunk/src/sudoku_coordinate.py
11,674
3.796875
4
# -*- coding: utf-8 -*- ''' Created on 27 juil. 2011 @author: eagius ''' # ----------------------------------------------------------------------------------- class Coordinate(object): """ Classe gérant les coordonnées dans la grille. Cette classe lie entre elles les differents objets de ...
47d65496b3e4cd30aac956908a894cce3e0a35e1
ankile/ITGK-TDT4110
/timeoppgaver/lister_1.py
140
4
4
liste = [1, 3, 5, 7, 9] * 5 for num in liste: print(num ** 2) print("") for i in range(0, len(liste)-1, 3): print(liste[i] ** 2)
18356049012f5d6fada1008ad51de205ed66231e
naye0ng/Algorithm
/SWExpertAcademy/SW역량테스트/2105.py
2,945
3.578125
4
""" 디저트 카페 https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5VwAr6APYDFAWu """ def isNotWall(N,x,y) : if x >= 0 and x < N : if y >= 0 and y < N : return True return False dx = [-1,1,1,-1] dy = [1,1,-1,-1] def visitCafe(N) : for x in range(1,N-1) : ...
63cc1af0f9b8fc26c4c93df10e637e69c6356d46
golfnut1400/Python101
/List_using randon choice.py
364
3.6875
4
# use of random, not in import random all_data = random.sample(range(1000),15) #creates 15 random numbers up to 1000 #all_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15] #hard coded list choices = [] while len(choices) < 4: selection = random.choice(all_data) if selection not in choices: ...
4ed39a9c39f83f2ac1634ad6174007f6ec09081c
Aasthaengg/IBMdataset
/Python_codes/p03523/s856070832.py
211
3.625
4
S=input() b=S.replace("A","")=="KIHBR" if b: L=list(map(len, "".join("*" if s!="A" else s for s in S).split("*"))) X=[1,0,0,1,1,1,1] b&=all(L[i]<=X[i] for i in range(len(L))) print("YNEOS"[not b::2])
5e4876099e300baf45c6db0fd1a74cd876addf29
Murrow90/Python-Algorythm
/l3t6.py
1,637
4.0625
4
#В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. #Сами минимальный и максимальный элементы в сумму не включать. #Я че-то не очень поняла, по позиции или по значению должны они быть заключены между минимальным и максимальным поэтому сделала для обоих кейсов. #По ...
a0701ec01041256f2abfd05010b714eb7ca1ca27
Loxfran/PythonProgrammingPractice-PPP.-
/01-python/03-闭包.py
323
3.671875
4
def test(number): print("--1--") def test_in(number2): print("--2--") print(number+number2) print("--3--") return test_in print("-"*50) ret = test(100) print("-"*50) ret(100) print("-"*50) ret(200) print("-"*50) ret2 = test(1) print("-"*50) ret2(300) print("-"*50) ret(300) print("-"*50...
a46d94ab99ce6cb58e381eae5e1f4acb24d5b738
vicious-lu/python_learningTheBasics
/4 loops/while.py
319
4.15625
4
#basic while structure, infinite_______________________________ # cond = True # while cond: # print('executing while cycle') # else: # print('end of while cycle') # print('\n\n') #separator #print a value three times count = 0 while count < 3: print(count) count += 1 else: print('end while cycle')
96b98587a0a2904a21c2be6d0207b1df4542d46b
Tarun-Rao00/Python-CodeWithHarry
/Chapter 2/07_pr_03_average.py
138
3.8125
4
a = input("Enter Value Of X : ") a = int(a) b = input("Enter Value Of Y : ") b = int(b) c = (a+b)/2 print("The Average Of X and Y is ", c)
cca782123b39983d5e0cc6b4bee4708e05d9dfc6
wang264/JiuZhangLintcode
/Algorithm/L3/optional/65_median-of-two-sorted-arrays.py
2,761
3.890625
4
# 65. Median of two Sorted Arrays # 中文English # There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. # # Example # Example 1 # # Input: # A = [1,2,3,4,5,6] # B = [2,3,4,5] # Output: 3.5 # Example 2 # # Input: # A = [1,2,3] # B = [4,5] # Output: 3 # Challenge # The ...
1ec82eb8446e00714ae55e226e0209528febff88
NgyAnthony/supinfo-mastermind
/model.py
3,415
4.03125
4
import random ROWS = 6 COLS = 6 COLOR_ARR = ["Green", "Blue", "Orange", "Red", "Yellow", "Purple"] class Model: def __init__(self): # Define the number of cols and rows you want (i.e 6 cols = 2 dedicated for the numbers and the hints) self.rows = ROWS self.cols = COLS self.PLAYABL...
d9d08476c2eda6da0f1f36cb9b23ef7348b3bfc4
saddamarbaa/python-for-everybody-specialization
/Python Tuples Assignment 10.2.py
1,722
4.21875
4
""" Assignment 10.2 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan ...
0ce922eec80ac31d73d2e7d1b410d6802c915bc0
pepitogrilho/learning_python
/cConsolidation/c_DataTypes/l_lists_dicts_tuples_sets/l_lists/070_functions_003_filter.py
469
4.21875
4
# -*- coding: utf-8 -*- """ """ #Program to filter out only the even items from a list def filter_list(nums): filtered_list=[] for i in nums: if i%2 == 0: filtered_list.append(i) return filtered_list nums = [1,5,4,6,8,11,3,12] nums_filtered=filter_list(nums) print(nums_filtered) #.....
71b152187496aa7f1cb6b2214538c4d976944886
eireland22/udacity
/rps1.1.py
3,551
4.28125
4
#!/usr/bin/env python3 """This program plays a game of Rock, Paper, Scissors between two Players, and reports both Player's scores each round.""" import random # Three different moves the player can make moves = ['rock', 'paper', 'scissor'] # Function for who wins and loses def beats(one, two): ...
ef2014533bc849ca946a932343cc887f97c74c1f
maiconm/python-class
/exercicio 7.py
531
3.640625
4
vezes_chamada = 0 def conta_consoantes(string): global vezes_chamada total_consoantes = 0 for letra in string.lower(): if letra != 'a' and letra != 'e' and letra != 'i' and letra != 'o' and letra != 'u': total_consoantes += 1 vezes_chamada += 1 return total_consoantes...
71a8ed8401e7a79321287cbc7392e042e0c09dc4
gokuorzzl/rsp
/game.py
2,551
3.59375
4
import random import sys class Game: hands = ('가위', '바위', '보') def __init__(self, player): self.player = player self.batting_coin = 0 self.bonus = 0 def game_start(self): batting_coin = input('배팅할 코인량을 입력해주세요:') try: self.batting_coin = int(batting_coin...
91c2bf67f2d63d823ccac7d1e61eb0cf516fe136
d1rtyst4r/archivetempLearningPythonGPDVWA
/Chapter08/Tasks/make_album.py
800
4.03125
4
# Task 8-7 def make_album(artist, album_title, number_of_tracks=''): album = {'artist': artist, 'album title': album_title} if number_of_tracks: album['number of track'] = number_of_tracks return album miasma = make_album('the black dahlia murder', 'miasma', 15) steal_this_album = make_album('syst...
388de3f5b8b1c93cb948cb73e21042c825ced388
ryancabrera/COMP157
/practice/cabrera_class_exercise3_1.py
4,565
3.65625
4
import random import time # import copy __author__ = 'Ryan Cabrera' class SortingExamples(object): def __init__(self): self.random_sample_size_10 = random.sample(range(1, 10000), 10) self.random_sample_size_100 = random.sample(range(1, 10000), 100) self.random_sample_size_1000 = random.sa...
299e670d10bf280e856114424b0fc2ea6265194e
Anshika03/.py
/factorial.py
584
4.0625
4
#------------------------------------------------------------------------------- # Name: module3 # Purpose: # # Author: Anshika # # Created: 23-12-2018 # Copyright: (c) Anshika 2018 # Licence: <your licence> #--------------------------------------------------------------------------- a=(...
9400d2d69e54ee0bb809eced1ff439ed82b3bfad
JCarlosSL/FisicaComputacional
/Practica3/Ejericio10.py
1,181
3.5
4
import matplotlib.pyplot as plt import numpy as np def velocidad(vx,vy): return np.sqrt(pow(vx,2)+pow(vy,2)) def K(C,A,p,m): return (1/2) * ((C*A*p)/m) def Euler(px,pv,pa,v,h=0.01): pa = np.array([-k*v*pv[0],-10-k*v*pv[1]]) px = px + pv*h pv = pv + pa*h v=velocidad(pv[0],pv[1]) return (px...
f18b438ee2cbc25284b4e30acbeb3274f7046d06
watinya/zerojudge
/python/d010.py
342
3.703125
4
# coding:UTF-8 import sys s = sys.stdin.readline() while(s != ""): t = 0 for i in range(1,int(s)): if(int(s) % i == 0): t += i if (t > int(s)): print("盈數") elif (t == int(s)): print("完全數") elif (t < int(s)): print("虧數") s = sys.stdin.re...
5c4478ee6cc5c74399bfd456064f9fdab73a5419
andyyaldoo/AoC
/2020/day-4/part2.py
2,229
3.5625
4
input = [] # with open('inputinvalid.txt') as my_file: # with open('inputvalid.txt') as my_file: # with open('inputeasy.txt') as my_file: with open('input.txt') as my_file: for line in my_file: input.append(line.strip()) input2 = [] i = 0 fullPassport = "" while i < len(input): fullPassport ...
53f4675c75612e8900860cfd91a88e165d8f2696
iuliia-eagle/hometask
/Tasks/a0_my_stack.py
755
4.15625
4
""" My little Stack """ from typing import Any stack = [] def push(elem: Any) -> None: """ Operation that add element to stack :param elem: element to be pushed :return: Nothing """ global stack stack.append(elem) return None def pop() -> Any: """ Pop element from the top of the stack :return: popped e...
e7b96c6cb060843756f45dc336fa8e7dd8f3439c
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/89b6c1f0f67f467a8020d05548b4748d.py
187
4.03125
4
#!/usr/bin/env python3 from collections import Counter def word_count(text): """Counts the occurences of each word, returning a dict.""" return dict(Counter(text.split()))
b31241ba675d6d229362d3c74afee620b98c1eef
tcdavid/advent-of-code-2019
/python/day1/Day1Part2.py
396
3.546875
4
from math import floor def main(): f = open("input.txt", 'r') lines = f.readlines() result = sum(map(calc, lines)) print(result) def calculate(val): return floor(int(val) / 3) - 2 def calc(val): acc = 0 start = val while calculate(start) > 0: additional = calculate(start) ...
18fa9171e24b9ada616366e24ec7862b2a091e81
siddharthbaghel/matplotlib
/scatter diagramm.py
352
3.96875
4
import matplotlib.pyplot as pl x=[1,2,3,4,5,6,7,8] y=[5,4,2,7,9,4,6,8] pl.scatter(x,y,label='my scatter',color='m',s=500,marker="*") ## in a marker we can also use +,x,. in place of marker. by defalut it is (.). ## symbol s stands for size pl.title("interesting graph\ncheck it out") pl.xlabel("X-axis") ...
1a9adc1c778865956cd85141d390efcf49c5655e
feisal-Codes/pythonOOP
/BasicsOfOOP/contactmanager.py
3,467
3.890625
4
import datetime import pickle import json class Contact: __contactList=[] def __init__(self,name,phoneNumber,location, email): self.name=name self.phoneNumber=phoneNumber self.location= location self.email=email self.date= datetime.date.today() Contact.__contact...
06f2c17a75a9342ecd64642045e88ed54cc38881
savadev/LeetCodeProblemSet
/dividetwointegers.py
932
4.125
4
#!/usr/bin/env python3 class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == -2 ** 31 and divisor == -1: return 2 ** 31 - 1 negative = False if (dividend >...
76b58ce93b14e793f53060843d75b586d92c723d
bai345767318/python-java
/python/python/day03/demo03.py
600
3.921875
4
''' 列表生成式 List Comprehensions ''' l = [1,2,3,4,5] # 利用range(start,end,step)函数生成列表 m = list(range(10)) print(l) print(m) n = list(range(0,10,2)) print(n) # [0, 2, 4, 6, 8] # [0, 4, 16, 36, 64] o = [] n = list(range(0,10,2)) for x in n: o.append(x*x) print(o) # 列表生成式 p = [x*x for x in n] print(p) # 可以添加条件 q = [x*x...
8f7ca17e12dca00b388c1307359a53e26afa8746
kickbean/LeetCode
/code/robotPath_9_2.py
1,046
4
4
''' robot path using 'Down' and 'Right' to reach (X,Y) from (0,0). There could be 'off-limit' points Created on Dec 2, 2013 @author: Songfan ''' def path(destination, limits,h): x = destination[0] y = destination[1] assert(x>=0 or y>=0),"input error: desination must be non-negative" if (x,y) in limit...
d3ccf91661fedc4ad7e76fb0e645d5a8f5371695
solito83/aprendendo-programar-em-python
/e-estruturas condicionais/des-031 condicional-005.py
522
3.890625
4
des = 'Desafio-031 estruturas condicionais' print ('{}'.format(des)) # Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas. kmh = int(input('Quantos kilometros tem seu percurso? ')) fim = 'T...
04809e0808dce52660d671750e108200123f5409
brucechenssfireinthehole/individual
/study_code/study_python/lesson1-hello.py
434
4.21875
4
print("hello python world") message = "hello python world" print(message) #>1string add first="my name is" last="Dosu" total=first+" "+last print(total) #>2\t \n print("\tpython") print("languages:\npython\nc++\njavascript") #>3delate null in string #right null .rstrip() lest null: .lstrip() both side: strip() str1="p...
1124c0c044053478f1d0ef6822ef68d2cc47f0ac
Peteliuk/Python_Labs
/lab4_2.py
257
3.90625
4
import sys import math print('Enter 3 real numbers') numA = float(input('')) numB = float(input('')) numC = float(input('')) res = (1/numC*math.sqrt(2*math.pi))*math.exp((-1*math.pow((numA-numB),2))/(2*math.pow(numC,2)) print('Result:',res)
e90901580ae7878802ee64892fe8ce6f6278f12e
Aasthaengg/IBMdataset
/Python_codes/p02260/s898164103.py
569
3.53125
4
def selection_sort(a, n): counter = 0 for i in range(n): minj = i for j in range(i, n): if a[j] < a[minj]: minj = j if i != minj: counter += 1 tmp = a[i] a[i] = a[minj] a[minj] = tmp return counter def prin...
6321e222f339dcb32fe85c2d96b50a092ef52d43
j000/Python
/zestaw07/poly.py
16,265
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ zadanie 7.2 Wielomiany Jarosław Rymut """ class Poly: """Klasa reprezentująca wielomiany.""" # wg Sedgewicka - tworzymy wielomian c*x^n def __init__(self, c=0, n=0): """ Construct polynomial >>> Poly() Poly([]) >>> ...
36295ab33f0db680461a20c809e27651725f171b
Arverkos/GeekBrains-Homeprojects
/py_intro02/Les.02.Task02.py
456
3.8125
4
n = int(input('Введите количество элементов в списке: ')) my_list = [] i = 0 for i in range(n): my_list.append(input('Введите элемент списка: ')) print('Введеный список', my_list) for i in range(0, n, 2): if i == n - 1: break swap = my_list[i] my_list[i] = my_list[i + 1] my_list[i + 1] =...
7a345f66e92762da1fe312d474011698a61f83f6
chintanpokhrel/exercises
/src/hash_tables/closest_pair.py
461
3.75
4
def closest_pair(arr): lookup = {} distance = None index = 0 for item in arr: if item in lookup: if distance: if (distance > index - lookup[item]): distance = index - lookup[item] else: distance = index - lookup[item] lookup[item] = index else: lookup[item] = index index += 1 return...
0536f66922d228c51287a5e2f3cc679da5c836de
Retha05M/Methods_Final
/palindrome.py
310
3.921875
4
class Palindrome: def __init__(self, word): self.word = word def reversed_word(self): my_original_word = self.word.lower() my_reversed_word = my_original_word[::-1] if my_reversed_word == my_original_word: return True else: return False
f5ceb4780b0be313b197c650a16a8d841a41fe33
Shimpa11/PythonTutorial
/stringformatting.py
1,170
3.953125
4
name="Fionaa" age=20 print("the name is {}. Her age is {}.".format(name,age)) print("Welcome to the app %s" %(name)) print("Welcome to the app", name) products = [3454, 2411, 1341, 4568, 8976] for i in range(0,len(products)): oldPrice=products[i] products[i]=products[i]-0.4*products[i] newPrice=products[i]...