blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d13ae730277e6e7d23baf413b7f4d75d2c0db676 | astreltsov/firstproject | /Tuples_and_2d_arrays/Tuple_example.py | 279 | 3.796875 | 4 | my_tuple = ('green', 'red', 'blue')
joe_marks = [55, 63, 77, 81]
tom_marks = [65, 61, 67, 72]
beth_marks = [97, 95, 92, 88]
class_marks = [joe_marks, tom_marks, beth_marks]
print(class_marks)
for student_marks in class_marks:
print(student_marks)
print(class_marks[0][2]) |
21ebc728e479de829511bedfb57b09e26e818380 | soumasish/leetcodely | /python/paint_fence.py | 425 | 3.65625 | 4 | """Created by sgoswami on 7/30/17."""
"""There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence."""
class Solution(object):
def num... |
9ad4449e02b68e330e74ce28f2cc1b8f02dd5d81 | madelyneriksen/sage-manager | /sagemanager/crypto.py | 1,821 | 3.796875 | 4 | """
Main Cryptographic functions for the SageManager library.
SystemRandom() is used for generating cryptographically secure password choices.
The level of security may not be the same on all systems.
Encryption itself is done with GPG encryption, using a user entered password
for encrypting/decrypting passwords.
"""... |
6ad8208dc2d5ce85018c182d7b5f8673695d6f74 | hongjiacan/learning | /ai/python/dailyPy/2019/py1114_tuple.py | 703 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 元组
# 初始化后就不能修改
# tuple 的每个元素,指向永远不变
# 但指向的元素可变
# 更安全
sex = ('male', 'female')
week = ('Monday', 'Tuesday', 'Wensday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
print(sex)
print(week)
tuple1 = ()
tuple2 = ('single',) # 单元素的元组必须带个逗号
str1 = ('single') # 不是元组
print(tupl... |
e0600eb0bf50398584e38f94b461735795662367 | ssangitha/guvicode | /div_modulo_in_line.py | 173 | 3.515625 | 4 | s=input()
a=""
b=""
if "/" in s:
i=s.index("/")
a=s[0:i-1]
b=s[i+2:]
print(int(a)//int(b))
elif "%" in s:
i=s.index("%")
a=s[0:i-1]
b=s[i+2:]
print(int(a)%int(b))
|
d5c9b8be440d03559e2e7e2f5c6470f25c43434a | HDPark95/algorithm | /graph/bfs.py | 766 | 3.75 | 4 | #너비 우선 탐색 알고리즘인 BFS는 큐자료구조에 기초한다는 점에서 구현이 간단하며, 파이선에서는 deque 라이브러리를 사용하는 것이 좋다.
from collections import deque
def bfs(graph, start, visited):
#큐 구현을 위해 deque라이브러리 사용
queue = deque([start])
#현재 노드를 방문 처리
visited[start] = True
#큐가 빌 때까지 반복
while queue:
#큐에서 하나의 원소를 뽑아 출력
v = queu... |
63d135fadae0a622dd66e65aa0ded74b22495438 | Lfritze/cs-module-project-algorithms | /single_number/single_number.py | 990 | 4.03125 | 4 | '''
Input: a List of integers where every int except one shows up twice
Returns: an integer
'''
def single_number(arr):
# Your code here
solo = []
for x in arr:
if x not in solo:
solo.append(x)
# print(solo)
else:
solo.remove(x)
# print(solo)
... |
c4555a881cd78198058ba877dab47aa1ee6ab8ee | billcccheng/algorithms | /bitwise_or_range.py | 622 | 3.65625 | 4 | #!/usr/bin/env python3
from functools import reduce
def bitwise_or_range(m, n):
if len(bin(m)) != len(bin(n)):
left_shift = max(m.bit_length(), n.bit_length())
return (1 << left_shift) - 1
left_shift = 0
while m != n:
m >>= 1
n >>= 1
left_shift += 1
return (n << ... |
1dc75536b17254e53d498531fb98fa168acfa3af | realnitinworks/bitesofpy | /282/bridgehand.py | 4,247 | 3.609375 | 4 | from collections import namedtuple, defaultdict
from enum import Enum
from typing import Sequence
Suit = Enum("Suit", list("SHDC"))
Rank = Enum("Rank", list("AKQJT98765432"))
Card = namedtuple("Card", ["suit", "rank"])
HCP = {Rank.A: 4, Rank.K: 3, Rank.Q: 2, Rank.J: 1}
SSP = {2: 1, 1: 2, 0: 3} # cards in a ... |
9ef6dcaf4b48e6eb5735ed44fb5830837cebab94 | Long0Amateur/Self-learnPython | /Chapter 2 Loops/Chapter 2 (exercises).py | 1,229 | 3.96875 | 4 | #Problem 1
print('Problem 1')
name = 'LONG'
for i in range(5):
print(name)
print(sep='\n')
#Problem 2
# A program to fill the screen horizontally and vertically with your name
print('Problem 2')
for i in range(5):
print('LONG'*5)
print(sep='\n')
#Problem 3
print('Problem 3')
for i in ran... |
5afcea597a9a3864987e504e4eff0c50074f48a2 | jormao/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 3,490 | 3.546875 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
Class Rectangle that inherits from Base
"""
from models.base import Base
class Rectangle(Base):
"""class Rectangle"""
def __init__(self, width, height, x=0, y=0, id=None):
super().__init__(id)
self.validate_int(width, 'width')
self.vali... |
066e99f791d648cfaa859874c5b79ee62d2a2983 | daisyzl/program-exercise-python | /Finger/zuichanghuiwenzichuan.py | 1,104 | 3.859375 | 4 | # -*-coding:utf-8-*-
'''
题目:最长回文子串
https://leetcode-cn.com/problems/longest-palindromic-substring/
推荐方法为动态规划
没有实现
'''
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
l, r = 0, 0
n = len(s)
max_length = 0
temp = ... |
746dd875c42c3522b6a287ff8bb7530485f85c68 | vnikov/Fall-2017 | /CS111/Lab4/lab4task3.py | 682 | 4.125 | 4 | #
# Lab 4, Task 3 - debugging a recursive function
#
def remove_spaces(s):
''' return a string in which all of the spaces have been removed '''
if len(s) == 0:
return ''
elif s[0] == ' ':
return '' + remove_spaces(s[1:])
else:
return s[0] + remove_spaces(s[1:])
def test():
... |
e59b3358ff3b1f576c18357c43e2b3f663b9da61 | BowieSmith/project_euler | /python/p_023.py | 765 | 3.53125 | 4 | # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
import p_021
if __name__ == "__main__":
abundant_nums = set()
for i in range(1,30_000):
if p_021.d(i) > i: # if sum of divisors > i
abundant_nums.add(i)
nums_sum_of... |
bb0dab26fd0f0ec33e846c32a9cabd70878703c0 | aventador2018/Principle-Programming-Language-504-51 | /Assignment_7/Account2.py | 735 | 3.546875 | 4 | class Account:
def __init__(self, name, account_number, initial_amount):
self.name = name
self.no = account_number
self.balance = initial_amount
self.transactions = 0
def deposit(self, amount):
self.balance += amount
self.transactions = self.transactions + 1
... |
323ec3122a7d64fb31dde246a86c44ebff5e4f30 | Sakib37/OOP_Python | /inheritance.py | 2,066 | 4.25 | 4 | """ learning of OOP in Python by Mohammad Badruzzaman
All the programs will contain detail explanation for my understanding"""
class BaseClass( object ):
"""This class is inherited form a base class 'object' which is a base class of python which allows inheritance to happen. If we delete
the object and inherit only... |
d2b300ec6573b03c0321e5ea763c4735791a1082 | ZUGRII/OOP | /Week 2/binaryToDecimal.py | 210 | 4.0625 | 4 | #Convert Binary to Decimal
#Author: Georgiana Zugravu
#Date: 26th September 2019
#Compiler: PyCharm
import math
binary_str = input("Enter a binary number: ")
number = int(binary_str,2)
print("The number is: ", number)
|
7d5a08ca0dee72e0efcf14d473c34629af1b3b71 | MisterrLuck/timer | /Timer.py | 899 | 3.53125 | 4 | import time, sys, beepy
print("----------Timer----------")
s = int(input("How many seconds: "))
m = int(input("How many minutes: "))
h = int(input("How many hours: "))
sys.stdout.write(f"\r{h}:{m}:{s}")
time.sleep(1)
sys.stdout.write("\r ")
while True:
if h > 0 or m > 0 or s > 0:
if s > 0:
... |
cbd619e3b5abcebd66ba2f4d28338aad472ae8f2 | guilhermejcmarinho/Praticas_Python_Elson | /02-Estrutura_de_Decisao/06-Maior_de_tres.py | 438 | 4.1875 | 4 | numero01 = int(input('Informe o primeiro numero:'))
numero02 = int(input('Informe o segundo numero:'))
numero03 = int(input('Informe o terceiro numero:'))
if numero01>numero02 and numero01>numero03:
print('Primeiro numero: {} é o maior.'.format(numero01))
elif numero01<numero02 and numero02>numero03:
print('Pr... |
cae4ddb9e4c7627bc1db3676e40c64cc425ce6dd | UlisesND/CYPUlisesND | /libro/problemas_resueltos/capitulo1/problema1_1.py | 192 | 3.5625 | 4 | PREPRO=float(input("precio del producto:?"))
PAGO=float(input("De cuanto es tu pago:"))
DEVO=PAGO-PREPRO
print(f"Pagaste: ${PAGO} el precio del producto es:${PREPRO} y su cambio es: ${DEVO}")
|
bf93ba1ad9e5219948d92cb4ab4ccc48b7466ea5 | marcelofabiangutierrez88/PythonEnClase | /6.1.EstaEnListaConWhile.py | 276 | 3.53125 | 4 | def estaEnLaLista3(ent, lst):
i = 0
esta=False
while i < len(lst):
if ent in lst:
esta=True
i+=1
return (esta)
def main():
lst =[0,1,2,15,45]
ent = 23
print(ent,lst)
print(estaEnLaLista3(ent,lst))
main() |
66bab8379c7f585e4c1993ce18613f4b61ddbfa7 | ndquang245/Quang | /minihack/bai4.py | 107 | 3.9375 | 4 | from turtle import *
r = int(input("Enter a radious you like:"))
circle (r)
shape("turtle")
mainloop() |
24c8f33cbac34f20ff1c2664fd5e752542d6d6db | lc-leonesse/Python | /Coursera - Parte 1/Semana 4/impares.py | 237 | 3.921875 | 4 | """
Receba um número inteiro positivo na entrada e imprima os n primeiros números ímpares naturais.
"""
n = int(input("Digite o valor de n: "))
i = 0
ímpar = 1
while i < n:
print(ímpar)
i = i + 1
ímpar = ímpar + 2
|
c544bfa7f82f44ca8003b32cdb6bf34e9ac0a2a6 | dev-arthur-g20r/how-to-code-together-using-python | /How to Code Together using Python/EVENT DRIVEN PYTHON/perimeterofrectangle.py | 314 | 4.0625 | 4 | import os
def perimeterOfRectangle(l,w):
p = 2 * (l + w)
return p
print("Enter length and width of rectangle to check its perimeter: ")
length = float(input("Length: "))
width = float(input("Width: "))
perimeter = perimeterOfRectangle(length,width)
print("Perimeter of rectangle: ", perimeter)
os.system("pause") |
854bcd4bfac80cab7c235cb968fc665e1fcadadc | wheresauldo/circles_and_spiderwebs | /spider_web.py | 2,207 | 3.75 | 4 | # Spider Web
import turtle
my_turtle = turtle.Turtle
turtle.speed(0)
turtle.bgcolor("black")
turtle.color("white")
home = (0, 10)
not_home = (-10, 20)
"""
def draw_base(leg_num, length):
angle = (360/leg_num)
turtle.up()
turtle.goto(home)
turtle.right(angle)
turtle.down()
turtle.forward(leng... |
e163c20c3492092eb1b3c4a40500982e4968916b | Vimala390/Vimala_py | /sam_primenumber.py | 210 | 3.84375 | 4 | # 2 3 5 7 ...
n = int(input('enter number :'))
for i in range(2,n+1):
x = True
for j in range(2,i):
if i%j == 0:
x = False
if x:
print(i,end=" ")
|
72e4f4de0b2d94e8e015dfeffed282af7c76cfde | 549982170/python_learning | /test/testpower/atest22.py | 381 | 3.765625 | 4 | #!user/bin/python
# encoding:utf-8
def processor(page, maxmun, num=1, count=0):
count += page
if count <= maxmun:
yield num
else:
count = 0
num += 1
yield num
c = processor(1, 2)
print c.next()
c = processor(2, 2)
print c.next()
c = processor(2, 2)
print ... |
870ffd55c6bd39c58f54e9d01b32f7b72d40e9a6 | ajpiter/PythonProTips | /Stats/CoinFlips.py | 962 | 4.03125 | 4 | #Use simulated repeated measurements to compute probabilities
#np.random is a suite of functions based on random number generation
#draws a number bewteen 0 and 1
np.random.random()
#integer fed into random number which will produce the same random results everytime
np.random.seed()
#Bernoulli trial, an experiment... |
6812b92a80a2d99077153c6a8ae857c74e7a80aa | CelesteEspinoza/4-Busquedas-Informadas | /canibales.py | 3,879 | 3.515625 | 4 | import busquedas
class ModeloCanibales(busquedas.ModeloBusqueda):
"""
Problema de los misioneros y canibales, donde x = ((nM0, nC0), (nM1, nC1), 0)
es el estado con la cantidad de misioneros, canibales.
La primera tupla es el numero de misioneros y canibales
del lado izquierdo, la segunda tupla es ... |
e882f8a74ab83b54403250cb643a8c2c59a28c7f | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/84_13.py | 2,744 | 4.375 | 4 | Python – Prefix frequency in string List
Sometimes, while working with Python lists, we can have a problem in which we
need to get the count of strings that start with particular substring. This
can have an application in web development and general programming. Lets
discuss certain ways in which this task ca... |
407ac3cdb453392c98224f30efa3a4d80e09c82a | 4RG0S/2020-Fall-Jookgorithm | /최민우/[20.09.09] 2331.py | 410 | 3.515625 | 4 | from collections import deque
def nextNode(num):
result = 0
for c in str(num):
result += int(c) ** P
return result
def bfs(start):
queue = deque([[start, [start]]])
while queue:
q, path = queue.popleft()
p = nextNode(q)
if p in path:
return path.index(... |
df1b1620c22a8ddab1ebb8dcdff50b64fe0631d5 | hgmiguel/sphere | /palin.py | 1,131 | 3.703125 | 4 | #!/usr/bin/python
def has_cuentas(numero,numeros,length=1):
numero_s="".join(numero)
if numero_s in numeros:
return numeros[numero_s]
while True:
l=int(numero[0])
r=int(numero[-1])
if l == r:
break
elif r > l:
l+=10
numero=in... |
6eb70d7b7c6c224bfec97c3016c3edff1b4c69f1 | HIT-jixiyang/offer | /printAllString.py | 752 | 3.734375 | 4 | # -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.result=[]
def Permutation(self, ss):
# write code here
if len(ss)==0:
return []
chars=[]
for i in range(len(ss)):
chars.append(ss[i])
self.helper(chars,0)
def helper(self,c... |
a205b84d3f2f3186c7b3b4337e2cd3999983273d | emmas0507/lintcode | /remove_duplicates_sorted_array.py | 443 | 3.78125 | 4 | def remove_duplicates_sorted_array(input_array):
current_value = input_array[0]
current_index = 1
for i in range(1, len(input_array)):
if input_array[i] > current_value:
current_value = input_array[i]
input_array[current_index] = current_value
current_index = curr... |
8bb4fbe55ea3ba6d77bd05986422b4df5dc4c28d | nishaagrawal16/Datastructure | /Linklist/sum_of_link_lists_in_same_order.py | 3,112 | 4 | 4 | #!/usr/bin/python
# Date: 2019-06-23
#
# Description:
# Two numbers represented by a linked list, where each node contains a single
# digit. The digits are stored in forward order, such that the 1's digit is at
# the tail of the list. Write a function that adds the two numbers and returns
# the sum as a linked list in... |
2b6e887ac6d714fb1bd7702f22b09fb783388c97 | diegoandresalvarez/elementosfinitos | /codigo/1D/EF_barra_2_nodos/deduccion_func_forma_EF_barra_2_nodos.py | 567 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# Deducción de las funciones de forma del elemento de barra de 2 nodos
import sympy as sp
# Defino las variables simbólicas
u1, u2, x, x1, x2, a1, a0 = sp.symbols('u1 u2 x x1 x2 a1 a0')
r = sp.solve((sp.Eq(u1, a1*x1 + a0),
sp.Eq(u2, a1*x2 + a0)), (a0, a1))
print('a0 = '); sp.p... |
9706893ca592f5c3bbc6fee2d2201b1186f96e62 | av1234av/hello-world | /bracket.py | 664 | 3.75 | 4 | def balanced_brackets(s):
l=[]
balanced=True
for c in s:
if c in '({[':
l.append(c)
else:
if l:
top=l.pop()
if not matches(top,c):
balanced = False
else:
balanced = False
if balanced ... |
f1d91e3185104055b6d9011dc1213637ccda2f6f | arisskz6/learnPython | /chapter03/exercise_3-3.py | 229 | 3.578125 | 4 | # 使用存储喜欢的通勤方式并以宣言的方式输出
commute = ['by bike', 'by motorcycle', 'by car', 'on foot', 'by air']
for i in range(4):
message = f"I would like to commute {commute[i]}."
print(message)
|
7234816d8381e35cfd3a22bf84d03695e176069f | MikkelLauridsen/P5-Project | /datareader_csv.py | 10,038 | 3.75 | 4 | """Functions for loading and parsing data from the csv files into lists of Messages."""
import csv
import pandas as pd
import datapoint
import message
import os
from metrics import Metrics, Result, get_metrics_path
from datapoint import datapoint_features
def __load_data(filepath, parse_func, start, limit, verbose=Fa... |
1750055fe56a31d41c5fac2a0e061c0b0cb3a387 | bdliyq/algorithm | /lintcode/hash-function.py | 729 | 3.671875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Question: http://www.lintcode.com/en/problem/hash-function/
class Solution:
"""
@param key: A String you should hash
@param HASH_SIZE: An integer
@return an integer
"""
def hashCode(self, key, HASH_SIZE):
# write your code here
magic_nu... |
3a742e72798d2bd056da9563bce9e5e574758432 | jakehoare/leetcode | /python_1_to_1000/109_Convert_Sorted_List_to_Binary_Search_Tree.py | 1,829 | 4 | 4 | _author_ = 'jake'
_project_ = 'leetcode'
# https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
# Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
# Count the length of the list. Form left subtree from nodes before mid. Mid node forms... |
c8c862d95746ec173767543bcbce22ef6b63dcad | josebalcon/demorep | /ejercicio.py | 326 | 3.859375 | 4 | # HOla mundo ..
# ///////////////////////
# new
a = 1
acumulador = 0
contador = 0
while a == 1:
notas = int(input("Ingresa tus notas (presiona 0 para promediar) :"))
if notas > 0:
acumulador = acumulador + notas
contador = contador + 1
elif notas <= 0:
a += 1
promedio = acumulador/contador
print pr... |
8b74e48d3019c8d193e14634e209b980463043cc | kamileo/AccessVBA | /ProjectEuler/[0 - 25]/Problem1/program.py | 99 | 3.8125 | 4 | s = 0
for x in range(0, 1000):
if (x % 3) == 0 or (x % 5) == 0:
s += x
print(s)
|
31327f5d766167fe3551c6abc4e5f7832d9ea736 | xtakacsx/bitesofpy | /74/bday.py | 171 | 3.53125 | 4 | import calendar
def weekday_of_birth_date(date):
"""Takes a date object and returns the corresponding weekday string"""
return calendar.day_name[date.weekday()]
|
48ce7b899681acc1dfb9466d46ac394ca02c3470 | youbingchenyoubing/Machine_Learning_in_Python | /Linear_Regression/BatchGradientDescent.py | 2,776 | 3.859375 | 4 | ### Univariate batch (standard) gradient descent algorithm
### author: Dr. Marko Mitic
### year 2015
### contact: miticm@gmail.com
import numpy as np
import matplotlib.pyplot as plt
class BatchGD: #Main class for Univariate Batch Gradient Descent
def __init__(self, data):
### data is given in two-... |
8f880097eb5836148fa953b283ee4cfc6444803b | ChristieGC13/hello_flask | /hello.py | 726 | 3.65625 | 4 | from flask import Flask # Import Flask to allow us to create our app
app = Flask(__name__) # Create a new instance of the Flask class called "app"
@app.route('/') # The "@" decorator associates this route with the function immediately following
def hello_worldcopy():
return 'Hello World!' # Return the... |
7c6afe35506dd569fedb55e2f6801efebe04501c | xtet2008/algorithms_grokking | /quick_sort.py | 1,935 | 3.640625 | 4 | import random
def recursive_sum(arr):
_tmp = 0
if arr.__len__() == 0:
return 0
elif arr.__len__() == 1:
return arr[0]
else:
return arr[0] + recursive_sum(arr[1:])
print (recursive_sum([1, 3, 5]))
print (recursive_sum([0]))
def recursive_count(arr):
if arr == []:
... |
7729daf146109ee53d145333f6e435a25d85e559 | pedrohft/URI | /python/1140.py | 533 | 3.640625 | 4 | while True:
string = input()
if string == '*':
break
dataSplit = string.split(" ")
flag = 0
if len(dataSplit) == 1:
flag = 1
else:
for i in range(len(dataSplit)-1):
if (dataSplit[0][:1].lower() == dataSplit[i+1][:1].lower() and dataSplit[0][:1].lower(... |
9598d2648dbca266566886e7b097394159bd6d96 | Pedro-D13/Higher-or-Lower-Game | /card_deck.py | 757 | 3.546875 | 4 | import random as rand
suits = ['clubs', 'spades', 'hearts', 'diamonds']
numbers = [x for x in range(2, 10)]
face_cards = ["Ace", "Ten", "Jack", "Queen", "King"]
fc_values = [1, 10, 11, 12, 13]
def deck_creator():
num_deck = [f"{num} of {suit}" for num in numbers for suit in suits]
# Face card Deck
fc_deck =... |
d509f2a03f49e1d7dbfefd0252a822ba57374942 | mathews012468/webScrapingExamples | /yahooFinanceScraperSolution2.py | 2,907 | 3.703125 | 4 | import requests
import json
from datetime import datetime
from pprint import pprint
#ticker is a string containing the symbol of the stock we're interested in
#period1 and period2 and integers containing the unix timestamps of the oldest
# and most recent stock prices we're interested in, respectively
def getStockP... |
228e9108554d026eb6687109b66bc83bbed509f8 | Cyki89/Python_Algorithms_and_DataStructures | /Algorithmic Problems/Tower Hopper Problem/Tower Hopper Problem.py | 1,452 | 3.90625 | 4 | ## Recursive solution with rev_sort outside function
'''
def is_hoppable(data):
if data == []:
return True
for x in enumerate(data,1):
if x[0] <= x[1]:
if is_hoppable(data[x[0]:]):
return True
return False
data = [4,2,0,0,2,0]
data = data[::-1]
... |
c801cf6b67e8be29da3bf378e55009f3c3897c6a | knrastogi/PythonPrograms | /EndTermLabExamSol/BA/A1.py | 1,633 | 4.28125 | 4 | '''
Write a program that performs the following operations using appropriate functions on a
string.
a) Check whether the string is a valid identifier or not.
b) Convert the string into title case.
c) Get the elements at alternate places.
d) Swap the case of the string.
e) Find whether a character or a... |
cc2b15bcca43430bbc6d953f5d669a35ea7c0520 | jasanjot14/Data-Structures-and-Algorithms | /Algorithms/recursive_binary_search.py | 1,604 | 4.40625 | 4 | # Function to determine if a target (target) exists in a SORTED list (list) using a recursive binary search algorithm
def recursive_binary_search(list, target, first, last):
# Base condition
if first > last:
return None
# Updates the midpoint in the search space
midpoint = first + (las... |
814e3eba5eb4a43908b0c1b2a1134230ef720131 | mkuentzler/AlgorithmsCourse | /heaps.py | 5,209 | 3.890625 | 4 | """
heaps.py
Wrapper classes implementing the functions of the heapq module as methods of a
heap. Supports minimum heaps and maximum heaps. By Moritz Kuentzler.
"""
import heapq
class Minheap:
"""
A wrapper class implementing the heapq functions as methods of a
minimum heap.
The Minheap class is ini... |
5d93ae106fca65d611a574a7ec216adc9bbfb185 | ronaldsnyder/Learn-Python-The-Hard-Way | /chapter36/my36.py | 2,863 | 3.828125 | 4 | #Name: my36.py
#Date: 1/15/2014
#Author: Ron Snyder
#Purpose: Project for the first 36 chapters of LPTHW
from sys import exit
import random
def fight():
life = random.randint(1,10)
return life
def start():
print """
You enter the underground dungeon and find a room
to your right, left and ... |
f43cc2ee4a4eaa3f9ebc56be2f67546bc79c3429 | debsilverman/Programs | /usingInput.py | 230 | 4.0625 | 4 | name = input("Enter your name: ")
surname = input("Enter last name: ")
when = "today"
#message = "Hello %s" % user_input
#message = f"Hello {user_input}"
message = f"Hello {name} {surname}. What's up {when}"
print(message)
|
d2ba5849d5d4dc18024d6ff667d3b66ecb346663 | ekukura/hackkerrank | /_algorithms/bit-manipulation/maximizing-xor.py | 582 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maximizingXor function below.
def maximizingXor(l, r):
max_val = 0
for v1 in range(l, r):
for v2 in range(v1 + 1, r+1): # a xor a = 0 always
cur = v1 ^ v2
if cur > max_val:
... |
091ad1ce8161a64f91ce71d84383e36b73c2949e | GAYATHRY-E/python-programme | /datatypes.py | 403 | 3.78125 | 4 | #finding datatype
#datatypes in python(8)
#None,Numeric,List, Tuple,Set, String,Range, Dictionary
>>> type(a)
<class 'int'>
>>> int(5.66489)
5
>>> float(569)
569.0
>>> complex(5,6)
(5+6j)
>>> range(0,10)
range(0, 10)
>>> list(range(0,10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(0,10,2))
[0, 2, 4, 6, 8]
>>> list(r... |
2db97180c4269f2ee6c8d9f142098b848d633646 | Xerrex/rmw-API | /app/data/controller_user.py | 1,050 | 3.671875 | 4 | from .models import User
def create_user(name, username, email, password):
"""Create a new User
Args:
name (String): name of the User
username (String): a unique name to identify user
email (String): an Email formated string
password (String): The secret key to authenticate a ... |
03a66e1423270ae53e94aed1d885dbc12bd23fba | jossrodes/PYTHONFORDUMMIES | /063_error_types.py | 216 | 3.546875 | 4 | price = raw_input('Enter price: ')
qty = raw_input('Enter quantity: ')
price * qty
price, type(price)
qty, type(qty)
price = float(price)
qty = int(qty)
price * qty
price = float(raw_input('Enter price: '))
|
48692ace1122c950fc966f5762be12ebdb6091a1 | dlwlsrnjs/webday | /project/bookreview/12/soluotion.py | 192 | 3.5 | 4 | n=input()
n=int(n)
print(n)
result = []
for i in range(2,n+1):
while(n%i==0):
n/=i
result.append(i)
i+=1
for j in range(result):
print(result[j],result[j+1]) |
b85804495de009fbc9e768ed883191949b4ce8f9 | bcinbis/portfolio2018 | /Python/ShapeTester/SourceCode/Pyramid.py | 455 | 3.578125 | 4 | class FidgetSpinner:
volume = 0
SA = 0
def __init__(self):
self.pW = 0
self.pL = 0
self.pH = 0
def volume(self):
volume = self.pW * self.pL * self.pH * (1/3)
print("Your volume is: " + str(volume))
def SA(self):
SA = self.pW * self.pL + self.pL * (... |
800c04152dd5cf0d1ce032552ffb7dcd057f2124 | deanpjones/Codecademy-Python-Coursework | /08-Project (Thread Shed)/proj8_thread_shed.py | 8,652 | 3.96875 | 4 | # THREAD SHED
# PROJECT #8
# CODE ACADEMY
# PROGRAMMING WITH PYTHON
# Dean Jones, Aug.13, 2018
# You've recently been hired as a cashier at the local sewing hobby shop, Thread Shed.
# Some of your daily responsibilities involve tallying the number of sales during the day,
# calculating the total amount of money made... |
d16abdcf6db7850f652943eeb57a3d3061640807 | marlonjames71/Intro-Python-I | /src/env python3.py | 1,552 | 4.25 | 4 | #!/usr/bin/env python3
import random
# Create Rock Paper Scissors Game in Python
# Player should be able to type r, p, or s
# Computer will pick r, p, or s
# Game will print out the results and keep track of wins, losses, and ties
# Type q to quit
# Build REPL
wins = 0
losses = 0
ties = 0
choices = ["r", "p", "... |
311fb7482e86abe6542de0b12183fd16f2380aab | imandr/neural-npy | /lib/mynnet/lstm.py | 13,476 | 3.6875 | 4 | """
This is a batched LSTM forward and backward pass
"""
import numpy as np
from mynnet import Layer, InputLayer
class LSTM(Layer):
def __init__(self, inp, out_size,
reversed = False,
last_row_only = False, weight_decay=1.e-5,
name = None, applier = None):
... |
51866f0e93d3af882332291de664584eb3112caf | Hroderic-Rovira/AP_Final_Project-Test | /datos_json/json_manager.py | 2,386 | 3.71875 | 4 | import json
import os
"""
Los métodos dentro de la clase Administrador_JSON funcionarán como nuestro CRUD.
"""
class Administrador_JSON():
def __init__(self, archivo_json):
#Obtenemos la ruta abosulta del archivo JSON.
path = os.path.abspath(__file__)
nombre_directorio = os.path.dirname(... |
e27e7512250a6d5fd5ed7227cd906f14833a9806 | Nazar961/OG19PythonShostak | /Porahyi.py | 189 | 3.65625 | 4 | def porahyi(a):
p = 0
while a > 0 :
l = a % 10
p += l
a //= 10
else:
print(p)
a = int(input("Введіть значення a = "))
porahyi(a) |
2e326ea00a11530d9191ec8853e9bda6bcedb786 | arjunth2001/Brick-Breaker | /Game_Object.py | 1,665 | 3.71875 | 4 | from config import SCREEN_HEIGHT, SCREEN_WIDTH
class Game_object:
''' The generalisation of a Game Object. Base class for all objects in the game'''
def __init__(self, x, y, xlength, ylength, xv, yv, __array, __color):
self.x = x
self.y = y
self.xv = xv
self.yv = yv
s... |
b6af90d3c7e7f5b6af9e2b2e6d660f1eef5f2029 | IvanAlexandrov/HackBulgaria-Tasks | /week_0/1-Python-simple-problem-set/sum_of_digits.py | 293 | 3.84375 | 4 | import math
def sum_of_digits(n):
n = abs(n)
n = str(n)
result = 0
for number in n:
result += int(number)
return result
def main():
tests = [1325132435356, 123, 6, -10, -33, -4213, 87429510488]
for number in tests:
print(sum_of_digits(number))
if __name__ == "__main__":
main() |
26ea2b39ec225973ff5a8243cdf6945a14885717 | nmyraz/sa-trending-topics-pandemic | /translate-eng.py | 1,108 | 3.515625 | 4 | import pandas as pd
import numpy as np
import re
import csv
import time
from googletrans import Translator
if __name__ == "__main__":
#set filename for input and output
fileName = "dataset-7"
input = f"{fileName}.csv"
output = f"{fileName}-translated.csv"
# Read csv file into a pandas dataframe
... |
a512d62884a07dd404bfbffb7821c32df45e7d61 | KatyaKalache/holbertonschool-machine_learning | /supervised_learning/0x02-tensorflow/3-calculate_accuracy.py | 336 | 3.5 | 4 | #!/usr/bin/env python3
"""
Calculates the accuracy of a prediction
"""
import tensorflow as tf
def calculate_accuracy(y, y_pred):
"""
Returns a tensor containing the decimal accuracy
"""
pred = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(pred, tf.float32))
... |
47c25bd584a51fd3aa9af74dcad9e6f0f44c011e | cobalt-cho/Pythonstudy | /basic/gcd.py | 305 | 3.859375 | 4 | '''
최대공약수 구하기(유클리드)
이해가 안되서 그냥 외웠다.
'''
x = int(input("정수 입력(큰 수)"))
y = int(input("정수 입력(작은 수)"))
while(y!=0):
r = x%y
x,y = y,r # python은 swap과정을 이런 방법으로 쉽게 가능.
print("최대 공약수 :" ,x)
|
66244e1335ec859d77987bb04ebebfaeb04f6c80 | Bhoomika-KB/Python-Programming | /listrev.py | 134 | 3.625 | 4 | # -*- coding: utf-8 -*-
#List1=[1,2,3,4,5,6,7,8,9], reverse the list in single line code
list1=[1,2,3,4,5,6,7,8,9]
list1[::-1 ] |
ceecb0c8e40014a1b4d53087ba50d4a088d06d78 | Utsav-Raut/python_tutorials | /python_basics/dictionaries-5.py | 2,300 | 4.6875 | 5 | #Dictionaries allow us to work with key-value pairs. They are like maps of Java
#Keys can be any immutable data-types
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
# print(student)
# print(student['name'])
# print(student['courses'])
# print(student['phone']) # This throws a key error
#Instea... |
1ab4df9fc4029fdb27ec8875cdc9c2a9df4ba725 | Niveshpai/University_Login_System | /student.py | 1,236 | 3.953125 | 4 | class Student:
# Using a global base for all the available courses
numReg = []
# We will initalise the student class
def __init__(self, number, name, family, courses=None):
if courses is None:
courses = []
self.number = number
self.numReg.append(self)
... |
030e00a1f590f830088c49d6044f920bd4d02034 | changtingQ/python_leetcode | /sample/28_strStr.py | 1,439 | 3.71875 | 4 | def find_common(str_1, str_2):
index = str_1.find(str_2)
return index
a = find_common("dfasfqrsf", "sf")
print(a)
"--------------------------answer----------------------------"
"----------------思路1。package----------------"
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
... |
60a4bbe6290eb23a55c19966db4979b584e92c8e | flovera1/CrackingTheCodeInterview | /Python/Chapter2Lists/partition.py | 1,150 | 4.15625 | 4 | '''
Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x. If x is contained within the list, the values of x only
need to be after the elments less than x (see below). The partition element x can appear anywhere
in the "right partition"... |
9f3565688c63e93d318faac5054ca16766dc6a6c | Tclack88/Scientific-Computing-Projects | /Intermediate/VdayCardAutomation.py | 1,409 | 4.40625 | 4 | #!/usr/bin/python3
with open('classlist.csv') as classlist: # with is necessary for "open as"
# function to work. It has the
# additional benefit of # automatically closing the file
for line in classlist: # 1
student = line.split(',') # 2
last_na... |
e631881bf71d7cf63ffa4ba246e2fb3a5874fd3b | karthikljc/Codility | /Iterations.py | 261 | 3.875 | 4 | print("### For Loop ###")
anime_arr = ["Code Geass","Cowboy Bebop","Naruto","Blood+","GIS"]
for anime in anime_arr :
print(anime)
print("\n")
print("### For Using Indexes ###")
for i in range(len(anime_arr)) :
print("i :"+str(i)+" anime:"+anime_arr[i])
|
f8d07cfa5e390a0e388db0217bb3558c93b1a59e | guntupalliramesh/django_pro | /foodwaste/mysite/core/d15.py | 834 | 3.84375 | 4 | import random
def ODDevenSort(array1,arraylength):
sortedArray = 0
while sortedArray == 0:
sortedArray = 1
for a in range(0,arraylength -1,2):
if array1[a]>array1[a + 1]:
array1[a],array1[a + 1] = array1[a+1],array1[a]
sortedArray = 0
for a in... |
5031de88ee20c87df02dea396b28214040a7b918 | rcmccartney/TA_code | /2014F/CSCI141/Wk12/tree_print.py | 3,342 | 4.125 | 4 | """
Recitation: Trees, traversals
"""
from bst import *
def inorder( tree ):
"""
Prints the values in the given list in order
where smaller values (to the left) are printed
first, then this node is printed, then larger
values are printed (by going right)
"""
if tree is not None:
inorder( tree.left )
print... |
f4d5eb100c53520aa55d8c9c59aa89abc3dd2f49 | lalitsshejao/Python_PractiseCode | /SeleniumPython/09_DataDrivenExcel_01.py | 351 | 3.703125 | 4 | import openpyxl
path="C:\DownloadedFiles\Data.xlsx"
workbook=openpyxl.load_workbook(path)
sheet=workbook.active
rows=sheet.max_row
col=sheet.max_column
print(rows)
print(col)
#read Data from Excel
for r in range(1, rows+1):
for c in range(1,col+1):
print(sheet.cell(row=r,column=c).value,end=" ")
p... |
9f61dabaa1eccc101dd5042506ff234d7989b10a | BloodyBrains/PvP_RPG | /buttons.py | 4,463 | 3.703125 | 4 | # buttons.py
import pygame
import camera
import constants
class Button():
def __init__(self, ID, sprite=None, width=0, height=0, pos=(0, 0), text=None):
"""Defines a clickable button.
With no sprite, width and height are used to determine the rect.
If sprite is used without width ... |
bddfb3a913580421d00c05079ad5f552c025cb75 | RenatoMartinsXrd/UriOnlineJudge-Solutions | /Python/A_NivelIniciante/Exercicio_1073.py | 281 | 3.5 | 4 | # -*- coding: cp1252 -*-
# -*- encoding: utf-8 -*-
#url do problema - https://www.urionlinejudge.com.br/judge/pt/problems/view/1073
leia = int(input())
aux = 1
for x in range(leia):
if aux%2==0:
aux3 = aux**2
print("%d^2 = %d" %(aux,aux3))
aux = aux + 1
|
7c6adaf08177c5fd630cdcceaf165a3c08ddf24c | am-ansari/Hackerrank-challenges | /door_mat.py | 912 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Printing a pattern as shown below (Size 7x21)
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
"""
def print_doormat(n,m):
midCol = n//2
pattern = '.|.'
... |
bcb8ca1185e99ae8d36576e8e6d22a4b423698e6 | justinyates887/python-temp-converter | /main.py | 1,745 | 4.09375 | 4 | import sys
def f_conversion():
f = input("Enter your temperature in Farenheit: ")
f_int = int(f)
celsius_conversion = ((f_int - 32) * 5) / 9
c_round = round(celcius_conversion, 2)
kelvin_conversion = f_int + 457.87
print("Your temperature in Fahrenheit is: " + str(f))
print("The conversio... |
29a00e62f2ff644329174c72fbb93e2679489f03 | raghukrishnamoorthy/Python-Cookbook | /01_Data Structures and Algorithms/13_sorting_objects_with_no_native_comparison_support.py | 742 | 3.609375 | 4 | # Sort objects of the same class that does not support
# native comparison
class User():
def __init__(self, user_id):
self.user_id = user_id
def __repr__(self):
return 'User({})'.format(self.user_id)
users = [User(23), User(42), User(31), User(99)]
print(sorted(users, key=lambda u: ... |
da8ffe5c6d8f6c2fc44a4c51e8262b942dc9e4e5 | IgorTelles9/ufrj | /MAE125/main2.py | 8,896 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
this code was the final assignment of my linear algebra class
it's a simple linear regression algorithm with an even simpler classification algorithm. But it works just fine!
"""
import numpy as np
import pandas as pd
def plu (matriz, vetor_w):
size = len(matriz)
for n in range(siz... |
f66d6b86557fe607b17dae20a5e103aa27d3b327 | paulbradshaw/unzip_scraper | /scraper.py | 2,687 | 3.734375 | 4 | import scraperwiki
#yep
#this is used to unzip the files: https://docs.python.org/2/library/zipfile.html
import zipfile
#this is used to temporarily store the file: https://docs.python.org/2/library/tempfile.html
import tempfile
#to open the url
import urllib
#to read the csv files within the zip
import csv
#Here we'v... |
ae492af8869f64782fb8431e39b8f681e4cf1e81 | yvlian/algorithm | /python/设计模式/工厂模式.py | 3,275 | 4.125 | 4 | '''
工厂模式分为:
简单工厂模式(并不在23中模式之中),工厂方法模式以及抽象工厂模式,
其中我们通常所说的工厂模式指的是工厂方法模式,工厂方法模式是日常开发中使用频率最高的一种设计模式。
'''
class Triangle2D(object):
def __init__(self):
print('Triangle_2D')
def __repr__(self):
print('Triangle_2D')
class Circle2D(object):
def __init__(self):
print('Circle_2D')
def __r... |
a08a7e3727cad73cd4de211858ea39e13b24f524 | csco90/python_school | /lottery.py | 341 | 3.59375 | 4 |
import random
def main():
number_list=[0,0,0,0,0,0,0]
for i in range(len(number_list)):
number_list[i]=random.randint(0,9)
for i in range(len(number_list)):
if i!=len(number_list)-1:
print(number_list[i],end='-')
else:
print(number_list[i], en... |
305c8188c619df8385b511fc64058fe2256b779d | morphzeus83/alc_calc | /tests.py | 613 | 3.859375 | 4 | Name = input("Wie heißt du? ")
Alter = int(input("Wie alt bist du? "))
while True:
Geschlechtsabfrage = input("Bitte gebe dein Geschlecht ein (w/m): ")
Geschlecht = {"w" : "weiblich", "m" : "männlich"}
if Geschlechtsabfrage in Geschlecht:
break
print("Falsche Eingabe! Bit... |
1cf00a7e79ca45ef070ba5f6c1dd022ef9e17d0f | gbrandt555/techdegree-project-2 | /app.py | 2,457 | 3.53125 | 4 | import constants
import copy
teams = copy.deepcopy(constants.TEAMS)
players = copy.deepcopy(constants.PLAYERS)
panthers = players[:6]
bandits = players[6:12]
warriors = players[12:]
def main_menu():
print("***Basketball Team Stats Tool***\n\n")
print(".....Main Menu.....\n\n")
print("1. Disp... |
ff5fe02dfcff7a25b3ea0edf7dea72963e3c4498 | BroshkovD/python-algorithms | /searching_algorithms/email_search_example.py | 1,435 | 3.5 | 4 | from random import choice
from string import ascii_letters
from time import time
from bisection_iter import bisection_iter
print(bisection_iter)
##### functions to generate lists of random emails ####
def generate_name(length_of_name):
return ''.join(choice(ascii_letters) for i in range(length_of_name))
def get_dom... |
56546eff2851a5f2bef58a3a9698d2ad1811f281 | gabriellaec/desoft-analise-exercicios | /backup/user_085/ch21_2020_03_12_19_46_07_080884.py | 236 | 3.78125 | 4 | d = int(input('Digite a quantidade de dias: '))
h = int(input('Digite a quantidade de horas: '))
m = int(input('Digite a quantidade de minutos: '))
s = int(input('Digite a quantidade de segundos: '))
print(s + (m*60)+(h*3600)+(d*86400)) |
6e3e64a7aa692aff97e3b623bf721bbd6842053f | prasoonsoni/Python-Questions-1st-Semester | /Dictionary/how to change values.py | 114 | 3.671875 | 4 | d = {1:"cse1001",2:"cse1002",3:"cse1003"}
d[1]="cse1004"
print(d[1])
print(d.get(1)) # to access particular value
|
d61f59a0d61cb241054e56eb8acaa660b68c1754 | magnoazneto/IFPI_Algoritmos | /Fabio06_strings/Fabio06_06_algarismo_extenso.py | 791 | 3.859375 | 4 | from string_tools import number_check
def main():
string = input()
count = 0
while count < len(string):
if number_check(string[count]):
print(number_filter(string[count]), end='')
else:
print(string[count], end='')
count += 1
print()
def number_filter(nu... |
c76b364cdbe929b154048be6ac62ff9f9bb7bd80 | deaz/hackerrank | /cracking-the-coding-interview/02_making_anagrams.py | 300 | 3.703125 | 4 | # https://www.hackerrank.com/challenges/ctci-making-anagrams
from collections import Counter
def number_needed(a, b):
c1 = Counter(a)
c2 = Counter(b)
res = (c1 - c2) + (c2 - c1)
return len(list(res.elements()))
a = input().strip()
b = input().strip()
print(number_needed(a, b))
|
047d38c08f2582bd1aad17bf665d57d2afca286a | Duman001/Yessimov-D | /Неделя 3/solution9.py | 277 | 3.765625 | 4 | from math import sqrt
partial_sum = 0
partial_sum_squares = 0
x_i = int(input())
n = 0
while x_i != 0:
n += 1
partial_sum += x_i
partial_sum_squares += x_i ** 2
x_i = int(input())
print(sqrt((partial_sum_squares - partial_sum ** 2 / n) / (n - 1)))
|
8a89b1728fcc5863ccbc7ba25a545f607007a1d5 | snailQQ/lxf_python | /6_4decorator.py | 945 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。
# >>> def now():
# ... print('2015-3-25')
# ...
# >>> f = now
# >>> f()
# 2015-3-25
# def now():
# print('2015-3-25')
# f = now
# f()
# print(now.__name__)
# print(f.__name__)
# 现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.