blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c1ff16c07e439787af8778e3663f8cc24cb0dc97
ragvri/python-snippets
/threading/basics.py
547
4.03125
4
import threading # threading allows us to create threads in python # threads allows a program to run multiple operations concurently at the same process space def first_thread(): print("First thread") return a = threading.Thread(name="first thread", target=first_thread) # name gives ...
dd8a9d781c745c1c6bfd4fe409bb412763f54e99
conradylx/Python_Course
/17.03.2021/Flame/flame.py
2,142
4.1875
4
# FLAMES to popularna gra, której nazwa postała od akronimu: # Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. # Choć gra nie pozwala dokładnie przewidzieć przyszłości to może sprawdzić się jako andrzejkowa wróżba. def start_game(): """Main paragraph which is responsible for launching every function""" ...
d8c3cd2323380a138ac9248841cf8bbae6ae46b7
sudoheader/TAOD
/letter_counter_app.py
492
4.21875
4
#!/usr/bin/env python3 print("Welcome to the Letter Counter App\n") name = input("What is your name: ").title().strip() print("Hello " + name + "!") print("I will count the number of times that a specific letter occurs in a message.\n") message = input("Please enter a message: ").lower() letter = input("Which lette...
f31cdd1ba0717325cf22d02b3ce11881d7b1a8de
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_53/581.py
543
3.515625
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- import sys def judge(N, K): # print "N:" + str(N) # print "K:" + str(K) return ((K + 1) % (2**N)) == 0 casenum = int(sys.stdin.readline().rstrip()) testcases = [] for line in sys.stdin.readlines(): line = line.rstrip() testcases.append(line) for t...
e0fc12f8c21a87b1217ad2f61c1d6994fe7e4c49
StepykoTatyana/Memorization_tool
/Update_the_flashcards.py
6,931
4
4
# 3/4 """Different Query object methods can give access to the table entries. The all() method returns a list of all table entries, update({<mapped class attribute>:<new value>}) replaces the existing value with a new value, delete() deletes query results. Take a look at how some of the methods can be applied: entries ...
f5f1f386f4cd2da3458a435ba3b790ca42076302
chaofan-zheng/tedu-python-demo
/month01/all_code/day08/exercise01.py
592
4.15625
4
""" 练习1:创建计算治愈比例的函数 confirmed = int(input("请输入确诊人数:")) cure = int(input("请输入治愈人数:")) cure_rate = cure / confirmed * 100 print("治愈比例为" + str(cure_rate) + "%") """ # 形式参数 def calculate_cure_ratio(confirmed, cure): """ 计算治愈比例 :param confirmed:确认人数 :param cure:治愈人数 :return:治愈比例...
83ebf080692eb2a55ca7f62ff7fd83cf67b53f5d
wxke/LeetCode-python
/643 子数组最大平均数 I.py
410
3.546875
4
子数组最大平均数 I class Solution: def findMaxAverage(self, nums, k): """ :type nums: List[int] :type k: int :rtype: float """ cont = sum(nums[:k]) list1 = [cont] for i in range(len(nums) - k ): a = cont-nums[i]+nums[i+k] li...
0c0778d20c800cc2a3b7f1e0f1fd41719ff4ade7
NickCampbell91/cse210-tc04
/hilo_template/hilo/game/director.py
1,592
3.625
4
from game.dealer import Dealer class Director: def __init__(self): self.keep_playing = True self.score = 300 self.dealer = Dealer() self.current_card = 0 def start_game(self): while self.keep_playing: #self.get_inputs() #self.do_upd...
7a4921853729182f25e1aae5e611e9d49a71fbb6
josephduarte104/Python-for-Everybody-PY4E-exercise
/ex_08_04.py
669
4.28125
4
"""8.4 Open the file romeo.txt and read it line by line.""" fname = input("Enter file name: ") wordlist = [] fh = open(fname) """For each line, split the line into a list of words using the split() method. The program should build a list of words.""" for line in fh: line = line.split() """For each...
bbca91c9ee7a327229e8229b6809639db0393daf
rogerlindberg/simple-review
/simplereview/json.py
753
3.5625
4
def json_value(python_value): if isinstance(python_value, int): return str(python_value) else: return '"%s"' % _string_escape(python_value) def _string_escape(string): replacements = ( ('\\' , '\\\\'), ('"' , '\\"' ), ('/' , '\\/' ), ('\b' , '\\b' ), ...
74fb43b729f5117c2969e0d32bce8fe1f424a89a
cheverebe/shadows
/LAB/shadow_detection/step3B.py
750
3.5
4
# classify the pixels with lower values in both L and B planes as shadow # pixels and others as non-shadow pixels. import cv2 class Step3B(object): def __init__(self): pass def run(self, image): l, a, b = cv2.split(image) maxval = 255 # L channel l_mean, l_stddev = c...
92de805f2507ffaaa82bdeaf451e15b8b21212db
Wei-Mao/Assignments-for-Algorithmic-Toolbox
/Greedy Algorithms/Collecting Signatures/collecting_signatures.py
1,087
3.90625
4
# python3 from collections import namedtuple from sys import stdin from typing import List Segment = namedtuple('Segment', ['start', 'end']) def is_point_in_seg(point: int, seg: Segment) -> bool: return seg.start <= point <= seg.end def compute_optimal_points(segments: Segment) -> List[Segment]: """ T...
959a256c0a93fb7c879baea2b6d8d470dec18fc4
grogsy/Python-HashTable
/buckets.py
1,775
3.65625
4
from linkedlist import LinkedList from nodes import HashNode class NoBucket(KeyError): pass class BucketHolder(LinkedList): '''A linked-list that holds other linked-lists(buckets)''' def _get_id(self, bucket_id): for bucket_node in self: bucket = bucket_node.value if buc...
697ba3aa40a21e1b0e9fb4eb24f8c9171c2a93ff
zz-zhang/some_leetcode_question
/source code/257. Binary Tree Paths.py
751
3.59375
4
from utils import TreeNode from typing import List, Optional class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: self.res = [] self.dfs(root, '') self.res = [s[2:] for s in self.res] return self.res def dfs(self, node, path): new_path = f'{...
d0308e8b5bf3bf182134363fdf5e0d9be808576e
chirayu11/python_learning
/code/sorting/insertion_sort.py
368
4.125
4
def insertion_sort(numbers): for i in range(1, len(numbers)): key = numbers[i] j = i - 1 while numbers[j] > key and j >= 0: numbers[j + 1] = numbers[j] j = j - 1 numbers[j + 1] = key return numbers def _swap_array_values(array, i, j): temp = array...
e39ff3e2843350c1c8614d8aca065d592a283812
shockflux/python_basics
/basic4.py
136
4.25
4
#area of circle using math module import math r=float(input("Enter radius of circle")) area=math.pi*r**2 print("area of circle =",area)
5b0cb93fe561c17b7587c36c25266da90cc88cbf
AshPan777/ICS33-Projects
/program1/program1/reachable.py
3,004
3.65625
4
# Submitter: nicholhh(Huynh, Nicholas) import goody import prompt from collections import defaultdict def read_graph(file : open) -> {str:{str}}: with file: line_list = [line.rstrip('\n') for line in file] nodes_dict = {} for each_line in line_list: if nodes_dict.get...
ffbb0c67816adf658f75522f93d11b888612cf24
TomasNiessner/Mi_primer_programa
/Datetime_1.py
365
3.6875
4
#Crea un programa que te diga la fecha de hace 5 días respecto a hoy, y el día de la semana. import datetime today = datetime.datetime.now() #Hoy past_5_days = datetime.timedelta(days=5) #Esto significa 5 días difference = today - past_5_days print("Hace 5 días era el día {} del {}".format(difference.weekday(), dif...
2185506e8ee54d5d857987c530bd11839e5434f0
povert/Programming
/python/装饰器实现单例/装饰器实现单例.py
604
3.765625
4
def SingleObject(cls): _instance = {} def _singleton(*args,**kwargs): # print(_instance) if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls] return _singleton @SingleObject class A(object): def __init__(self,name): self.name = ...
cb36899a59c6b71abef1c15e0d2a224d8c0ba605
SagnikAdusumilli/PycharmProjects
/iterEX.py
250
3.90625
4
# each point is a touple present inside the square touple square = ((10,8),(10,23),(25,23),(25,28)) # interators can be used to interate through complex data structures it = iter(square) print(next(it)) print(next(it)) print(next(it)) print(next(it))
ff14fd34c51ab03ba9b587c449ffb519153ac0c6
RansherSingh10/Compiler-Design
/FileOperations.py
2,423
3.515625
4
n = 10 def add(num,marks): f = open("student.txt", "a") f.write(num + " " + marks +"\n") f.close() def delete(num): f = open("student.txt", "r") txt = f.read() f.close() lines = txt.split('\n') lines = lines[0:len(lines)-1] n=-1 for i in lines: n+=1 ...
fc1863c9d52aeb479680be82aa4201694b9a0e21
rmoore2738/CS303e
/assignment4_rrm2738.py
1,599
4.28125
4
#Rebecca Moore RRM2738 #Question 1 print("I’m thinking of a number from 1 to 10000. Try to guess my \nnumber! (Enter 0 to stop playing.)") guess = input("Please enter your guess:") guess = int(guess) number = 1458 if guess == number: print("That's correct! You win! You guessed my number in X guesses.") while guess...
0ebf891610bcf5a256e6b2084edd44a11fcde7b1
PhoduCoder/code_to_death
/Factorial.py
243
3.984375
4
def factorial(x): fact=1 if(x==0): fact=1 for i in range(1,x+1): fact = fact*i return fact #print fact def main(): result = factorial(5) print result #factorial(8) if __name__ == "__main__": main()
77cd55de89a5c804f6da8bf882aaec5eba029b7f
erikdelange/Neural-networks-in-numpy
/backpropagation.py
1,177
4.59375
5
# Backpropagation example # A neural network of 1 layer with 1 node, without a bias. # Goal is to train the network so that W is such that input of X results in output of Y # Great explanation by Mikael Laine at https://www.youtube.com/watch?v=8d6jf7s6_Qs import matplotlib.pyplot as plt X = 1.50 # input Y = ...
0f523a09e0fc080d8bf05bf729046cf16e3790e9
wendah-snp/TimeConverter
/SOAL_2.PY
453
4.03125
4
def timeConverter(seconds): if seconds > 359999 or seconds < 0: print('Invalid Input!') elif type(seconds) != int: print('Invalid Input!') elif seconds <= 359999: HH = seconds // 3600 MM = (seconds % 3600) // 60 SS = (seconds % 3600) % 60 print('%d : ...
cfe03a014187ae31c608d1e860210e404cd3890c
stefanpostolache/pythonHandsOnExamples
/complete/example-3/main.py
2,555
3.828125
4
import matplotlib.pyplot as plt """ This module contains functions to create a graph of the averages of other graphs A graph is pair of lists of numbers, one list for the abscissas and another for the ordinates, both lists having the same size. """ def averages(graphs): """ Function that takes a list of grap...
03257eaa2a3f2dc507669adc8adcd1582b8f190f
megharana/EskoChallenge
/src/TrainProblem.py
5,210
4.03125
4
def min_dst(dst, queue): """ objective: function to find the vertex with minimum dist value, from the set of vertices still in queue @param : dist(containg inf for unvisited vertices) and queue(conatining all vertices) @returnValue : min_index(vertex with minimum distance value) """ minimum = fl...
629c43e56aa2ae6762182cec63b1093ff3bfd372
ViviTurtle/Code-Snippets
/Useful Code/Decorators/thead.py
1,148
4.125
4
#!/usr/bin/env python3 # Main source code was pulled from http://code.activestate.com/recipes/576684-simple-threading-decorator/ from threading import Thread def run_async_thread(func): """ Decorator to run a function in a seperate thread. Only use when variables and resources will not be modified in following code...
a72bafb8f0ff1404eb04d18f69d98168e7d46b29
kdeberk/advent-of-code
/python2016/day7.py
1,657
3.71875
4
# 2016, Day 7. # The input lines contain IPv7 addresses which each consist of 'inner' and 'outer' blocks. # These blocks can contain an ABBA or ABA substrings. # # Part 1: Count addresses for which at least one outer has an ABBA but no inner has one. # Part 2: Count addresses for which an outer has an ABA and an inner ...
d8dd6328c10868f42dafc769c031b083ba07834c
jhglick/comp120-sp21-lab11
/list_linked.py
3,253
4.25
4
# File: list_linked.py # Date: April 13, 2021 # Author: COMP 120 class # Description: Linked list implementation of List ADT. class Node: def __init__(self, item, next = None): """ Constructor. Creates a node.""" self.next = next self.item = item class LinkedList: def __init__(self): ...
97d5ecb3721b4fd7beeb1b38eaf53780e60095b0
maverickmishra/x9115NVN
/hw/code/3/employee.py
863
3.875
4
#Exercise on Employee class import os ##os.system('clear') class Employee(object): def __init__(self,name,age): self.name = name self.age = age def __repr__(self): return "%s(name='%s',age=%s)" \ % (self.__class__.__name__,self.name,self.age) de...
10776f22a8f9f5646293f741900523b88ada482a
ericgarig/daily-coding-problem
/013-length-longest-substring-with-distinct-chars.py
885
4.09375
4
""" Daily Coding Problem - 2018-10-20. Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb". """ def longest_substring(num_chars, some_str): """...
33a012e46ec2d049f49604bc4d33fe02ee9e88ba
AmbystomaMexicanum/pcc2e-exerc
/src/ch_06/e_6_3.py
568
3.5625
4
term_defins = { 'integer': 'A number without a decimal point (.)', 'float': 'A number with a decimal point (.)', 'list': 'A data structure that stores items in a specific order', 'dictionary': 'A data structure that stores PAIRS of items', 'if-test': 'Test which results in a True/False val...
c0ce7155ee4a25244f86043ecd11f72e7ddc3ba6
zn-jba/Python-TicTacToe
/Problems/Palindrome/main.py
223
3.984375
4
word = input() index = 0 r_index = len(word) - 1 for _ in range(len(word)): if word[index] != word[r_index]: print("Not palindrome") break index += 1 r_index -= 1 else: print("Palindrome")
5bc5c111958b820559341c6b082aad6d5083f89d
AleCoria94/Phyton
/ciclos.py
732
3.75
4
#SUMAR 10 veces un numero# #def multiplicar(n): # m=0 # for i in range(10): # m=m+n # return m #print (multiplicar (10)) #Implementar una sumatoria que reciba un numero enteroo n y devuelva la suma de todos los numeros del 0 al n #def sumatoria(n): # m=0 # for i in range(n+1): # m=m+i #...
d56230984050ffa5da4d0157cae8ab4bcf43a4db
neelesh1234/Python-Data-Analysis
/Course 3-3 Project/Project3.py
5,813
4.53125
5
""" Project for Week 3 of "Python Data Analysis". Read and write CSV files using a dictionary of dictionaries. Be sure to read the project description page for further information about the expected behavior of the program. """ import csv """ Problem 1: Reading the field names from a CSV file First, you will write a...
4403a7e4ab443f65ad89915b63a192bd27bf4e2b
Dawnlnz/data-structure-and-algorithm
/algorithm/SortingtAlgorithm.py
5,689
3.984375
4
""" 常用排序算法 1、冒泡排序 2、选择排序 3、插入排序 4、归并排序 5、快速排序 6、堆排序 """ # 冒泡排序bubble sort def bubbleSort(arr): length = len(arr) for i in range(1, length): for j in range(0, length-i): if arr[j+1] < arr[j]: temp = arr[j+1] arr[j+1] = arr[j] arr[j] = temp ...
6b27f200207eb302d8ec9504bca8be6a7157c6fe
Jose-Humberto-07/pythonFaculdade
/listas/futsal.py
1,355
3.78125
4
"""Construa um algoritmo em Python que receba o salario de jogares de um time de futsal em duas listas. Lista T, com o salário dos 5 titulares e lista R, com o salário dos 5 reservas. Em seguida retorne a soma, a média, o maior salário e o menor salário. Todas as informações devem ser discriminadas para time reserva,...
eddbe180d5d1b3b5ec8559228ac1fa1df303eb6f
PKpacheco/exec_roman_numerals
/roman_int.py
1,084
3.9375
4
import logging VALUES = { 'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1 } class RomanLetterInvalid(Exception): pass def get_roman_letter(): return str(input("Input roman letter: ")) def letter_validation(roman_letter): roman_letter = roman_letter.upper() if (roman_letter not...
0ed74bcb2d9e4abf0d7885dc53d61270bc87c964
berkcangumusisik/CourseBuddiesPython101
/Pratik Problemler/06 - Lists Seviye 1/03 - removeSecond.py
567
3.828125
4
"""remove_second Listeden ikinci elemanı kaldıran bir fonksiyon yazın .İkinci bir öğe yoksa, orijinal listeyi döndürün. Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir değil bu liste boş olmadığını varsayalım. """ def remove_second(my_list): if len(my_list) > 0: if len(m...
38365c8d7ab1ada30e608b2a1ff399e9d52e8961
glangetasq/FundClustering_Fall2020
/Tools/Labeling/define_levels.py
401
3.625
4
def define_levels(array): """returns High/ Mid/ Low categories based on 33%, 66%, 100% percentiles""" low_thresh = array.quantile(1/3) mid_thresh = array.quantile(2/3) temp = list() for i in array: if i <= low_thresh: temp.append('Low') elif i<= mid_thresh: ...
c1117b4ec678525c2b93e640618f37ad9b247b42
vishalmishra14/Leet-Code-solutions-in-python
/getNthFromLast.py
2,238
4.21875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def getNthF...
06f15e6f174e25bc4390c1ec01e261ed3b821bcf
r1606/TCC_Python_Ridalvo_2020_06
/CodigoRidalvo.py
2,583
3.53125
4
################################################# # Introdução à Programação com Python # Professor: Carlos Artur Guimarães # Aluno: Ridalvo Medeiros Alves de Oliveira ################################################# ################################################# # Importações do NUNPY, do PANDAS e do MATPOTLIB ...
92f1fe0b0ea2f69b96b9cd14fcaf5a101fb38e49
schirrecker/Codewars
/reverse.py
419
3.671875
4
def solve(s): spaces = [] i = 0 for c in s: if c == " ": spaces.append(i) i += 1 print(spaces) s_reverse = s[::-1] s_reverse = s_reverse.replace(" ", "") print(s_reverse) for i in spaces: s_reverse = s_reverse[:i] + ' ' + s_reverse[i:] ...
f96fa26eb390d082e02c000aa783e1bddc21bd78
AlexanderTankov/Music-player
/src/playlist_test.py
3,341
3.53125
4
import unittest from playlist import Playlist from song import Song class TestPlaylist(unittest.TestCase): def setUp(self): self.test_playlist = Playlist("Rock'n'roll") self.test_song = Song( "Hells Bells", "ACDC", "Hells Bells", 5, 309...
1cee2dd9ba2552fb90bc872b23575ec4ced47ad4
Eih3/otusDLP
/utils/database.py
876
3.5625
4
# -*- coding: utf-8 -*- import sqlite3 database_file = "utils/database.db" c = sqlite3.connect(database_file) print "Opened database successfully" class Database: def __init__(self): self.createTables() self.insertValues() self.closeDB() def createTables(self): try: ...
bbe53b704e12061d330c6c76a34fd91ef76e21a7
KampfWut/CodeGeneratedDuringLearning
/Python Encryption/02_ReverseCipher.py
251
4.0625
4
# Reverse Cipher print("\n> Reverse Cipher, input your message:") message = input("<<< ") translate = "" i = len(message) - 1 while i >= 0: translate = translate + message[i] i = i - 1 print("> Finish! Ciphertext is this:\n " + translate)
707aa65783b708bbe53f3a895a08f5b7d742191c
rahil1303/LISTS_USING_PYTHON
/6_List_Operations.py
299
4.09375
4
### "+" operator concatenates a = [1,2,3] b = [4,5,6] c = a+b print(c) ### "*" operator a = [0] a = a*4 print(a)' ### len() function of lists print(len(c)) ### Max() returns the item with the highest value in the List print(max(c)) ### Sum() returns sum of all items in the List print(sum(c))
9b981fcbbb6712e7ba03648611ff5412c46f1255
FuzzyLogick/ChooseYourOwnAdventure-1
/pg91.py
350
3.65625
4
def text(): print("") print("") #print("From part 76") print("") print("You run into the alien spaceship. Perhaps you can make the aliens free Dr. Walker. But as you enter, the doors shut and this is the last time you see planet Earth.") print("") print("") print("+ The End.") prin...
61b84211b0780359ed024a3e599892874785003b
Niket-iiitu/Plotter
/Plot_v1.py
1,330
3.515625
4
import matplotlib.pyplot as plt from colorama import Fore, init init() print(Fore.RED+"Welcome to Plotter v1.0") print(Fore.BLUE+"Enter the co-ordinate in format 'x y'\nEnter 'BACK' to remove previous value and 'EXIT' when you are completed.") print(Fore.WHITE, end="") x=[] y=[] while True: try: cor=input(...
bb3174d25928a07ade3149545f20fa2d823c5954
pragin/python-challenges
/eureka.py
887
4.40625
4
#Eureka! - Archimedes and King Hiero's Crown - www.101computing.net/eureka-and-king-hieros-crown/ mass = float(input("Input the mass of the crown in kg: ")) volume = float(input("Input the volume of the crown in cubic meter: ")) #Complete the code here to calculate the density and compare it with the density of a ra...
959345ddc9f466b4d3298ad52bce3f7b8d12e839
Madinanachan/Garden-House
/adv.py
4,179
3.703125
4
from room import Room from player import Player # Declare all the rooms room = { 'Garden': Room("Garden Gate", """You stand in a small garden. To the south lies a large iron fence with a beautifully adorned gate. The path you are on leads north to a cottage"""), 'Cottage': Room("Cute C...
8d909b90a59cce51160c8310d681220165e54169
l3kn/generative_cfg
/generative_cfg/turtle.py
1,742
3.5
4
import math import numbers import random from .vec import Vec2 class Turtle(): def __init__(self, backend): self.position = Vec2(); self.direction = Vec2(0.0, -1.0); self.__scale = 1.0; self.drawing = True self.backend = backend # Used to (re)store the turtles sta...
0ba37a3cde0bd1254528dd3abc6d430acbe9639a
aditiyaf/Hacktoberfest_2021
/code/reader-writer-threading.py
1,089
3.78125
4
import threading import random global x x = 0 wlock = threading.Lock() rlock = threading.Lock() def Reader(): global x try: wlock.acquire() print('Reader is Reading!') print('Shared Data:', x) wlock.release() print() except: print("Reader could...
4445f3f1e7ba51dd66d131b0d4919a8da10ec4d3
danilosp1/Exercicios-curso-em-video-python
/ex095.py
1,293
3.625
4
jogador = dict() time = [] gol = [] tot_gols = 0 while True: cont = ' ' tot_gols = 0 jogador['nome'] = str(input('Nome do jogador: ')) partidas = jogador['total'] = int(input('Partidas jogadas: ')) for i in range(0, partidas): gol.append(int(input(f'Quantos gols na partida {i+1}? '))) ...
5b5abc7db4c0e644b8c59d4c59e51a49be6683a1
hhj227/Data-structure-and-Algorithm-Study
/programmers/해시/전화번호 목록.py
743
3.546875
4
# first solution # failed at efficiency test def solution(phone_book): answer = True for a in range(len(phone_book)): for b in range(len(phone_book)): if a==b or len(phone_book[a])>len(phone_book[b]): continue if phone_book[b][0:len(phone_book[a])]==phone_bo...
199bde0741caaaf9ae0ebb18d9cf0280d530c9b1
deystroyter/python-homeworks
/python-hw1/2_for.py
3,234
4.09375
4
print("""\n1. Найти N-й член последовательности 1, 1, 2, 3, 5, 8, 13...""") # Следующий член последовательности равен сумме 2-ух предыдущих def find_element1(n): prev = cur = 1 for n in range(int(n - 2)): tmp = prev + cur prev = cur cur = tmp return cur usern1 = ...
c18d9ac24437cc145efbc4a297dc92fcf5c50e5b
mohammadreza-ebrahimi/Advanced-Python
/docs/generators\OOP.py
4,185
3.78125
4
# Created on Fri Dec 25 10:56:21 2020 # @Author: Mohammadreza Ebrahimi #%% import matplotlib.pyplot as plt import numpy as np # %% def diff(f, x, h=1E-5): return (f(x + h) - f(x)) / h #%% def f(x, y): while x > y: yield x ** 2 + x * np.sin(2 * y) y += 1 for i in f(10, 1): print(i) # ...
4d1c26bb7a5bd81c1f7ca350be19e4f5689240b8
soumandal/nlp-tools-en
/preprocess_tools/preprocess.py
452
3.90625
4
def elongation_check(token): characters = [char for char in token] if len(characters) > 2: for index in range(2, len(characters)): current = characters[index] previous_1, previous_2 = characters[index - 1], characters[index - 2] if current == previous_1 and current =...
64199bee69bb339c1d338430368ca6e43badd7f6
WanlinLi798/android_test
/src/case/test_threading.py
242
3.625
4
# -*- coding: utf-8 -*- ''' @author: uidq1501 ''' import threading def sum(a): print(a+6) threads = [] for i in range(3): # print i t = threading.Thread(target=sum, args=(i,)) threads.append(t) for j in threads: j.start()
f0b8c45c3a78e2b2f5dd6d89e6f310d1509b165f
leeeju/PyCharm
/turtle.py
344
3.671875
4
import turtle turtle.shape('turtle') turtle.color('blue') # 거북이 별 그리기 for i in range(5): turtle.back(210) turtle.right(100) turtle.left(320) turtle.left(280) #turtle.forward(150) #turtle.left(100) #turtle.forward(60) #turtle.left(100) #turtle.right(120) #turtle.back(90) turtle.m...
caab5c4bf1830438ff56c2061787bab66ef04fad
Strugglingrookie/oldboy2
/module3/0homework/exam/exam.py
935
4
4
class People: def __init__(self, name, life, weapon, sex, blood): self.name = name self.life = life self.weapon = weapon self.sex = sex self.blood = blood def attack(self, other): other.life -= self.blood print("%s 攻击了 %s ,失去 %s 生命值" % (self.name, other.n...
ddf78c6f538986401332f245f9af812c0d0d657c
meetashok/projecteuler
/60-70/problem-63.py
1,067
3.828125
4
## Problem 63 ## Powerful Digit Counts # Below from https://github.com/nayuki/Project-Euler-solutions/blob/master/python/p063.py # Let's examine n^k for different values of n and k and see which # choices cannot possibly work (i.e. not being exactly k digits long). # # When n = 10, for each k, n^k has exactly k+1 di...
5a708d6a0369e8dd40adfc8dc434b9cef55426f2
navin106/20186106_cspp-1
/cspp1-assignments/m6/p3/digit_product.py
571
4.03125
4
''' Given a number int_input, find the product of all the digits example: input: 123 output: 6 ''' def main(): ''' Read any number from the input, store it in variable int_input. ''' INT_INPUT = int(input()) PRO = 1 REM = 0 TEMP_INT = INT_INPUT if INT_INPUT != 0: if TEMP_INT < 0: TEMP_INT = abs...
c10cc9268177720151286f408a8366b52b06d396
Zmitc002/Physics177
/week05/ex03.py
2,727
3.8125
4
# Zachary Mitchell # Physics 177 # Spring 2015 # University of California Riverside # Assignment 5 # Problem 3 # ----------------------------------------------------------------------------- import numpy as np import matplotlib.pylab as plt # From the github repository, folder “extra_info_labs” please download the f...
220a54805b4806c778af45a45e462c855164d9a1
SebastianCharlesMillar/PaddleGame
/PaddleBallGameGroupProject2.pyde
5,027
3.703125
4
#BrickGame #Ball is moving at a constant speed and bounce off the walls #Ball Reflects when it hits walls and ceiling #bonus Features, could include making the rows of bricks a different colour #Hit detection - import random key_mode = 0 padpos= -10 padpos1 = 0 def paddle(): fill(255) circle(pa...
4a9c3eb514082dc5b61522ad3da2b56c9aec093d
AutumnColeman/python_basics
/python-lists/matrix_addition.py
669
3.984375
4
print "Given two two-dimensional lists of numbers of the size 2x2 two dimensional list is represented as a list of lists:" # With numpy # import numpy as np # # Mat1 = np.matrix([[2, -2], # [5, 3]]) # Mat2 = np.matrix([[5, 2], # [1, 0]]) # # print Mat1 + Mat2 # With empty matrix Mat1 = [[2, -2], ...
509dff64f04a3a293123fef8ddb62c57403781bd
snasuddertale/Kody
/petle_cwiczenia_gagat_kl2ag1/petla_cw_2.py
588
3.515625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def main(args): a = int(input("Podaj liczbę: " )) b = int(input("Podaj liczbę: " )) if a > 1000000 or b > 1000000 * a: print("podałeś za wysokie parametry, drogi użytkowniku") if a <= b: for liczba in range(a, b + 1): ...
c93b8112ab8a0cbea9d8db1f3743dd74b242c351
bpatter5/nonlinear_optimization
/nonlinear_optimization/convex_opt/gradient_methods/gradient_descent.py
1,214
3.75
4
# ============================================================================= # Created By: Brett Patterson # Updated By: Brett Patterson # Created On: 9/20/2018 # Updated On: 9/20/2018 # Purpose: Perform unconstrained gradient descent on convex functions # ============================================================...
60bab01c897d1650d20912b1f377c8ddbefbf6f4
caimengyuan/daydayup
/sortAlg/QuickSort.py
1,315
3.953125
4
''' 快速排序,分治法,三步走 ''' def quickSort_01(array): # 递归出口 if len(array) < 2: return array else: index = 0 # 第一个元素作为pivot pivot = array[index] less_part = [ i for i in array[index+1:] if i <= pivot ] great_part = [ i for i in array[index...
a7c23f623e967126f1f4350ab049540db4178596
emilysteiner71/Hangman
/Hangman.py
5,216
4.09375
4
#Welcome to my Hangman Python game! #The computer gets a random word from the word list. The user will have to guess this word import random lines = open("wordlist.txt", "r").read().splitlines() myline = random.choice(lines) blanks = list("_" * len(myline)) print ("HHH HHH NNNN NN GGGGGGGGG...
ffeb73a9b1601c8fcd1f14f640f76016833bb978
andhy-gif/diya_challenge1
/tentukanbilanganterbesar.py
101
4
4
def max(x,y): if x <= y: return x else: return y print(max(10,8)) z = max(2,5) print (z)
13765af254772e3153204b92d8e2422f66c29ed5
nOctaveLay/Data_Structure
/Data_Structure_python/LinkedList/SinglyLinkedList.py
1,072
3.734375
4
from Node import Node class SinglyLinkedList(Node): def __init__(self): self.size = 0 self.head = None self.tail = None def size(self): return self.size def isEmpty(self): return (self.size == 0) def first(self): if self.head == None: return None else: return head.getElement() def last(self): if sel...
00d7a126dd38ceac04e9bcc0a47e19fdb2a316bd
samuaicc/Python-
/使用元组类型.py
1,529
4.125
4
#-*-coding:utf-8-*- ''' 使用元组 元祖可以看做一种特殊的列表, 唯一与列表不同的是元组内的数据元素不能发生改变 不仅不能改变其中的数据项还不能添加和删除数据项 当开发者需要创建一组不可改变的数据时 通常会把这些数据放在一个元组中 元组也可以嵌套 ''' tup1 = ('google','huawei',1991,1120) tup2 = (1,2,3,4,5,6,7,8) print(tup1[0]) print(tup2[1:5]) #截取元祖 for elements in tup1: #for循环遍历元组 print(elements) ''' pyth...
9e8d96ce8622669262e53b5982533b857f91cea3
PEPER0oEGGS/NetCracker
/Task4.2.py
1,849
4.09375
4
""" Статистика вызовов функций (на декораторы и генераторы) Написать генератор-декоратор(!) stat_counter, который конструирует объекты (назовём пока statistic), такие что: - первый вызов next(statistic) (он же statistic.send(None)) возвращает словарь, в котором stat будет хранить информацию вида { функция: количество...
16c492d23ac2e4ef3135ddf439bb7c522a18437a
Win-Htet-Aung/kattis-solutions
/aliennumber.py
389
3.78125
4
def decimal_to_target(deci): base = len(target) number = '' while deci != 0: number = target[deci % base] + number deci = deci // base return number for i in range(int(input())): number, source, target = input().split() print('Case #{}: {}'.format(i + 1, decimal_to_target(sum([source.index(number[j]) * len(...
7bbc01a0a92ce0a739d8f5c22f85ab8b51404985
Acekicker277/alx-higher_level_programming
/0x0A-python-inheritance/3-is_kind_of_class.py
496
3.640625
4
#!/usr/bin/python3 """Defines a class and inherited class-checking function.""" def is_kind_of_class(obj, a_class): """Check if an object is an instance or inherited instance of a class. Args: obj (any): The object to check. a_class (type): The class to match the type of obj to. Returns: ...
6a66e6ca0ed0c27a9133ac618d6311fb28a2b03a
coderford/euler-solutions
/053_combSelect.py
348
3.59375
4
def factorial(x): fact = 1 i = 1 while i<=x: fact *= i i += 1 return fact def combinations(n, r): return factorial(n)/(factorial(n-r)*(factorial(r))) n = 1 count = 0 while n<=100: r = 1 while r<=n: if combinations(n, r) > 1000000: count += 1 r +=...
4a65aa9cbbea95fe52f5818060d2a08162715187
alexfire008/centrale
/server/src/models/user.py
610
3.625
4
""" Define the User model """ from . import db from .abc import BaseModel, MetaBaseModel class User(db.Model, BaseModel, metaclass=MetaBaseModel): """ The User model """ __tablename__ = "user" first_name = db.Column(db.String(300), primary_key=True) last_name = db.Column(db.String(300), primary_key=...
7db67ee135ba5b45a4590a06f32beee2d99cd084
AdamZhouSE/pythonHomework
/Code/CodeRecords/2810/60627/236814.py
101
3.546875
4
# 41 inp = input() num = list(inp) for i in range(len(num)): num[i] = int(num[i]) print(max(num))
c9cc1a3cfa594126b8fef46c3d0567cd597a04bf
smahamkl/ScalaSamples
/jan2021challenge/WordLadder.py
1,639
3.890625
4
from typing import List import collections ''' Given two words beginWord and endWord, and a dictionary wordList, return the length of the shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Return 0 if ther...
814d740b558eab357b0d1e8a1d07306b21a1ef4a
pwatson1/python
/exampleCode/overriding_example.py
710
4.3125
4
# Override replaces variables in the # base class with an inherited variable # have the same name and be spelled # the exact same way. class BaseClass(object): def __init__(self): # Default variable from parent # having a default variable insures the program doesn't # crash ...
0ecfeb0b4306183a4e9d4e11e68f10b51ba762eb
zihuaweng/leetcode-solutions
/leetcode_python/841.Keys_and_Rooms.py
889
3.671875
4
#!/usr/bin/env python3 # coding: utf-8 # https://leetcode.com/problems/keys-and-rooms/ # DFS # Time complexity: O(N+K) # Space complexity: O(N) class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: queue = collections.deque(rooms[0]) opened = set() opened.add(0) ...
f2a296dcb090c192e86fecc957aa8cd73da6ffc8
JoseArtur/phyton-exercices
/PyUdemy/Day17/Start.py/main.py
503
3.703125
4
class User: # Constructor # WHen a object is created it must be provided with user_id and username def __init__(self, user_id, username ): self.id = user_id self.username = username self.followers = 0 self.following = 0 def follow(self, user): user.followers += 1 ...
2eda1ae670609d151d0f979ba96daca8d750fd52
kaio358/Python
/Mundo 1/Modulos/Desafio#25.py
104
3.6875
4
nome = str(input('Informe seu nome completo : ')).strip() print('Tem Silva ? ','silva' in nome.lower())
129303da16840a68b99e3868de5e50eedadd7fd4
AM2i9/TheTunnels
/rooms/puzzle_room.py
3,988
4.125
4
from base.Room import Room # A puzzle. Attached to large intersection name = "Weird Puzzle" description = """The first thing you notice about the room is a large grid on the floor. There are nine squares, each with one number\nbetween 1 and 9 on it in Roman numerals. It seems to be some form of large keypad, the...
25271f04435c11bb5e2e93c7d9bb1c10001ac886
QiaoXingLi/Insight-Data-Engineering-Coding-Challenge
/src/donation_analytics.py
7,615
3.5
4
## Author: Nadav Tanners ## Purpose: First, identify donations from repeat donors, defined as a ## donor (defined as a unique name & 5-digit zipcode combination) that ## has previously made a donation in any prior calendar year. ## Second, for every donation from a repeat donor, calculate the ## following informat...
56fee13890465c3b738702ea17f2ce17e7c5339f
willsunnn/FinanceManager
/TableWidget.py
18,096
3.5625
4
import tkinter default_cell_width = 5 default_header_justify = 'center' default_entry_justify = 'left' direction_to_compass = {'center': 'center', 'left': 'w', "right": 'e'} default_pad_x = 3 default_pad_y = 1 default_pad_header = 5 class TableEditListener: def send_edit_to_database(self, table_name: str, row_in...
c79629cb0825104ce6ce3d8068366993a65a57d5
nehavatsyan/Guess-The-Number
/guess.py
416
4.0625
4
import random secretNumber=random.randint(1,10) guess=0 i=0 while guess!=secretNumber: i=i+1 print("Take a guess of number (1-10)") guess=int(input()) if guess < secretNumber: print('Your guess is too low.') elif guess > secretNumber: print('...
2575e2883be641d445e46c39ac45d6961b97f16a
hideyukiinada/ml
/examples/kmeans_example
3,048
4.0625
4
#!/usr/bin/env python """ Example code to demo k-means. Notes ----- As the below Wikipedia article points out, there is no guarantee that this implementation of k-means finds the optimal clustering result. Reference --------- https://en.wikipedia.org/wiki/K-means_clustering __author__ = "Hide Inada" __copyright__ = ...
f5d1c5a2659e5c31fd2b87cf109694a7a58d1a9a
bryanfassett/TinyFarm
/Game/Common/Throw.py
394
3.5
4
from Game.Common import Logger ## throw function will always log and print data. Primarily used for exceptions or important events ## Will throw exception by default, set to false if manually handling exception elsewhere def Throw(data, handle = True): if handle: try: raise Exception(data) ...
9283a7afd97a5c3899f5c19803b828957411da80
abhinandhani/bita
/primenumber.py
572
3.734375
4
#to find the 10th prime number '''import time start=time.time() count=0 for numer in range(2,500): for denum in range(2,numer): if numer%denum==0: break else: print(numer) time.sleep(1) end=time.time() print('execution time',end-start)''' #to fi...
ccebdf820de15e6ff5c5e06b20fa75bbd06448f9
mitchell-hardy/CP1404-Practicals
/Week 3/asciiTable.py
1,280
4.125
4
__author__ = 'Mitch Hardy' def main(): NUMBER_MINIMUM = 33 NUMBER_MAXIMUM = 127 # get a number from the user (ASCII) and print the corresponding character. user_number = get_number(NUMBER_MINIMUM, NUMBER_MAXIMUM) # get a character from the user and print the corresponding ASCII key print("The...
f2aefd12636f91d3b65a4d16161cd2312a6afbae
lohitbadiger/python-basics-all
/47.py
149
3.984375
4
# area of circle def fact(x): if x==0: return 1 return x*fact(x-1) x=int(input('enter the values for x ')) print( fact(x))
ff8618aafd1f2f1c7719181e9bbc56f57aaf21f2
Omodiagbe-Daniel/alx-higher_level_programming-1
/0x06-python-classes/1-square.py
241
3.6875
4
#!/usr/bin/python3 """Square module.""" class Square: """Defines a square.""" def __init__(self, size): """Constructor. Args: size: length of side of the square. """ self.__size = size
fbc3beb2e837b71c518262182995d0ffe5dc05a6
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4194/codes/1595_1016.py
464
3.984375
4
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. a = float(input("Digite um numero para o lado a do triangulo: ")) b = float(input("Digite um numero para o lado b do triangulo: ")) c = fl...
981f12ed9f245b0405097d735d17e29cd09f3254
LucasSGomide/Python
/Códigos/Exercicios_função/ex_26.py
374
3.84375
4
'''Funções para somar todos os algarismos anteriores ao numero fornecido pelo usuário. Obs: implantar INPUT. ''' def soma(n): soma = 0 for numeros in range(1, n + 1): soma += numeros return(soma) print(soma(50)) def soma_2(n): lista = list(range(1, n + 1)) lista = sum(lista) total ...
704d1323d73a8e13288905645a0794f25e1c7da0
mmasniy/Maraphon-Python
/sprint00/t04_bridge_of_death/input.py
486
3.703125
4
print('BRIDGEKEEPER: Stop.') print('Who would cross the Bridge of Death must answer me these questions three.') name = input('BRIDGEKEEPER: What is your name?\n') quest = input('BRIDGEKEEPER: What is your quest?\n') color = input('BRIDGEKEEPER: What is your favorite color?\n') print('-' * 10) print(f'Traveler info:...
129bc79a1e4d5b724a41c94ee98eaafc8b4e2fe8
Neeraj111/programming111
/python-codes/buy_computer_enumerate.py
982
3.75
4
lis=["computer","monitor","keybord","mouse","mousepad","hdmi cable"] current_choice = "_" computer_parts = [] # createvan empty list valid_choices=[str(i) for i in range(1,len(lis)+1)] print (valid_choices) while current_choice != "0" : if current_choice in valid_choices: index = int(curr...
eb4100f4d81b0f5069d9be1f9783df6b456fe500
tom-f/sudoku
/sudoku/grid.py
1,739
3.859375
4
from __future__ import print_function class Grid: def __init__(self): self.grid = [None] * 81 def load_data(self, data_string, separator=","): """Take string with values split by given separator.""" self.grid = [(lambda x: int(x) if x != '' else 0)(x) for x in data_string.split(separa...