blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9c8f4cfc063f8eac099d4e666fb060a514d0781f | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/gbrpri001/question2.py | 438 | 4.09375 | 4 | """PRIYANKA GOBERDHAN
QUESTION TWO
08/05/14"""
count=0
def string_count(word):
global count
if word == '':
return count
else:
if(len(word) > 1 and word[0] == word[1]):
count = count + 1
return string_count(word[2:len(word)])
else:
... |
07094a7fc43f88aba275bd3d89ffbdde7d67990c | MarcosRios1/GuessingGame | /GuessingGame.py | 1,307 | 4.25 | 4 | import random
guess = 3
def guessing_game():
input("Let's play the guessing game! I'm going to ask you to select a range to guess between.\n\
Press any key to start! ")
min_ = input("What's the beginning number of the range? ")
max_ = input("What's the max number of the range? ")
global guess_num
... |
1b7c7c99b6ee34bec5c3f951987d38cc0d5d93b7 | Built00/Leetcode | /Target_Sum.py | 3,421 | 4.3125 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# You are given a list of non-negative integers, a1, a2, ..., an,
# and a target, S. Now you have 2 symbols + and -. For each integer,
# you should choose one from + and - as its new symbol.
# Find out how many ways to assign symbols to make sum of integers equal to target ... |
ef13e0688688b1590ad1e636890f83239d3598ee | shingyipcheung/study-path-backend | /edxDB/permutations_brutal_pruning.py | 2,648 | 3.78125 | 4 | # permutation example by Luc
def find_node_set(dictionary):
'''
**goal**: find the set of:
1. all nodes
2. all nodes that is some others' parent
3. all nodes that is some others' child
:param dictionary: dictionary of edges, parent -> list of children
'''
f... |
b5bf52bd7af17042aa158d3d9a03584706ea39cf | Jesta398/project | /while loop/even number(lower-upper.py | 157 | 4 | 4 | lower=int(input("enter the lower limit:"))
upper=int(input("enter the upper limit:"))
while(lower<=upper):
if(lower%2==0):
print(lower)
lower+=1
|
28f1bb4b2d19ce7579bddb3872a0f02376755cce | zksheikh/Hangman | /main.py | 911 | 3.90625 | 4 | import random
a = ["dog", "mouse", "cat"]
word = random.choice(a)
print(len(word))
count = 0
#Lives in the game
lives = 6
#location of the character in the word
location = 0
used = ""
def new_guess(guess):
global count
global lives
global location
global used
if guess not in used:
used... |
9611399328bd7973d5b77106a1bbd8584cc79b7e | OmarMontero/150-challenges-for-python | /eighty-two.py | 434 | 3.78125 | 4 |
def main():
sentence = "No es verdad ángel de amor, que en aquella apartada orilla, si tu novio nos pilla, las hostias me las llevo yo?."
limit = len(sentence)
print(sentence)
low_limit = int(input(f"Type in the low limit(between 0 and {limit}): "))
top = int(input(f"Type in the high limi... |
71b3eed6fe39e359f5ec20b1d015aa35d7be5b18 | allenwhc/Algorithm | /Company/Microsoft/ReverseWordsString(M).py | 674 | 3.8125 | 4 | class Solution(object):
"""
String reverse solution
Time complexity: O(nk), n is length of s, k is average length of each word
Extra space: O(1)
"""
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
if not len(s): return
s.reverse()
start,n=0,len(s... |
a255422f6fb1c26902741b59bce5636a1a357b94 | codeBeefFly/bxg_python_basic | /Day08/21.多态.py | 1,427 | 3.65625 | 4 | '''---------------------- 父类 ----------------------'''
class Human:
def eat(self):
print('人类吃饭')
'''---------------------- 中国人 ----------------------'''
class ZhHuman(Human):
def eat(self):
print('用筷子吃饭')
'''---------------------- 美国人 ----------------------'''
class USHuman(Human):
def eat... |
f189a2dedc078bdb6e3f13a1f2bc3797df2ac944 | shifty049/LeetCode_Practice | /Medium/1609. Even Odd Tree.py | 1,910 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isEvenOddTree(self, root: TreeNode) -> bool:
queue = [root]
lst = []
... |
0da63ab02aa037dd36ddf85c2fd41a662a3093f5 | ztaylor2/data-structures | /src/radixsort.py | 1,704 | 3.96875 | 4 | """Radix sort."""
from collections import OrderedDict
from que_ import Queue
def stringify_nums(nums_list):
"""."""
stringified_nums = []
for num in nums_list:
stringified_nums.append(str(num))
return stringified_nums
def while_condition(string_unsorted_list):
"""."""
num_lengths = [... |
46d98ee77939b7203096a2eafabf627506f3ae9d | bgmacris/100daysOfCode | /Day81/funciones.py | 1,221 | 3.8125 | 4 | def f_len(word):
count = 0
for i in word:
count += 1
return count
def f_split(text_string, delimiter):
lista = []
word = ''
for char in text_string:
if char == delimiter:
lista.append(word)
word = ''
else:
word = word + char
if wo... |
4e4cc4cd2eba56f4571a6a863d1ac182dee2b6e8 | jaredStevens/python-exercises | /Python1/guess_the_number2.py | 387 | 3.984375 | 4 | secret_number = 5
print('I am thinking of a number between 1 and 10.')
while True:
guess = int(input("What's the number? "))
if guess == secret_number:
print('Yes! You win!')
break
elif guess > secret_number:
print('Too high. Try again.')
elif guess < secret_number:
print... |
b43caedc24f8451afa6473a2eb66b1e17a1b7121 | kesihain/python-challenges | /error_fixing.py | 1,822 | 4.28125 | 4 | # Run the code. Read the error message.
# Fix it
# def mean(numbers):
# print(type(numbers))
# total = sum(numbers)
# return total / len(numbers)
# print(mean([5, 3, 6, 10]))
# Define a method called user_details that takes in two arguments
# def user_details(name, occupation):
# return f"Hi! My nam... |
fee1b7356114c8a9b20a76f03f9894d4269ae52f | gabrodhic/MOOCdb | /modeling_ps/analytics/generate_attempt_resource_use.py | 8,863 | 3.578125 | 4 | """
Created on: 2/1/2014
Author: Elaine Han (skewlight@gmail.com)
From problem csv files, generate resource distribution
after each answer attempt (first, second ...) for all users
1. list top resource consulted after each attempt ordered by count/percentatge
2. plot/save historgram of the distribution with
a) no... |
57569e62fa029136f3d9d817f5477e2a500ae6bb | doragon/aribon | /p42/coin.py | 937 | 3.609375 | 4 | """p42 problem"""
# coding: utf-8
# ---------------------------------------------------------
# 硬貨の問題
# ---------------------------------------------------------
def get_used_coin_list(C, A, key_list):
"""
使用したコインのリストを返す
"""
used_coin_list = []
for key in key_list:
for i... |
9f655f6206a724b9a37ab55828ccc869f859a372 | alysse24/finalproject | /main.py | 484 | 3.8125 | 4 | from data import get_data_frame, plot_graph
print('\n')
print('Retrieving data, please wait...')
df = get_data_frame('2009-1-1', '2017-12-1', 'BCHAIN/MKPRU', 'annual', 'bitcoin', 100, 100)
print('\n')
print('This table shows the value of bitcoin and the Reddit statistics for posts containing "bitcoin"')
print('\n')
p... |
180309d829c2fc78cbe605e05e71749e8326c7c7 | FlyingBackdoor/Data-Structures-and-Algorithms | /Python/05 - Graphs.py | 1,367 | 3.75 | 4 | class Graph:
def __init__(self):
self.numberOfNodes = 0
self.adjecentList = {}
def addVertex(self, node):
self.adjecentList[node] = []
self.numberOfNodes += 1
def addEdge(self, node1, node2):
#undirected graph
try:
#for node1
currentC... |
140a49dde3cf7d99cf837777daa203f4cdd4495c | elendmire/class0 | /functions.py | 339 | 3.890625 | 4 | def square(x):
return x*x
def main():
for i in range(10):
#f bilmemne yapmak yerine bu şekilde bağlama da yapabiliriz print olaylarında
print("{} squared is {}".format(i, square(i)))
#ayrıca python yukarıdan aşağıya kodu okur yani fonksiyonu yukarıda yazman lazım!
if __name__ == "__main__":
... |
c76ee37abddf20128f1a8e43442a2b8d92d540e4 | DaBearsCodeMonkey/SchoolProjects | /PlayFair/Playfair.py | 9,336 | 3.53125 | 4 | import re
table = [['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*']]
no_j = [0] * 50
no_x = [0] * 50
j = 0
r = 0
def playfair(secret, plaintext):
secret = input("Enter a keyword: ")
creat... |
b90b067299dbd0f243cb97968bcb4a105a2d0a22 | oceanbei333/leetcode | /897.递增顺序查找树.py | 1,250 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=897 lang=python3
#
# [897] 递增顺序查找树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
... |
b2824c1b3092948b81450eb80e4739e3e5393e69 | aAlejandroz/Airport-IATA-Service | /test/airport_test.py | 3,528 | 3.59375 | 4 | import unittest
from src.Airport import (Airport)
from src.airport_status import (AirportStatus)
class AirportStatusTest(unittest.TestCase):
def setUp(self):
self.airport_status = AirportStatus()
self.iah = Airport("George Bush Intercontinental/houston", 'IAH',None,None,None,None)
self.iad = Airport("Dulles Air... |
e031831f9070f995242589eea35d6e45bfcaaafb | mike006322/ProjectEuler | /Solutions/PE010_summation_of_primes/python/summation_of_primes.py | 984 | 3.515625 | 4 | #!/bin/python3
# https://www.hackerrank.com/contests/projecteuler/challenges/euler010
# This solution is correct but not fast enough
# Number of test cases can be up to 10^4
# Better solution is to build the sieve once up to 10^6, then construct table with the sums
# See fast_summation.py for that implementation
def... |
f8e4f120403b10aa42b88154944e048e44642b9d | ctc316/algorithm-python | /Lintcode/Ladder_37_BB/medium/1357. Path Sum II.py | 790 | 3.75 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a binary tree
@param sum: the sum
@return: the scheme
"""
def pathSum(self, root, sum):
results = []
se... |
6a790093564e6b455a4bc60041f9cc5e76c620ba | djaychela/playground | /codefights/arcade/diving_deeper/array_max_consecutive_sum.py | 297 | 3.59375 | 4 | def arrayMaxConsecutiveSum(inputArray, k):
highest = 0
for i in range(len(inputArray)-k+1):
current = sum(inputArray[i:i+k])
print(i, current)
if current > highest:
highest = current
return highest
print(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2)) |
9861f9d1daebf99dcf394425e3c9071b765c47f9 | redgyuf/guessthenumber | /numcheck.py | 606 | 4.09375 | 4 | import math
def checkEven(randomNumber):
if((randomNumber % 2) == 0):
print("It is even!") # its even
else:
print("It is odd!") # its odd
def checkDivisible(input, randomNumber):
if((randomNumber) % input == 0):
print("It is divisible by {}.\n" .format(input))
else:
... |
9f9e2bb33d0f5ec52c0f38169fb923bcd2614386 | Aabid-Hussain/PythonLearningProg | /Basics/func_inside_func4.py | 1,502 | 4.3125 | 4 | #Decorator - it is function that takes another function as it's argument.
# and add some kind of functionality and return a function without
# altering the original source code function which is passed in
'''
meaning of @decorator_functions
display = decorator_functions(display)
TypeError: wrap... |
9f2833c6eecb0e349128b16a37c0efc042fa7571 | keriwheatley/projectGrandmaGame | /main/fac.py | 516 | 4.5 | 4 | """Write a script to compute how many unique prime factors an integer has.
For example, 12 = 2 x 2 x 3, so has two unique prime factors, 2 and 3.
Use your script to compute the number of unique prime factors of 1234567890."""
def fac(i):
factors = []
print "Starting number is ", i
f = 2
while i <> 1:
w... |
375db9e6f18c343d9ddf2c43cf26c5ad9310f6aa | JasmineRain/Algorithm | /Python/Others/56_Medium_合并区间.py | 652 | 3.71875 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
ans = []
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
ans.append(intervals[0])
for i in range(1, len(intervals)):
if intervals[i... |
81205b153533fee07ed2daf85ae419b9ab2cb545 | krzkrusz/untitled | /hello.py | 440 | 3.96875 | 4 | import os
my_str = "Hello Academy"
str2 = "Hi"
age = 24
name = "Krzysztof"
output=my_str + str2 + " " +str2
str_template = "my name is {}.I am {} years old."
print(str_template.format(name,age))
def add_vegetable(vegetable='carrot', list_of_vegetables=[]):
list_of_vegetables.append(vegetable)
return list_... |
d4e4203069eb8881480a27e04fef0c20a644a189 | Katuri31/PSP | /python/functions.py | 910 | 4.09375 | 4 | '''
#a function is a piece of code which runs when it is refered.
#it is used to utilize the code in more than one place in a program, in-built functions,user defined functions print(),input().
def add(x,y):
return(x+y)
x=3
y=4
z=add(x,y)
print("z=",z)
#or else we can directly write-
#print(add(x,y)) or... |
a1aacca990bdabc1150b4c5e1fb40bbc7026c4d2 | syurskyi/Python_3_Deep_Dive_Part_2 | /Section 8 Iteration Tools/87. Grouping - Coding.py | 7,386 | 4.125 | 4 | print('#' * 52 + ' ### Grouping')
import itertools
with open('cars_2014.csv') as f:
for row in itertools.islice(f, 0, 20):
print(row, end='')
print('#' * 52 + ' Trivial to do with SQL, but a little more work with Python.')
from collections import defaultdict
makes = defaultdict(int)
with open('cars_... |
f1e446377f5448ffbbccf5595a85aff9b8318483 | vero11602/bmi | /bmi.py | 564 | 4.03125 | 4 | weigh = input('你體重多少:')
weigh = float (weigh)
heigh= input('你身高多少')
heigh = float (heigh) / 100
bmi = (weigh) / (heigh **2)
print ('您的bmi為:' , bmi )
if bmi < 18.5:
print ('您的' , bmi , '過輕')
elif bmi >=18.5 and bmi < 24 :
print ('您的' , bmi , '在正常值')
elif bmi >=24 and bmi < 27 :
print ('您的' , bmi , '過重')
elif bmi >... |
d3ac720d3d5dfc94964b820c46c2da28d5c5dfba | rafaelperazzo/programacao-web | /moodledata/vpl_data/74/usersdata/230/39044/submittedfiles/lecker.py | 461 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import math
n1=float(input('Digite primeiro número: '))
n2=float(input('Digite segundo número: '))
n3=float(input('Digite terceiro número: '))
n4=float(input('Digite quarto número: '))
if n2>n1 and n2>n3 and n4>n3:
print('N')
elif n1>n2 and n4>n3:
print('N')
elif n3>n4 and n3>n2 and n1>... |
62fc43cfc8dd6e646357522489e49aefff4ca49d | GauthamAjayKannan/guvi | /onestep.py | 91 | 3.6875 | 4 | n=int(input())
while n!=0:
for i in range(n,0,-1):
print(1,end=" ")
n=n-1
print()
|
2f5be61f4e6d5de4e9aa1f817830d3c883eabb53 | ArunCSK/PythonWeek1 | /pythonbasics.py | 1,501 | 4.1875 | 4 | #print('hi')
from datetime import date
#reverse string
def name():
firstname = input('Enter First name')
lastname = input('Enter Last Name')
#print(firstname + ' ' + lastname)
txt = firstname + ' ' + lastname
reversetxt = reversestring(txt)
newtxt = ""
for t in reversetxt:
newtxt +... |
380a24e8c7aef24c3d294839d8b1609f810f3c47 | GunnarDiestmann/MasterArbeit_CoopLaneChange_Git | /src/cost_and_evaluation_functions_python/Vehicle.py | 3,074 | 3.578125 | 4 | import numpy as np
import cost_function
class VehicleList(object):
veh_list = []
num_of_veh_tl = 0
num_of_veh_il = 0
class VehicleEnvelop(object):
"""
This class describes the outlines of a vehicle
"""
def __init__(self, veh_properties):
"""
:type veh_properties: VehicleP... |
20d7992cb93bcfe1c5b229a761d3b2bfb4e541d8 | liu839/python_stu | /程序记录/类与对象/两点间距.py | 432 | 3.609375 | 4 | import math as m
class Point():
def __init__(self,x):
self.posion=[x[0],x[1]]
class Line():
def __init__(self,a,b):
self.length=0.0
self.point_a=Point(a)
self.point_b=Point(b)
def get_len(self):
self.length=m.sqrt(pow(self.point_a.posion[0]-self.point_b.posion[0],2)+p... |
71a1c49da511401df03ad52f294d3f8055208c41 | Axieof/DiceRoller | /diceroll.py | 1,380 | 4.0625 | 4 | #Program by Pritheev
#Dice Roller
import random
#Variable Initialization
Loop = True
DiceSet = False
def MainMenu():
print("========================")
print("[1] Choose Dice Size")
print("[2] Roll Dice")
print("[0] Exit")
print("========================")
def CoolDice(Number):
print("+++++")... |
567bc248b9c440fe5d06ebe0282ea0db5c647f42 | ZarmeenLakhani/Python-Documentation | /Calendar.py | 541 | 4.15625 | 4 | import calendar
print (calendar.weekheader(3))
print("")
print(calendar.month(2020,3))
print(calendar.monthcalendar(2020, 2))
#this is in more scalar form. Here the 2 is basically
print(calendar.calendar(2020))
print("")
day_of_week=calendar.weekday(2020,9,21)
print(day_of_week)
#In python days start from monday and i... |
4462079897a0c890a48678ff23e70df32694e505 | bowie2k3/cos205 | /COS-205_assignment5b_AJmemoized.py | 873 | 4.625 | 5 |
# Write a function to compute the nth Fibonacci number. A Fibonacci sequence
# is a sequence of numbers where each successive number is the sum of the
# previous two. The classic Fibonacci sequence begins as 1, 1, 2, 3, 5, 8, 13, ...
import time
def fibo(n):
memo = {}
if n in memo:
return memo
if... |
31253153bbc48e3c4884beaca2b3a1fa4a4b9375 | gavinmcguigan/gav_euler_challenge_100 | /Problem_24/LexicographicPermutations.py | 1,325 | 3.859375 | 4 | from globs import *
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:
... |
94adbe8e68cb706ad9e841536c335bda11ed63a6 | CodingWD/course | /python/chenmingming/class/restaurant.py | 1,291 | 3.734375 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print('this restaurant\'name is '+ self.restaurant_name.title())
print('and it is a '+self.cuisine_type+' rest... |
d8bd47faca977c597b5c72ef899e9e984d1d9c93 | codefather91/100DaysOfPython | /Day-004-Randomization_Lists/RockPaperScissors.py | 2,107 | 4.28125 | 4 | # A simple game of rock paper scissors
# Simple rules:
# Rock beats scissors
# Scissors beats Paper
# Paper beats Rock
# import random module
import random
#initialise ASCII art for rock, paper & scissors
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
__... |
ccb29ce6948dd0d8c8b171adcf4a5f46d51a96a7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/chtpro001/question2.py | 280 | 4.03125 | 4 | z = input('Enter a message:\n')
def pairing(z):
if len(z)==0 or len(z)==1:
return 0
elif z[0]==z[1]:
return 1 + pairing(z[2:])
elif z[0]!=z[1]:
return pairing(z[1:])
print('Number of pairs:',pairing(z))
|
7ec15b2148bc965392f971dfd414552bebf89be9 | kugg/Recordsticker | /ui/terminalui/__init__.py | 2,785 | 3.5625 | 4 | """
Text User interface for searching on discogs.
"""
import curses
from curses.textpad import Textbox, rectangle
def enter_is_terminate(x):
"""This thing makes enter terminate the input."""
if x == 10:
return 7
else:
return x
def compact(input, maxlen=70):
"""Creates a compact strin... |
9838e831860754198a972d15649aa6d2ef8e93c4 | mnevadom/pythonhelp | /3_colecciones/diccionarios.py | 676 | 3.9375 | 4 | # desordenados. Con clave y valor
diccionario = {}
diccionario = {"azul" : "blue", "amarillo" : "yellow"}
print(diccionario)
print(diccionario["azul"])
# agregar. y esto es desordenado siempre
diccionario["verde"] = "green"
diccionario["azul"] = "Bluuue"
del(diccionario["verde"])
diccionario2 = {"Mario": [22, 1... |
0ed1e580de30341b6b75d990e9a62996d370418a | claraxuxu/Python_joy | /image_to_code.py | 1,212 | 3.5625 | 4 |
from PIL import Image # use the Pillow library, for download : sudo pip install Pillow
import os
IMG= 'pics/cat.jpg'
path = os.path.join(os.getcwd(), IMG)
img = Image.open(path)
WIDTH = int(round(img.size[0] /10)) #get current image's width
HEIGHT = int (round(img.size[1] / 18)) # get current image's height and... |
95f5dc1188949d6379cefe90d445b6a07b7a1fab | Prayatna-To-Prabhutva/Learn_Code | /Typing Speed.py | 2,254 | 3.953125 | 4 | import time
import enchant
import re
from WordCount import Word_Count
Test_Phrase = """At three o’clock precisely I was at Baker Street, but Holmes had not
yet returned. The landlady informed me that he had left the house
shortly after eight o’clock in the morning. I sat down beside the
fire, however, with the intenti... |
6f0d74cd0371f412525a345ce85eb720c9137bc5 | thomas-holmes/Euler | /36/36-4.py | 282 | 3.6875 | 4 | #!/usr/bin/python2.7
def is_palindrome(n):
nstr = str(n)
if nstr != str(nstr)[::-1]:
return False
b = str(bin(n))[2:]
return b == b[::-1]
if __name__ == "__main__":
total = 0
for x in range(1,1000000):
if is_palindrome(x):
total += x
print(total)
|
b0f98e6b2b3d66ecd40c796842559a2da99a88ad | rdiaz21129/python3_for_network_engineers | /dev/cisco_devices/dev_test.py | 683 | 3.71875 | 4 |
#https://stackoverflow.com/questions/8583615/how-to-check-if-a-line-has-one-of-the-strings-in-a-list
#https://stackoverflow.com/questions/29106881/check-if-any-of-the-items-of-a-list-is-in-a-line-of-a-file-if-not-then-write-t
# OPen and close file
f = open('serial_numbers.txt', 'r')
f_output = f.readlines()
f.clo... |
45beddcca3ec5081f0c4009df741238717591e8f | Eacaen/diff_Code_Learn | /python/源代码/第八章/8_1.py | 410 | 3.6875 | 4 | # 类的创建
class Fruit::
def __init__(self): # __init__为类的构造函数,后面会详细介绍
self.name = name
self.color = color
def grow(self): # 定义grow函数,类中的函数称为方法
print "Fruit grow ..."
if __name__ == "__main__":
fruit = Fruit() # 实例化
fruit.grow() # 调... |
cc9ab0aa49aa2e30dd6432a59f8b976cf0220334 | yuenliou/leetcode | /141-linked-list-cycle.py | 2,755 | 4 | 4 | #!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from datatype.list_node import ListNode
def hasCycle(head: ListNode) -> bool:
"""
头尾相接的循环链表:p->next == head
6型循环链表:内外遍历 > has表(集合/删除) > 双指针(快慢指针)
双指针问题:翻转链表(前后指针),获取倒数第k个元素(k间距指针),获取中间位置的元素(快慢指针),判断链表是否存在环(快慢指针),判断环的长度(第二次相遇的移动次数)
"""
fast = sl... |
acf94f0e560a9a33bb2945aa31ee529481bf6f1e | seniortesting/cheatsheet-startup-parent | /cheatsheet-startup-python/example-basic/builtin/types-fun.py | 353 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import types
def test():
print('test')
if __name__ == '__main__':
isfun=type(test)==types.FunctionType
print('isfun: ',isfun)
isbuiltin=type(abs)==types.BuiltinFunctionType
print(isbuiltin)
islamba=type(lambda x:x+3)==types.LambdaType
print(i... |
85b6caf8616a4868b52dd1ee7076b93ab18a226b | Shadat-tonmoy/DeepLearningNanoDegreeUdacity | /NeuralNetworks/projects/SentimentAnalysis/NLTK/03.Stemming.py | 1,050 | 4.15625 | 4 | from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
'''
Stemming is the process of cut off sufix like ing, ed, s, es etc from words and get back the root word
For example, Write, Writing, Written, Writes will be stemmed to the root same word Write
NLTK use P... |
511c1098457bf1728453b0d5243e2fc183a7bb1b | samescolas/web-scraping | /src/setup.py | 1,148 | 3.6875 | 4 | import sys
import os
import pickle
def prompt(q):
return input("{}\n>> ".format(q))
try:
config = pickle.load( open("config.pickle", 'rb') )
except:
config = {
'image_dir': '',
'data_dir': ''
}
image_dir = prompt('Where would you like the images saved?')
while not os.path.isdir(image_dir):
yes = prompt("Di... |
e95f209bae96867f64dcd72b62cd61edf2587522 | CalumDoughtyYear3/Functions | /exercise2.8.py | 4,903 | 4 | 4 | import math
### ADD
def add():
first = int(input("Please input first number: "))
second = int(input("Please input second number: "))
answer = first + second
print("Answer = " + str(answer))
### SUBTRACT
def subtract():
first = int(input("Please input first number: "))
second = int(input("Pleas... |
dac3554d44d3fc5585e59f8f2e1cb25efdca3763 | stephen1776/Data-Structures-and-Algorithms | /02 - Data Structures/01 - Basic Data Structures/check_brackets.py | 1,688 | 3.796875 | 4 | # python3
'''
Input Format. Input contains one string 𝑆 which consists of big and small latin letters, digits, punctuation
marks and brackets from the set []{}().
Output Format. If the code in 𝑆 uses brackets correctly, output “Success" (without the quotes). Otherwise,
output the 1-based index of the first unmatched... |
e0bc5ada09bbb906622c181c757a297733283cb2 | koking0/Algorithm | /LeetCode/Problems/139. Word Break/139. Word Break.py | 842 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-H -*-
# @Time : 2020/6/25 7:59
# @File : 139. Word Break.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex 007
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://github.com/koking0
#... |
63882823dd751b08e3edf3322965ddb3feeec518 | willianjeff/estrutura_sequencial | /Aula 1 - Tarefa_5.py | 121 | 3.765625 | 4 | metros = 0
metros = int(input('Informe a quantidade de metros: '))
print ('O valor em centimetros é = ', metros * 100) |
65dc974fbbebd9fe50bc98f4f9c00cd568ddef75 | mgermaine93/python-playground | /python-coding-bat/list-1/sum2/test_module.py | 1,679 | 3.890625 | 4 | import unittest
from sum2 import sum2
class UnitTests(unittest.TestCase):
def test_1_2_3_returns_3(self):
actual = sum2([1, 2, 3])
expected = 3
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1, 2, 3] to return 3')
def test_1_1_returns_2(self):
... |
1530d904b2e4708da3fc107c25bc54b4431de429 | reinderien/advent | /2017/03/03.py | 1,737 | 3.65625 | 4 | #!/usr/bin/env python3
from math import sqrt
i = 325489
def p1():
def coords(i):
"""
This uses analytical expressions for the size of interior square of the spiral and the
coordinates of the current cell based only on the current index. The expressions are heavily
piecewise but th... |
667f5431676171ec885a009196dcff8c6e241e92 | sunzhongyuan/learnPython | /first.py | 237 | 3.859375 | 4 | print("--------------------游戏??-------------------")
temp = input("请在心里猜一个数字:")
guess = int(temp)
if guess == 8:
print("猜中了!!")
print("是8")
else:
print("猜错了")
print("游戏结束")
|
5a0e5b5a87a087de246b1dd4f72e60d16ca6427a | Code-Wen/LeetCode_Notes | /996.number-of-squareful-arrays.py | 1,303 | 3.5625 | 4 | #
# @lc app=leetcode id=996 lang=python3
#
# [996] Number of Squareful Arrays
#
# https://leetcode.com/problems/number-of-squareful-arrays/description/
#
# algorithms
# Hard (47.61%)
# Likes: 277
# Dislikes: 19
# Total Accepted: 11.5K
# Total Submissions: 24.2K
# Testcase Example: '[1,17,8]'
#
# Given an array A... |
bba08e55984af20a9311113564f852161ea883fe | cnin/python-leetcode | /solutions/solution2.py | 918 | 3.75 | 4 | #encoding=utf8
"""
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.经过替换之后的字符串为We%20Are%20Happy。
时间限制:1秒 空间限制:32768K
"""
class Solution2(object):
def replace_space(self, s):
return s.replace(' ','%20')
def replace_space_alter(self, s):
str_ = ''
for char in s:
str_ =... |
75c174f174668f75a0ee6cb0f8458070042b13f2 | JoanChirinos/AdventOfCode | /2019/day1_1.py | 228 | 3.875 | 4 | def calculate(mass):
return mass // 3 - 2
def go():
with open('day1_INPUT.txt') as f:
nums = f.read()
total = 0
for num in nums.split():
total += calculate(int(num))
print(total)
|
93e020bba6b216ad0b3342254e197a6eec1e96fc | jgam/hackerrank | /arrays/newchaos.py | 739 | 3.609375 | 4 | #this is to use bubble sort
def minimumBribes(queue):
lastIndex = len(queue) - 1
swaps = 0
swaped = False
# check if the queue is too chaotic
for i, v in enumerate(queue):
#finding chaotic here with index pointer moving 2 ahead
if (v - 1) - i > 2:
return "Too chaotic... |
bd109475043269f02ef0956f2a443caabae42765 | theoctober19th/ds-algorithms | /examples/doubly_linked_list.py | 844 | 4.1875 | 4 | from data_structures.doubly_linked_list import DoublyLinkedList
# creating a doubly linked list
animals = DoublyLinkedList()
print('Adding a few elements on the front...')
animals.insert_front('Cow')
animals.insert_front('Tiger')
animals.display()
print('\nAdding a few elements on the back...')
animals.insert_back('... |
d7271e903e70a36e34cdad99719577af07d2035f | ymirthor/T-201-GSKI | /Midterms/Æfing fyrir hlutapórf 2/Arraydeque.py | 2,144 | 3.53125 | 4 | class Arraydeque:
def __init__(self):
self.capacity = 4
self.array = [0] * self.capacity
self.size = 0
self.start = 0
self.end = 0
def __str__(self):
ret_str = ""
walk = self.start
for i in range(self.size):
ret_str += str(self.ar... |
af1228eea2280b0896d6a693e16213885743425f | mniju/Datastructures | /EPI book/9.2 is_tree_symmetric.py | 1,380 | 4.3125 | 4 |
class BinaryTreeNode:
# Utility function to create new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_symmetric(tree:BinaryTreeNode)->bool:
def check_symmetric(subtree_0,subtree_1):
if not subtree_0 and not subtree_1:
... |
2b3fcfa43684186f07597d964b0546e18c38a0b4 | RamonCris222/Ramon-Cristian | /questao_12_listas.py | 411 | 3.71875 | 4 | a = []
b = []
c = []
print("Digite os valores da primeira lista: ")
for i in range(10):
a.append(float(input()))
print("Digite os valores da segunda lista: ")
for i in range(10):
b.append(float(input()))
print("Digite os valores da terceira lista: ")
for i in range(10):
c.append(float(in... |
88cd3bb80fcae3d0b2630154be9887310cbe9ea9 | wiktoriamroczko/pp1 | /02-ControlStructures/zadanie49.py | 471 | 3.921875 | 4 | print ('| PN | WT | SR | CZ | PT | SB | ND |')
nrDniaTygodnia =3
print ('| '*nrDniaTygodnia, end='')
for i in range(1, 31):
if i < 10:
print ('|', i, end=' ')
elif i >=10:
print ('|', i, end=' ')
if i == 7-nrDniaTygodnia:
print ('|')
if i == 14-nrDniaTygodnia:
print ... |
d7b81a5a8f0df17fc3106e7899a588f0bbe5447e | JiungChoi/Baekjoon | /baekjoon_10809_other.py | 150 | 3.703125 | 4 | ary = list(input())
for i in range(97,123):
if chr(i) in ary:
print(ary.index(chr(i)), end=' ')
else : print(-1, end=' ')
|
2c13e487abd8f6ebb73386de7b707853761519a2 | lukaszsi/Automate-the-Boring-Stuff---practical-tasks | /Chapter 8/CH08_mad_libs.py | 792 | 4.1875 | 4 | #! Python3
'''Script that finds words like ADJECTIVE, NOUN, ADVERB, VERB
in a given text and enables to override them. '''
import re
# opens .txt file
textFile = open(input('Name of the file? '))
newTextFile = textFile.read()
textFile.close()
# regexes and changing of the text
words = ['ADJECTIVE', 'NOUN', ... |
ac073bbfd0591d73787ef7d0a6e5ead2b4ce6f1e | ozcayci/python_examples | /examples_two/quest_03.py | 323 | 3.96875 | 4 | def isIntAndPositive(val):
if val.isdigit():
return True
number = input("Please a give number: ")
if isIntAndPositive(number):
number = int(number)
total = 0
for i in range(0, 3):
total += number * int("1" * (i + 1))
print(total)
else:
print("Invalid value"... |
fa23fb8a8de28c3e6eb8e5f91526c022191c7b49 | cadelau/NN_EECS_445 | /visualize_cnn.py | 2,012 | 3.546875 | 4 | """
EECS 445 - Introduction to Machine Learning
Winter 2019 - Project 2
Visualize CNN
This will produce visualizations of the activations of the
first convolutional layer and save them to file.
Usage: python visualize_cnn.py
"""
import torch
import torch.nn.functional as F
import numpy as np
import utils
... |
ebe65aff36fa0cb5dd914b65f795309baa7bd75d | JaeHeee/algorithm | /baekjoon_python/10866.py | 952 | 3.765625 | 4 | #10866 Deque
count = int(input(''))
deque = []
for i in range(0,count):
command= str(input(''))
if "push_front" in command:
number = int(command[10:])
deque.insert(0,number)
elif "push_back" in command:
number = int(command[10:])
deque.append(number)
elif command == "po... |
b0204c0deab0e0e25166fb57e311627870c911c8 | Amirreza5/Class | /example_string02.py | 584 | 3.984375 | 4 | x = 'maryam is a student'
name = 'Samira'
list_name = ['Amire', 'Lena', 'Amirh', 'moein']
#1)length01 = len(x)
#print(length01)
#for character in x:
#if character == 'm':
#print(character)
#2)print('maryam' in x)
#3)print(x[0:6])
#4)print(x.capitalize())
#5)print(x.upper())
#6)print(x.case... |
c9693b4cf2204956cefd5b394b5397aa821db320 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2706/60781/280206.py | 274 | 3.90625 | 4 | str1=input()
pan=0
if(str1=='[["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]'):
print([["John", 'johnsmith@mail.com', 'john00@mail.com', 'john_newyork@mail.com'], ["John", "johnnybravo@mail.com... |
a89a60b286af90a01447471f18579f1512a3c20b | blhwong/algos_py | /leet/merge_two_sorted_lists/main.py | 1,048 | 3.875 | 4 | from data_structures.list_node import ListNode
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
curr1 = l1
curr2 = l2
head = None
tail = None
def add_to_tail(val):
nonlocal head
nonlocal tail
if not head:
... |
fa86c6e6bee5af05880acb2b8bee828fa1372fc9 | JasonTLM/multiprocess_spider | /queue_get_put.py | 923 | 3.59375 | 4 | # coding=utf-8
"""
queue中,put和get的参数里默认拥有一个block参数,默认为True,即为在插入队列为满或者取出为空时
默认为阻塞状态,等待取出取出或者插入数据。
"""
from queue import Queue
import time
import threading
def put_value(q):
index = 0
# another = 1
while True:
q.put(index)
# q.put(another)
index += 1
# another += 1
... |
b0ea78999e4b9c95ac84162c46aba65e692a93a6 | drcyfai/Computer-Vision | /5thCV_ClassicCV_Project1_ImageStitching_by_ChenYaofeng.py | 5,983 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### AI 第五期 CV 课 Classic CV project 1: Image Stitching
# #### Student: Chen Yaofeng
# In[ ]:
"""
The image stitching algorithm consists of four steps:
Step #1: Detect keypoints (DoG, Harris, etc.) and extract local invariant descriptors (SIFT, SURF, etc.) from the two input i... |
c4fd22f5eed45b43457dd5b3fed8ddb74c147627 | ChrisLiu95/Leetcode | /leetcode/array_partition.py | 1,429 | 3.875 | 4 | """
Given an array of 2n integers, your task is to group these integers into n pairs of integer,
say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + m... |
d2741915cf265207e3918cd8e87c6b4b9f65ccd4 | lhserafim/python-100-days-of-code-monorepo | /day-4/treasure-map/main.py | 704 | 4.0625 | 4 | # 🚨 Don't change the code below 👇
# I'm using emojis
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
#sp... |
4dbcee2267ffb4b83aa965a1ffd4a8b276fee08e | juliagimbernat/nlp | /percentages.py | 160 | 3.765625 | 4 | import re
import pandas as pd
#x = "This is a percentage 12-16%"
#result = re.findall(r'[0-9]*\-?[0-9]+\%', x)
#print(result)
x = "low controls"
result = |
ca61253cdbfb3ea4cc27622c97f2194c86bc61d9 | Tharsisboamorte/BLASTOFF | /Blastoff questão 6.py | 887 | 4.09375 | 4 | #Nas 13 primeiras linhas eu utilizo da conversão de horas para segundos e de minutos para segundos para fazer o calulor da diferença posteriormente na linha 16
print("Esse programa vai calcular quanto tempo durou a partida de futebol que você participou/assistiu")
print("Digite as horas inicias:")
h1 = int(input())
... |
499feb0f5edd5e46ad0b38716c73b5835a9b8738 | MY-Park/AI-Projects | /2017_코드_A*.py | 40,378 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import math
# AlphaBeta, GameTree, GameNode class modify from https://tonypoer.io/2016/10/28/
class AlphaBeta:
def __init__(self, game_tree, AI_turn):
self.game_tree = game_tree
self.root = game_tree.root
self.AIturn = AI_turn
return
def alpha_beta_sea... |
8051d9bb3f98a3b9a5768e4a7ab760caee2ff00d | Mehvix/competitive-programming | /MSOE Op Computer Competition/2018/2018_Problem7.py | 1,550 | 4 | 4 | import math
time = int(input("Enter UNIX time:"))
# time = 1111111111
minute = 60
hour = minute * 60
day = hour * 24
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
year_noleap = day * 365
year_leap = day * 366
year_four = 3*year_noleap + year_leap
total_years = 1970
total_months = 1
total_days = 1
total_ho... |
c8c7c66658202d2683239abb752d02055bd19b7e | sbbasak/CIT_ES_PP_2001_Assignment-1 | /input.py | 128 | 4.375 | 4 |
# 1. take an input and print it.
print('Enter your nick name:')
your_name = input()
print('Welcome!' + your_name + '.')
|
423a23b0a17a7bda7427234788ab293d6d1d0711 | or0986113303/LeetCodeLearn | /python/280 - Wiggle Sort/main.py | 1,226 | 3.953125 | 4 | class Solution(object):
def mergesort(self, source):
if len(source) <= 1 :
return source
middle = len(source) >> 1
leftpart = self.mergesort(source[:middle])
rightpart = self.mergesort(source[middle:])
return self.merge(leftpart, rightpart)
def merge(self, lef... |
5f1e06850c679d27d599e38370968d24fb0a69ee | skyyi1126/leetcode | /quora_diagonal_sort.py | 555 | 3.796875 | 4 | def solution(A):
N = len(A)
def sort_diagonal(i,j): #i, j is the starting index of the diagonal line
to_sort = []
while (i<N and j<N):
to_sort.append(A[i][j])
i += 1
j += 1
i -= 1
j -= 1
to_sort.sort()
while (i>-1 and j>-1):
... |
bdb211d000daaa801da4e9eddc85346d5f781845 | xshirl/ctci | /chapter2/2.4.partition.py | 1,560 | 3.765625 | 4 | from Node import Node
def partition(head, x):
h1 = l1 = Node(0)
h2 = l2 = Node(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = h2.next
... |
6f7b804a5988266451ae56fa94d2c3bd90855f59 | IchiiDev/homeworks | /NSI-Terminale-2021-2022/modules/exercises/balistique.py | 1,887 | 3.703125 | 4 | import math
import matplotlib.pyplot as plt
import numpy as np
import turtle as t
class projectile:
G = 9.81
def __init__(self, alpha, v, h):
self.alpha = alpha
self.v = v
self.h = h
return
def getDistance(self):
return (self.v / self.G) * math.cos(self.al... |
b4c469f92139c4e13006f5a746bc127e4bd4a094 | RowanASRCResearch/Image-Fusion | /Merging/ImageMerge.py | 14,451 | 3.640625 | 4 | from PIL import Image
import PixelProcess
debug = 0
class Merger:
def __init__(self, outfile):
"""
`Author`: Bill Clark
A merger is a class that allows for a number of images to merged sequentially. It is designed to
merge each image incrementally, outputting to an outfile when... |
766ed7715a9ae969fdcc7718bf13839981ccdd4d | cccccccccccccc/Myleetcode | /49/groupanagrams.py | 990 | 3.65625 | 4 | """
timecomplexity = O(n*m) n=len(strs),m=len(s) s is item in strs spacecomplexity = O(n+m)
construct deflautdict deflautdict is a method from moudle collections can easy to use append() from List
use the deflautdict to contain result. iterate all s in strs, define tmp list count [0]*26, iterate every word in s
and d... |
908d5206ec6e0d288f038a9fc6f6006a083e442e | rebecca16/CYPAbigailAD | /libro/problemas_resueltos/capitulo1/ifelse.py | 299 | 3.90625 | 4 | edad = int (input("Dame tu edad: ") )
INE = bool (int (input("Tines INE (0 No / 1 Si)?: ") ) )
if edad >= 18 and INE == True:
print ("Es mayor de edad")
print ("Puede entrar al bar")
else:
print ("Eres menor de edad")
print ("Puedes ir a jugar Lol")
print ("Fin del programa")
|
e9e66f8a248e413ac15d93621b32cb2e164653e1 | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Strings/Permutations of a given string.py | 487 | 4.125 | 4 | # Given a string, print all permutations of a given string.
string = list('ABC')
def permutations(string, step = 0):
if step == len(string):
print ("".join(string), end=" ")
for i in range(step, len(string)):
string_copy = [character for character in string]
string_copy[step], string_... |
fdfb5c6fdf991787b26fc3834f96832ab4a7fed1 | sushmithasushi/playerlevel | /HEXA.py | 127 | 3.75 | 4 | try:
a1=input()
a1=int(a1,16)
a1=str(a1)
if a1.isnumeric()==True:
print('yes')
except:
print('no')
|
43e84f0117eaa3cc6d31afccd211cd730c9cc002 | Toka-Taka/mill-db | /pymilldb/context/Argument.py | 1,166 | 3.9375 | 4 | import abc
class Argument(abc.ABC):
def __init__(self, name):
self.name = name
@abc.abstractmethod
def print(self):
pass
@abc.abstractmethod
def signature(self):
pass
class ArgumentParameter(Argument):
def __init__(self, name, parameter=None):
super().__init... |
e9d5de9016239474c04185415bcb200b68a84568 | apurvdhadankar/Translator-with-python | /translator.py | 652 | 3.71875 | 4 | import tkinter as tk
from googletrans import Translator
win = tk.Tk()
win.title("Translator")
win.geometry("300x150")
def translation():
word = entry.get()
translator = Translator(service_urls=['translate.google.com'])
translation1 = translator.translate(word,dest="marathi")
label1 = tk.Label(win,tex... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.