blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
f984cc81842f604c1c29e1ddecf630c2f49df851
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_OOP/product.py
1,605
3.875
4
class product(object): def __init__(self,price,name,weight,brand,cost): self.name = name self.price = price self.weight = weight self.brand = brand self.cost = cost self.status = "for sale" def sell(self): self.status = "sold" print self.name,...
6c96a66ca122128582076cba695de6325d6b32e9
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_fundamentals/strings_and_lists.py
993
3.96875
4
'''def replace_string(long_string, old,new): return long_string.replace(old,new) words = "It's thanksgiving day. It's my birthday,too!" old_string = "day" new_string = "month" print words print replace_string(words,old_string,new_string) def minmax(some_list): some_list.sort() x=len(some_list) -1 ...
7ca52317a28ac1a45a2a44b3d8d769def95493e5
cd-chicago-june-cohort/dojo_assignments_mikeSullivan1
/python_fundamentals/MakingDicts.py
329
4.34375
4
def print_dict(dict): print "My name is", dict["name"] print "My age is", dict["age"] print "My country of birth is", dict["birthplace"] print "My favorite language is", dict["language"] myDict = {} myDict["name"]="Mike" myDict["age"]=34 myDict["birthplace"]="USA" myDict["language"]="Python" print_dic...
7732208f5d3e7826e263da85dd8941cadd25fa37
MarkiianAtUCU/TeamTask
/interface.py
2,375
3.796875
4
from main import * import os menu = """ 1) - Add Client 2) - Add Mail 3) - Send All 4) - Mail Number 5) - Clients info 6) - Quit """ clients = [] mails = MailBox() def create_client(lst): name = input("[Client name] > ") age = input("[Client age] >") while not age.isdigit() and not (1 < int(age) < 110):...
09d3cf114f83a5d284c0f810b02ca87dee711b30
ical9016/bootcamp13_fundamental
/fundamental_01.py
892
4
4
""" syntax programming language consist of: - Sequential - Branching - Loop - Modularization using : a. Function b. Class c. Package example program to be made : Blog with Django """ judul = 'Menguasai python dalam 3 jam' author = 'Nafis Faisal' tanggal = '2019-11-02' #jumlah_artikel = 100 # #if jumlah_ar...
188abf2fd259085a3bcf6d538ce8dfb67d6357f5
ashley015/python20210203
/3-2.py
370
3.625
4
m=[] total=0 high=0 low=100 n=int(input('How many people in this class?')) for i in range(n): score=int(input('Plase input the score:')) total=total+score if high< score: high=score if low>score: low=score m.append(score) average=total/n print(m) print('average...
63cd3250a2453bc5dcf1083a3f9010fd6496fe1f
BrandonCzaja/Sololearn
/Python/Control_Structures/Boolean_Logic.py
650
4.25
4
# Boolean logic operators are (and, or, not) # And Operator # print(1 == 1 and 2 == 2) # print(1 == 1 and 2 == 3) # print(1 != 1 and 2 == 2) # print(2 < 1 and 3 > 6) # Example of boolean logic with an if statement # I can either leave the expressions unwrapped, wrap each individual statement or wrap the whole if con...
5cf03dca2de00592db494a9bb2c00b80147f387a
frba/biomek
/biomek/function/spotting.py
6,045
3.59375
4
""" Functions to create CSV files to be used in biomek Source Plate Name,Source Well,Destination Plate Name,Destination Well,Volume PlateS1,A1,PlateD1,A1,4 PlateS1,A1,PlateD1,B1,4 PlateS1,A2,PlateD1,C1,4 PlateS1,A2,PlateD1,D1,4 """ from ..misc import calc, file from ..container import plate import sys MAX_PLATES = 1...
3605da3592356af8f961812c48b5d8b0ea3a7a16
CharnyshMM/python_tracker
/console_interface/parser.py
344
3.578125
4
"""This module describes Parser class""" import argparse import sys class Parser(argparse.ArgumentParser): """Just a wrapper for default ArgumentParser to add ability to print help in case of error arguments""" def error(self, message): sys.stderr.write('error: %s\n' % message) self.print_hel...
ddda02473ba71bf752d22572e92a52bd9dff6f35
BlandineLemaire/StegaPy
/tools/charSearch.py
1,223
3.75
4
''' Fonction : charSearcher(byteList) byteList : liste de byte dans lesquels on va chercher tout les caracteres qui sont imprimable Explication : charSearcher est une fonction qui permet de trouver tout les caracteres imprimable qui sont dans une liste de bytes et de les retourner dans une v...
38ea269387d3a34e05fa0831239d249f487347f9
LeeJiangWei/algorithms
/8-puzzle.py
3,999
3.796875
4
import random class puzzle: def __init__(self, state=None, pre_move=None, parent=None): self.state = state self.directions = ["up", "down", "left", "right"] if pre_move: self.directions.remove(pre_move) self.pre_move = pre_move self.parent = parent self....
4dacc73ac8d08acb3a6ac4d6fda0c62c4b89305f
kyle-yan/python
/sets.py
134
3.828125
4
#集合-用大括号表示,去重 sets = {1, 2, 3, 4, 5, 6, 1} print(sets) if 3 in sets: print('haha') else: print('hoho')
8545c73344abaabdafdd6686bafe4a6382e48b2f
bhattacharyya/biopythongui
/objects.py
6,264
3.65625
4
class Item: def save(self, filename=0): import cPickle if filename==0: filename = self.name ext = filename.split('.')[-1] if ext == filename: filename += self.extension file = open(filename, 'wb') cPickle.dump(file, self, -1) file.close() def changeName(se...
e6042faa1b4190457bf74b49b0d8728a36e14bbe
Ang3l1t0/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
305
3.859375
4
#!/usr/bin/python3 """Inherits """ def inherits_from(obj, a_class): """inherits_from Arguments: obj a_class Returns: bol -- true or false """ if issubclass(type(obj), a_class) and type(obj) is not a_class: return True else: return False
aacccdbd244dd21b31268344bc4a6cbcd31fa597
Ang3l1t0/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-number_of_lines.py
311
3.703125
4
#!/usr/bin/python3 """Number of Lines """ def number_of_lines(filename=""): """number_of_lines Keyword Arguments: filename {str} -- file name or path (default: {""}) """ count = 0 with open(filename) as f: for _ in f: count += 1 f.closed return(count)
6ae9ddc15cbedfe51a661dbcd58911f22b616280
Ang3l1t0/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/6-print_comb3.py
239
3.921875
4
#!/usr/bin/python3 for n1 in range(0, 9): for n2 in range(0, 10): if n1 < n2: if n1 < 8: print("{:d}{:d}".format(n1, n2), end=', ') else: print("{:d}{:d}".format(n1, n2))
674d9922f89514e4266c48ec91b98f223fdcf313
Ang3l1t0/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
410
4.1875
4
#!/usr/bin/python3 """Append """ def append_write(filename="", text=""): """append_write method Keyword Arguments: filename {str} -- file name or path (default: {""}) text {str} -- text to append (default: {""}) Returns: [str] -- text that will append """ with open(filena...
982c7852214a41e505052c5674006286fc26b4b9
Ang3l1t0/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
444
4.34375
4
#!/usr/bin/python3 """print_square""" def print_square(size): """print_square Arguments: size {int} -- square size Raises: TypeError: If size is not an integer ValueError: If size is lower than 0 """ if type(size) is not int: raise TypeError("size must be an integ...
af528387ea37e35a6f12b53b392f920087e5284b
Ang3l1t0/holbertonschool-higher_level_programming
/0x02-python-import_modules/2-args.py
596
4.375
4
#!/usr/bin/python3 import sys from sys import argv if __name__ == "__main__": # leng argv starts in 1 with the name of the function # 1 = function name if len(argv) == 1: print("{:d} arguments.".format(len(sys.argv) - 1)) # 2 = first argument if is equal to 2 it means just one arg elif len(a...
5253817eac722b8e72fa1eadb560f8b7c7d73250
weeksghost/snippets
/fizzbuzz/fizzbuzz.py
562
4.21875
4
"""Write a program that prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number. For the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'.""" from random import randint def fizzbuzz(num): for x in range(1, 101): if x ...
4d221fa61d3ec90b303ef161455e3cf4f328c40e
Pavanyeluri11/LeetCode-Problems-Python
/numTeams.py
833
3.5625
4
def numTeams(rating): ans = 0 n = len(rating) #increasing[i][j] denotes the num of teams ending at soldier i with length of j in the order of increasing rating. increasing = [[0] * 4 for _ in range(n)] #decreasing[i][j] denotes the num of teams ending at soldier i with length of j in the order ...
1efbc8cb0c81c8e34da0c5ec8370f2b7eee61095
NeutronCat/EarlyLearningPython
/String_Challenge.py
3,057
4.0625
4
#counts letters letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def unique_english_letters(word): uniques = 0 for letter in letters: if letter in word: uniques += 1 return uniques print(unique_english_letters("mississippi")) # should print 4 print(unique_english_letters("Apple")) # shou...
d6f097dd5b99e039ac4d33ba958ca79834075248
NeutronCat/EarlyLearningPython
/BasicMathFunctions.py
2,936
4.0625
4
# average # Write your average function here: def average(num1, num2): return (num1+num2)/2 # Uncomment these function calls to test your average function: print(average(1, 100)) # The average of 1 and 100 is 50.5 print(average(1, -1)) # The average of 1 and -1 is 0 # tenth power # Write your tenth_power function...
7b55bb9eddd6cf5f9a4be3738a2fab13dfcfca00
abdullahelshoura/MOBILE-COMPUTING
/NerualN.py
987
3.515625
4
#1 Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn import datasets from sklearn import metrics iris = datasets.load_iris() X = iris.data[:, :4] y ...
e2ad5022f9820b69b1f85f863bf6326155d7f876
Jonly-123/homework1_3
/获取文件大小.py
795
3.828125
4
import os # def getFileSize(filePath,size = 0): 定义获取文件大小的函数,初始文件大小是0 # for root, dirs, files in os.walk(filePath): # for f in files: # size += os.path.getsize(os.path.join(root, f)) # print(f) # return size # print(getFileSize('./yuanleetest')) all_size = 0 def dir_s...
d49ada9b93882faf7afc97e34094015263f8dfc4
Yuxiao98/PE
/PE34.py
595
3.953125
4
# Project Euler: Q34 # Find the sum of all numbers which are equal to the sum of the factorial of their digits. import math def individualDigits(num): digitsList = [] while num: digitsList.append(num%10) num //= 10 digitsList = digitsList[::-1] return digitsList magicSet = se...
0e8b73b3dd48465db2b9f1c6673d8437b9876908
Yuxiao98/PE
/PE25.py
510
3.875
4
# Project Euler: Q25 # Find the index of the first term in the Fibonacci sequence to contain 1000 digits def countDigits(num): c = 0 while num: num //= 10 c += 1 return c fibonacci_numbers = [0, 1] i = 2 while True: fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_n...
a3cb355f81a27113efd62c52523b958855e673fa
Kirstihly/Edge-Directed_Interpolation
/edi.py
5,388
3.625
4
import cv2 import numpy as np from matplotlib import pyplot as plt import math import sys """ Author: hu.leying@columbia.edu Usage: EDI_predict(img, m, s) # img is the input image # m is the sampling window size, not scaling factor! The larger the m, more blurry the image. Ideal m >= 4. # ...
87a46c9d2df91ef1d4fdddd74e1c7c0771b72fd9
linnil1/2020pdsa
/teams.sol.py
1,140
3.765625
4
from collections import defaultdict from typing import List from queue import Queue class Teams: def teams(self, idols: int, teetee: List[List[int]]) -> bool: # build the graph self.nodes = defaultdict(list) for i,j in teetee: self.nodes[i].append(j) self.nodes[j].a...
f10d6210fc4e22a2d9adaf14ec5b40f756804f09
atjason/Python
/learn/map_reduce.py
765
3.890625
4
def str2int(str): def merge_int(x, y): return x * 10 + y def char2int(c): char_dict = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } return char_dict[c] # map means apply function to each member ...
9a6e7b9ac1d4dceb8acf9e618cbe5dc63a92566e
roger1688/AdvancedPython_2019
/03_oop_init/hw1.py
1,039
4.125
4
class Node: def __init__(self, val): self.val = val self.next = None def print_linked_list(head): now = head while now: print('{} > '.format(now.val),end='') now = now.next print() # print newline # # Linked-list and print test # n1 = Node(1) # n2 = Node(3) # n3 = Node...
fe1e263511e1f24f17a10b4dc54e0b1c3cd40bc9
David-Loibl/gistemp4.0
/steps/eqarea.py
9,455
3.703125
4
#!/usr/local/bin/python3.4 # # eqarea.py # # David Jones, Ravenbrook Limited. # Avi Persin, Revision 2016-01-06 """Routines for computing an equal area grid. Specifically, Sergej's equal area 8000 element grid of the Earth (or any sphere like object). See GISTEMP code, subroutine GRIDEA Where "tuple" is used below,...
4544382ae2d171e544bf693e0f84d632df1e1a8f
egorov-oleg/hello-world
/task36.py
450
3.765625
4
m=int(input('Введите 2 натуральных числа: \n')) n=int(input()) if m>n: mini=n else: mini=m mindiv=0 i=2 while i<=mini: if n%i==0 and m%i==0: mindiv=i break else: i=i+1 if mindiv!=0: print('Наименьший нетривиальный делитель данных чисел:',mindiv) else: print('Наименьшего н...
51a0fb3465dfc09150fa00db37fecb5bb9277ce9
egorov-oleg/hello-world
/task25.py
163
3.71875
4
x=int(input('Введите число и его степень: \n')) n=int(input()) r=1 while n!=1: if n%2!=0: r=r*x x=x*x n=n//2 print(x*r)
6e26a991dae4e695874e3744a09f4b8dee29c693
egorov-oleg/hello-world
/task46.py
152
3.734375
4
n=int(input('Введите n: ')) fib0=0 fib1=1 i=2 while i<=n: fib=fib1+fib0 fib0=fib1 fib1=fib i=i+1 if n==0: fib1=0 print(fib1)
f2e80b4dfe9683fb3acba1272bde622fc4d55bc0
egorov-oleg/hello-world
/task38.py
408
3.828125
4
n=int(input('Введите натуральное число: ')) a=n digits=0 while a!=0: a=a//10 digits=digits+1 i=1 right=0 while i<=digits//2: right=right*10+n%10 n=n//10 i=i+1 if digits%2==1: n=n//10 if n==right: print('Данное число является палиндромом') else: print('Данное число не является палиндромом...
1c9a70bd869ed86792485f45a8e9b9a649c70042
egorov-oleg/hello-world
/task31.py
128
3.625
4
n=int(input('Введите натуральное число: ')) r=0 while n!=0: r=r*10 r=r+n%10 n=n//10 print(r)
8380193b3ae6c07d2468b2914b353b75f23424f0
egorov-oleg/hello-world
/task42.py
377
3.6875
4
a=int(input('Введите последовательность чисел:\n')) count1=0 while a!=0: count=0 b=1 while a>=b: if a%b==0: count=count+1 b=b+1 else: b=b+1 if count==2: count1=count1+1 a=int(input()) print('Простых чисел в последовательности:',count1)
0a91701ab33752409a27a9a242025a6f68025a10
egorov-oleg/hello-world
/task16.py
253
3.71875
4
a=int(input('Введите натуральное число: ')) count=0 b=1 while a-b>-1: if a%b==0: count=count+1 b=b+1 else: b=b+1 print('Количество делителей у данного числа:',count)
1cd6467c387ad89b19c6d34ecac63ccae15b2e4e
vasugarg1710/Python-Programs
/fibonachi.py
304
3.890625
4
# 0 1 1 2 3 5 8 13 def fibonachi(n): if n==1: return 0 elif n==2: return 1 else: return fibonachi(n-1)+fibonachi(n-2) print(fibonachi(5)) def factorial_iterative(n): fac = 1 for i in range(n): fac = fac * (i+1) return fac print(factorial_iterative(5))
6577851c9f791b876a6b7d7fc09f5e725d911091
vasugarg1710/Python-Programs
/2.py
335
4.03125
4
# Variables a = 10 b = 20 # Typecasting y = "10" # This is a string value z = "20" # print(int(y)+int(z)) # Now it it converted into integer """ str int float """ # Quiz # Adding two numbers print ("Enter the first number") first = int(input()) print ("Enter the second number") second = int(input()) print ("The sum is...
504c061e4c8e3a19dc54ce43005b902b1cce23f8
SK9415/Python
/loops.py
794
4.09375
4
#there are only two types of loop: for and while def main(): x = 0 print("while loop output") #while loop while(x<5): print(x) x = x+1 print("for loop output") #for loop #here, 5 is inlusive but 10 is excluded for x in range(5,10): print(x) #for loop over a...
31a4cbc00d468ecffbf4d4963ef68dca9015d6ee
citcheese/aws-s3-bruteforce
/progressbar.py
3,922
3.640625
4
#!/usr/bin/python # # Forked from Romuald Brunet, https://stackoverflow.com/questions/3160699/python-progress-bar # from __future__ import print_function import sys import re import time, datetime class ProgressBar(object): def __init__(self, total_items): """Initialized the ProgressBar object""" ...
da0858bbaa399f271317a1bc72db9bc496741a7c
RicardoPereiraIST/Design-Patterns
/Behavioral Patterns/Interpreter/example.py
2,546
3.796875
4
import abc class RNInterpreter: def __init__(self): self.thousands = Thousand(1) self.hundreds = Hundred(1); self.tens = Ten(1); self.ones = One(1); def interpret(self, _input): total = [0] self.thousands.parse(_input, total) self.hundreds.parse(_input, total) self.tens.parse(_input, to...
3d6e9293a05058f88e080a1ca82c5c0640c3a0ff
RicardoPereiraIST/Design-Patterns
/Structural Patterns/PrivateClassData/private_class_data.py
551
3.84375
4
''' Control write access to class attributes. Separate data from methods that use it. Encapsulate class data initialization. ''' class DataClass: def __init__(self): self.value = None def __get__(self, instance, owner): return self.value def __set__(self, instance, value): if self.value is Non...
0637d75b9e1a1968a0e5420e81c25834a5be6e81
RicardoPereiraIST/Design-Patterns
/Behavioral Patterns/Null Object/example.py
678
3.5
4
import abc class AbstractStream(metaclass=abc.ABCMeta): @abc.abstractmethod def write(self, b): pass class NullOutputStream(AbstractStream): def write(self, b): pass class NullPrintStream(AbstractStream): def __init__(self): self.stream = NullOutputStream() def write(self, b): self.stre...
949c75b95b53ea80f89808de44e048b8d35c46b2
lBenevides/CS50
/pset6/credit.py
951
3.6875
4
from cs50 import get_int card_number = get_int("Number: ") card = card_number count = 1 sum1 = 0 checksum = 0 c = card while card_number >= 10: # loop to know how many digits card_number /= 10 count += 1 i = count/2 card = int(card * 10) for x in range(int(i)+1): # iterates the number, diving by 10 an...
83807f66e3b59665593c9f8f0afa45f1f795d5b1
superlisohou/aspect-term-extraction
/add_pos_tag.py
1,364
3.5
4
#-*-coding:utf-8-*- """ Created on Sat Feb 24 2018 @author: Li, Supeng Use nltk package to perform part-of-speech tagging """ from xml_data_parser import xml_data_parser import nltk def add_pos_tag(input_file_name, split_character_set): # xml_data_parser(input_file_name=input_file_name, split_character_set=...
5c154be5da45623e64754aea0b096f32c30ea47a
chapman-cs510-2017f/cw-04-cpcw3
/primes.py
1,295
3.96875
4
#!/usr/bin/env python3 # Name: Chelsea Parlett & Chris Watkins # Student ID: 2298930 & 1450263 # Email: parlett@chapman.edu & watki115@mail.chapman.edu # Course: CS510 Fall 2017 # Assignment: Classwork 4 def eratosthenes(n): """ uses eratosthenes sieve to find primes""" potential_primes = list(i for i in rang...
5f0faab3f8ab77137a26b7767c0b45aa8d1ff12e
ThaisSouza411/ac3_arquitetura
/ac3_teste.py
994
3.5
4
import unittest from ac3 import Calculadora class PrimoTeste(unittest.TestCase): def teste_soma(self): calculadora = Calculadora() resultado = calculadora.calcular(20, 4, 'soma') self.assertEqual(24, resultado) def teste_subtracao(self): calculadora = Calculadora() res...
584a23a449e725e67f40ac8888b91359737e4a97
ARTC-RatLord/Puzzles
/collatz conjecture.py
338
3.625
4
# coding: utf-8 # In[5]: def collatz(a): collatz_conjecture=[a] while collatz_conjecture[-1]>1: if collatz_conjecture[-1]%2 == 0: collatz_conjecture.append(collatz_conjecture[-1]//2) else: collatz_conjecture.append(collatz_conjecture[-1]*3+1) return collatz_conjec...
fec505b5d8d11af5ff062722996be56342931a5a
ARTC-RatLord/Puzzles
/chess.py
1,336
3.9375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 13:35:20 2020 @author: 502598 """ def ValidChessBoard(move): valid_pieces = ['pawn', 'bishop', 'king', 'queen', 'knight', 'rook'] valid_letters = ['a','b','c','d','e','f','g','h'] valid_colors = ['w', 'b'] square_flag = True f...
ebb9cedc7c5ab5fe70d00d81b91daad46cdfac55
Zokhira/basics
/functions/functions_exercises.py
315
3.53125
4
def favorite_book(book_title): print(f"One of my favorite books is '{book_title}'") favorite_book("Harry Potter") def multi_num(a: int, b: int): c = a * b print(f"product of {a} and {b} is {c}.") multi_num(5, 6) multi_num(0,6) multi_num(-1, -1) multi_num(True, True) def swap(a,b): return a, b swap(5,6...
df03b5998aa5f44ee50831fc37137489c6248f77
Zokhira/basics
/classes/cars_exec.py
1,134
3.984375
4
# 04/03/2021 # This file is for executing the cars.py classes from classes.cars import Car # Execution # drive() we will not have an access to this function yet # mycar = Car() # Car is the class, mycar is an object...in this line we are creating instance of the (instantiation) mycar = Car("BMW", "530xi", "black") ...
fbfd41c416a36b7435a0cfab07969af7468500ad
Zokhira/basics
/dictionaries_loops.py
213
3.890625
4
rivers = {'nile': 'Egypt', 'tigres': 'Iraq', 'amazon': 'Brazil', 'mississippi': 'Usa'} for river, country in rivers.items(): #or key for values print(f"The {river.title()} runs through {country.title()}. ")
9274b177898d108ffe4b872c3a7e9c9bd70ad50e
MeeSeongIm/computational_complexity_py
/discrete_fourier_transform.py
722
3.59375
4
# Discrete Fourier Transform: only for the case when the signal length is a power of two. from cmath import exp, pi, sqrt x = 3 # change this to any nonnegative integer. N = 2**x j = sqrt(-1) data = [] # for the moment, let all x_n = 1 for all n and for each DFT sample. for p in list(range(int(N))): ...
a5fa1b5ffe4d5c21331d4773736bdd7939bb729e
keepmoving-521/LeetCode
/程序员面试金典/面试题 02.03. 删除中间节点.py
1,718
4.03125
4
""" 实现一种算法,删除单向链表中间的某个节点(即不是第一个或最后一个节点), 假定你只能访问该节点。 示例: 输入:单向链表a->b->c->d->e->f中的节点c 结果:不返回任何数据,但该链表变为a->b->d->e->f """ # Definition for singly-linked list. class LinkNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): # create a linklist def cr...
25d76b3da92239864774bebd5d2c47ddce06974e
kknnn/ProjectEuler
/SummationOfPrimes.py
293
3.59375
4
def esPrimo(numero): for i in range(2,numero): if ((numero%i)==0): return False return True suma = 0 for i in range(2, 2000001): if (esPrimo(i)): suma += i print(suma) #NO TERMINA DE EJECUTAR NUNCA -.- HAY QUE BUSCAR UNA SOLUCION MAS EFICIENTE
b0e2d53e58c970e711f06a7ae3715181d070f3f7
jugal13/Design_And_Analysis_Algorithms
/Programs/Breadth First Search(Layers).py
832
3.625
4
graph={ 1 : [ 2, 3 ], 2 : [ 1, 3, 4, 5 ], 3 : [ 1, 2, 6, 7 ], 4 : [ 2, 5, 8, 9], 5 : [ 2, 4, 9], 6 : [ 3, 7 ], 7 : [ 3, 6 ], 8 : [ 4, 9 ], 9 : [ 4, 5, 8, 10 ], 10 : [9] } source = 1 def bfs(graph,source): tree = [] traversal = [] layer = [] i = 0 visited = [0]*11 visited[source] = 1 layer.append([sour...
c1c431abb02873134f13691a27cef1d4ad842600
jugal13/Design_And_Analysis_Algorithms
/Programs(User Input)/Breadth First Search(Layers).py
871
3.6875
4
def bfs(graph,source,n): tree = [] traversal = [] layer = [] i = 0 visited = [0]*(n+1) visited[source] = 1 layer.append([source]) traversal.append(source) while layer[i]: r = [] for u in layer[i]: for v in graph[u]: if visited[v] == 0: traversal.append(v) tree.append([u,v]) visited[v]...
bca96439911f431aab27a193f351a810c6424436
jugal13/Design_And_Analysis_Algorithms
/Programs/Knapsack.py
731
3.546875
4
items = { 1 : [ 3, 10 ], 2 : [ 5, 4 ], 3 : [ 6, 9 ], 4 : [ 2, 11] } W = 7 M = [[0]*(W+1)] def matrix(items,M,W): for i in range(1,len(items)+1): row = [0] wi = items[i][0] vi = items[i][1] for w in range(1,W+1): if w < wi: row.append(M[i-1][w]) else: row.append(max(M[i-1][w],vi+M[i-1][w-...
27f2639a391a5e7ad4d6a25e6f6b5da9fe74a97c
luisjimenezlinares/AGConsta
/Fuentes/funciones_AG/comasaf/mutation.py
1,930
3.515625
4
# -*- coding: utf-8 -*- import random def mutation(G): #Muta un 1% de los genes genes_a_mutar = [] genes1p = len(G) / 100 #Si el 1% es 0, se selecciona un gen al azar if genes1p == 0: genes_a_mutar = [random.randint(0, len(G)-1)] #Sino se selecciona un 1% de los genes else: ...
9bd622894d7e1dde61b4957a91975f4cbced94fb
benv587/baseML
/LinearRegression/LinearRegression_bgd.py
2,039
3.8125
4
import numpy as np class LinearRegression(object): """ 根据批量梯度下降法求线性回归 """ def __init__(self, alpha, max_iter): self.alpha = alpha self.max_iter = max_iter def fit(self, X, y): X = self.normalize_data(X) # 标准化数据,消除量纲影响 X = self.add_x0(X) # 增加系数w0的数据,就不需要对w区别对待了 ...
6305227ae30aa254fc14bbe65e646b3ecfc38224
guingomes/Linguagem_Python
/1.operadores_aritmeticos.py
385
4.125
4
#objetivo é criar um programa em que o usuário insere dois valores para a mensuração de operações diversas. n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) s = n1+n2 m = n1*n2 d = n1/n2 di = n1//n2 e = n1**n2 print('A soma é: {}, o produto é: {} e a divisão é: {:.3f}'.format(s, m, d)) pri...
6724a08be69d5429e28bbf028f3cafe78337b8f2
zzfima/GrokkingAlgorithms
/Rec_sum_p81.py
357
4.125
4
def main(): print(SummArrayNumbers([3, 5, 2, 10])) def SummArrayNumbers(arr): """Sum array of numbers in recursive way Args: arr (array): numerical array Returns: int: sum of numbers """ if len(arr) == 1: return arr[0] return arr[0] + SummArrayNumbers(arr[1:]) i...
01af00a403187b6b3a2e68e0c1a3c82b475b8794
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/Six tasks/Six tasks.py
1,177
4.21875
4
# Ипортирование мматематической библиотеки import math # Катеты прямоугольного треугольника oneCathetus, twoCathetus = 1, 1 # Получение данных oneCathetus = float(input("Введите первый катет прямоугольного треугольника: ")) twoCathetus = float(input("Введите второй катет прямоугольного треугольного: ")) oneCathetus ...
2c4ecba0227a2e6c535e541e91ca1d1ab822ba8c
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/One tasks/One tasks.py
496
4
4
# Действительные числа a и b a, b = 0.0, 0.0 # Получение данных a = float(input("Пожалуйста введите число A: ")) b = float(input("Пожалуйста введите число B: ")) # Ответы задачи print("\n", a, " + ", b, " = ", (a + b)) print("\n", a, " - ", b, " = ", (a - b)) print("\n", a, " * ", b, " = ", (a * b)) input("\nДля зав...
6b560a28e34a507c79d88f04995fc7dd0bd4571a
walleri18/Programming-tasks-Python-3.x
/Programming tasks/The first paragraph/Twenty one tasks/Twenty one tasks.py
1,276
3.96875
4
# Импортирование математической библиотеки import math # Действительные числа c, d = 0, 0 # Корни уравнения x_one, x_two x_one, x_two = 0, 0 # Получаем данные c = float(input("Введите коэффициент C: ")) d = float(input("Введите коэффициент D: ")) # Находим корни уравнения D = (-3) ** 2 - 4 * (-math.fabs(c * d)) if...
bfc77608f4fff3bf16b36463a0a34debfe4052d6
Adva-Bootcamp21/google-project-efrat-noa
/data.py
356
3.703125
4
class Data: """ Save all the sentences can be searched in a dictionary format that includes all the word as the keys """ def __init__(self): self.__list = [] def get_sentence(self, index): return self.__list[index] def add(self, sentence): self.__list.append(sentence) ...
d350f927573693cfbf32b423e7d41150ea61ef2d
callmebg/arcade
/arcade/examples/perlin_noise_1.py
4,490
3.546875
4
""" Perlin Noise 1 If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.perlin_noise_1 TODO: This code doesn't work properly, and isn't currently listed in the examples. """ import arcade import numpy as np from PIL import Image # Set how many rows and col...
c412c9b5239cab36c3d23beffcf2c6429de45701
callmebg/arcade
/arcade/examples/texture_transform.py
3,380
3.75
4
""" Sprites with texture transformations Artwork from http://kenney.nl If Python and Arcade are installed, this example can be run from the command line with: python -m arcade.examples.sprite_texture_transform """ import arcade from arcade import Matrix3x3 import math import os SCREEN_WIDTH = 800 SCREEN_HEIGHT = 60...
e7836387e0f7799a52b6ed24c912e502cb1b4066
callmebg/arcade
/arcade/geometry.py
2,384
3.890625
4
""" Functions for calculating geometry. """ from typing import cast from arcade import PointList _PRECISION = 2 def are_polygons_intersecting(poly_a: PointList, poly_b: PointList) -> bool: """ Return True if two polygons intersect. :param PointList poly_a: List of points t...
152e9cbfbd601c868fd22ed95b71745f0fcf377f
mchrzanowski/ProjectEuler
/src/python/Problem112.py
995
3.59375
4
''' Created on Mar 15, 2012 @author: mchrzanowski ''' from time import time def main(): LIMIT = 0.99 iteration = 101 # 101 is the first bouncy number bouncies = 0 while float(bouncies) / iteration != LIMIT: strIteration = str(iteration) monoIncrease = mo...
2e0b949e98c20620649d095cd49012fe9266a323
mchrzanowski/ProjectEuler
/src/python/Problem138.py
993
3.671875
4
def main(): ''' God, I hate these recurrence relation problems. We are given the first two Ls: 17, 305. Note that: 305 = 17 * 17 + 16 * 1 5473 = 17 * 305 + 16 * 18 .... Let P = [1, 18]. Then, the general formula, found with much trial and error, is: L_new = ...
6b03bb6a11c7d281b149df1f39c25239e6161dbf
mchrzanowski/ProjectEuler
/src/python/Problem135.py
2,511
3.5
4
''' Created on Sep 20, 2012 @author: mchrzanowski ''' def produce_n(z, k): return 2 * k * z + 3 * k ** 2 - z ** 2 def main(max_n, solution_number): solutions = dict() # we can write x ** 2 - y ** 2 - z ** 2 = n as: # (z + 2 * k) ** 2 - (z + k) ** 2 - z ** 2 == n # if you find the partial der...
8a0fc1fe53bd0be86da21a304645c84fa192c215
mchrzanowski/ProjectEuler
/lib/python/ProjectEulerLibrary.py
5,447
3.765625
4
''' Created on Jan 19, 2012 @author: mchrzanowski ''' from ProjectEulerPrime import ProjectEulerPrime def generate_next_prime(start=2): ''' generator that spits out primes ''' # since 2 is the only even number, # immediately yield it and start # the below loop at the first odd prime. if start ==...
f9d31311fa563aacdbb541583f00ac178d2b1cdc
mchrzanowski/ProjectEuler
/src/python/Problem019.py
1,268
3.78125
4
''' Created on Jan 16, 2012 @author: mchrzanowski ''' from time import time YEAR_LIMIT = 2001 YEAR_BASE = 1900 daysInMonth = { 1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, ...
3648ca0b5536bcc00bb779e8a023079364e19003
iljones00/TicTacToe
/TicTacToe.py
1,409
3.71875
4
import Model from View import View, ConsoleView, MiniView from Strategies import * def main(): model = Model.Model(3, 3) view = MiniView(model) strategy = playAnyOpenPosition(model) print("This is the game of Tic Tac Toe") print("Moves must be made in the format 'x,y' where x and y are the coordin...
4ef7941c333484fc25c4b37e9cfd8a58993e6722
ykmc/contest
/atcoder-old/2015/0818_abc027/b.py
730
3.578125
4
# Python3 (3.4.3) import sys input = sys.stdin.readline # ------------------------------------------------------------- # function # ------------------------------------------------------------- # ------------------------------------------------------------- # main # -------------------------------------------------...
0d304747aaae387f0fe931a0f1ca1f9666faaaba
prtk94/Python-Scripts
/hangman.py
1,497
3.796875
4
#A basic hangman game. import random #dict with keys as movie name and values as a list of clues. movie_db={'Inception' : ['Sci fi movie','Directed by Chirstopher Nolan'], 'Spiderman' : ['Superhero movie','Features a friendly neighbourhood guy'], 'Home Alone' : ['Kids movie'] } gameOver= False themo...
d4638e1949299167c8580b8f61c1b0d9f5b43280
yenjenny1010/homework
/EX04_22.py
412
3.953125
4
#s0951034 顏禎誼 x,y=eval(input("Enter a point with two coordinates:(seperate by comma) ")) distance=(x**2+y**2)**(1/2)#計算與原點距離 if distance<10: print("Point (" ,x,",",y, ") is in the circle") elif distance==10: print("Point (" ,x,",",y, ") is on the circle") else: print("Point (" ,x,",",y, ") is not in the cir...
2abf36f2f383c05c27879d59394dc2b326a31e7a
thanhtd91/proso-apps
/proso/list.py
980
4.09375
4
""" Utility functions for manipulation with Python lists. """ import proso.dict def flatten(xxs): """ Take a list of lists and return list of values. .. testsetup:: from proso.list import flatten .. doctest:: >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ return [...
70d05ab9ca90e384aaa08eb3699dc5f1e9e718de
Zokol/blackhat-python
/src/task2.py
958
3.625
4
import sys import re sample = "$8:2>9#2%2$#>90$#%>90" def is_printable(s): if len(set(s)) < 4: return False return bool(re.match('^[a-zA-Z0-9]+$', s)) #return not any(repr(ch).startswith("'\\x") or repr(ch).startswith("'\\u") for ch in s) def testXOR(s): for i in range(0, 255)...
0077eae25b7f9731ffa985e5f7a8e079e417c27b
ScottBlaine/mycode
/fact/loopingch.py
808
4.28125
4
#!/usr/bin/env python3 farms = [{"name": "NE Farm", "agriculture": ["sheep", "cows", "pigs", "chickens", "llamas", "cats"]}, {"name": "W Farm", "agriculture": ["pigs", "chickens", "llamas"]}, {"name": "SE Farm", "agriculture": ["chickens", "carrots", "celery"]}] Farm = farms[0] for...
53b199987de8d0e6982fda66e1def7226d44a1ff
ChrisMusson/Problem-Solving
/HackerRank/RegEx/0-Easy/17-alternative-matching.py
293
3.59375
4
''' Given a test string, S, write a RegEx that matches S under the following conditions: S must start with Mr., Mrs., Ms., Dr. or Er.. The rest of the string must contain only one or more English alphabetic letters (upper and lowercase). ''' regex_pattern = r"^(Mr|Mrs|Ms|Dr|Er)\.[a-zA-Z]+$"
db4ad5a5c2dec491b9d50a14aaf617b2cebe5ebe
ChrisMusson/Problem-Solving
/Project Euler/032_Pandigital_products.py
1,622
4
4
''' We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Fin...
9ac7cd01376277bb2c276880b8127768a967acf7
ChrisMusson/Problem-Solving
/Project Euler/050_Consecutive_prime_sum.py
1,628
3.84375
4
''' The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime,...
b70f2af3499fde9447ec8739f19601e97671c4c6
ChrisMusson/Problem-Solving
/Project Euler/014_Longest_Collatz_sequence.py
1,250
4.03125
4
''' The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) c...
33d66808b44b182de3a9978dee9a8e88ce2d8b83
kranthikiranm67/TestWorkshop
/question_03.py
1,044
4.1875
4
#question_03 = """ An anagram I am Given two strings s0 and s1, return whether they are anagrams of each other. Two words are anagrams when you can rearrange one to become the other. For example, “listen” and “silent” are anagrams. Constraints: - Length of s0 and s1 is at most 5000. Example 1: Input: s0 = “listen” ...
c29b943b165450a4c087cb85e5b2c40c67661b8d
AlenaRyzhkova/CS50
/pset6/sentimental/crack.py
1,680
3.6875
4
import sys import crypt def findPassword(hash, salt, guessPass): # trying for 1-letter key for fst in range(ord('A'), ord('z')): guessPass=chr(fst) tryingHash = crypt.crypt(guessPass,salt) if tryingHash == hash: print(guessPass) return # trying for 2 lett...
26c06e9f868010768bdc7c7248cd1bf69032b1c4
AlenaRyzhkova/CS50
/pset6/sentimental/caesar.py
628
4.21875
4
from cs50 import get_string import sys # 1. get the key if not len(sys.argv)==2: print("Usage: python caesar.py <key>") sys.exit(1) key = int(sys.argv[1]) # 2. get plain text plaintext = get_string("Please, enter a text for encryption: ") print("Plaintext: " + plaintext) # 3. encipter ciphertext="" for c in ...
8820e78c180b4a61dfcd417047605a0dba15a1fe
Imonymous/Practice
/Interviews/Amazon/automata.py
666
3.546875
4
#!/usr/bin/env python def exor(a, b): if a == b: return 0 else: return 1 def cellCompete(states, days): # WRITE YOUR CODE HERE n = len(states) if states == [0]*(n) or days <= 0: return states for i in range(days): new_states = [0]*(n) for j in range(n):...
130ec723c0d1278ea92bf3f3f56b294f358e199c
Imonymous/Practice
/Recursion/pattern_matching.py
1,075
3.5625
4
#!/usr/bin/env python3 # Mock 8 def check_for_all_stars(pattern, pattern_idx): i = pattern_idx while i < len(pattern): if pattern[i] != "*": return False i += 1 return True def doesMatch(string, pattern): return doesMatchRecursive(string, 0, pattern, 0) def doesMatchRecur...
bde17e2a75b7c65cc0ae6d0676ae7f6319f9e45f
Imonymous/Practice
/Trees/printAllPaths.py
2,519
3.546875
4
#!/usr/bin/env python import sys from collections import deque class TreeNode(): def __init__(self, val=None, left_ptr=None, right_ptr=None): self.val = val self.left_ptr = left_ptr self.right_ptr = right_ptr class BinaryTree(): class Edge(): def __init__(self, parentNodeIndex...
f4b77306a9d41e8bf77b05b590c73452ec2cfd4b
Imonymous/Practice
/Sorting/Mock_1.py
1,609
3.96875
4
#!/usr/bin/env python3 # 1st Mock - sort(arr, k) where k=max distance of an element from its original position # Actual attempt (Selection sort) a = [2, 3, 1, 6, 5, 4] k = 2 # def sel_sort(arr, k): # for i in range(len(arr)): # min_idx = i # for j in range(i+1, i+k+1): # if j < len(ar...
0047e4e9211409c8c94e9f20494f72f35f6d60e6
itf/led-curtain-2
/Patterns/ExtraPatterns/StatePatterns.py
5,640
3.703125
4
import random import math import colorsys import Patterns.Pattern as P import Patterns.StaticPatterns.basicPatterns as BP import Patterns.Function as F ''' State Patterns are patterns that have an internal state ''' import Config import random import copy StateCanvas = Config.Canvas _dict_of_state_patterns={} def ...
53139e4c82ea5ba946ba0e1099f550855a3c054d
IvanMerejko/3-semestr
/КГ/lab3.py
2,043
3.65625
4
from tkinter import * PIXEL_SIZE = 2 HEIGHT = 400 WIDTH = 400 black_rbg = 123456 dots = [] window = Tk() # Place canvas in the window canvas = Canvas(window, width=WIDTH, height=HEIGHT) canvas.pack() def is_point_in_line(point, start_line, end_line): x, y = point[0], point[1] x0, y0 = start_line[0], start_l...
17e7494fcbb225659e4e6add6d0f4874fdf87f59
dannslima/MundoPythonGuanabara
/MUNDO3/ex072.py
561
4.25
4
#Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extenso, # de zero até vinte. #Seu programa deverá ler um numero pelo teclado (entre 0 e 20) e motra-lo por extenso. cont = ('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze','doze', 'treze','quatorze','q...
8f47a65043ee96d8ef02c731343b5d103d178edf
navlalli/colour-soap-films
/src/decorators.py
314
3.625
4
""" Decorators """ import time def timeit(func): def wrapper(*args, **kwargs): start_time = time.time() output = func(*args, **kwargs) end_time = time.time() print(f"{func.__name__}() --> {end_time - start_time:.2f} s execution time") return output return wrapper
adb324d9193027da91f64735499ed88bbfb2aa9e
Manish-bit/Fresh
/birth.py
112
3.5625
4
birth_date = input('birth date:') print(type(birth_date)) age = 2020-int(birth_date) print(type(age)) print(age)