blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4009f1adddb7dfee2b442da308572a635616057e | haotianzhu/Questions_Solutions | /search_rotated_sorted_array/solution.py | 1,270 | 3.796875 | 4 | class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return -1
lo = 0
hi = len(nums)-1
old_size = len(nums)
# if not rotated
if nums[lo] <= nums[hi]:
return self.binary_search(nums,lo,hi+1,target)
else:
# ext... |
bb21534050939709853ae2cb1a08aabaa398b701 | haotianzhu/Questions_Solutions | /trapping_rain_water/solution.py | 1,170 | 3.828125 | 4 | class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
left = 0
right = len(height)-1
total_area = 0
if height[left] <= height[right]:
m = left
else:
m =right
while(left < right):
if height[left] <= height[right]:
# move m... |
0288929f388cb0a9abacd32f1a7ae05247710a14 | kkjasoncheung/CSCA20-tests | /labs/lab4_unittest.py | 3,555 | 3.59375 | 4 | import unittest
from lab4 import *
class TestCountLetter(unittest.TestCase):
errorMessage = "Incorrect number of occurrences for {} in {}"
def test_multiple_occurrences(self):
string = 'hippopotamus'
ch = 'p'
expected = 3
result = count_letter(string, ch)
self.as... |
b578bd38813c54ce00f9c07b4eed6d17d5e52554 | VictorMello1993/CursoAnaliseSentimentosTextos | /testeNLTK.py | 1,054 | 3.875 | 4 | import nltk
texto1 = 'Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow'
texto2 = 'Olá, meu nome é Victor, tudo bem?'
# print(texto1.split('.')) #Maneira manual (versão em Python)
# frases = nltk.tokenize.sent_tokenize(texto1) #Separação de frases usando o recurso... |
ec14175e97f83328e2cafbd220fbbdd2008132ad | hc-fig/brainf-workshop | /Tape.py | 922 | 3.734375 | 4 | """
In this file we represent the infinite tape which is the state
of a brainf machine
"""
# All classes inherit from Object by default
class Tape:
"""
Invariant: The pointer is valid.
"""
def __init__(self):
self.tape = [0]
self.pointer = 0
def getLen(self):
return le... |
140a7abfc1606f67a4b385fe449765d0cf2e5525 | muizahmed/life-in-weeks | /main.py | 281 | 3.625 | 4 | age = input("What is your current age?")
age_as_int = int(age)
days_left = (75 - age_as_int) * 365
weeks_left = (75 - age_as_int) * 52
months_left = (75 - age_as_int) * 12
message = (f"You have {days_left} days, {weeks_left} weeks, and {months_left} months left.")
print(message)
|
45338cc774949ac4a0bbba2d9afc2ae142f34d5f | Jeremiah9000/prime_numbers_truncatable | /prime_numbers_truncatable_faster.py | 1,477 | 4.0625 | 4 | import time
import math
def timed_quit():
print('\ntime:\n' + str(time.time() - start))
quit()
number0 = int(input('enter number to see if it is truncatable: \n->'))
start = time.time()
def check_prime(number):
print(f'current time: {time.time() - start}')
print(number)
if numb... |
f752055a3d6efdade46f93d811e10b27c3474e13 | HohenYao/pdsnd_github | /bikeshare.py | 13,436 | 4.0625 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
#add month_list, DayOfWeek_list by Hohen
month_list = ['january', 'feburary', 'march', 'april', 'may', 'june','all']
DayOfWeek_l... |
4578a059ebb7dc45060633612042751c499ba068 | darcy3000/MNIST_classification | /ann.py | 3,088 | 3.515625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#Loading the dataset
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
n_nodes_hl1 = 100
n_nodes_hl2 = 100
n_nodes_hl3 = 100
n_nodes_hl4 = 100
n_classes = 10
batch_size = 100
# PLACEHOLDERS
x = tf.placeholder(tf.float32... |
3e23dc4f3229ae3f223d1afcbc586ce69745bb55 | bkaczor00/python-challenge | /PyPoll/.ipynb_checkpoints/main-checkpoint.py | 1,614 | 3.578125 | 4 | import csv
import os
path = "election_data.csv"
with open(path, "r") as file:
csv_reader = csv.reader(file)
print("Election Results")
print("--------------------")
header = next(csv_reader)
row_count = sum(1 for row in file)
print("total votes: "+ str(row_count))
print("----... |
04a6c1222cc822ef77db1b6c5348ad76d382ea39 | qingbol/ClmsTOPL | /toplProject6/cases/recursiveFunc2.py | 86 | 3.8125 | 4 | def f(x,y):
if x==1:
return 1
else:
return x*y*f(x-1,y-1)
print f(3,3)
|
dbeea42d0a9e19192f2c4061df76089edfa5ab88 | REDVM/birthday-paradox | /birthday.py | 670 | 3.90625 | 4 | # Birthday Paradox in Python
# Considering that birthday are independant and identiquely distribued
# by a uniform law.
from __future__ import print_function
import numpy as np
def same_birthday(n_people):
# Generate n birthday dates
dates = np.random.randint(0, 365, size=n_people)
# If at least 2 ... |
075f64b6c1c9b52e9a14a46af11ddadf39eac6d5 | laofuLF/DataStructureAlgorithm | /Graph/adjacency_matrix_to adjacency_list.py | 567 | 3.5625 | 4 | # Convert an unweighted undirected graph edges from adjacency matrix to list with starting index 1
from collections import defaultdict
def matrix_to_list(matrix):
graph = defaultdict(list)
# Enumerate list from index of 1, eliminate 0s
for i, v in enumerate(matrix, 1):
for j, u in enumer... |
76081c4204e93d1e07d72f975d15ee24da68e95e | brittainhard/sicp | /py/116.py | 373 | 3.640625 | 4 | def expt(b, n):
return expt_iter(b, n, 1)
def expt_iter(b, counter, product):
print(b, counter, product)
if counter == 0:
return product
elif counter % 2 == 0:
return expt_iter(b, counter / 2, product ** 2)
else:
return expt_iter(b, counter - 1, (b * product))
def expt(b, n... |
5ec6b294fde029d0bfa6b3a340429bb789e9d29b | Marcialbarajas/Scientific-Computing-with-Python---Certification | /Arithmetic Formatter/Arithmetic_arranger.py | 2,002 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 23:20:38 2021
@author: Marcial
"""
import re
def arithmetic_arranger(problems, solve=False):
# First of all, we have to check if there are more than 4 problems in the array
if (len(problems) > 5):
return "Error: Too many problems."
#We defi... |
13c45fcd1eace3dd0475899bcf11836591421b37 | magentapowa/codility-tasks | /L7-Nesting.py | 475 | 3.5625 | 4 | # Lesson: 7 - Stacks and Queues
# Excersice: Nesting
# link: https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/
# Score : 100%
def solution(S):
lefts = S.count('(')
rights = S.count(')')
if lefts != rights:
return 0
open = 0
for i in S:
if i ... |
e5058784419d8ed849e7e0d2b884779a114861d0 | AshFromNowOn/AdventOfCode2018 | /day2.py | 648 | 3.6875 | 4 | import sys
import collections
with open("sourceFiles/day2input.txt") as f:
total_2 = 0
total_3 = 0
for line in f:
line = line.strip('\n')
line_count = collections.Counter(line)
line_has_2 = False # if the line has a character repeated exactly 2 times
line_has_3 = False # if ... |
7780f37587dc6bc07109b72911dc720f332268ad | garimadawar/LearnPython | /DynamicAvg.py | 262 | 4.1875 | 4 | print("Calculate the sum and average of two numbers")
number1 = float(input("Enter the first number"))
number2 = float(input("Enter the second number"))
print("the sum equals to " , number1 + number2)
print("average equals to " , (number1 + number2) / 2)
|
c1fa73caced9e5aeafe0e282ae88e6cb5c58a7fd | justinhinckfoot/Galvanize | /github/Unit 1 Exercise.py | 1,662 | 4.34375 | 4 | # Unit 1 Checkpoint
# Challenge 1
# Write a script that takes two user inputted numbers
# and prints "The first number is larger." or
# "The second number is larger." depending on which is larger.
# If the numbers are equal print "The two numbers are equal."
first = int(input('Enter first test value: '))
second = int... |
deae1d1f2362c3263638badf8226890c8be9f1b2 | oswaldospn/TSOGH | /Listas_Python/Lista 001.py | 3,187 | 4.28125 | 4 | #Ex.01
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
num3 = int(input('Digite mais um número: '))
média = (num1 + num2 + num3) / 3
print('A média entre os três números é: ' + str(média))
#Ex.02
num = int(input('Digite um número: '))
print('Sucessor:', num + 1, '\nAntecessor:', num... |
67d6434991960bc00dc515d4067313809af929a6 | OliverSmith95/i_O | /Agent_Framework_2.py | 1,911 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 14:14:00 2018
@author: gy18os
"""
import random
class Agent():
#x and y is different values from the model and class.
#define and initate agents - self is a parameter within python inorder create an object referennce.
def __init__ (self, environment): # Introduce... |
ee89d3b2a83e0ec7118165333ca4f59471057902 | Nikhil-Rajendra-Patil/Git_Training | /Hands_On_1.py | 132 | 3.84375 | 4 | input_string = input()
count = 0
vowels = 'aeiouAEIOU'
for i in input_string:
if i in vowels:
count += 1
print(count) |
1a8e9a0e54035d5bc47c2325ab1a4e58d96e1f3f | Nikhil-Rajendra-Patil/Git_Training | /Player_IRC.py | 1,555 | 3.734375 | 4 | class Player:
def __init__(self,playerName,playerCountry,playerAge,noOfMatches,noOfRuns,noOfWickets):
self.playerName = playerName
self.playerCountry = playerCountry
self.playerAge = playerAge
self.noOfMatches = noOfMatches
self.noOfRuns = noOfRuns
self.noOfWickets = noOfWickets
cla... |
d01c51e1b6be53b5da762e75a838decc1ac4ee3c | Dragonet-D/python3-study | /第四章/迭代器和生成器.py | 2,022 | 3.59375 | 4 | # 列表生成式
'''
将临时变量i存到i再*2
'''
x = [i * 2 for i in range(10)]
print(x)
a = []
for i in range(10):
a.append(i * 2)
print(a)
def func(i):
print(i)
y = [func(i) for i in range(10)]
# 通过列表生成式,我们可以创建一个列表;但是收到内存的限制;而且包含一个一百万元素的列表,不仅占用很大的储存空间.如果我们只要一小部分就浪费空间
print(range(10))
# 生成器
t = (i * 2 for i in range(1000000... |
2c86f82938fc6dd74902d3b17969b435f73a0f49 | Dragonet-D/python3-study | /10-30/集合.py | 1,801 | 4.15625 | 4 | # 去重 关系测试 测试两个列表的 交集 并集
# 集合也是无序的
a = set([3, 4, 5, 6, 2, 3])
print(a)
list_1 = [1, 3, 4, 5, 234, 23, 2, 2, 3, 4, 5]
list_1 = set(list_1)
list_2 = set([2, 3, 45, 4, 6, 12, 34])
list_3 = set([1, 2, 4])
'''
print(list_1, type(list_1)) # <class 'set'>
print(list_1, list_2)
# 取交集 intersection &
print(list_1.intersectio... |
62f6a1b0e5f7b7200dcc288813b35c55126e6bc5 | Dragonet-D/python3-study | /第七章/7-Socek服务器端.py | 527 | 3.671875 | 4 | # 服务器端
import socket
server = socket.socket()
server.bind(('localhost', 6969)) # 绑定要监听的端口
server.listen() # 监听 listen(5) 最多挂起几个链接
print('我要开始等电话了')
# 返回两个字 链接实例, 对方地址
# conn就是客户端连过来而在服务端为生成的链接实例
conn, addr = server.accept() # 等电话打进来
while True:
# print(conn, addr)
print('电话来了')
data = conn.recv(1024)
pri... |
27ac45135335c69de26a9f29da07003147a4e275 | Dragonet-D/python3-study | /7-28/for.py | 835 | 3.75 | 4 | '''
age_of_oldboy = 56
for i in range(3):
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy:
print("yes you got it")
break
elif guess_age > age_of_oldboy:
print('123')
else:
print('234')
else:
print('you have tried too many times')
'''
#for i in range(0,10,2):
# print("loop:"... |
2cc7357dbda3cda28068bcc901d8836c21920186 | martymonero/ctf | /2018/rctf/misc/numbers-game/mastermind-codebreaker.py | 3,696 | 3.609375 | 4 | from random import randint
import itertools
SECRET_LENGTH = 4
num = [1, 2, 3, 4, 5, 6]
num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
secret = [randint(min(num),max(num)),randint(min(num),max(num)),randint(min(num),max(num)),randint(min(num),max(num))]
#secret = [1,1,4,1]
if not len(secret) == SECRET_LENGTH:
exit()
print(... |
ca465b570b2d7f29b76d97243f2c590fcc34b457 | Sudhanshu-Srivastava/hackerrank-1 | /python/introduction/whats-your-name.py | 279 | 3.875 | 4 | #https://www.hackerrank.com/challenges/whats-your-name
import fileinput
#Input
first_name, last_name = fileinput.input()
first_name = first_name.strip()
last_name = last_name.strip()
#Solve and output
print("Hello %s %s! You just delved into python." % (first_name, last_name)) |
865e576182cf9a5cf9b12b482322819f90e07ca0 | Sudhanshu-Srivastava/hackerrank-1 | /python/introduction/finding-the-percentage.py | 380 | 3.609375 | 4 | #https://www.hackerrank.com/challenges/finding-the-percentage
import fileinput
#Input
lines = fileinput.input()
#Solve
grades = dict()
N = int(lines[0])
for i in range(1, N+1):
line = lines[i].split(" ")
name = line.pop(0)
grades[name] = grades.get(i, []) + list(map(float, line))
marks = grades[lines[N+... |
d594a43ce5c139369645eed13363d8747c63f1e9 | yash001dev/learnpython | /_30.Dictionary_Project2.py | 215 | 3.859375 | 4 | #Emoji Converter Using Dictonary
message=input(">")
words=message.split(' ')
emojis={
":)":"Happy",
":(":"Sad"
}
output=""
for word in words:
output+=emojis.get(word,word)+" "
print(output)
|
c885eddd2134ce420caa34892e7b4bd7cf6d266a | yash001dev/learnpython | /_43.py | 388 | 3.875 | 4 | #Generating Random Value In Python
import random
members=['john','Mary','Bob','Mosh','Yash','Js']
leader=random.choice(members)
print(leader)
#Roll Dice
#Create Class Dice and add methods roll
class Dice:
def roll(self):
first=random.randint(1,6)
second=random.randint(1,6)
retur... |
f0ef250c95acc6eef0ee2796bbfb9caa026fcf9f | yash001dev/learnpython | /_9.If_Statement.py | 271 | 4.0625 | 4 | #If Statements
is_hot=False
is_cold=False
if is_hot:
print("It's A Hot Day")
print("Drink Plenty Of Water...")
elif is_cold:
print("It's a Cold Day")
print("Wear Warm Clothes")
else:
print("It's a Lovely Day...")
print("Enjoy A Day...")
|
b8980967816db471789706f6084b7c009e138765 | yash001dev/learnpython | /_35.Class.py | 207 | 3.546875 | 4 | #Classes In Python
class EmailClient:
def move(self):
print("move")
def draw(self):
print("draw")
obj1=EmailClient()
obj1.draw()
obj1.move()
obj1.x=5
print(obj1.x)
|
9519d3910c4cd9122b1cb633016d1f72e5c3a080 | yash001dev/learnpython | /_13.if_Project.py | 248 | 4.125 | 4 | weight=input("Enter Weight:")
unit=input('(L)bs or (K)g:')
if unit.upper()=="L":
converter=float(weight)*0.45
print(f"You are {converter} Kilos")
else:
converter=float(weight)/0.45
print(f"You are {converter} Pounds")
|
95350d0995ec53e75601c3db0010b9da7ce90ebe | ricek/lpthw | /ex11/ex11-1.py | 265 | 4.40625 | 4 | # Prompt the user to enter their name
# end='' arg tells print function to not end the line
print("First Name:", end=' ')
first = input()
print("Last Name:", end=' ')
last = input()
# Prints out formatted string with the given input
print(f"Hello {first} {last}")
|
9013585a902e8aa2384f162b4a8c25e730429778 | arossholm/Py_Prep | /egg_problem.py | 1,347 | 4.125 | 4 | # A Dynamic Programming based Python Program for the Egg Dropping Puzzle
# http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
INT_MAX = 32767
def eggDrop(n, k):
# A 2D table where entery eggFloor[i][j] will represent minimum
# number of trials needed for i eggs and j floors.
eggFl... |
a6050335ed99aff48731abcc38aa4bf85a7a69ac | OneHalf3544/try-robot-framework | /src/ValidNumberSolution.py | 2,062 | 3.65625 | 4 | import re
class Solution:
def isNumber(self, s: str) -> bool:
s = s.strip(" ")
if len(s) == 0:
return False
split = s.split("e")
if len(split) > 2:
# several 'e'
return False
if len(split) == 2 and not self.isIntegerNumber(split[1]):
... |
1422fe5f8aa1cc107078478fde45973a9f234057 | fronzag/stmetrics | /stmetrics/basics.py | 4,498 | 3.578125 | 4 | import numpy
from.utils import *
def ts_basics(timeseries):
"""
This function compute 7 basic metrics
"Mean" - Average value of the curve along one cycle.
"Max" - Maximum value of the cycle.
"Min" - Minimum value of the curve along one cycle.
"Std" - Standard deviation of the cycle’s... |
15736fddabeae0cc481fec6bc6c40bdecae06799 | KabanguJDTshikuma/my-practices | /Who likes it/whoLikesIt.py | 546 | 4.125 | 4 | def likes(names):
if len(names) == 1:
return names[0] + ' likes this'
elif len(names) == 2:
return str(names[0]) + ' and ' + str(names[1]) + ' like this'
elif len(names) == 3:
return str(names[0]) + ', ' + str(names[1]) + ' and ' + str(names[2]) + ' like this'
elif len(... |
023d084024b168edff71f9b22964dc9a6e051d4e | KabanguJDTshikuma/my-practices | /Compare Versions/compare_versions.py | 1,130 | 3.703125 | 4 | def compare_versions(version1, version2):
if '.' not in version1 and '.' not in version2:
if int(version1) > int(version2) or int(version1) == int(version2):
return True
else:
return False
elif '.' in version1 and '.' in version2:
a = version1.split('.')
b... |
7a8cb3cae334d66aeb28f53b112a10e84a5ef08f | shakil2995/100Days-Of-Code | /Math_problems/BiSectionMethod.py | 888 | 3.796875 | 4 | import os
ErrorRate = 0
def func(x):
return x*x*x - 4*x -9
def bisection(a,b):
if (func(a) * func(b) >= 0):
print("Root not found for a and b\n")
return
counts=0
c = a
while ((b-a) >= ErrorRate):
counts=counts+1
c = (a+b)/2
if (func(c) == 0.0):
... |
ca99e11602821b83b5d140f29f8aa6a3c3ee2bc0 | shakil2995/100Days-Of-Code | /day4 rock paper scissor.py | 2,369 | 3.984375 | 4 | # LIST SPLIT and RANDOM
#import random
# print(f"{random.choice(input('Input all the names with a , : ').split(', '))} will give the bill")
# Treasure hunt
# while True:
# print(" ")
# row1=["🥵","🥵","🥵"]
# row2=["🥵","🥵","🥵"]
# row3=["🥵","🥵","🥵"]
# ma... |
607f240ccafcaa43c37a94b497870e9417ef4ff7 | sagaar333/Python | /Bubble_Sort.py | 702 | 3.953125 | 4 | def BubbleSort(l1=[]):
i=0
for i in range(len(l1)-1):
#print("value of i=",i)
flag =0
for j in range(len(l1)-i-1):
#print("value of j = ",j)
if l1[j]>l1[j+1]:
flag=1
temp=l1[j]
l1[j]=l1[j+1]
... |
7059aba4cb753cfbd24f357b8ca4a1aac5cea3ae | sagaar333/Python | /mergeSort.py | 573 | 4.25 | 4 | import Bubble_Sort
def mergeSort(l1,l2):
l3=[]
i=0
j=0
while(i<len(l1))&(j<len(l2)):
if(l1[i]<l2[j]):
l3.append(l1[i])
i+=1
else:
l3.append(l2[j])
j+=1
if(i<len(l1)):
l3.extend(l1[i:])
else:
l3.exten... |
b073e30fb0c7b43e61845de6a0cb50ea6fe1d4f0 | Benature/Computational-Physics-Course-Code | /chp9/随机数/布朗运动1d.py | 1,082 | 4.25 | 4 | # 参考答案
# random walk,随机行走
import matplotlib.pyplot as plt
import random as rd
# %matplotlib inline
nsteps = 100 # input('number of steps in walk -> ')
nwalks = 100 # input('number of random walks -> ') 粒子数
seed = 10 # input('random number seed -> ')
rd.seed(seed)
steps = range(nsteps)
xrms = [0.0] * nsteps # mean ... |
dee3aeb3cd46b2eff9f4c971fa3d41874e59bf62 | Benature/Computational-Physics-Course-Code | /chp9/物理问题/模拟退火_快递.py | 1,910 | 3.75 | 4 | # 快递员问题
from math import sqrt, exp
from numpy import empty
from random import random, randrange, seed
import matplotlib.pyplot as plt
N = 25 # 多少个小镇
R = 0.02
Tmax = 10.0 # 最大的退火温度
Tmin = 1e-3 # 最小的退火温度
tau = 1e4 # 温度的半衰期
# Function to calculate the magnitude of a vector
def mag(x):
return sqrt(x[0]**2+x[1]*... |
de5b568aabd7c15a89fe9e0a48a380ae58377fe5 | Benature/Computational-Physics-Course-Code | /chp6/梯度下降法_6.1ex.py | 743 | 3.703125 | 4 | # 练习参考答案
from math import exp, sqrt
import numpy as np
import matplotlib.pyplot as plt
# Constants
sigma = 1.0 # Value of sigma in nm
g1 = (sqrt(5)-1)/2
g2 = 1 - g1
accuracy = 1e-6 # Required accuracy in nm
# Function to calculate the Buckingham potential
def f(r):
return (sigma/r)**6 - exp(... |
0aa078c864ba9f8571b2a4092069b86918a0eda9 | cbollin/python_basics | /OOP/python_basics_OOP.py | 2,991 | 3.96875 | 4 | # class Human(object):
# def __init__(self, clan=None):
# self.age = 18
# self.intel = 22
# self.strength = 44
# self.hp = 100
# self.clan = clan
# print "Hello World!"
# def taunt(self):
# print "You want to go?!"
#
# tom = Human("tacos")
# print tom.clan... |
667f38b8b24bb434543e6e950b892ac51e46b4bc | pratapreddyavula1/Python-Files | /Oops/Choice.py | 418 | 3.84375 | 4 | from Student import Student
from Employee import Employee
class Choice(Student,Employee):
def choice(self):
ch=input(("Enter Which File do you want to Open (Student/Employee):"))
if ch.lower()=="student":
self.StudntDetails()
elif ch.lower()=="employee":
self.... |
745516e0c9fd368a9a2d0f6443b96766646a1b88 | pratapreddyavula1/Python-Files | /Oops/Employee.py | 2,211 | 3.703125 | 4 | from Human import human
class Employee(human):
def EmployeeDetails(self):
self.input()
self.ename=input("Enter Employee Name:")
self.eid=int(input("Enter Employee Id:"))
self.desg=input("Enter Employee Designation:")
self.sal=int(input("Enter Employee Salary:"))
... |
868641db65a3e067adc48f803a6eba669a8c5712 | cakesjams/matasano-crypto-challenges | /2.10.py | 1,781 | 3.828125 | 4 | #!/usr/bin/env python
from crypto import *
import time
#start timer
start = time.time()
"""
Problem
CBC mode is a block cipher mode that allows us to encrypt irregularly-sized messages, despite the fact that a block cipher natively only transforms individual blocks.
In CBC mode, each ciphertext block is added to... |
462226a9149820d02739c917abffa50c55231391 | MStimpson/Python-Training | /Casino.py | 1,159 | 3.796875 | 4 | import random
###Dice Class #############################
class Dice(object):
def __init__(self, sides):
self.sides = sides
def rollDie(self):
return random.randint(1,self.sides)
###Cards Class ###########################
class Cards(object):
def __init__(self):
self.cardList = [['2','3','4','5','6',... |
e20dc295aaf28edb4af9d202811a2759e7fb32d0 | 1391020381/python-learning | /python/map.py | 500 | 3.65625 | 4 | # -*- coding:utf-8 -*-
def f(x):
return x*x
r = map(f,[1,2,3,4,5,6,7,8,9])
print(list(r))
print(list(map(str,[1,2,3,4,5,6,7,8,9])))
from functools import reduce
def add(x,y):
return x+ y
print(reduce(add,[1,3,5,7,9]))
from functools import reduce
def fn(x,y):
return x*10 +y
def char2num(s):
digi... |
2a6c9ba06c25ebf82a1a4fa25f52041006739774 | gravito/Projects | /Numbers/fib.py | 575 | 3.828125 | 4 | def fib(f1,f2):
return (f1 + f2)
if __name__ == "__main__":
while True:
try:
n = int(input("Please enter positive value \n"))
if n <= 0:
raise Exception("Please enter positive value \n")
break
except ValueError:
print ("... |
cffaf98d75bbc1bbb7fbf3d2d6cac2aec6e65e4d | Chandramani/socialmediaanalytics | /get_tweets/by_user/get_tweets_by_users.py | 1,803 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import csv
import tweepy
from keys import keys
# Get your Twitter API credentials and enter them here
consumer_key = keys['consumer_key']
consumer_secret = keys['consumer_secret']
access_token = keys['access_token']
access_token_secret = keys['access_token_sec... |
d4da240f0452486d162f69e47ac6949ff856efeb | RomLuLu/TpOpenClassrooms | /TpLabyrinthe/carte.py | 809 | 3.5625 | 4 | """Classe carte"""
class Carte:
"""Classe qui permet de sauvegarder la carte en cour
attribut de classe 'compteur' pour savoir si une carte est en
cours. 0 si non 1 si oui."""
compteur = 0 #
def __init__(self,nom ='', path=''):
self.nom = nom # le nom du fichier qui sera chargé.
... |
8d438ab34eeabf335bf71c407f802efa67fa3609 | ro123/study | /guessgame.py | 887 | 3.984375 | 4 | from random import randint
x = randint(1,100)
print("Guess game \nRules: Guess the number, which was randomly picked by a program")
guesses_list = [0,0]
while guesses_list[-1] != x:
guesses_list+=[int(input('Guess the number '))]
if guesses_list[-1]==x:
break
else:
if len(guesses_li... |
0bb48e09dcbde0d8d604075bf650e9f2c42e9570 | jezzicrux/Python-Alumni-Course | /Excercises/inclass9_16.py | 508 | 4.28125 | 4 | #Making a function the adds three number and divdes by 3. (Pretty much average)
#This the function to get the average of the three numbers
avg = 0
def average(x,y,z):
avg=(x+y+z)/3
print(f"The average the three numbers is {avg}.")
def getting_numbs():
print ("Please enter your first number")
x = int(in... |
ef1b85d6df36bc6b251b94edd51c27c019bc63ec | jezzicrux/Python-Alumni-Course | /Excercises/triangle.py | 992 | 4.25 | 4 | def main():
print(f"Welcome to the triangle finder program")
print(f"Please enter 3 values for each side.")
print(f"Enter in value for side 1")
side1 = int(input(">> "))
print(f"Enter in value for side 2")
side2 = int(input(">> "))
print(f"Enter in value for side 3")
side3 = int(input(">... |
17a546db017b9abc0b1853b1df5137167e6fb795 | jezzicrux/Python-Alumni-Course | /Excercises/HW1.py | 837 | 4.34375 | 4 | #a message stating it going to count the number on chickens
print("I will now count my chickens:")
#number of hens
print("Hens", 25 + 30 / 6)
#number of roosters
print("Roosters", 100 - 25 * 3 % 4)
#a message counting the number of eggs
print("Now I will count the eggs:")
#The math for calculating the number of eggs
pr... |
3a9404263c22829cf66813b013126e569ec042ea | shahshahid81/tic-tac-toe | /tic-tac-toe.py | 3,612 | 3.90625 | 4 | from math import ceil
from random import random
def get_single_block():
return " |"
def print_board(board):
header = " " + "_" * 11
top_row = "|" + get_single_block() * 3
bottom_row = "|" + "___|" * 3
marker_rows = [2,5,8]
print(header)
for i in range(1,10):
if i % 3 == 0:
... |
e1e9207e329ad60d527bffa418194aea5aae138f | mateobosco/Starshipy | /Modelo/Movil.py | 2,285 | 3.75 | 4 | ANCHO_PANTALLA = 640
ALTO_PANTALLA = 480
class Movil(object):
lista = []
def __init__(self,duenio,posicion,tamano,velocidad):
self.duenio = duenio
self.posicion = posicion ; self.posicion[0] -= tamano[0]/2
self.tamano = tamano
self.velocidad = velocidad
self.posicionEnLista = len(Movil.lista)
Movil.lista... |
fb8125f73e2825f92d99ac10951cf857e8be7239 | jaredmckay17/DataStructuresAlgorithmsPractice | /binary_search.py | 1,120 | 4.125 | 4 | # Non-recrusive implementation
def binary_search(input_array, value):
first = 0
last = len(input_array) - 1
while first <= last:
midpoint = (first + last) // 2
if input_array[midpoint] == value:
return midpoint
else:
if value < input_array[midpoint]:
last ... |
435171ef5e7c5a08542ddad82b613b34c0519400 | Deepsick/python-project-lvl1 | /brain_games/engine.py | 786 | 3.859375 | 4 | import prompt
def run_game(description, rounds):
print('Welcome to the Brain Games!')
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name))
print(description)
for round in rounds:
question, correct_answer = round.values()
print('Question: {}'.format(questi... |
4d7ef8b54249c859456a3ffffc5db638636232fa | s1c5000/learn_code | /python_study/Study/while.py | 500 | 3.640625 | 4 | #while 조건 :
num = [1,2,1,1,2,1,1,2,2,1]
while 1 in num:
num.remove(1) #remove는 지워야할게 여러개있으면 앞에있는걸 지운다.
print(num)
i=0
while i<5:
print(i, end=", ")
i +=1
print()
array = [1, 10, 5, 8, 7, 6, 4, 3, 2, 9]
#index,temp
for i in range(10):
min = 9999
for j in range(i,10):
if min > array[j]:
... |
622fcca8ab5f8c6c280f6ec1c75df9ff52f81e07 | sumforest/first_python | /test_repr_str_format.py | 563 | 4.15625 | 4 | # 输入一个立方表
for x in range(1,11):
print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ')
print(repr(x*x*x).rjust(4))
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
# 在:后面跟数字可以保证宽度
table = {'Google':1,'Runoob':2,'Alibaba':3}
for k,v in table.items():
print('{0:10}===>{1:10}'.format(... |
5563efa4fc3149b63432b4d207d46ba77359e6b2 | sumforest/first_python | /stringDemo_1.py | 352 | 3.6875 | 4 | var1 = 'Helloworld'
var2 = 'Runoob'
print(var1[0])
print(var2[1:5])
var3 = 'Hello World!'
print(var3[:6]+'Runoob')
print('\n','*'*50,'\n')
# f-string
# 1.替换字符串
name = '广州荔湾加油'
print(f'yeah! {name}')
print('\n','*'*50,'\n')
# 2.替换表达式
print(f'{1+2}')
print('\n','*'*50,'\n')
# since python 3.8
x =1
print(f'{x+1=}')
|
f3f08d4b739c4993a6597060d8e8b66340b4d514 | sumforest/first_python | /列表-列表推导式.py | 587 | 4.15625 | 4 | # 将列表中每个数值乘三,获得一个新的列表:
vec = [3,6,9]
print([x*3 for x in vec])
# 得到一个嵌套列表
print([[x,x*2] for x in vec])
# 对序列里每一个元素逐个调用某方法:
freshfruit = [' banana', ' loganberry ', 'passion fruit ']
print([fruit.strip() for fruit in freshfruit])
# 使用if做过滤条件
print([x for x in vec if x > 3])
# 循环和其它技巧的演示:
vec1 = [1,2,3]
vec2 = [2... |
af9fc94c818bd0266f31a93fc5196ab46b3369a3 | sumforest/first_python | /level.py | 411 | 3.625 | 4 | print('*'*10,'请输入你的级别','*'*10)
level = int(input())
if level == 1:
print('免费关卡随便玩。。。')
else:
print('本关卡需要充值!请输入充值金额:')
money = int(input())
if money % 100 == 0 and money > 0:
print('充值成功,您充值的金额为:',money)
else:
print('您充值的金额有误,充值的金额必须时100的倍数!!!') |
627f973eb5f47cd9eee82382d831c4e9b3ccd879 | sudo-bin/algorithm_study | /solved/이것이코딩테스트다/그래프 이론/커리큘럼.py | 951 | 3.515625 | 4 | # 위상정렬
from collections import deque
from copy import deepcopy
n = int(input())
# 진입차수 0으로 초기화
indegree = [0] * (n + 1)
# 각 노드의 간선 정보를 저장 하기 위한 list
graph = [[] for _ in range(n + 1)]
# 강의 듣는데 필요한 시간 0으로 초기화
time = [0] * (n + 1)
for i in range(1, n + 1):
info = list(map(int, input().split()))
time[i] = in... |
0e0eeef2eddf4dca1ae97c5fa84e674b97733592 | justinmyersdata/ProjectEuler | /27_Project_Euler.py | 1,348 | 4.09375 | 4 |
def isprime(x):
'''Returns True if x is prime and false if x is composite'''
if x < 1:
return False
elif x == 1:
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
else:
for y in range(3,int(x**(1/2))+1... |
12e2e542a238b5d2ac29e5d879af93ef07710c28 | justinmyersdata/ProjectEuler | /6_Project_Euler.py | 353 | 3.921875 | 4 |
def sumsquare(n):
'''Returns the difference between the sum of the first n digits squared
and the square of the sum of the first n digits'''
square = 0
sumsquare = 0
for i in range(1,n+1):
square += i**2
sumsquare += i
sums = sumsquare**2
return(sums-square)
... |
f791702e716e22da1327780cbc9e272648b5c2b8 | justinmyersdata/ProjectEuler | /7_Project_Euler.py | 607 | 4.25 | 4 |
def isprime(x):
'''Returns True if x is prime and false if x is composite'''
if x == 1:
return False
elif x == 2:
return True
elif x % 2 == 0:
return False
else:
for y in range(3,int(x**(1/2))+1,2):
if x % y == 0: ... |
4ecf24bce874796c78645a1e76e06f5dc7f2bdc1 | justinmyersdata/ProjectEuler | /5_Project_Euler.py | 714 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 19:15:09 2021
@author: MYERSJ1
"""
def factors(x):
factor_list = []
factor = 2
while x > 1:
if x % factor == 0:
x = x/factor
factor_list.append(factor)
else:
factor +=1
return(factor_l... |
be778d5c81e7d6b29ea6465cf2cdc9fb2b4e06fe | Doreen-Chen/Excel | /87_excel.py | 932 | 3.78125 | 4 | # 87. 處理 Excel 檔 (使用第三方套件流程示範)
# & 88. 處理 Excel 檔 (應用展示)
# https://openpyxl.readthedocs.io/en/stable/
# Python 所有東西都是物件
### Key Classes (from https://openpyxl.readthedocs.io/en/stable/ )
### openpyxl.workbook.workbook.Workbook
### openpyxl.worksheet.worksheet.Worksheet
### openpyxl.cell.cell.Cell
# from 指定套件 ; ... |
7a002f62bc68b8773030144c81415c06d5171a26 | ModarYaghi/hackerrank-problem-solving-challenges | /electronics_shop_.py | 1,403 | 3.9375 | 4 | """Hacker Rank Problem Solving - Challenge 42;
Lest Comprehension Solution of Electronics Shop"""
# I found this solution in the repo of sapanz/Hackerrank-Problem-Solving-Python-Solutions
# This solution has written in one line, but it is rearranged as PEP8 style to be more readable
# The idea of this solution i... |
503985ac84f51576e92638f386476915b43f3078 | ModarYaghi/hackerrank-problem-solving-challenges | /counting_valleys.py | 458 | 4.03125 | 4 | """Hacker Rank Problem Solving - Challenge 23; Counting Valleys"""
def counting_valleys(n, s):
sea_surface = 0
valleys = 0
for step in s:
if step == "U":
sea_surface += 1
if sea_surface == 0:
valleys += 1
else:
sea_surface += -1
re... |
4d9cc902234a91f5e333c26810db8b2d8e31492f | warSantos/ProductMatching | /utils/text_clean.py | 618 | 3.828125 | 4 | import string
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# Remove pontos, números e stopwords.
def clean_text(sentences, accept_num=True):
stop_words = {word: True for word in stopwords.words("english")}
table = str.maketrans("", "", string.punctuation)
tokens = []
for t... |
16d56f2b851849225daf0aa74488817cf46f8cca | weilyu/hackerrank_python | /sets/union_Operation.py | 200 | 3.6875 | 4 | # https://www.hackerrank.com/challenges/py-set-union
n1 = input()
l1 = input().split()
n2 = input()
l2 = input().split()
set1 = set(l1)
set2 = set(l2)
combine = set1.union(l2)
print(len(combine))
|
2573b806c098d7f148ed6d16ff4d3b37a333ba7c | weilyu/hackerrank_python | /sets/Introduction_to_Sets.py | 195 | 3.796875 | 4 | # https://www.hackerrank.com/challenges/py-introduction-to-sets
n = input()
line = input().split()
nums = set()
for s in line:
curr = int(s)
nums.add(curr)
print(sum(nums) / len(nums))
|
f572dbd167bc8d860b357bfab431a981f38e7041 | P3n9W31/Leetcode | /Python/#657._Robot Return to Origin.py | 350 | 3.53125 | 4 | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
L_move = moves.count('L')
R_move = moves.count('R')
U_move = moves.count('U')
D_move = moves.count('D')
if L_move == R_move and U_move == D_move:
re... |
ac383ad914ad32e1f68f3fee538f4de38810c401 | P3n9W31/Leetcode | /Python/#9_Palindrome Number.py | 976 | 3.78125 | 4 | class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
ranger = 1
while x / ranger >= 10:
ranger *= 10
while x:
left = x // ranger
right = x % 10
... |
32c38d755c59bd55288d3ba14151c8e908b8ac25 | P3n9W31/Leetcode | /Python/#896_Monotonic Array.py | 711 | 3.578125 | 4 | class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if len(A) == 1:
return True
state = A[-1] - A[0]
if state > 0:
for num_index in range(1,len(A)):
if A[num_index] < A[num_ind... |
5322a38bc919be83344096dc1ea2d5ff569cfd5d | dR3m/somecode | /math_and_sage/reaktivnoe_soprotivlenye.py | 4,047 | 3.890625 | 4 | #ОПРЕДЕЛЕНИЕ РЕАКТИВНЫХ СОПРОТИВЛЕНИЙ И СДВИГА ФАЗ В ЦЕПЯХ С СИНУСОИДАЛЬНЫМ НАПРЯЖЕНИЕМ
from decimal import *
from math import *
def complex_mul(a, b):
res = [0,0]
res[0] = a[0]*b[0]+(-1*a[1]*b[1])
res[1] = a[0]*b[1] + a[1]*b[0]
return res
def complex_sum(a, b):
res = [0,0]
res[0] = a[0]+b[0]
res[1] = a[1]+b[... |
155ef1da898cbc7797e18ecdcd414c46dcb55133 | chinadiaosi/leetcode | /1. Two Sum.py | 470 | 3.609375 | 4 | # -*- coding: utf-8 -*-
from sys import stdout
while 1:
cache = int(raw_input('Please input the number:'))
num = int(cache)
pf = []
i = 2
stdout.write(' The prime facors of 'str(num)+' : ')
while num <> 1:
if num % i ==0:
pf.append(i)
num = num / i
else:
... |
9da9cd9952e65874d7db6d113a8e332a763c298f | 02KellyV/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 182 | 3.890625 | 4 | #!/usr/bin/python3
class Square:
__size = 0
def __init__(self, new_size=0):
"""Initialize class."""
if new_size is not 0:
self.__size = new_size
|
fff769d540403dafc9c46dd7bf6d672ae417ca40 | amitshipra/PyExercism | /misc/turtle.py | 1,052 | 3.65625 | 4 | DIRECTIONS_ORDER = ['North', 'East', 'South', 'West']
def solution(A):
if len(A) == 0:
return 0
position = (0, 0, 0, '')
moves = list()
for move_idx, advance in enumerate(A):
direction = next_direction(move_idx)
if direction is 'North':
x, y, steps = position[0], po... |
4b790776bf214c8851be79d5931623ee3614d34e | amitshipra/PyExercism | /sublist/sublist.py | 2,164 | 3.9375 | 4 | __author__ = 'agupta'
class EQUAL:
pass
class UNEQUAL:
pass
class SUBLIST:
pass
class SUPERLIST:
pass
def check_lists(list1, list2):
if len(list1) == 0 and len(list2) == 0:
return EQUAL
if len(list1) == 0 and len(list2) != 0:
return SUBLIST
if len(list2) == 0 and ... |
ab65d41474186820587e216e5c91617621b599c2 | amitshipra/PyExercism | /recursion/examples.py | 743 | 4.28125 | 4 | __author__ = 'agupt15'
# Source: http://www.python-course.eu/python3_recursive_functions.php
#
#
#
#
# ## Example 1
#
# Write a recursive Python function that returns the sum of the first n integers.
###
def rec_add(num):
if num == 1:
return 1
return num + rec_add(num - 1)
print(rec_add(10))
### ... |
405974a2c23bac27263c4d32d5b63f5ae98f8a1d | mhali31/automation_renaming_files | /automation_renaming_files.py | 1,034 | 3.796875 | 4 | import os
import time
'''this script was used to rename the files'''
# an easy way to get folder location is to drag folder into cmd or gitbash
os.chdir(input("insert the directory of files: "))
#print(os.getcwd())
''' to get the name of each file in the directory '''
for f in os.listdir():
#print(f)
... |
583b219c25c9b6efd16f2632ca94683ce0c35821 | fmcooper/matchingproblems | /matchingproblems/generator/instance_options_parser.py | 15,664 | 3.5 | 4 | import argparse
from argparse import RawTextHelpFormatter
from .enums import *
"""Instance options parser for generating matching instances."""
class Instance_options_parser:
def check_bounds(self, parser, args):
"""Checks bounds for many input parameters.
Not all bounds are checked - the user i... |
4350d764af0961abc44c2adb1c54d4d8173dd403 | srikanthpragada/pythondemo_21_june_2019 | /oop/gen_demo.py | 269 | 4.125 | 4 | # Generator to yield even number from start to end
def even_numbers(start, end):
if start % 2 != 0:
start = start + 1
for n in range(start, end + 1, 2):
yield n
print(type(even_numbers(10, 20)))
for n in even_numbers(11, 21):
print(n)
|
5779075af7758671ea6222a304ee6304d6161562 | srikanthpragada/pythondemo_21_june_2019 | /funs/number_funs.py | 364 | 3.828125 | 4 | def iseven(n):
"""
Finds out whether the given number is even
:param n: number
:return: True if number is even otherwise false
"""
return n % 2 == 0
def isodd(n):
return n % 2 != 0
if __name__ == '__main__': # running module as script
print("Running number_funs")
else: # importi... |
78638471258c97dd57f39262f092f248df6cd686 | srikanthpragada/pythondemo_21_june_2019 | /oop/avg_nums.py | 214 | 3.953125 | 4 |
total = 0
count = 0
try:
for i in range(1, 6):
n = int(input("Enter number :"))
total += n
count += 1
except ValueError as ex:
print("Invalid number!")
print(total / count)
|
ffd2177c0dfe6ae5ff57834f7582135a85454862 | srikanthpragada/pythondemo_21_june_2019 | /ex/common_chars.py | 173 | 3.90625 | 4 |
s1 = input("Enter first string : ")
s2 = input("Enter second string : ")
common = set() # Empty set
for c in s1:
if c in s2:
common.add(c)
print(common)
|
ad0ba398c3053b62c0e9e3b5a93fa5ed840c4e35 | cm080691/npd_c3_a2 | /assignment2.py | 566 | 3.515625 | 4 | from logging import getLogger
def aDecorator(func):
def _func(*args, **kwargs):
print 'I am excecuting before method call %s!' % func.func_name
_ret = func(*args, **kwargs)
print 'I am executing after method call %s!' % func.func_name
return _ret
return _func
@aDecorator
def my... |
5bea9d32a0f174543c3d734002f8e856d6ac6279 | gurkiratsandhu/Assignment_Daily | /assignment7 (1).py | 1,521 | 4.15625 | 4 | #(Q.1)- Create a function to calculate the area of a circle by taking radius from user.
def area():
pi = 3.14
radius = float(input("enter radius: "))
area = pi*radius**2
print("Area of a circle = ",area)
area()
#(Q.2)- Write a function “perfect()” that determines if parameter number is a perfect number.
#Us... |
96a4803f2cdf428f9e3e0c42f339e4980315f3e7 | hoaxanalyzer/hoax-analyzer-ml | /query_builder/backup/preprocess.py | 795 | 3.71875 | 4 | """
PREPROCESS
Preprocess input text
"""
import nltk, sys
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
print("Input user: ")
print(sys.argv[1:])
data = "Earlier this week, a story went viral about a man who claimed he purchased a yak while high on... |
97e39e1e65729a3a28e186af0864ab1208d1fbd5 | lordwayden/python__random_code | /remove_duplicate_values_from_list.py | 109 | 3.859375 | 4 | a = [3, 2, 5, 3, 9, 2, 9]
b = []
[b.append(x) for x in a if x not in b]
print(b)
c = set(a)
print(c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.