blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dd57652f40ff2722ce0399af6d3eb240901f89b2
zhangwei1989/algorithm
/Python/1-two_sum_first.py
434
3.671875
4
# Difficulty - Easy # Url - https://leetcode.com/problems/two-sum/ # Time complexity: O(N2); # Space complexity: O(1); class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(0, (len(num...
cdb6c7bc8d2c4b93f5d45f0498ae6ed71930aba1
FranMZA/NumericMatricProcessor
/domain/MatrixBuilder.py
1,159
3.671875
4
class MatrixBuilder: def build(self, m_dim=None, m_val=None): print(f'{m_dim}') dim_matrix = self.dim_input() print(f'{m_val}') values = list() for row_index in range(dim_matrix[0]): values.append(self.row_input(dim_matrix[1])) return dim_matrix, values ...
22016138907f3567e29a8c80a769c89b6ff4d7dc
anniequasar/session-summaries
/Red_Hat/sess_8/s8b_functions.py
5,971
3.84375
4
# -*- coding: utf-8 -*- """ Functions - Beginners Python Session 8 - s8b_function.py @author: Tim Cummings Demonstrates: Logging, Exceptions, Testing """ import logging import datetime import decimal # Can be useful to include logging in function # Challenge set logging level to DEBUG and confirm that logging outpu...
ed9008fadbd117482229ffe9e0479051640eba15
karandevgan/Algorithms
/StringMatch.py
1,754
3.6875
4
class Solution: # @param haystack : string # @param needle : string # @return an integer def strStr(self, haystack, needle): #import pdb; pdb.set_trace() if len(haystack) == len(needle): if haystack == needle: return 0 else: return ...
f1e13b8fb7cb01f43bc90dba091c7bca5f311865
vsdrun/lc_public
/string/67_Add_Binary.py
891
3.921875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/add-binary/description/ Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". """ class Solution(object): def addBinary(self, a, b): """ :type a: str ...
c911452b9df135a5fe2638a2730536525c375264
xcsp3team/pycsp3
/problems/csp/complex/StableMarriage.py
2,020
3.90625
4
""" Consider two groups of men and women who must marry. Consider that each person has indicated a ranking for her/his possible spouses. The problem is to find a matching between the two groups such that the marriages are stable. A marriage between a man m and a woman w is stable iff: - whenever m prefers an other woma...
fe684d9664f0bf4ffe279d7632f15b0076aa2d74
nicktheo59/eulerPy
/21-40/36.py
400
3.625
4
def IsPallindromic( number ): number = str(number) if len(number) == 0 or len(number) == 1: return True elif number[0] == number[-1]: return IsPallindromic( number[1:-1] ) else: return False print IsPallindromic( 13111 ) sum = 0 i = 0 for num in range(1000000): if IsPallindromic( num ) == True and IsPal...
7404646dd3bf2ef7344a7ba11b985bbac58ef4f5
ming-log/Multitasking
/01 多线程/07 通过继承Thread重写run方法来创建线程.py
453
3.828125
4
# !/usr/bin/python3 # -*- coding:utf-8 -*- # author: Ming Luo # time: 2020/9/4 11:55 from threading import Thread import time class MyThread(Thread): # 重写run()方法 def run(self): for i in range(3): time.sleep(1) msg = "I'm " + self.name + ' @ ' + str(i) print(msg) ...
ef1fbbd2a78c688aa9262470107b3d31c0e57ad0
bezerrasara/programacao-orientada-a-objetos
/listas/lista-de-exercicio-02/questao07.py
114
3.84375
4
lado = float(input('medida do lado: ')) area = lado**2 print(f'area = {area}' ) print(f'dobro da area = {area*2}')
5868f83d57d24064dc30eb4a999ee3b7e5700527
MathMS/atividadesPython
/Mundo 02 - Estruturas de Controle/Atividade 050 - Estrutura For.py
336
4.03125
4
"""Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o""" soma = 0 for c in range(0,6): numero = int(input('Digite o número: ')) if numero%2 == 0: soma += numero print('\nA soma dos números pares deu: {}'.f...
dbf58cf62057e821c559bfec8d0d5148bfa1029b
vitaliipazhbekov/challenges
/codewars/is_this_a_triangle.py
122
3.921875
4
def is_triangle(a, b, c): if a + b > c and b + c > a and a + c > b: return True else: return False
e73a0185387440dab199a5cf3f9519350b2a5efa
Abel3581/Practicas_Python_UNGS
/practica_3_Ciclos_For_While_Range_Cadenas.py
25,230
4.1875
4
##Realizar un programa que solicite dos números y realice la división entre ellos, no se debe permitir que el denominador sea 0. ##Realizar un programa que imprima la tabla del 2 (desde el 1 al 10). ##Modificar el programa anterior, para que pida al usuario un número entero e imprima la tabla de multiplicar de di...
50efc8b8bfcae4bca3c1295e639aa8865d010a00
mwan780/softconass1
/demo/demo09.py
308
4.03125
4
#!/usr/bin/python2.7 -u # Test For Statements i = 0 array = [] for i in xrange(1, 10) : print i, array.append(i) print print "Array Default Print" print array i = 0 while (i < 9 and i > -1) : print i, i += 1 print print print "Iterative Array Print" for i in array : print i, print
9780ab7151f628558c7ec0597d6f6b7066c3f58e
Ch4uwa/PYpractise
/NameValues/valueofname.py
968
3.828125
4
# 46K text file containing over five-thousand first names, # begin by sorting it into alphabetical order. # Then working out the alphabetical value for each name, # multiply this value by its alphabetical position in the list to obtain a name score. # # For example, when the list is sorted into alphabetical order, # CO...
b8beeac3e320035d4a9420d5a6392cc2642bf46d
teoangelyn/2013pythonlab1
/validate_mastervisa.py
1,240
4.34375
4
# validate_mastervisa.py # validate a user input MasterCard or VISA credit card number import re def validate(card_no): ''' Function to validate a MasterCard or VISA credit card number''' total = 0 for a in range(0, 16, 2): # add value of digit multiplied by 2 to total if digit is less than 4 ...
7e5cbc34dba8ae30e59119dcc4f18a4187782e1e
Minkov/python-oop-2021-02
/attributes_and_methods/demos_dict.py
779
3.671875
4
class Person: def __init__(self, name): self.name = name def get_attributes_with_prefix(self, prefix): return [key for (key) in self.__dict__.keys() if key.startswith(prefix)] def set_later_value(self): self.age = 17 def set_dict_value(self): self.__dict__['something']...
593f4edce4e6d75f35ca5312a88501fa64310377
arturoromerou/practice_python3
/cambio_dolar_soles.py
216
4.09375
4
"""Convertir la cantidad de dolares ingresados por un usuario a soles y mostrar el resultado""" print("") dolares = 3.30 soles = float(input("Introduzca el monto a cambiar:\n")) cambio = soles / dolares print(cambio)
1707e41c5f578a169cd658448ed436d6ee817a86
NAMEs/Python_Note
/高级语法/04.py
350
3.828125
4
# deque与list类似,但是有些区别 from collections import deque q = deque(['a', 'b']) l1 = ['a', 'b'] # print(dir(list)) # print() # print(dir(deque)) print(q) print(l1) l1.append('c') q.append('c') print(l1) print(q) # l1.appendleft('d') # 列表中没有这个内置函数 q.appendleft('d') print(l1) print(q)
b3207c507ab49ae51f734465dc53e9fa1e48ef05
johnmontejano/Tweet-Generator
/reaarrange.py
443
3.671875
4
import random import sys shuffle_words = [] def shuffle(words): for _ in range(len(words)): rando = words[random.randint(0,len(words)-1)] shuffle_words.append(rando) words.remove(rando) return shuffle_words if __name__ == "__main__": word_list = sys.argv[1:] if len(word_l...
66dd5955023cad4d323b68410cb3f940591fde02
maykim51/ctci-alg-ds
/sort_and_search/merge_k.py
2,673
3.5
4
''' !!!!!!!!!!! part of CTCI 10.6 Big file. [merge k sorted arrays, external sort 중 앞에꺼] ''' import unittest class heapNode: #heap as in ARRAY def __init__(self, val, i=0, j=0): # i: ix of parent array, j: ix of next var in parent array self.val = val self.i, self.j = i, j ...
932712d72f82365c115df66246fdbc5b9b76e964
sumanshil/TopCoder
/TopCoder/python/misc/BinaryTreeMaximumPathSum.py
845
3.671875
4
class TreeNode: def __init__(self, value): self.val = value self.left = None self.right = None class Solution: max_value = float('-inf') def maxPathSum(self, root): self.recursive(root) return self.max_value def recursive(self, root): if not root: ...
cbb9f7808b544c4b277b832d55bb84b6a2b00293
rdargali/htx-immersive-08-2019
/01-week/3-thursday/labs/Rawandlabs/madlib.py
214
4.125
4
print (f'____\'s favorite subject in school is _____!') name = input ('What is the student\'s name?') subject = input('What is their favorite subject?') print (f'{name}\'s favorite subject in school is {subject}!')
01292a1275b275e9a22acc9acf78f215fb60342c
pichuang/leetcode
/500_Keyboard_Row/Solution.py
719
4.0625
4
import unittest class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm') answer = [] for word in words: lower_word = set(word.lo...
7ae8bf36caf5ccf1e1ba85dd3dbdd01a7978dd06
kncalderong/codeBackUp
/python/Rosalind_programming/stronghold/expected_offspring.py
430
3.65625
4
##! entry of dates values = list() while len(values) < 6: entry = int(input('Please enter the number of couples for each genome:')) values.append(entry) print(values) print( '-----------------') ##! probabilities and genomes prob = [1,1,1,0.75,0.5,0] ##! math con = 0 total = 0 for n in values: sum = n * ...
389e4eacd8a0f5276130a03328340da9cd0f4462
shyingCy/shying_ML
/others/newTon_test.py
197
3.859375
4
# -*-coding:utf-8-*- """ 测试用牛顿法求数的平凡根 """ def newton_sqrt(x): k = 1.0 while abs(k ** 2 - x) > 1e-10: k = 0.5 * (k + x/k) return k print newton_sqrt(2)
851dd921b036db5eafb13fdb6d1cb9ae2778a1a4
Sreelekshmi-60/Programming-lab
/4.2bank.py
966
4.125
4
class Bank_Account: def __init__(self,Account_no,Name,Type_of_account): self.acc_no=Account_no self.name=Name self.acc_type=Type_of_account self.balance=0 def deposit(self): amount=float(input("Enter an amount to deposit :")) self.balance+=amount print("Am...
3ba3100e83278793fcbaf9911d21fa21536f6689
yimanliu/CS5001-Fall2019-yimanliu
/Assignment-1/format-practice.py
1,047
4.21875
4
# part 1 animal = input("What is your favorite animal? ") num_animals = int(input("How many {}s would you like? ".format(animal))) print("I like {}s, too! But, {} is a lot of {}s! Maybe you should just " "have {:.0f}!".format(animal, num_animals, animal, num_animals / 2)) # part 2 print() flower = "Daisy" car = "...
e2e413c66fc074a99b986cc1e988de8cccfbf976
atulkukreti/practice-git
/exercise.py
433
3.953125
4
import random winning = random.randint(1,1000) guess = 1 number = int(input("enter a number : ")) game_over = False while not game_over: if number == winning: print(f"you win and you guessed this number in {guess} times") game_over = True else: if number < winning: print("too...
36db50b512d372e4bb12460359321e8ba636b7b5
wataoka/atcoder
/abc162/b.py
103
3.625
4
n = int(input()) cnt = 0 for i in range(1, n+1): if i%3!=0 and i%5!=0: cnt += i print(cnt)
6f898986da7bd470f00b72138dbb1feb132ab055
Hilgon2/prog
/PE7/PE7_5.py
153
3.75
4
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for getal in list: for nummer in list2: print(getal * nummer)
8ebbfa09c96cf17490e1ecc209dfad24d14f5e62
DwanW/cohort4
/01-getting-started/syntax.py
1,927
3.90625
4
# define attributes / variables # number (int float in python) # string # boolean # array # dictionary / objects # None # if / else # functions # parameters # returns # arrays # add to the front # add to the end # update values # loops # for/in # Objects / Dictionaries # declare object # lookup key to retrieve the valu...
4e149084923960714f994d9c89110a41cb81afe3
joeaoregan/Python-GamesAndTutorials
/Python3-Sockets/echo_server_3.py
634
3.640625
4
#!/usr/bin/env python3 """ Joe O'Regan 21/02/2019 Looping TCP Echo Server """ import socket HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 8888 # Port to listen on (non-privileged ports are > 1023) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen() pr...
50b50bced6ebae1699f6d9b313c18ad16d9f6040
nikoWhy/softuniPython
/slojni_proverki/figure.py
412
4.09375
4
h = int(input()) x = int(input()) y = int(input()) if ((x <= 3 * h and x >= 0) and (y <= h and y >= 0)): if x == 0 or y == 0 or x == 3 * h or y == h: print('border') else: print('inside') elif ((x <= 2 * h and x >= h) and (y <= 4 * h and y >= h)): if x == h or x == 2 * h or y == h or y == 4...
24c7c7901084412103898f2d96d2c5a71bf07b6f
meemain/tensorflow
/multiclass_classifier_handlanguage.py
4,195
3.5625
4
# download sign mnist data (2 csv files) from here :https://www.kaggle.com/datamunge/sign-language-mnist import csv import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator def get_data(filename): # You will need to write code t...
7e9351b102ddba5b3ad9b40171b9ae5031fff25c
IvayloSavov/Fundamentals
/More Exercises_Basic Syntax_Conditional_Statements_and_Loops/how_much_coffee_do_you_need.py
585
3.78125
4
command = input() needed_coffee = 0 is_break = False while command != "END": event = command is_upper = False if event.isupper(): is_upper = True event = event.lower() events = ( (event == "coding") or (event == 'dog' or event == 'cat') or (event == "movie") ...
8acad694919dd4960936952f06ef62294358dae2
adonskoi/integrity
/integrity/__main__.py
666
3.6875
4
import sys from .calculate import is_hash_match from .parse import parse def main(): if len(sys.argv) < 2: print("please enter filename") return file_path = sys.argv[1] path_to_given_files = "" if len(sys.argv) > 2: path_to_given_files = sys.argv[2] try: with open...
bbb1e0c7a648c4cbf5ed646ddfcea1927a84046f
soharabhossain/BMU_Placement_Training_Python
/28th July 2021/pickle.py
1,111
3.5
4
# ---------------------------------------------------------------- import pickle as pk # Serialize f = open("pic.pk","wb") dct = {"name":"Raj", "age":23, "Gender":"Male","marks":75} pk.dump(dct, f) f.close() # De-Serialize f = open("pic.pk","rb") d = pk.load(f) print(d) f.close() # -------------...
32a369bed50eee351aff311120069fed3dbe97d8
aveedibya/pythonBasics
/Python_Basics.py
3,544
3.6875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 13 11:46:14 2018 @author: Aveedibya Dey """ """PYTHON DATATYPES: Source: https://www.programiz.com/python-programming/variables-datatypes Types: int, float, complex Use type() function to check the type """ a = 5 type(a) print(a, "is of type", type(a)) a = 2....
74d3bb780e3362dc16c483b7380d4ff3302c0c2a
Rakshy/coding
/Linkedlists/palindrome.py
1,287
4.09375
4
#logic - use fast/slow runner #initialize 2 pointers at the head, move one at 1 place per move and the other 2 places per move. # when the 2nd pointer reaches the end, the 1st will be pointing at the center of the list. #store values of head 1 in an array and then compare head 2 with the array as it moves from Linkedl...
600c274c6c3c25b04511f8ff27dab34bef6a60fe
SachieTran/easy_sudoku
/sudokugrid.py
4,159
3.84375
4
# sudokugrid.py # # Created by: Tran Tran # # # The program implements the SudokuGrid ADT that will be used to represent # the puzzle grid. from ezarrays import Array2D # Values representing the empty cell on the grid. EMPTY = 0 class SudokuGrid(): # Creates a new Sudoku grid of empty cell...
223ebc3168491cb942b1033efcb4bec66022ad07
altareen/csp
/03Functions/userfunctions.py
803
3.828125
4
def pythagoras(opp, adj, tau, epsilon): hyp = (opp**2 + adj**2)**0.5 solution = hyp * tau + epsilon return solution result = pythagoras(3.2, 4.7, 1.3, 0.57) print(result) # a function that takes no parameters and does not return a value def displayhello(): print("hello") displayhello() # a function ...
afdb7bacebcbcd5fdccf995a9b8f78776735ce01
AnushreeGK/anandology-solutions
/chap1&2/wordfreq.py
170
3.640625
4
def word_frequency(words): frequency = {} for w in words: frequency[w] = frequency.get(w, 0) + 1 return frequency print word_frequency("qw wq qw wq")
fa26f280bb90a203fe0722c9d09d19744b1bd086
jackyyy0228/RL-environment-for-Tetris-Battle
/keyboard.py
1,456
3.625
4
import pygame from tetris import Tetris key_actions=['RIGHT','LEFT','DOWN','UP','z','SPACE','LSHIFT'] delay_time= [ 150,150,200,200,200,400,450] class Keyboard: def __init__(self): self.T = Tetris(action_type = 'single',is_display = True) def run(self): while True: state = self.T.re...
e34426f6a0f2e7fea665bcadddf22df77c9f7dd1
SvetlanaTsim/python_basics_ai
/lesson_8/task_8_1.py
1,790
3.796875
4
""" Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый — с декоратором @classmethod. Он должен извлекать число, месяц, год и преобразовывать их тип к типу «Число». Второй — с декоратором @staticmethod, долже...
d15daf400633a793f939241d3d9b6c68d298c63b
JunaidParacha/python
/raj_chetan/assignments/bubble_sort.py
395
3.671875
4
import random import time my_arr = [int(1000*random.random()) for i in xrange(20)] def bubble_sort(arr): start = time.time() counter = 0 for do_times in range(len(arr)): counter +=1 for count in range(0, len(arr)-counter): if arr[count] > arr[count+1]: (arr[count], arr[count+1]) = (arr[count+1], arr[cou...
548a966107da3176f1524645f50efd7e3ce632e1
or0986113303/LeetCodeLearn
/python/599 - Minimum Index Sum of Two Lists/main.py
1,201
3.765625
4
import collections class Solution(object): def findRestaurant(self, list1, list2): """ :type list1: List[str] :type list2: List[str] :rtype: List[str] """ list1hash = {} list2hash = {} result = {} for index, parts in enumerate(list1): ...
3235cf5a894c4ac9c116a7fcbf1fadf0dfbbd50b
ericxlima/ILoveCoffee
/scrips/jogo_da_forca.py
3,719
3.515625
4
from random import choice import json class JodoDaForca: def __init__(self, nick): self.categorias = {'animais': ['coelho', 'cavalo', 'coruja', 'gaivota', 'porco', 'galinha', 'macaco', 'baleia', 'golfinho', 'morcego', 'girafa', 'elefante', ...
71c7dfd1340af498b21f405cb08ac7a9b8a64d2b
DivyaReddyNaredla/python_programs_practice
/constructor.py
341
3.609375
4
class bankaccount: def __init__(self):#constructor self.balance=0 def withdraw(self,amount): self.balance-=amount return self.balance def deposit(self,amount): self.balance+=amount return self.balance e=bankaccount() print(e.deposit(5000)) #5000 print(e.wi...
2f13ef171346b673e2acc935a84acb0571f180c9
Marcus-Mosley/ICS3U-Unit3-01-Python
/adding.py
551
4.15625
4
#!/usr/bin/env python3 # Created by Marcus A. Mosley # Created on August 2020 # This program adds two user inputted integers def main(): # This function adds two user inputted integers # Input variable_x = float(input("Enter the first integer to be added: ")) variable_y = float(input("Enter the seco...
d9501c3078f358b0a72d1ebd9c6548f3e32eed9d
sp314/Programming-Challenges
/Challenge Files/A_Real_Challenge.py
412
3.84375
4
''' Input: The input consists of a single integer aa (1≤a≤10181≤a≤1018), the area in square meters of Old MacDonald’s pasture. Output: Output the total length of fence needed for the pasture, in meters. The length should be accurate to an absolute or relative error of at most 10−610−6. ''' import math def fenceNeeded...
0cc67fde98911a9ab3890b187ec5266a8d417ebf
KR031994/bch5884
/Python Projects/temperature/temperature.py
341
4.21875
4
#Python program to convert temperature from Fahrenheit to Kelvin #Link to Repository Path:https://github.com/KR031994/bch5884.git import sys print("Please enter a temperature in Fahrenheit: ") Fahrenheit=float(sys.stdin.readline()) Kelvin=273.5 + ((Fahrenheit - 32.0) * (5.0/9.0)) print("The corresponding Kelvin temper...
2df28653055e9fe1cadd2fe436547ac159bbc6c7
jiajiabin/python_study
/day01-10/day07/作业/15_逆序返回.py
344
4.28125
4
# 编写函数※传入一个语句,由单词和空格组成,将每个单词逆序再拼回一个字符串 # 传入:hello world # 返回:olleh dlrow def reversed_order(str1): list1 = str1.split(" ") str2 = "" for i in list1: i = i[::-1] + " " str2 += i return str2 print(reversed_order("hello world"))
19c968c07f943f73a7c2dbafff00db120f1b8b0b
7eventhCircle/Python
/dicegame.py
968
4.4375
4
'''This program is a number guessing game, a user will input a guess and the program will see if they are right.''' from random import randint from time import sleep def get_user_guess(): guess = int(input('Guess a number: ')) return guess def roll_dice(number_of_sides): first_roll = randint(1,number_of_sides) ...
80b165e68760e15edb251c9d0724081b27cb2e35
Mozikoff/geekbrains_python1
/lesson-1/hw01_normal.py
3,241
3.703125
4
import math import random __author__ = 'Мозиков Евгений Александрович' # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. # Например, дается x = 58375. # Нужно вывести максимальную цифру в данном числе, т.е. 8. # Подразумевается, что мы не знаем это число заранее. # Число приходит в ...
e7fec11f6abfe037f483924d510ed607a3264992
weiweiECNU/QBUS
/qbus6850_19_1/week6/Lecture06_Example01_Updated.py
4,212
3.578125
4
""" Created on Wed Mar 28 09:34:07 2017 @author: Dr Chao Wang Revised by: Professor Junbin Gao """ from sklearn import tree from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder import pandas as pd import numpy as np # Load the dataset, please view the csv file b...
6033199b01c20593c1697ab3d2f2dbe9491df78a
alamyrjunior/pythonExercises
/ex019.py
319
3.515625
4
import random aluno1 = input('Digite o nome do primeiro aluno: ') aluno2 = input('Digite o nome do segundo aluno: ') aluno3 = input('Digite o nome do terceiro aluno: ') aluno4 = input('Digite o nome do quarto aluno: ') r = random.choice([aluno1, aluno2, aluno3, aluno4]) print('O aluno escolhido foi',r)
16c0f3a391c21fbc4a30b97f21f7a60b6dff5fda
riodementa/Python_Michigan-University
/9_1.py
160
3.859375
4
fhand = open("words.txt") my_dict=dict() for line in fhand: for word in line.split(): my_dict[word]=1 print "Rio" in my_dict print "or" in my_dict
1329d04d1c92d7463477aae42b18b8860bcc531f
Exia01/Python
/Self-Learning/Algorithm_challenges/sum_pairs.py
792
3.75
4
# Write a function called sum_pairs which accepts a list and a number and returns the first pair of numbers that sum to the number passed # to the function def sum_pairs(val_list, num): x = 1 list_length = len(val_list) - 1 for index in range(list_length): temp_sum = val_list[index] + val_list[x] ...
c8e357d45a0b6456d6b1a542944d526ec357a557
flateric94/python
/cupge/tp3/morpion_1ere_version.py
8,422
3.765625
4
#triangle de pascal def pascal(N): #N:numero de la ligne avec premiere ligne à 1 liste=[[1],[1,1]] #je definie la 1ere et la 2eme ligne print(liste[0]) print(liste[1]) for i in range(2,N): #je m'occupe des nouvelles lignes liste.append([1]) #chaque l...
06d9702c4d44fc06dca98c158e8187fdff8cb0fe
zzy1120716/my-nine-chapter
/ch02/related/0183-wood-cut.py
1,447
3.75
4
""" 183. 木材加工 有一些原木,现在想把这些木头切割成一些长度相同的小段木头,需要得到的小段的数目至少为 k。 当然,我们希望得到的小段越长越好,你需要计算能够得到的小段木头的最大长度。 样例 有3根木头[232, 124, 456], k=7, 最大长度为114. 挑战 O(n log Len), Len为 n 段原木中最大的长度 注意事项 木头长度的单位是厘米。原木的长度都是正整数,我们要求切割得到的小段木头的长度也要求是整数。 无法切出要求至少 k 段的,则返回 0 即可。 """ # 基于答案值域的二分法 class Solution: """ @param L: Given n piece...
bc4e838330af81d19ddd69bfb7de88d64f7f964c
aniketmandalik/ProjectEuler
/Problem053.py
381
3.703125
4
from timeit import default_timer as timer from math import factorial def combinatoric_selections(n, a): total = 0 for i in range(1, n + 1): for j in range(1, i + 1): options = factorial(i)/factorial(j)/(factorial(i - j)) if options > a: total += 1 return total start = timer() print(combinatoric_selecti...
916b03bb93664be3f52471167b1319d61708c28e
OsmanCekin/Programming_V1B_OsmanCekin
/Opdracht 10/Final Assignment.py
2,692
3.9375
4
def inlezen_beginstation(stations): laatsteHalte = 'maastricht' invoerBeginstation = input('Wat is je beginstation?: ').lower() if invoerBeginstation == laatsteHalte: print(laatsteHalte + ' is de laatste halte. Vul een andere beginstation in.') elif invoerBeginstation in stations: return...
d0d2621df97a7eefb4b86d423d62cf0dd90b3045
AnjuBA99/pythonlab
/Excercise4.py
145
3.796875
4
mvalue=1.8 addvalue=32 cel=int(input("Enter temperature in celsius:")) fah=(cel*mvalue)+addvalue print("Temperature in fahrenheit is:",fah)
5d2f7f98d7e2ab0ff8346c87ca49169d64c51faa
syurskyi/Python_Topics
/095_os_and_sys/examples/realpython/021_Copying Directories.py
741
3.515625
4
# While shutil.copy() only copies a single file, shutil.copytree() will copy an entire directory and everything # contained in it. shutil.copytree(src, dest) takes two arguments: a source directory and the destination directory # where files and folders will be copied to. # # Here’s an example of how to copy the conten...
971aaf789b09ca50fa2d67982deb71646a65a051
matrix-lab/machine-learning
/jiangruikai/Project/Task0.py
1,124
3.765625
4
#coding:utf-8 """ 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务0: 短信记录的第一条记录是什么?通话记录最后一条记录是什么? 输出信息: "First record of ...
dc7803ffb304fdf313a122ae198e601be87e07ca
trevorDarley/BoilerCode2017
/variables.py
249
3.875
4
age = 16 #Defining age num1 = 5 num2 = 6 print "I am %d years old" %age #print age in formatted format print "If I add %d, %d and %d I get %d" % (age, num1, num2, age + num1 + num2) #adds numbers print "\nHello \t\t world\n" #Tabbed Hello world
a14d0a480d79e15d1f7c06ee46f135cb23985bed
Xiristian/infosatc-lp-avaliativo-02
/atividade05.py
246
4.03125
4
minhalista = [3, 5, 6, 4, 9] elementoX = int(input("Digite um número inteiro para saber se o item esta na lista: ")) if elementoX in minhalista: print("O item digitado está na lista") else: print("O item digitado não está na lista")
46584a6bd67011dac3c3873a79c54b6fc2f0336d
rustamiwanttobefree/2lesson-2
/zadanie2.py
403
3.65625
4
var_count = int(input("Введите количество элементов списка ")) my_list = [] i = 0 var = 0 while i < var_count: my_list.append(input("Введите следующее значение списка ")) i += 1 for elem in range(int(len(my_list)/2)): my_list[var], my_list[var+ 1] = my_list [var + 1], my_list[var] el ...
beb054e4bc8b1408e9d85770dfa9c3cf4f69f186
excelsky/Leet1337Code
/HackerRank/Hired_balanced_bracket.py
2,183
3.8125
4
# def solution(angles): # # Type your solution here # if len(angles) > 1: # print("if") # new_angles = [] # for i in range(len(angles)-1): # print(i) # if (angles[i] != "<" or angles[i+1] != ">") and i+2 == len(angles): # print("ifif") # ...
196cbb127fe0f7309e15341b078c0a532f721a34
LanyK/TheAngerGames
/bombangerman/client/Sprites.py
6,597
3.609375
4
import pygame import json from collections import defaultdict class Spritesheet(object): @classmethod def from_file(cls, filename, sprite_size=(16, 16)): """ @param sprite_size: Defaults to (16,16) Load a spritesheet from a file. This method will load an image file and cut it...
798d0bf382c6046ceeb76a5faa19e64362af3465
anton-perez/graph
/src/directed_graph.py
3,510
3.5625
4
class Node: def __init__(self, index): self.index = index self.children = [] self.parents = [] self.previous = None self.distance = None class DirectedGraph: def __init__(self, edges): self.edges = edges self.max_index = self.get_max_index() self.nodes = [Node(i) for i in range(self...
0cf85e201b73c511eb95bde428083520a7ae4b13
samisosa20/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/0-positive_or_negative.py
211
4.15625
4
#!/usr/bin/python3 import random number = random.randint(-10, 10) if (number < 0): str = "is negative" elif (number > 0): str = "is positive" else: str = "is zero" print("{} {}".format(number, str))
04602fea3b2896f619ee3b0c0202d88176e7f14f
hohaidang/Python_Basic2Advance
/ErrorHandling/main.py
439
3.921875
4
import sys # try: # print(a) # except NameError: # print("Name Error") # except: # print("Error") try: print(x) except: print("Something went wrong") finally: # Will print regardless of try is throw error or not print("The 'try except' is finished") sys.exit(1) try: f = open("demofile.txt...
00a89345238f6dfe5b9988207a405231c4c5ea87
amol10/python_challenge
/7/sol3.py
951
3.5625
4
from zipfile import ZipFile #unzipped = zipf.read() #print(unzipped) #zipf.printdir() def extract_files_from_zip(): zipf = ZipFile('channel.zip', 'r') zipf.extractall(path='unzipped') def follow_the_chain(): n = '90052' while True: text = '' with open('unzipped/' + n + '.txt', 'r') as f: text = f.rea...
5f255a17b1d81b1b3edaa2acf2e8222d1deb8750
Code-Institute-Submissions/portfolio-project-three
/pokergame.py
2,840
4
4
from poker import Poker from inputhandler import InputHandler class RunPoker: """ This class runs the game Poker and stores information for use in highscore table """ def __init__(self, name='NoName'): self.name = name self.games_played = 0 self.games_won = 0 self.g...
f6f7799574576094164b222751bfa73e9f5e0c92
Levintsky/topcoder
/python/leetcode/dp/1125_smallest_sufficient.py
5,170
4.03125
4
""" 1125. Smallest Sufficient Team (Hard) In a project, you have a list of required skills req_skills, and a list of people. The i-th person people[i] contains a list of skills that person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one pers...
2c15bc6624d1e5813fcf3a741f817319e3bcd465
rafaelblira/python-progressivo
/imprime_n_linha.py
168
4
4
def piramide(n): for c in range(1, n + 1): letra = str(c) print(c * letra) numero = int(input('Digite um número para imprimir:')) piramide(numero)
ae48e16cf504be5f931772fd7cebfd42bca3af80
skattelmann/myrep
/hacker.org_solver/mortal_coil/mortal_coil.py
3,931
3.5
4
import random import math import numpy as np import time def recSearch(board, ii, jj, dirs): # bottom i = ii+1 j = jj pos = board[i,j] if pos == 0: while pos == 0: board[i, j] = 1 i += 1 pos = board[i,j] i -= 1 board[i,j] =...
d2b6828f2578a47d77fb1c8fd29a3f89c9a6a5f6
olegzinkevich/programming_books_notes_and_codes
/numpy_bressert/ch03_sklearn/clustering.py
1,607
3.6875
4
# SciPy has two packages for cluster analysis with vector quantization (kmeans) and hierarchy. # The kmeans method was the easier of the two for implementing and segmenting # data into several components based on their spatial characteristics # DBSCAN algorithm is used in # the following example. DBSCAN works by f...
7c9cd494da22e2ab209287da81e7eaa196d634b1
Light2077/LightNote
/python/python测试/example/vector/vector.py
607
3.625
4
class Vector: def __init__(self, x, y): if isinstance(x, (int, float)) and \ isinstance(y, (int, float)): self.x = x self.y = y else: raise ValueError("not a number") def add(self, other): return Vector(self.x + other.x, ...
72d19ed37e40efb5fba000bd7467f25a5163b964
adebayo5131/Python
/Recursion and Iteration.py
234
4.09375
4
def iteration(low, high): while low <= high: print(low) low = low+1 def Recursive(low, high): if low <= high: print(low) Recursive(low+1, high) print(iteration(1, 5)) print(Recursive(1, 5))
ac59647c0f616345e77c30116cb7cf2c77fc237c
semiramisCJ/practice_python
/binary_search_number_list.py
783
3.8125
4
def binary_search(input_list, start, end, query): if start >= end: return False half = (start + end) // 2 if query == input_list[half]: return True elif query > input_list[half]: start = half return binary_search(input_list[start:], start, len(input_list[start:]), query) ...
f41f1044d0c8ae3c729d3ebe9b747f59d2456f40
M0GW4I-dev/programming-competition
/qiita/product.py
170
3.75
4
def main(): a, b = [int(i) for i in input().split()] if a*b%2 == 0: print("Even") else: print("Odd") if __name__ == '__main__': main()
6a54effc2e9043f8f725a0861dccb54a35003b94
Pabloitl/data-structures
/Estructuras/src/Presentacion/Ejemplos/BFS.py
2,617
3.703125
4
""" 1.- Meta: Escribir("Encontrar la ruta más corta entre dos nodos") Escribir("a partir del número de aristas") 2.- Datos: 2.1.- Inicalizar: visitados = set() parent = dict() G = eval(leerGrafo()) 2.1.1.- LeerGrafo: // Lee el grafo de un archivo Es...
c7a9367bd3e63a97740edb83c1886cd1f03dc831
filesmuggler/python-code
/transpositionDecrypt.py
1,704
3.765625
4
## http://inventwithpython.com/hacking (BSD Licensed) ## Krzysztof Stężała (BSD License) import math,sys,time ## main() is the main function of this script or module. def main(): # encrypted message and key myMessage = 'Rg r!ahb itecnssoy td a inrfnieog' myKey = 8 # getting original message ...
2248b7332d27942c36deb2dcf834f72a13b541ef
wmm0165/crazy_python
/05/named_param_test.py
316
3.96875
4
# -*- coding: utf-8 -*- # @Time : 2019/6/22 22:08 # @Author : wangmengmeng def girth(width, height): print("width:", width) print("height:", height) return 2 * (width + height) print(girth(3.5, 4.8)) print(girth(width=3.5, height=4.8)) print(girth(height=4.8, width=3.5)) print(girth(3.5, height=4.8))
b5d49fce93f403f4977f19a6b12cd31b3bb778d9
kaos8192/Freecell-py
/deck.py
542
4.03125
4
import random def shuffle_deck(Card, seed=None): '''generates a shuffled deck with the provided Card class Note that Card should have a constructor that takes two arguments in (rank, suit) order. rank is in the range [1,13] and suit is [0,3] If seed is omitted, the generated shuffle will be different...
55fd7ade9f336582bdb3365ca99d8ef8e705b0be
iamSamuelFu/cs177_hw3
/targaryend.py
2,706
3.90625
4
import sys import crypt import itertools import string salt = "aa" real_hash = ".YVJDT1VruA" # def guess_password(real): # chars = string.ascii_lowercase + string.digits # attempts = 0 # for password_length in range(1, 9): # for guess in itertools.product(chars, repeat=password_length): # ...
bc291c10469285b2d85b8f690532cc3d99c1b764
Abel2Code/TeachingPython
/Examples/Text-BasedGames/MarioVSSonicFramework.py
2,235
4.21875
4
import # Figure out what to import to generate random numbers # Mario Stats marioHealth = 64 marioAttackRange = [6, 8] # When mario attacks, make his attack between 6 and 8 (inclusive) # By learning how to generate random numbers. you should be able to figure out how to generate a number between 6 and 8 marioHea...
a48e91a699fd8c9ce1a217a3a4520ff7683a0620
chenjinpeng1/python
/day4/JSQ.py
1,264
3.546875
4
#python 3.5环境,解释器在linux需要改变 #作者:S12-陈金彭 import re def jisuan(num): num=chengchu(num) # String=jiajian(num) return num def chengchu(num): # print(num) # print(re.search('\d+[\.?\d+]?[\*|\/]\d+',num)) if re.search('\-?\d+[\.?\d+]?[\*|\/]\d+',num) is None: return num String=re.search('...
542b814715ea82133e3f084cefc5395324c3326d
jordanNewberry21/python-practice
/lesson19-advanced-string-syntax.py
1,140
4.21875
4
# double quotes avoid messing up with apostraphes str = "That is Alice's cat." # escape characters str2 = 'Say hi to Bob\'s mother!' # backslash is used before certain characters to denote certain text things for example # \' = single quote in string # \" = double quote in string # \t = tab in string # \n = new line...
00fd5efa4c66b7bd4617f4c886eddcdf38b951b7
engineeredtoprogram/my-first-blog
/python_intro.py
450
4
4
print ("Hello, Django girls!") volume = 57 if volume < 20: print("It's kinda quiet.") elif 20 <= volume < 40: print("It's nice for background music") elif 40 <= volume < 60: print("Perfect, I can hear all the details") elif 60 <= volume < 80: print("Nice for parties") elif 80 <= volume < 100: print...
79f97af923664e035a7d221ece6ec36debba7a5d
awsumal/Python-sem-1
/ali6.py
153
4.03125
4
a=int(input("Enter a number ")) for i in range(2,a): if(a%i==0): print(a,"is not prime \n",i,"times",(a//i),"=",a) break; else: print(a,"is prime")
e7e6dd3c39ff6c59dd456f0f744086aa34ca9047
slowy07/crackingPythonInterview
/arrayAndString/rotateMatrix/rotateMatrix_solution.py
511
3.8125
4
def rotateMatrix(matrix): # Transpose the Matrix for i in range(len(matrix)): for j in range(i + 1, len(matrix)): # Switch the row and column indices matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse every row for r in range(len(matrix)): for i in...
a0528579d80039e00011b45d152dbca00415d4c2
Juozapaitis/CodeWars
/6 kyu/cm7_find_senior_developer.py
326
3.703125
4
def find_senior(lst): max = -1 answer = [] for i in range(len(lst)): if lst[i]['age'] == max: answer.append(lst[i]) if lst[i]['age'] > max: max = lst[i]['age'] answer.clear() answer.append(lst[i]) return answer # your cod...
4b349cb2774e66fdf3bbc597c7c5bf761ba23947
federix8190/Reactjs
/services/script.py
90
3.546875
4
a = 5; s = 2; if a == s: print 'a y s son iguales' else: print 'nada' range(1,2) len(1.2)
11587eb37af3e8b0b892f2d6866762b3b8c411fb
fengbingchun/Python_Test
/demo/simple_code/test_typing.py
5,259
3.828125
4
from typing import Callable, List, NewType, Any, NoReturn, Union, Optional, Literal, TypeVar, Generic, TypedDict, Dict, Mapping, List, Sequence, Set, Tuple, Iterable # Blog: https://blog.csdn.net/fengbingchun/article/details/122288737 var = 9 # reference: https://docs.python.org/3/library/typing.html if var == 1: # ...
bd477fa48b2680e00a1e4bbe3248cd2a479563b2
jaehojang825/CS-313E
/Spiral.py
2,924
4.15625
4
#File: Spiral.py #Description: prints surrounding values of central value of spiral #Student's Name: Jaeho Jang #Student's UT EID: jj36386 #Course Name: CS 313E #Unique Number: 50300 #Date Created: 2/17/20 #Date Last Modified: 2/17/20 # Input: dim is a positive odd integer # Output: function ...
65c64695c57b7b45a31a36878176f102e1378d1c
samuel-santos3112/Exercicios-Python
/Tabuada.py
196
3.96875
4
numeroTabuada = int(input("Informe o número de 1 a 10, qual deseja ver a tabuada: ")) for i in range (10): if i > 0: multiplicacao= numeroTabuada * i print(numeroTabuada,"",)
887f411438f68dc3490ab46992ee52695083d4c9
K-Rdlbrgr/hackerrank
/Dictionaries and Hashmaps/Sherlock and Anagrams/sherlockandanagrams_solution.py
2,642
4.09375
4
# First we import Counter and combinations from collections import Counter from itertools import combinations def sherlockAndAnagrams(s): # Assigning an empty list for the count count = [] # The for-loop and the list comprehension loop through the string and create for i in range(1, len(s) + 1): ...