blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6a5a0e8ea213a5ae9d906aee96700b0c054296b0
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3987/codes/1712_2502.py
229
3.828125
4
from math import * m = int(input("termo geral:")) c = 0 d = 1 e = 0 aux = 1 while(c < m): e = e + (aux * (1/(d*(3**c)))) if(aux == 1): aux = -1 else: aux = 1 c = c + 1 d = d + 2 e = e * sqrt(12) print(round(e, 8))
a17fe6619f2eec9fecd90b1e2d46a2433eba629a
alsheuski/python-project-lvl1
/brain_games/cli.py
227
3.515625
4
"""CLI module.""" import prompt def welcome_user(): """Ask a name of user and greet them.""" name = prompt.string('May I have your name? ') print('Hello, {name}!'.format(name=name)) # noqa:WPS421 return name
e9e0a48dd459f34b911617479213664d792ab72a
jorgepdsML/CLASE_PYTHONTEC
/CLASE1/codigo_python/listas2.py
360
4.0625
4
""" USO DE LA LISTA Y SUS METODOS """ #lista1 lista1=[10,20,30] N=len(lista1) print("ANTES DEL METODO POP ",lista1) #lista2 lista2=[5,2,3,100] #concatenar listas print(lista1+lista2) #sacar un elemento de la ultima posición de la lista lista1 val=lista1.pop() print("ELEMENTO QUE SE EXTRAIDO ES: ",val) pri...
21079101ad64cba17156e6b61be21816270a8266
huyngopt1994/python-Algorithm
/green/green-05-array/flowers.py
626
3.96875
4
# Verify requirement: # input a list of number(height of flowers) # Output : find total energy = sum( difference between the shorest flower and another flowers) # Solution : # 1./ find the shortest and the sum the height of flowers # 2./ calculate the the energy = sum the height of flowers - (shortest* the number of fl...
b25da5694cafd4914a9cce6ed151e8011f5d5479
yksa/automate_the_boring_stuff_with_python
/example.py
286
4
4
print('How many cats do you have?') numCats = input() try: if int(numCats) >= 4: print('That is a lot cats.') elif int(numCats) < 0: print('You cannot enter a negative number.') else: print('That is not that many cats.') except ValueError: print('You did not enter a number.')
9084e9a982279f7ec6a90f61eec8c6e7dd5cfe4a
prabin544/data-structures-and-algorithms
/python/tests/test_linked_list.py
3,279
3.546875
4
import pytest from code_challenges.linked_list.linked_list import LinkedList, Node # Code Challenge 06 Tests # Can successfully create a node # @pytest.mark.skip("pending") def test_a(): node1 = Node("apple") actual = node1.value expected = "apple" assert actual == expected assert node1.next == Non...
997e04563f3148c5526b3a87cbafe1841cf41e20
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/gigasecond/7c4d246575e846329bd1f61460ea7d59.py
706
3.625
4
""" messed around with date object for a bit, was looking for to/from seconds since the epoch, but couldn't find it. I was going to write a function to add the days, and then adjust for years, and might do so for a second iteration of this particular problem, but then I found the to/from ordinal ...
8c92cf1617decbeffcea62934521557b54264f3b
ssinad/quera-solutions
/3539.py
175
3.859375
4
def sum_digit(num): s = 0 while num > 0: s += num % 10 num //= 10 return s n = int(input()) while not (0 <= n <= 9): n = sum_digit(n) print(n)
21db15bfb4ef16b2e0cda44b531723d1b5ebd00f
AWT-01-API/katas
/src/Angelica/kata_11_6/reverse.py
486
4.09375
4
# Reverse every other word in a given string, then return it. # Don't forget to include the spaces! def reverse_text(text): a = "" for i in range(len(text) - 1, 0, -1): a += text[i] a += text[0] return a def reverse_alternate(string): reverse = "" words = string.split(" ") for x ...
a9e4aba69e1c8d00f1c09026f1a25218ab11548b
coci/sliding-puzzle
/sliding.py
4,302
3.875
4
import random board_game = ["#",1,2,3,4,5,6,7,8," "] class Board: def __init__(self,board): self.board = board def shuffle_board(self): random.shuffle(self.board) hashtag = self.board.index("#") if not hashtag == 0: self.board[hashtag],self.board[0] = sel...
bcf1ecbc4cde9c1c3385f83d1072def2b47be858
antonkomp/new-tms-21
/HW_14/task14_01.py
1,236
3.65625
4
import argparse from datetime import datetime from time import sleep def create_args(): parser = argparse.ArgumentParser() parser.add_argument('-n', '--name', required=True) parser.add_argument('-l', '--lastname', required=True) parser.add_argument('-o', '--hours', type=int, required=True) parser....
fdaf926aa6d2e60ceb4971044315bda0875a227f
chetanpv/python-snippets
/LevelThree/word_freq.py
659
4.21875
4
# Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. # Suppose the following input is supplied to the program: # New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. # Then, the output should be: # 2:2...
d01a15410f19de8791ef8366f8e13356b5de63dc
baiden00/implementingAlgos
/SortingAlgos/selectionsort.py
397
4.03125
4
def selection_sort(array): for i in range(0, len(array)): min_idx = i for j in range(i+1, len(array)): if array[j]<array[min_idx]: min_idx = j array[i], array[min_idx] = array[min_idx], array[i] array = [4, 22, 41, 40, 27, 30, 36, 16, 42, 37, 14, 39, 3, 6, 34, ...
be327a0b18564afc312ec2639f3f10e6b9026d17
rlorenzini/python-notes-
/pythonlesson5.py
2,236
4.28125
4
##OBJECTS AND CLASSES #CLASS = BLUEPRINT #CLASSES have hierarchies #CAR would be the SUPERCLASS #HONDA ACCORD would be the SUBCLASS #make, model, color, year would be the PROPERTIES of the CLASS #Car (Class) #- color #- make #- model #- year #- price #- wheels #- doors #Class can have functions #methods: # ignitio...
34686d23167f900e209561cda811d4f5f64ec91c
ajheilman/A-game-of-craps
/main.py
1,100
3.859375
4
from player import Player def playOneGame(): #Plays a single game and prints the results player = Player() youWin = player.play() print player if youWin: print "You win!\n" else: print "You lose!\n" def playManyGames(): #Plays a number of games and prints the statistics ...
93f23fed867d42397a4b7682e52c9d854e52b201
Raptors65/python-scripts
/MyScripts/User Interface/Scrabble Helper/scrabble_helper.py
1,313
3.890625
4
import itertools import ui from urllib.request import urlopen # Opening the file with the words. with open("scrabble_words.txt") as words_file: # Storing a set of English words. words = {word.rstrip() for word in words_file.readlines()} # Run when button to find valid words is pressed. def find_words(sender): '@ty...
e953700fe7f8606497981fa7c218b1dfc94128f7
doddydad/python-for-the-absolute-beginner-3rd-ed
/Chapter 7/Trivia.py
5,585
3.734375
4
# -*- coding: utf-8 -*- """ Created on Fri May 29 13:59:08 2020 @author: Andrew """ #Trivia thingy #imports import sys, pickle #Definitions #Grabs the file, exception built in def open_file(file_name, mode): """opens file, exceptions built in""" try: the_file = open(file_name, mode) except IO...
5e55a12291abc12daef03ef30e150190f9df5477
Hu-Wenchao/leetcode
/prob115_distinct_subsequences.py
870
3.796875
4
""" Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subse...
2180d58428e5b5b6e13344151511dcd47b1b9546
byAbaddon/Basics-Course-Python-November-2020
/3.0 Conditional Statements Advanced - Lab/03- Animal Type.py
173
3.984375
4
animal = input() list_reptile = ['snake', 'tortoise', 'crocodile'] print('reptile' if animal in list_reptile else 'mammal' if animal == 'dog' else 'unknown') # dog # snake
433568e59ea51161226bb22e3271cf6e8e10abc7
DanteASC4/cs_sem_1_hw
/hw46_walk_100.py
239
3.765625
4
#Name: Dante Rivera #Date: October 2018 #A turtle that walks randomly for 100 steps import random import turtle bob = turtle.Turtle() bob.speed('fastest') for i in range(100): bob.right(random.randrange(0, 359, 1)) bob.forward(10)
04a8219d049d95aa9183a744449d59586b91af7d
GeHaha/AboutPython
/PythonDaily/PythonLearing/demo/def函数.py
3,660
3.921875
4
# -*- coding: utf-8 -*- """ Created on Tue May 29 20:47:19 2018 @author: Administrator """ """ def display_message(): print("本章学习的是函数的定义") """ """ def favorite_book(bookname): print("One of my favorite book is "+bookname.title()+".") """ """ def describe_pet(animal_type, pet_name): print("\nI have a...
8a1236e2233f4c41b2767f4feaf89c77f8f3c08b
JpryHyrd/python_2.0
/Lesson_3/1.py
493
3.609375
4
# 1. В диапазоне натуральных чисел от 2 до 99 определить, # сколько из них кратны каждому из чисел в диапазоне от 2 до 9. a = 2 b = 0 list = [] while True: for i in range(8): print("Числа, кратные " + str(a) + ": ", end = "") for g in range(100): if g < 100 and g > 1 and g % a == 0: ...
1ef7d0d4379199fd1b773e9f2d0d0f3f0ce11c80
Saradippity26/Beginning-Python
/words.py
2,265
3.921875
4
""" get a file from the web, https://icarus.cs.weber.edu/~hvalle/hafb/words.txt Task: 1 Count the number of words in document """ from urllib.request import urlopen #package url #file = "https://icarus.cs.weber.edu/~hvalle/hafb/words.txt" from functions import even_or_odd #with urlopen(file) as story: #give nickname ...
8eda67f2a0313efb0a0d9a3d58ba64b9d2cf3e11
4roses41/COM404
/1.basics/5-functions/8-function-calls/bot.py
1,221
3.8125
4
def DisplayInBox(CrypWord): print("*" * (len(CrypWord) + 10)) print("** ", CrypWord, " **") print("*" * (len(CrypWord) + 10)) def DisplayLowerCase(CrypWord): answer = (CrypWord.lower()) return answer def DisplayUpperCase(CrypWord): answer = (CrypWord.upper()) return answer def Displ...
254b169fbfa4331f1cc64a699fa5511de668ce40
ChrisMichael11/ds_from_scratch
/simple_linear_regression.py
5,520
3.59375
4
from __future__ import division from collections import Counter, defaultdict from linear_algebra import vector_subtract from statistics import mean, correlation, standard_deviation, de_mean from gradient_descent import minimize_stochastic import math, random def predict(alpha, beta, x_i): """ Predict y_i = Be...
d7bb989be72a416e4ade3de87696f86e4485701e
Ran-oops/python
/3/01类和对象/python核心算法-代码/19/simpledialog.py
1,074
3.90625
4
#简单对话弹窗 import tkinter import tkinter.simpledialog root = tkinter.Tk() root.minsize(300,300) #添加按钮 (获取用户输入字符串的弹窗) def dialog(): result = tkinter.simpledialog.askstring(title = '请输入用户名',prompt = '用户名必须为中文',initialvalue = '匿名用户') print('用户名:',result) btn1 = tkinter.Button(root,text = '字符串弹窗',command = dialog...
af6c31bee64b17dbdae60f2ec3ae915c35f36a92
aayala15/coursera-algorithms
/jobs.py
784
3.609375
4
with open("jobs.txt") as file: number_of_jobs = int(file.readline()) jobs = {} for i in range(number_of_jobs): jobs[i] = [int(j) for j in str.split(file.readline())] def greedyscheduler(jobs, type="ratio"): if type == "ratio": score = {key:[-(value[0]/value[1]), -value[0]] for key, value in jobs.items()} else...
4527d18b6c35b5aa32e043f4172d5c344fac6619
ErmirioABonfim/Exercicos-Python
/Exercios Em Python/ex027.py
167
3.8125
4
nome = str(input('Informe seu nome')).split() print(' Seu primeiro nome é {}'.format(nome[0])) print(' seu último nome é {}'.format(nome[-1])) print('Tanks a Lot')
962289cb3940dd5a6d1e69bed229bf2355146c40
misterpeddy/weebo
/stop_example.py
373
4
4
from nltk.corpus import * from nltk.tokenize import word_tokenize sentence = "This is an example of a dumb sentence with no real actual stuff" words = word_tokenize(sentence) stop_words = set(stopwords.words("english")) print(stop_words) print(type(stop_words)) #stop_words = set(stop_words) print(stop_words) [prin...
e7c52299cc97f2f0a5152e0d304f041260f72809
Akashdeepsingh1/project
/2020/groupAnagram.py
870
3.515625
4
class classy: def __init__(self): self.refresh_list = set() def anagram(self, word, index,s): if len(word) == index and ''.join(word) in s: self.temp_list.append(''.join(word)) self.visited.append(''.join(word)) print(word) for i in range(index, len(...
b89323170bfc8c0ee6b53f50209a6b6d8c365e48
Zhaokun1997/UNSW_myDemo
/COMP9021/COMP9021_quiz_7/quiz_7.py
3,551
3.96875
4
# COMP9021 19T3 - Rachid Hamadi # Quiz 7 *** Due Thursday Week 9 # # Randomly generates a grid of 0s and 1s and determines # the maximum number of "spikes" in a shape. # A shape is made up of 1s connected horizontally or vertically (it can contain holes). # A "spike" in a shape is a 1 that is part of this shape and "st...
084b68c7bbee6214a008f69e0babd20eab02a257
weichuntsai0217/leetcode
/266-Palindrome_Permutation.py
1,081
4.1875
4
""" * Ref: No * Key points: * Explain your thought: A string which can can permute palindrome must satisfy - if the length of this string is even, then all frequencies of letters in this string must be even - if the length of this string is odd, then only one letter's frequency is odd, others' frequenc...
53310c6d142d2990cfae0f6a5f57996be51b6a5d
changshun/A_Byte_of_Python
/Functions/func_param.py
237
3.875
4
__author__ = 'shihchosen' def printMax(a, b): if a > b: print('The maximum is', a) elif a == b: print(a, 'is equal to', b) else: print('The maximum is', b) printMax(4, 3) x = 2; y = 7 printMax(x, y)
47baa3558dd4c517a9bd1381ad56e9fbcfe15891
VanillaGorilla0713/projects
/familyNamesListApp.py
318
3.984375
4
familyNames = [] while True: print("Enter the name of family member " + str(len(familyNames)+1) + " (Or press enter to stop.):") name = input() if name == '': break familyNames = familyNames + [name] print("Your family member names are:") for name in familyNames: print(' '+name)
51286c93a6b5cddb6a20489fa231d83f6ff5d779
sombriyo/Leetcode-_questions
/sliding_window/Minimum Size Subarray Sum.py
740
3.984375
4
''' Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. ''' def two_pointer(nums, s): p1 = 0 p2 = 0 ...
9d74304b02c8b6f69b48cd433848c6b02176e8d1
pedrob14/PythonCurso
/CursoemVideo/PythonExercicios/ex006.py
246
4.125
4
# Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada from math import sqrt n = float(input('Digite um número: ')) print("Valor {}: \ndobro {} \ntriplo {} \nRaiz Quadrada {:.2f}".format(n, n * 2, n * 3, sqrt(n)))
4a54d83cc2b70b1c0258fd067d0e433ddf5852a0
ronbenbenishti/Starting-up
/Encrypt with key/script3.py
1,305
4.1875
4
#This is simple script for encoding and decoding text by special key key=input("Enter key: ") k="" for x in key: k=str(k)+str(ord(x)) key=int(k) separate=chr(0) def encode(): file = open("hiden.txt","w") enlist=[] text=input("enter text to encrypt:\n") for x in text: x= ord(x)+ke...
5bf40ec11c82489da71209bfa7c6b26c45812189
prathamesh-collab/python_tutorials-pratham-
/csv_module.py/practic_CSV_module.py/gym_read1.py
777
4.1875
4
#!/usr/bin/env python3 # here i write script for read my gym_Write1 file by using some csv reader method and etc import csv #csv file name filename ='_gym_write1.csv' #initilizing the titles and rows list fields = [] rows = [] #reading csv file with open(filename , 'r') as csvfile: csvreader = csv.reader(...
d50616dbb613d40fa281987fd5d5686cc5d17a1b
ibews/NSS
/uebung6/aufgabe5.py
1,103
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 26 12:56:36 2013 @author: ibews """ # Modify the grammar # # S -> NP VP # PP -> P NP # NP -> Det N | Det N PP | 'I' # VP -> V NP | VP PP # Det -> 'an' | 'my' # N -> 'elephant' | 'pajamas' # V -> 'shot' # P -> 'in' # # (cf. lecture Grammatiken und Parsing in NLTK (sli...
74a6c2170b891cf67dd9917bd7fa534a50801399
ahmadajal/leet_code
/maximum_xor/max_xor.py
359
3.515625
4
from typing import List class Solution: def findMaximumXOR(self, nums: List[int]) -> int: ans = 0 for i in range(32)[::-1]: ans <<= 1 prefixes = {num >> i for num in nums} ans += any(ans^1 ^ p in prefixes for p in prefixes) return ans s = Solution() prin...
0fd84928bcba9a7542af1f00ef366a3a143eba0b
neelima513/python101
/ex_factorial.py
530
4.25
4
#factorial '''the factorial number of 7 is: 5040''' def factorial(n): factorial = 1 if n<0: print("factorial number doesnot exits") elif n==0: print("the factorial of 0 is 1") else: for i in range(factorial,n+1): factorial = factorial * i print("the factorial number of",n,"is:",factorial) n = 7 factoria...
2a9bfd8e00edc448781718b8a70a6e7e4ae8d318
gcon97/cs50finalproject
/sqlqueries.py
1,487
3.859375
4
import sqlite3 def insertUser(username, hash): try: sqliteConnection = sqlite3.connect('trending.db') cursor = sqliteConnection.cursor() sqlite_insert_with_param = """INSERT INTO 'users' ('username', 'hash') VALUES (?, ?);""" d...
22df342f46f40c94187dbcfff6500efdbe5c0c97
narendra1100/python_projects
/decorators.py
363
3.546875
4
r=[2,5,6,88,4,1] g=r[0] for i in r: if g<i: g=i print(g) ''' def num(): return 7 def decorate(fun): def inner(): a=fun+7 return a return inner f=decorate(num) print(f) def nari(): for i in range(1,11): yield i g=nari() print("return values"...
b04dc254b1cfef4d63765fa91444257849bccbb0
joshterrell805-historic/EClass
/testing/implementation/unit/Presentation/QuestionListTest.py
2,975
3.8125
4
import unittest import sys sys.path.insert(0, '../../../implementation/source/python/model/') from Presentation.QuestionList import QuestionList from Person.Question import Question class QuestionListTest(unittest.TestCase): """ Class QuestionListTest is the companion testing class for class Presentation. It...
9b047b95046cac88faf5a4d41946b59704f95829
JerryHu1994/CS838-Data-Science-Project
/Stage-1-IE-from-natural-text/data/extract_name.py
799
3.53125
4
""" Univertity of Wisconsin-Madison Yaqi Zhang """ import sys import os import re if __name__ == "__main__": '''extract names from taged files in a folder''' if len(sys.argv) != 3: print("Usage: >> python " + sys.argv[0] + " <input_folder> <output_file>") sys.exit(1) folder_name = sys.argv...
a9498a9675477a69bba75b8ebd9736bbf9dd3dcd
df-danfox/python-challenge
/PyBank/main.py
2,469
3.90625
4
#import modules import os import csv #set file path csvpath = os.path.join('..','budget_data.csv') #read csv file with open(csvpath, 'r') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter = ',') # Ignore the header row header...
84c0c20f397d6e1238e8a7b84bc7ad640e4f419c
jonathan-JIPSlok/Aprendendo_Pandas
/sort_values.py
610
3.734375
4
import pandas as pd import openpyxl df = pd.read_excel("Arquivo.xlsx", engine="openpyxl") print(df.sort_values("Nome")) #Ordena a tabela port ordem alfabetica ou numerica print() print(df.sort_values("Idade")) print() df.sort_values("Idade", inplace=True)#Modifica a tabela para ordenado. print(df) print() print(df....
f1998f12a92cca8e9ca7a82edc34f026bd23adc9
tjatn304905/algorithm
/baekjoon/8958_OX퀴즈/sol1.py
648
3.53125
4
# https://www.acmicpc.net/problem/8958 # 테스트 케이스의 개수를 입력받는다. num = int(input()) # 그 개수만큼 테스트 케이스를 입력받는다. for i in range(num): test_case = input() count = 0 score = 0 # 테스트 케이스의 길이만큼 순회하면서 for i in range(len(test_case)): # 문자열이 O 라면 if test_case[i] == 'O': # count 에 1을 더해...
a679b4bd53f98489295a022280f4e5607af678d6
rao003/StartProgramming
/PYTHON/einstieg_in_python/Beispiele/zahl_umwandeln.py
452
3.890625
4
# Positive Zahl x = 12/7 print("x:", x) # Rundung und Konvertierung rx = round(x,3) print("x gerundet auf drei Stellen: ", rx) rx = round(x) print("x gerundet auf null Stellen: ", rx) ix = int(x) print("int(x):", ix) print() # Negative Zahl x = -12/7 print("x:", x) # Rundung und Konvertierung rx = round(x,3) print("...
c79b00ac6682d64a10d676ce4670aa9ed0e029c5
MrBrezina/python-workshop
/Basics/4-3-functions-reverseDict.py
711
3.9375
4
# Define a function that revereses # a language dictionary # expect that all values can work as # keys and that they are unique # header: # def reverseDict(dic): # returns dictionary # dictionary cs_en = { "ahoj":"heya", "nashledanou":"goodbye", "na zdravi":"cheers", "jedna":"one", "dva":"two", "tri":"three" } ...
6274518b1913ba8c5f3e4e42bfa65619d09b8e06
markTTTT/OSS
/002_Python/Week2_SimplePrograms/isIn.py
624
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 23 23:42:06 2017 @author: markt """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' lowC = 0 highC = len(aStr) testC = int((l...
afd463bdf5bc20b7c58666231b62773b8c45c1d7
Gscsd8527/python
/python/set/set_1.py
233
4
4
tan={'tt','tt','dd','gg','vv','bb'} print(tan) # 推导 # number=[x*x for x in range(1,10)] # print(number) # names=['tff','tfjyf','tfyhyf','tfjjf','tfyyf'] # upperlist=[x.upper() for x in names if len(x)>3] # print(upperlist)
104747edede3d7d69aeb8f193fd6c4ee8c979c03
Bhagya9999/CSCI-B551-Artificial-Intelligence-
/Assignment-1/part-2/route.py
15,486
3.859375
4
#!/usr/bin/env python import string from collections import defaultdict from Queue import PriorityQueue from math import radians, cos, sin, asin, sqrt import sys # All the heuristic logics, and ways of handling the data inconsistency explained below. # Assuming the end_city given as input will have lat, lon values as ...
45393ca9ffdb4d17a2dd5ab96c79ce7ed5b9171c
PiusLucky/python-classes
/overriding methods in python.py
1,218
3.953125
4
# method override - Two(2) classes scenario class parent: def method1(self): print('Iam a Viking, a Legend meant to be in Valhalla') class child1(parent): def method1(self): print('Iam Bjorn, the first child of Ragnar Lothbrok') super().method1() # Add method1 from the super-class[pare...
941deca2ddb7410b585479dd501c38f1565aea83
namratavalecha/Algorithms
/quick_sort.py
715
3.859375
4
def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i+=1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return(i+1) def quick_sort(arr, low, high): if low<high: pi = partition(arr, low, high) quick_sort(arr, low, pi-1...
7eec08ad7cd5da6d40865f595af5d002969d136f
tonitonishier/AlgorithmSolution
/SwordToOffer/SwordToOffer-PythonSolution/19_printMatrix.py
1,593
3.90625
4
# 19. 顺时针打印矩阵 # 题目描述 # 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. # -*- coding:utf-8 -*- class Solution: # matrix类型为二维列表,需要返回列表 def printMatrix(self, matrix): # write code here result = [] w...
af880633ed2716821d332b642a9f4701fe4ce25f
AIFFEL-coma-team01/Sanghyo
/chapter_8/21_Merge_Two_Sorted_Lists.py
1,140
4.0625
4
''' 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists. Example 1: Input : l1 = [1,2,4], l2 = [1,3,4] Output : [1,1,2,3,4,4] Example 2: Input : l1 = [], l2 = [] ...
86b5a4fe00659e0524582801b56aa8016c7a9dc3
junzhougriffith/test
/PyLab/W1B5.py
2,372
4.1875
4
##//////////////////////////// PROBLEM STATEMENT ////////////////////////////// ## A website requires the users to input username and password to // ## register. Write a program to check the validity of password input by // ## users. Following are the criteria for checking the password: 1. At least // ...
c1402208921b4f5ac60a8a761181b3e25b863115
emanoelmlsilva/ExePythonBR
/Exe.Lista/EL.07.py
260
3.78125
4
lista = list(range(5)) v = [] soma = 0 mult = 1 for i in range(len(lista)): num = int(input('Digite um valor: ')) v.append(num) soma += num mult *= num print('números {}'.format(v)) print('soma: {}'.format(soma)) print('Multiplicação: {}'.format(mult))
feb9db64d5b5b059ef7bb77179f31017a6f339e2
Aasthaengg/IBMdataset
/Python_codes/p03476/s792762452.py
685
3.59375
4
from itertools import accumulate def primes(n): is_prime = [True] * (n + 1) is_prime[0] = False is_prime[1] = False for i in range(2, int(n**0.5) + 1): if not is_prime[i]: continue for j in range(i * 2, n + 1, i): is_prime[j] = False return [i for i in range(...
fd1c62d9afaf4f51d4236e0439fd99a696596654
Beebruna/Python
/CursoemVideoPython/Desafio 3.py
299
3.984375
4
''' Desafio 3 Crie um script Python que leia dois números e tente mostrar a soma entre eles. Exemplo: Primeiro número 6 Segundo númeo 3 A soma é 63 ''' print('======== Desafio 3 ===========') n1 = int(input('Primeiro número ')) n2 = int(input('Segundo número ')) print('A soma é',n1 + n2)
e1cff7730d97badc96be53891f01238d56202922
joshRpowell/DataAnalyst
/P2/problem_sets/ps4_visualizing_data.py
2,774
4.5625
5
from pandas import * from ggplot import * import datetime def weekdays(dates): for date in dates: # return date.weekday() return date.strftime('%A') def plot_weather_data(turnstile_weather): ''' You are passed in a dataframe called turnstile_weather. Use turnstile_weather along with gg...
3a3f05f487d1085fe64d0b3bfee5002bcac56a5b
demeth0/REPO_CS_P2024
/Python Project/TD/Archive/Gabin/fibonacci.py
323
3.6875
4
#Ce programme est juste mais surement un peu compliqué à comprendre #Les noms de variables ne doivent pas être très claires var_1=0 var_2=1 rang_Max=int(input("Donner le rang : ")) print(var_1) print(var_2) for n in range(rang_Max-1) : resultat=var_1+var_2 print(resultat) var_1=var_2 var_2=resultat
b8fb3a40a24aca3403b17138c1366f172699b0e3
reneafranco/Course
/tkinter/07-botones.py
2,129
3.671875
4
from tkinter import * ventana = Tk() ventana.title("Encabezado de Formulario") ventana.geometry("700x400") #Texto encabezado encabezado = Label(ventana, text="Formularios con Tkinter") encabezado.config( fg="white", bg="darkgray", font=("Open Sans", 18), ...
8f992050cce5967fae55a1dec400e847ff746843
brunocorbetta/exerciciocursoemvideo
/ex025.py
87
3.828125
4
name = str(input('Qual é o seu nome?')) print('Seu nome tem "silva"', 'silva' in name)
64f082724da2b3b8f1166659d775dea182bf5c12
Pure75/TP3-THLR-correction
/tp3_cache.py
4,778
3.65625
4
from display_automaton import export_automaton # Non-deterministic finite automaton class NFA: def __init__(self, all_states, initial_states, final_states, alphabet, edges): # States: a set of integers self.all_states = set(all_states) # The alphabet: a set of strings ...
76451d511e05b673b4eaabfd5d2acb2a5237a30c
Marcus893/maximum-robot-euclidean-distance
/main.py
3,598
3.90625
4
# open and read the file, every line is an array element with open("input.txt", "r") as ins: array = [] for line in ins: array.append(line.split(' ')) # get the road blocks' indexes to be a separate array. blocks = array[1:11] # use two dictionaries to store x-axis and y-axis pairs blockx, blocky = {}...
d32c7cecae18c2b07663a3faba7d433ef8471601
intellivoid/CoffeeHousePy
/deps/scikit-image/doc/examples/segmentation/plot_marked_watershed.py
1,965
3.84375
4
""" =============================== Markers for watershed transform =============================== The watershed is a classical algorithm used for **segmentation**, that is, for separating different objects in an image. Here a marker image is built from the region of low gradient inside the image. In a grad...
77fa17a4a8d174743876dd4f08aeef9418618c0a
edu-fr/checkers-AI
/checkers/game.py
2,882
3.546875
4
import pygame from .AI import check_if_possible_moves from .constants import RED, WHITE, BLUE, SQUARE_SIZE from checkers.board import Board class Game: def __init__(self, win): self._init() self.win = win def update(self): self.board.draw(self.win) self.draw_valid_moves(self....
91427966ae78cd5ac5321c21c4e34979b9b27a70
siddheshmhatre/Algorithms
/Data_Structures/hashtable.py
908
3.734375
4
import random class HashTable(object): def __init__(self): self.size = 10 self.table = [[] for x in range(self.size)] self.data_size = 0 def hashfunction(self,x): return x % self.size def insert_data(self,idx,ele): self.table[idx].append(ele) def insert(self,data): self.data_size += len(data) if se...
6f50d05bc75666e6b6ec63a6b7c57821f7513019
Letoile/project-euler
/problem-20.py
1,283
4.0625
4
# -*- coding: utf-8 -*- """ Factorial digit sum n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! --------------------- Сумма цифр факториала n!...
d67de743e67f54cd2ae5ca5437c39eb1ce82a3d3
KongChan1988/51CTO-Treasure
/Python_Study/第三模块学习/面向对象/公有属性.py
2,099
3.8125
4
#-*- Coding:utf-8 -*- # Author: D.Gray '''' 公有属性: 1、类里所有对象都能访问的属性 2、在类里直接定义的属性 3、类内部的函数方法都是公有属性 r1 = Role('Alex', 'police', 'AK47') 这些只是r1这个对象的成员属性并不是Role类的公有属性 ''' class Role(object): nationality = 'JP' #定义一个公有属性,r1和r2实例都能共享(相同)的一个属性 def __init__(self, name, role, weapon, life_value=100, money=15000)...
6490bfbbd51278223076db152188dbb6ed342758
fabmedeiros/ciphers
/ciphers/railfence.py
1,976
3.671875
4
# -*- coding: utf-8 -*- from .cipher import Cipher """ implementacao da cifra Railfence """ class Railfence(Cipher): ''' Cifra railfence ''' def gen_railfence(self, tam, key): ''' Retorna um lista de inteiros com a posicao da linha que o caracter do texto ira ocupar, variando de 0 ate k...
8a3e87ff005bce48dbda557c69dcbf25c57e3f1a
maya1amyx/Scratch
/Tillie - woohoo.py
63
3.59375
4
num1=2 num2=7 print(num1+num2) print("can we take a fat nap")
672f64a0f8ad5e033887fd735aa90f61d98817de
Balakumar5599/Intern-s_assignmentTW
/preetha_assignment/validate_pan_num.py
210
3.953125
4
import re def validate_pan_num(num): if re.match(r'^[A-Z]{5}[0-9]{4}[A-Z]$',num): return True else: return False num=input("Enter the PAN number: ") print(validate_pan_num(num))
0c3b77a21f3f509c3d6cff5ae689b0227bdefe5b
peterkabai/python
/algorithm_problems/helpers/min_span_tree.py
2,751
3.53125
4
def count_v(edges): seen = [] v = 0 for edge in edges: if edge[0][0] not in seen: seen.append(edge[0][0]) v += 1 if edge[0][1] not in seen: seen.append(edge[0][1]) v += 1 return v def edges_to_dict(edges, directed=True): graph = {} ...
c3af846fac309a4b1810e3c50323d74ec3292ccc
abhishekpawar96/Multiplayer.RPSLS
/button.py
869
3.609375
4
import pygame from colors import WHITE_DR from font import create_font class Button: def __init__(self, text, x, y, color): self.text = text self.x = x self.y = y self.color = color self.width = 110 self.height = 60 def draw(self, win): pygame.draw.rec...
f5a022dc5494a0deaed1ceee10a3fbe1c8688811
KevinZM/Python
/Programs/Sort/SortClass.py
2,430
4.1875
4
# -*- coding:utf-8 -*- class SortClass(object): def __init__(self): pass #冒泡排序,列表中数据两两对比,对比一次之后,最大值被排到最后面,因此下次再排序就可以不排最后一个,效率比较高 def bubble_sort(self, list): length = len(list) while length > 0: for j in range(length-1): if list[j] > list[j+1]: ...
b1d596d754c4a8f62df78e065e08cc249aca6d66
aaroncymor/coding-bat-python-exercises
/Warmup-2/string_match.py
414
3.953125
4
""" Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. """ def string_match(a,b): counter = 0 for i in range(len(a)): if len(a[i:i...
22ac4a3ccdaa3e9f1a5a26a62df5e48e19fd9e25
alex-radchenko-github/codewars-and-leetcode
/leetcode/15. 3Sum.py
1,244
3.59375
4
import itertools def twoSum(target, nums): rez1 = [] rez = {} print(nums) for i, num in enumerate(nums): n = -target - num if n not in rez: rez[num] = i else: rez1.append([rez[n], i, target]) return rez1, def threeSum(nums): rez = [] nums ...
273f561ef07f50e6deef9d3cf850e1fae3aea494
LewisBray/ProjectEuler
/Problems 1-10/Euler9.py
722
3.6875
4
def triangles(max_side_length): for a in range(1, max_side_length + 1): for b in range(a + 1, max_side_length + 1): for c in range(b + 1, max_side_length + 1): yield (a, b, c) def right_triangles(max_side_length): for triangle in triangles(max_side_length): if triang...
a2a8cc9be7e214136b0056b59b88d912675ba314
Dnlhuang/products
/products.py
2,273
3.890625
4
# 作業系統模組(第五步驟) import os # operating system,標準函式庫中 # path 路徑; isfile 檢查檔案在不在 def read_file(filename): products = [] #先產生空清單 with open(filename, 'r', encoding = 'utf-8') as f: for line in f: if '商品,價格' in line: continue # continue跟break一樣只能寫在迴圈(第5~11行)裡。 continue就是跳到下一迴的意思 ...
3e79e5911348c4460107d8cb986471115d98f804
williamd1k0/ascii_art
/ascii_art/picture.py
2,574
3.703125
4
from PIL import Image, ImageDraw class ASCIIPicture: def __init__(self, text, background_color='white'): """ Class for saving and displaying ASCII art. Automatically checks if the text is in color. Background can be hex, rgb, or html color name. :param text: ASCII text :p...
9bddf1aba3a4f31048b44b59f28f11c09289a3d0
taranumjamadar/basic_concepts-of-python
/fun_withNwithoutargs.py
177
3.8125
4
#without argument def prompt(): name = input("Enter your name:") print('Hello',name) prompt() #with argument def prompt(n): print('Hello',n) prompt('tanu')
f0ccf86b5b8378166858bab4ef38d686b6654294
acay08/nguyenminhque-fundamental-c4e16
/section4/Homework/correct_name.py
154
3.9375
4
name = input('Your full name: ') while ' ' in name: name = name.replace(' ',' ') name = name.lower().strip().title() print('Updated name:',name)
0dd19b61bf1af8595c2822cbbd16ccf93926405c
ambrosy-eric/100-days-python
/beginner/day-7/main.py
1,271
4.09375
4
from art import stages, logo from words import word_list from utils import chose_word, check_if_completed, is_guessed, update_board, check_guess def main(): print(logo) lives = 6 generate_hangman = chose_word(word_list) chosen_word = generate_hangman[0] board = generate_hangman[1] print(" ".joi...
d1ceb6a29cdec72005a4bf239d03f845111807f8
lijiayu0725/Leetcode-Python
/234.palindrome-linked-list.py
1,258
3.828125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: if head is None or head.next is None: return True slow = head fast = head.next wh...
443b390808b6823cfad26b6b0d36598870865035
lulumon/ApartmentUnitApp
/client.py
7,049
3.640625
4
#Import Modules import apartment import apartment_db import tenant import tenant_database #setup apartment database from file aptDB = apartment_db.Apartment_db() aptDB.loadApartments('apts.txt') tenantDB = tenant_database.Tenant_db() #clean-up def float_input(prompt): while True: try: parsed =...
8479d0dd433c5cb41540c29e5b25b20cb50e68cd
SundaySSSSS/my_note
/Knowledge/Python/GUI/_v_attachments/1519179139_22401/entry_advance.py
1,302
3.796875
4
from tkinter import * root = Tk() #用表格的方式布局控件 Label(root, text = "账户:").grid(row = 0, column = 0) Label(root, text = "密码:").grid(row = 1, column = 0) e1 = Entry(root) def m_test(): if e2.get() == "good": print("OK") return True else: print("NG") e2.delete(0, E...
99902633d6de7661e4719bd70dc52c1b70cf8161
fainle/data_structure
/python/stack/divide_by2.py
338
3.8125
4
from python.basic.stack_by_list import Stack def divide_by2(i): s = Stack() while i != 0: r = i % 2 s.push(r) i //= 2 res = '' while not s.is_empty(): res += str(s.pop()) return res if __name__ == '__main__': assert divide_by2(5) == '101' assert divide_...
4a598adc38cf222dd441d467e3685adf18db58f2
JhoLee/Algorithm
/HeapSort02.py
827
3.609375
4
def findMax(tree, P): temp = tree[P] L = (P * 2) R = (P * 2) + 1 if (tree[L] > tree[R]): if (tree[L] > tree[P]): # L.key > P.key return L if (tree[R] > tree[P]): # R.Key > P.key return R else: return P def buildHeap...
1ce153ba0f6327b07d5bc80ed0c8dfa3875f04d6
iansear/DigitalCrafts
/week1/day3assignments/temp_converter.py
658
4.09375
4
def temp_converter(): temp, scale = get_valid_temp() if scale == "f": ans = (temp - 32) * 5/9 return f"{ans}c" else: ans = temp * 9/5 +32 return f"{ans}f" def get_valid_temp(): is_good = False temp = 0 scale = "" while is_good == False: user_input = input("Enter temp to convert. (eg. ...
ea573bc9187f813f2ab04e46838a01d2ae307d74
balta2ar/scratchpad
/myleetcode/062_unique_paths/62.unique-paths.python3.py
1,695
3.921875
4
# # [62] Unique Paths # # https://leetcode.com/problems/unique-paths/description/ # # algorithms # Medium (43.45%) # Total Accepted: 200.2K # Total Submissions: 460.8K # Testcase Example: '3\n2' # # A robot is located at the top-left corner of a m x n grid (marked 'Start' in # the diagram below). # # The robot can ...
7396ff869850b0d25aa83073962346ee5cfd6f4e
ujin77/esdm3
/_timer.py
1,315
3.59375
4
#!/usr/bin/python # -*- coding: utf-8 # import time from threading import Timer from threading import Event class RepeatTimer(Timer): def run(self): while not self.finished.wait(self.interval): self.function(*self.args, **self.kwargs) self.finished.set() class CTimer(object): e...
eb6fee2c9ca41b3079aa11912a524fd7a43d63a9
gsandoval49/stp
/ch5_combine_list_kw_in_and_notin.py
430
4.34375
4
colors1 = ["blue", "green", "yellow"] colors2 = ["red", "pink", "black"] # combine both lists colors3 = colors1 + colors2 print(colors3) # you can check if an item is in a list with the keyword in: print("green" in colors3) #using the keyword not to check if an item is not in a list. print("periwinkle" not in colo...
0a0373806a42705132e2d1a4dae1d07031c9ef40
PingRen32/LeetCodePersonalSolutions_Algorithms
/Easy/0026_Remove_Duplicates_from_Sorted_Array.py
846
3.65625
4
# Given a sorted array nums, remove the duplicates in-place such # that each element appear only once and return the new length. # # Do not allocate extra space for another array, # you must do this by modifying the input array in-place with O(1) extra memory. class Solution(object): def removeDuplicates(self, num...
02053f930b6c0a75ddfcc15efef0d3e8f6c0fa77
jsong022/simple-sudoku-solver
/simple-sudoku.py
3,513
3.875
4
#!/usr/bin/env python3 import sys import time #returns True iff i and j indexes are in the same column def sameCol(i, j): return (abs(i-j)%9 == 0) #returns True iff i and j indexes are in the same row def sameRow(i, j): return (int(i/9) == int(j/9)) #returns True iff i and j indexes are in the same 3x3 block def sam...
fd898a2168a9c11aebc97f09a19823e0dfbad4a3
chrismanucredo/newton-non-linear-systems
/newton-non-linear-system.py
1,937
4.53125
5
# -*- coding: utf-8 -*- """ author: chris manucredo, chris.manucredo@gmail.com about: this is an implementaion of newton's method for solving systems of non-linear equations. as an example we use two different non-linear systems. at the end you'll see a work-accuracy plot for both systems. """ impo...
898afc3bd2735e5c04c572ae98241ed65ce9a660
fzaman500/Shoe-Lab
/Shoe Party/problem_1.py
562
3.71875
4
import numpy as np import matplotlib.pyplot as plt from shoes_lib import * trials = 500 max_people = 100 data = [exp_value(num_people, trials) for num_people in range(1, max_people + 1)] plt.plot(range(1, max_people + 1), data, 'ro', label = "Experimental Data") plt.plot(range(1, max_people + 1), np....
c6be74449a15f9c277bb6d1c4173917a679f123d
Ayu-99/python2
/session8(b).py
1,023
4.15625
4
""" h.w 1.order can have many food items with user input create a small program with user input add as many food items in list called cart Create a function in order class ->getTotalAmount() which return total Create a function applyPromoCode in order class -> applyPromoCode Create a functio...