blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e21b07ec20397cf333cf826f2ef683e58e97c4c3 | jantsankhorloo/Udacity-CS101 | /L2Ps1.py | 186 | 3.625 | 4 | #Define a procedure, udacify, that takes as input a string,
#and returns a string that is an uppercase 'U'
#followed by the input string.
def udacify(str):
return 'U'+str
|
1326b80209a390f89bd597a6f49037ee49c86139 | qianyu1988/myTEST | /src/test_case/tree.py | 3,378 | 3.625 | 4 | from turtle import *
from random import *
from math import *
import turtle
import random
t = turtle.Turtle ( )
t.speed (0)
# 绘制黑夜
t.width (80)
for x in range (20):
t.up ( )
t.goto (-250, 250 - x * 60)
t.down ( )
t.color (x * 10, x * 10, x * 10)
t.fd (1000)
t.pensize (1)
# 绘制出五角星
for k in range (30)... |
b48f84397539f29d1475a0872edb6719f2667ce1 | Nilcelso/exercicios-python | /ex012.py | 155 | 3.5 | 4 | pre = float(input('Qual o preço do seu produto? R$ '))
des = pre - (pre * 0.05)
print('O preço do produto é R$ {:.2f}, com 5% de desconto.'.format(des)) |
e9640868460cd23dfea6d6da9c4ce1d6766106cd | KalebeGouvea/exercicios-python | /lista01/exer5.py | 377 | 3.734375 | 4 | #Solicite o preço de uma mercadoria e o percentual de desconto.
#Exiba o valor do desconto e o preço a pagar.
preco = float(input('Digite o preço da mercadoria: '))
desc = float(input('Digite o percentual de desconto (em %): '))/100
vdesc = preco * desc
pdesc = preco - vdesc
print (f'O valor do desconto foi R$ {vdes... |
7097fc1e609a526963055ba492e331574e3fbae6 | nascarsayan/lintcode | /884.py | 597 | 3.53125 | 4 | class Solution:
"""
@param s: a string
@return: return a list of integers
"""
def findPermutation(self, s):
# write your code here
size = len(s)
nums = list(range(1, size + 2))
nexi = s.find('I')
if nexi < 0:
return list(nums[::-1])
ptr = -1
per = []
while (len(nums) > 0... |
6d0a96f5697344d79c1f1770fd57c2feaad15d3b | stefanduscher/stefanduscher | /Anfänger_Tag1_Programm_Berechnung_Volumen.py | 1,276 | 3.90625 | 4 | # Programm: Berechnung Volumen eines Quaders
#
# Autor: Stefan Duscher
#
# Datum: 22.09.2019
#
# ---------------------------------------------------------------
def kubik(a,b,c):
# Dieser Funktion werden drei Zahlen übergeben
# sie multipliziert die drei Zahlen miteinand... |
8322c5466e33b43bcdfe496787d76ce4e6103dcb | maddieclayton/COS435-project | /db.py | 643 | 3.671875 | 4 | # Creates and manages the ratings DB.
import sqlite3
import os
db_file = 'data.db'
def create_db():
"""
Creates the DB file and the tables. Fails with an error if the DB already exists.
"""
if os.path.isfile(db_file):
print("DB already exists!")
return
# Create it!
conn = sql... |
f300c7d1799642a272d94cb9bd33ff5194bfb065 | ksayee/programming_assignments | /python/CodingExercises/PerfectBinaryTree.py | 2,357 | 4.125 | 4 | '''
Check whether a given binary tree is perfect or not
Given a Binary Tree, write a function to check whether the given Binary Tree is a prefect Binary Tree or not.
A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level.
Examples:
The following tree is a p... |
0ebcd4c496b40c195314393951a810d74892309a | tdesfont/CtCI-6th-Edition-Python | /Chapter01/7_Rotate Matrix/RotateMatrix_.py | 838 | 3.734375 | 4 |
def rotate_matrix(M):
n = len(M)
assert n == len(M[0])
N = [[None for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
N[j][n-1-i] = M[i][j]
return N
def transpose(M):
for i in range(n):
for j in range(0, i):
M[i][j], M[j][i] = M[j... |
a8a55b1e1748d008499206f0c8d7e5c7a6138464 | SrChach/numpy_stack_and_algorithms | /numpy/basics.py | 784 | 4.59375 | 5 | import numpy
numpy_vector = numpy.array([1, 2, 3])
print("Original vector: ", numpy_vector)
# Numpy will treat "+" sign as vector addition, not concatenation as normal Python
print("sum of vectors: ", numpy_vector + numpy_vector)
# Mutiplication of vectors also works (in this case, a scalar multiplying a vector)
pri... |
0a16b0d3e54e601adadedcccd1b99a1701c19367 | AlfredKai/KaiCodingNotes | /docs/algorithms/binary search.py | 750 | 3.640625 | 4 | def binarySearch(arr, x):
l = 0
r = len(arr) - 1
while l <= r:
mid = (l + r)//2
if arr[mid] > x:
r = mid - 1
elif arr[mid] < x:
l = mid + 1
else:
return mid
return -1
def binarySearchRecurrion(arr, x, l, r):
mid = (l... |
272d0b0759c878b1275cb813373f2b57e7e9b40b | MaximilianoCaba/UADE-Programacion-Python | /fundamentos/Clase4.py | 5,059 | 4 | 4 | import random
# 1 - ingresar un valor positivo menor a 100, controlar que se asi eh informar si es par o impar
# 2 - ingresar un valor menor a 500, informar si es un numero primo (divisible por uno y por si mismo)
# 3 - ingresar un numero positivo e informar si es un numero abundante (suma de los divisores da mas qu... |
cbb2695cf5edbf7121b417c2bf8732bb86c05924 | izmirli/python3-course-demos-and-solutions | /19-data-lab/19-data-lab_ex1.py | 888 | 3.78125 | 4 |
user_access_table = {
'apple': 'red',
'lettuce': 'green',
'lemon': 'yellow',
'orange': 'orange',
}
def check_user_access(user_name, password):
"""
Gets username and password, and check them at user_access_table.
If OK prints 'Welcome Master' and return True, otherwise... |
2edf7037998c84416d96767a7553c931c169facc | rookie-LeeMC/Data_Structure_and_Algorithm | /leetcode/回溯/N皇后/0052_N皇后2.py | 1,059 | 3.59375 | 4 | # -*- coding:UTF-8 -*-
'''
https://leetcode-cn.com/problems/n-queens-ii/
'''
def totalNQueens(n):
if not n: return 0
board = [['.'] * n for _ in range(n)]
ans = []
def isValid(board, row, col):
# 行
for i in range(n):
if board[i][col] == "Q": return False
# 左上
... |
e0f0bea8a75cca08e1331661017911c60fec1513 | Alekselion/project-euler | /task3.py | 724 | 3.828125 | 4 | task = "What is the largest prime factor of the number 600 851 475 143?"
num = 600851475143
d = 2
while d * d <= num:
if num % d == 0:
num //= d
else:
d += 1
print(f"Task: {task}\nAnswer: {num}")
# #############
# FIRST VERSION
# #############
# def check_prime(n):
# d = 2... |
433d310a2b3d69fa6f0bc14f443b260301cbf770 | SCarozza/simulate_and_track | /simulate_diffusion/simulate_diffusion.py | 2,610 | 3.765625 | 4 | __author__ = 'Sara'
import sys
import simulate_diffusion_trace
import IO
"""
Simulates a particle undergoing free diffusion and creates a movie: the name of the movie is given by command line.
1. Generates the coordinates of the movement, simulating a free diffusion: the parameters of the diffusion are given as inpu... |
ff663efe8f83b6fa06faded29db74be2b1857b2d | yqz/myalgoquestions | /intervals.py | 7,366 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import tree
"""
QUESTION:
一个range的序列(链表或数组),如[1,3], [2,6], [8,10],[15,18]
写程序合并有重叠的range,比如上面的序列合并为[1,6], [8,10], [15,18]
如果这个序列不是静态的,而是一个数据流,如何 处理?"""
def are_intervals_intersecting(i1, i2):
"""return if two intervals have overlap"""
return not (i1[0] > i... |
626b243cb15e9e8479a183308d3a53f4e823190b | nerdy-rups/fun-python-drawing | /MyInput.py | 953 | 3.984375 | 4 | import time
import Drawing as D
def taking_input():
global Choice
Choice = input("What do you want to draw?\nhut or flower?\n")
#print("I am from inside function", Choice)
def input_usage():
if Choice.upper() == "HUT":
print("Correct answer\nEnjoy")
D.hut()
elif Choice.up... |
f9e451c54210be1dda51203a8ff39eb3d65a913c | auxo86/python0824 | /str_demo.py | 429 | 3.5625 | 4 | # encoding=UTF-8
str1 = 'abcde12345'
str1 *= 2
print str1
print str1[0], str1[2], str1[10]
print str1[-1], str1[-5], str1[-7]
# slice 包含起點但是不包含終點。也可以不寫起點跟終點
print str1[0:5], str1[5:8]
print str1[:5], str1[5:]
print len(str1)
str2 = 'www.uuu.com.tw'
print type(str2)
result = str2.split('.')
print type(result), result
... |
efceefa1aa7508a85bb7563831a779a5e52c0683 | SquareKnight/onb-math | /solutions/euler005.py | 1,447 | 3.59375 | 4 | """Smallest multiple
n;Numbers from 1 to n;int;20
#multiple
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import solutions.libEuler as e
def att... |
dd26aa0418d38558cfbfc32f8ae142c8c2fb54aa | olya-bo/A_level | /Lesson2/Classwork/divisors_number.py | 184 | 3.90625 | 4 | digital = int(input('Put your number '))
print(f'делители числа {digital}', end=': ')
for i in range(digital):
if digital % (i + 1) == 0:
print(i+1, end=' ')
|
0a00815128a9ad03d3b7902e7d2f31a2ca8218ab | innovatorved/BasicPython | /x23- assistant.py | 3,132 | 4.03125 | 4 | #assistant
a=input("Enter your Name: ")
print('hey',a)
print("what can i do for you-\npls selectthe choice: ")
print('Enter 1 for Solve A.P. problem-')
print('Enter 2 for Solve G.P. problem-')
print('Enter 3 for find area of different shapes-')
print("Enter 4 for change on temprature value-")
print("Enter 5 for find pr... |
5e9da6e9c9f9dfec24a825fc6d2068b7b757171f | ceyhunsahin/TRAINING | /EXAMPLES/EDABIT/EXPERT/001_100/19_how_many_digits_between.py | 924 | 4.53125 | 5 | """
How Many Digits between 1 and N
Imagine you took all the numbers between 0 and n and concatenated them together into a long string. How many digits are there between 0 and n? Write a function that can calculate this.
There are 0 digits between 0 and 1, there are 9 digits between 0 and 10 and there are 189 digits b... |
80d557141a437a4873963da3d2f11cf4789d1e0f | Burdeinick/Tasks | /Coursera/Погружение в Python/Week_3_read.py | 433 | 4.09375 | 4 | class FileReader:
""" The class that reading the path and return the string"""
def __init__(self, path):
self.path = path
def read(self):
""" This function for reading a files, if the path is wrong return '' """
try:
with open(self.path, 'r') as f:
line... |
91c86f02b5143002a984b2f9136a10c9e8d9304f | jonathanschen/python_practice | /mitlab4.py | 324 | 3.75 | 4 | _large_prime = 137
_KEY = 99
guesses = 0
while guesses < 3:
pw = raw_input("Please enter your password...")
attempt = hash(pw)
converted1 = attempt%_large_prime
if converted1 == _KEY:
print "you got it"
exit(0)
elif converted1 != _KEY:
print "Try again"
guesses += 1
print "You dont know the password"
... |
2fe6e7e68fc87863309a8b6d0663daa3682d1976 | akashpunagin/tensorflow | /tf_core_learning_algorithms/hidden_markov_model/whether_prediction.py | 2,420 | 3.703125 | 4 | # The components of a markov model
# 1. States: In each markov model we have a finite set of states
# These states could be something like "warm" and "cold" or "high" and "low" or even "red", "green" and "blue"
# These states are "hidden" within the model, which means we do not direcly observe them.
#
# 2. Observations... |
ae6dfed9d3214681df970a279aba7c15e4f365e6 | neu-velocity/code-camp-debut | /codes/MartinMa28/python3/0206_reverse_linked_list.py | 884 | 3.921875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
retur... |
6ea9cb4ee2086da90c394b5ab83d72f01d6f4062 | icysun/python-learn | /Learn by example/Example2_python/多级子菜单.py | 2,086 | 3.734375 | 4 | from tkinter import *
#http://www.cnblogs.com/hongten/p/hongten_python_tkinter_choices_menu.html
def makeCascadeMenu():
# make menu button
Cascade_button = Menubutton(mBar, text='Cascading Menus', underline=0)
Cascade_button.pack(side=LEFT, padx="2m")
# the primary pulldown
Cascade_button.menu = ... |
cebb46578db5c28b637f3dbc8130eb215b341a3c | blogin/algorithms | /HW_4/hw_4_3.py | 2,440 | 3.984375 | 4 | """
Задание 3.
Приведен код, формирующий из введенного числа
обратное по порядку входящих в него
цифр и вывести на экран.
Сделайте профилировку каждого алгоритма через cProfile и через timeit
Сделайте вывод, какая из трех реализаций эффективнее и почему!!!
И можете предложить еще свой вариант решения!
Без аналитики... |
1455a3f9abbf8bd6b667de9ac56cf1adcb87336b | linjorejoy-small-projects/ascii-art | /ASCII text/generate-ascii.py | 948 | 3.671875 | 4 | import json
if __name__ == "__main__":
options = []
json_file = None
with open("ASCII text/file-list.json") as file_list:
json_file = json.load(file_list)
[options.append(font) for font in json_file.keys()]
font_index = 0
font_style = ''
while(True):
print("\n\nFont... |
53d58e7b1749b6f7047231bcb6caf6608ec950bb | TrellixVulnTeam/HelloPython_244B | /venv/src/Python100days/day3_12_19/oop_practice.py | 461 | 3.671875 | 4 | class Student(object):
def __init__(self,name,age):
self.name=name
self.age=age
def study(self,courseName):
print('%s is studying %s'%(self.name,courseName))
def surfInt(self):
if self.age<18:
print('Watching math online classes')
else:
print('... |
5187e0a4b8b8ce4a150a428b843561831114ca17 | Harshala-Gaikwad/Tkinter | /radiobutton.py | 595 | 3.90625 | 4 | from tkinter import *
def selection():
selection = "You selected the option"+str(radio.get())
label.config(text=selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text="Favourite programming language: ")
lbl.pack()
R1 = Radiobutton(top,text="C",variable=radio,value=1,comma... |
30d847d7735a4d7af05becdf4d0e50ef22d2df6e | Tiiaraa1907/machineLearningPath | /percabangan.py | 193 | 3.640625 | 4 | # # TERNARY OPERATORS
# nice = True
# kata= ("perbaiki", "selamat")[nice]
# lulus = True
# kata = "selamat" if lulus else "perbaiki"
hasil = None
pesan = hasil or "Tidak ada data"
print(pesan) |
48b5f59c905f288a36598dd8e8635da738968abb | zcallanan/python-learning-projects | /.ipynb_checkpoints/Fibonacci determination-checkpoint.py | 2,961 | 4.125 | 4 | '''Write a Python program to get the Fibonacci series between two numbers'''
def user_input(): #Take two user inputs, because I can
def is_number(x): #Is it a number? function
try:
int(x)
return True
except ValueError:
return False
'''First user input'... |
956be9b82d1365190ec4de7a1969bd86b7409c5e | haardiksharma/Dataquest---Python-Programming-Intermediate | /3. Error Handling.py | 4,568 | 4.78125 | 5 | ## 2. Sets ##
"""
Formal introductio to set
A set behaves very similarly to a list. However, if you add an element to a set that it already contains, the set will ignore it. Also, the items in a set are unordered, while each item in a list has an index.
You can add items to a set using the add() method:
unique_an... |
f005798b0986b0385380e66e7a223b22b0f09d8d | 15032373556/mystudy | /study/chapter3/tourist.py | 961 | 3.78125 | 4 | tourist_place = ['Zhang Jia Jie','Eye of Tianjin','The Imperial Palace','Yuan Ming Yuan','Old dragon head']
print('\n原始顺序打印')
print(tourist_place)
print('\n使用sorted()按字母顺序打印')
print(sorted(tourist_place))
#核实排列顺序未变
print(tourist_place)
print('\n使用sorted()按字母顺序相反的顺序打印')
print(sorted(tourist_place,reverse = T... |
77bbce7f68b2787d5e21382551df908883e01462 | arvakagdi/GrokkingTheCodingInterviews | /GTCI_Subsets/2/StructuredBST.py | 1,664 | 3.984375 | 4 | '''
Structurally Unique Binary Search Trees (hard) #
Given a number ‘n’, write a function to return all structurally unique Binary Search Trees (BST) that can store values 1 to ‘n’?
Example 1:
Input: 2
Output: length of List containing root nodes of all structurally unique BSTs.
Explanation: Here are the 2 st... |
0f4b45816e1253e3e3e0bc6c0b2b62beed36afdc | besteekmen/Saarland | /NODE/ex01/ex01_P1.py | 848 | 4.15625 | 4 | import numpy as np # package for numerical linear algebra
import matplotlib.pyplot as plt # package for plotting and visualization
################################################################################
### Problem 1 ##################################################################
### gener... |
f62547dcadb1116c040258ee07a9726fb70e9857 | danieltshibangu/Mini-projects | /morse_code.py | 1,366 | 4.1875 | 4 | # this program converts strings to morse code
# create list of characters
characters = [ ' ', ',', '.', '?', # special char
'0', '1', '2', '3', '4', # numbers
'5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', # letters
'F', 'G', 'H', 'I', 'J... |
670be0756ccaa3ca81c4ad477454b10194238f18 | timurridjanovic/data-structures | /stack/linked_list/linked_list.py | 8,988 | 3.671875 | 4 | import copy
class LinkedList(object):
def __init__(self, *args):
self.currentNode = None
for e in args:
self.append(e)
def __iter__(self):
if self.length() is None:
return
for i in range(self.length()):
yield self.retrieve(i)
... |
f70dac1bce8672addd3e85b6792367aa3d5068fe | tylrdvs277/StackPractice | /stacks.py | 3,056 | 4.28125 | 4 | # Name: Tyler Davis
# Course: CPE 202
# Instructor: Dave Parkinson
# Assignment: Lab 2
# Term: Fall 2017
class StackArray:
"""Implements an efficient last-in first-out Abstract Data Type using a Python List"""
def __init__(self, capacity):
"""Creates and empty stack with a ca... |
99219f0d3b2ea5956fa6f68fc0289e83abf8e3f4 | pricillacruz/Python | /python_pro_renzo/dicionario.py | 1,368 | 4.25 | 4 | #criando dicionario
#primeiro você coloca a chave'br' dois ponto e seu valor 'Português'
linguas = {'br':'Português', 'eua':'Inglês', 'mexico': 'Espanhol'}
print(linguas['br'])
print(linguas['eua'])
print(linguas['mexico'])
#posso buscar essas chaves com get
print(linguas.get('eua'))
#posso buscar essas chaves com g... |
2e36c7631d078a1379b9b0b5c8dbb3f8563d367d | bandiclv/RTR105 | /sin_caur_summu_ver3.py | 396 | 3.703125 | 4 | from math import sin
x = float(input("Lietotaj, ludzu, ievadiet argumentu (x): "))
y = sin(x)
print ("sin(%.2f) = %.2f"%(x, y))
a = (-1)**0*x**1/(1)
S = a
print ("a0 = %.2f S0 = %.2f"%(a, S))
a = (-1)*x*x/(2*3)
S = S + a
print ("a1 = %.2f S1 = %.2f"%(a, S))
a = (-1)*x*x/(4*5)
S = S + a
print ("a2 = %.2f S2 = %.2f"... |
b7095e2d49f41d2880a21b60939739db556b67fb | gfokkema/discoverping | /threadpool.py | 1,144 | 3.5 | 4 | from queue import Queue
from threading import Thread
def loop(fn, input, output) -> None:
while True:
work = input.get()
if work:
output.put(fn(work))
input.task_done()
if not work:
break
class ThreadPool(object):
def __init__(self, target, num_threads... |
e9ac11adc065be0f3787e29bdb48af86ce125f5d | hamza-smh/project- | /PAIAC/AI/python/OOP- classes.py | 1,811 | 4.4375 | 4 | # Creating a class
class Car():
# attributes => variable
def __init__(self,color,make,model,year):
# These attributes are to be provided
self.make = make
self.color = color
self.model = model
self.year = year
# default attribute
self.battery = "50... |
70634722e7af070dba3f6db22d6e882ccb7434ec | datarocksAmy/APL_Python | /ICE/ICE07/ICE07-6 Trigram.py | 752 | 4.0625 | 4 | # ------------------------------------------------------------------------------------------------------------
# * Python Programming for Data Scientists and Engineers
# * ICE #7-6 NLTK - Trigram
# * #11 Chia-Hui Amy Lin
# ----------------------------------------------------------------------------------------------... |
2737706807709ed7d79892e2843a628d185bdd8f | JaydeepKachare/Python-Classwork | /Session13/02 Decorator.py | 1,150 | 3.859375 | 4 | # program for unserstanding Decorator in python
# Assume as Inbuilt function from module
# do not modify anything here
def sub(num1,num2) :
return num1 - num2
def subdecorator(func_name) :
print("10 : Inside subdecorator")
def updator(a,b) :
print("12 : Inside upodator")
if a < b :... |
41a1e328fa48900776616724b44dd6150d7ce18e | chromiumdioxide/babylog | /babylog/symbols.py | 426 | 3.5 | 4 | class Symbol:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
class SymbolTable:
def __init__(self):
self._symbol_table = dict()
def put_symbol(self, symbol):
se... |
f616af2049f60d286eb40c3eb84dfe5216a4df2e | alexZeLoCO/EJ5_TresOpciones | /main.py | 636 | 3.8125 | 4 | n = int (input ("Introduzca un número entero: ")) #PIDE NÚMERO
#TIPO INT
print ("Opción a) Cuadrado del número.") #GUÍA USUARIO
print ("Opción b) Cubo del número.") #GUÍA USUARIO
print ("Opción c) Doble del número.") #GUÍA USUARIO
usr = input ("Opción: ") #INPUT OPCIÓN
... |
cb6b76fc98e92398d467fbc8b7f6fda230a7ade4 | kristinavisko/learning | /double-digit.py | 684 | 4.0625 | 4 | """Load 5 int double-digit numbers. If the entered number is not double-digit,
throw it away. Sum the last digits of each entered number and print the sum."""
i = 0
y = []
sum = 0
right_number = 5
print ("Please insert five int double-digit numbers")
while i < 5:
print ("You need to enter", right_number, "numbers... |
2eab8cf1b1164a8f51f1901f8c5e7c50ffa3b1a4 | jngraham/TMProject | /process.py | 2,012 | 3.75 | 4 | # James Graham
import Board
import re
# We are guaranteed in the statement of the assignment that this file contains at least two lines
# The first line contains a number and the second line contains tuples of coordinates and orientations.
def initialize(intext):
# Create a board with the specified size
siz... |
3984772a9fbd2ec25a8f566ae3318312bd2121ac | nezumisama/4D-Blocks | /logic.py | 17,122 | 3.859375 | 4 | # -*- coding: utf-8-*-
"""This module provides game logic for 4D tetris-like game, with the \"Y\" dimension being the one in which blocks fall."""
import random, copy, operator
class p4d:
"""This class represents a point in 4-dimensional space with color index assigned."""
def __init__(self, x, y, z, w, col=0... |
7061cc5e9b3276d61d023e0a6510f02660aceb0d | gschen/where2go-python-test | /1906101001周茂林/2020寒假/C=1-10/2.py | 347 | 3.515625 | 4 | '''
有一堆煤球,堆成三角棱锥形。具体:
第一层放1个,
第二层3个(排列成三角形),
第三层6个(排列成三角形),
第四层10个(排列成三角形),
…
如果一共有100层,共有多少个煤球?
'''
a, b, c = 1, 3, 4
for i in range(3, 101):
a = b
b = i**2 - a
c += b
print(c)
|
6859474c2457eb998291a1d219ba3a25d912027e | daniel-reich/ubiquitous-fiesta | /xCXdch4XLpXZZagxm_22.py | 177 | 3.71875 | 4 |
import calendar
def num_of_leapyears(years):
s = 0
for i in range(int(years.split('-')[0]),int(years.split('-')[1])+1):
if calendar.isleap(i):
s += 1
return s
|
8e2802aa3cf890f117b6880d75baf954066a2647 | nima-hakimi/TDT4113 | /Project2/single_game.py | 994 | 3.578125 | 4 | """
test
"""
class SingleGame:
""" A single game. """
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
def perform_game(self):
action1 = self.player1.select_action()
action2 = self.player2.select_action()
self.player1.receive_resu... |
1eb7c4e534ad1e20ffb70b6aa5ab0418dc01e253 | AndreyZemskov/Algorithms | /graphs/dijkstra_algorithm.py | 1,051 | 3.90625 | 4 | def main():
G = read_graph()
start = input('Which top to start with ?')
while start not in G:
start = input('This top is not found. Which top to start with ?')
shortest_distances = dijkstra(G, start)
def read_graph():
M = int(input('Number of edges: ')) # M - количество ребер, далее - стро... |
7a1aad0ba1263cce4dc1d88218f0778749752d1f | Kunal2412/news-detection-model | /news_model.py | 1,799 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Name : Kunal Sachdev
Email id : kunalsachdev456@gmail.com
"""
#import necessary packages/libraries required
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.metrics impor... |
6b7ebaca6be9538aba6d13c50f6616176e3dbf72 | bartkowiaktomasz/cs-learning | /UCL and DeepMind COMPM050 - Reinforcement Learning/easy21/monte_carlo_control.py | 2,522 | 3.953125 | 4 | """
The goal of this assignment is to apply reinforcement learning methods to a
simple card game that we call Easy21. This exercise is similar to the Blackjack
example in Sutton and Barto 5.3 – please note, however, that the rules of the
card game are different and non-standard.
"""
from collections import defaultdict
... |
4f458ec83a7d29498e963407dcb9bd5113cbc781 | liza0525/algorithm-study | /0_before/0807-0808/bs.py | 568 | 3.703125 | 4 | def binarySearch(page, goal):
first_p, last_p, cnt = 1, page, 0
while first_p != goal and last_p != goal:
md_p = int((first_p+last_p)/2)
if goal >= md_p:
first_p = md_p
else:
last_p = md_p
cnt += 1
return cnt
for tc in range(int(input())):
p, a, b... |
35760f43328c9a2b33ada2ed9f732c2d989d2923 | artmukr/homework_2 | /homework_2.py | 466 | 3.9375 | 4 | name = 'Artem'
current_day = 'Saturday'
print('It`s a good ' + current_day + ', ' + name + '!')
first_name = 'Artem'
last_name = 'Syrota'
print('I wish you a lot of money, ' + first_name + ' ' + last_name)
not_a = float(input('Enter first number: '))
not_b = float(input('Enter second number: '))
print(
not_a + n... |
067e1f92786e71f66de9b2d17c207541ffd403ad | jasminecronin/intro-to-cs-I | /Coursework/Assignments/Assignment 4/RushHourGame.py | 8,712 | 4.3125 | 4 | """Assignment 4: The Object of the Game
This program plays a text based version of the game Rush Hour. Moves are
prompted to the console and entered by the user. The game grid is printed
after every move. See the rules for legal moves in the readme.txt file.
Author: Jasmine Roebuck, Nov. 27, 2017"""
import sys
def ... |
e4bf5f5b51dca7bcc970e7cc4cbef7405db81be1 | imgomez0127/daily-programming | /interview-questions/dip28.py | 505 | 3.71875 | 4 | def max_change_helper(mat,i,j):
if i == len(mat)-1 and j == len(mat[0])-1:
return mat[i][j]
if i == len(mat)-1:
return mat[i][j] + max_change_helper(mat,i,j+1)
if j == len(mat[0])-1:
return mat[i][j] + max_change_helper(mat,i+1,j)
return mat[i][j] + max(max_change_helper(mat,i,j+... |
ffc68ce71d7b8e66035fb79f26e994657dd1ec17 | CristofherAndres/Codigos_Python | /guia asincronica/triangulo.py | 294 | 4.09375 | 4 | print("Bienvenido al triangulo de asteriscos")
ancho = int(input("Ingresa un ancho para tu triangulo: "))
for i in range(1,ancho+1):
for j in range(1,i+1):
print("*",end="")
print()
for i in range(ancho-1,0,-1):
for j in range(1,i+1):
print("*",end="")
print() |
4c3059cf099cdd218c589e0245c2028dac743800 | thyagogm/meusarquivos | /mostrar_numero_inteiro_de_um_valor.py | 155 | 3.9375 | 4 | from math import floor
# Armazena Valores
a = float(input('Digite um Numero!\n'))
print('O Numero = {}\nTem a Parte Inteira = {}'.format(a, floor(a)))
|
89ae73868ace91e4b5248ff11a2a767b21d660c7 | Kim-Ly-L/LPTHW | /00P1/00P2.py | 1,446 | 4.40625 | 4 | # An example of a Class Definition with Inheritance
# Define the classes
class Bookcase(object):
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return self.prettyprint()
def prettyprint(self):
return "A Generic Bookcase"
clas... |
59c745175d6a9a17b8acf15923a501f0f07ebf3e | pramodghadge/Python-Data-Structure | /algorithms/CareerCup/romanToDecimal.py | 1,378 | 3.578125 | 4 | def getValue(myStr):
if myStr == 'I':
return 1
elif myStr == 'V':
return 5
elif myStr == 'X':
return 10
elif myStr == 'L':
return 50
elif myStr == 'C':
return 100
elif myStr == 'D':
return 500
elif myStr == 'M':
return 1000
else:
... |
11bbc5f3b796fc7b2b3708b0e346ab1b90925882 | Lucian-N/CS50 | /pset6/mario/mario.py | 343 | 3.84375 | 4 | import cs50
while True:
print("Please select the pyramid height: ", end = "" )
height = cs50.get_int()
if height >= 0 and height <= 23:
break
for level in range(height):
print (" " * (height - level - 1), end = "" )
print ("#" * (level + 1), end = "" )
print (" ", end = "" )
pri... |
d7cf2b029976585f7be464cf911046e1946e9fc0 | Aditya8821/Python | /Python/Daily Challenges/Searching And Sorting/Bubble_Sort.py | 365 | 4.15625 | 4 | def BubbleSort(arr):
n=len(arr)
for i in range(n):
for j in range(n-i-1): #Here n-i-1 Bcoz largest element is reached to its pos(top) previous pass
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
arr=[64,34,25,12,22,11,90]
BubbleSort(arr)
print("Sorted Array: "+st... |
e77861cc46c9b1407a84ff2c8414df2ba284911e | cgazeredo/cursopython | /mundo02/aula-12_exercicios-044-gerenciador-de-pagamentos.py | 801 | 3.703125 | 4 | preco = float(input('Qual o preço normal do produto? R$'))
condicao = str(input('A condição de pagamento será à vista ou parcelado? '))
if condicao == 'à vista':
condicao_vista = str(input('O pagamento será feito em dinheiro cheque ou cartão? '))
if condicao_vista == 'dinheiro' or condicao_vista == 'cheque':
... |
a5549e7d440dc523f249bdacaada0abce6899fc4 | PedroVitor1995/Algoritmo-ADS-2016.1 | /Sequencial/Questao05.py | 409 | 3.796875 | 4 | #__*__ encoding:utf8 __*__
"""5. Leia um nmero inteiro (3 digitos), calcule e escreva a soma de seus elementos (C + D + U)."""
def calcula_soma(numero):
C = numero / 100
D = (numero % 100) / 10
U = numero % 10
soma = C + D + U
return soma
def main():
numero = input ('Digite um numero inteiro de 3 digi... |
81b44e98456e2864a96ad4c377d26b2cba662ec5 | alecmchiu/MOOCs | /MIT Python Part 1/Week 4/midterm.py | 3,003 | 3.984375 | 4 | #!/usr/bin/env python3
def is_triangular(k):
"""
k: a positive integer
returns: True if k is triangular, False otherwise
"""
if k == 1:
return True
n = 0
for i in range(k):
n += i
if n == k:
return True
return False
def print_without_vowels(s):
'''
s: a string to convert
returns: None
prints s wi... |
03d47098129aff89777e18542c8e75defe756bed | irq8/crypto | /keyspace.py | 1,059 | 3.96875 | 4 | # Simple key space calculator
passwd = raw_input('Password? ')
length = len(passwd)
symbolset = "!\"#$%&'()*+,-./:;<=>?@[\]^_\\`{|}~"
charcount = 0
symsum = 0
powerlength = False
uppercase = sum(1 for x in passwd if x.isupper())
lowercase = sum(1 for x in passwd if x.islower())
stringdigit = sum(1 for x in passwd if ... |
02ed3813c73571c6582a75ad237994855115c2d1 | mukhtarbayerouniversity/fairensics | /fairensics/data/decision_boundary.py | 8,097 | 3.65625 | 4 | """Decision boundary plots for 2D data sets.
The code for the scatter function is adopted from fair-classification:
https://github.com/mbilalzafar/fair-classification.
Usage and interpretation is explained in the example jupyter notebook.
"""
import matplotlib.pyplot as plt
import numpy as np
from aif360.dataset... |
00ac8ad4060f747351ae623657ff640e2ad0f3da | jasonwang1031/Coursera_Algorithms_C1 | /week3/QuickSort.py | 903 | 3.546875 | 4 | import random
def QuickSort(A):
if len(A) <= 1:
return A
else:
# P = random.randint(0, (N-1))
A, P = Partition(A)
Pivot = A[P]
B = QuickSort(A[:P])
C = QuickSort(A[P+1:])
B.append(Pivot)
array = B + C
return array
def Partition(A):
... |
e60ee72d6756ae85d8c05c0ed3499ad3fe6b59db | BrianDunneKK/GettingStarted-Python | /BlockyPython Answers/Level2.py | 2,633 | 3.75 | 4 | question = 101
if question == 1:
age = input("What age are you? ")
next_age = int(age) + 1
print("At your next birthday, you will be " +
str(next_age) + " years old.")
if question == 2:
age = input("What age are you? ")
twice_age = int(age) * 2
print("If you were twice as old, you’d ... |
f0325ef902cce3543ad97228030944a05716d219 | kesarb/leetcode-summary-python | /practice/solution/0876_middle_of_the_linked_list.py | 656 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_hea... |
f8314c487cfb615490bc0faede12a2ce74df3495 | gyyfifafans/jbt-simulator | /models/measure.py | 391 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Measure(object):
def __init__(self, measure, notes):
self.measure = measure
self.notes = notes
def to_string(self):
note_str = ""
for note in self.notes:
note_str += note.to_string() + "\n"
return "Measure[%d, \n%s]" % (self.me... |
13e643de80042d206decbd29b326e551a6d1e49a | odia101/Class4 | /our_csv_parser.py | 1,444 | 3.65625 | 4 | #!/usr/bin/env python
import os
#import numpy
#import csv
myfilename = "housing.data.txt"
# if os.path.isfile(myfilename):
# print("yay, I have a file")
# if sky == blue:
# print('yay the sky is blue')
# else:
# print ('boo, no files for me')
with open(myfilename, 'r') as file_handle:
housinglist = []
fo... |
65710d0b6b4b758d0c41382fe4c287da8b10e4ee | GINK03/atcoder-solvers | /abc205_e.v2.py | 765 | 3.515625 | 4 |
import timeit
def timer(function):
def new_function():
start_time = timeit.default_timer()
function()
elapsed = timeit.default_timer() - start_time
print(f'"{function.__name__}" took {elapsed} seconds')
return new_function
MOD = 10**9 + 7
""" mod combを用いるとテストケースで失敗する!! """
def mod_cmb(n, a, mod... |
91b7f994d704ecd31f8d98de1433dd7b3dce5032 | HarlemBusinessAlliance/WebDevelopmentSquad | /python/fourthpyfile.py | 1,792 | 3.828125 | 4 | # create a variable that holds 100k dice rolls in a two-dimensional array (100k rows, 2 columns) as part of the assignment
# Collecting Input
'''
import random
x = input("My name: ")
rolls = []
for n in range(10):
rolls.append([random.randint(1, 10), random.randint(1, 10)])
print("Hello,", x, ". You have the follow... |
05601d13a420b505162a760fdaf0139c0874c919 | jiangchance/git_test | /test1.py | 141 | 3.859375 | 4 | list = [1, 2, 3, 4]
for x in list:
for y in list:
for z in list:
if x!=y & y!=z &x!=z:
print (x,y,z) |
5bbe3fcd372f6a05689cbfac0fb37add954477fc | rajeshpyne/Work | /Algorithms/binary_search.py | 594 | 4.03125 | 4 |
def binary_search(arr, low, high, x):
if high >= low:
mid = (low+high)//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binary_search(arr, low, mid-1, x)
else:
return binary_search(arr, mid+1, high, x)
else:
return -1
if _... |
56394019de4413c4db18c57195ca223052d2f53e | Aquat1cTSK/pythonProject | /FileHW.py | 1,496 | 3.515625 | 4 | from pprint import pprint
def make_dict(file_name):
cook_book = {}
with open(file_name, 'r', encoding='utf-8') as file:
for line in file:
dish_name = line.strip()
records_quantity = int(file.readline())
ingredient_list = []
for ingredient in range(record... |
37837c6e356cb504add7327b57d1a9c8735d36cf | asheux/pyalgorithms | /codebreak/random/longest_substring.py | 687 | 4.03125 | 4 | def longest_substring(string):
l = len(string)
left = right = longest = 0
store = {}
longest_value = str()
while right < l:
letter = string[right]
if letter not in store:
store[letter] = True
n = len(store)
if n > longest:
... |
ea099e93ac8646147f82ebe45ca64f1a37fbf597 | duliodenis/python_master_degree | /unit_01/02_lists/expenses.py | 416 | 4.15625 | 4 | # Multi-dimensional Lists
# You can put lists inside of lists.
# This allows for you to create dimensions like rows and columns.
travel_expenses = [
[5.00, 2.75, 22.00, 0.00, 0.00],
[24.75, 5.50, 15.00, 22.00, 8.00],
[2.75, 5.50, 0.00, 29.00, 5.00],
]
print("Travel Expenses")
week_number = 1
for week in t... |
17c7c01b18a1d32d50b8524b0bc5a603ddb7903f | sid-am-ahd935/LetsUpgrade-Advanced-Django-Sept2020 | /Day 16 Assignment 1.py | 1,019 | 3.84375 | 4 | #Program To Store All IP Adresses From WebPage
def ip_extractor(ip:'Regex',page : str)->None:
import re
found_ip = re.finditer(ip,page)
#All IPs Found In Page In One Iter Object
c = 0 #For Counting All IP Addresses
for each in found_ip:
#each=<ipMatchObject> From Iter Object
c += 1
print(f"{c})",each.... |
9fa77e53b25a6ec2821cbd67d158ef26f3556c45 | B179372-2020/Lecture_exercises | /Lecture13/ex01.py | 916 | 3.53125 | 4 | #!/usr/bin/python3
#data = open("data.csv","w")
#dmeef main():
with open ("data.csv") as data:
for line in data:
line_list = line.split(",")
#print(line_list)
gene_name = line_list[2]
print(gene_name)
seq = line_list[1]
#print(len(seq))
print(seq[89:110])
at_content = (seq.count("a")+seq.count("... |
583edbf053189c85f7fe2e79a170f15ddd42ca03 | LingB94/Target-Offer | /64求1+2+...+n.py | 220 | 3.6875 | 4 | def Sum0(n):
return 0
def SumForN(n):
funChoice = {False:Sum0, True:SumForN}
flag = not not n
result = n+funChoice[flag](n-1)
return result
if __name__ == '__main__':
print(SumForN(5)) |
1a5a9b78bd6910a203ba7d06fd76bbc6a9cf1a59 | amrit2356/Dev-Training-Python-Fundamentals | /06_Python_Generators_iterators/02_Generators_intro.py | 330 | 4.15625 | 4 | """
Implementation of Generators in Python
"""
def square_numbers(nums):
for i in nums:
yield(i*i)
my_nums = square_numbers([1,2,3,4,5])
for num in my_nums:
print(num)
# List Comprehension Implementation of Generator
my_nums = (x*x for x in [1,2,3,4,5])
print(my_nums)
for num in my_nums:
... |
d1d911aa868ffd23ac9f1c094a06c27a96cb9517 | linzhongxiazhi/student_python | /学习/复习/1到100求和.py | 550 | 3.609375 | 4 | # # 1 到100求和
# #定义计数器
# i = 1
# #定义总和
# r = 0
# while i <= 100:
# a = r
# r += i
# print("进行到第{}计算:{}+{}={}".format(i,i,a,r))
# i += 1
#
# print("1到100总和为:{}".format(r))
""" 1到100偶数和 """
# 定义计数器
i = 1
c = 1
# 定义总和
r = 0
while i <= 100:
if i % 2 == 0:
i += 1
continue
else:
... |
18a2f38f2a462790834f831dd403a117b355ddfa | alice2018/Python | /3-16-2.py | 201 | 3.734375 | 4 | # -*- coding: cp936 -*-
import re
a = re.search('\d+','231422sadf')
print a.group(0)
#-------------------------
x = re.search('3', "3456")
y = re.search('3', "14789")
print x.group(0)
print y
|
d2bac103de7bb9650dad691b9a4c875ab9472bcc | alyhhbrd/CTI110- | /P3LAB_Hubbard.py | 976 | 4.25 | 4 | # CTI-110
# P3Lab1 - Debugging
# Aaliyah Hubbard
# 03032019
#
# This program takes a number grade and outputs a letter grade.
# student inputs score
# calculate input and determine grade using 10-point scale
# display letter grade as output
def main():
# define scores
A_score = 90
B_scor... |
25c161afa8c758587754aa0521f01afcfba10b4c | 646981700/autotest1 | /testbaidu.py | 1,525 | 3.703125 | 4 | data={}
#登录功能
def loginfun():
print('提示:(1)登录 (2)注册')
num = input('请选择')
# 注册
if str(num) == '2':
while True:
id = input('请输入账号')
pwd = input('请输入密码')
verify = input('请确认密码')
if id in data.keys():
print('账号密码已存在,请重新输入')
... |
3b13f8572be5c2312f8d288fa891227eccbc8eb1 | solanyn/cs-courses | /intro-cs/intro-to-programming/exercises/ex_12_05.py | 797 | 3.65625 | 4 | """
Exercise 5: (Advanced) Change the socket program so that it only shows data after the headers and a blank line have been received. Remember that recv receives characters (newlines and all), not lines.
"""
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
url = input('Enter URL: ')
if len(u... |
59437628554f61e5fb07ab2ac0e666c90cf83d6e | hacktoolkit/code_challenges | /project_euler/python/076.py | 3,424 | 3.953125 | 4 | """http://projecteuler.net/problem=076
Counting summations
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two positive integers?
Solution by jontsai <hello@jo... |
e8ad81b14118013426f15d7c872e136e4f5ca4db | vinaykumar7686/Leetcode-Monthly_Challenges | /July/Week2/Find Peak Element.py | 1,038 | 4.21875 | 4 | # Find Peak Element
'''
A peak element is an element that is strictly greater than its neighbors.
Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞.
You must write an algor... |
bd8152bd11599c3f8fb474e4fca5014fed3cb56a | the-hobbes/hadoop_mapreduce | /part_1/mapper_highest_individual_sale_per_store.py | 661 | 3.953125 | 4 | #!/usr/bin/env python
'''
Provide data to the reducer to solve the following:
2) Find the monetary value for the highest individual sale for each separate
store
Output to the reducer should be the store and cost of each item pulled
from every line of the input.
'''
import sys
def mapper():
'''
data is i... |
d46e31649b7d16eb9716815dcfa213c8f3868307 | viswamraju/python-learning | /searching/binary_serach.py | 906 | 4.21875 | 4 | def search(numbers, item):
is_exists = False
lower = 0
upper = len(numbers) - 1
# check for lower is always less than or equal to upper
while lower <= upper:
# calculate mid integer division
mid = (lower + upper) // 2
print(f"lower: {lower}, upper: {upper}, mid: {mid}")
... |
2409981d7e02f5c94885f27b1bb0abc26cbd0cde | AlexWoroschilow/uni_hamburg | /GSA/uebung_4/aufgabe4_1-nicht-in-n2.py | 883 | 3.5625 | 4 | # GSA
# Aufgabe 4.1
import string
import sys
print #print empty line for aesthetics
k = 3 # choose a substring lenth
s1 = "aaaba" # hard-code two strings, s1 and s2
s2 = "baaba"
def matchcount(x,y):
# reset counter for matchcount to 0 every time the function is called
counter = [0]
for i in range(len(x)... |
09117cf1ad43a4dbc6573e171ad501c29ea840ef | lj015625/CodeSnippet | /src/main/python/tree/breadthFirstSearch.py | 1,091 | 3.828125 | 4 | class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
# O(vertices+edges) time O(vertices) space
def breadthFirstSearch(self, array):
queue = [self]
while queue:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.