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
6c19713fa60435e615e13525645afcec6553185b
emilnorman/euler
/problem037.py
2,482
3.9375
4
# !/usr/bin/python3 # -*- coding: utf-8 -*- # The number 3797 has an interesting property. Being prime itself, it is # possible to continuously remove digits from left to right, and remain prime # at each stage: 3797, 797, 97, and 7. Similarly we can work from right to # left: 3797, 379, 37, and 3. # # Find the sum of...
48798e1b51baefc7c23b92cf86b34eef35313cee
emilnorman/euler
/problem007.py
493
4.15625
4
# !/usr/bin/python # -*- coding: utf-8 -*- # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, # we can see that the 6th prime is 13. # # What is the 10 001st prime number? def next_prime(p): temp = p + 2 for i in xrange(3, temp, 2): if ((temp % i) == 0): return next_prime(t...
aad8eaca6bded8291f3ea6bbedc8c9fc93540eaa
tobbyGithub/ML-CSC715
/chisom.py
690
4.0625
4
import numpy as np f1 = open('6.-.-.-.txt', 'r') lines = f1.readlines() #print alll rows print(lines) #print first row print(lines[0]) #list to store column 3 items stuffs=list() #loop to iterate and pick items for line in lines: columns = line.split() #print the 3column for u to see print (columns[2]) ...
902420aa2057c4fa92ac4c2db41a6209b6454fb8
rsoemardja/Python
/PythonAndPygameArcade/Chapter 4 Guessing Games with Random Numbers and Loops/4.2/PythonForLoopAnim/PythonForLoopAnim/test.py
318
4.09375
4
# This will only print Hello 5 times and There 1 time # Because the for loop is asscociated with the indent and the unindented line is not for i in range(5): print ("Hello") print ("There") # This code everything indented is associated with the for loop for i in range(5): print ("Hello") print ("There")
05bd5cba24b50221d83ae84bee8958dff9b2c7ae
rsoemardja/Python
/PythonAndPygameArcade/Chapter 3 Quiz Games and If Statements/3.2/PythonOrder/PythonOrder/test.py
996
4.3125
4
# we are going to be taking a look at logic with if Statements # Their is actually a hidden error # The error is that computer looks at each statement # and is 120 > 90. It is indeed and the else would execute but the else DID not excute hence the logic error temperature=input("What is the temperature in Fahrenheit? ")...
313c45fa97a1c12eee440966216c3904f549cd07
KDRGibby/learning
/nthprime.py
781
4.46875
4
def optimusPrime(): my_list = [1,2] my_primes = [] prime_count = 0 # this is supposed to add numbers to my_list until the prime count reaches x numbers. while prime_count < 10: last_num = my_list[-1] my_list.append(last_num + 1) #here we check to see if a number in my_list is a prime for i in my_list: ...
fbbab1cb7a3638b414a9c06dd65d845c5c9a48de
WHeesters/PythonHelp
/Lesson16_sorting-lists-tuples-objects.py
3,051
4.125
4
import sys print(sys.version) print("================================================") print("SORTING LISTS, TUPLES AND OBJECTS") print("================================================") print("---------------------") print("LISTS") print("---------------------") num_li = [9, 2, 3, 6, 5, 4, 1, 7, 8] s_num_li = sort...
950618e6a2097e03785b487d6cc1afa1ddabf60c
WHeesters/PythonHelp
/Lesson17_error-handling_try-except.py
1,408
3.96875
4
import sys print(sys.version) print("================================================") print("ERROR HANDLING WITH TRY/EXCEPT") print("================================================") try: f = open("files/text.txt") # Wrong except Exception: print("File doesn't exist") # Throws exception based on anything...
ee381f36ecae1eb128267ca4bdc0b8afe342d7bb
ethancooley/Money-Tracker
/tracker.py
4,029
3.8125
4
from function import process_file sampleRegularTransactions = 'Sample_Regular_Transactions.txt' noRegularTransactions = 'No_Regular_Transactions.txt' weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] # Imports command line arguments and tests function for exceptions try: major_list = process_file(file...
318222d09c0adabbf2b29a14d6f0686bcd284a67
kislayt/2021sp-final-project-nikhar1210_Public
/src/text_prep_func.py
4,361
3.53125
4
# -*- coding: utf-8 -*- """ @author: nikshah text prep functions """ import nltk import string import html from nltk.corpus import wordnet import re def multipleReplace(text, wordDict): """ take a text and replace words that match the key in a dictionary with the associated value, ret...
6c0fcf97e0aa94637e2582269a0984bb41003c52
LeiZhang0724/leetcode_practice
/python/practice/easy/reverse_int.py
2,743
4.15625
4
# Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside # the signed 32-bit integer range [-231, 231 - 1], then return 0. # Assume the environment does not allow you to store 64-bit integers (signed or unsigned). def reverse(x: int) -> int: INT_MIN, INT_...
53012172964cb3269a658d479d809eafd022c9c7
yngwieli10/password-try
/password-try.py
224
3.703125
4
password = 'a123456' n = 3 while n>0: psd = input('請輸入密碼:') if psd == password: print('登入成功') break else: n = n-1 print('密碼錯誤你還有', n,'次機會')
fcff2e506888d5440c56780263cde7ae02f7ec20
Heasummn/DevLang
/lexer.py
7,353
3.75
4
from enum import Enum class Operator(Enum): plus = '+' sub = '-' mult = '*' div = '/' func_one = '=' func_multi = '=>' arg_list = '->' type_sep = '|' class Special(Enum): EOF = 0 Whitespace = 1 class Type(Enum): Integer = 0 Char = 1 String = 2 class Keyword(Enum):...
08e9beb56310f0d3918386285b1664cb4cc4d77d
Vent002/Python
/code/day04/CRAPS赌博游戏.py
1,447
3.90625
4
''' @Date: 2020-02-28 14:47:24 @LastEditors: gxm @LastEditTime: 2020-02-28 15:04:00 @FilePath: \Python workplace\code\day04\CRAPS赌博游戏.py **说明**:CRAPS又称花旗骰,是美国拉斯维加斯非常受欢迎的一种的桌上赌博游戏。 该游戏使用两粒骰子,玩家通过摇两粒骰子获得点数进行游戏。 简单的规则是:玩家第一次摇骰子如果摇出了7点或11点,玩家胜; 玩家第一次如果摇出2点、3点或12点,庄家胜; 其他点数玩家继续摇骰子,如果玩家摇出了7点,庄家胜; 如果玩家摇出了第一次摇的点数,玩家胜; 其他点数,玩家继...
edb822d25ea8a99dc97163595cd355e5bfa83cdc
Vent002/Python
/code/day04/完美数.py
647
3.5625
4
''' @Date: 2020-02-28 15:15:44 @LastEditors: gxm @LastEditTime: 2020-02-28 15:20:26 @FilePath: \Python workplace\code\day04\完美数.py **说明**:完美数又称为完全数或完备数, 它的所有的真因子(即除了自身以外的因子)的和(即因子函数)恰好等于它本身。 例如:6($6=1+2+3$)和28($28=1+2+4+7+14$)就是完美数。 ''' import math for num in range(1,10000): result = 0 for i in range(1,int(math.sqr...
e170befde825656d17d5b17b81cd51d3c0f09c55
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.36.py
294
4.125
4
#-*-coding: utf-8 -*- """ Write a Python program that inputs a list of words, separated by whitespace, and outputs how many times each word appears in the list. You need not worry about efficiency at this point, however, as this topic is something that will be addressed later in this book """
26f12c3a70ccad682d7de1d86d26c4a276898171
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 2/R/R-2.15.py
825
4.03125
4
#-*-coding: utf-8 -*- """ The Vector class of Section 2.3.3 provides a constructor that takes an integer d, and produces a d-dimensional vector with all coordinates equal to 0. Another convenient form for creating a new vector would be to send the constructor a parameter that is some iterable type representing a seque...
fbef3fb244b0ecb1c97a293c1f9e029fe3273f6f
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 2/R/R-2.4.py
426
4.3125
4
#-*-coding: utf-8 -*- """ Write a Python class, Flower, that has three instance variables of type str, int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method that initializes each variable to an appropriate value, and your c...
3d1efee5bd503d5503ecafc36e40b60ef833fb7c
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/R/R-1.1.py
590
4.40625
4
#-*-coding: utf-8 -*- """ Write a short Python function, is_multiple(n, m), that takes two integer values and returns True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise """ def is_multiple(n, m): n = int(n) m = int(m) if n % m == 0 and n != 0: return True els...
092eca02e6e2d164b20444d05b2c328e0b548cb6
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.32.py
395
4.21875
4
#-*-coding: utf-8 -*- """ Write a Python program that can simulate a simple calculator, using the console as the exclusive input and output device. That is, each input to the calculator, be it a number, like 12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input, you should o...
80ec0232a799f23da0bd025587ecb4143c8dc065
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 7/P/P-7.44.py
660
3.984375
4
#-*-coding: utf-8 -*- """ Write a simple text editor that stores and displays a string of characters using the positional list ADT, together with a cursor object that highlights a position in this string. A simple interface is to print the string and then to use a second line of output to underline the position of the...
78dc75ea1330111af5a9707625ed73d57753dc83
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.31.py
564
4.09375
4
#-*-coding: utf-8 -*- """ Write a Python program that can “make change.” Your program should take two numbers as input, one that is a monetary amount charged and the other that is a monetary amount given. It should then return the number of each kind of bill and coin to give back as change for the difference between t...
22b452d292aa36f6157ea4c232f504ae8848754d
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 7/R/R-7.7.py
2,151
4
4
#-*-coding: utf-8 -*- """ Our CircularQueue class of Section 7.2.2 provides a rotate( ) method that has semantics equivalent to Q.enqueue(Q.dequeue( )), for a nonempty queue. Implement such a method for the LinkedQueue class of Section 7.1.2 without the creation of any new nodes. """ class LinkedQueue: """FIFO qu...
c2cbd4fce80c162b3f026c3a91a5868dac04d87e
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/C/C-1.20.py
443
3.625
4
#-*-coding: utf-8 -*- """ Python’s random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possible order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a ...
16593f3b9b3fd86e47147d265e85750bb8e8942c
allenxzy/Data-and-Structures-and-Alogrithms
/python_data/Chapter 1/P/P-1.35.py
450
3.53125
4
#-*-coding: utf-8 -*- """ The birthday paradox says that the probability that two people in a room will have the same birthday is more than half, provided n, the number of people in the room, is more than 23. This property is not really a paradox, but many people find it surprising. Design a Python program that can te...
cb240b40528ebdb6d01eb421a9aec8dec6f1f34a
wndessy/Algorithm
/Basic/validate_pin.py
450
3.546875
4
import re import unittest def validate_pin(pin): #return true or false r=re.compile(r"^(\d{4}|\d{6})$") result=bool(re.match(r,pin)) result=pin.isdigit() and( len(pin)==4 or len(pin)==6) print(result) # validate_pin('098765') # unit tests import unittest class MyTestCase(unittest.TestCase): ...
a8b7e913ed08031e7e10d12732b75cb34a3806a7
bhaskararaokarri/unittestjuly6th
/main.py
3,172
3.65625
4
""" @ Bhaskara Rao Karri, Date : 06/07/2020. """ # Import the required Modules on here. import warnings # Create a Testclass on here. class Test(): pass # Create a Test1class on here. class Test1(): pass # Define the functions with required arguments for Exception and checking the conditions that functio...
9f24c42b2d66592bdc91173a09a564f1842e45d7
TomokiIkegami/Numerical-method2
/cl_3-2-1.py
181
3.984375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 27 18:00:41 2020 @author: Tomoki Ikegami """ A=[2,3,5,8,12] for i in reversed(A): if i==3: pass else: print(i)
b679eba70c481486c07c7f4d33939bdb89a1f1b0
faithfem/webscrapper
/BloomDJ.py
456
3.546875
4
# import libraries import urllib2 from bs4 import BeautifulSoup quote_page = "https://www.bloomberg.com/quote/INDU:IND" page = urllib2.urlopen(quote_page) soup = BeautifulSoup(page, "html.parser") name_box = soup.find('h1', attrs={'class': 'name'}) name = name_box.text.strip() # strip() is used to remove starting a...
b507b4c79a4d761431a9e1a1cc13ad0ad4e2f6dc
CR-ari/Python
/p.126.py
717
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 4 16:56:38 2020 @author: 9876a """ print('List Name: ') name = input() print('List Element: ') element1 = input() name = [] name.append(element1) print('Do you want to add more elements? [Y/N]') choice = input() while choice == 'Y': print('Element: (If you want ...
bd221d612cafc1dfcf1cff7242ae73f2d8088a40
v1ct0r2911/semana_6_lab
/ejercicio 1.py
116
3.96875
4
numero=int(input("ingrese un numero: ")) if numero % 2 == 0: print("numero par") else: print("numero impar")
2124b62809bc75f650e3ed62908a4fb2aaf74ac9
avanti-bhandarkar/ML
/2.py
1,812
4.125
4
#1 - linear regression with sklearn import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt #predictor variable x = np.array([5, 15 , 25 , 35 , 45 ,55]) xm = x x = x.reshape((-1,1)) x.shape #response variable y = np.array([4,7,23,5,39,23]) ym = y #y = y.reshape((-1,1)) y....
fda5b523a5f3b59c2c888f8517a95a9040900543
majingpu/Spider_Python
/request_spider/demo_re.py
586
3.59375
4
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import re password = 'hello world IFJKLS342jkflsj' line = "Cats are smarter than dogs" result = re.match(r'^hello world (\w+)$', password) print(type(result)) print(result.group(1)) result1 = re.search(r'(.*) are (.*?) .*', line) print(type(result1)) print(result1.group...
0508802ca1112fb2eb9998c545cfe90245b9ffbf
swj8905/2021_Hongik_Summer
/test.py
2,899
3.875
4
list = [] numOfData = 0 ##### 이런 것도 하나의 함수로 만들어 놓으면 조금이라도 코드의 가독성을 높이는 효과가 있습니다. def showMenu(): print("—————————" + "\n" + f"현재 {len(list)}개의 데이터가 있습니다." + "\n" + "—————————") print('''1. 전화번호 추가 2. 전화번호 검색 3. 전화번호 삭제 4. 전화번호 전체 출력 5. 종료 ------------------''') def showMsg(): print("프로...
f69fcbe376c60174372a55045aba9cb2e70c1cc8
Moskovetc/Python
/study/les_5/easy.py
2,235
3.734375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Задача-1: # Напишите скрипт, создающий директории dir_1 - dir_9 в папке, # из которой запущен данный скрипт. # И второй скрипт, удаляющий эти папки. import os import shutil def make_dir(dir_name): dir_name=os.path.join(os.getcwd(),dir_name) try: os.mkdir(...
d22cd7865db4233da780c7346c2df1a21d7ef71c
jeasonliang/Learning-notes
/Python/3-8-9-10address.py
2,702
4.28125
4
#想出至少 5 个你渴望去旅游的地方。将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。 world_address = ['LosAngeles','Beijing','Xiamen','Amsterdam','Caribbean Sea'] print('按照原始排列顺序打印该列表:\n\t',world_address)#按原始排列顺序打印该列表。 print('按照临时排列字母的顺序打印该列表:\n\t',sorted(world_address))#使用 sorted()按字母顺序打印这个列表,同时不要修改它。临时排序 print('按照原始排列顺序打印该列表:\n\t',world_address)#再次...
7fef6b643fa7d1e7229a9e3f9cb9883c6814359f
trulshj/Kattis
/quadrants.py
204
3.5625
4
import fileinput x, y = [int(line.rstrip()) for line in fileinput.input()] if x > 0 and y > 0: print(1) elif y > 0 > x: print(2) elif x < 0 and y < 0: print(3) elif x > 0 > y: print(4)
0a183f72d56eaeac21187fd064312cb6758e3bbd
MrAlekzAedrix/MetodosNumericos
/Append.py
339
3.984375
4
def AppendValue(lista, el): try: if el in lista: raise ValueError else: lista.append(el) return lista except ValueError: print("You can't have duplicated values") return lista list = [1, 2, 3, 4, 5, 6] print("The full list is: ",Ap...
332fc756edf963a9f305cb9e03ded25021006b89
MrAlekzAedrix/MetodosNumericos
/Calificacion.py
249
3.921875
4
#Calificación n = int(input("Please enter you final grade: ")) if n < 5 : print('Failed') if n == 5 : print('F') if n == 6 : print('E') if n == 7 : print('D') if n >= 8 : print('Approved')
442e96d83f34f389833cff1432eebb4e5180363e
MrAlekzAedrix/MetodosNumericos
/GreaterNumber.py
525
3.796875
4
#Número mayor print('Welcome!') #Mensaje de bienvenida n1 = int(input('Please enter the first number: ')) #Entrada primer número n2 = int(input('Please enter the second number: ')) #Entrada segundo número if n1>n2 : #Condición si el primero es mayor print('The higher number is: ', n1) #Imprime el primero ...
b0d46c8504fb5727ee24fb69445df9cd1de01ed7
wampiter/pun
/vowelreplace.py
1,584
3.640625
4
#This program finds all phonetic sub and super strings of the given ENGLISH word. import codecs import string #reload(sys) dicty=codecs.open('nocdict.txt', 'r', 'utf-8') #sys.setdefaultencoding('utf-8') eng = raw_input("Please enter an English word (spelling counts):\n") eng=eng.lower() wordlist=[] for line in dicty...
3b2697ab6e542498a23f4285488175269fe8a304
msawastian/python-playground
/9-Classes/user.py
1,186
3.515625
4
class User: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name self.login_attempts = 0 def describe_user(self): print("This user's name is: " + self.first_name.title() + ' ' + self.last_name.title() + '.') def greet_user(self...
63d1b463e3e5baee36ac80d7fdcc561a38180e14
ksemele/hangman
/hangman.py
1,629
3.984375
4
from random import choice def open_hidden_letter(choice_word, hidden_word, input_letters, c): i = 0 if c in input_letters: print("You've already guessed this letter") return True else: if len(c) == 1 and c.islower(): input_letters.append(c) if c not in choice_word:...
6b39e106e65c8f82782ce7f578c23e7249bc96b5
yanbinbi/leetcode
/101-200/117.py
1,067
3.921875
4
# Definition for binary tree with next pointer. # class TreeLinkNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None from collections import deque class Solution(object): def connect(self, root): """ :type...
c4c94702791987eda57c945de3e29c528683f402
yanbinbi/leetcode
/301-400/381.py
1,784
3.953125
4
import random class RandomizedCollection(object): def __init__(self): """ Initialize your data structure here. """ self.data = [] self.pos = {} self.length = 0 def insert(self, val): """ Inserts a value to the collection. Returns true if the coll...
89432ec5a5e67243ab6aa109b5823bd3a7a38eef
yanbinbi/leetcode
/101-200/105.py
855
3.8125
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 buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] ...
600eab4d379d92633f96eba643daa039a65782fb
yanbinbi/leetcode
/101-200/143.py
969
3.828125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. ...
faafefb201e93b4f30f462e273fe37c2fe651529
yanbinbi/leetcode
/101-200/173.py
1,002
3.9375
4
# Definition for a binary tree node # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator(object): def __init__(self, root): """ :type root: TreeNode """ self.q = [] if root is None els...
b363f8b7633f4cc5b88dc340ccebf825e094d9dd
yanbinbi/leetcode
/1-100/82.py
922
3.6875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: ...
21cc366435012f82f20da4b9ed14a69d4ab9dc32
yanbinbi/leetcode
/1-100/23.py
1,241
3.90625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ size = len(lists) ...
597f5db62acb39140934496b697e14acf390608a
yanbinbi/leetcode
/201-300/236.py
1,042
3.609375
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 lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :t...
b0325e6d0744e6ea42bfbd29509498caa3dca52a
mariosantiago/githubActividad2FD
/2.ocp.py
730
3.890625
4
import abc from abc import ABCMeta class Coche (object): __metaclass__ = ABCMeta def init(self, name: str): self.name = name @abc.abstractmethod def precioMedioCoche(self) -> str: pass class Renault(Coche): def precioMedioCoche(self): return 'Renault ' + str(18000) clas...
8707aee1d71dcf4a68289e7c2bed7de28b42e49b
FernandoVinha/Heart-Attack-30
/routes.py
2,019
3.578125
4
from flask import Flask from data import insert #from machine_learning import precisao app = Flask("API") #metodo da api para verificar a precisão da inteligencia artificial @app.route("/precision", methods=["GET"]) def precision(): return {"a precisão é"} #metodo da api para verificar um novo dado @app.route...
b03af57fe792735585523efe6e5b744c4e0267ad
Acowboyz/cousera-algorithmic-toolbox
/Algorithmic Warm Up/Least Common Multiple/lcm.py
613
3.921875
4
# python3 def lcm_naive(a, b): assert 1 <= a <= 2 * 10 ** 9 and 1 <= b <= 2 * 10 ** 9 multiple = max(a, b) while multiple % a != 0 or multiple % b != 0: multiple += 1 return multiple def gcd(a, b): if b == 0: return a else: a_prime = a % b return gcd(b, a_pr...
3f6a53764e1d21189bf7815d741d8f5a4ceb3fc9
Cristian-alfa/helloworld
/sfera.py
198
3.5
4
#sfera.py import math r = input("iserire raggio") s = 4. * math.pi * r * r v = 4. / 3. * math.pi * r * r * r print "la superficie della sfera di raggio ", r, "e' ", s, "mentre il volume e' ", v
448f26631206b409634a73644631cc2f7988feda
rioscesar/Python
/Algos and Data Structures/Sorting.py
1,700
3.765625
4
from itertools import product def bubble_sort(l): for i, j in product(range(len(l)), range(len(l))): if l[j] > l[i]: l[i], l[j] = l[j], l[i] return l def merge_sort(l): if len(l) > 1: mid = len(l) // 2 left = l[:mid] right = l[mid:] merge_sort(left) ...
ca063f4057583c505da0228a70bc7b25fec24108
rioscesar/Python
/Algos and Data Structures/BST and Node.py
3,047
3.828125
4
class Node(object): def __init__(self, value): self.value = value self.right = None self.left = None @property def value(self): return self.__value @value.setter def value(self, value): self.__value = value @property def right(self): return...
c6a33c69cd7b53d72aad72dea161b506d68bfd08
rioscesar/Python
/Learning Python/TEST Class.py
665
3.953125
4
class TEST(object): def __init__(self, fname, lname): self.fname = fname self.lname = lname @property def fname(self): return self.__fname @fname.setter def fname(self, fname): if fname.lower() == "cesar": self.__fname = "Jose" else: ...
d7afb165346fce1c1e7739795fd68b58f75691e8
fish-ball/leetcode
/algorithms/leet.0563.src.1.py
519
3.59375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTilt(self, root: TreeNode) -> int: ans = 0 def dfs(nd): nonlocal ans ...
859fd853fe9f9da63b42d64dbdf7c4c7d43f4a37
fish-ball/leetcode
/algorithms/leet.1609.src.1.py
817
4
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: q = [root] odd = True whi...
dafc36d48f761202feafcd2fea021078f875aeed
fish-ball/leetcode
/algorithms/leet.0863.src.1.py
1,255
3.640625
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 distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]: ans = [] # 向下 def dfs(node, n=0): ...
5b8c283fadbd573bc3244d3f14ec8122ed4dc8ed
fish-ball/leetcode
/algorithms/leet.0108.src.1.py
494
3.671875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None ...
c1329b5e075f4691b8cb276233e513bcbb3d598f
fish-ball/leetcode
/algorithms/leet.0092.src.1.py
716
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: if left >= right: return head p = None ...
e6bb226c684ef9e77adfcaede2775b8e068cb1af
fish-ball/leetcode
/algorithms/leet.0208.src.1.py
1,322
4.0625
4
class Trie: def __init__(self): """ Initialize your data structure here. """ self.value = '' self.children = [None] * 26 self.end = False def insert(self, word: str) -> None: """ Inserts a word into the trie. """ k = ord(word[0])...
0a3f0c905505781370979f0cca19787ff85b3455
fish-ball/leetcode
/algorithms/leet.5960.src.1.py
173
3.546875
4
class Solution: def capitalizeTitle(self, title: str) -> str: return ' '.join([w[:1].upper()+w[1:].lower() if len(w) > 2 else w.lower() for w in title.split()])
004d1f0badf642f8bdc45f0d8e7ff8a1a6cfb697
fish-ball/leetcode
/algorithms/leet.0725.src.1.py
635
3.5
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]: n = 0 p = head while p: n += 1 ...
87462e42bee8e4199af71d5ada56576571849d20
ArdaCemBilecan/Programlama-Lab
/Hafta1Crsb.py
673
3.78125
4
# pow fonksiyonunun recursive hali def power(a,b): if b ==0: return 1 elif b == 1: return a else: if b%2==0 : return power(a*a,b//2) else: return power(a*a,b//2)*a print(power(2,5)) print(power(2,4)) # Verilen listede alt kümelerin max olan toplam...
48ceaef59cab8db5b5ca8d050cbcde39d2f33f06
xInsanityx1022/Movie_Fundraiser.2
/00_MF-Base_v1.1.py
515
3.59375
4
# import statements # functions go here # ********** Main Routine ********** # set up dictionary / lists needed to hold data # ask user if they have used the program before & show instructions # loop to get ticket details # get name (not blank) # get age (between 12 & 130) # calculate ticket price...
718937ce35249bf2ff4601b9e3f5be95880f5df3
ko-takahashi/college
/CS596/Homework/HW3/main_logit.py
4,262
3.765625
4
""" This scripts includes two types of implementations of logistric regression. The first one is to implement the gradient descent (GD) method from scratch; the other is to call the sklearn library to do the same thing. The scripts are from the open source community. It will also compare how these two methods work t...
27fa386a6f4644700ec5b910a15e5505dcb89ea0
glendaqm/Llbean_data_science
/Sesion2/Ejercio_pixeles.py
500
3.640625
4
pixel = [0.6, 0.3, 0.4] a = pixel[0] + pixel[1] + pixel[2] a = a/len(pixel) listado = [8.999, 7.3, 10.4] promedio = 0 promedio = sum(listado)/len(listado) print(a) print('promedio', promedio, 'redondeado', round(promedio)) #otra solucion con un loop p = 0 for numero in pixel: p += numero p = p / len(pixel...
d41e2e3ac97dbcaa584d87c6cd2e12bb60066f04
unsortedtosorted/FastePrep
/Miscellaneous.py
653
4.0625
4
""" Given a two-dimensional array, if any element within is zero, make its whole row and column zero. """ def make_zeroes(matrix): # TODO: Write - Your - Code visited = set() def change(i,j): #make all row element zero for r in range(0,len(matrix)): matrix[r][j] = 0 visited.add((r,j)...
257ddb7373c0eb91bc107ef5e6e47cc429ec73b2
unsortedtosorted/FastePrep
/LinkedList/Add2Integers.py
919
3.6875
4
""" Given the head pointers of two linked lists where each linked list represents an integer number (each node is a digit), add them and return the resulting linked list At each step new node value = head1 + head2 + carry """ from LinkedList.linkedList import Node,generateList,printll #head1 = generateList([1,3,4...
04f3a32f5f6d42e4ac3e948d44c4234d1396ea3b
unsortedtosorted/FastePrep
/backtrack/print_all_braces.py
687
3.84375
4
""" Print all braces combinations for a given value 'n' so that they are balanced. Keep track of open and close brackets. if open brackets are less than n, add it and increament o by 1 if close brackets are less than open brackets, add it and increment c by 1 """ def print_all_braces(n): out = [] def dfs(...
3bf03b9465a285c5459f9461eae180bdbbb03ed3
unsortedtosorted/FastePrep
/Trees/inorder_iterative.py
613
3.953125
4
""" Write an inorder traversal of a binary tree iteratively. 1. check top of stack, if not none 2. keep adding left of curr to stack 3. if none: -- pop top (remove none) -- curr = pop (to print value) -- add curr.left tp stack Runtime : O(N) """ def inorder_iterative(root): result = "" ...
5947c58dd126e946c8168b6b34027d119004b84c
unsortedtosorted/FastePrep
/graphs/minspanningTree.py
3,668
3.953125
4
""" Find the minimum spanning tree of a connected, undirected graph with weighted edges. 1. start from a node, 2. visted the edge with least wieght to node not yet visited. """ import heapq from collections import defaultdict class vertex: def __init__(self, id, visited): self.id = id self.vi...
88f2f7683025b2fcbcc0006b279bce698743d10b
himanshu2801/leetcode_codes
/sort colors.py
912
4.15625
4
""" Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Follow up: Could you solve thi...
ca9e1be6d5c2e425d5389e58b9825cac1da61c23
himanshu2801/leetcode_codes
/504.Base 7.py
678
3.8125
4
""" Question... Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202" Example 2: Input: -7 Output: "-10" Solution... """ class Solution: def convertToBase7(self, n: int) -> str: if n>0: i=1 s=0 while(n!=0): r=n%7 ...
33546a15c86dd5bec1cc39d831b8519984f34642
himanshu2801/leetcode_codes
/1287. Element Appearing More Than 25% In Sorted Array.py
590
3.578125
4
""" Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time. Return that integer. Example 1: Input: arr = [1,2,2,6,6,6,6,7,10] Output: 6 Constraints: 1 <= arr.length <= 10^4 0 <= arr[i] <= 10^5 Accepted 33,754 Submissions 56,201 ""...
b06e84fbbfe4be1d8820db10c60f30367c1dc47f
himanshu2801/leetcode_codes
/22. Generate Parentheses.py
1,333
3.796875
4
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] Constraints: 1 <= n <= 8 """ class Solution: def generateParenthesis(self, n: in...
7abfe30e40444bbc67aa1a11c47fb5a75250f60b
himanshu2801/leetcode_codes
/permuatation II.py
1,024
3.875
4
""" Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Example 1: Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Constraints: 1 <= nums...
949d7c2c4bf292005d16dd8abb3571e7ea25c6d7
himanshu2801/leetcode_codes
/Largest Fibonacci Subsequence.py
961
4.09375
4
""" Given an array with positive number the task to find the largest subsequence from array that contain elements which are Fibonacci numbers. Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the arra...
b3743812986b4fd149f3d63c0a9c070bc9f3115a
himanshu2801/leetcode_codes
/9.Parindrome_number.py
614
4.09375
4
Question...Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome...
ce7146bbe917e8879ad33b6f7c35f116113aba9e
karimelgazar/OpenCV-in-Arabic-for-Beginners
/#17_extract_coins.py
1,750
3.546875
4
import cv2 import numpy as np img_path = "images/coins.jpg" image = cv2.imread(img_path) cv2.imshow("Original", image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #! changing the blur kernel size affects the detection #! like with >>> coins.webp blurred = cv2.GaussianBlur(gray, (15, 15), 0) edged = cv2.Canny(blu...
91b8edb9a2c55ba118e7607c80fef0642a59e798
karimelgazar/OpenCV-in-Arabic-for-Beginners
/#07_bitwise_operations.py
867
3.546875
4
import numpy as np import cv2 square = np.zeros((300, 300), dtype="uint8") color = 255 # ! Why I used only one integer instead of a tuple? cv2.rectangle(square, (25, 25), (275, 275), color, -1) cv2.imshow("Square", square) circle = np.zeros((300, 300), dtype="uint8") cv2.circle(circle, (150, 150), 150, 255, -1) cv2...
6830588fce08c32076390d3c092e948bb3308608
chancmg/practs
/python/count.py
103
3.96875
4
count=1 while count<5: print "count less than 5" count+=1 else: print "count not less than 5"
4a20ecf01fba31bc3e1579aa658c15c386c04ee5
chancmg/practs
/python/oops2.py
534
3.765625
4
class parent: parentattr=100 def __init__(self): print 'parent constructor' def parentmethod(self): print 'parent method' def setparentattr(self,a): parent.parentattr=a def getparentattr(self): print "Parent attr:",parent.parentattr class child(parent): def __init__(self): print "child...
472b23445389c3d0140109454bfc2d75c118ad37
chancmg/practs
/python/palin.py
133
3.84375
4
str=raw_input() strrev=reversed(str) if list(str)==list(strrev): print "palindrome" else: print "not a palindrome"
eb9c158ffc2f26ff3f9507eca8ed07e283d232b3
chancmg/practs
/python/fileop.py
484
3.75
4
try: file=open("FruitList.txt","r") lines=file.readlines() d={} linecount=0 for line in lines: if(linecount>0): token=line.split(" ") d[token[1].lower()]=token[2] linecount+=1 ch="y" while ch == 'y': str=raw_input("Enter the food name to be searched : ").lower() if str in d: ...
59ea7b4ac9d43bace75c06d21fe5044e62c9b544
YongJaeChung/algo_repo
/programmers/dp/triangle.py
1,126
3.515625
4
def solution(triangle): # 배열의 마지막에서 두번째 행부터 시작 for i in range(len(triangle)-2,-1,-1): print(i) # 행을 잘 가리키고 있는지 확인 # 삼각형 행의 각 배열을 순회하며 for j in range(len(triangle[i])): # 바로 아래의 열의 왼쪽,오른쪽 배열과 더하기 해본 후 if triangle[i][j]+triangle[i+1][j] > triangle[i][j]+triangl...
96ffd6f2d96e810840f4e8aab3bd3d5968f600ba
bitomann/classes
/pizza_joint.py
1,322
4.625
5
# 1. Create a Pizza type for representing pizzas in Python. Think about some basic # properties that would define a pizza's values; things like size, crust type, and # toppings would help. Define those in the __init__ method so each instance can # have its own specific values for those properties. class Pizza: d...
f565f8cd80799be0cb8fabfda75abf7705e58e8d
juan-restrepop/chessByDeMeGa
/curses_tutorial/playing_with_curses_tuto4.py
533
4
4
''' In this tutorial we see how to 'animate" the display. The corresponding youtube tutorial can be found at: https://www.youtube.com/watch?v=7bwK9tsdve4 ''' import curses import time screen = curses.initscr() height, width = screen.getmaxyx() message = "Let's play some chess!" for j in range(width...
3af8fa69dcef2ce28d8816b1ee4f478be15651d0
luiskelvin/EXERCICIOS
/exercicio_2.py
432
3.5625
4
#Criar uma agenda para manipular os dados: nome, e-mail, idade e cidade, #essa agenda terá opções para cadastrar, alterar, selecionar e excluir #contatos. Cada ação da agenda deverá estar em uma função. lista_agenda = [] def cadastrar(): linha_da_genda = [input("Nome Completo:"), input("E-mail:"), ...
e85f6b3194dda0f4a129407c6cf706ae4a6b604d
lunarchan/crawler
/python3.7/11重定向.py
643
3.703125
4
import urllib.request # #判断有没有重定向 # response = urllib.request.urlopen("http://www.baidu.cn") # print(response.geturl()=="http://www.baidu.cn") class RedirectHander(urllib.request.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers):#重302定向 res = urllib.request.HTTPRedirectHandler.ht...
78a41f8906daccdeadb7e27d1393e200565e82f4
marcou49/ejercicios-python
/buzz.py
720
3.84375
4
#coding:utf-8 lista = True intentos = 0 while lista == True: numero = input("Pon un numero del 1 al 20\n ") numero = int(numero) if numero > 1 and numero < 21 : #comprobamos que el numero está entre 1 y 20 lista = False else: if intentos < 1: print("Picha, te hemos dic...
3c2d0ba76f1cabe4fbc88244b0576c55318edd9a
paulusdevries/rock-paper-scissors
/dictionaries.py
568
3.828125
4
def print_dict(dictionary): for key,val in dictionary.items(): print(f'Ik ben {key}, en ik woon in {val}') def wpl_count(dictionary): wpls = list(dictionary.values()) for wpl in set(wpls): num = wpls.count(wpl) print(f'Er wonen {num} namen in {wpl}') naw = {} while Tru...
a059816268c633947d769c6d394af66b219c6709
satyatejachikatla/OS
/sqrtTill2ndDecimalAcc.py
341
3.640625
4
import sys n = 10 def binSearch(n): prev_mid = 0 low = 0 high = n mid = n/2 while (prev_mid*100) // 1 != (mid*100)//1: if mid * mid < n: low = mid high= high elif mid * mid > n: low = low high= mid else: return mid prev_mid = mid mid = (low+high)/2 return round(mid,2) print(binSearc...
1dc793bafe8e702fab8190882afef93196ebc2e5
C-MTY-TC1028-031-2113/tarea2-decisiones-XimenaCarvajall
/assignments/04Cuadrante/src/exercise.py
552
3.96875
4
def main(): grados = int(input("Dame los grados: ")) if grados > 0 and grados < 90: print("Cuadrante 1") elif grados > 90 and grados < 180: print("Cuadrante 2") elif grados > 180 and grados < 270: print("Cuadrante 3") elif grados > 270 and grados < 360: print("Cua...
be294142b4ddbcb7687bfd5d216f8b13f166f8e1
drawar/leetcode-coding-patterns
/two-pointers/intersection-of-two-arrays-ii.py
876
3.703125
4
# https://leetcode.com/problems/intersection-of-two-arrays-ii/ from typing import List class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() i, j, k = 0, 0, 0 while i < len(nums1) and j < len(nums2): if nums1[i] ...
fb3d59057e9657ccd5876d52d86d5a1e52e1e770
BalintHompot/DeepLearningUvA
/Assignment 1/code/train_mlp_numpy.py
5,845
3.90625
4
""" This module implements training and evaluation of a multi-layer perceptron in NumPy. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import os from mlp_numpy import M...
ce0e73f852265fc5b7db841160d29fd29efb58b5
BalintHompot/DeepLearningUvA
/Assignment 1/code/train_mlp_pytorch.py
6,909
3.5
4
""" This module implements training and etestuation of a multi-layer perceptron in PyTorch. You should fill in code into indicated sections. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.optim as optim from torch.autograd impo...