blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4427b63e24065ca9b1d1a6d544f0918cefe422c0 | rakibul7/Basal-Metabolic-Rate-Calculator | /bmr.py | 581 | 3.859375 | 4 | # Basal Metabolic Rate Calculator
weight=int(input("Enter Your Weight in KG: \n"))
height=int(input("Enter Your Height in CM: \n"))
age=int(input("Enter Your Age in years: \n"))
isMale= str(input("Are You Male? (y/n)"))
if isMale == "y":
isMale = True
elif isMale == "n":
isMale = False
else:
print("Error"... |
a194acedb907bda1d8242b81e1dc20c587f2cb76 | KunyiLiu/algorithm_problems | /kunyi/data_structure/data_stream/random_element_from_stream.py | 729 | 3.859375 | 4 | import random
"""
For i = 0, we would've picked uniformly from [0, 0].
For i > 0, before the loop began, any element K in [0, i - 1] had 1 / i chance of being chosen as the random element.
We want K to have 1 / (i + 1) chance of being chosen after the iteration. This is the case since the chance of having being chose... |
08b34265a21795b877f82b1e38ff780f1fb666cb | Lesi-N/Sorting_alg_comparison | /main.py | 965 | 3.84375 | 4 | """
Main module for conducting the sorting algorithms comparison experiment
"""
from generate_list import generate_lists
from timing import *
def main():
"""
Main function
Generates lists and conducts all experiments
:return:
"""
types = ["Random list average", "Ascending list", "Descending l... |
ec4abf5e836239f521aa6ade66a652c019a29c0a | cjyanyi/leetcode | /recursion.py | 2,449 | 3.84375 | 4 | # -*- coding:UTF-8 -*-
def sort_array(arry):
if len(arry)==1:
return arry
else:
next_arry = sort_array(arry[1:])
return __insert(arry[0], next_arry)
def __insert(n,arry):
l =len(arry)
new_arry = []
for i in range(l):
if n>arry[i]:
conti... |
4b7e44924b5a0327539e342bb2411fd7c4a55b33 | thingscouldbeworse/AdventOfCode | /2020/day12/part1.py | 968 | 3.546875 | 4 | directions = []
next_orientation = {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}
next_orientation_L = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
def increment(x, y, direction, magnitude):
if direction == "E":
x = x + magnitude
elif direction == "N":
y = y + magnitude
elif direction == "W":
x = x - magnitud... |
4bed32aa479a7c16f23b5e19ca37fa9116f6ee19 | LinUwUxCat/school-projects | /python/recursive/fibo-ex4.py | 398 | 3.671875 | 4 | import time
def fibo(n):
if n == 1 or n == 2:
return 1
else: return fibo(n-1) + fibo(n-2)
start = time.time()
def fibo_it(i):
a, b, cpt = 0,1,0
while cpt <= i:
if cpt < 2:
c = cpt
else:
c = a+b
a=b
b=c
cpt+=1
return c
... |
c3edc0d71d49473b67f54c7d18aae4fc9e9fa0d5 | NeSergeyNeMihailov436hdsgj/SummerP | /1B/11.py | 817 | 3.796875 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
money = 0
count = 0
while True:
a = input("Years old:")
if str(a) == str("-"):
if count >= 10:
money = money - money * 0.1
... |
32fc3c7c0cce12dda16bb666b32aae05237d9dac | YanTaocheng/Contact_Book | /query_contact.py | 774 | 4.03125 | 4 | # _*_ coding:utf-8 _*_
import re
def query_contact():
name = input('----------------------\nWhich contact you want to query?(deflaut is all):')
with open(r'.\contact.txt', 'r') as f:
contacts = f.readlines()
if name == '':
print('----------------------')
for contact in ... |
01447953497b317f601d0a4f3be85b04e55fa54e | Sergey-Laznenko/Stepik | /Generation Python - A Beginner's Course/5_EXAM/2.py | 526 | 3.875 | 4 | """
Заданы две клетки шахматной доски. Напишите программу, которая определяет имеют ли указанные клетки один цвет или нет.
Если они покрашены в один цвет, то выведите слово «YES», а если в разные цвета — то «NO».
"""
x1, y1 = int(input()), int(input())
x2, y2 = int(input()), int(input())
if (x1 + y1 + x2 + y2) % 2 == ... |
a7c47c80620d1267981abf69cb2bd9bc46f3d5ec | Adricf28/Backup | /Python/Fundamentos/ClasesCurso/sobrecarga_operadores.py | 179 | 4.03125 | 4 | # + es un ejemplo de sobrecarga de operadores
a = 2
b = 3
print(a + b)
str1 = 'Hola '
str2 = 'Mundo '
print(str1 + str2)
lista1 = [1, 2]
lista2 = [4, 5]
print(lista1 + lista2)
|
913d97bc3de5a7c2a656843811722388837d5749 | thecodearrow/100-Days-Of-Code | /No Strings Attached.py | 1,139 | 3.53125 | 4 | #https://www.codechef.com/JULY18B/problems/NSA
#Partially Solved 30 pts
#Reference Counting Inversions
#https://medium.com/@ssbothwell/counting-inversions-with-merge-sort-4d9910dc95f0
import heapq
only={}
only[1]=True
def calculateY(arr):
if len(arr) == 1:
return arr, 0
else:
a = arr[:len... |
e4d38c9a98b988f624d2c1fb85efac7b3f5e6c8d | SpeedSourceLAB/Calculator-PyTestProject | /PyTest_Project/Calculator/tests/test_Calculator_Performance.py | 1,723 | 3.640625 | 4 | from Calculator.Calculator.Calculator import Calculator
"""Use conftest.py while running this test"""
c= Calculator()
def test_add(numbers_csv):
for set in numbers_csv.index:
print(set)
print(numbers_csv['num1'][set], numbers_csv['num2'][set])
result = c.add(numbers_csv['num1'][set], numb... |
317124e60a10ba2aa1d28c96b2179fc6ffb7d549 | baloooo/coding_practice | /climbing_stairs_min_cost.py | 1,500 | 3.90625 | 4 | # coding: utf-8
'''
https://leetcode.com/problems/min-cost-climbing-stairs/discuss/110111/Easy-to-understand-C++-using-DP-with-detailed-explanation
'''
import pytest
class Solution():
def min_cost_climbing_stairs(self, cost):
'''
Time: O(n) Space: O(1)
'''
if len(cost) == 0:
return 0
... |
03640388ed710754822704b9516e99b5684ddfe1 | himynameisfil-website-challenges/Code-Eval-Challenges | /EvenNumbers.py | 454 | 3.953125 | 4 | #status: solved
#problem: https://www.codeeval.com/open_challenges/100/
#Write a program which checks input numbers and determines whether a number is even or not.
#Solution: Even/ odd test is easily done via mod 2 and you can switch even = 0 and odd= 1 to even = 1 and odd = 0 by adding 1 to the number
import sys
test... |
7a2eeda259d1a42171d1f0c8fbb2ba60df62fd17 | alita-moore/ableton | /src/warp.py | 12,660 | 3.65625 | 4 | class Warp():
"""
# Description
The Warp class organizes this program's primary functionality.
Specifically, this is defined as the ability to automatically
adjust tempo (beats / s) as a function of markers. A marker
is defined as given beat and its complimentary seconds marker.
Notably, th... |
628277e414232a7b18a9ea86055d78ff6a474274 | rafaelperazzo/programacao-web | /moodledata/vpl_data/79/usersdata/157/43845/submittedfiles/serie1.py | 152 | 3.53125 | 4 | n=int(input('Informe um valor:'))
s=0
for i in range (1,n+1,1):
if (i%2==1):
s=s+(i/(i**2))
else:
s=s-(i/(i**2))
print('%.5f'%s) |
9047f8eea956219320c2b75dff14933f6859a40f | ashwani311/30-Days-Of-Code | /python/Day-7.py | 204 | 3.5 | 4 | #!/bin/python3
import sys
n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
string = ""
for i in range(n-1,-1,-1):
string += (str(arr[i])+" ")
print(string)
|
5e535ebd554455db150b3ee948ce3ed675601ec3 | williamife/portfolio | /temprature_converter.py | 473 | 4.46875 | 4 | #6. Write a Python program to convert temperatures to and from celsius, fahrenheit.
#Celsius to Fahrenheit formula = ((temp/5)*9)+32 #Fahrenheit to Celsius formula = ((temp - 32)*5)/9
temperature = int(input("Enter the temperature you would like to convert: "))
scale = input("Enter C for Celsius or F for Fahrenheit: "... |
6f99e506d5dc1bddc90041b9d184e2220518acfe | Jiaoshichun/python_study | /study/arithmetic7.py | 3,514 | 3.59375 | 4 | # 迪克斯特拉算法
# 1.建立图
graph = {}
graph["start"] = {}
graph["start"]["a"] = 5
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["c"] = 4
graph["a"]["d"] = 2
graph["b"] = {}
graph["b"]["a"] = 8
graph["b"]["d"] = 7
graph["c"] = {}
graph["c"]["d"] = 6
graph["c"]["fin"] = 3
graph["d"] = {}
graph["d"]["fin"] = 1
graph["fi... |
75970ecea7105bb8fcb0eda2f6cef2e0884ec334 | jamesanderson9182/tides | /tides.py | 1,392 | 3.890625 | 4 | '''
Uses data from Belfast-Harbour.co.uk/tide-tables to
print the tides that are greater than 3.5 meters
'''
import urllib
import re
url = 'https://www.belfast-harbour.co.uk/tide-tables/'
regexDepth = '<span class="depth">(.+?)</span>' #An array of whatever is between the two span tags
patternDepth = re.compile(... |
e9de894aee95c9713ac5441b41f755acba7ccc39 | pkgcore/snakeoil | /src/snakeoil/currying.py | 5,399 | 3.859375 | 4 | """
Function currying, generating a functor with a set of args/defaults pre bound.
:py:func:`pre_curry` and :py:func:`post_curry` return "normal" python functions
The difference between :py:func:`pre_curry` and :py:func:`functools.partial`
is this
>>> from functools import partial
>>> from snakeoil.currying import pr... |
10428236454d8623a3dace0fe4b16c2387218b5d | astroj6/TSP-solution-using-an-evolutioanry-algorithm | /TSP_Evolution_Najim/City.py | 535 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 09:08:07 2018
@author: jforr
"""
import math
# city class description where we will hold information about each city
destinations = []
class City:
def __init__(self,x,y,name,num):
self.x=x #coordinates
self.y=y
self.name=name
... |
56beec102f0d77bf7a6958787e1ff1c19345ad53 | richherr/richherr.github.io | /data8/_build/jupyter_execute/chapters/04/2/Strings.py | 1,511 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Strings
#
# Much of the world's data is text, and a piece of text represented in a computer is called a *string*. A string can represent a word, a sentence, or even the contents of every book in a library. Since text can include numbers (like this: 5) or truth values (True), ... |
40c9707d1f216d9f8388855d52019951fde14de3 | NGat/Other | /Marks.py | 529 | 3.53125 | 4 | print 'subject','teacher','year','term','mark','type'
import re; import csv; import sys
dict = {}
count=0
inp = raw_input("Query: ")
queries = inp.split(',')
for q in queries:
field, value = q.split('=', 1)
dict[field] = value
lines = open('Marks.csv', 'rU').readlines()
for line in csv.DictReader(lines, fieldnames=... |
8a3274db6bfa54eac9a3edfef04683f119ae4e53 | sidneyalex/Desafios-do-Curso | /Desafio091.py | 729 | 3.625 | 4 | #Crie um pgm onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um dicionário.
#No final, coloque esse dicionario em ordem, sabendo que o vencedor tirou o maior número no dado.
from random import randint
from operator import itemgetter
from time import sleep
jogo = dict()
for n i... |
4cb265f1bf3e5c6e77f282a2ee231158ff8a37ad | MaazAmjad/MyDataScienceMasters_2015-16 | /Python Specialization - Uni of Michigan/2_python_data_structures/assignments/8.1-2 assignment.py | 1,416 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 14 18:10:02 2015
@author: steph_000
"""
# Open the file romeo.txt and read it line by line. For each line,
# split the line into a list of words using the split() function.
# The program should build a list of words. For each word on each
# line check to see if the wor... |
a271389632617c803f41e535e58d0f7658c28f0d | sai-varshith/Hacktoberfest21-letshack | /Python Programs/Average.py | 181 | 4.03125 | 4 | a = float(input("Enter first number:"))
b =float(input("Enter second number:"))
def average(a, b):
return (a + b) / 2
m = average(a,b)
print("The Average is {0}".format(m))
|
040a3b0c7d5a2320a56eb35bb4dc6cdaa090046b | cwaa079/Programmers | /Lever2/최댓값과 최솟값.py | 392 | 3.625 | 4 | #https://programmers.co.kr/learn/courses/30/lessons/12939
def solution(s):
answer = ''
s = s.split()
temp = [int(word) for word in s]
answer += str(min(temp))
answer += str(max(temp))
return answer
s = "-1 -2 -3 -4"
print(solution(s))
#더 나은 풀이
def solution(s):
answer = list(map(int, s... |
dd3e46836e745f9e8151bbc1a250af272dd2765f | UrlBin/Lessons-10 | /Обработка последовательностей.py | 1,289 | 3.921875 | 4 | # input text - '3 4 5@1 2 3@ 3 4 6 9' и '5@7@0'
text = input('Введите строку для обработки: ')
# разделение трех последовательностей цифр
split_text = text.split(sep='@')
# обработка первой последовательности цифр. Нахождение суммы цифр.
sum_of_first_sequence = 0
first_action = split_text[0].split()
for i in first_a... |
49b517d37c7d91f28047837888138e27b1f58076 | alt-scale/computational_physics | /programming_exercises/simple_exercises/palindromes.py | 873 | 4.25 | 4 | def is_palindrome(n):
s = str(n)
return s == s[::-1]
def largest_palindromic_n_digit_product(n):
"""
find the largest palindromic product of two n-digit numbers
>>> largest_palindromic_n_digit_product(2)
9009
:param n: number of digits
:return: largest palindromic product if exists, ... |
fa3a2c80c013edc467ab10fc6a76f787b6bbeb45 | ksatola/Data-Science-Notes | /final_python/src/utils/file_io.py | 570 | 3.59375 | 4 | import json
from typing import Dict
def read_json(json_path: str) -> Dict:
"""
Deserializes JSON file.
:param json_path: full path to JSON file
:return: Python dictionary
"""
with open(json_path, 'r') as read_file:
return json.load(read_file)
def write_json(data: Dict, json_path: str... |
347e129551a52137707f4e16abfb27226955e8ea | hyesungoh/AA_Algorithm | /python/프로그래머스_다리를지나는트럭.py | 1,399 | 3.609375 | 4 |
from collections import deque
def solution(bridge_length, weight, truck_weights):
truck_weights = deque(truck_weights)
length = len(truck_weights)
exit_length = 0
bridge_now = deque([0 for _ in range(bridge_length)])
bridge_weight = 0
answer = 0
while exit_length != length:
if t... |
2a60c78fcda40b1fe28a9a2dde1f912f8be1dcac | colbehr/DojoAssignments | /PythonDjango/PythonBasics/day3/Car.py | 891 | 3.859375 | 4 | class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if (price > 10000):
self.tax = .15
else:
self.tax = .12
def displayAll(self):
... |
7e1b787c11ad4dd56c7076a99418eaa5540a2f45 | Padreik/euler | /005.py | 458 | 3.5625 | 4 | # 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?
MAX = 20
jump = MAX * MAX - 1
multiple_found = False
i = 0
while not multiple_found:
i += jump
mult... |
2d1bd423fb141b0de295556bfa4564192ff32a73 | micoli/DoorStationSandbox | /ScreenSaver/Ball.py | 1,438 | 3.53125 | 4 | import math
import random
class Ball:
__slots__ = ('x', 'y', 'v','angle','vx','vy','radius','screen_rect')
def __init__ (self, screen_rect,radius):
self.screen_rect = screen_rect
self.radius=radius
self.x = random.randint(self.screen_rect.width/4,self.screen_rect.width*3/4)
self.... |
2e8a19a2df1f6b2bd8816c61a7eb4c81cdee0a88 | sairam-py/CodeForces-1 | /ArrivaloftheGeneral.py | 1,318 | 3.546875 | 4 | __author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/144/A
Solution: Interesting problem.
Firstly, we prefer to get the largest value on the left-most index and smallest value on the right-most index.
This way we reduce the swaps in case of duplicates for largest/smallest values.
Once we have t... |
78a4c0d5eb886cb1f89451594a8164930905ca37 | huashuolee/intel_script | /demo/count/cout.py | 142 | 3.640625 | 4 | """
f = open('file','r')
f.read()
for line in f.read():
print line
"""
with open('file','r') as f:
for line in f:
print line
|
e31e0a23eb730ccf12dbafd336645f0f6c3549d5 | amandazk/uri-exercicios | /Python/Python-1007.py | 310 | 3.5 | 4 | # Leia quatro valores inteiros A, B, C e D. A seguir,
# calcule e mostre a diferença do produto de A e B pelo
# produto de C e D segundo a fórmula: DIFERENCA = (A * B - C * D).
a = int(input())
b = int(input())
c = int(input())
d = int(input())
diferenca = (a*b - c*d)
print("DIFERENCA = %d" %diferenca) |
8224f4ae3a9aa7d2175f95f3e86bdb2d88420695 | amirmirzaeimoghadam/PYTHON | /Ex5/071.py | 169 | 3.90625 | 4 | list_sport = ['Taekwando','football','handball']
name_sport = input('plz enter name your sport=')
list_sport.append(name_sport)
list_sport.sort()
print(list_sport)
|
03467b7fda335c1c07e25b61207cd83f36180b89 | VladyslavPodrazhanskyi/python-cursor | /week2/lesson2-intro-to-functional/homework/DmytroMelnyk/utils/task_7.py | 839 | 3.859375 | 4 | def convert_dec_roman(inp):
"""
Function that will convert decimal values to Roman Numerals
:param inp: arabian num
:return: Roman num
"""
for k, v in to_roman.items():
if inp == k:
return v
if inp > k:
temp = v
temp1 = k
remain = inp - te... |
fd00f08ec7762951b5eb9d3bf90008ddc043ef44 | chinnuz99/luminarpython | /practice/qc1.py | 251 | 4.03125 | 4 | a=int(input("enter the number"))
def num(a):
if(a>10):
print("the",a,"is greater than 10")
elif(a==10):
print("the",a,"is equal to 10")
elif(a<10):
print("the",a,"is less than 10")
while True:
num(a)
break
|
990e84f59c5be58a6bebb93d9fe5198489bd0ca9 | guillermovillois/codewarskata | /roman_coding.py | 637 | 3.609375 | 4 |
def solution(num):
roman = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL',
50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'}
# roman = OrderedDict(False)
# print()
def roman_num(num):
for r in list(reversed(sorted(roman.keys()))):
x, y = di... |
b884cddd26007e1a529a52ea70fb62625db0bb6a | RocKr96/Infosys-Training | /Day-1/13.py | 695 | 3.703125 | 4 | '''
Assignment 13: Control Structures – Demo
Objective: Given a real world problem be able to understand the need for control structures and operators to implement the logic and solve the problem
Problem Description: Suppose the retail store management now wants to provide discount for all bill amounts as mentioned bel... |
e20fffb809df0d0fb32b7bef1c80b5081bd92bf0 | conquener/ArithmeticDemo | /selectionSort.py | 687 | 3.5 | 4 | # -*- coding: utf-8 -*-
datas = [22,15,21,54,76,15,12,56,45,38]
#data 是数据集 index 是排序位置
def selectionSort(paramDatas):
result = [];#接收数据的结果集
for i in range(len(paramDatas)):
index = 0; # 数组索引
max_data = paramDatas[0];
#通过循环,选出最大的元素
for j in range(len(paramDatas)):
i... |
98186a1adf839fffe529b50d207b17bad0ffd097 | kaankabalak/python-exercises | /multiplication-table.py | 196 | 3.8125 | 4 | for k in range (0,13):
if k == 0:
print 'x',
else:
print k,
print '\n'
for i in range(1,13):
for j in range (1,13):
if j == 1:
print i,
print i*j,
else:
print i*j,
print '\n' |
40bd0db628d25d56cf5607d810714594117576ce | ch1huizong/study | /lang/py/cookbook/v2/19/cross.py | 1,002 | 3.734375 | 4 | #! /usr/bin/env python
# -*- coding:UTF-8 -*-
# 矢量积
def cross_loop(*sequences):
if sequences:
for x in sequences[0]:
for y in cross_loop(sequences[1:]):
yield (x,) + y
else:
yield ()
def cross_list(*sequences):
result = [ [] ]
for seq in sequences:
r... |
e87f506642a0d48130e0b9d4e9cd2bc24eec7cfb | nodir-malikov/python-entering | /son_topish_oyini/functions.py | 1,704 | 3.5 | 4 | from random import randint
def sontop(x=10):
tasodifiy_son = randint(1, x)
print(f"Men 1 dan {x} gacha son o'yladim. Topa olasizmi?", end="")
taxminlar = 0
while True:
taxminlar += 1
taxmin = int(input(">>>"))
if taxmin < tasodifiy_son:
print("Xato. Men o'ylagan son... |
9b445f1a8df1c7ce7a5145c15679e9814417c1bf | hubbm-bbm101/lab5-exercise-solution-b2210356086 | /exercise3.py | 398 | 4.15625 | 4 | print("This is a number guessing game, The interval is [1,100] (Both included)")
import random
target = random.randint(1,101)
guess = int(input("Please enter your guess: "))
while guess != target:
if guess < target:
guess= int(input("Increase your number: "))
else:
guess= int(input("Decr... |
b7f9c34625ebebb492013d9441b91cd0d93add74 | Pabitra-26/Problem-Solved | /LeetCode/Remove_All_Adjacent_Duplicates_In_String.py | 883 | 3.875 | 4 | # Problem name: Remove All Adjacent Duplicates In String
# Description: Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
#
# We repeatedly make duplicate removals on S until we no longer can.
#
# Return the final string after all suc... |
2b468dc53c2bd6e879bc14e4e5d1731fd5efdc49 | aravinthvp/hackerrank | /runnerup.py | 371 | 4.03125 | 4 |
#Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
a = int(input())
nums = list(map(int,input().strip().split()))[:a]
# print(nums)
w = max(nums)
# print(w)
while max(nums)... |
5e3b89b16f445d20cb0708cfede0806cde05badb | queirozfellipe7/easyocr-basic-Equation-calculator | /easyocr-basic-calculator/leitor_de_imagem.py | 1,157 | 3.546875 | 4 | import easyocr
reader = easyocr.Reader(['pt']) #Define the language to be used
resultado = reader.readtext('images.png',paragraph=False)#Run the image reading
for resultado in resultado:
x = resultado[1]# transfer the obtained data to a variable
if(x[2]=="+"):#identifies the operation that will be pe... |
bed199cd640b70b822ab05c0197dbdce01934a35 | mikekiwa/ATM | /Dane/program.py | 842 | 3.84375 | 4 | import sys
bal = 0
def checkbal():
return(bal)
def withdraw(amnt):
x = bal
if amnt < x:
x -= amnt
print(x)
return(x)
else:
print('You can\'t do that!')
def deposit(amnt):
x = bal
x += amnt
print(x)
return(x)
while True:
user_input = input('What wo... |
0f9bc8a9bb9458561eed34232d2985a49193aed1 | Guanqifeng/Dataworks_ETL | /data_works_python_etl/AutoMateWithPython/ChapterFour/PractiseFiles/practise4_10_1.py | 552 | 3.84375 | 4 | #spam = ['apples', 'bananas', 'tofu', 'cats']
def transListToString(lista):
getResultString = ''
if isinstance(lista,list) and lista:
for i in range(len(lista)):
if i == len(lista) - 1:
getResultString += " and "+str(lista[i])
else:
getResultStrin... |
6053f3bb8fe39077dc64ec353a34546325e324ae | jcorbaley/Weather-App | /Final_Project.py | 1,710 | 4.34375 | 4 | #Name: Jason Corbaley
#Datae: 08/07/2019
#Course: DSC 510
#Description: This program will act as a weather app.
#Usage: This program will prompt the user to enter Yes or No on whether or not they would like to see what the weather is
# in a city or zip code. If you input y then the program will ask you to enter a cit... |
3afbf1a9ae50c7ba6f273365832f91b4b648d976 | joc44/PtyhonPractice | /gyak1.py | 228 | 3.921875 | 4 | szo = input("Írj be egy szót: ")
if szo < "limonade":
place = "megelőzi"
elif szo > "limonade":
place = "követi"
else:
place = "fedi"
print("A", szo, "szó", place,"a 'limonade' szót a névsorban" ) |
d60429370fe8b390d395dd2911fec726b0378c46 | takuhartley/Python_Practice | /Strings/strings.py | 1,797 | 4.1875 | 4 | print("Hello World!")
print('Hello World!')
a = "Hello World!"
print(a)
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut la... |
b81ffca33b2f51522e5c2ea8f5bfbcbb5971f5a7 | chloro4m/python_practice_codes | /binary_heap_sort_nLogn_WRONG.py | 3,736 | 3.609375 | 4 | ##Using the buildHeap method, write a sorting function
##that can sort a list in O(nlogn) time
##MAJOR BUGS in this implementaion :(
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i... |
c844cccb54d063412b1151729cf764bbfbd0dfb1 | SpiroKostiris/University-Projects | /Honours/Vernam Cipher/vernam.py | 1,939 | 4.375 | 4 | # Run using python3
def cipherMessage(message,key):
convert = "";
i = 0;
# Bitwise operation
for letter in message:
convert = convert + chr(ord(letter) ^ ord(key[i]));
i = i + 1;
return convert
print("Please note - there might be characters that are not visually shown when encrypti... |
3833cbc0f9956af3946561d8ed112709d7980a72 | thehushkat/Python_Coursera | /ch7_2_hw.py | 782 | 3.921875 | 4 | '''Write a program that prompts for a file name, then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those
values and produce an output as shown below. Do... |
2374e4ea9ce5dc89231c050958986f7e47f904c4 | neelimamukku/LeetcodeSolutions | /DiameterOfBinaryTree-543.py | 763 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def height(self,root,hei):
if root == None:
return 0
if root in hei:
... |
1fe20638a04f36a48f55ebcb886661379bb28052 | santhoshnec/python- | /biggestamong3nos.py | 155 | 3.84375 | 4 | a=int(input())
a1=int(input())
a2=int(input())
if(a>a1) and (a>a2):
print(a,"is big")
elif(a1>a2):
print(a1,"is big")
else:
print(a2,"is big")
|
0321ce01b0ffb37d76062292b3270085bef8a549 | fettahyildizz/Kohonen_network | /main.py | 12,019 | 3.921875 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
class Kohonen:
def __init__(self, learning_rate, number_neuron,number_epoch,sigma0,time_constant1,time_constant2):
self.sigma0 = sigma0
self.time_constant1 = time_constant1
self.time_constant2 = time_constant2
self.num... |
8cb0e09019e4d3b7c8f7a77dbd01c5b19b731823 | clovery410/mycode | /algorithm_exercise/stack_sort.py | 680 | 3.96875 | 4 | # Sort the element in the stack, only use pop(), top(), push(), isEmpty(), isFull()
def isEmpty(s):
if len(s) == 0:
return True
return False
def top(s):
return s[-1]
def sort_stack(s):
dest = []
while not isEmpty(s):
candidate = s.pop()
if isEmpty(dest) or candidate >= top(... |
27575e98064b479643ddf6f2ec83e03240921a00 | deadsy/pycs | /wip/other/prefix.py | 381 | 3.71875 | 4 |
def lc_prefix(prefix, s):
"""return the longest common prefix of prefix and s"""
if prefix is None:
return s
n = 0
for i, j in zip(prefix, s):
if i != j:
break
n += 1
return prefix[:n]
def lc_suffix(suffix, s):
"""return the longest common suffix of suffix and s"""
if suffix is None:
... |
c8810e6aafa3bf0df718be44381861a4f3988983 | l200180017/algostruk | /MODUL 1/LatReview2.py | 269 | 3.859375 | 4 | print("kita perlu bicara sebentar...")
nm = input("siapa namamu ?")
print("selamat belajar",nm)
angkastr = input("masukkan sebuah angka antara 1 sampai 100")
a = int(angkastr)
kuadratnya = a * a
print(nm + ", tahukah kamu bahwa ", a ,"kuadrat adalah", kuadratnya,"?")
|
00e187918046976a842d8d82200b27296efa3f18 | AndersonAngulo/T_10-Angulo-Damian | /angulo/menu1.py | 1,195 | 3.5625 | 4 | import libreria
def agregarDNI():
# 1. Pedir el DNI
nombre=libreria.pedir_nombre("Ingrese el nombre:")
DNI=libreria.pedir_dni("Ingrese el DNI:")
# 2. Guardar el DNI en el archivo dni.txt
contenido=nombre + "-" + DNI + "\n"
libreria.guardar_datos("dni.txt", contenido, "a")
print("Datos guard... |
71fba5387912a343773d578f30ba916afbb10b9c | ccpwcn/PythonLesson | /012 趣味学习/001 出门办事,原路返回.py | 1,366 | 3.890625 | 4 | # 任务描述:
# 1、去楼下花园找王大爷,取3元钱
# 2、去小区门口的包子店买3个现蒸的肉包子
# 3、去小区外马路对面快递公司去快递
# 4、将肉包子送给王大爷
# 解决思路:
# 栈
class Task(object):
steps = []
def forward(self, location, desc):
if not self.steps:
print('即将行动,从家里出发')
self.steps.append((location, desc))
print('【前进】所在位置:{},任务:{}'.format... |
7acdc34a98b1c5a58d87f94fe57467e087b75512 | Argonautic/self-driving-car | /sdc.py | 12,580 | 4.03125 | 4 | import random
import os
import torch
import torch.nn as nn
import torch.nn.functional as F #all functions from pytorch for neuron activation
import torch.optim as optim #optimizer
from torch.autograd import Variable
#Creating the architecture of the neural network
class Network(nn.Module):
def __init__(self,... |
a9cda3b2fcddc44abf6039bb2d3757ff69de4033 | prasang-gupta/online-courses | /data-structures-and-algorithms-specialization/course-02-data-structures/assignment/week-03/1_make_heap/build_heap.py | 1,752 | 3.828125 | 4 | # python3
def siftdown(data, idx, swap):
size = len(data)
minval = data[idx]
if (2 * idx) + 1 < size and minval > data[(2 * idx) + 1]:
minval = data[(2 * idx) + 1]
minchild = (2 * idx) + 1
if (2 * idx) + 2 < size and minval > data[(2 * idx) + 2]:
minval = data[(2 * idx) + 1]
... |
c61f5f0915a0164f95c97ac3b8fa68211e8ca03f | momchil-lukanov/hack-bulgaria | /programming-0/week-1/saturday-tasks/int_palindrom.py | 204 | 4 | 4 | n = input()
n = int(n)
palindrom = n
m = 0
while n != 0:
m = m * 10 + (n % 10)
n = n // 10
if palindrom == m:
print("The number is palinrom")
else:
print("The number is not palindrom")
|
301197234942e8ca2c036acb152914f5f4f02c1b | prkirankumar/LearningPython | /Basics/functions_recursion.py | 307 | 4 | 4 | def factorial(n):
f=1
while n>0:
f*=n
n-=1
print(f)
factorial(5)
factorial(-2) #2
def factorial_recursion(n):
if n==1:
return 1
return n*factorial_recursion(n-1)
print(factorial_recursion(5))
#print(factorial_recursion(-2)) # throws RecursionError
|
9d2e9a1986647b0842ada6c4607f408696399a54 | BrindaSahoo2020/Python-Programs | /SkipCount.py | 260 | 4.1875 | 4 | #Python program to print all the numbers between 0 to 100 skipping 10
#Sample Output
'''List after skipping 10 is : [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]'''
lst = []
for i in range(0,101,10):
lst.append(i)
print("List after skipping 10 is :",lst) |
7b9c72140c2b8ef58bedcd29408fbcb1eaa2f9aa | lnixffm/aoc2020 | /day_10.py | 1,478 | 3.796875 | 4 | #!/usr/bin/python
import sys
# day 10:
# Read Data
input_list = []
fobj = open("input_day10_01.txt", "r")
lines = fobj.readlines()
for line in lines:
line = line.replace('\n','')
input_list.append(int(line))
input_list.append(max(input_list) +3 )
print sorted(input_list)
cache = {}
def first_star():
mai... |
a07cf187d0b7179a3e7b518c2f4b1e67d54bf5cb | qumogu/pystudy | /2-2/yield02.py | 766 | 3.8125 | 4 | import time
def work1():
for i in range(1,10):
print("---第%d次执行work1---" % i)
time.sleep(0.2)
yield
return "work1,111111!"
def work2():
for i in range(1,10):
print("---第%d次执行work2---" % i)
time.sleep(0.1)
yield
return "work2,game over!"
def work3():
... |
f6852a06100028117602ea8180e373694443dd0c | linouk23/leetcode | /640.py | 2,633 | 3.859375 | 4 | # 640. Solve the Equation - https://leetcode.com/problems/solve-the-equation
# Credits to https://discuss.leetcode.com/topic/95283/python-regex-solution-explained
class Solution:
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
# Coefficients are d... |
bdeff76d23f0b259509e58dba769dafc0fcd85bb | Caioseal/Python | /Exercícios/ex78.py | 998 | 3.84375 | 4 | lista = []
maior = menor = 0
for posição in (range(0,5)): #Posição é o contador, que vai até o número definido no intervalo
lista.append(int(input(f'Digite um valor para a posição {posição}: '))) #Comando para adicionar valores digitados pelo usuário em uma lista
if posição == 0: #Quando for o primeiro núme... |
b9da5013583a112808f2e6d4c628247aad6bba1a | PragayanParamitaMohapatra/Basic_python | /edureka.py | 199 | 3.953125 | 4 | from num2words import num2words
def factorial(num):
if num ==1:
return num
else:
return num*factorial(num-1)
num=5
f=factorial(num)
print(num2words(f,ordinal=True,lang='en'))
|
1689946265dc339264468eac7f44089df223f4c4 | 0904-mansi/Perceptron_3038 | /criminal_detection/abc.py | 1,486 | 3.515625 | 4 | import sqlite3
conn = sqlite3.connect('test3.db')
print ("Opened database successfully");
# create table criminaldata(
# id int primary key auto_increment,
# `name` varchar(20) not null,
# `father name` varchar(25),
# `mother name` varchar(25),
# gender varchar(6) not null,
# dob varchar(10),
# `blood group` varchar... |
5280334409b8c79bfef4946e6ebaa95d28c68e0c | Akshay1350/Python | /FileHandling/FileCheck.py | 319 | 3.625 | 4 | import os,sys,Read as r,imp
def checkFile():
fname=input("Enter file name ")
if os.path.isfile(fname):
print("File exists:",fname)
imp.reload(r)
r.fileRead(fname)
else:
print("file doesn't exist")
sys.exit(0)
return
checkFile()
|
bb307b651643eb615e92914f2a824bb29b8dde88 | FawneLu/leetcode | /1055/Solution.py | 532 | 3.515625 | 4 | ```python
class Solution:
def shortestWay(self, source: str, target: str) -> int:
sour=set(source)
tar=set(target)
for t in tar:
if t not in sour:
return -1
res=0
j=0
while j<len(target):
i=0
while i<len(sou... |
efe6dba86572d3a563be57beb6ef8cde2e67d2c3 | jessicahojh/python_practice | /ascii.py | 164 | 3.796875 | 4 | firstChar = "p"
print("The ASCII code for the character ", firstChar, " is ", ord(firstChar))
value = 102
print("The ASCII value", value, "represents", chr(value)) |
dd5a34e2b3a275b212de51347ce7f29da94e7c74 | Rafaellinos/learning_python | /libraries/sys/test.py | 1,050 | 3.6875 | 4 | import unittest
from guessing_game import _randomize, _get_nums, main
class Test(unittest.TestCase):
def setUp(self):
print("about to start")
def test_get_nums(self):
pass
def test_radomize(self):
random = _randomize(1, 5)
self.assertTrue((1 <= random <= 5))
def test... |
c5804023d4fcc347f28ad0fad4b5ccd367096770 | algorithm005-class01/algorithm005-class01 | /Week_06/G20190343020140/LeetCode547_week06_0140.py | 2,782 | 3.9375 | 4 | #解法1 并查集 加了parent 数组和rank秩,路径压缩
class UnionFind:
def __init__(self,n):
self.count = n
self.parent = [i for i in range(n)]
self.rank = [1 for i in range(n)]
def get_count(self):
return self.count
def find(self,p):
while p != self.parent[p]:
self.... |
a1c1ba27c93f7ade95a014410eb48618e3902553 | NicolasAbroad/automate-the-boring-stuff | /Password check | 1,404 | 4.59375 | 5 | #! python 3
# Password character checker - checks if password contains 8 characters,
# including at least one uppercase, lowercase and digit
import re
def check():
pswd = input('Enter a password at least 8 characters long, containing at least both upper and lower case characters, and having at leat one digit: ')
... |
329ff4a7164480788c1c8540d4dc3b5fcbdb41e3 | sajeed786/woc3.0-eventmanager-Sk-Sajeed-Hossain | /TASK_3/contact_keeper.py | 3,886 | 4.09375 | 4 | from ContactRecord import ContactRecord
def displayContactBook(plist):
print("Name Contact Number(s)")
print("____ _________________\n")
nSpaces = 30
sp = " "
for person in plist:
print(person.name + sp*(nSpaces - len(person.name)), end = ""... |
c365b4b8e2fdd9787b7a330380d58f775ecdd677 | nilax97/leetcode-solutions | /solutions/Deepest Leaves Sum/solution.py | 687 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def dfs(self, node, height):
if node == None:
return
if len(self.mat) < hei... |
4ce053f2c7695766216e230059f0b683f7fd29ca | jayjay300/CS361-Programming-Languages-and-Implementation | /python/exercise10.py | 416 | 3.71875 | 4 | import numpy as np
import matplotlib.pyplot as plt
def formula(x):
sinval = x-2
eexp = -1 * x**2
sin = (np.sin(sinval))
sin = sin ** 2
eval = np.exp(eexp)
sin = sin * eval
return sin
def graph(formula):
x = np.linspace(0, 2, 50)
y = formula(x)
plt.plot(x,y)
plt.xlabel('x value')
plt.ylab... |
76434ca37a70a232e56e3b04bb3256b3a19b2ce4 | Spector255/izdruka | /uzdevumi/uzd_12_03.py | 829 | 3.8125 | 4 | #Uzraksti programmu, kura prasīs lietotājam ievadīt veselus nenegatīvus skaitļus (kāmēr nav 0), pievienos tos sarakstam un izvādis skaitļu skaitu, kas ir lielāki par savu nākamo kaimiņu.
skaits = 0
a = 0
mylist = []
while True:
n = int(input("Ievadi veselu nenegatīvu skaitli: "))
if a > n:
skaits += 1
... |
95e28f8cf35dea1a9c887e91dbbcbc85cf5ef248 | LukasKalit/U.S.StatesGame | /main.py | 2,089 | 3.875 | 4 | import turtle
import os.path
import pandas
from writing_on_screen import pen
# screen init
screen = turtle.Screen()
screen.setup(width=725, height=491)
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
pen = pen()
# downloading states names
country_data = pand... |
61ebb5573aa32b55d1085d26367077d2b2b9d98f | AdityaVelugula/Python | /ICP3/employee.py | 992 | 4.0625 | 4 | #employee class 'Parent class'
class Employee:
noOfEmployee = 0 # a data member to count the number of Employees
totSalary = 0 # a data member to save the total salary
# constructor for Employee class
def __init__(self):
self.name = input('Name :')
self.family = input('Family :')
self.d... |
c6321b374d380743d5895f117e77c428218b035a | samarthgupta0309/leetcode | /String/defanging-an-ip-address.py | 517 | 3.71875 | 4 | '''
Question : Defanging an IP Address
https://leetcode.com/problems/defanging-an-ip-address/
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]".
Solution:
'''
class Solution:
def defangIPaddr(self, address: str) ->... |
ec69b2539c674f91348a5d892b8f9b24208c622b | jdl49/calculator_stat | /RandomNum/random_list.py | 834 | 3.640625 | 4 | # Generate a list of N random numbers with a seed and between a range of numbers - Both Integer and Decimal
from numpy.random import seed
from RandomNum.random_list_float import random_float
import random
class RandomList():
@staticmethod
def list_Of_Ints(data, length, theSeed):
if isinstance(data,... |
f91795f678753b39fd16b77855421f678de3093c | ShervinSadeghvand/NetworkProject | /oopProject.py | 5,287 | 3.796875 | 4 | # Variables
Num_Of_Node=None
Num_Of_Link=None
MenuChoose=None
Location=[]
Degrees=None
InNodeId=None
OutNodeId=None
Node_Del_choose=None
Link_Del_choose=None
l=0
Id=0
nodes={Id:{'Location':[], 'Degrees':0}}
links={l:{'InNodeId':None, 'OutNodeId':None}}
# Functions
def MainMenu():
print("Choose What you Want to Do o... |
dc5271e0d1b0e42c101f037361d769d281e2b641 | TJBos/CS-Algorithms | /algo_foundations/searching/checkifsorted.py | 252 | 3.953125 | 4 | #check if a list is sorted
def issorted(itemlist):
#you can do this with a for loop but we'll use a python comprehension here
#in JS similar array method: .every
return all(itemlist[i] <= itemlist[i+1] for i in range(len(itemlist) -1))
|
83b702a38679277f931c7494da1cc8ef16688b8d | MattlearnPython/8_puzzel | /QueueAndStack.py | 812 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 20:31:58 2018
@author: jinzhao
"""
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
... |
830de8368ff654a63b412b09845fd2571ba7adf8 | cartier/python | /revfunc.py | 333 | 4.28125 | 4 | #!/usr/bin/python
"""
reverse a string
"""
mystr = "this is my string"
def interative_reverse_string( str ):
""" interative function to reverse a string """
revstr = ''
for i in xrange( len(str)-1, -1, -1 ):
revstr = revstr + str[i]
return revstr
print interative_reverse_string("this is ... |
c9a3be420f00d10a2810e04a1acfcaf22a45c0a7 | YashaswiThannir/BackEndAutomation_RESTApi-Python | /PythonBasics/DemoOopsPrinciples.py | 1,247 | 4.34375 | 4 | # classes are user defined prototype or a blueprint
# constructor is a method which is automatically created when you create a object for any class
# the variables declared inside a class are called class variables.
# the variables created inside constructor are called instance variables.
# instance variables keep ... |
44c53e87372afb2d63173f771a526ef05994ea1f | ZiningZhu/Leetcode | /958-binary-tree-completeness/soln.py | 891 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isCompleteTree(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# Count the number of n... |
f2bbf889d288f8edc03041f8d4d97146c6ff1515 | toaco/.py | /threading/lock.py | 882 | 3.6875 | 4 | from threading import Thread, Lock
from utils import timeit_cm, pause
def no_lock():
init = 10 ** 6
def countdown(start, end):
while end > start:
end -= 1
pw = Thread(target=countdown, args=(1, init))
pr = Thread(target=countdown, args=(1, init))
with timeit_cm():
pw... |
67ddf107b4b9790a6f602074e12747c03ba956d7 | LiamMZ/POR-CodingChlng | /src/State.py | 458 | 3.921875 | 4 | class State:
'''Class to hold the state of a TicTacToe game
to_move = the player whose turn it is
utility = the value of a state, 0 for no winner,
1 for X win, -1 for O winn
board = current spots on the board that have been marked
moves = available moves'''
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.