blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
cf6cb78d29c07d0194f389d2bfd9c4f8b95ae80a
lohithsubramanya/Python
/08_exception_handling_&_reg_exp.py
1,572
4.28125
4
### Exceptions - Predefined ### Almost 15 exceptions declared by python itself. # try: ##### Nested try , except is also valid # print b # except NameError: # # b=0 # # print b, 'this error occured due to name error' # # except IOError: # # print 'error' # else: ...
e8b5e97137891039236a9938cb5e3f6d9dd9741b
Vinaypatil-Ev/DataStructure-and-Algorithms
/6.Tree/Binary Search Tree/Python/binary_tree_using_array.py
1,011
3.875
4
class BinaryTree: def __init__(self, size): self.bt = [None] * size self.i = 0 def parent(self, i): return i def left(self, i): return i * 2 + 1 def right(self, i): return i * 2 + 2 def isFull(self): return self.i == len(self.bt) - 1 def insert(sel...
ce120d0a2f8934b4f2c3c2dc6df89dff9b33526b
ravisjoshi/python_snippets
/DataStructure/sorting/mergeSort.py
1,026
4.125
4
""" Merge sort: https://en.wikipedia.org/wiki/Merge_sort """ from random import randint def merge(arr, left, right): i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += ...
476500db19d5e7e87502e1e5e2bd8ac136aacded
Divya552/tattvalabs
/Assignment10.py
879
3.8125
4
import pandas as pd df1=pd.DataFrame({ 'Name':['divya','bhavya','shaila','kumar','pooja','keerthi', 'lakshmi','kiran','surya','kala'], 'USN':[1,2,3,4,5,6,7,8,9,10], 'Sem':[4,6,8,4,5,7,7,8,4,5], 'Branch':['ec','ec','ec','cs','ec','cs','is','cs','is','cs'], 'Score':[50,60,70,80,90,85,65,91,77,67], 'Region':[...
030605fc72cfba71428dd56a22ac2b8eb1869256
ARJOM/pyaudio-practices
/example.py
973
3.53125
4
import speech_recognition as sr # Funcao responsavel por ouvir e reconhecer a fala def listen_microphone(): # Habilita o microfone para ouvir o usuario microphone = sr.Recognizer() with sr.Microphone() as source: # Chama a funcao de reducao de ruido disponivel na speech_recognition microph...
69c65787a43f7ec655034224fb5ba1b4dc86c5a4
kakuilan/pypro
/test045.py
233
3.9375
4
#!/usr/bin/python3 # coding: UTF-8 # ASCII码与字符相互转换 c = input('请输入一个字符:') a = int(input('请输入一个ASCII码:')) print(c+" 的ASCII码为:", ord(c)) print(a, " 对应的字符为:", chr(a))
7798183638d3d992d8ccece3ef9f2815a746c318
DouglasAllen/Python-projects
/my_code/is_a_vowel_funtion.py
194
3.9375
4
# is_a_vowel_funtion.py def is_a_vowel(c): vowels = "AEIOUaeiou" return c in vowels if __name__ == "__main__": print(is_a_vowel("X")) print(is_a_vowel("O")) print(is_a_vowel("e"))
9dbaf04c36010fc57e41b4a672cfef63225312b8
Todd-Davies/third-year-notes
/COMP36111/programs/savitch.py
638
3.875
4
#!/usr/bin/python # For log import math graph = {0 : [1,3,4], 1 : [0,2], 2 : [1,3], 3 : [0,2], 4 : [0]} def is_reachable(start, end, graph, steps): print "is_reachable(%d, %d, graph, %d)" % (start, end, steps) if steps == 0: return start == end or (end in graph[start]) e...
774d5ef691a134b2af306af8d592f38ab9b73fd5
TPrime001/Grundgesetz
/preprocess.py
413
3.78125
4
import re from stemming.porter2 import stem tokenize_re = re.compile("\w{2,}") digits_only_re = re.compile("^\d+$") def tokenize(text): tokens = [token.lower() for token in tokenize_re.findall(text)] # tokens_without_numbers = ["number" if digits_only_re.match(token) else token for token in tokens] retur...
e3f9e6abb744917eab45059ee38b8a11dbc036c0
HankDa/Python_DataSturcture_Parctice
/LargestContinuousSum_Array.py
1,015
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 26 17:36:26 2020 @author: Hank.Da """ """ Largest Continuous Sum Problem Given an array of integers (positive and negative) find the largest continuous sum. Solution Fill out your solution below: """ def large_cont_sum(arr): sum_max = 0 ...
1c990e0e443c1a2f4a0a1ca84d6d4c134be23163
mariololo/EulerProblems
/problem32.py
1,047
3.8125
4
""" Maximum product is either 2digits * 3digits or 1digits*5digits """ import sys def is_pandigital(a,b,c): a_str = str(a) b_str = str(b) c_str = str(c) all_numbers = [num for num in a_str+b_str+c_str] if len(all_numbers) != 9: return False else: for i in range(1,10):...
08403bd1f380e2ada2079ef0ca5170288b8f4588
SeekingAura/mathematicsComputing
/classes/clase 07-06-2019/geometric graphs.py
3,682
3.65625
4
import sys import os import matplotlib.pyplot as plt import networkx as nx # https://networkx.github.io/documentation/stable/reference/drawing.html # https://networkx.github.io/documentation/stable/reference/functions.html # https://matplotlib.org/examples/color/named_colors.html # H = nx.DiGraph(G) # convert G to di...
e69cd726f7382e09340d2369f858a146537efbc4
NagarajuSaripally/PythonCourse
/Operators/usefulOperators.py
2,313
4.5625
5
# range(). --> it prints specified range but not the includes the specified number for num in range(10): print(num) # range(0,10,2) 0 is begining of the range, 10 is end of the range and 2 is the steps that needs to consider for num in range(0,10,2): print(f'with step 2 : {num}') print('\n') ''' Enumerate: built ...
febff7a8ea02be46441e6d11d5ec2198f4071786
kmgowda/kmg-leetcode-python
/evaluate-reverse-polish-notation/evaluate-reverse-polish-notation.py
792
3.65625
4
// https://leetcode.com/problems/evaluate-reverse-polish-notation class Solution: def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ st = list() for ch in tokens: if ch == '+': st.append(st.pop()+st.pop()) e...
cc8172d19b582d78360af08665dd56d9818f7903
komo-fr/AtCoder
/abc/088/d/main.py
180
3.5625
4
#!/usr/bin/env python3 H, W = list(map(int, input().split())) s_table = [] for _ in range(H): s_list = list(map(int, input().split())) s_table.append(s_list) print(ans)
40cb03a36d751254dd6b05c7ac58caae99a2527b
LuckyLub/python-fundamentals
/src/03_more_datatypes/2_lists/04_11_split.py
491
4.53125
5
''' Write a script that takes in a string from the user. Using the split() method, create a list of all the words in the string and print the word with the most occurrences. ''' userString=input("Please, type a sentence without using syntax.") userStringSplitted = userString.split() count=0 for word in userStringSp...
5f2916d0c02b08eb78e42478bb2bdafb0ad41cbc
tuipopenoe/practice_questions
/cracke_the_skye/Chapter1/1_2.py
697
4.28125
4
#!/usr/bin/env python # Tui Popenoe # 1.2 from sys import argv def reverse(string): return string[::-1] def reverse_c_style(string): length = len(string) string = list(string) for i in range(length - 1): temp = string[i] string[i] = string[i+1] string[i+1] = temp return '...
c131622813f0b6a1f28592c592158e58704306d1
albertkowalski/100-days-of-code
/day_10/day_10.py
1,158
4.09375
4
import art print(art.logo) def add(n1, n2): return n1 + n2 def substract(n1, n2): return n1 - n2 def multiply(n1, n2): return n1 * n2 def divide(n1, n2): return n1 / n2 operations = { "+": add, "-": substract, "*": multiply, "/": divide } run_calculation = True num1 = float(i...
7d14b6bbec9e2df1ccdad835aa7e2bd96d3b2b95
Computer-engineering-FICT/Computer-engineering-FICT
/I семестр/Програмування (Python)/Лабораторні/Братун 6305/Labs/LABA2/PRES_5/Exmp33.py
347
3.953125
4
print("Введіть слово 'stop' для одержання результату") s = 0 while True: x = input("Введіть число: ") if x == "stop": break # Вихід із циклу y = int(x) # Перетворимо рядок у число s += y print("Cyмa чисел дорівнює:", s)
b7707068c3dbd0f323d88310ce3daf1452c2fe10
ahddredlover/python_book
/codes/chapter-06/eg_6-08.py
498
3.765625
4
class Name: def __init__(self, family_name, given_name): self.family_name = family_name self.given_name = given_name def __get__(self, obj, type): return f'{self.given_name} {self.family_name}' def __set__(self, obj, value): self.family_name = value[0] self.given_na...
ecdc366da1aa8af824c1d203c0c25035fed8635c
mayhibb/tulingxueyuan_exercises
/066_注册用户/注册用户.py
1,665
3.859375
4
users_passwords = {"qqq":123456789,"www":123456} user_names = users_passwords.keys() def create_user_name(): # 全局化变量,下面要用到存储 global username username = str(input("请输入用户名: ")) # 判断用户名是否存在 if username in user_names or username == "": print("用户名已存在!请重试...") return create_user_name()...
fde6538f2a7660ed0cb201b6c2eea847bd78ed57
Bestlm/PythonTest
/PythonSE/PythonDay12-2.py
504
4.03125
4
""" 元组 让函数返回多个值 """ # 编写一个找出列表中最大值和最小的函数 def find_max_and_min(items): """找出列表中最大和最小的元素 :param items: 列表 :return: 最大和最小元素构成的二元组 """ max_one, min_one = items[0], items[0] for item in items: if item > max_one: max_one = item elif item < min_one: min_one = i...
44ffc00fb69a64f69e017fd22a89de389a702e2f
andreson94/Python
/exe050.py
251
3.75
4
print('10 termos de uma PA') t = int(input('Primeiro termo: ')) r = int(input('Razão: ')) d = t + (10 - 1) * r #formula para saber o prdecimo termo for c in range(t, d + r, r): #laço que vai ate o decimo termo print(c, end= '->') print('acabou')
0ba963cf50f915b2037e493e87388ff79dc72af0
Ajod/LRI
/lri/transpositionCipher.py
465
3.796875
4
def encrypt(message, key): index = 0 count = 0 cipher = [] for letter in message: cipher.append(message[index]) index += int(key) if index > len(message) - 1: count += 1 index = count return ''.join(cipher) def decrypt(cipher, key): message = [''] * len(cipher) index = 0 count = 0 for lette...
0d3ffab42cb172ad53449194a5f2200742377639
Aasthaengg/IBMdataset
/Python_codes/p00005/s232400621.py
314
3.578125
4
import sys def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def lcm(a, b): return a * b // gcd(a, b) def main(): for i in sys.stdin.readlines(): a, b = [int(x) for x in i.split()] print(gcd(a, b), lcm(a, b)) if __name__ == '__main__': main()
c4d60daab992e6693aa7ff0ae903390df2e88c33
UO-CIS211/Agenda
/appt_io.py
2,062
3.828125
4
""" Input and output conversions for Appt and Agenda objects. parse_appt is inverse of Appt.__str__ parse_agenda is inverse of Agenda.text """ import appt import datetime from typing import Iterable def parse_appt(appt_text: str) -> appt.Appt: """Parse something like "2018-05-03 15:40 16:15 | Study hard" ...
9a68bca2d6a1dc4a354ac81395420ee60ef0b4b8
diegobq/ejercicios_python
/Clase03/tablamult.py
857
3.53125
4
# tablamult.py # Ejercicio 3.17: Tablas de multiplicar def imprimir_header(num_columnas): header_str = f'{"":3s}' for index in range(num_columnas): index_str = str(index) header_str += f' {index_str:>5s}' print(header_str) print('-' * len(header_str)) def imprimir_tablas(num_filas, nu...
5aa10f2190fded924ae9259a4a3d8ebe2fcf2988
krrishrocks009/classes
/class.file
1,640
4.5
4
#!/usr/bin/env python # __init__ #self #methods vs functions class Human(): def __init__(self, name, gender): self.name = name self.gender = gender #lets see what a self used for #lets make a method def speak_name(self): print "My name is %s" % self.n...
0d0d88b869470cac3c7c202b011e063badba4509
gabriellaec/desoft-analise-exercicios
/backup/user_292/ch27_2020_03_25_12_19_10_506049.py
177
3.921875
4
while b!="não": b=(input("Voce tem duvida na disciplina sim ou nao?")) if b=="não": print("Até a próxima") else: print("Pratique mais")
91f18cb894f13f6136354ec5fa90bc98484f4c03
usman-tahir/rubyeuler
/py_euler1.py
133
3.515625
4
#!/usr/bin/env python accumulator = 0 for i in xrange(1,1000): if (i % 3 == 0 or i % 5 == 0): accumulator += i print accumulator
cd616d6df2f548198e52b68b7b09685c98c656a0
AndriiDiachenko/pyCheckIo
/0_Home/date-and-time-converter.py
1,826
4.65625
5
''' Computer date and time format consists only of numbers, for example: 21.05.2018 16:30 Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes Your task is simple - convert the input date and time from computer format into a "human" format. Input: Date and time as a string Output: The same ...
5d448152fee815a2e6b5075b4271c0099cb7d922
smrthkulkarni/sunil_misc
/Interview_practice/13_rat_move.py
1,147
3.9375
4
""" Backtracking - Rat maze Can only move forward & down """ class RatMaze(object): def __init__(self): self.maze = [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] self.path_followed = [[None, None, None, None], [None, None, None, None], ...
f9b61a5ab95c6763d7df83a6167d01078863fe17
stef55/python-exercises
/awesomeness.py
249
3.953125
4
"""create a list made by 5 name and add them to a list with wroten "is awesome""" names=['Brian','Zac','Cody','Oronzo','randomname'] awesome_names=[name +' '+'is awesome' for name in names] for awesome_name in awesome_names: print(awesome_name)
c9ccb881e979f9d68fd863e45a48836e016d25db
DanPsousa/Python
/Q15_Repetição.py
438
3.921875
4
n = int(input("Forneça um número inteiro: ")) print("Os divisores de %d são: " % n, end = "") if n == 0: print("todos os números reais diferentes de zero.") elif n > 0: for c in range(n,1,-1): if n % c == 0: print(c, end = ", ") print("1.") elif n < 0: for c in range(n,0,1): if n % c == 0: pri...
f0c969286d230e3e523a3125e824b92007eab784
susebing/HJ108
/二叉树/重建二叉树.py
959
3.546875
4
# coding=utf-8 # 题目描述 # 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 # 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 # 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}, # 则重建二叉树并返回。 # # 示例1 # 输入 # 复制 # [1,2,3,4,5,6,7],[3,2,4,1,6,5,7] # 返回值 # 复制 # {1,2,5,3,4,6,7} class TreeNode: def __init__(self, x): self.val = x self.left = No...
cd3f7e42076f7ab6b3e3dda658184d57b514a5e1
troels/TSPs-and-Tourists
/TSP/tsp-solver.py
2,425
3.59375
4
#!/usr/bin/python import sys,re from numpy import matrix def main(fh): filedata = (x for x in fh.read().split('\n')) filedata = (re.split('\s+', x) for x in filedata) filedata = [[int(x) for x in y if x] for y in filedata] reading_header = True for line in filedata: if not line: continue...
453c942eda820ad7715f141d743167c4cb6fa638
athena15/leetcode
/longest_substring.py
574
3.53125
4
from collections import defaultdict class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = defaultdict(int) start = 0 stop = 1 length = 0 longest = 0 while s[start] == s[stop]: stop += 1 length += 1 if length > longest: longest = length if s...
b383ef833f13063804ffd194ebdab00b1cc88082
Itseno/PythonCode
/12-18-18.py
648
3.6875
4
#Dictionaries population = { 'St. Louis': 308294, 'Ted': 105} print(population['Ted']) print(population['St. Louis']) menu = {} menu['Chicken Alfredo'] = 14.50 zoo_animals = {'Unicorn':'Candy House', 'Sloth':'Rainforest'} del zoo_animals['Unicorn'] zoo_animals['Sloth'] = 'Panther' for x in zoo_animals: pri...
c33584362be121bed9691e944e427b34202abe05
lorenzocappe/adventOfCode2020
/day23.py
2,714
3.8125
4
def read_input(input_line: str) -> list: result = [] for ch in input_line: result.append(int(ch)) return result def play_game(starting_cup_sequence: list, number_moves: int) -> list: current_cup_sequence = starting_cup_sequence.copy() for index in range(len(current_cup_sequence)): ...
6bf4d00303f789ef574840e2ceadf22b7d738912
huangqin1202/awesome-python3-webapp
/practice/listAndtuple.py
2,567
4.625
5
#list # 列表,有序集合,可添加删除(可变) # 列出班里所有同学的名字: classmates = ['Michael', 'Bob', 'Tracy'] print (classmates) #用len()函数可以获得list元素的个数 print ('list 中元素个数:',len(classmates)) #用索引来访问list中每一个位置的元素,索引从0开始 print ('list 中第一个元素:',classmates[0]) print ('list 中第二个元素:',classmates[1]) print ('list 中第三个元素:',classmates[2]) #当索引超出了范围时,Python会报...
eecb784fc4e3a8cb01995068e064468cbe4f2ad8
asperaa/back_to_grind
/bactracking/1079. Letter Tile Possibilities.py
852
3.5625
4
"""We are the captains of our ships, and we stay 'till the end. We see our stories through. """ """1079. Letter Tile Possibilities """ class Solution: def numTilePossibilities(self, s): n = len(s) s = sorted(s) self.total_length = n self.ans = 0 visited = [False for i in r...
5d18ac7f82458e9ed293037615458845d82b2cfe
ebrahimayyad11/data-structures-and-algorithms
/challenges/hashmap-tree-intersection/hashmap_tree_intersection/hashmap_tree_intersection.py
680
3.796875
4
import sys sys.path.append("/home/ebrahimayyad11/data-structures-and-algorithms/Data-Structures/hash-table") from hash_table.hash_table import Hashtable def tree_intersection(tr1,tr2): arr1 = tr1.pre_order() arr2 = tr2.pre_order() if arr1 == 'the tree is empty!' or arr2 == 'the tree is empty!': re...
bebb0bfed98f10287b6f5a430ceeb194faebfa15
SeriousBlackMage/Python_References
/Files/Files.py
737
3.859375
4
def main(): #Open() öffnet eine File oder erstellt sie falls sie noch nicht vorhanden ist f = open("textfile.txt","w+") #Das Erste Argument ist die zu behandelnde Datei und das zweite ist "was gemacht werden soll" for i in range(10): f.write("This is line %d \r \n" % (i+1)) f.close() f ...
04c1ab58f42e46d0a6d457155b354486db2e42e9
dooleys23/Data_Structures_and_Algorithms_in_Python_Goodrich
/C4/9.py
819
3.859375
4
# C-4.9 Write a short recursive Python function that finds the minimum and maximum # values in a sequence without using any loops. import code set = ['1','22','6549','1000','304','21'] class result(): def __init__(self,max,min): self._max = max self._min = min x= result(None,None) def find_max_m...
5614d25d85c0bed58f4ef46d40e1ce0d666a9ed7
alex-stybaev/leetcode
/lib/zigzag.py
690
3.53125
4
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ list = self.sequence(len(s), numRows) result = [''] * numRows for i in range(0, len(s)): result[list[i]] += s[i] return ''.jo...
26ce72014157938cc5c20c545aeaef78e5665131
wizardshowing/pyctise
/polymorphism_subtype.py
507
4.21875
4
# # Subtyping, or inheritance, is the most famous thing in OO. However, it is not suggested to use it widely since it is too heavy in designing. # class Shape(object): def draw(self): print('Cannot draw an abstract shape') class Rectangle(Shape): def draw(self): print('Drawing a Rectan...
1d5530302c35ebeb9b4dd47d02e1eb76443b9e43
MichelleZ/leetcode
/algorithms/python/validParentheses/validParentheses.py
558
3.8125
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/valid-parentheses/ # Author: Miao Zhang # Date: 2021-01-06 class Solution: def isValid(self, s: str) -> bool: dicts = {')': '(', '}': '{', ']': '['} stack = [] for c in s: if c in dicts.va...
40bb17f05db9501325ab172d48d4d6b00e1313d5
FelipeDreissig/PenseEmPy
/Cap 10/Ex10.9.py
1,038
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon May 18 01:59:23 2020 @author: dreis """ import datetime import time def met_append(): caminho = open(r'C:\Users\dreis\Desktop\Estudos\Projetos\words.txt', 'r') t = list() for palavra in caminho: t.append(palavra.strip()) return t def met_mais(): ...
878cb02e674ba0bff0a63f8f23b38823d62e53bb
georgebohnisch/ultralights
/animations/rainbow.py
1,304
3.671875
4
# # Python Module example import animation import time import neopixel class Animation(animation.Animation): def __init__(self, args={}): args['delay'] = args.get('delay') or 0.0005 self.cycle_index = 0 self.cycle_range = 255 super().__init__(args) def drawFrame(self)...
c11a0b6c5e47af2a28aa94e1f154c0e25d373100
derickdeiro/curso_em_video
/aula_15-estrutura-repeticao-break/desafio_067-tabuada-v3.py
491
4.03125
4
""" Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. """ while True: num = int(input('Quer ver a tabuada de qual valor? (Negativo para encerrar) ')) print('~'*20) if...
8ed7fb2834f7fb6dbc1e0d7e344d3ccdf763e2e4
siddhant1999/Computer-Science-EngSci
/simplenet.py
2,748
3.734375
4
import numpy as np import math class NeuralNet(): inp = [] outp = [] learning_rate=0.1 def __init__(self, inp, outp): self.inp = inp self.outp = outp self.w= np.random.uniform(low=-1, high=1, size=(3,3,3)) self.n= [[0 for j in range(3)] for i in range(4)] self.w[0][0][0] = 0 self.w[0][1][0] = 0 #s...
7546bea2113ffb1e96969cb01bf378e666e11cdd
CameronRushton/photo-editor
/grayscale_filters.py
2,296
4.09375
4
""" SYSC 1005 A Fall 2015 Image processing examples - two filters that create a grayscale image from a colour image. To run all the filters, load this module into Python, then call test_all from the shell: >>> test_all() """ from Cimpl import * def grayscale(img): """ (Cimpl.Image) -> None ...
63a916444cdbcf0a4fd078d3cee8d0452b6f43e6
minjun0622/CSCI127
/pset46.py
1,427
4.46875
4
#CSci 127 Teaching Staff #October 2017 #A program that uses functions to print out months. #Modified by: Minjun Seo #Email: minjun.seo58@myhunter.cuny.edu def monthString(monthNum): monthString = "" if (monthNum == 1): monthString = "January" elif (monthNum == 2): monthString = "Febru...
f76c14671f78b2658732407420b92ddc1d9a74a6
cgsarfati/CodingChallenges-Reverse-LL-In-Place
/reversellinplace.py
3,005
4.1875
4
"""Given linked list, reverse the nodes in this linked list in place. Iterative solution doctest: >>> ll1 = LinkedList(Node(1, Node(2, Node(3)))) >>> ll1.as_string() '123' >>> reverse_linked_list_in_place(ll1) >>> ll1.as_string() '321' Recursive solution doctest: >>> ll2 = LinkedList(Nod...
521dd59f93977c0d703346faa1ceb9f4697794e5
thejen72/CP3-Jenwiji-Ratanasiriwit
/Exercise11_Jenwiji_R.py
151
4
4
stars = 1 height = int(input("Please input pyramid height!")) for x in range(height): print((height-x)*" "+("*"*stars)) stars += 2
04d6a5b02894a552267398045f9b511567c8a07f
ppinko/python_exercises
/math/expert_truncatable_primes.py
1,473
4.21875
4
""" https://edabit.com/challenge/BfSj2nBc33aCQrbSg """ import math def is_prime(n: int) -> bool: if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, math.ceil(math.sqrt(n)) + 1, 2): if n % i == 0: return False r...
354e24517e91ebe060366072d43dd3ae1567a7f0
Slawak1/pands-problem-set
/second.py
1,199
4.28125
4
# Problem No. 9 # Slawomir Sowa # Date: 11.02.2019 # Write a program that reads in a text file and outputs every second line. The program # should take the filename from an argument on the command line. # argv() is part of sys library. import sys # validate file name, if none or wrong file name provided, error mess...
8ebf4f35582bdbf41be20c45b5c1b87721d4a847
amirarfan/INF200-2019-Exercises
/src/amir_arfan_ex/ex05/bounded_sim.py
3,889
3.75
4
# -*- coding: utf-8 -*- __author__ = 'Amir Arfan' __email__ = 'amar@nmbu.no' from walker_sim import * class BoundedWalker(Walker): def __init__(self, start, home, left_limit, right_limit): """ Initialise the walker Arguments --------- start : int The walker's...
2492461054f3d6089a71862805b3c05e25da5d0d
ataabi/pythonteste
/Desafios/ex058.py
1,311
3.875
4
# Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em um número entre 0 e 10, # Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos # palpites foram necessários para vencer. from random import randint player = 0 count = 0 print('\033[4:35m-#\033[m'*20, f"\n{'[ Jogo de A...
c3f3b8375f53bdc1539b0ecff13b33cd5ce19944
ilahoti/csci-101-102-labs
/102/Week3B-siblings.py
473
3.90625
4
#Ishaan Lahoti #CSCI 102 – Section C #Week 3 - Lab B - Three Siblings #References: None #Time: 20 minutes print("Input a positive number for the siblings to consider:") num = int(input("NUMBER> ")) print("The sibling(s) who will work with", num, "follow:") digi = str(num) digisum = 0 for i in digi: digisum += int(...
2b54435b15db4767687ae6ebeb1e2ea269fd1c13
syurskyi/Python_Topics
/070_oop/002_special_method/examples/__getattribute__/001.py
535
3.53125
4
class Foo(object): def __getattribute__(self, name): print "getting attribute %s" % name return object.__getattribute__(self, name) def __setattr__(self, name, val): print "setting attribute %s to %r" % (name, val) return object.__setattr__(self, name, val) foo = Foo() foo.v...
0925bfa5914a531ba7ab43a27a0f5c86e627db77
mevikpats/KTH
/Fundamentals of Computer Science/Mode.py
769
3.65625
4
import math def mode(vec): """Returns the most common element in a list of integers. If several integers occurs the same amount of times it returns the smallest. """ dict = {} count = 0 value = 2**64 for i in vec: # O(n) if i in dict.keys(): dict[i] += 1 # O(1) ...
d617554120f722b19744c13ef384865c7f905187
NMVRollo/PythonStepik
/6_3/8.py
77
3.5625
4
email = input() print('YES' if all(_ in email for _ in ('@', '.')) else 'NO')
1abf2947c600ce9833d27e307b0086ed9ea2392a
st34-satoshi/solving-matrix-game
/main.py
5,998
3.609375
4
from ortools.linear_solver import pywraplp def solve_matrix_for_row_size_two(matrix): """ Compute the value and the Row player strategy. The size of the matrix is 2*2. x (=(x1, x2))is the strategy of the Row player. a_i,j is the value of the matrix. Maximize 'L' such that a_1,1 * x1 + a_2,...
6b2c9708b6c0672d062f03d7f2b1a59c0d52d955
MinniFlo/curpymines
/src/GameLogic/Field.py
1,940
3.65625
4
class Field: def __init__(self, y, x): self.y_pos = y self.x_pos = x self.render_x_pos = x * 2 self.mine = False self.open = False self.flag = False # is used to highlight Fields, that are relevant for further solving self.relevant = False s...
c5b9cd4efb400faed6e6ca07ed0722f35129fc42
vardhan-duvvuri/Challange
/ch16.py
380
3.765625
4
def isAllLettersUsed(word, required): letters = [] requiredlist = [] for i in required: letters.append(i) letters = set(letters) for i in word: requiredlist.append(i) requiredlist = set(requiredlist) if len(letters.intersection(requiredlist)) == len(letters): return True else: return False if __name...
03c78b2c5231142cb98a8d3bd996cc670bdf3a9d
DShKMG/Hackkerrank-Python
/ProblemSolving/betweentwosets.py
335
3.515625
4
from functools import reduce def getTotalX(a, b): def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return a*b//gcd(a, b) l = reduce(lcm, a) g = reduce(gcd, b) s = 0 for i in range(l, g+1, l): if(g % i == 0): s += ...
cfef347f881a7c5a3745eec03e68eb29bcf1a54b
silverbowen/COSC-1330-Intro-to-Programming-Python
/William_Bowen_Lab5av2.py
3,406
4.34375
4
# This program uses semi-recursive loops # to calculate conversions between # Standard and Metric measurements def main(): # initializes variables and calls GetMeasure errorcount = 0 miles = -1 fahren = 1001 gallon = -1 lbs = -1 inch = -1 GetMeasure(errorcount, miles, fahren, gallon, lb...
cbe83a31f785877dac8d532c44b689ef260853a9
pipilove/MachineLearning
/AndrewNG/GradientDescent.py
2,031
3.640625
4
#coding: utf-8 ''' Created on Jul 13, 2014 @author: 皮皮 ''' import matplotlib.pyplot as plt import numpy as np import math # def mse(list_x, list_y): # mse = 0.0 # for x, y in zip(list_x, list_y): # mse += math.pow(x -y, 2) # return mse / len(list_x) if ...
9e1b0d1a82a907516b8e3c019fc4eb070bee2fdd
izipris/reviewsIdentifier
/learning/ID3.py
14,574
3.65625
4
# python file responsible for creating a classification tree using the ID3 algorithm import pandas as pd import math from heapq import nlargest class IGNode: def __init__(self, attribute=None, label=None, one=None, zero=None, parent=None): self.attribute = attribute # the attribute this node splits by ...
c7cd6cce13f228d71e686ce42fc281f0d1822597
AustinTSchaffer/DailyProgrammer
/LeetCode/ReverseWordsInString/app.py
436
3.765625
4
class Solution: def reverseWords(self, s: str) -> str: output = [] current_word = "" for char in s: if char == " ": if current_word: output.insert(0, current_word) current_word = "" else: current...
68888932ca34d1e0e4e2339f759eee26d45f165e
raffivar/SelfPy
/unit_9_files/are_files_equal/are_files_equal.py
217
3.5625
4
def are_files_equal(file_path_1, file_path_2): with open(file_path_1, "r") as file1, open(file_path_2, "r") as file2: return file1.read() == file2.read() print(are_files_equal("file1.txt", "file2.txt"))
ea13119c9755e037785f60ff9b155f53c6c0d800
joy1303125/Gaming_Project_and_Web_scrapping
/Rock_Paper_scissor/rock paper.py
2,510
4.0625
4
import random import simplegui Computer_score=0 Human_score=0 computer_choice="" human_choice="" def choice_to_number(choice): rps_dict={'rock':0,'paper':1,'scissors':2} return rps_dict[choice] def number_to_choice(number): rps_dict={0:'rock',1:'paper',2:'scissors'} return rps_dict[number] d...
6507a6110914b3484ccccb6af4011e5927a7b819
ritchie-xl/LintCode-Ladder-Nine-Chapters-Python
/ch2/find_bad_version.py
1,033
3.703125
4
# class VersionControl: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use VersionControl.isBadVersion(10) to check whether version 10 is a # bad version. """ @param n: An intege...
c221cbe0148f0c5838bcf43581e9d62aa795b47f
Ariok-David/edd_1310_2021
/Tarea 6/pruebas.py
233
3.5
4
from listas import LinkedList l = LinkedList() l.append(0) l.append(1) l.append(2) l.append(3) l.append(4) l.append(5) l.append(6) l.append(7) l.append(8) l.append(9) l.append(10) l.append(11) l.append(12) l.transversal() l.get(-1)
b9ccde8e600e15daef4b3a00135bdbfe9e539fa9
alexparunov/leetcode_solutions
/src/1-100/_28_implement-strstr.py
472
3.59375
4
""" https://leetcode.com/problems/implement-strstr/ """ class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 N = len(haystack) K = len(needle) if K > N: return -1 for i in range(N - K + 1): k = ...
0bfbd8d226ea61cf0de3df1d947b52e67f6793b5
Bangatto/Braille_Translator
/english_braille.py
9,987
3.875
4
# COMP 202 A2 Part 5 # Author: GATTUOCH KUON from text_to_braille import * ENG_CAPITAL = '..\n..\n.o' # You may want to define more global variables here #################################################### # Here are two helper functions to help you get started def two_letter_contractions(text): '''(str) -> st...
10a9a45312f1439dd980143ddb0610f24a717f4f
nivedithaHN/OpenCV
/Image color split .py
1,617
3.5625
4
# coding: utf-8 # In[95]: #Choose RGB image - Plot R, G & B separately import matplotlib.pyplot as plt import cv2 # In[96]: #Read the image img = cv2.imread("img5.jpg") #Image type type(img) # In[97]: #Shape of image array img.shape #3 stands for color channel. #There is a difference in pixel ordering in O...
f248e66d6809c9ca825f80f1aab4c285c8492b58
coolmanjingwu/zillow-estimate
/tic-tac-toe.py
3,463
3.984375
4
import random #our board in dictionary form board = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' ' } g_numx_win = 0 g_numo_win = 0 g_num_tie = 0 g_times = 0 g_turn = ['X', 'O'] #print our board def printBoar...
0a736a95d85a3f6b37b671a95c5005378b8e9d81
algono-ejercicios-upv/CACM
/Programming-Challenges/Chapters/3/Doublets/doublets.py
10,450
3.703125
4
def str_diff(one: str, two: str): if len(one) == len(two): diff = 0 for l_one, l_two in zip(one, two): if l_one != l_two: diff += 1 return diff else: return None def str_diff_closure(one: str): return lambda two: str_diff(one, two) def str_inc(...
9f0ef50c14cbe3fb6231d68e7c07a5b3d3342ff1
andrewsokolovski/Python-learning
/Alien_ inv/ship.py
1,227
3.703125
4
import pygame class Ship(): """ class for ship running """ def __init__(self, ai_game): """ init ship and assign start posission """ self.screen = ai_game.screen self.settings = ai_game.settings #self.settings = ai_game.settings self.screen_rect = ai_game.screen.get_rect() #Load ship drawing and get r...
7abd452e3f039d11224d862292fce05e6ff588ae
peterJbates/euler
/020/factorial_sum.py
399
3.984375
4
import time start_time = time.time() #computes the factorial of n def factorial(n): product = 1 while n > 0: product *= n n -= 1 return product #computes the digit sum of a number def digit_sum(n): summation = 0 number = str(n) for i in number: summation += int(i) return summation print(di...
0d044ce2b69a16127a8478495ad54961068f8f47
jsonhc/git_test
/landing.py
2,770
3.578125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:jsonhc #f = open(r'D:\study\project\day1\file_new.txt','w') #f.write("hello world") ''' 作业需求: ① 输入用户名密码 ② 认证成功后显示欢迎信息 ③ 输错三次后锁定 ''' ''' >>> i = "hello world" >>> i.strip() 'hello world' >>> i = "hello world " >>> i.strip() #strip()方法去掉末尾空格字符 'hello worl...
bed1773e706c01812a79f29971e0ed2b2f906269
Lisolo/Python-Cookbook
/Data Structures and Algorithms/Sorting_Objects_Without_Native_Comparison_Support.py
1,896
4.25
4
# coding=utf-8 """ Problem You want to sort objects of the same class, but they don’t natively support comparison operations. Solution The built-in sorted() function takes a key argument that can be passed a callable that will return some value in the object that sorted will use to compare the objects. For example...
0fb11e67d0a63f59f29b79dc804076e4d15e8b19
amiraliakbari/sharif-mabani-python
/by-session/ta-932/j5/recursive2.py
999
3.53125
4
a = [1, 2, 6, 7, 9, 10, 20, 30] def search_linear(a, x): for y in a: if x == y: return True return False def search_linear_index(a, x): for i in range(len(a)): if a[i] == x: return i return -1 def search_binary(a, x): n = len(a) if...
6195c769c5bb0a3113dd0dc89eb2854d0d573c07
pingany/leetcode
/majorElements.py
742
3.640625
4
#!/usr/bin/env python #-*- coding: utf-8 -*- import os,re,sys,commands,glob reload(sys) sys.setdefaultencoding("utf-8") class Solution: # @param num, a list of integers # @return an integer def majorityElement(self, num): map = {} for n in num: if n not in map: ...
26d84a24aa812ad70307d92a061f4dd46a93ab3f
Lyonmwangi/learn_python
/python_practice.py
145
3.625
4
print "ian" ''' var=1 while var==1: print("leo") ''' count =0 while(count<50): print "the count is:",count count= count+10 print "goodbye"
73e4340274a26749dfd0f90ec013dd24c239cbb3
kbethany/LPTHW
/ex6.py
749
4.0625
4
# create var x that is a string, with a number, %d, that is set to 10 x = "There are %d types of people." % 10 #creates var binary set to string "binary" binary = "binary" #same do_not = "don't" #creates var y that is a string with 2 format characters that reference other already-made string vars, binary and do_not y =...
30463e25c78ae51d99a5ddc06a58c1f7d17127ea
sharannyobasu/Hacker-Blocks
/gcd.py
166
3.859375
4
def gcd(a,b): if(b>a): if(b%a==0): print(a) else: gcd(b-a,a) else: if(a%b==0): print(b) else: gcd(a-b,b) a=int(input()) b=int(input()) gcd(a,b)
d0be2ceae0c4d04c808d442bbebd42106def7a8b
Irfanmuhluster/Belajar-python
/loop2.py
135
3.890625
4
x = [2, 3, 4, 4] y = [100, 200, 300] x1 = [] x2 = [] y.append(x) for loop in y: x1.append(x) x2.append(x) print(list(x1, x2))
4738eefb49f7f4f759f3d2752aaf4bfb777d1242
ashrafatef/Prims-Task
/app.py
1,588
3.703125
4
import functools def get_all_prime_numbers_in_list (prime_numbers): p = 2 limit = prime_numbers[-1] + 1 while p*p < limit: if prime_numbers[p] != 0 : for i in range(p*p , limit , p): prime_numbers[i] = 0 p+=1 return prime_numbers def get_m...
7d5e642ca72fd87f31e4fa9cc8f62a9b158adf1d
martinbudden/epub
/test/test_xml.py
770
3.5
4
""" Test the xml conversion. """ #import epub.mediawikibook from epub import mediawikibook def test_xml(): """Test reading a file that contains non-ascii data.""" print "Testing alice preface" title = "Through the Looking-Glass, and What Alice Found There" title = "alice" filename = "test/data/" ...
6cd5d5613b198c9ac5e33626d808d8d5b8b10043
Pavel-svg/Python
/les1.py
372
3.71875
4
names = ["Володя", "Валера", "Вася", "Саша", "Антон", "Яков"] search_for = "Антон" def linear_search(where, what): for v in enumerate(where): if v[1] == what: return v[0] return None print("Искомый элемент", search_for, "Найден под индексом", linear_search(names, search_for))
53d631e1d777e4cd482b635fa21eb4452ef91c2e
roohom/FileAndIO
/search_file/Search_file.py
1,105
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : Search_file.py # Author: roohom # Date : 2018/10/23 0023 """ 搜索文件脚本 version 1.0 - 用户输入文件目录和目标文件的名称,开始在目标文件夹里搜索目标文件,结果返回目标文件所在的1文件夹名称 - search_file函数负责工作 - os.listdir列出文件夹里所有的文件 - os.path.isdir判断文件是否为文件夹 - 是,调用search_file函数,继续...
6d4aaa5c49e252f1ab27a96c70d28ffb908715c2
yangao118/exercises
/CLRS/C10_elementary_data_structures/tree.py
2,746
4.1875
4
#!/usr/bin/env python # Since we only deal with how to print a tree, but no assumptions # about how to insert and delete node. So, the algorithms here # is much like pseudo codes. class BinaryTreeNode: def __init__(self, key, parent, left = None, right = None): self.key = key self.parent = parent ...
7fd64f6eb9a27fb2d118ff5c45b88f2266a9fd50
Li-Pro/Short-Codes
/ptc1.py
6,062
3.609375
4
""" A Simple Game. Control: <Space> + WASD Beat this game: make your self the top 0.0% """ ## TODO: ## 1. replace move() into coords() ## 2. features: level / better collision check # Tkinter + Canvas practice import math import random import tkinter as tk import time def _hexRGB(r, g, b): return '{:02x}{:02x}{:0...
590c73608b3db2f0e44dedffcd7bcd27625c55b1
nana4/Lab_Python_02
/lab03a_1.py
371
3.953125
4
###Q1) num=raw_input("enter a number to send: ") num=int(num) while num>0: coded=num%10 print coded, num=num/10 print "\n------------------------------------------------" ###Q2) num=raw_input("enter a number to send: ") num=int(num) while num>0: coded=(num+7)%10 print coded, num=num/10 print "\...
dcce5fefe6dd75ed4ba62af8b7c054917e27f2e0
sheadan/LabDAQ-App
/serialHandlerUI.py
6,314
3.75
4
""" The SerialPortFrame class sets up a GUI frame that allows the selection of a desired serial port from a list of all available serial ports, provides connect and disconnect buttons, as wells as a connection indicator. Added button to refresh available ports. self.device refers to an Arduino object that can be used f...
7e96fc68c679449a2ca1f96864229828dfc55264
altair1016/TicTacToePY
/Game.py
645
3.59375
4
import TicTacToe as TTT import time import sys import Ia from TTTException import * game = TTT.TicTacToe() playerIa = Ia.Ia(1, "O") while game.getPlay() != 0: player = game.getTurn() print("E il turno di " + player) try: val = input("Dammi le coordinate Riga,Colonna: ") posY,posX = val.split...
4c696cbc094f7b7b14ebc79411740950ebd2d949
FrMohande/Licence-2---Semestre-3
/Programmation/Parentheses/src/parentheses_checker2.py
2,066
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Outioua Mohand -- Jonathan Soleillet from stack import * def well_parentheses(filename): """ Print which parenthesis is closed or not :param filename: file :type filename: file :UC: None :Example: >>> well_parentheses("stack.py...