blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f2b49603b7d73397bfea44963877660e6ba6b32c | gerffson/design-patterns-python | /adapter/object_adapter.py | 1,003 | 3.515625 | 4 | class ObjectAdapter():
"""
This is the Adapter class: it implements the target interface that is expected
by the clients and is composed of an Adaptee object instance. In this case,
adaptation is achieved through composition. Please notice that, as Python
is dinamically typed, it makes no sense to... |
3b0294c499e934ac3f9c8ea834484fa6f63461d7 | davidmcglashan/advent-of-code-2020 | /day 6.py | 1,177 | 3.625 | 4 | partOneTotal = 0
partTwoTotal = 0
with open('day 6 input.txt') as f:
lines = f.readlines()
partOneGroup = set()
partTwoGroup = set()
first = True
for line in lines:
line = line.strip()
# a blank line is a new set. Add the group total to the major part One Total
if ( len( l... |
899e033fb380e35de6bc47b4328d33c15f0fde73 | cenwachukwu/pythonCLIProject | /notes.py | 8,386 | 3.75 | 4 | #first after creating your directory and your file is to run {pipenv install peewee then pipenv install psycopg2-binary} to install peewee in your file
#importing peewee
from peewee import *
from datetime import date
#Using the PostgresqlDatabase class to create a database connection,
#passing in the name of the dat... |
46dc3ff1eb130cdf2ab1d64abc3d291f88b67d9d | Chiva-Zhao/pproject | /201909/20190910/matplotlib_viz.py | 5,635 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
# sample plot
x = np.linspace(-10, 10, 50)
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Curve using matplotlib')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()
# figure
plt.figure(1)
plt.plo... |
b04e7e104e4a865919126af2c51f998f457934de | BrianBORV/Tesis | /Drive/vista.py | 6,737 | 3.671875 | 4 | from tkinter import *
from tkinter import ttk
import quickstart
# La clase 'Aplicacion' ha crecido. En el ejemplo se incluyen
# nuevos widgets en el método constructor __init__(): Uno de
# ellos es el botón 'Info' que cuando sea presionado llamará
# al método 'verinfo' para mostrar información en el otro
# ... |
462627812b44018fae34bf356779f96dcc387dba | shaversj/100-days-of-code | /days/44/cp.py | 727 | 3.65625 | 4 | import shutil
import argparse
def copy(src, dst):
"""Copies a file or folder from source to destination."""
try:
shutil.copyfile(src, dst)
# shutil.copyfile will throw an IsADirectoryError if src is a directory instead of a file.
except IsADirectoryError:
shutil.copytree(src, dst)
... |
135f030d65a54c87aeed6c71db125e2306b6854a | giahieu01/giahieu01 | /b8c5.py | 460 | 3.953125 | 4 | def Sequential_Search(arr, n, x):
for i in range(n):
if (arr[i] == x):
return i
return -1
arr=[]
n =int(input('Co bao nhieu item: '))
for k in range(n):
item=input('Nhap item: ')
arr.append(item)
x =input('Nhap vao item can tim: ')
n= len(arr)
result = Sequential_Search... |
7b21cbed746633114aec027fb229031ce8d8f52f | syurskyi/Python_Topics | /125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-161-count-files-and-directories.py | 1,606 | 4.375 | 4 | """
Complete count_dirs_and_files traversing the passed in directory path.
Return a tuple of (number_of_directories, number_of_files)
Let's use the tree command to show an example:
$ mkdir -p project/a/1/I project/a/1/II project/a/2 project/b/1/I
tree project/
project/
├── a
│ ├── 1
│ │ ├── I
│ │ └── II
│ ... |
754bc94b52ff09719cdd0f474a38df6236d11247 | talkycape/PythonChallenge | /challenge0/challenge0.py | 523 | 3.75 | 4 | import webbrowser
print("hello world")
solution = 2**38
target_url = 'http://www.pythonchallenge.com/pc/def/%s.html' % solution
print("The value of 2**38 is: " + str(solution))
print("The target URL is therefore: %s" % target_url)
# If new is 0, the url is opened in the same browser window if possible.
# If new is 1,... |
6a7f403551b1283d7234ed8f92834c7194753b1a | smile921/hak_blog | /code/dato-code-userguide/how-to/word_frequency.py | 1,503 | 3.59375 | 4 | import graphlab as gl
def get_word_frequency(docs):
"""
Returns the frequency of occurrence of words in an SArray of documents
Args:
docs: An SArray (of dtype str) of documents
Returns:
An SFrame with the following columns:
'word' : Word used
'count' : Number of times the word occure... |
8df47a922a83fcedcc6083e9323aa93dc3887503 | FluffyKod/gameOfLife | /game_of_life_starter.py | 4,282 | 4.09375 | 4 | #!/usr/bin/env python3
import time
import os
import random
import sys
###################################
# HELPER FUNCTIONS
###################################
def clear_console():
"""
Clears the console using a system command based on the user's operating system.
"""
if sys.platform.startswith('w... |
f9c7aa8e19d538c4cd2d40bf7d883b8282b31b15 | AxelThevenot/Logistic_Regression | /algorithm/logistic_regression.py | 7,976 | 3.65625 | 4 | import csv # to deal with .csv file
import numpy as np # to deal with array and matrix calculation easily
import matplotlib.pyplot as plt # to plot
import matplotlib.animation as animation # to animate the plot
from mpl_toolkits.mplot3d import Axes3D # for 3D plot
import matplotlib.patches as mpatches # to a... |
cdfddeb686c6d61fb879230095bd612cd457c774 | poojakancherla/Problem-Solving | /Leetcode Problem Solving/DataStructures/Strings/438-find-all-anagrams-in-a-string.py | 1,599 | 3.625 | 4 | # https://leetcode.com/problems/find-all-anagrams-in-a-string/
from collections import deque
from collections import Counter
def findAllNeedles(hayStack, needle):
def delFromCounter(i):
dq[hayStack[i]] -= 1
if dq[hayStack[i]] == 0: del dq[hayStack[i]]
def addToCounter(i):
dq[hayStack[i... |
dec21d8b21dc06a286841442752191bd7bdf53fe | AlejandroQR23/pong | /main.py | 1,276 | 3.6875 | 4 |
from turtle import Screen
from paddle import Paddle
from scoreboard import Scoreboard
from ball import Ball
import time
# * Screen
screen = Screen()
screen.setup( width=800, height=600 )
screen.title( "Pong" )
screen.bgcolor( "black" )
screen.tracer( 0 )
# * Scoreboard
scoreboard = Scoreboard()
# * Ball
ball = Bal... |
87d72cf503e730caf97c173a6987658fd03c0074 | iramshiv/ase_scraper | /src/main/python/duration_check.py | 339 | 3.84375 | 4 | def duration_check(duration_value):
number_duration = int(duration_value)
while number_duration > 2 or number_duration < 1:
print("Enter Job posted duration: (0-Default, 1- newer than 24 hours, 2- newer than 7 days)")
duration_value = input()
number_duration = int(duration_value)
ret... |
4e80d38220902473aba2fb523c039d4cf15f36f0 | Nutlope/algorithms | /Problems/Strings/reverse_vowels.py | 803 | 3.890625 | 4 | '''
Leetcode problem 557: Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
'''
def reverseVowels(s: str) -> str:
# O(N) time, O(N) space
# Use a set for because checking if an element is in a set is O(1) on ave... |
94ffc44d49bfd56e5080fa35385762a833d2a736 | nguyntony/class | /small_exercises/small_sequences/5.py | 108 | 3.734375 | 4 | num_list = [-5, -4, -3, -2, -1, 0, 1, 10]
for number in num_list:
if number > 0:
print(number)
|
d4ad9cd64e06a95e4b9fbd1f561138de81e82f5f | msckat11/python-challenge | /PyBank/main.py | 4,028 | 3.953125 | 4 | # Import libraries
import os
import csv
#Tell it where to get the csv file
file_path = os.path.join("Resources", "budget_data.csv")
#Create variables to count months and net profit loss later
total_months = 0
net_profit_loss = 0
#Create empty lists and dictionaries to fill later
months = []
raw_pl_list = []
pl_list1... |
ea3a0799aab160429524881f76eeb7819d2d4c1d | Orodef/Python | /Reverse.py | 367 | 4.3125 | 4 | text = ''
def reverse(text):
total = []
for i in range(len(text)-1,-1,-1):
# '-1' meanings in order: len-1, until -1 and step -1
total.append(text[i])
return "".join(total)
print("Welcome to the reverse program")
text = input("Enter the word you want to reverse: ")
reverse(text)
... |
3fdd830f6307a7c5a357b5fa517a0eebeb0cbde3 | Iansdfg/9chap | /5Two pointers/521. Remove Duplicate Numbers in Array.py | 515 | 3.65625 | 4 | class Solution:
"""
@param nums: an array of integers
@return: the number of unique integers
"""
def deduplication(self, nums):
# write your code here
left, right = 0, len(nums) - 1
visited = set()
while left <= right:
if nums[left] not in visited:
... |
308bfd8f6793e70b7939d043a172fd02b75b5bd8 | dikspr/homeworks | /homework5/mod2.py | 647 | 3.984375 | 4 | # 2: Создайте модуль.
# В нем создайте функцию, которая принимает список и возвращает из него случайный элемент.
# Если список пустой функция должна вернуть None.
# Проверьте работу функций в этом же модуле.
# Примечание: Список для проверки введите вручную. Или возьмите этот: [1, 2, 3, 4]
import random
def rand_el(... |
445ff3303ba592ecd82bbfe416b417e28929284c | dbzahariev/Python-Fundamentals | /lec_01_python_intro_functions_debugging/01_functions_and_debugging/08_multiply_evens_by_odds.py | 314 | 4.1875 | 4 | numbers = input()
def printing():
sum_odd = 0
sum_even = 0
for later in numbers:
if later != '-':
number = int(later)
if number % 2 == 1:
sum_odd += number
else:
sum_even += number
print(sum_odd * sum_even)
printing()
|
c438e1b2aa27a8383d25645c1ca167ff0a19784b | mayankp158/Machine-Learning-and-Artificial-Intelligence | /MLAIPractical12.py | 922 | 3.625 | 4 | import numpy as np
arr = np.array( [11, 22, 33, 0. ,44, 55] )#one float value will covert other in float in output
print( "arr.sum() = ", arr.sum() )
print( "arr.std() = ", arr.std() )
print( "arr.mean() = ", arr.mean() )
print( "arr.max() = ", arr.max() )
print( "arr.min() = ", arr.min() )
print( "arr.size : = ... |
8298cc9ae110c032ce884c2c764c9cbdaa3a2872 | sjd-2020-gy/sjd-5003-2-gy | /neighbourhood.py | 12,813 | 3.65625 | 4 | '''
Neighbourhood Data Object
Purpose:
- Creates a 3 x 3 cell instance from the terrain
Filename:
- neighbourhood.py
Input:
- Terrain surface Raster data (excluding headers)
- Terrain resolution / cell size
- Terrain processing cell row number
- Terrain processing cell column number
... |
9290087a2c36ac9563a01857245c9be22e41912f | oscarjibo/project-ux-identificador-analisis-qra | /algoritmo.py | 3,516 | 3.78125 | 4 | # arrancamo
import listas.py
import fun
# numero de instalacion
numero_instalaciones=int(input())
instalacion=[]
tipo_instalaciones=[]
numero_sustancias=[]
tipo_sustancia=[]
tipo_sus_t_i_e=[]
cantidad_sustancia=[]
condiciones=[]
o1=[]
o2=[]
o3=[]
g=[]
d=[]
A_sus=[]
num_dis=[]
distancias_s=[]
... |
b7305367b256472f6418731aefbda47e41eda612 | IvanWoo/coding-interview-questions | /puzzles/unique_morse_code_words.py | 2,038 | 4 | 4 | # https://leetcode.com/problems/unique-morse-code-words/
"""
International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
'a' maps to ".-",
'b' maps to "-...",
'c' maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the Englis... |
ad8bf6d2f51d2c0fa038bd16f1354668fd60d6e5 | steamedbunss/LEARN-PYTHON-THE-HARD-WAY | /05.py | 1,266 | 4.34375 | 4 | my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = "Blue"
my_teeth = "White"
my_hair = "Brown"
print("Let's talk about %s." % my_name)
print("He's %d inches tall." % my_height)
print("He's %d pounds heavy." % my_weight)
print("Actually that's not too heavy.")
print(... |
5be54578c502bfe9d4ebbe593f09c2ef9f4f6691 | gil-log/GilPyBrain | /baekjoon/stepseven/string_repeat.py | 309 | 3.53125 | 4 | # https://www.acmicpc.net/problem/2675
test_case_number = int(input())
for i in range(test_case_number):
R, S = input().split()
R = int(R)
P = ''
length = len(S)
for index in range(length):
letter = S[index]
for repeat in range(R):
P = P + letter
print(P) |
c01522cc690254a0695aaa184f7db3a5802fd7e8 | kanuos/python-programs | /Basic Program/CompoundInterest.py | 531 | 3.921875 | 4 | # Python Program for compound interest
def calculate_compound_interest(p,t,r,n):
r = r/100
amount = p * (1+r/n)**(n*t)
return amount
print('-'*50)
principal = float(input('Enter the principal : '))
time = int(input('Enter the time period : '))
rate = float(input('Enter the rate of interest : '))
compoun... |
b9bb04f867fb279f24714ba655967765453638e7 | Cuits-spec/testRepo | /Browser_driver/3-coad/test_09_pytest-参数化.py | 947 | 3.625 | 4 | # 如何编写一个pytest的测试类?
import pytest
# 定义被测试的函数
from parameterized import parameterized
def divide(x, y):
a = x / y
return a
# 1.定义pytest的测试类
class TestDivide:
# 2.定义测试方法
# 测试个数位的除法
def test_pp_001(self):
a = divide(2, 2)
assert a == 1
# 测试多位数的除法
def test_pp_002(se... |
e545f33782c9dcc2b27792524c9875948552ee1a | dlm95/Highlight-Portfolio | /Academic Highlight/CSC 3340 Programming Languages/lab5.py | 494 | 3.578125 | 4 | import math
import socket
while True:
p = float(input('Enter Original Investment \n'))
if p > 0:
break
print (p)
while True:
r = float(input('Enter Annual Interest Rate \n')) / 100
if r >= 0:
break
print (r)
while True:
n = int(input('Enter years \n'))
... |
a9f15805e833ac78e2f082eebb3745d66c69f5f5 | SowmicaML/Cryptography | /Caesar cipher/caesar.py | 1,077 | 4.375 | 4 | #python program to implement caesar cipher
import sys
#encrypt func
def encrypt(str,shift):
res=""
for char in str:
if(char == ' '):
continue
if(char.isupper()):
res += chr(((ord(char)+shift-65)%26)+65)
else:
res += chr(((ord(char)+shift-97)... |
6e9b9f1c6d8a5ea8e3894b22c73c8c5acda2e717 | ljrky/functional_program | /src/immutable.py | 213 | 3.734375 | 4 | a = 0
b = 0
def increment_mutable():
global a
a += 1
return a
def increment_immutable(b):
return b + 1
print a
print increment_mutable()
print a
print b
print increment_immutable(b)
print b
|
fbdb74171f5d1a1309d037b7f4bdb9c7784011a1 | yq-12/ml | /Logistic/Logistic.py | 2,800 | 3.640625 | 4 | # logistic
# 数据集来自《机器学习实战》
from matplotlib import pyplot as plt
import numpy as np
#读取数据
def readData():
filename = "testSet.txt"
ifile = open(filename)
lines = ifile.readlines()
trainDataSet = []
trainLabel = []
for line in lines:
line = line.split('\n')[0]
lineList = line.spl... |
a38e30bad8ca940f381cf5bed9c2627c4c2b3d75 | ItzMystic/school-projects | /Turtle game. | 1,211 | 3.984375 | 4 | #!/bin/python3
import time
from turtle import *
from random import randint
speed(0)
penup()
goto(-140, 140)
for step in range (15):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(20)
ada = Turtle()
ada.color('red')
ada.shape('turtle')
... |
cb33a7b8fbcdd9e8cc0a54ef7ef233e5235c2988 | dyb-py/pk | /com/baizhi/杜亚博作业/计时器.py | 948 | 3.78125 | 4 | import time
class TimeJ():
start=''
end=''
def start(self):
print('开始计时')
self.start=time.localtime()
def end(self):
if self.start:
print('结束计时')
self.end=time.localtime()
else:
print('未开始计时')
def jiShi(self):
if self.start... |
73fe83f4681119f752e71f19ea8e30ea2de2ab68 | junyanyao/LC_solutions | /_3_LongestSubstringWithoutRepeatingChar.py | 2,298 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 17:01:15 2021
@author: YaoJunyan
"""
# 3 longest substring without repeating characters
#解法1:单指针: window是滑窗内字符的集合,初始化为空。从前向后移动滑窗,同时更新当前子串长度cur_len和最长子串长度max_len。当滑窗右端移动到字符ch:
#如果ch已存在window中,那么从滑窗的左端起删除字符,直到删除ch。每删除一个字符cur_len减1。
#将ch添加到window中,... |
5c1d1d931d456b0622ec9fc9db3dc9a1601d667f | KATO-Hiro/AtCoder | /ABC/abc001-abc050/abc043/b.py | 359 | 3.5 | 4 | '''input
0BB1
1
01B0
00
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem B
if __name__ == '__main__':
s = input()
result = ''
for si in s:
if si == '0' or si == '1':
result += si
elif si == 'B':
if len(result) != 0:
result = resul... |
b3b6681536fad51b9a3c0c1629d16b95e5ad0a72 | 1fabrism/Daily-Programmer | /[Easy] UPC check digits/checkdigits.py | 878 | 3.953125 | 4 | #!usr/bin/env
#TODO:
# sanitize user input
def check12():
#step 1
str_number = raw_input("Enter an 11 digit number: ")
while (len(str_number) < 11): #If input is less than 11 digits, pad with leading zeroes
str_number = "0"+str_number
even_digits = [int(str_number[i]) fo... |
6c63b740793d2a4b27d5a546149a19a17f23f5cd | olivcmoi/euler | /euler028.py | 781 | 3.890625 | 4 | # -*- coding: utf-8 -*-
#Number spiral diagonals
#Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
#21 22 23 24 25
#20 7 8 9 10
#19 6 1 2 11
#18 5 4 3 12
#17 16 15 14 13
#It can be verified that the sum of the numbers on the diagonals is ... |
0d51d8e62b41361e89a1cc3edacbceedf65a743f | hartikainen/euler | /380_amazing_mazes.py | 295 | 3.8125 | 4 | def amazing_mazes(m, n):
data = [[[0,0,0,0] for x in xrange(n)] for y in xrange(m)]
for x in xrange(0, n):
pass
print(amazing_mazes(2, 3))
def jiiri(x_0, y_0, column):
x, y = x_0, y_0
for i in xrange(2, column+1):
x, y = 2*x + 2*y, x + y
return x, y
print jiiri(2, 3, 3)
|
1c323c88e96d9ff92826c62ed01aca867bb799ec | Vik81/algorithm | /lesson_5/Task_2.py | 2,407 | 3.53125 | 4 | # Написать программу сложения и умножения двух шестнадцатеричных чисел. При этом каждое число представляется
# как массив, элементы которого это цифры числа. Например, пользователь ввёл A2 и C4F.
# Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.
# Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение ... |
c0dc9b079c3b10ea103a92244cb2e6b65b88dc18 | student-103653193/ICTPRG-Python | /Week 3/2strings.py | 128 | 3.953125 | 4 | string1= "Rela238#"
password =str(input("Enter the password "))
if password == string1:
print ('yes')
else:
print ('no') |
973e89bbfdb77eac8cd1072d8de6adfed2cd0c81 | hiagoleite93/exercicios | /aula6.py | 676 | 3.921875 | 4 | """
Iniciar com letra, pode conter numeros, separar _, letras minúsculas
"""
import math
nome = 'Luiz Otávio'
idade = 32
altura = 1.80
peso = 75
e_maior = idade > 18
imc = peso/(math.pow(altura, 2))
imc_1 = (f'{imc:.2f}')
print('Nome: ', nome)
print('Idade: ', idade)
print('Altura: ', altura)
print('É maior de idade... |
89e3058b2ac71809b033ec11c78877d3a2bb9e0f | hanrick2000/LaoJi | /Leetcode/0721.py | 1,589 | 3.75 | 4 |
# 721. Accounts Merge
'''
Basic idea:
Union Find
1. Save unique email to username dictionary
2. union all emails under same username
3. get all emails under same root
Time O(n) (Amortized) where n is the number of total emails
'''
class UnionFind:
def __init__(self, email_username):
self.p =... |
27fe2d41e9a027f815bce85d1701e466141e81d0 | AngryBird3/gotta_code | /leetcode_oj/surrounded_region3.py | 1,622 | 3.859375 | 4 | '''
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
'''
import collections
clas... |
14b0b5eb568a3d64d9856468c8d68a707e68ef33 | kmtheobald/project_euler | /80-89/80.py | 584 | 3.640625 | 4 | # For the first one hundred natural numbers, find the total of the digital sums
# of the first one hundred decimal digits for all the irrational square roots.
import decimal
from math import sqrt
decimal.getcontext().prec = 105 # safely above 100 to avoid rounding errors
digital_sum = 0
for i in range(1, 101):
ro... |
5d849d42860e51071232284dbd1f9d9516410655 | wojtez/ThePythonWorkbook | /004.AreaOfField.py | 457 | 4.34375 | 4 | # Create a program that reads the length and width of a farmer’s field
# from the user in feet. Display the area of the field in acres.
# Hint: There are 43,560 square feet in an acre.
width = float(input('What is the width of the field in feet: '))
length = float(input('What is the length of the field in feet: '))
... |
6d80a49e40b9566ef1a15df8ce3b339d0b7415c6 | FacundoAcevedo/tp3 | /modulos/tad.py | 3,655 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tad.py
#version 0.1
"""Modulo. Contiene los tipos abstractos de datos a usar
en el programa"""
class Pila(object):
"""Clase pila"""
def __init__(self):
"""Constructor"""
self.items = []
self.largo = 0
def __str__(self):
... |
1f0c00866cc0eca8087a7bb89e8c093bebd1113e | BhagyashreeKarale/request | /5ThodisiProgramming.py | 1,328 | 3.65625 | 4 | # Thodi si Programming!
# What we have done so far
# requests use kar ke courses download kar liye
# aur user ko aapne ek list of courses bhi dikha di
# Aage kya karna hai?
# user koi bhi ek course select karega iske liye user,
# uss course ke saamne likha hua number input karega
# agar aap dhyaan se dekhenge toh, yeh... |
0332c2f5563fb2ab2578841273eaf9a7b143411b | irfanahamed69/python | /Day1/exercise1.py | 140 | 3.765625 | 4 | names = ["john", "jake", "jack", "george", "jenny", "jason"]
for name in names:
if len(name) < 5 and 'e' not in name:
print(name) |
b0db2f98bc4e77b552cee0342b382de8d7171ece | GintasBu/python-code | /openbookproject_thinkcs_python/ch21_tree.py | 1,892 | 3.546875 | 4 | class Tree():
def __init__(self, cargo, left=None, right=None):
self.cargo=cargo
self.right=right
self.left=left
def __str__(self):
return str(self.cargo)
def total(tree):
if (tree)==None: return 0
return total(tree.left)+total(tree.right)+tree.... |
5a28477169c4a081dd1a78ab6a2afe8d87376295 | Qiong/ycyc | /pchallengecom/chain.py | 1,227 | 3.578125 | 4 | #follow the link
#http://www.pythonchallenge.com/pc/def/linkedlist.php
# http://www.pythonchallenge.com/pc/def/peak.html
#http://wiki.pythonchallenge.com/index.php?title=Level4:Main_Page
"""
<!-- urllib may help. DON'T TRY ALL NOTHINGS, since it will never
end. 400 times is more than enough. -->
<center>
<a href="lin... |
37aa65bd55ab8c2309a869a61f1c0766a4690c53 | whiteavian/hkrnk | /median.py | 1,753 | 3.734375 | 4 | from heapq import heappush, heappop
class MedianList:
def __init__(self):
self.min_heap = []
self.max_heap = []
self.median = None
def __repr__(self):
return "Min {}, max {}".format(self.min_heap, self.max_heap)
def add(self, element):
element = float(element)
... |
3b0b8161abc02dcd9a68dcafbe0405fc3e364ddc | SanGlebovskii/lesson_5 | /homework_5_4.py | 164 | 3.8125 | 4 | n = int(input())
def sum_of_n(number) -> int:
summary = 0
for i in range(1, number + 1):
summary += 1 / i
return summary
print(sum_of_n(n))
|
5f4980e7b213461779bebe0f7feafd57d9c9a87e | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/87/12928/submittedfiles/decimal2bin.py | 135 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=bin(input("digite valor do numero binario:"))
inteiro=int(n)
print(inteiro) |
5327cf91a96bf1b8de03987e42adc7d1c4e21b4f | anildhaker/DailyCodingChallenge | /LeetCode/stockProfitDP.py | 608 | 3.71875 | 4 | # Say you have an array for which the ith element is the price
# of a given stock on day i.
# If you were only permitted to complete at most one transaction (i.e.,
# buy one and sell one share of the stock), design an algorithm to find
# the maximum profit.
# MAx profit using dym=namic programming
def maxProfit(... |
32bd12a885092bf1d6c9c8f4f34d7e7bd4239ea2 | jamesl33/210CT-Course-Work | /task4/part 2/main.py | 1,448 | 4.3125 | 4 | #!/usr/bin/python3
"""main.py: Code to use quick sort to get an input from the user and return that
indexes value from the sorted list
"""
import random
from sorting import quick_sort
def ordinal(num):
"""ordinal: Generate an ordinal number representation of 'num'
:param num: Integer which you want the ordi... |
5340bd5f0dcd8a3789672a5c1074c967e02e144b | vb64/bulls_cows | /source/default/bull_cows.py | 2,299 | 3.859375 | 4 | """Bull&Cows game."""
import sys
import random
PUZZLE_LENGTH = 4
def make_puzzle():
"""Return random string from 4 different digits."""
puzzle = []
while len(puzzle) < PUZZLE_LENGTH:
digit = str(random.choice(range(10)))
if digit not in puzzle: # pragma: no cover
puzzle.appen... |
f7ab51ddc54c8a0b3d4a6bdbfda65f3da03a5b0f | katameszaros/homework | /1.hello/hello.py | 265 | 3.9375 | 4 | import sys
def has_name_argument():
return len(sys.argv)>=2
def get_name_argument():
return sys.argv[1]
def print_hello(name="World"):
print("Hello " + name + "!")
if has_name_argument():
print_hello(get_name_argument())
else:
print_hello()
|
0797bae7b23070403ae5a39e71f343c38b17364d | wherculano/wikiPython | /04_Exercicios_Listas/06-MediaDe4Notas.py | 613 | 3.875 | 4 | """
Faça um Programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno,
imprima o número de alunos com média maior ou igual a 7.0.
"""
medias = []
for a in range(10):
soma = 0
for n in range(4):
nota = float(input(f'{n + 1}ª Nota do {a + 1}º aluno: '))
so... |
0c6ee9533d11bd5c04e321f6a786490aa589525a | ftorresi/PythonLearning | /Unit8/ej8.34.py | 1,432 | 3.546875 | 4 | import numpy # not as np since np is an important variable here
import time, sys
try:
x0 = int(sys.argv[1]) # Initial money
F = int(sys.argv[2]) # Target Fortune
p=float(sys.argv[3]) #Winning probability
except IndexError:
x0= 10
F = 100
p=0.7 #Using p<0.5 takes TOO LONG
def number_of_... |
b8159f969ed72a6aa73d67fb449f6a807c2bc04e | pele98/Object_Oriented_Programming | /OOP/Exercise4/Exercise4_5/cellphone_main.py | 995 | 4.03125 | 4 | # File name: Cellphone_main
# Author: Pekka Lehtola
# Description: Cellphone class main function
from cellphone_class import Cellphone
#List of all cellphone objects
cellphone_object_list = []
def create_cellphones():
global cellphone_object_list
ID = 0
#Ask user how many objects are created
#ID i... |
964e60e3d535766bc01df74e592d4ebbc744f757 | srisrinu1/Coursera | /Python files and dictionaries/week3/assignment-1.3.py | 293 | 4.1875 | 4 | '''
Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument
given, and returns that new string.
'''
def change(string):
return("{}Nice to meet you!".format(string))
if __name__=="__main__":
string=input()
print(change(string))
|
7a95dce1ce60dcc80a9cce866adba18d078036a8 | eldadmwangi/sifu | /design/lru_cache.py | 515 | 3.578125 | 4 | from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.lru = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.lru:
return -1
v = self.lru.pop(key)
self.lru[key] = v
return v
def put... |
4f28e04a784677848d23c7ab0b7b367e3d8a656b | xururuca82/PythonForEveryone | /12B-fact.py | 464 | 3.578125 | 4 | ## 1부터 n까지 곱을 구하는 함수
def factorial(n):
fact = 1 # 곱을 구하기 위한 변수 fact(시작 값을 1로 지정).
for x in range(1,n+1): # range(1,n+1)로 1,2,...n까지 반복합니다(n+1은 제외).
fact = fact*x # 지금까지 계사된 값에 x를 곱해 fact에 다시 저장합니다.
return fact # 계산된 fact 값을 돌려줍니다.
print(factorial(5))
print(factori... |
39a79a8daa28c7b852448e68bf31dbb4799003fc | skriptkoder/dns-resolver | /dns-resolver.py | 6,842 | 3.703125 | 4 | """"
A program that search and store store domain name dns
Domain Name, A Records, MX Records, MX, CNAME, TXT
"""
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter import scrolledtext
import dns.resolver
import whois
import socket
from tkinter import filedialog
def add_spacer():
... |
d39bef736958bf77d7367d746e1ad29abaca0395 | A-Shot/Flask | /flask_7/csvorder.py | 1,247 | 3.609375 | 4 | import csv
def csv_read(file_):
with open(file_, 'rb') as csv_file:
reader = csv.reader(csv_file)
mydict = dict(reader)
return mydict
def csv_write():
with open('dict.csv', 'wb') as csv_file:
writer = csv.writer(csv_file)
for key, value in mydict.items():
writer.writerow([key, value])
def csv_writ... |
da2dc4c6eeeaddeacb6efc5bae48ea7a7557b382 | micy-snoozle/GB_Python | /les6_task3.py | 2,317 | 3.9375 | 4 | # 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты:
# name, surname, position (должность), income (доход).
# Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы:
# оклад и премия, например, {"wage": wage, "bonus": bonus}.
# Создать класс Position (должно... |
51051711dbc5ad004ed1bc521204b4f0a7a3170f | tharlysdias/estudos-python | /aula_3.py | 320 | 4.28125 | 4 | # if elif else
a = 3
b = 2
if a >= b:
print("a é maior ou igual")
else:
print("a é menor")
if a < b:
print("Faça isso")
# else if === elif
elif a > b:
print("Faça aquilo")
# exemplos
if a > b:
print("A")
elif a > c:
print("C")
elif b > c:
print("B")
elif c > b:
print("C")
else:
print("Nada encontrado") |
129536deecde1c2c6a46388062278d0aeafcd52e | MacBruce/lc101 | /chapter10/counting.py | 1,360 | 3.984375 | 4 |
#inp_str = input("Count the amount of time charecters appear in a string! Input string!")
def count_char(str):
#alphabet map
alphabet = {
'a' : 0,
'b' : 0,
'c' : 0,
'd' : 0,
'e' : 0,
'f' : 0,
'g' : 0,
'h' : 0,
'i' : 0,
'j' : 0,... |
30f1b2cfac7c7d15b7e76177eef833828cd64c1c | Shivampanwar/algo-ds | /Dynamic Programming/Alpha code.py | 3,460 | 3.984375 | 4 | '''
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:
Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.”
Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’... |
381aafc92d22a8bf9a42fc31bdab369c3ceaa062 | Pratyush1014/Python | /ControlstrucControlstat/numbers/strong.py | 192 | 3.921875 | 4 | n = input("Enter any number :")
b = n
sum = 0
while n>0 :
d=1
a = n%10
while a>0 :
d = d*a
a-=1
sum = sum + d
n = n/10
if sum == b :
print "its a strong number"
else :
print "not"
|
c9e259d3d1d31fecb15b55420ffa02987f2603a2 | adamtupper/alphablooms | /blooms/BloomsLogic.py | 15,846 | 3.921875 | 4 | """A board class for the game of Blooms.
"""
import copy
from itertools import permutations
import matplotlib.pyplot as plt
import numpy as np
from bidict import bidict
from matplotlib.patches import Patch, RegularPolygon
class Board:
"""A board class for the game of Blooms.
"""
def __init__(self, size=... |
9c605be132b004aa7a411df28303f2094b3b0004 | hyunjun/practice | /Problems/hacker_rank/Algorithm/Strings/20150313_Palindrome_Index/solution2.py | 424 | 3.921875 | 4 | def is_palindrome(s):
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
def palindrome_index(s):
if is_palindrome(s):
return -1
str_len = len(s)
for i in range(str_len):
if is_palindrome(s[:i] + s[i + 1:]):
return i
return 0
if __na... |
c22bfdfc4f43b84b922cbd1f4e930578c4d9fbf5 | yoshimo8/100knock_project | /0-10project/project4.py | 471 | 3.875 | 4 | def word_sort(words):
word_legend = {}
numbers = [1, 5, 6, 7, 8, 9, 15, 16, 19]
word_list = words.split()
for word,i in zip(word_list,range(len(word_list))):
if i in numbers:
word_legend[word[1]] = i
else:
word_legend[word[0:2]] = i
return(word_legend)
word... |
66ba94e2d190f8560945cfd177e40d15aef886b2 | jxy147258/qianfeng_python | /qianfeng_400/多任务/线程/8,凑够一定数量才能一起执行.py | 575 | 3.671875 | 4 | '''
bar = threading.Barrier(2)
凑够2个数量之后才能运行bar.wait()之后的语句,凑不够就一直等
'''
import threading,time
bar = threading.Barrier(2)
def run():
print("%s---开始"%(threading.current_thread().name))
time.sleep(1)
bar.wait()
# 根据开头的说明,一共5个线程,凑够两个才能运行以下语句,所以一定会有一个线程因为凑不够而阻塞
print("%s---结束"%(threading.current_thr... |
94bc21cf75c755167018b8a07258941b7c96e1e3 | DouglasKosvoski/DFA-Generator | /main.py | 1,305 | 3.859375 | 4 | from sys import argv, exit
from Automata import *
from Csv import *
"""
Author: Douglas Kosvoski
Email: douglas.contactpro@gmail.com
Construction of an application to construct, determinate and minify
(eliminate dead and unreachable grammar rules) of finite automata.
This program executes the token load (reserv... |
3584ac548af8a35eaf432af7024a3c3172047374 | SafonovMikhail/python_000577 | /001132StepikITclassPy/Stepik001132ITclassPyсh05p03st01THEORY01_20210216.py | 840 | 4.09375 | 4 | string = "1501"
print(string.isdigit())
#True
string = "school"
print(string.isdigit())
#False
string = "sch1501"
print(string.isdigit())
#False
string = "15.01"
print(string.isdigit())
#False
string = "-1501"
print(string.isdigit())
#False
# использование функции
def is_digit(string):
if string.isdigit():
... |
134901fe69a7e3ed09fdac7f60116235706fd3d7 | sharifh530/Learn-Python | /Beginner/Data types/5.escape_sequence.py | 284 | 4.25 | 4 | # whatever comes after "\" it will be a string
weather = "Its a \"kind of sunny\" weather "
print(weather)
# whatever comes after "\t" it create a tab space and "\n" creates a new line
weather1 = "\t Its a \"kind of sunny\" weather \n hope you have a good day"
print(weather1)
|
0ceaeaf9d5d7edcdb51804a15d0b1e629c5ef7e7 | luxcem/advent-2019 | /src/utils.py | 1,228 | 3.5 | 4 | from math import sqrt
def fid(x):
return x
def Input(filename, split=str.split, mapt=int):
with open(filename) as fo:
if split:
source = split(fo.read())
else:
source = fo.read()
if mapt:
return list(map(mapt, source))
else:
ret... |
7a19110181b28d387cfc3737e6bbf1d6906686c9 | prashant133/Labwork | /question4.py | 534 | 4.3125 | 4 | '''
4. Given the integer N - the number of minutes that is passed since midnight -
how many hours and minutes are displayed on the 24h digital clock?
The program should print two numbers:
the number of hours (between 0 and 23) and the number of minutes (between 0 and 59).
For example, if N = 150, then 150 minutes hav... |
d3341fba3d94aac16e23ecb3abba35773a33f963 | lowellbander/girlswhocode | /python/mad_libs.py | 1,255 | 3.734375 | 4 | '''
Mad Libs
adapted from the Shel Silverstein poem "Magic" from
"Where the Sidewalk Ends"
Original Poem
Sandra’s seen a leprechaun,
Eddie touched a troll,
Laurie danced with witches once,
Charlie found some goblins’ gold.
Donald heard a mermaid sing,
Susy spied an elf,
But all the magic I have known
I’ve had to make m... |
80d00909fda338ba2df63033f504c29563b95a2a | Nhalzainal/Tugas5 | /Praktikum3latihan1.py | 200 | 3.609375 | 4 | print("Tampilkan n bilangan acak yang lebih kecil dari 0.5")
jumblah = int(input("Masukan jumblah n: "))
import random
for i in range(jumblah):
print("Data ke",i+1 ,"-",(random.uniform(0.1,0.5))) |
daf5115bcd51b72a54a3996e4aa40d521aafa524 | GMwang550146647/network | /0.leetcode/99.有趣问题/acm/fence repair using heap.py | 1,310 | 3.515625 | 4 | #-*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import sklearn
from pandas import DataFrame, Series
import matplotlib.pyplot as plt
class heap(object):
def __init__(self):
self.arr=np.zeros(20)
self.size=0
def push(self,value):
position=self.size
self.si... |
ba8ac2ed813820055e71719ae071205def7a94a7 | pranav-kirsur/megathon2019 | /discourse_connector.py | 595 | 3.609375 | 4 | def discourse_connector(sentence):
connectors = ['because of', 'despite the fact that', 'in spite of', 'however', 'nevertheless', 'despite', 'in addition to', 'although', 'since', 'therefore', 'due to', 'as a result of', 'and', 'but', 'consequently', 'in addition', 'additionally', 'furthermore', 'moreover', 'along... |
dfacb834de3cdbdcc1082248a4dae2096841985b | StevenLdh/PythonActualPractice | /Excption.py | 2,273 | 4 | 4 | #!/usr/bin/env python
# -*- coding:utf8 -*-
'''
# 捕获异常处理
num1 = input("please input a num1:")
num2 = input("please input a num1:")
try:
print(float(num1)/float(num2))
except ZeroDivisionError:
print("error")
finally:
print("over")
assert (float(num2) != 0),'Error!'
print(float(num1)/float(n... |
4d2fea298fe6157fe96ff5e0621071c7345bc736 | zois-tasoulas/algoExpert | /medium/numberOfWaysToMakeChange.py | 503 | 3.9375 | 4 | def number_of_ways_to_make_change(n, denominations):
ways_per_number = dict()
ways_per_number[0] = 1
for ii in range(1, n + 1):
ways_per_number[ii] = 0
for element in denominations:
for ii in range(element, n + 1):
ways_per_number[ii] += ways_per_number[ii - element]
re... |
e1baf2d2b8aacdfe71cf25c979d15b284ac9a0b1 | myth002/CP1404_Practical | /Prac5_2.py | 672 | 4.1875 | 4 | #Pgm to output color codes based on keys using dictionaries
COLOR_NAME={"aliceblue": "#f0f8ff","antiquewhite": "#faebd7","beige": "#f5f5dc","black": "#000000","coral": "#ff7f50","darkgreen": "#006400","darkviolet": "#9400d3","greenyellow": "#adff2f","lavender": "#e6e6fa","magenta": "#ff00ff"}
user_choice = str(input(... |
026333579c68799c18c795b8bd1996b1fa890ff4 | rebecabramos/Course_Exercises | /Week 4/integer_division.py | 477 | 4.3125 | 4 | # Program that prompts the user to enter two integers.
# Then, display the result of dividing the first number by the second number,
# using integer division so that the answer is an integer quotient, and a remainder
value1 = int(input('Enter an integer >'))
value2 = int(input('Enter an integer >'))
division = int(v... |
81092b495c775235a8d97230c2a28f65e58d3138 | TimothySjiang/leetcodepy | /Solution_429.py | 562 | 3.59375 | 4 | """
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root: return []
queue = [root]
ans = []
while queue:
r... |
998f29d674561ff168519a8fe67afe5e6cb82015 | ptamayo4/DojoAssignments | /Python/pythonFun/stars.py | 301 | 3.71875 | 4 | def draw_stars(arr):
for i in range(len(arr)):
if type(arr[i]) is int:
print "*" * arr[i]
elif type(arr[i]) is str:
temp = arr[i]
print temp[0] * len(temp)
x = [4,6,1,3,5,7,25]
y = ["Patrick",2,10,"Richard", "Hello"]
draw_stars(x)
draw_stars(y)
|
0606c869a817c216bb97f500b9ce2314895124c2 | angiegonzalez596/Proyecto1 | /entrada de datos2.py | 306 | 3.859375 | 4 | nombre = input("Ingrese su Nombre")
print("Hola " + nombre + ", Vamos a realizar una suma," )
num_uno = int(input("Por favor ingrese el primer valor: "))
num_dos = int(input("Por favor ingrese el segunto valor: "))
resultado = num_uno + num_dos
print(nombre + " El resultado de la suma es: ", resultado)
|
59c886e2b0a8350f3e63eedf351cc3c4e7d824b1 | felit/python-expirement | /decorator.py | 556 | 3.859375 | 4 | #-*- coding:utf8 -*-
def foo():
print("foo")
foo
print foo()
foo = lambda x: x + 1
print foo(2)
def w1(func=None,hello="world"):
print("添加装饰器:%s%s"%(func,hello))
def inner(*args,**kwargs):
print "from w1"
return func(*args,**kwargs)
return inner
@w1
def f1():
print("f1")
"""
f1 =... |
423114e77ee15c36fbd36a206fb431c07a6eeea5 | pierrce/euler | /one.py | 237 | 3.75 | 4 | #!/usr/bin/python
print('Calculating...')
myList=[]
x=0
for i in range(1, 1000):
if(i%3)==0 or (i%5)==0:
print('Appended...')
myList.append(i)
myList = map(int, myList)
x = sum(myList)
print(x)
|
11f8f6af5140f5b8c7042ccef577b3f43987045f | dudulacerdadl/Curso-Python | /Mundo2/Exercícios/ex062.py | 499 | 3.9375 | 4 | start = int(input('Digite o primeiro número de uma PA: '))
reason = int(input('Digite a razão de uma PA: '))
decimal = start + (10 - 1) * reason
counter = 0
counter2 = 0
terms = 10
print('')
while terms != 0:
while counter < terms:
print(start, end=' -> ')
start += reason
counter += 1
... |
7fd73df6ab94d6443e78636bad0c7e1af2ef124a | RrennM/python_bc_mileage_converter | /mileage_converter.py | 317 | 4.0625 | 4 | print("How many kilometers did you cycle today?")
kms = input()
mile = float(kms) * 0.621371
# kms = str(kms)
# mile = str(mile)
# print("Okay, you said " + kms + " kilometers. That's about " + mile + " miles!")
round_mile = round(mile, 2)
print(f"Okay, you said {kms} kilometers. That's about {round_mile} miles!") |
61e1054c9b4aff6e3c955e7b40963351f5a98cdd | AlterFritz88/pybits | /bite177.py | 2,054 | 3.796875 | 4 | import pandas as pd
import numpy as np
movie_excel_file = "https://bit.ly/2BVUyrO"
def explode(df, lst_cols, fill_value='', preserve_index=False):
"""Helper found on SO to split pipe (|) separted genres into
multiple rows so it becomes easier to group the data -
https://stackoverflow.com/a/40449726... |
1a9e0d0476c1d56ecdae3241ecf901e87d447aec | S-PaveI/tutorial | /MyCoin.py | 658 | 3.96875 | 4 | # Программа для имитации подбрасывания монеты
import random
class Coin:
def __init__(self):
self.__sideup = 'Орел'
def toss(self):
if random.randint(0, 1) == '0':
self.__sideup = 'Орел'
else:
self.__sideup = 'Решка'
def get_sideup(self):
return sel... |
b86f1080f3455d89b905d2ce81c402d0b776b8bb | NEO2756/HackerEarth | /python/max_heap.py | 1,467 | 3.953125 | 4 | from sys import stdin, stdout
tree = [0, 10, 40, 15, 50, 100, 30, 10]
heap = []
def insert(new):
heap.append(new)
idx = len(heap) - 1
while heap[idx//2] != -1:
if heap[idx//2] < heap[idx]:
heap[idx//2], heap[idx] = heap[idx], heap[idx//2]
idx = idx//2
continue
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.