blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8a56bdf0bd3b0ac390c9af5809e7378c9faf1283
glbter/kpi-computing
/algorithms_theory/binary_tree_linked_list.py
5,366
3.8125
4
class Tree: def __init__(self): self.root = None def add(self, elem): newNode = Tree.TreeNode(elem) if self.root == None: self.root = newNode else : current = self.root prev = current while current != None : ...
bf82af4eec931bcad6e329fb79f28ac03c2fa529
JMcWhorter150/python_grocery_list
/grocery_list.py
1,221
4.09375
4
# reused functions def make_grocery_list(): groceries = [] while True: user_input = input('What do you need from the grocery store? ') if user_input == '': break else: groceries.append(user_input) return groceries def print_grocery_list(grocery_list):...
d4b95201fead3666539f9b9dea049aaca630e5cf
prashantpandey9/codesseptember2019-
/hackerearth/number_pattern.py
111
3.578125
4
d=int(input()) for k in range(d,1,-1): for kk in range(d,1,-1): print(k,end='') print("")
b0ae99a1defe08ad10fa8feca0adc0967ba859b4
Full-Stack-Artisan/LeeLeeCoCo
/002_346_moving_average_from_data_stream/py_code_2.py
635
3.8125
4
from collections import deque class MovingAverage: def __init__(self, size: int): """ Initialize your data structure here. """ self._queue = deque() self._sum = 0 self._size = size def next(self, val: int) -> float: if len(self._queue) == self._...
fca95ab6866c297c2dd575206614ec748e8f1c9d
agzimmerman/darts-and-prime-numbers
/darts_and_prime_numbers.py
2,964
3.90625
4
''' This script answers a question that came up while playing darts at Sowieso the other night. Someone observed that, when you look at any two adjacent sections, their number very often summed to prime numbers. We counted nine. I suppose I should double check that number on a standard dart board found on the intern...
7615b4cd331d617c5e52ca40bd5490aeeb279125
StevenCM199/Introduccion-a-la-programacion
/Recursion de cola/divide3.py
490
3.984375
4
#Recibir un numero y eliminar los digitos divisibles entre 3 def divide3 (num): if isinstance(num,int): return divide3_aux(num,0,0) else: return "Error: el número no es un entero" def divide3_aux(num,resultado,pot): if (num == 0): return resultado elif (num%10) % 3 =...
21a43144a7759af3bc15df40b278359f71845762
JeIIicoe/Python-Testing
/tests/test.py
535
3.71875
4
def tester(a, b) : print( 'Addition:\t' , a , '+' , b , '=' , a + b ) print( 'Subtraction:\t' , a , '-' , b , '=' , a - b ) print( 'Multiplication:\t' , a , 'x' , b , '=' , a * b ) print( 'Division:\t' , a , '/' , b , '=' , a / b ) print( 'Floor Division:\t' , a , '//' , b , '=' , a // b ) prin...
dd2914d92e26e4c13a239be931f2df76cf47d36c
f-fathurrahman/ffr-komputasi-material
/autoforce/util_flake.py
1,705
3.890625
4
# + import numpy as np from numpy.linalg import norm def generate_random_cluster(n, d, dim=3): """ Generates a random cluster of n points such that all nearest neighbor distances are equal to d. n: number of points d: nearest neighbor distances dim: Cartesian dimensions """ def rando...
2d68b383821e1686239563cfaf38ff143ea8d135
ConorODonovan/online-courses
/Udemy/Python/Complete Python Bootcamp/Blackjack/Blackjack_deck_class.py
684
3.546875
4
''' Deck class ''' class Deck: def __init__(self, suits, ranks): from Blackjack_card_class import Card self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) def __str__(self): deck_str = "" ...
c63b3c7e7567e42926e12e151171ce70fff95620
alexshacked/algorithms
/data_structures/disjoint_set.py
1,389
3.703125
4
class DisjointSet: def __init__(self): self.forest = {} def makeSet(self, x): exist = self.forest.has_key(x) if not exist: self.forest[x] = {'parent': x, 'rank': 0} def find(self,x): exist = self.forest.has_key(x) if not exist: return None ...
b17846518551748c8daa4978e35141eb20b1e0e8
asettouf/projectEuler
/pb50.py
1,366
3.859375
4
import math def constructListOfPrime(lim): pp = 2 ps = [pp] toAdd = False while pp < lim: pp += 1 toAdd = True for a in ps: if a > math.sqrt(pp): break if pp%a == 0: toAdd = False break if toAdd: ps.append(pp) return ps def lengthSumOfPrime (primeList, prime): temp = 0 count = 0 ...
40b6ba1c4aa3e5d7ba46325aa7654b1ee65c9bbe
tanuja333/ML_Training
/ML_Simplilearn/example_exercise_simple_linear_regression_TaxiFare_forDemoV1.py
1,412
3.921875
4
# Simple Linear Regression """ Created on Wed May 9 06:59:15 2018 @author: Shivendra This is Simple Linear Model illustration code for ML training """ # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Now, Lets import the data set # Read from data file # slice the i...
e1cd9a3bb927d66c65566077cdd5de543f7b50b9
CircleZ3791117/CodingPractice
/source_code/LC10_RegularExpressionMatch.py
2,991
4.34375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'CZ' """ Description: Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire i...
cac1ec82a0a207a3184cc3d0873741dd6a451bb6
imnikkiz/Interfaces-and-Main-Loops
/arithmetic.py
566
3.9375
4
def add(num1, num2): return num1 + num2 def subtract(num1, num2): return num1 - num2 def multiply(num1, num2): return num1 * num2 def divide(num1, num2): a = float(num1) b = float(num2) return a / b def square(num1): return num1 * num1 def cube(num1): return num1 * num1 * num1 def ...
4ae85640c5bf96a7cce955efcf5370624771f2c4
immuno121/Contactless_Sensing
/LSTM.py
14,252
4
4
# -*- coding: utf-8 -*- r""" Sequence Models and Long-Short Term Memory Networks =================================================== At this point, we have seen various feed-forward networks. That is, there is no state maintained by the network at all. This might not be the behavior we want. Sequence models are centra...
ac13b247ea8616ade8f45c400c426d94e90e403e
memling/TomaszMering_python
/2.5_Pozdrawiacz.py
276
3.515625
4
# Program 'Pozdrawiacz' # Demonstruje użycie zmiennej # (Z książki "Python dla każdego" Michaela Dawsona, wydawnictwo Helion) # Python 3.7.1 name = "Ludwik" print(name) print("Cześć,", name, ".") input("\n\nAby zakończyć program, naciśnij klawisz Enter.")
26516fcb9df9de26469719c7e48d391f6d1b7fc2
Yang-Jianlin/python-learn
/LeetCode/T-2.py
1,216
3.796875
4
from LeetCode.链表排序 import CreateLink from LeetCode.链表排序 import LinkNode class Solution: def addTwoNumbers(self, l1, l2): newlink = LinkNode(None) new_l1 = l1.next new_l2 = l2.next num_l1 = 0 num_l2 = 0 i = 1 j = 1 while new_l1: num_l1 = n...
7ea38af0a77efcf35d4709e86251693dc8e9e1ea
ymeysa25/Python
/Password Generator/app.py
3,809
3.71875
4
# Import Suitable Library import string import random from tkinter import * from tkinter import messagebox from PIL import ImageTk from PIL import Image # Declare CONSTANT VARIABLE LETTERS = string.ascii_letters NUMBERS = string.digits PUNCTUATION = string.punctuation # ================================== Function...
4028a5460c0035becbe6e07b2124c25e44f17917
whdesigns/Python3
/1-basics/2-guis/1-classes-and-objects/Grid-Intro/DropDown-Menu/bot.py
952
4.21875
4
from tkinter import * # | CREATING DROP DOWN MENUS | def doNothing(): print("ok ok I won't...") root = Tk() menu = Menu(root) root.config(menu=menu) #States that we're setting up a menu and its equal the variable declared above. subMenu = Menu(root) menu.add_cascade(label="File", menu=subMenu) # This is the na...
efc08c013e87c66de4bb57df3e5e42800573bef4
un4ckn0wl3z/pythonpract
/advance_buit-in/any_and_all.py
615
3.984375
4
friends = [ { "name": "Anuwat", "location": "Nakhon Si Thammarat" }, { "name": "Pansa", "location": "Chonburi" }, { "name": "Surachad", "location": "Phattalung" }, { "name": "Chaiyapat", "location": "Phuket" } ] your_locat...
620b25ea4f1c0a0f76a5c5c6959b906688065cc8
greenteawarrior/blackjack
/blackjack_func.py
6,809
3.84375
4
import random #emilywang #softdes spring 2013 #functional programming #blackjack #making a deck def makedeck(howmanydecks=1): deck = [] #initial value of deck #an element of deck... [name of suit, [name of card, vlaue of card]] # [string, [string, integer]] #each element of the name lists is.. [name of...
ba4873664408a1df566cb43bd606471e0e3d4271
ychalier/dice
/dice/misc/progress_bar.py
2,521
4.09375
4
import threading import queue import time class ProgressThread(threading.Thread): """ Basic utility to show progress over an iterative task. """ def __init__(self, q, total): super().__init__() self.q = q self.total = total self.current = 0 def run(self): ...
63e5790860586d29346a835dc01dc8db49978825
junjiegithub/test001
/20220927/break01.py
341
3.765625
4
#break:当某些条件成立,退出整个循环 #循环吃5个苹果,吃完第3个吃饱了,第四个和第5个不吃了(不执行) --==4或>3 i=1 while i<=5: #条件:如果吃到4或>3打印吃饱了,不吃了 if i==4: print('吃饱了,不吃了') break print(f'吃了第{i}个苹果') i+=1
e592f0dfd12297e08989f05a44367e8d26ed13fa
Peter1509/Homework05
/Homework_05/PostsDefault_table.py
611
3.53125
4
from smartninja_sql.sqlite import SQLiteDatabase db = SQLiteDatabase("BlogDB_main.sqlite") db.execute("""CREATE TABLE IF NOT EXISTS Posts_Default( PostDefaultId integer primary key autoincrement, PostName text, PostText text); """) postname = "Ha...
5dc186a389b17d25fee07aaf000c3b5c22aab5aa
Aasthaengg/IBMdataset
/Python_codes/p02627/s933475021.py
68
3.796875
4
a=input() if('a'<=a and 'z'>=a): print('a') else: print('A')
39f584038856a18d6928acc63a7c53db93142b64
xmaseve/Lambda
/lambda.py
466
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 04 20:32:29 2016 @author: YI """ #the usage of lambda list1=[1,2,6,4] list2=[3,4,2,6] data=zip(list1,list2) #data sorted by the first element of the tuple data.sort() #output: [(1, 3), (2, 4), (4, 6), (6, 2)] #sort by the second element data.sort(key=l...
3ccaf2b37b094fc6081ee9563edc5c8c3dd2ff23
Ti1mmy/ICS-201
/Loops 1/Loops 1 - 1.py
544
4.5625
5
# Create a program that will ask the user for a word. The program will iterate through the string and print out each character except for the vowels. word = input('Please type in a word: ') # vowels = ['A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'] # doesn't work for replace(), therefore used string include_y = i...
e861625fc7b2bf67b92d898041d31b20d82a84be
JeaneC/jsnake
/snake.py
2,416
3.5625
4
import pygame from pygame.sprite import Sprite from pygame.sprite import Group from turnPoint import TurnPoint class Snake(Sprite): """A class to represent the snake""" def __init__(self, ai_settings, screen, stats): """Initialize thhe snake.""" super(Snake, self).__init__() self.scree...
c85c222303954ec3605c30ef6f266c6a4f5ff8c0
amartini93/materia_python
/Actividades/AC04/13622625_AldoMartini.py
2,260
4.09375
4
# coding=utf-8 # Completen los métodos # Les estamos dando un empujoncito con la lectura del input # Al usar la clausula: "with open('sonda.txt', 'r') as f", el archivo se cierra automáticamente al salir de la función. def sonda(): list_minerals = [] dict_minerals = {} with open('sonda.txt', 'r') as f: ...
a4781c4e37baa74bd08c8879903e4431e3b2c598
minwiley/sqlalchemy_SurfsUp-
/app_mw.py
4,822
3.5625
4
# Step 2 - Climate App # Now that you have completed your initial analysis, design a Flask API based on the queries that you have just developed. # Use FLASK to create your routes. # Dependencies import numpy as np import pandas as pd import datetime as dt import sqlalchemy from sqlalchemy.ext.automap import automap_...
62a3ca2fe58422f0481cf19512042382a40f40e6
vaishnavinambiar/Function-abstraction-exercises
/tc_factorial.py
355
3.578125
4
import unittest def recur_factorial(n): if n ==1: return n else: return n*recur_factorial(n-1) class MyTest(unittest.TestCase): def test1_fact(self): self.assertEqual(recur_factorial(5), 120) def test2_fact(self): self.assertEqual(recur_factorial(2), 3) if __name__ ...
98976316c5a937d6343f7c162d9976886d9e5fa9
eshatwo/Python
/python_OOP/car.py
1,044
3.71875
4
class Car: def __init__(self, price, speed, fuel, milaege): self.price = price self.speed = speed self.fuel = fuel self.milaege = milaege self.tax = 0 def taxing(self): if self.price > 10000: self.tax = 0.15 else: self.tax = 0.12 ...
9a153b22783fe79ca672f9658752297d489c47c8
brat-chndr2001/pythonproject
/Order Details(Pricing)/orderdetails.py
1,777
4.21875
4
print("CHOOSE YOUR FAVOURITE RESTAURANT") print("----------------------") print("The list of reataurants are:") print("1) Khana khajana") print("2) Olive garden") print("3) Karachi darbar") x = input("Choose your desired restaurant number: ") if x == "1": print("The meals in the restaurant are :") prin...
e7df0a1fa87b49205f84adeac3be75a2636fff0c
Helloworld616/algorithm
/SWEA/Sort/1966_숫자를정렬하자/sol5.py
820
3.78125
4
import sys sys.stdin = open('input.txt') def merge_sort(numbers): N = len(numbers) if N < 2: return numbers mid_idx = N // 2 left = numbers[:mid_idx] right = numbers[mid_idx:] sorted_left = merge_sort(left) sorted_right = merge_sort(right) merged = [] l = r = 0 while...
49739785e85560f74bf7e0560d2ee134ad2bcd38
davidsuffolk/Python-Input-Sorter
/6.1 Programming Assignment.py
2,058
4.40625
4
#File: 6.1 Programming Assignment #Name: David Suffolk #Date: April 19th, 2019 #Course: DSC510-T303 Introduction to Programming (2195-1) #Assignment Number: 6.1 #Purpose: Gather temperature inputs, validate their value, return largest, smallest, and total entries. #Create an empty list called temperatures temperatures...
950dc112f5d9bf8bd07bcc1d5967a9db9d0e6595
khadkasagar662/LabExercise1
/TkinterProject/Drop down.py
360
3.8125
4
from tkinter import * root =Tk() root.title('Drop down Menu') def show(): label =Label(root, text=clicked.get()).pack() clicked =StringVar() clicked.set("Monday") drop =OptionMenu(root,clicked,"Monday","Tuesday","Wednesday","Thrusday","Friday","saturday","sunday") drop.pack() mybutton =Button(root, text="show sel...
fc45793670553a1afd0c9b465c9010a76f6f80f2
AJ228/Freshman-Immigration-coding-challenges
/Two-sum.py
1,059
3.65625
4
class Solution(object): def twoSum(self, nums, target): #Challenge parameters """ :type nums: List[int] :type target: int :rtype: List[int] """ answer = [] #Blank list to store answer indices for i in range (len(nums)-1): #Checks all combinati...
c412079838d178c42d06ff67bbdffea18141e89d
hakaorson/CodePractise
/Dynamic/backpack.py
2,168
3.53125
4
''' Lintcode https://www.lintcode.com/problem/?tag=backpack 一系列的背包问题 ''' class Solution(): def backPack_recursive(self, m, A): # 重量等于价值的背包问题,相当于背包装满问题 if m == 0 or len(A) == 0: return 0 stuff = A[0] if stuff < m: return max(self.backPack(m-A[0], A[1:])+A[0...
9dab4529c8aff8acf8a05eeb8b294e218980b4bb
ai-kmu/etc
/algorithm/2020/0923_Rotate_Image/myunghak.py
442
3.625
4
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ 2차원 행렬의 경우 reverse 후에 transpose하면 시계방향으로 90도 회전하는 in-place 알고리즘이 됨 """ matrix.reverse() for i in range(0,len(matrix)): for j in range(1,len(matrix[i])-i): matrix[i][i+j], ma...
70bbd2e1f1db52a069e6794d68964457bdf8ad92
QI1002/exampool
/Leetcode/145.py
2,620
3.640625
4
#145. Binary Time Postorder Traversal class stack: def __init__(self): self.body = [] def push(self, data): self.body.append(data) def pop(self): if (len(self.body) == 0): return None else: return self.body.pop() def isEmpty(self): ret...
09af53f4147116607b487aa0abcc5003b8c78828
saikir/my_first_python
/demo.py
1,018
4.46875
4
print ('hi') print(22/7) #comment """multiline comment can be done by keeping three double quotes""" print(22//7) #can be called floor division output is 3. print(22%7) #called as modulo division gives remainder. print("test 'ducking' string"); #Double quotes only need to be escaped in double quote strings, and the sam...
e50832c7f6b01cdf0023b218df561129133cbda8
ayushmittal02/Python-Basics
/Intro_to_Pandas.ipynb
9,339
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # In[ ]: flights=pd.read_csv("flights.csv") # In[ ]: flights.shape # In[ ]: flights.head() #Prints first five rows of the dataset # # Reading selected columns or rows from the dataframe # In[ ]: flights=pd.read_csv("flights.csv", us...
0053f470f420a7b96598925e499d6b362cd44f83
yukihirai0505/tutorial-program
/programming/python/machine-learning/basic.py
870
3.859375
4
# calculate print(1 - 2) print(4 * 5) print(7 / 5) print(3 ** 2) # check type print(type(10)) print(type(2.78)) print(type("hello")) # use variable x = 10 print(x) x = 100 print(x) y = 3.14 print(x * y) print(type(x * y)) # list a = [1, 2, 3, 4, 5] print(a) print(len(a)) print(a[0]) print(a[4]) a[4] = 99 print(a) pr...
0321662cfde748244a93de8a0b14f1763b7bf261
XaserAcheron/damnums
/damfont.py
1,070
3.796875
4
import sys MAX_DIGITS = 5 # [TODO] document this silly thing: def genfonts(prefix, width, height): yoffset = height - 2 for charindex in range(10): char = chr(65 + charindex); for numdigits in range(2, MAX_DIGITS+1): spritewidth = width * numdigits xoffset = int(spritewidth / 2) for digit in range(...
45996462a5f1670fc439054c4465b9f6e421ccbe
marri88/python-base
/FOR_WHILE/prob7.py
695
3.953125
4
even ='' odd='' for index, char in enumerate (['Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',]): if (index % 2 == 0): even += char else: odd += char print (odd) '''# 7. У вас всё тот же список имён: # names = ('Максат','Лязат','Д...
3b8befae3b0b76538e368179b319b2dad685da64
changray1201/AE402-Python
/算平均1.py
1,321
3.6875
4
scores = [] names = [] score = 0 n = int(input("請輸入全班學生人數")) #輸入人數 high = 0 low = 100 global highn,lown,avg avg = 0 highn = "" lown = "" def highscore(scores): high = 0 n = len(scores) for i in range(n) : if scores[i] >= high : high = scores[i] highn = names...
6c38fa20358c8aea5b4d73baa6203da0999f6e1f
acid9reen/Artezio
/Lesson_1/task04.py
397
4.09375
4
'''Count special strings''' def special_string_counter(list_): '''Return special strings count''' counter = 0 for str_ in list_: if len(str_) > 1 and str_[:1] == str_[-1:]: counter += 1 return counter def main(): '''Run special_string_counter function with user input''' ...
ad420cc5d043cc1cd78934c670dc00552b5788ab
zshuangyan/algorithm
/binary_tree.py
2,871
3.609375
4
class Node: def __init__(self, val): self.val = val self.left = None self.right = None class BinaryTree: def __init__(self, root=None): self.root = root def inOrder(self, node): if not node: return [] stack =...
07f7eb09c3f0ae0307d49af0b098436a37da57fe
TARRAKAN/python_things
/Grokking Deep Learning/chapter2/functions.py
763
3.71875
4
def elementwise_multiplication(vec_a, vec_b): assert(len(vec_a) == len(vec_b)) output = list() for i in range(len(vec_a)): output.append(vec_a[i] * vec_b[i]) return output def elementwise_addition(vec_a, vec_b): assert(len(vec_a) == len(vec_b)) output = list() for i in range(len(vec...
3cebb00b33da6da4bc8c2c4bd2eebd28732f4bea
VersionBeathon/Python_jerboa
/data_structures&&algorithms/question_about_dict.py
1,124
3.75
4
# _*_ coding:utf-8 _*_ # 将键(key)映射到多个值的字典(一键多值字典[multidict]) from collections import defaultdict from collections import OrderedDict import json d = { 'a': [1, 2, 3], 'b': [4, 5] } e = { 'a': {1, 2, 3}, 'b': {4, 5} } print(d) print(e) # 利用collections模块中的dafaultdict类创建字典(它会自动初始化第一个值) d = defaultdict(l...
bde9f2c11f5b5e741cb875329e410aed8a33993a
lukastencer/coursera-algorithms
/lesson2/llstack.py
1,568
3.6875
4
class llstack: class node(): next = None val = None def __init__(self,nextNode,val): self.next = nextNode self.val = val head = None iterIdx = None def __iter__(self): self.iterIdx=self.head ...
e45f36545c688ef44fb1ef36a177b969402bb3ab
CiaranGruber/Python-Tutorial-Solutions
/fahrenheit_to_celsius.py
201
3.765625
4
def main(): fahrenheit = int(input("Fahrenheit value: ")) celsius = (fahrenheit - 32) * 5 / 9 print(fahrenheit, "fahrenheit is", celsius, "celsius") if __name__ == "__main__": main()
95d9679265dd278433f8867571ee4d1590cf85c9
natemago/adventofcode2017
/day19_series_of_tubes/solution.py
2,350
3.71875
4
def read_input(f): grid = [] with open(f) as inpf: for line in inpf: grid.append([c for c in line]) return grid MN = {(-1,0):'up', (0,1):'right', (1,0):'down', (0,-1):'left'} def follow_diagram(diagram): moves = [[-1,0], [0,1], [1,0], [0,-1]] # up, right, down, left y...
2f7fa2f3a4212c9984bcaeb23eae795b0d60eb85
JPCARVALH0/python_equacao_2_grau
/calculo.py
386
3.78125
4
import funcoes_calculo print("digite respectivamente os valores correspodentes a A, B, e C\npor favor utilize números por extenso\npor exemplo no lugar de 5/2 escreva 2.5 utilizando ponto no lugar de vírgula\ncerto 2.5/errado 2,5") A = float(input("digite A ")) B = float(input("digite B ")) C = float(input("digite C ")...
f745af7ec18b1a21f7a3fde9cd3d748234c64d1c
AaronTengDeChuan/leetcode
/leetcode/110.BalancedBinaryTree.py
1,143
3.859375
4
#!usr/bin/env python #-*-coding:utf-8-*- import sys class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getHeight(self, root): if root == None: return 0 left = self.getHeight(root.left) ...
da7624b23578e48d705f4683f477547d84ad4489
borjas93/mi_primer_programa
/agenda.py
701
4.0625
4
''' Ejercicio de una agenda de telefonos usando listas. ''' agenda = [] while True: print('') print('¿Que quieres hacer?') print('') accion = input('Añadir numero [A] / Consultar numero [C] / Corregir numero [Corregir] / Salir [S] ').capitalize() print('') if accion == 'A': nombre = i...
4555f47390891184f0b58db64f44923a0d5c2976
Leu-s/Simple-text-editor
/tk-Редактор текста.py
1,762
3.75
4
import tkinter as tk from tkinter .filedialog import askopenfilename from tkinter .filedialog import asksaveasfilename def open_file(): """Открывает файл для редактирования""" filepath = askopenfilename( filetypes=[('Text files', '*.txt'), ('All Files', '*.*')] ) if not filepath: retur...
f605e555115ad4ded79098f83ed2e75bb5dbba05
FelixDavidson/MyPythonPrograms
/ThinkPython/5_4.py
400
4.0625
4
def is_triangle(a, b, c): if a > b + c or b > a + c or c > a + b: print 'No' else: print 'Yes' def try_tri(): print 'You have three sticks. Choose 3 lengths that make a triangle.' a = int(raw_input('Choose a length for a:\n')) b = int(raw_input('Choose a length for b:\n')) c = ...
fcdf944e416674eb0cdf9e2002bf18180af71e1a
D-DanielS/MetodosNumericos
/metodoBisecion.py
699
3.765625
4
from f import f xi = float(raw_input("Ingrese xi: ")) xs = float(raw_input("Ingrese xs: ")) error = float(raw_input("Ingrese error: ")) xa = (xi + xs)/2.0 i = 0 itmax = 100 print("\n{:^10}{:^10}{:^10}{:^10}{:^10}{:^10}{:^10} ".format("i","xi","xs", "xa", "signo", "cambio", "error")) while(abs( f(xa)) > error and i ...
abc9b9641fa462186d018f5ebed85fc62aba77e3
hotai1806/reversigame
/array.py
1,949
3.59375
4
board = [['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', 'W', 'B', '.', '.', '.'], ['.', '.', '.', 'B', 'W', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '.', '.', '.', '.', '.'], ['.', '.', '.', '...
80c9f8399223a7203328cb3dd8465f70502b1d65
Nehanavgurukul/function_ques
/power_of_number.py
276
4.21875
4
def power_of_number(num1,num2): if(num2>0 and num1>0): power_of_number=num1**num2 a=power_of_number return a else: return 0 n1=int(input("enter the number")) n2=int(input("enter the number")) print(power_of_number(n1,n2))
3abe52970d58dd41884c9ef93c8bfa6a6f941d39
Venkat-Rajgopal/Python_Tricks_and_OOP
/Algorithms/change.py
528
3.921875
4
# Uses python3 import sys """ Find the minimum number of coins needed to change the input value into coins with denominations 1, 5, 10 """ def get_change(m): large = 10 mid = 5 small = 1 result = 0 coins = [large, mid, small] while m != 0: for coin in coins: if...
fa15218bc842f18a3474c3a78490551ddfe0ae16
saood321/ebmpFYP
/actual/MusicSelection.py
3,133
3.578125
4
import actual.DataBaseConnect mydb,mycursor=actual.DataBaseConnect.database() """ @requires: songType means happy,sad etc username of user and limit represents how many songs we want to fetch @functionality: This function select 3 top rated songs from user history @effect: returns limit of history song """ def history...
f1658375f4d27a43b920464319cfae6f142a5521
sauravghoshroy/human-beahviour-prediction
/mypackage/function.py
513
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Name of the project: Individual Programming Exercise: (IPE) # Description: A program that "predicts" human behavior using a simple game. # File Name: function.py # File Description: Python code of the function that generates random numbers for the IPE program. # Auth...
b978e78dd713e2457bdbf275679a5505e4502683
rafal1996/CodeWars
/Array.diff.py
385
3.890625
4
# Your goal in this kata is to implement a difference function, # which subtracts one list from another and returns the result. # It should remove all values from list a, which are present in list b keeping their order. # array_diff([1,2],[1]) == [2] def array_diff(a, b): return [x for x in a if x not in b] ...
82f2ece78281e64b2d36e45eb3eeab959bb9ce4f
boknowswiki/mytraning
/lintcode/python/0652_factorization.py
1,235
3.640625
4
#!/usr/bin/python -t from math import sqrt class Solution: """ @param n: An integer @return: a list of combination """ def getFactors(self, num): res = [] def dfs(start, n, tmp): for i in range(start, int(sqrt(n))+1): if n % i == 0: d...
5427e76091a62fd5af90933f826e92c309879666
spizzirri/fundamentos-machine-learning
/_numpy.py
1,863
4.1875
4
import numpy as np """ Biblioteca de Python comúnmente usada en la ciencias de datos y aprendizaje automático (Machine Learning). Proporciona una estructura de datos de matriz que tiene diversos beneficios sobre las listas regulares. """ print("** NUMPY **\n") print("Creando un arreglo") arreglo = np.array([10, 30,...
7333c228e33d17762e3a60f676061ac8cfee07e1
ulysses-sl/algorithm-implementations
/python/linkedlist/StackQueue.py
2,997
3.59375
4
from LinkedList import SinglyLinkedList, DoublyLinkedList class SLStack: def __init__(self): self.store = None self.count = 0 def push(self, v): x = SinglyLinkedList(v) x.next = self.store self.count += 1 self.store = x def pop(self): if self.store...
b61ebe33d3692b88e494800b6863a2fe5494e38a
annpia92/Tester_School
/czykwadrat.py
166
3.5625
4
x = 101 for i in range(x+1): if i**2==x: print('podana liczba jest kwadratem', i) break else: print('podana liczba nie jest kwadratem')
1d88f94e9757ea3359138e8c55d3f018124ea716
jaskaran-23/Combat-Tanks
/tank10.py
810
3.53125
4
def pause(): paused=True message_to_screen("Paused",red,-100,size="large") message_to_screen("Press C to continue or Q to quit.",black,25,"medium") pygame.display.update() while paused: for event in pygame.event.get(): if event.type==pygame.QUIT: pygame.qui...
b18dc02fb769f4706edc70760e99d9d5073e559f
my-xh/DesignPattern
/03行为型模式/18备忘模式/模拟TodoList.py
2,032
4.09375
4
class TodoList: """待办清单""" def __init__(self): self.__work_items = [] def write_work_item(self, item): self.__work_items.append(item) def get_work_items(self): return self.__work_items class TodoListCaretaker: """ToDoList管理类""" def __init__(self): self.__tod...
723c47fc8bf9afc4e56b0a435ddff15beae98792
edson-gonzales/SICARIOS
/test/customer_test.py
3,080
3.984375
4
#customer_test.py __author__ = 'Roy Ortiz' import unittest from admin_module.user_module.customer import Customer class CustomerTest(unittest.TestCase): def test_create_a_new_customer_instance(self): """ Will verify that a new customer instance is an instance of Customer class ...
a12371dc955643632c3b3c88ac9d03d1f781a58f
Dragonriser/DSA_Practice
/Arrays/MaxSubSum.py
408
3.703125
4
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. #CODE: class Solution: def maxSubArray(self, nums: List[int]) -> int: curSum = maxSum = nums[0] for num in nums[1:]: curSum = max(num, curSum + num) ...
a401126d4d1c119f0fd1a3e25f500c196b1e423e
nflondo/myprog
/python/workbook/sort_int.py
721
4.28125
4
#!/usr/bin/python3 # Read 3 ints from user, and display them in sorted order # use built-in function min() and max() user_input = input("Enter 3 numbers (separated by a space): ") list_num = user_input.split() #splits on space by default #print("list_num: ", list_num) if len(list_num) == 3 : min_number = min(int(l...
c15e16fb0f780640010e13cbc8f5e03288ae1c66
ginaschmalzle/fibonacci
/fibo_func.py
275
3.796875
4
#!/usr/bin/python #find fibonocci number of the 10th element start=[0,1,1] # Fn(0), Fn(1), Fn(2) n = 10 def get_fibo(n, start): i = 3 fn1=start[1] fn2=start[2] while ( i <= n): fn = fn1 + fn2 fn1 = fn2 fn2 = fn i = i+1 return fn print get_fibo(n, start)
64ff067f003bd8be6d9c09c6df40cf9c007293d0
robertsdionne/clrs
/ch02/linear_search.py
587
3.671875
4
#!/usr/bin/env python import argparse def linear_search(items, value): for i in xrange(0, len(items)): if value == items[i]: return i return None def main(): commands = argparse.ArgumentParser(description = 'Insertion sort.') commands.add_argument( 'integers', metavar = 'N', type = int, nar...
33e907839dbdfaa2840584850e217f2a8551d1db
QuentinDuval/PythonExperiments
/greedy/CoinPiles.py
3,999
4.0625
4
""" https://practice.geeksforgeeks.org/problems/coin-piles/0 There are N piles of coins each containing Ai (1<=i<=N) coins. Now, you have to adjust the number of coins in each pile such that for any two pile, if a be the number of coins in first pile and b is the number of coins in second pile then |a-b|<=K. In ord...
2314a35958a26dceadecb84ad90cc131aa88a5e8
AshkenSC/Programming-Practice
/LeetCode/0150. Evaluate Reverse Polish Notation.py
974
3.625
4
''' 150. Evaluate Reverse Polish Notation 根据 逆波兰表示法,求表达式的值 思路:用栈存储数字,遇到运算符就取出栈顶两个计算,放进栈里。 ''' class Solution: def evalRPN(self, tokens: List[str]) -> int: num_stack = list() for token in tokens: if token == '+': a = num_stack.pop() b = num_stack.pop() ...
bfe8f78a6a64ebef5e6f33a2afb2792fe77628a1
ictcubeMENA/Training_one
/codewars/7kyu/doha22/shortest_word/bench_test.py
1,832
3.6875
4
from shortest_word import find_short from shortest_word import find_short ,find_short2 def test(benchmark): assert benchmark(find_short, "bitcoin take over the world maybe who knows perhaps") == 3 def test2(benchmark): assert benchmark(find_short2, "bitcoin take over the world maybe who knows perhaps") == 3...
4d566b935b38a51df7c7eb0bb193aca170952b6e
Adarsh-Liju/Python-Course
/inheritance_sample.py
707
4.5
4
''' Inheritance Syntax: class Base(object) Base_Body Derived(Base) Derived_Body ''' #Example 1 class Parent: pass class Son(Parent): pass print(issubclass(Son,Parent)) # issubclass(Derived_Class,Base_Class) : returns True #Example 2 class Debian: def rel_date1(self): print("Debian was re...
068ce0e9e636aa44d071ab73b299109dd8928328
Iruyan-Zak/py-tmp
/position.py
303
3.78125
4
class Vector2: def __init__(self, x, y): self.x = x self.y = y def __add__(self, v): return Vector2(self.x + v.x, self.y + v.y) def __repr__(self): return "Vector2({},{})".format(self.x, self.y) v1 = Vector2(2,5) v2 = Vector2(3.5, -1) v1 += v2 print(v1)
1b56ac9127a28ba87b29d11601a200783eb3cdf7
antonkrupin/algorithms
/28_tasks/TreeOfLife.py
3,680
3.6875
4
def TreeOfLife(treeHeight, treeWidth, years, tree): for x in range(len(tree)): replacedString = tree[x].replace('+','1') replacedString = replacedString.replace('.','0') tree[x] = replacedString yearsCounter = 0 while(yearsCounter < years): yearsCounter += 1 ...
d1900cf4ef9a7928120d6288e562ac9107d9ead1
DenysShvets/LaboratoryWork8
/1.3.1(2).py
1,178
3.84375
4
import numpy as np while True: while True: try: n, m = 3,3 #задаем размерность матрицы a = np.zeros((n, m), dtype=int) #выделяем место для массива b = np.zeros((m, n), dtype=int) #выделяем место для массива break except ValueError:...
0f25678348d22c06de6b9bfab6d53757fe8fea7f
ChronicStone/Python_philippe
/le_wagon_exercises/ex4_playgroundRefactoring/playground_refactoring.py
339
3.921875
4
def circle_math(radius): return [3.141592653589793*(radius*2), 3.141592653589793*(radius*radius)] print(circle_math(3)) values = circle_math(5) print(f"Radius=5 => Perimeter={round(values[0], 1)}, Area={round(values[1], 1)}") values = circle_math(6) print(f"Radius=6 => Perimeter={round(values[0], 1)}, Area={rou...
8a2bf00edc8b65bcdff4f1b6b8533ec1b8aba9d8
goalstrack/python-training-Day1
/python-training/arithmaticoperation.py
165
3.65625
4
x=12.4 y=2.7 print('sum is= ',x+y) print(x-y) print(x*y) print(x/y) #floor division print(x//y) #power of operator print(x**y) print(x%y)
716339cd9e1994e296c0a15d168cfa83845dde47
chris-purcell/lpthw
/scrape.py
367
3.5
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup url = "http://www.rackspace.com" r = requests.get(url) soup = BeautifulSoup(r.content) links = soup.find_all("a") for link in links: print "<a href='%s'>%s</a>" %(link.get("href"), link.text) g_data = soup.find_all("div", {"class": "info"}) ...
d1d38e78c193e8caac9b1ab0345f75fe36452931
deniseicorrea/Aulas-de-Python
/python/ex040.py
295
3.921875
4
n1 = float(input('Digite a primeira nota: ')) n2 = float(input('Digite a segunda nota: ')) media = (n1 + n2) / 2 print(f'A média desse aluno é {media}') if media < 5.0: print('Reprovado') elif media >= 5.0 and media < 7: print('Recuperaçao') elif media >= 7.0: print('Aprovado')
be782e6b776ad1d579f9e02c02822b37a7334f8c
AbiramiRavichandran/DataStructures
/Tree/MirrorTree.py
1,180
3.796875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def mirror(self): lnode = self.right.mirror() if self.right else None rnode = self.left.mirror() if self.left else None self.left = lnode self.right = rnode ...
8cc94edbe41ae017b7593618b5df0b4e20da16d4
eMUQI/Python-study
/python_book/basics/chapter04_list_operation/04-01.py
132
3.84375
4
list_of_pizza = ["pizza1","pizza2","pizza3"] for pizza in list_of_pizza: print("I like %s"%pizza) print("I really love pizza!")
5d67061ad2e0b2c36f2a6e7d6772618799c689db
gullihans/100DaysOfCode
/Day23/car_manager.py
272
3.515625
4
from turtle import Turtle import random COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 class CarManager(Turtle): def __init__(self): super().__init__() self.color(random.choice(COLORS))
930b8c75369499186b55a83d141b04859d676a0e
michaelkornblum/python-studies
/object-oriented/cat.py
682
4.46875
4
#Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats cat1 = Cat('Michael', 50) cat2 = Cat('Sheila', 52) cat3 = Cat('Roosevelt', 15) # 2 Create a function that finds the oldest cat def fin...
9ecbd36f8882e44edd90a870151fd529eda944e0
RafaelMarinheiro/CS5220-MatMul
/lecture/lec01plot.py
1,498
4.125
4
import matplotlib.pyplot as plt import numpy as np def make_speedup_plot(n, rmax, tc, tt): """Plots speedup for student counting exercise. Plots the speedup for counting a class of students in parallel by rows (assuming each row has equal student counts) vs just counting the students. Args: ...
9922b6dee796e31ce4906177d9cdf08bcefc578e
BrindhaS/Python-Problems
/strings.py
381
3.734375
4
def substrings(string): length = len(string)+1 return [string[x:y] for x in range(length) for y in range(length) if string[x:y]] x=int(input('Enter test cases')) y=int(input('Enter length')) while(x>0): s = input('Enter string') lst = substrings(s) new_list = list(filter(lambda w:w[...
9cbc562d5da3be23506d70cd78e61af7733bdf6e
Nika-C/Bioinformatics_Genome-Answers
/bioinformatics_2_2.py
101
3.78125
4
Str = raw_input('Enter a string: ') L = list(Str) print 'The string length is ' + str(len(L)) + '.'
7d7e4a0ca5efbab70b87cdbd62f5b93475b10afb
GorobetsYury/Python_beginning
/lesson_1_task_3.py
400
3.890625
4
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. Например, # пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. n = int(input('Введите число n: ')) nn = n*10 + n nnn = n*100 + nn sum_ = n + nn + nnn print(f'Сумма чисел n + nn + nnn равна: {n} + {nn} + {nnn} = {sum_}')
09a678b800dd6b50d7b9f711e38f24afd2713137
xinbeiliu/leetcode_easy_collection
/array/plus_one.py
781
4.03125
4
# Given a non-empty array of digits representing a non-negative integer, plus one to # the integer. The digits are stored such that the most significant digit is at the # head of the list, and each element in the array contain a single digit. You may # assume the integer does not contain any leading zero, except the nu...
70cbd0ab6a8a23cb07fcb7124946c7fc9a64b1c8
ritwikbera/leetcode
/quickselect.py
863
3.515625
4
import random def Partition(a): if len(a)==1: return([],a[0],[]) if len(a)==2: if a[0]<=a[1]: return([],a[0],a[1]) else: return([],a[1],a[0]) p = random.randint(0,len(a)-1) pivot = a[p] right = [] left = [] for i in range(len(a)): if not i == p: if a[i] > piv...
3d6e94607ecbf3b77af5c0c11086fa107d7ab2aa
PatrickUncle/python
/猜数字欢乐游戏.py
442
3.859375
4
import random #生成随机数 x = random.randint(0,100) #使用while进行无限循环 while 1: #获取用户输入 guess = input("请输入您的猜想数字:") guess = int(guess) #判断用户输入数字与随机数的大小相等关系 if guess == x: print("you are so smart!") break else: if guess < x: print("small,try again") else: ...
d40bd002df923296a879d2ff2ade45096d25477d
bswathireddy/learning
/leetcode/intersection-lists.py
329
3.65625
4
def intersection(nums1, nums2): output = [] i = 0 while i <= len(nums1)-1: for j in nums2: if nums1[i] == j: if j not in output: output.append(j) else: continue i += 1 return output print(intersection(...
e047b97c9bfbad4535585f198882f88d1c8bc34a
rayandas/100Python
/Day3/13.py
441
4
4
''' Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 ''' w = input() letter, digit = 0, 0 for i in w: if (i>='a' and i<='z') or (i>='A' and i<='Z'): ...