blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
d064b683c1581f0d4f3f1f41bd5f6caa2ba4a215 | amari-at4/Password_Hacker | /Topics/Kwargs/Tallest people/main.py | 295 | 3.65625 | 4 | def tallest_people(**kwargs):
tallest = {}
for name, height in sorted(kwargs.items()):
tallest.setdefault(height, []).append(name)
tallest_height = sorted(tallest, reverse=True)[0]
for people in tallest.get(tallest_height):
print(f"{people} : {tallest_height} ")
|
234ddfccd1c03b8d7fd3a4d3eaf7fd88bc290386 | vishalsood114/pythonprograms | /sigma.py | 326 | 3.71875 | 4 | """ function that computes the sum of any function passed as
a parameter
"""
def sigma(f,a,b):
return sum(f(x) for x in range(a,b))
def square(x):
return x*x
def cube(x):
return x*x*x
print sigma(square, 1,10)
print sigma(cube,1,10)
print sigma(lambda x:x**0.5, 0,10)
print sigma(lambda x:1.0/x,1... |
91aa873537912aa320e4d02bebb5a6125146e5a4 | develooper1994/DeepLearningCaseStudies | /SırajRaval/MathOfIntelligence/Chapter1/LinearRegression.py | 3,511 | 3.84375 | 4 | from numpy import *
from numpy.core._multiarray_umath import ndarray
import matplotlib.pyplot as plt
'''
This example about single line modelling. y = mx + b (Linear regression)
There is also polinominal models like y = (k=1->inf)sum(mk*x**k) + b =m1*x + m2*x**2 + m3*x**3 + ... + b (Polinom fit)
'''
# y = mx + b
# m ... |
609cca7ecdae8b1851b9290a3ea3d9e8f6038ff2 | sxt/pipython | /sayhello.py | 168 | 3.765625 | 4 | #!/usr/bin/python
import sys
print "Hello " + sys.argv[1]
option = sys.argv[1]
if option == "1":
print "Turning on pin 1"
else:
print "Not turning on a pin"
|
c378b70ddd789fc251b7a66718689b9c7023b339 | Ichiro805/crypto-mining-sites | /telegram/ZEC Click Bot/sleep.py | 242 | 3.625 | 4 | import time
from datetime import datetime, timedelta
def sleep(ms):
timenow = datetime.now()
print("Sleeping for: ", ms, " ms. Sleep is from ", str(timenow), "to", str(timenow + timedelta(hours = ms / 1000 / 3600)))
time.sleep(ms / 1000)
|
c0a6ec73851426331ea2aec71c52e6d8fc113455 | Yiisux/Clase | /PycharmProjects/untitled1/ArteagaDuranJesusExamen/Ejercicio2.py | 366 | 3.796875 | 4 | #-'- coding: utf-8 -'-
list = []
print "Diga la primera palabra"
list.append(raw_input())
print "Diga la segunda palabra"
list.append(raw_input())
print "Diga la tercera palabra"
list.append(raw_input())
print "Diga la cuarta palabra"
list.append(raw_input())
print "Diga la quinta palabra"
list.append(raw_in... |
5c2240e374a1dafa9e9c2558a3336515bb993365 | monish7108/PythonProg2 | /fibonacciNumChecking.py | 1,384 | 4.28125 | 4 | """This programs check every number from command line
and tells whether number is in fibbonacci series or not.
Math: Instead of producing loop and checking the number there is a mathematical formula.
If (5*x*x)+4 or (5*x*x)-4 or both are perfect squares,
then the number is in fibona... |
424f40816cbcc82c156a9c43647b4c7b5d956f5a | CaiqueAmancio/ExercPython | /exerc_22.py | 796 | 4.125 | 4 | """
Leia a idade e o tempo de serviço de um trabalhador e escreva se ele pode ou não se aposentar.
As condições para aposentadoria são:
- Ter pelo menos 65 anos;
- Ou ter trabalhado pelo menos 30 anos;
- Ou ter pelo menos 60 anos e trabalhado pelo menos 25 anos
"""
print('Digite sua idade e seu tempo de serviço e dire... |
fcbb4d738d62c7e376322ae42d255088d4c712aa | radavis47/automate_python | /Programs/collatzSequence.py | 594 | 4.3125 | 4 | def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*+number+1)
return 3 * number + 1
r=''
print('Enter the number')
while r != int:
try:
r=input()
while r != 1:
r=collatz(int(r))
break ... |
d5e3bca573d32316aef967b1712a15996475c2ab | vengrinovich/python | /number_guess.py | 478 | 3.984375 | 4 | import random
a = random.randint(1,9)
guesses = 0
while True:
user_number = raw_input("Please guess a number from 1 to 9:")
if user_number == 'exit':
break
elif int(user_number) == a:
guesses += 1
print "You guessed it right using %d guesses" % guesses
break
elif int(user_number) > a:
guesses += 1
pri... |
14c48fc45021cdc354c1ebd3ba1f4b874d24ec49 | hungcold/BaiKiemTraXSTK | /Bai2.py | 358 | 3.5 | 4 | A=[1,1,2,3,5,8,13,21,34,55,88]
B=[1,3,5,4,7,88,66,59,40,54]
C = set(A) & set(B)
print("Các phần tử trùng nhau trong list A,B là",C)
for i in A:
for j in B:
if(j==i):
A.remove(j)
B.remove(j)
print("Xóa các phần tử trong list A bị trùng nhau",A)
print("Xóa các phần tử trong list B bị t... |
fae2a2ad56cd8cadb6295067f623fcb90334ed0b | Albert-Richards/Python | /QA_community/programs/debug.py | 898 | 4.15625 | 4 | import pdb
"""## exercise 1
num = float(input("Burger price:"))
price = {"Burger": num}
user_funds = 10.31
item_price = price["Burger"]
if item_price < user_funds:
print("You have enough money!")
if item_price == user_funds:
print("You have the precise amount of money")
if item_price > user_funds:
print("S... |
6c147e14300b51aca7c8251bc132f4a7312e5b92 | lidianxiang/leetcode_in_python | /树/501-二叉搜索树中的众数.py | 856 | 3.53125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import collections
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
if not root:
return []
self.count = collections... |
e62d424cca83e3cef9c581893948b3d6ec0aedce | GauthamAjayKannan/guvi | /binary.py | 114 | 3.71875 | 4 | #62
s=input()
b,n=0,0
for i in s:
if i=="0" or i=="1":
b=1
else:
n=1
break
print("no" if n==1 else "yes")
|
439cbd5337f4e64b5b0628d6b765351ffbfa1f8d | ericlarslee/RockPaperScissorsLizardSpock | /game.py | 2,025 | 4.0625 | 4 | import math
from human import Human
from computer import Computer
def game():
print('Hello!\n--------------------\nWelcome to RPSLS!\n--------------------\n'
'Here are the game Rules:\nRock crushes Scissors\nScissors cuts Paper\n'
'Paper covers Rock\nRock crushes Lizard\nLizard poisons Spock\n... |
ba31d159601f9af8e092ad35aac0c97dae80b306 | eskog/password-compare | /PwComp.py | 939 | 3.6875 | 4 | #!/bin/usr/python
#Loads in 2 password files formated as user:password and opens a output file.
file1 = ""
file2 = ""
matches = open("matches.txt" ,"w")
#Opens the first file, Retrieved the Username and password, then search the other file for a identical password.
with open(file1 ,"r") as pw1:
for line in ... |
401ca8a067c49c874ece1e2b2d67f73d2816d285 | veena863/python-practice-01 | /practice03.py | 1,904 | 4.625 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
#How to change,add,deleting elements in a list
fruits=['Apple','mango','banana','gauava']
print(fruits)
#1changing elements in list
fruits[1]='pea'
print(fruits)
# In[2]:
#2 Adding/append the element in the list
fruits=['Apple','manga','banana','gauava']
print(fr... |
fdaee51960f758bf2388ce2dc4fae3de5815f9aa | heyulin1989/language | /python/books/writing-solid-python-code-91-suggestions/30.py | 964 | 3.609375 | 4 | #coding:utf8
nested_list = [['Hello', "world"], ['Goodbye', 'World']]
# [expr for iter_item in iterable if cond_expr]
nested_list = [[s.upper() for s in xs if len(s) > 5] for xs in nested_list ]
print nested_list
# 支持多重迭代
nested_list = [(a,b) for a in ['a','1'] for b in [3,'b'] if a != b]
print (nested_list)
# 表达式可以... |
bc4933b335a9bbd4dff7df249c6fe3c32bce1208 | jedzej/tietopythontraining-basic | /students/sendecki_andrzej/lesson_01_basics/tens_digit.py | 211 | 4.0625 | 4 | # lesson_01_basics
# Tens digit
#
# Statement
# Given an integer. Print its tens digit.
import math
print("Enter the number")
n = int(input())
res = abs(n) // 10 % 10
print("The tens digit is: " + str(res))
|
a402af35c7fc722a5eba8ee9d9640d57e3c99627 | bullethammer07/Python_Tkinter_tutorial_repository | /progress_bar.py | 1,061 | 4.0625 | 4 | #------------------------------------
# Implementing a Progress Bar
#------------------------------------
# importing tkinter module
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Progress bar widget
progress = Progressbar(root,
orient=HORIZ... |
2b2eeafbb099d2d8c469b467584f46c8f3c066e7 | balasubramanyas/PythonMultiThreadApplication | /source/com/sbala/thread/concurrent/ThreadPoolExecutorExampleMain.py | 601 | 3.734375 | 4 | '''
Created on Jan 8, 2019
@author: balasubramanyas
'''
from concurrent.futures.thread import ThreadPoolExecutor
def printData(x):
return x + 2
if __name__ == '__main__':
values = [1,2,3,4]
executor = ThreadPoolExecutor(2)
# Submit method
print("Executor.submit() : ")
submitresultData = {exe... |
ed3d8d1270296da678983c27284d43a9a74df6e1 | usernamegenerator/MOOC | /MIT OpenCourseWare/MITx6.00.2x Introduction to Computational Thinking and Data Science/Unit2/exe3.py | 785 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 15:57:37 2019
@author: yuhan
"""
#Exercise 3-1
#0.0/5.0 points (graded)
#Write a deterministic program, deterministicNumber, that returns an even number between 9 and 21.
import random
def deterministicNumber():
'''
Deterministically generates and returns an ... |
06a50ef6249ec7dc987fc81b4b5c7f6a8dcf336f | Maria16pca111/Design-and-Analysis-of-Algorithms | /SquareRootNo.py | 2,557 | 3.875 | 4 | # find the square root of a given no
# using the Iterative Method
import math
def iseven(m):
flag = False
if(m % 2 == 0):
flag = True
return flag;
def betterguess(m,a):
betterguessarr = []
differencearr = []
flag = False
for i in a:
difference = m - round (i * i)... |
bdb5818bafafe4b96dd5145a5f212d43a65bbc62 | Laurahpro/EXERCICIOS-EM-PYTHON | /ex000.py | 323 | 3.828125 | 4 | nome = input('Qual o seu nome?')
print('É um grande prazer te conhecer,', nome)
idade = input('Quantos anos você tem?')
print('Bacana que você tem', idade,'anos', nome,'!')
filho = input('Você tem filhos?')
print('Que bacana!')
nomeFilho = input('Qual o nome do seu filho?')
print('Então ele se chama', nomeFilho, '!') |
65773d0b9e03e1e1f94eac0501a2ff404c7bd542 | 4doctorstrange/DS-and-Algorithms-in-Python | /solved/codechef/Gasoline 2 Lunchtime.py | 622 | 3.5625 | 4 | for _ in range(int(input())):
n=int(input())
fuel=list(map(int,input().split()))
cost=list(map(int,input().split()))
sorted_indicesC=[i[0] for i in sorted(enumerate(cost),key=lambda x:x[1])] #this line will sort indices of array on the basis of values and those indices are stored in array
ans=... |
bfac67572c16b6d0de6e5906b008e564348740c9 | farzanehta/project-no.1 | /Mosh/list_remove_the_duplicates.py | 338 | 3.8125 | 4 | #1(Myself)
numbers = [1, 6, 3, 3, 6, 7, 3, 4, 4, 10]
for i in numbers:
if numbers.count(i) > 1:
numbers.remove(i)
print(numbers)
numbers.sort()
numbers.reverse()
print(numbers)
#2(Mosh)
numbers = [1, 6, 3, 3, 6, 7, 3, 4, 4, 10]
uniques = []
for i in numbers:
if i not in uniques:
uniques.append(... |
cb9ff9c61369f3cda5324f8bf33be211914c05c4 | fatemehmakki13/CIS2001-Winter2017 | /MoreClasses/MoreClasses/MoreClasses.py | 1,277 | 3.9375 | 4 | class BankAccount:
def __init__(self,name,number):
self._name = name
self._number = number
self._balance = 0
def GetName(self):
return self._name
def GetNumber(self):
return self._number
def GetBalance(self):
return self._balance
def Withdraw(... |
e012e6b35e8c430bed63b3dea3901fa7b747c056 | sederj/zork | /Python/Player.py | 2,238 | 3.546875 | 4 | import random
from Weapon import Empty
from Weapon import HersheyKiss
from Weapon import SourStraw
from Weapon import ChocolateBar
from Weapon import NerdBomb
'''
Created on Nov 2, 2017
@author: Joseph Seder, Daniel Gritters
'''
class Player(object):
'''
This class holds the game's player object... |
1bdc2c167487e6b560d7da652e32d658498c05d1 | aaka2409/HacktoberFest2020 | /Python/Factorial.py | 377 | 4.34375 | 4 |
# To take input from the user
n = int(input("Enter a number: "))
factorial = 1
# checking wheather the number is negative, positive or zero
if n < 0:
print("factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = f... |
34fdeacd670fda71aa3b4cf6f90b93dc3fc2129f | narayanants/complete-python-bootcamp | /4 Methods and Functions/lambda.py | 763 | 3.84375 | 4 | def square(num):
return num ** 2
my_nums = [1, 2, 3, 4, 5]
for item in map(square, my_nums):
print(item)
list(map(square(my_nums)))
# MAP FUNCTION
def splicer(s):
if len(s) % 2 == 0:
return 'EVEN'
else:
return s[0]
names = ['Andy', 'Eve', 'Sally']
print(list(map(splicer, names))... |
d68a75bd1e6454913ce19913bb1ebd8cb0b213f1 | Yutong-Wu/Applets | /兔子问题/test11.py | 327 | 3.53125 | 4 | '''
古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月
后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
'''
n,a,b=1,0,1
while n<=15:
print('第{}月,有兔子{}只'.format(n,b*2))
a , b = b,a+b
n +=1 |
e811a24b12060fa99d5bd41e6c2b9b3bb8435a3d | saikumarsandra/My-python-practice | /Day-14/super.py | 563 | 4.09375 | 4 | class company():
def __init__(self,company):
self.company=company
def display(self) :
print(f"company name {self.company}")
class emp(company):
def __init__(self, company,emp_name):
super().__init__(company)
self.emp_name=emp_name
def display(self):
... |
9ac4f39aae592f6b20bf6379611d5d6d57615371 | c-u-p/data-science-project | /Data Science Mini Projects/Data Science Mini Proj 2/2.12.py | 431 | 3.65625 | 4 | import matplotlib.pyplot as plt
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# portion covered by each label
slices = [3, 7, 8, 6]
# color for each label
colors = ['r', 'y', 'g', 'b']
# plotting the pie chart
plt.pie(slices, labels = activities, colors=colors,
startangle=90, shadow = True, explode = ... |
4515a25705d18a9ef861e909e185d91b1421e6a3 | AndersonAngulo/T07.Angulo_Damian | /angulo/bucle_iteracion/ejer4.py | 330 | 3.96875 | 4 | # factorial de un numero x
import os
#input
x=int(os.sys.argv[1])
#validacion de datos
x_invalido=(x<0)
while(x_invalido):
x=int(input("ingrese valor correcto de x:"))
x_invalido = (x < 0)
#processing
i=1
producto=1
#bucle_while
while(i<=x):
producto *= i
i += 1
#fin_while
print("el factorial de ",x ,"es:",... |
dc0472efb2b093e37439fef9378453da6436bab2 | Gayatri-soni/python-training | /assignment9/q1.py | 411 | 4.03125 | 4 | #q1 Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class circle:
def __init__(self,radius):
self.radius=radius
def getArea(self):
area=math.pi*(self.radius**2)
print(area)
def getCircumference(self):
crcm=2*(math.pi*... |
97365121faf64986046f2332192de7463fbf17fc | LalithK90/LearningPython | /privious_learning_code/String/String lstrip() Method.py | 641 | 4.28125 | 4 | str = " this is string example....wow!!! "
print(str.lstrip())
str = "88888888this is string example....wow!!!8888888"
print(str.lstrip('8'))
# Description
#
# The method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the
# string (default whitespace characters). Synta... |
6215703fcc4305c2f41bf6de9671b295de3f498e | fliper6/PERFIL_PLC | /2º Semestre/SPLN/Testes/spln20190118.py | 6,203 | 3.5625 | 4 | import re
from typing import Collection
import random
## Questão 1 - a)
def max_diff(ex_ints):
dif = []
for n in ex_ints:
for n2 in ex_ints:
dif.append(abs(n - n2))
max = 0
for n in dif:
if n > max:
max = n
print(max)
#max_diff([1,1,3,5,2])
## Questão 1 ... |
80c89ccffdbe866c0d3d2493fc97377e88763c58 | nareshkbojja/machinelearning | /gas.py | 2,577 | 3.8125 | 4 |
# coding: utf-8
# # **Predicting Gas Consumption Value using Linear Regression**
# ## Import Libraries
# #### _Import the usual libraries_
# In[131]:
import pandas as pd , numpy as np, pickle
import matplotlib.pyplot as plt,seaborn as sns
#get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.model_se... |
4f98bdffa6d4f8c831719480be67731a63ddf25a | nsarlin/ml_simple | /Utils.py | 1,274 | 3.6875 | 4 | import numpy as np
import numbers
def sigmoid(z):
"""
The sigmoid function is used to uniformally distribute values from
[-inf;+inf] to [0;1].
z can be a matrix, a vector or a scalar
"""
return 1.0/(1.0+np.exp(-z))
def sigmoid_grad(z):
"""
Gradient of the sigmoid function
"""
... |
9bb29979de08f4480fb2cb7da9504d71d856015f | kelsadita/Algorithms | /sorting/merge/inversion.py | 1,219 | 3.953125 | 4 | # A version of inversions pair finding algorithm designed on the basis of merge sort algorithm
# Courtesy : Tim Roughgarden (coursera: Algorithm design and analysis 1)
import math
def merge_sort(a, p, r):
if p < r:
q = int(math.floor((p + r) / 2))
merge_sort(a, p, q)
merge_sort(a, q + 1, r)
if q != len(... |
97f08997d92401642d935082f8243365dd544790 | stimko68/daily-programmer | /challenge_anwers/168_easy_2.py | 947 | 4.28125 | 4 | """
String Index
Given an input string and a series of integers, create indexes for each
valid word in the string and then return a string based on the given
integers.
Example:
Input string: "The lazy cat slept in the sunlight."
Input ints: 1 3 4
Output: "The cat slept"
"""
import re
input_string = "...You...... |
537814de9e9fa13b06fbf81c0987e24c5eeb75eb | rbuerki/reference-code-python-programming | /algorithms/1_algorithmic_toolbox/week1_programming_challenges/2_maximum_pairwise_product/submission.py | 711 | 4 | 4 | # python3
def max_pairwise_product_fast(numbers):
"""My implementation."""
numbers = [int(x) for x in numbers]
n = len(numbers)
index_1 = 0
for index in range(n):
if numbers[index] > numbers[index_1]:
index_1 = index
if index_1 == 0:
index_2 = 1
else:
i... |
2312bf2cdfbb259e671b0cc563c6a14a40f8c482 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/w3resource/W3resource-exercises-master/16. return diff between 17.py | 185 | 3.90625 | 4 | def difference():
n = int(input("Enter a number to calc diff from 17, double if its over: "))
if n > 17:
print((n - 17) * 2)
else:
print(17 - n)
difference() |
135c200d744ce6b8c1ef93e781ad13061930572b | lissity/AoC | /2018/Day2/main.py | 824 | 3.75 | 4 |
# First star
file = open("Day2/input.txt", 'r')
two_letters = 0
three_letters = 0
for line in file:
found_two = False
found_three = False
for char in line:
char_count = line.count(char)
if (char_count == 2 and found_two == False):
two_letters += 1
found_two = True
... |
09c0f9fde75fe93ed4d8fa8311df983462ef2e90 | rubinshteyn89/Class_Spring | /Python/Lab_7/question3.py | 1,983 | 4.09375 | 4 | __author__ = 'ilya_rubinshteyn'
import os
import random
import sys
def Rando():
Y = (int(random.random()*100))
return Y
def guess():
y = Rando()
print("The computer generated a random number between 0 to 100.")
print("For testing purposes,",y," is the random number")
tries = 0
turned_on ... |
e5eb7b12d6758a35aab329d101d1d30f7f007b41 | Ale1503/Launchpad-Learning- | /Trivia.py | 2,092 | 4.0625 | 4 | def check_keep_playing(game):
keep_playing = input("Do you want to try the other game? -> (Yes/No)")
if keep_playing == "No":
print("Well, it was a pleasure!")
if keep_playing == "Yes":
if game == 1:
game = 2
run_game(game)
elif game == 2:
game = 1
run_game(game)
def run_game(g... |
dd5a9eb2e5331c25087010843c12c5eeb6491727 | agerista/HR_Python | /algorithms/implementation/day_of_the_programmer.py | 1,532 | 4.21875 | 4 | def solve(year):
"""Marie invented a Time Machine and wants to test it by time-traveling to
visit Russia on the Day of the Programmer (the 256th day of the year) during
a year in the inclusive range from 1700 to 2700.
From 1700 to 1917, Russia's official calendar was the Julian calendar; since
1919... |
734a23985c9663d9208004b11c9d216e5a3af595 | Guochiuan/NLP | /HW-3/hw3_skeleton_word.py | 8,413 | 3.875 | 4 | import math, random
from typing import List, Tuple
import collections
################################################################################
# Part 0: Utility Functions
################################################################################
def start_pad(n):
''' Returns a padding string of leng... |
d7223d045c4a663ba691719810ba9438100022ab | lokivmsl98/python | /pos or neeg.py | 97 | 3.796875 | 4 | l=int(input())
if(l>0):
print("Positive")
elif(l<0):
print("Negative")
else:
print("Zero")
|
ac36414acd860ecc6dbc7cc5838cace82f430c6f | VijayaR151852/Hackerrank | /Algorith_BubbleSort.py | 309 | 3.5 | 4 | def bs(a): # a = name of list
b=len(a)-1 # minus 1 because we always compare 2 adjacent values
for x in range(b):
for y in range(b-x):
if a[y]>a[y+1]:
a[y],a[y+1]=a[y+1],a[y]
return a
a=[32,5,3,6,7,54,87]
bs(a)
|
b39b9b9f8ba688a8639e60b2b5e0d06ccafead28 | sergzorg/pythonhillel | /DZ_1/5.py | 189 | 4 | 4 | #!/usr/bin/python3
##by Sergey Zhukanov
dict_one = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
dict_two = { 'a': 6, 'b': 7, 'z': 20, 'x': 40 }
print(set(dict_one.keys()).intersection(set(dict_two.keys())))
|
51494b2b7182ad866218499953546eb6f4ec9af7 | SBazelais/ATM-application | /Transactions.py | 1,081 | 3.765625 | 4 |
def withdraw(amount):
"""function to add elements to withdraw text file"""
tran_list = [amount]
f = open('withdraw_tran.txt', 'a')
space = '\n'
for item in tran_list:
f.write(item + space)
f.close()
def deposit(amount):
"""function to add elements to deposit text file"""
tran_... |
f23e9eceaf0e942e1f11178367e1e9d4e44c571e | Mantvydas-data/pands-problem-sheet | /secondstring.py | 348 | 3.953125 | 4 | #A program that asks user to input a string and outputs every second letter in reverse order.
#Author: Mantvydas Jokubaitis
sentence = input("Please input a sentence: ")
example = "The quick brown fox jumps over the lazy dog."
print("Example sentence: ", example, "Every second letter in reverse order: ", example[::-2]... |
1807440261891f52c2481b57be4c18bf0f80d364 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileInteraction/filepracticeread.py | 383 | 3.875 | 4 | # This program reads and displays the contents of the philosophers.txt file
def main():
# Open the file named philosophers.txt
f = open('philosophers.txt', 'r')
# Read the files contents
f_contents = f.read()
# Close the file
f.close()
# Print the data that was read into memo... |
89070b8ff30187306732fa9e24fa24f32d6cc44f | DayGitH/Python-Challenges | /DailyProgrammer/DP20130111C.py | 1,718 | 3.6875 | 4 | """
[01/11/13] Challenge #116 [Hard] Maximum Random Walk
https://www.reddit.com/r/dailyprogrammer/comments/16dbyh/011113_challenge_116_hard_maximum_random_walk/
# [](#HardIcon) *(Hard)*: Maximum Random Walk
Consider the classic random walk: at each step, you have a 1/2 chance of taking a step to the left and a 1/2 ch... |
e9956b768784a801ced97be6ca9a72e68e4997d8 | PdxCodeGuild/Intro-to-Computer-Programming | /example-files/boolgame.py | 2,217 | 4.15625 | 4 | #!/usr/bin/env python
"""
PDX Code Guild Curriculum. Boolean Game.
"""
__author__ = "Christopher Jones"
__copyright__ = "Copyright 2016, PDX Code Guild"
__version__ = "0.1"
import random
bools = {
'not False': not False,
'not True': not True,
'True or False': True or False,
'True or T... |
2c4ba9ad889876cf81ba3933a76d832542c77ae3 | ventisk1ze/leetcode | /smaller_then_current.py | 155 | 3.78125 | 4 | nums = [8,1,2,2,3]
res = []
for num in nums:
count = 0
for n in nums:
if num > n:
count += 1
res.append(count)
print(res) |
dc11e0b4564d1f26088b267a5425762fe189ede2 | Sebastian-WR/Python-Exercises | /ses3/Mandatory_Handin_Sebastian_Wulff_Rasmussen.py | 3,780 | 4.34375 | 4 | # 1: Model an organisation of employees, management and board of directors in 3 sets.
board = ['Benny','Hans', 'Tine', 'Mille', 'Torben', 'Troels', 'Søren']
management = ['Tine', 'Trunte', 'Rane']
employees = ['Niels', 'Anna', 'Tine', 'Ole', 'Trunte', 'Bent', 'Rane', 'Allan', 'Stine', 'Claus', 'James', 'Lars']
# who ... |
22fecd51a6c0d2736dc02de440b360fcbcf11a9e | leoscalesi/Mini-Games | /mini juegos1.py | 12,491 | 3.734375 | 4 | import tkinter as tk
ventana=tk.Tk()
ventana.title(" MINI GAMES ")
ventana.geometry('1200x720')
ventana.resizable(False,False)
import math
def calculadora():
pisos=int(piso.get())
metros=2.5*pisos
vf=math.sqrt(2*9.8*metros)
t=round(vf/9.8,2)
km=vf/1000
kmh=round(km/0.0002777778,2)
resulta... |
fbcf2d7048347b75c446bae76ebc30d5d2cdbf18 | Nick12321/python_tutorial | /guessing_game.py | 1,631 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 21:07:07 2020
@author: nick
"""
###make import statements in homework5_8.py
# Make Guess_Game class to store guess number, tries per game.
# method to generate random number, check guess (low or high)
# Game__init__ generate and store random num... |
8b48ca9b4b4630345ec4cf1ddc6b76af3be01f5a | manjunatha-kasireddy/python-programs | /numpyufuc/ufunc.py | 183 | 3.6875 | 4 | # x = [1, 2, 3, 4]
# y = [4, 5, 6, 7]
# z = []
# for i, j in zip(x, y):
# z.append(i + j)
# print(z)
import numpy as np
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = np.add(x, y)
print(z) |
997d6ca85a770be84e4b2fd3f2bde28c77606c2a | VasssilPopov/AllSpiders | /_LIBRARY/HelperTools.py | 10,528 | 3.625 | 4 | # # -*- coding: utf-8 -*-
import jsonlines
import glob
#-------------------------------------------------------------------------
'''
It maps month name to month sequential number.
It returns '??' when the name is not found
'''
def bgMonthstoNumber(monthName):
monthName=monthName.lower()
... |
62305da2aa292c8326370c9540de5182cdc8fdfa | RWEngelbrecht/Learning_Python | /intermediate_stuff/static_and_class_methods.py | 743 | 3.875 | 4 | ## static and class methods
class Person(object):
# variable that belongs to class
population = 50
def __init__(self, name, age):
self.name = name
self.age = age
Person.population += 1
@classmethod # decorator
def getPopulation(cls): # method belonging to the class, not an ... |
5c7ccc3ffd9242ca29036e21fa81aa262a5bc904 | whitehamster26/python-project-lvl1 | /brain_games/games/progression.py | 375 | 3.609375 | 4 | from random import randint
DESCRIPTION = 'What number is missing in the progression?'
def start():
start = randint(1, 20)
step = randint(1, 10)
items = [str(start + item*step) for item in range(9)]
missed_item = randint(0, len(items))
answer = items[missed_item]
items[missed_item] = '..'
... |
07027e00071ddddf5d5917cb88259cd7dbab3dba | wfeng1991/learnpy | /py/leetcode/79.py | 989 | 3.6875 | 4 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def exist0(board,x,y,word,idx):
if x==len(board) or y==len(board[0]) or x<0 or y<0:
return False
if idx==len(word)-... |
75b0dba5462c02e098431800b76fe83c3aeafbc5 | maxfilter/project-rosalind | /Bioinformatics_Stronghold/REVC/revc.py | 469 | 4.03125 | 4 | '''
Complementing a Strand of DNA
Given: A DNA string s of length at most 1000 base pairs
Returns: The reverse complement s^c of s
'''
import sys
conjugate = {
'A' : 'T',
'C' : 'G',
'G' : 'C',
'T' : 'A',
}
with open(sys.argv[1], 'r') as f:
s = f.read().strip()
sequence = s[::-1] #reverse the str... |
24e7e7f55ede11703b4dfe1ae983aa92fa568e51 | jenkin-du/Python | /pyhon36_study/palindrome.py | 467 | 3.6875 | 4 | # 筛选回数
def is_palindrome(num):
if 10 > num > 0:
return True
numlist = []
low = num % 10
while num > 0:
numlist.append(low)
num //= 10 # 整除
low = num % 10
lens = len(numlist)
i = 0
j = lens - 1
while i < j:
if numlist[i] != numlist[j]:
... |
abc5e53f746f02d56b49512bc0fecca7a62577a0 | drewriker/USU-CS-1400 | /Assignment 3/task1.py | 860 | 3.90625 | 4 | # Andrew Riker
# CS1400 - LW2 XL
# Assignment #03
# enter investment amount
investmentAmt = eval(input("Enter the starting investment amount: $"))
# enter monthly payment amount
monthlyPay = eval(input("Enter monthly payment amount: $"))
# enter annual interest rate
annualInterestRate = eval(input("Enter the ... |
caaf8bc9d9eed74a4a65b2c1cdd8349cfacc6007 | BryceStansfield/Prime-Factor-Programming | /interpreter.py | 2,026 | 3.609375 | 4 | class program:
memory = [];
integer = 1;
instructions = [];
factors = [];
memPointer = 0;
inPointer = 0;
class primeIterator:
def __init__(self):
self.primes = [2];
def __iter__(self):
return(self);
def __next__(self):
test = self.primes[-1]+2;
while(1):
divisible = False;
index = 1;... |
59935e39718a69ccd2438c8ebfb6d77be566177d | JerinPaulS/Python-Programs | /MaximalSquare.py | 1,221 | 3.640625 | 4 | '''
221. Maximal Square
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
Example 2:
Input: matrix = [["0","1"],["1"... |
6595f00bfdec1ba02377619d833900c33fae064e | quadrant26/python | /Tkinter/test_dialogs_modules3.py | 728 | 3.53125 | 4 | '''
标准对话框
messagebox
filedialog
colorchooser 颜色选择对话框
arguments:
title 标题
message 消息内容
options 参数
default:
icon 图标
parent
'''
from tkinter import *
root = Tk()
'''
askopenfilename()
asksavefilename()
指定文件的后缀
defaultextension = ".py"
文件... |
4ef6e74afa7facf7f15931735e3f4dc657de454e | greenteemo/Murray-s-lectures | /FIT5191/NP07/getpath.py | 353 | 3.609375 | 4 | net = {
'x':['u','v','w','y'],
'y':['x','w','z'],
'z':['y','w'],
'u':['w','x','v'],
'v':['u','w','x'],
'w':['u','v','x','y','z']
}
def dfs(path, dest):
if(path[-1] == dest):
print(path)
return
for node in net[path[-1]]:
if(node not in path):
dfs(path+node, dest)
path = input("start node:")
dest = in... |
6f057b80b2c6f5cb8822a661d16180face891e3d | jasmineseah-17/euler | /10_Summation_of_primes.py | 286 | 3.625 | 4 | #Problem 10
def is_prime(n):
if n == 1:
return False
for i in range(2,int(n**(0.5))+1):
if n%i==0:
return False
count = 0
total = 0
n = 1
while n < 2000000:
n += 1
if is_prime(n) != False:
count += 1
total += n
print(total)
|
452c906f3d2753e9ceecd8b37ba7506e83d8edf0 | justgolikeme/My_MachineLearning | /the_use_Numpy/the_learn_from_NumpyChineseWebsite/Broadcasting/Demo.py | 2,753 | 4.0625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Mr.Lin'
__date__ = '2019/11/15 16:20'
import numpy as np
"""
广播Broadcasting
广播是一种强有力的机制,它让Numpy可以让不同大小的矩阵在一起进行数学计算。我们常常会有一个小的矩阵和一个大的矩阵,然后我们会需要用小的矩阵对大的矩阵做一些计算。
"""
# 举个例子,如果我们想要把一个向量加到矩阵的每一行,我们可以这样做:
# We will add the vector v to each row of the matrix x,
# storing the resul... |
9e451bdc3609320912e3fe1e49ac5abd8ad7e8d0 | smgraywood/Code_In_Place | /Khansole Academy.py | 1,591 | 4.28125 | 4 | Now that you’ve seen how programming can help us in a number of different areas, it’s time for you to implement Khansole Academy—a program that helps other people learn! In this problem, you’ll write a program in the file khansole_academy.py that randomly generates a simple addition problem for the user, reads in the a... |
6025948af67a72c2c1ace6291701efd402f049c9 | Improbus/DrexelCourseWork | /CS265/Lab4/s2.py | 528 | 3.640625 | 4 | #!/usr/bin/python
f = open( "students.csv", "r" ) # open file for reading (default)
# get rid of leading/trailing whitespace (spaces, tabs, newlines)
l = f.readline()
while l :
l = l.strip( ' \t\n' )
noname = l.strip('abcdefghijklmnopqrstuvwxyz, ')
numberlist = noname.split(",")
fsum = 0
for i in numberlist :
... |
80bbd5c218109d55621c3b06824d31fbe15a528e | adiaz14/exercism_exercises_python | /armstrong-numbers/armstrong_numbers.py | 271 | 3.75 | 4 | def is_armstrong_number(number):
sum = 0
temp = number
exp = len(str(number))
digit = 0
while temp > 0:
digit = temp % 10
sum += digit ** exp
temp //= 10
if number == sum:
return True
else:
return False
|
b8f5f4feaddec18742129b234d4d42be73598367 | HBinhCT/Q-project | /hackerrank/Algorithms/Accessory Collection/solution.py | 1,150 | 3.609375 | 4 | #!/bin/python3
import os
#
# Complete the acessoryCollection function below.
#
def acessoryCollection(L, A, N, D):
#
# Write your code here.
#
if D > A or D > N or N > L:
return 'SAD'
if D == 1:
return str(L * A)
n_rest_max = (N - 1) // (D - 1)
max_result = -1
for n_re... |
9418d2daeeb583c304be3129670c0fb932999f55 | tierchen/exercism-python-solutions | /allergies/allergies.py | 586 | 3.703125 | 4 | class Allergies(object):
allergies = ['eggs',
'peanuts',
'shellfish',
'strawberries',
'tomatoes',
'chocolate',
'pollen',
'cats']
allergies_mapping = {x: 2**i for i, x in enumerate(allergies)}
... |
e82118efcf764d94426e616c8c635801eeda53b3 | emreg00/toolbox | /dict_utilities.py | 1,129 | 3.546875 | 4 |
def keep_only_with_overlapping_values(key_to_values, set_to_overlap, n_min_overlap):
"""
Keeping it non-one-liner for potential future feature additions based on values
"""
key_to_values_mod = {}
for key, values in key_to_values.iteritems():
values &= set_to_overlap
if len(values) >= n_min_overla... |
9ab2cc6f379d282db130ea55eb76db9937a3b911 | Rashmidore/python-learning | /7conditional.py | 402 | 4 | 4 | def mean(value):
if type(value) == dict:
the_mean = sum(value.values()) / len(value)
else:
the_mean = sum(value) / len(value)
return the_mean
temp = {"mon":8,"tue":6,"wed":9}
date = (11,12,13,14)
print(mean(date))
print(mean(temp))
if isinstance(x, int) or isinsta... |
ab0d07cd3eddf6b466fcdb7ae6ba2e90b6817082 | ruduran/advent_of_code | /2017/python/src/aoc/day03/part1.py | 1,597 | 3.6875 | 4 | #!/usr/bin/env python
from . import BaseProcessor
class Processor(BaseProcessor):
def calculate_steps(self):
if self.number == 1:
return 0
current_number = 1
side_size = 0
while current_number < self.number:
side_size += 2
current_number += 4 *... |
1adab35d4f24f363da8ef71f6ef7132391677f82 | LionKimbro/panthera | /listdict.py | 4,642 | 3.515625 | 4 | """listdict.py -- quickly search & filter a list of dictionaries
Experimental idea, research.txt 0K2
Import with:
-----------------------------------------------------------
from listdict import cue, val, val01, req, srt
from listdict import EQ, NEQ, GT, LT, GTE, LTE
from listdict import CONTAINS, NCONTAINS, WITHIN... |
0ed1d616c7d2d9b196fcdda50520c829f3b4137a | QinGeneral/Algorithm | /sort/insert_sort.py | 1,551 | 3.921875 | 4 | # 插入排序
# 原地排序算法
# 稳定排序算法
# 时间复杂度:
# 最好 O(n)、最坏 O(n^2)、平均 O(n^2) ... |
11ff275bba81d2ddcf7713f4849d3b392f60a824 | palfi-andras/NBAPredictor | /NBAPredictor/core/positions.py | 1,029 | 4.0625 | 4 | from enum import Enum
class Position(Enum):
"""
An enum to represent the types of positions that are possible for Players to play in the NBA
"""
PG = 1 # Point Guard
SG = 2 # Shooting Guard
SF = 3 # Small Forward
PF = 4 # Power Forward
C = 5 # Center
def convert_to_position(char... |
064ebb94b84b0d3cddfacef52d391590f16ebfd6 | a652895216/example_of_qianduan | /pachong2/pachong4 xml.py | 1,858 | 3.65625 | 4 | #xml 就是传数据 w3school
#xpath 是一门查找信息的工具 w3cschool 开发工具chrome插件 百度安装
'''
1.常用路径表达式:选取此节点的所有子节点
/:从根节点开始
//:选取元素,而不考虑元素的具体为止
. :当前节点
.. :父节点
@ :选取属性
2. 谓语(predicates)
谓语用来精确查找
/bookstore/book[1] :选取第一个属于bookstore下的叫book的元素
/bookstore/book[last()]: 选取最后一个
/bookstore/book[last()-1]:选取最后第二个
/bookstor... |
858fc3582a0f8395546821ee85868fe34f0c7f9d | koalaboy808/Labor2Day_2.0 | /viewdatabase.py | 616 | 3.703125 | 4 | #!/usr/bin/python
import sqlite3
conn = sqlite3.connect('app.db')
print "Opened database successfully";
cursor = conn.execute("SELECT username, _password from Employers")
for row in cursor:
print "USERNAME = ", row[0]
print "PASSWORD = ", row[1], "\n"
cursor2 = conn.execute("SELECT request_title, emp_id fr... |
59b70ab9dc9a22d789f298055688447afdc8c7af | yskang/AlgorithmPractice | /leetCode/valid_parentheses.py | 536 | 3.546875 | 4 | # Title: Valid Parentheses
# Link: https://leetcode.com/problems/valid-parentheses/
class Problem:
def is_valid(self, s: str) -> bool:
last_len = len(s)
while s:
s = s.replace('()', '').replace('[]', '').replace('{}', '')
if len(s) == last_len:
break
... |
02446cc7e567e30ce3fe9d71ac7263345bb88981 | cinvilla/Python_Class10272018 | /Materia Vista en Clase/command_class_forloops10272018.py | 1,315 | 4.375 | 4 | # Primer ejemplo con loops - for
for indice, elemento in enumerate (['maria', 'jose', 'pedro', 'juan']):
print('El indice {} para el valor {}' .format(indice, elemento))
# enumerate - para obtener el índice de posición junto a su valor correspondiente.
# Primer ejemplo con loops - for
print()
for indice, elemento... |
52409b17f224a2cfc11156c218968188885abacb | oscarliu99/partia-flood-warning-system | /floodsystem/geo.py | 4,814 | 3.71875 | 4 | # Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from .utils import sorted_by_key # noqa
from floodsystem.stationdata import build_station_list
from math import radians, cos, sin, asin, sqrt
def haversine(point... |
2726bb722478687e2c18d793f6dfab2809ac7d88 | LeoneVeneroni/python | /exercicios/Aula15/aula15_exercicio1.py | 2,782 | 3.875 | 4 | class MeuTempo :
def __init__ (self , hrs = 0 , mins = 0 , segs = 0):
""" Criar um novo objeto MeuTempo inicializado para hrs, min, segs.
Os valores de mins e segs podem estar fora do intervalo de 0-59,
mas o objecto MeuTempo resultante será normalizado. """
# Calcul... |
ebecca8802c68d87f0c447eea2dee2261f0a098f | KorryKo/PythonPractice | /python-check/while «Количество четных элементов последовательности» _The number of even elements of a sequence_.py | 392 | 4.09375 | 4 | # «Количество четных элементов последовательности» "The number of even elements of a sequence"
# Определите количество четных элементов в последовательности, завершающейся числом 0.
n = -1
i = -1
while n != 0:
n = int(input())
if n % 2 == 0:
i += 1
print(i)
|
a0230d829227619ca7fed70823ec06d5c2a8ec4d | torenord/julekalender | /luke7.py | 417 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Luke 7
# Finn summen av alle positive heltall mellom 0 og 1000 som er har 7
# som en primtallsfaktor, der det reverserte tallet også har 7 som en
# primtallsfaktor.
# For eksempel teller 259 da en får 952 om en reverserer sifrene og
# begge disse tallene har 7 som en p... |
d9e1307745e50b054898fe89276818ece0cc7428 | 9zemel/python_course | /LessonSixth/diary.py | 134 | 3.625 | 4 | name = input("Enter you diary's name")
with open(name, 'a') as diary:
data = input('Enter your topic:\n')
diary.write(data)
|
fafa37c81f2d38c75741594fbee51511f7a2f647 | huayuhui123/prac05 | /word_occurrences.py | 263 | 3.75 | 4 | sentence={}
for word in input("Text:").split():
if word in sentence:
sentence[word]+=1
else:
sentence[word]=1
n=max(len(word) for word in sentence)
for key,value in sorted(sentence.items()):
print("{:<{}}{}".format((key+':'),n,value))
|
5808f003ea584c27c5ca885f7841293a6f30c141 | iamyoungjin/algorithms | /Basic/prime_number_basic.py | 333 | 3.734375 | 4 | #basic
#소수 판별 함수 (2이상의 자연수에 대해)
#시간 복잡도 : O(X)
def is_prime_number(x):
for i in range(2,x): #2부터 (x-1)까지 모든 수를 확인하며 x가 해당 수로 나누어 떨어지면 소수가 아님
if x%i == 0:
return False
return True
print(is_prime_number(7)) |
22adba30fa0648a2b41ec230fad4a998853236c7 | sukilau/data-structures-and-algorithms | /python/slliststack.py | 1,093 | 3.96875 | 4 | '''
Implementation of Stack using Singly Linked List
Basic operations:
get(i) O(n)
set(i,x) O(n)
add(i,x) O(n)
remove(i) O(n)
push(x) O(1)
pop() O(1)
peek() O(1)
getSize() O(1)
isEmpty() O(1)
'''
class Stack(object):
class Node(object):
def __init__(self, x):
self.value = x
self.next = None
... |
22a462de8d06ea2a477ecba0aa1ac68c6b4387b0 | littleliona/leetcode | /medium/138.copy_list_with_random_pointer.py | 2,033 | 3.625 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rt... |
12a33a3a7db19a8ed155f0a1a668d595054e07cb | JanSnobl/Madlibs | /madlibs.py | 2,086 | 4.125 | 4 | """ this program is telling story and you have to answer if the question is asked
Jan Snobl
"""
#The template for the story
STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to ... |
4cd3e5d16ea83232b6c2f51ad70a9cf3662ea44d | uibcdf/OpenPocket | /openpocket/alpha_spheres/alpha_spheres.py | 7,902 | 3.90625 | 4 | import numpy as np
from scipy.spatial import Voronoi
from scipy.spatial.distance import euclidean
class AlphaSpheres():
"""Set of alpha-spheres
Object with a set of alpha-spheres and its main attributes such as radius and contacted points
Attributes
----------
points : ndarray (shape=[n_points,3... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.