blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
18e60ef7e40d3a66201d24c96c3967b21a072150 | daniel-reich/ubiquitous-fiesta | /M47FDJLjfNoZ6k6gF_24.py | 183 | 3.65625 | 4 |
def cup_swapping(swaps):
current = 'B'
for i in swaps:
if current in i:
if current == i[0]:
current = i[1]
else:
current = i[0]
return current
|
8d5217dc93c27b806aa6db88ccb60af09b03dbd7 | reynardasis/code-sample | /ex16.py | 646 | 4.125 | 4 | from sys import argv
script, filename = argv
print "we're going to erase %r" %filename
print "press ctrl+c if you dont want"
print "Press enter if you want to proceed"
raw_input("?")
print "Opening file.."
target = open(filename, 'w' , 'r')
print "Erasing data in file..."
target.truncate()
print "Now im going to ... |
34c1822e5f366ad5e3dd7d8a069744dc2b24d199 | pascuapablo/CEIA | /src/deepLearning/Layer.py | 969 | 3.5625 | 4 | import numpy as np
from src.deepLearning.activationFunctions.IActivationFunction import IActivationFunction
from src.deepLearning.activationFunctions.SigmoidActivationFunction import SigmoidActivationFunction
class Layer(object):
def __init__(self, input_size: int = 1, neurons: int = 1,
activati... |
8f2c4c9cc76f770a29a89878dcece6670ed5d0b3 | venki19/pythontoto | /PycharmProjects/Myfirstproject/file_handling.py | 226 | 3.59375 | 4 | file = open("demo.txt", "w")
file.write("this is a new line")
file.close()
file = open("demo.txt", "r")
print(file.read())
file.close()
file = open("demo.txt", "a")
file.write("This is the second line entered")
file.close()
|
6bc6304e7852c80be830b6dd82f5031ad7065bcf | JayIvhen/LabMIPT | /lab5lecture8/task5.py | 506 | 3.953125 | 4 | """
curve of minkovskiy
"""
import turtle as T
LENGTH = 2000
N = 3
def curve(len, n):
if n == 0:
T.forward(len)
return
curve(len / 8, n - 1)
T.left(90)
curve(len / 8, n - 1)
T.right(90)
curve(len / 8, n - 1)
T.right(90)
curve(len / 8, n - 1)
curve(len / 8, n - 1)
... |
8fc17a276b91e34b4e1408a75b89dbef4c265e4b | mjnbrn/pythonThings | /atbs/myPets.py | 193 | 4.125 | 4 | myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a name.')
name = input()
if name not in myPets:
print(f" I do not have a pet name {name}.")
else:
print(f"{name} is my pet.") |
baada4b0227822a57055b4ccc2673a442b3fafbf | Aninassimova/Machine_Learning | /numpy&Matpoltlib/numpy/python_base.py | 2,231 | 4.28125 | 4 | #Python中字符串相关的处理都非常方便,来看例子:
a = 'Life is short, you need Python'
a.lower() # 'life is short, you need Python'
a.upper() # 'LIFE IS SHORT, YOU NEED PYTHON'
a.count('i') # 2
a.find('e') # 从左向右查找'e',3
a.rfind('need') # 从右向左查找'need',19
a.replace('you', 'I') #... |
8502fa0bca90cefdf0af85438f3957193f194845 | TMAC135/Pracrice | /isvalidparentheses.py | 2,326 | 3.84375 | 4 | ##Given a string containing just the characters '(', ')',
#'{', '}', '[' and ']', determine if the input string is valid.
#Example
#The brackets must close in the correct order,
#"()" and "()[]{}" are all valid but "(]" and "([)]" are not.
#my solution
# class Solution:
# # @param {string} s A string
# # @re... |
24d45f8096e40785a34a76bb3220b0c9ada63bee | Aasthaengg/IBMdataset | /Python_codes/p03307/s679796946.py | 133 | 3.796875 | 4 | n = int(input())
def gcd(a,b):
if b == 0:
return a
return gcd(b,a%b)
def lcm(a,b):
return a * b // gcd(a,b)
print(lcm(n,2)) |
a8149c82967f6b30f76b2be4cf8118f681f44347 | ccnelson/Python | /dynamic_classes/dynamic_class.py | 460 | 3.765625 | 4 |
def hello_world(obj):
print("Hello World from %s!" % obj)
class BaseClass(object):
def __init__(self, instance_name):
self.instance_name = instance_name
def __repr__(self):
return self.instance_name
my_class = type("MyClass", (BaseClass,), {"hello_world": hello_world})
my_cla... |
4e6d7331b5c880bbc9fedaa4a611c2c2d226b0f8 | MassloveDen/DjangoMovie | /movies/learn.py | 212 | 3.578125 | 4 | from tkinter import Tk
x = [7,8]
print(x)
x.append(5)
print(x)
class Try:
def show(self, name = "unknown"):
print('hello, '+ name)
x = Try()
y = Try()
x.show()
y.show("Den") |
77be16ae7d9f90099a103c018b9b140fb0ef670c | FahimCC/Problem-Solving | /Hacker Rank/PythonWithHackerrank/Hello World.py | 170 | 3.796875 | 4 | import sys
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
if __name__ == "__main__":
name = input("Enter your name: ")
print("My name is ",name) |
5ba749ad8c6c02ffc48fba5eeb8eb70b8a7003e7 | rafaelperazzo/programacao-web | /moodledata/vpl_data/164/usersdata/268/65811/submittedfiles/triangulo.py | 223 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import math
a= int(input('Digite o lado a '))
b= int(input('Digite o lado b '))
c= int(input('Digite o lado c '))
if (a> b + c) or (a == b + c):
print('N')
if (a< b+c):
print('S')
|
c813f480de1e82ea1e3de8f250f1780f0b2d913e | rzuniga64/python | /udemy/lesson12_data_structures/list.py | 732 | 4.1875 | 4 | """
List is an ordered sequence of items. It is one of the most used datatype in
Python and is very flexible. All the items in a list do not need to be of the
same type. Declaring a list is pretty straight forward. Items separated by
commas are enclosed within brackets [ ].
"""
# empty list
x = []
a = [5, 10, 15, 20, ... |
5cf5beac484eb237abf2574887fb68ad1610e4ec | adurtys/gene_expression_lookup | /parseForProteinCoding.py | 1,832 | 3.515625 | 4 | # Date Created: 12 July 2018
# Date Last Modified: 13 July 2018
# Execution: python parseForProteinCoding.py geneIdList
# geneIdList is a string containing the name of the file containing the genes to look up
# Description: checks whether a list of ENSGIDs is protein-coding, according to GENCODE
#!/usr/bin/env python
... |
67fe8d88409a4af7af4cae12257ceceb2b8b2187 | DanielMoscardini-zz/python | /pythonProject/Curso Em Video Python/Mundo 1/ex030.py | 228 | 4 | 4 | """
Faça um software que leia um numero e retorne se o mesmo é par ou impar
"""
numero = int(input('Digite o numero: '))
if (numero % 2 == 0):
print(f'Numero {numero} é PAR')
else :
print(f'Numero {numero} é IMPAR')
|
d8c9a10a57e0ab9a87da4ffe8990174adccd7092 | bycycle-tools/bycycle | /tutorials/plot_1_bycycle_philosophy.py | 7,251 | 3.921875 | 4 | """
1. Cycle-by-cycle philosophy
============================
Motivations behind the cycle-by-cycle approach.
Neural signals, like the example shown below, are analyzed in order to extract information about
brain activity. Basically, we process these signals in order to extract features that will hopefully
correlate ... |
354c516310d4bf1dfbb6dd33fad24a3e6617f999 | sakho3600/data-analytics | /Lesson 1 - Numpy/array_index_1.py | 210 | 3.515625 | 4 | import numpy as np
array = np.arange(0, 12)
print(array)
print(array[0])
print(array[0:5])
print(array[2:6])
array[0:5] = 20
print(array)
array[:] = 29
print(array)
array_copy = array.copy()
print(array_copy) |
150ccc7c87e3d16240075d8569cfc419400077c7 | Nathaniel-Rodriguez/utilities | /utilities/listmanipulation.py | 588 | 4 | 4 | def chunk_generator(l, n):
"""
Attempts to divide list into chunks of size n
Returns a generators that yields successive n-sized chunks from l.
"""
for i in xrange(0, len(l), n):
yield l[i:i + n]
def chunk_list(l, n):
"""
Attempts to divide list into chunks of size n
"""
re... |
7e8e4ab99469a6096b946a143ec2f7d27ea35834 | warg15/Dynamic-Programming-with-Hidden-Markov-Models-208 | /Directed Acyclic Graph/LCA.py | 2,544 | 3.9375 | 4 | #!/usr/bin/env python3
def find_LCAs(parent):
LCA = dict() # This is the nested dictionary you will be modifying
# TODO You will fill in the following "lca" function
def lca(u, v):
#This function computes the Least Common Ancestor between nodes u and v
#:param u: node u
#:param v: ... |
9fff1721f0b683ff5d8b4af1349bb9a27849228f | beautytiger/project-euler | /problem-062.py | 1,595 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
def cube_length(len_limit = 20):
n = 1
length = 1
len_dict = {}
len_dict[length] = n
while length<len_limit:
n += 1
if len(str(n**3))>length:
length = len(str(n**3))
len_dict[length] = n
return len_dict
def numb... |
e755d9cc864be952293bb671352990b2d06a33db | pingskills/python-for-kids | /chapter-03/wizard.py | 627 | 3.953125 | 4 | wizard_list = [
'spider legs', 'toe of frog', 'eye of newt',
'bat wing', 'slug butter', 'snake dandruff'
]
print(wizard_list)
print(wizard_list[2])
wizard_list[2] = 'snail tongue'
print(wizard_list)
print(wizard_list[2:5])
#append to list
wizard_list.append('mandrake')
wizard_list.append('hemlock')
wizard_li... |
b0476048ab429f1cc88c5aba33e8c04a70294234 | zaidazim/ai50 | /tictactoe/minimax.py | 2,926 | 4.03125 | 4 | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
return None
else:
if player(board) == X:
value, move = max_minimax(board)
return move
elif player(board) == O:
valu... |
1b9e6f306d87646e03cf8a5f28ffcb4aaf579550 | ryanleonbutler/hacker_rank | /challenges/time_delta.py | 548 | 3.875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from datetime import datetime
# Complete the time_delta function below.
def time_delta(t1, t2):
date_fmt = "%a %d %b %Y %H:%M:%S %z"
a = datetime.strptime(t1, date_fmt)
b = datetime.strptime(t2, date_fmt)
difference = int(abs((a... |
c15b8d1b5469a8295b85ccfcef9713c3ca5ddd37 | AndreyTork713/Udemy_Capstone-Projects | /Find PI to the Nth Digit.py | 500 | 4.15625 | 4 | # Find PI to the Nth Digit -
# Enter a number and have the program generate PI up
# to that many decimal places.
# Keep a limit to how far the program will go
import math
precision = int(input('Введите количество знаков после запятой: '))
while precision >= 15:
print('Слишком большое число...')
precision = i... |
7e741ce85d9f5f2f5a916440238e315dd2ce9748 | Yui-Ezic/Numerical-Methods | /labs/lab10.py | 4,930 | 4.34375 | 4 | """ Лабораторна работа номер 10
з курсу Чисельні методи, варіант 6
Завдання: Наближенно обчислити значення визначеного інтеграла з точністю ε = 0.001
за допомогою подвійного перерахунку, узявше початкове значення L = 2.
Використовувати метод Ньютона-Котес... |
f5005e81b3db56e43fd9e046b84b0383556b8a09 | sskate-2002/Documents | /kaijou.py | 147 | 3.59375 | 4 | def kaijou(a):
b = 1
while a > 0:
b = b * a
a = a - 1
return b
answer = str(kaijou(int(input("Enter an integer :"))))
print(answer)
|
e7e3293f72a26440106c435171f3a01d23e2ee1c | taalaybolotbekov/ch1pt2task10 | /task10.py | 874 | 4.21875 | 4 | f = 'In the first line, print the third character of this string'
print(f[3])
s = 'In the second line, print the second to last character of this string.'
print(s[1:-1])
t = 'In the third line, print the first five characters of this string.'
print(t[0:5])
f = 'In the fourth line, print all but the last two characters ... |
e26331615a08f3a466ce72759d20f26fdf4eb900 | bethke/hermes | /src/utils/clean_links.py | 1,291 | 3.6875 | 4 | #!/usr/bin/env python
def clean_links(text):
"""Remove brackets around a wikilink, keeping the label instead of the page
if it exists.
"[[foobar]]" will become "foobar", but "[[foobar|code words]]" will return
"code words".
Args:
text (str): Full text of a Wikipedia article as a single st... |
45fb709b694b3cd7bd148007eecb4bfe0f6de1ad | zarubiak/battlesnake-python | /app/main2.py | 4,897 | 3.734375 | 4 | import bottle
import os
import random
# Testing to see if server is running
#@bottle.route('/')
#def static():
# return "the server is running"
#
def distance(start, object):
# number of moves away from an object
distance_x = abs(int(start[0]) - int(object[0]));
distance_y = abs(int(start[1]) - int(object[1]... |
d0da6a05e71228e4366ab014e47c90a71e7c2401 | F1qN/sotuken | /proneo/human.py | 1,762 | 3.53125 | 4 | import random
from decimal import Decimal
class human:
idenNum = None
x = None
y = None
startTime = None
eatPattern = None
eatTime = None
eatNow = None
evaluation = None
individual = None
def __init__(self,idenNum,x,y):
self.idenNum = idenNum
self.x = x
... |
9fc04eb0f7e5e48c708eaf8e2cdb055bc12f7396 | alancpu/myLeran | /first.py | 189 | 4.09375 | 4 | def fibs(num):
'Calculates the square of the number x'
result = [0,1]
for i in range(num -2):
result.append(result[-2] + result[-1])
return result
print(fibs(10)) |
d7d30fb40e5d2b7fe99e00e38d06f0e1b30948c1 | jmelo77/LSVTech | /bouncy.py | 767 | 3.828125 | 4 | def is_bouncy(number):
asc = 0
desc = 0
for i in range(len(number) - 1):
if (number[i] <= number[i+1]):
asc += 1
if (number[i] >= number[i+1]):
desc += 1
if (asc == len(number) - 1):
# increasing number
return False
elif (desc == (len(num... |
28e4fa84e8f69226f64799d8cf439cbb93df7653 | georgelyuan/inference_results_v1.1 | /closed/FuriosaAI/code/quantization/furiosa_sdk_quantizer/ir/common/operator.py | 447 | 3.671875 | 4 | class HeightWidth:
def __init__(self, height: int, width: int):
self.height = height
self.width = width
class Padding:
def __init__(self, top: int, bottom: int, left: int, right: int):
self.top = top
self.bottom = bottom
self.left = left
self.right = right
cla... |
af3f70a277eda866047b4d76fc885a58c155c45f | dETAIL58/MIT-OpenCourseWare-6.00-Fall-2008 | /scrabble/ps5_ghost.py | 3,254 | 3.9375 | 4 | # Problem Set 5: Ghost
# Name:
# Time: 2:00
#
import random
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
... |
2e09cde6c30031dccb2bdcddd2b113f1f5fce844 | chlxry/cp2019 | /practical_4/q8_find_uppercase.py | 315 | 4.34375 | 4 | # Write a recursive function find_num_uppercase(str) to return the number of uppercase letters in a string str.
# For example, find_num_uppercase('Good MorninG!') returns 3.
def find_num_uppercase(string):
upper = 0
for i in string:
if(i.isupper()):
upper = upper + 1
print(upper)
|
111dce845dbe18cb7bfd223babcdaa8cd05d9c45 | Ericxk09/Aprendizado | /L1.Exercicio 5.py | 325 | 3.609375 | 4 | vlr_mercadoria = float(input('Valor da Mercadoria: $ '))
desconto = float(input('Valor do desconto em %: '))
desconto_final = vlr_mercadoria * (desconto / 100)
vlr_mercadoria_final = vlr_mercadoria - desconto_final
print('Valor do Desconto: $', desconto_final)
print('Valor da Mercadoria: $', vlr_mercadoria_fin... |
e3fa80f25151fd6972e09f57d5b42106aabd014a | lvzhidong/spider | /dict_sort.py | 768 | 3.859375 | 4 | #! user/bin/env python3
# -*- coding:utf-8 -*-
my_dict = {1: "a", 2: "b", -1: "c"}
print(sorted(my_dict.items(), key=lambda x: x[0], reverse=True))
class Screen(object):
__slots__ = ("__width", "__height")
@property # 读
def width(self):
return self.__width
@width.setter # 写
def widt... |
13d1a193d4703a4d4352de2cfd672bb227edbe02 | LittleFee/python-learning-note | /day05/01-while-practice.py | 2,325 | 4 | 4 | # 7-8 熟食店:创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名
# 字;再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders,对于
# 其中的每种三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表
# finished_sandwiches。所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders=['Big Mac','Filet-o-Fish','McChicken','Chicken McNuggets']
finished_sandwiches=[]
while san... |
200c3f80416ec1e370b0ebb9db649142678aa636 | danoliveiradev/PythonExercicios | /ex043.py | 595 | 3.84375 | 4 | print('-=-'*20)
print('\033[33mCalculadora de IMC\033[m')
print('-=-'*20)
peso = float(input('Digite seu peso em Kg: '))
altura = float(input('Digite sua altura em metros: '))
imc = peso / pow(altura, 2)
print('Seu IMC é {:.1f}'.format(imc))
if imc < 18.5:
print('\033[97mVocê está ABAIXO DO PESO\033[m')
elif 18.5 <... |
d15904939bed9bdd7860d7c6730b10b96db4c86d | heyjohnnie/MVA-Introduction-to-Python | /Variables/Variables/Variables/Variables.py | 408 | 4.34375 | 4 | #name = input ("What is your name? ")
#print ("Hi " + name)
#Declaring variable type
#NOTE: Python does not declares variables as C# does!
firstName = " "
lastName = " "
#Requesting input
firstName = input("What's your first name " )
lastName = input("What's yout last name ")
#Switching both variables to start with... |
81cb941c90de171b7121a4d3e0be0d3a5235a558 | wuzi2031/coolbook | /algorithm.py | 1,094 | 3.765625 | 4 | # 展开数组
def exportList(ls):
return sum([exportList(x) if type(x) is list else [x] for x in ls], [])
def li(ls, tem=[]):
for l in ls:
if type(l) is list:
li(l, tem)
else:
tem.append(l)
return tem
# 二分查找
def twoSerch(ls, x, low, hight):
if (low <= hight):
... |
0d770b48445deef0718897b5fc107ee4b815402e | jproddy/rosalind | /bioinformatics_stronghold/mrna.py | 731 | 3.75 | 4 | '''
Inferring mRNA from Protein
http://rosalind.info/problems/mrna/
Given: A protein string of length at most 1000 aa.
Return: The total number of different RNA strings from which the protein could have been translated, modulo 1,000,000. (Don't neglect the importance of the stop codon in protein translation.)
'''
fro... |
767b3d675f0aa21ae9e8d0cbe7f6d9663dc249ea | Steven4869/Simple-Python-Projects | /next_palindrome.py | 805 | 3.90625 | 4 | #PRINT NEXT PALINDROME AND THE NUMBER SHOULD BE GREATER THAN 10
"""
def nextpalindrome(n):
n=n+1
while not str(n)==str(n)[::-1]:
n+=1
return n
if __name__=="__main__":
size=int(input("enter the number of enteries"))
numlist=[]
for i in range(size):
numlist.append(int(input("... |
091f65f8d8186b2f097338fd8703f738bcb27d39 | thorhilduranna/2020-3-T-111-PROG | /assignments/strings/lower_upper.py | 223 | 4.0625 | 4 | a_str = input("Input a string: ")
lower_count = 0
upper_count = 0
for char in a_str:
if char.islower():
lower_count += 1
elif char.isupper():
upper_count += 1
print(lower_count)
print(upper_count) |
58dc44c35ad724d92db1e84548910c9b3f4d7b23 | Tsukumo3/Atcoder | /library/UnionFindTree.py | 1,249 | 3.5 | 4 | class UnionFindTree():
'''ランク無しUnionFind木'''
def __init__(self, n):
#親の番号
self.par = list(range(n))
def root(self, x):
#木の根を求める
if self.par[x] == x:#自分が根ノードなら
return x
else:
self.par[x] = self.root(self.par[x])
return self.par[x]
... |
50562f4b50a26dd37e182073f52dd6556baf2da5 | SB1996/Python | /Function/Generators.py | 1,502 | 4.6875 | 5 | # Generators in Python...!
#
# 1. Generator-Function : A generator-function is defined like a normal function, but whenever it needs to
# generate a value, it does so with the yield keyword rather than return. If the body of a def
# contains yield, the function automatically be... |
34cde19a99bdb4b0c350c0df0887d55d4dacbc1b | ammuaj/CodeSignal-PySolutions | /sortByHeight/solution.py | 420 | 3.828125 | 4 | # def sortByHeight(a):
# for i in range(len(a)):
# if a[i] != -1:
# for j in range(i+1, len(a)):
# if a[j]!=-1 and a[j]<a[i]:
# a[i], a[j] = a[j], a[i]
# return a
# def sortByHeight(a):
# b = sorted(a)[a.count(-1):]
# return [x if x ==... |
bb2b43d152d25d5d7ecb90eef1f81b2c7dcc3c49 | PyLadiesPoznanAdvanced/tic-tac-toe | /solutions.py | 4,677 | 3.796875 | 4 |
"""
Poniższe rozwiązania zostały napisane przez uczestników spotkania PyLadies w dniu 24 X 2016.
"""
# Adrian Wojtczak
def state(board):
output = [] # Here we put characters which create a winning streak
for i in range (0, len(board)): # loop checks our list of lists whether it's n x n dimension
if l... |
95e407a11e6d40cded7682bfa1a4e67133d76e7e | nasa/bingo | /bingo/symbolic_regression/implicit_regression.py | 10,991 | 3.640625 | 4 | """Implicit Symbolic Regression
Explicit symbolic regression is the search for a function, f, such that
f(x) = constant. One of the most difficult part of this task is avoiding
trivial solutions like f(x) = 0*x.
The classes in this module encapsulate the parts of bingo evolutionary analysis
that are unique to implic... |
b43e18612d270852d6ea676224553b1aefbfefcb | gopal-amlekar/Jumpstart-IOT-Python | /hello-world.py | 188 | 4.0625 | 4 | # A simple Python program to print hello <your name>
print "Welcome to Python on Raspberry Pi\n"
name = raw_input ("Please tell me your name and press Enter key\n")
print "Hello", name
|
d37380259d82d0f3fd482e4071dd7de3a4eae288 | JokerToMe/PythonProject | /shine/complexDecorator.py | 463 | 3.921875 | 4 | # 在不修改源码的基础上完善代码功能
# def say(age):
# print('Shine is %d years old' % age)
# 此装饰器只实用于参数只有一个且必须为number类型的函数,不通用
def outer(func):
def inner(age):
if age <=0:
age = 0
func(age)
return inner
# 通过@符号来替代 say = outer(say) 的写法
@outer
def say(age):
print('Shine is %d years old' % age)... |
cf75f09692826f52ccb705868dbcc06cd5910ae6 | jianantian/leetcode | /sort_int.py | 494 | 3.5625 | 4 | #coding:utf8
def sort_int(l):
"""对整数序列排序, 可以有如下的复杂度为 O(N + M) 的算法. N为序列的长度,
M为序列最大值与最小值的差"""
mi, ma = min(l), max(l)
q = []
for i in range(len(l)):
q.append(l[i] - mi)
que = [[] for i in range(ma - mi + 1)]
for j in range(len(q)):
que[q[j]].append(l[j])
res = []
... |
7a6b18459ca815c479b7b95df0e3a61a97a71cf2 | Shylcok/Python_Algorithm | /算法/bittree.py | 1,036 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# @Project : Algorithm_Python
# @Time : 0426
# @Author : Shylock
# @Email : JYFelt@163.com
# @File : bittree.py
# @Software: PyCharm
# ----------------------------------------------------
# import something
# 题目描述
# 现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
# 输入描述:
#
# 输入的第一行表示节点的... |
b2321d1345e432054ebb701d93b27805adfc7da4 | Caspeezie/TDDAssignments | /p_ahead.py | 343 | 3.8125 | 4 | point_ahead = 20
point_ahead = point_ahead - 3
has_ball = True
if has_ball == True:
point_ahead = point_ahead + 0.5
else:
point_ahead = point_ahead - 0.5
point_ahead = point_ahead**2
seconds_left = 12
if point_ahead > seconds_left:
print ('Lead team is safe')
else:
print ('Lead team ... |
1febf7421cc798dc7a0364308567fa3180ab9de3 | Anshul-GH/hackerrank | /Solutions/59. CountHappiness.py | 659 | 3.578125 | 4 | # https://www.hackerrank.com/challenges/no-idea/problem
if __name__ == "__main__":
n,m = input().split(' ')
# m = int(input())
arr = input().split(' ')
# converting str values to int
# arr = [int(val) for val in arr]
a = input().split(' ')
# converting str values to int
# a = [int(val... |
2a85dae92c778efb37528e702b88da6f7f88d9ab | AmRiyaz-py/Python-Arsenal | /List Operations in Python/problem3C3CO.py | 397 | 4.03125 | 4 | '''
Program :-Given a List of size n as input. Create a new List, where first element is 0, and
rest elements are same as original List
Author :- AmRiyaz
Last Modified :- April 2021
'''
oldList = [5,2,1,7]
lenOfOL = len(oldList)
newList = [0]
for i in range(0,lenOfOL):
ch = oldList[i]
... |
f087180a717c18d55152c25ced64a549005a2747 | cmtthomas/python | /example-ord.py | 150 | 3.5 | 4 | #example-ord.py cmt
def main():
chars = [' ','A','a','*','0']
for n in range(len(chars)):
print(n, chars[n], ord(chars[n]))
main()
|
a7429c0f5a97d4e139a2c5028b827568596ef5c0 | henchhing-limbu/Interview-Questions | /Matrix/rotting_oranges.py | 2,084 | 4.03125 | 4 | """
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minu... |
c8ce468b0f565f0ca8bdd484aceda5b65501fdbd | chaitanyakulkarni21/Python | /Balguruswamy/1_Intro_To_Python/ReviewExercises/Prob7.py | 203 | 4.28125 | 4 | #WAP to check whether an year is leap year or not
yr = int(input("Enter any year: "))
if yr % 4 == 0 and yr % 100 != 0 or yr % 400 == 0:
print(yr,"is leap year")
else:
print(yr,"is not a leap year") |
d69d66cb887a0296c4376c9f887b0748c102899e | vanigupta20024/Programming-Challenges | /BST.py | 2,341 | 3.953125 | 4 | '''
Operations performed on BST:
Insert a node in bst
Search a node in bst
Find successor
Inorder traversal
Delete a node in bst:
a. leaf
b. one child
c. both child
'''
class Node:
def __init__(self, data):
self.data = data
self.lchild = None
self.rchild = None
def inor... |
7214de45119dc7cd0fd71343d3e4792ba01ed623 | blessy1234/Programming-Lab-Python | /fnhcfandlcm.py | 381 | 3.890625 | 4 | def hcf(a,b):
hcf = 1
for i in range(1,a+1):
if a%i==0 and b%i==0:
hcf = i
return hcf
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
print('HCF of %d and %d is %d' %(first, second, hcf(first, second)))
lcm = first * second / hcf(first, sec... |
f6ead617e2d77ee19bd76280a4786a7ef872963d | Baudlicious/Self-Study | /Automate-The-Boring-Stuff-With-Python/regex_pdf_project.py | 2,011 | 3.65625 | 4 | #!/usr/bin/env python3
# This is x3830s python files from the book Automate Python The
# Boring Stuff with Python.
import re, pyperclip
def title(big_title, date):
print('!!!!' + big_title.upper().center(70) + ' !!!!')
print(date.upper().center(80))
def sep(title):
print("-" * 80)
print('[ + ] ' + ti... |
15e1e234479a4c1c804ec4669b15835cf8fdaf72 | Mahi/Minesweeper | /minesweeper/utilities.py | 886 | 3.8125 | 4 | """Utility functions and classes used by the game."""
import typing
__all__ = (
'KeyDefaultDict',
'Point',
'points_around_point',
)
class KeyDefaultDict(typing.DefaultDict):
"""Defaultdict which passes the key to :attr:`default_factory`."""
def __missing__(self, key: typing.Hashable) -> typing... |
90ec2f6becd9a2c25bb5b324bbc2d31cb1c0791c | DanielFranca/Python | /pythoncurso/args.py | 1,671 | 4.8125 | 5 | """"
Entendendo o args*
- O *args é um parâmetro, como outro qualquer, isso significa que você poderá chamar de qualquer coisa, desde que comece
com asterisco.
Exemplo:
*xis
Mas por convenção, utilizamos *args para defini-lo
Mas o que é *args
O parâmetro *args é utilizado em uma função, coloca os va... |
a51a4ee4d904a5add5305b41b9be44b34b484837 | ewellsgray/data_science | /practical_stats/chapter1.py | 2,192 | 3.84375 | 4 | # Chapter 1 - Exploratory Data Analysis
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
#%% Simulate populations for testing
# The aim here have a large enough sample point that it fully represents the
# population distribution and statistics
# Population 1: normal dist... |
09c5c2b868339df3d6e463d32c8eb866fe6c9b07 | AugustLONG/Code | /CC150Python/crackingTheCodingInterview-masterPython全/crackingTheCodingInterview/cha07/solution0705.py | 1,414 | 3.75 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""Design the data structures for an online book reader system."""
class Book(object):
def __init__(self, id, details):
pass
class BookStore(object):
def __init__(self):
self.books = []
def add_bo... |
1045ebf7fae36c57b3335951155012dfc6a3c4db | santiagoahc/coderbyte-solutions | /hard/intersecting_lines.py | 4,423 | 4.03125 | 4 | """
Using the Python language,
have the function IntersectingLines(strArr) take strArr which will be an array of 4 coordinates in the form: (x,y).
Your program should take these points where the first 2 form a line and the last 2 form a line, and determine whether the lines intersect,
and if they do, at what point.
F... |
a0db4da8b167bdf8112df203b3b9e93626be8e99 | rsauhta/ProjectEuler | /p125.py | 904 | 3.515625 | 4 | # https://projecteuler.net/problem=125
#
import math
def isNumberPalindrome(n):
"returns True if n is palindrome"
numStr = str(n)
return numStr == numStr[::-1]
def palindromeSum(maxNumber):
MaxN = int(math.sqrt(maxNumber) + 0.5)
SquareList = [n*n for n in range(0,MaxN)] # 0th entry is dummy
WorkingList = l... |
4738edf34ea4a33db6d7a013eb526da43f5071ad | mitsukakiyohara/ATCS | /Exercises/PythonAdvPractice_2019.py | 7,900 | 4.375 | 4 | """ This module is python practice exercises to cover more advanced topics.
Put the code for your solutions to each exercise in the appropriate function.
Remove the 'pass' keyword when you implement the function.
DON'T change the names of the functions!
You may change the names of the input parameters.
Put your... |
4821ae626a466adf86513a9e5c2ff35f259b9b89 | ziolkowskid06/Python_Crash_Course | /ch09 - Classes/9-01. Restaurant.py | 867 | 4.0625 | 4 | """
Make a class called Restaurant.
"""
class Restaurant:
"""Model of restaurant"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize restaurant_name and cuisine_type"""
self.restaurant_name = restaurant_name.title()
self.cuisine_type = cuisine_type
de... |
9898ae0dec093af3db6699d4dba5f5b34a54680f | 1raviprakash/P342-Assignment-2 | /QUESTION3.PY | 899 | 3.765625 | 4 | # Reading two matrices and printing their products
with open('m.txt', 'r') as f:
m = [[int(num) for num in line.split()] for line in f]
with open('n.txt', 'r') as j:
n = [[int(num) for num in line.split()] for line in j]
# This will be my A
a = [6, 4, 2]
# This will load the value of product of the matrices and... |
2fe54f0aa2918bf6e21ca20eef898209d2bbe056 | cieske/exercises | /Beakjoon/2739.py | 155 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 00:34:40 2018
@author: ciesk
"""
N = int(input())
for i in range(1, 10):
print(N,'*', i, '=', N*i) |
f223524b37efe5ab70ca44630d62b3a3a46d6661 | u101022114/NTHU10220PHYS290000 | /student/101022114/drop_ball_time.py | 176 | 3.53125 | 4 | g=10.0
def drop_ball_time(h):
if h>0:
t=(2*h/g)**0.5
print t
elif h==0:
print 0
else:
print'Sorry, the height cannot be negative.'
|
831b11469f57dff98db6cfa5be2fa14bd9688e7a | knightrohit/data_structure | /sort/merge_sort.py | 786 | 3.703125 | 4 | """
Time complexity = O(NlogN)
Space complexity = O(N)
"""
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def divide(lst):
if len(lst) == 1:
return lst
mid = len(lst)//2
return merge(divide(lst[:mid]), divide(lst[mid:]))
... |
43d1517a420407b5430f7e7dc96d1efaf9240ddd | chienk21/DataScience | /Collection1.py | 2,910 | 4.15625 | 4 | #question 1
def list_sum():
myList = [1, 50, 300, 43, 26]
#using built-in sum function finds the sum of the items in the list
print(sum(myList))
#question 2
def count_elements():
countString = "lkseropewdssafsdfafkpwe"
#create empty strings for initialization for the most common chars and the one t... |
42788cfb646fbbd43cc335e612cc77f10bd259d1 | alexander-matsievsky/HackerRank | /All_Domains/Python/Python_Functionals/map-and-lambda-expression.py | 160 | 3.9375 | 4 | N = int(input())
fibonacci = [0, 1]
for i in range(2, N):
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print(list(map(lambda x: x ** 3, fibonacci[:N])))
|
9fa0f7b9dcad93f15b0630c10fdba4d52ba3e19c | leeyj4470/python | /basic/com/python/basic01/string.py | 373 | 3.71875 | 4 |
if __name__ == '__main__':
a=""
b=""
print("a 변수 값을 입력하시오\n")
a=input()
print("b 변수 값을 입력하시오\n")
b=input()
print("a변수 타입 : "+str(type(a))+"\n")
print("b변수 타입 : "+str(type(b))+"\n")
c=int(a)+int(b)
print("{0} + {1} = {2}".format(a,b,c))
... |
82eba6fb186a1dce93005300820345896a5f0288 | junclemente/udemy-tkinter | /food_price.py | 2,143 | 4 | 4 | from tkinter import *
# Configure Window
root = Tk()
root.title("Food Price")
root.geometry("300x200")
root.resizable(width=False, height=False)
color = 'gray77'
root.configure(bg=color)
# Declare variables, IntVar() is tkinter variable declaration
BANANA = 8
APPLE = 6
ORANGE = 7
PINEAPPLE = 12
JACKFRUIT = 15
AVOCADO... |
12a2cfea0076601f482377f6b1e7ec81024d22d0 | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/exShelve.py | 6,712 | 3.84375 | 4 | '''
Arquivo: ferramentas.dat
ID NOME QUANTIDADE CUSTO UN
Visualizar
Atualizar
Inserir
Remover
Você é dono de uma loja de ferramentas e deseja manter controle sobre o estoque.
Escreva um programa que inicialize um arquivo
shelve “ferramentas.dat”, que permita você inserir
os seguinte dados relativos às diversas
ferram... |
504c72b75e27975448169a393eccb487555a65f6 | yshastri66/competitive-coding-python | /array/sort_colors.py | 1,280 | 4.3125 | 4 | '''
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without us... |
87782084f32b9fe8f5331425dc3edfbb6bede14b | jschrom311/codechallenges | /Python challenges/guessgame.py | 1,920 | 4.1875 | 4 | #Guessing Game-
#Write a program that picks a random integer from 1 to 100
#and has players guess the number. Rules:
#1. If a player's guess is less than 1 or greater than 100 return 'OUT OF BOUNDS'
#2. On a player's first turn if their guess is:
#(a) within 10 of the number, return 'WARM'
#(b)further than 10 from the ... |
8b47d6261094be8b427ff4e850993af33f5d4f2f | dvilinsky/lang-models | /languageModel.py | 2,183 | 3.765625 | 4 | import math
'''
Tuan Do
'''
class LanguageModel(object) :
START = "<S>"
STOP = "</S>"
UNK = "*UNKNOWN*"
'''
Constructs a language model from a collection of sentences.
-----
trainingSentences = list of lists of strings (words)
'''
def train(self, trainingSentences):
p... |
01be2620da882b2b4848af1906601640dc970ef4 | liyi0206/leetcode-python | /124 binary tree maximum path sum.py | 764 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxPathSum(self,root):
"""
:type root: TreeNode
:rtype: int
"""
self.res=-1000000
... |
4ba3634ee97e5a74493dd4a8fb2301110b0566f9 | mayhuberman/Logzio-Game | /venv/bin/Question.py | 557 | 3.578125 | 4 | import sys
class Question(object):
def __init__(self, question, answer, options):
self.question = question
self.answer = answer
self.options = options
def ask(self):
print self.question + "?"
for n, option in enumerate(self.options):
print "%d) %s" % (n + ... |
db1dae8d2abdc113fa675456aa3f9b7f5ac7e59d | TobiasKooijman/van-input-naar-output | /Stokbrood_2.py | 702 | 3.765625 | 4 | # Inputs
Aantal_Stokbrood = input('geef het aantal stokbroden ')
Stokbrood = input('geef de prijs van de stokbroden ')
Aantal_Croissant = input('geef het aantal croissants ')
Croissant = input('geef de prijs van de croissants ')
# Value Numbers:
Totaal_Stokbrood = int(Stokbrood) * int(Aantal_Stokbrood)
Totaal_Croiss... |
6bb33ea92d061ce5135841a6b9ab8804b742f88c | Stathis-Kal/web-scraping | /web-scraping.py | 1,543 | 3.578125 | 4 | from bs4 import BeautifulSoup
import requests
import pandas as pd
"""
Note:
The use of bots to scrap or crawl the web is not allowed from everyone. You should be carefull when you are using web crawlers or scraping data
from web pages.
Many many pages out there will block most of the crawlers unless they provide expli... |
4ddaf219303aab7c7c7c494aaecc7e6081b8dddf | JustgeekDE/scoville | /scoville/genericNodeTransformations.py | 2,273 | 3.71875 | 4 | import math
class NodeRotation:
def __init__(self, angle):
self.angle = angle
def rotateNode(self, node):
rotation = self._getNodeRotation(node)
rotation += self.angle
self._setNodeRotation(node, rotation)
return node
def _setNodeRotation(self, node, rotation):
while rotation >= 360:
... |
5c7738e51cf686217762972755238ddcf8edebce | bedzkowp/ftplb | /mininet/ftptopo.py | 1,012 | 3.84375 | 4 | """Custom topology example
Two directly connected switches plus a host for each switch:
host --- switch --- switch --- host
Adding the 'topos' dict with a key/value pair to generate our newly defined
topology enables one to pass in '--topo=mytopo' from the command line.
"""
from mininet.topo import Topo
class F... |
629b5956bd1abc6e46844cfdafb0e70b9fced301 | valentinogagliardi/create_pdf_python | /src/generate_pdf.py | 2,692 | 3.59375 | 4 | from weasyprint import HTML
from random import shuffle
from itertools import repeat
from questions import questions
style = """<style>
h1, h2 { margin-bottom: 30px; }
.question { display: block; margin-bottom: 20px; }
table { display: block; }
.question--multiple { display: block; margin-bottom: 50px; }
.question__id ... |
a2a74f51cf0b28482b41140e212c25917921e153 | certik/pydy | /examples/solver.py | 1,808 | 3.71875 | 4 | from numpy import array, empty
def rk4_step(x, y, h, derivs):
"""
Does one Runge-Kutta 4th order step.
Use rk4int() to solve the equations on the whole interval.
"""
k1 = h * derivs(y, x)
k2 = h * derivs(y + k1/2, x + h/2)
k3 = h * derivs(y + k2/2, x + h/2)
k4 = h * derivs(y + k3, x + ... |
7eb965dfd52577da5befd8946f437ffd7e71a294 | cristinamais/exercicios_python | /Exercicios Variaveis e tipos de dados/exercicio 49 time_delta_time.py | 1,156 | 3.75 | 4 | """
Time-Delta horas
"""
import datetime
t = datetime.time(9, 30, 45, 100000)#hora, minuto, segundo e microsegundo
print(t)
print(t.hour)
dt = datetime.datetime(2016, 7, 26, 12, 30, 45, 100000)
print(dt)
#>>>2016-07-26 12:30:45.100000
print(dt.time())#pega só o horário
print(dt.year)#pega só ano
tdelta = datetime.t... |
af70d5df59fc0f53b9e4ca9f871fafea767a7129 | King-Of-Game/Python | /Example/math/平方根.py | 505 | 4.125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# __author__ : YiXuan
# __date__ : 1/15/2021 12:53 PM
# __software__ : PyCharm
import cmath # 导入复数数学模块
# 只适用于正数
def square_root(number):
result = number ** 0.5
print(result)
# 适用于负数和复数
def square_root2(num):
result = cmath.sqrt(num)
print(f'{num} 的... |
61559462c7e23bcf9e94a930c599d02392fc3109 | kcnti/schoolWorks | /m4/6.py | 275 | 3.71875 | 4 | name = ['Arm','Bobby','Cathy','Dorothy','Emily']
score = [86,78,54,65,34]
alls = [[x,y] for x,y in zip(name,score)]
for x,y in alls:
if y >= 80:
print(x ,"4")
elif y >= 70:
print(x,"3 warning")
else:
print(x,"2")
|
6a3ed126ec1c5e9d3f054e7680fd966b9654d887 | JoelTParko/Advent-of-Code-2020 | /solutions/day4.py | 2,808 | 3.921875 | 4 | import re
#Reads the data in from the text file
#Formats each passport into a dictionary, relating a field to a value
#Returns list of dictionaries
def readFile(location):
input = []
passport = dict()
file = open(location)
for line in file:
if(line=="\n"):
input.append(passport)
... |
c6da6d1b3535f49533497eb85416ae014fa785ac | wangxuewen123/1805w | /09day/03-乘法口诀表.py | 166 | 3.859375 | 4 | #!/usr/bin/env python
# coding=utf-8
a = 1
while a <= 9:
b = 1
while b <= a:
print("%d*%d=%d"%(b,a,a*b),end="\t")
b+=1
print("")
a+=1
|
f492094b9282b5b4a6881f1d4db388607751ff29 | awesome-liuxiao/leetcodesolution | /2011_finalValOfVal.py | 571 | 3.78125 | 4 | from typing import List
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
res = 0
for opt in operations:
#tmp = sorted(opt)
if opt[1] == '+':
res += 1
else:
res -= 1
return res
X = Solution... |
9d43273eee5eebbd184102a50b5b8fde28a5263a | WeiyiDeng/my_python_trials | /accum_grades.py | 937 | 3.9375 | 4 | def read_grades(grade_list):
''' (file open for reading) -> dict of {float: list of str}
Read the grades from grade list into a dictionary where each key is a grade
and each value is a list of student IDs who earned the grade.
Precondition: the file grade_list contains a header with no blank lines,
... |
68ce3f69f1d192078e2a98f54bbcbee067afe36f | z4yx/Zynq-Danmaku-Code | /ZynqDanmaku-Host/captured_image.py | 637 | 3.765625 | 4 | #!/usr/bin/env python3
import cv2
import numpy as np
import sys
def create_blank(width, height, rgb_color=(0, 0, 0)):
"""Create new image(numpy array) filled with certain color in RGB"""
# Create black blank image
image = np.zeros((height, width, 3), np.uint8)
# Since OpenCV uses BGR, convert the colo... |
95e90ec0a763272ff3fdaa0112860efe18257b06 | Rebell-Leader/bg | /REST/python-refresher-master/34_first_class_functions/code.py | 1,888 | 4.1875 | 4 | # A first class function just means that functions can be passed as arguments to functions.
def calculate(*values, operator):
return operator(*values)
def divide(dividend, divisor):
if divisor != 0:
return dividend / divisor
else:
return "You fool!"
# We pass the `divide` function as a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.