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 |
|---|---|---|---|---|---|---|
5703e518f0d1307de1c7ecc91769aa483761b1e6 | martmwangi/Practise_Toy_Problems | /dash_insert/dash_inserter.py | 276 | 3.84375 | 4 | def DashInsert(str):
new_ = []
for i in range(len(str)):
if int(str[i]) % 2 != 0 and int(str[i - 1]) % 2 != 0:
if len(new_)>0:
new_.append('-')
new_.append(str[i])
return "".join(new_)
print (DashInsert("454793"))
|
a9f3950163ff30e68ec431f5e6c36340aa6f2158 | savourylie/interview_questions | /sorting/quick_sort.py | 1,291 | 3.890625 | 4 | def quick_sort(lst):
if len(lst) < 2:
return lst
pivot = lst[0]
smaller = [x for x in lst if x < pivot]
equal = [x for x in lst if x == pivot]
larger = [x for x in lst if x > pivot]
return quick_sort(smaller) + equal + quick_sort(larger)
# def quick_sort(lst):
# N = len(lst)
#
# ... |
beadb79ce6c4df356833bf50da1c989b1f18bbb0 | hanyunxuan/leetcode | /766. Toeplitz Matrix.py | 884 | 4.5 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
Example 1:
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5... |
6d351f284832098cef355095413b29d75845aa4d | hanyunxuan/leetcode | /821. Shortest Distance to a Character.py | 1,052 | 3.734375 | 4 | """
Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Example 1:
Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
"""
# # my solution
# S = "loveleetcode"
# C = 'e'
# indices = [i for i, x in enumerate(... |
f9396f83ad0bba53ff44d94e5f35c5ddaf36c1d2 | cmFodWx5YWRhdjEyMTA5/info | /Odesk Test - Full/python backend test/test2.py | 705 | 3.5625 | 4 | def matrix_circles(matrix):
N = len(matrix)
M = len(matrix[0])
output = []
k = 0
for i in range(k, N-k):
for j in range(k, M-k):
output.append(matrix[i][j])
for j in range(k+1, N-k):
if (M-k)> k:
output.append(matrix[j][M-k-1])
for j ... |
662e6622bc9073b5ebabfddf87b7fda3e7160000 | elphabecca/oo-melons | /melons.py | 2,549 | 3.875 | 4 | import random
import datetime
"""This file should have our order classes in it."""
class AbstractMelonOrder(object):
"""general information for any melon order """
def __init__(self, species, qty, country_code):
"""Initialize melon order attributes"""
self.species = species
self.qty ... |
a4747f39f521d37f53a3133a64a13c59f6c2d900 | jonasrosland/lpthw | /ex11.py | 429 | 3.875 | 4 | print "How old are you?"
age = raw_input("Age: ")
print "How tall are you?"
height = raw_input("Height: ")
print "How much do you weigh?"
weight = raw_input("Weight: ")
print "So, you're %s old, %s tall and %s heavy." % (age, height, weight)
print "What's your favourite colour?"
colour = raw_input("Colour: ")
print "... |
fec6eb9b831d4b5c437ad7a3cda86e317a201a1c | marinavicenteartiaga/Advent-of-Code-2020 | /puzzles/day_5/day_5.py | 1,188 | 3.734375 | 4 | from puzzles.utils import resources
input_data = resources.get_input_list_from_file("input_day5.txt")
def get_seat_id(boarding_pass):
rows = boarding_pass[0:7] # The first seven characters
columns = boarding_pass[7:10] # The last three characters
for i in range(0, len(boarding_pass)):
rows = ro... |
d93a6b601aa593fd502890e6a03eee625bffbeba | 29rithm/algospot | /CLIMBING/climbing_jimin.py | 701 | 3.578125 | 4 | class Solution:
def __init__(self):
self.climb_history = {1: 1, 2: 2}
def climbStairs(self, n: int) -> int:
if n <= 1:
return n
return self._climb_combination(n)
def _climb_combination(self, n):
if not n in self.climb_history:
self.climb_history[n] ... |
5d7716d0c8965421c5b00cf3c727d571aa5f9523 | 29rithm/algospot | /LONGEST_PALINDROMIC_SUBSTRING/longest_palindromic_substring_yoonnoon.py | 1,684 | 3.828125 | 4 | """
https://leetcode.com/problems/longest-palindromic-substring/
"""
import unittest
class Solution:
"""
Runtime: 924 ms, faster than 85.15% of Python3 online submissions for Longest Palindromic Substring.
Memory Usage: 13.8 MB, less than 22.69% of Python3 online submissions for Longest Palindromic Substr... |
478c236a531e8edf149c27495da9a5a83ca974a6 | 29rithm/algospot | /JUMPGAME/jumpgame_yoonnoon.py | 2,087 | 3.75 | 4 | import unittest
class JumpGame:
def __init__(self, _n, _data):
self.n = _n
self.data = _data
self.is_arrive = False
self.visit_memo = set()
def solution(self):
self.move(0, 0)
return "YES" if self.is_arrive else "NO"
def move(self, row, col):
if r... |
307435c2738eddcde8842d4402ac165f891e4539 | horacioMartinez/L2RPN | /old/src/generate_rand.py | 847 | 3.59375 | 4 | import random
import numpy as np
np.set_printoptions(suppress=True)
lowest = 0.1
highest = 0.9
highest_first = 0.15
numbers = []
NUM_RANDOM_NUMBERS = 7
spins = 100
for a in range(0, spins):
numbers = []
for i in range(0, NUM_RANDOM_NUMBERS):
if i == 0:
r = random.uniform(lowest, highest_... |
28f97c5ecddc50b4763fbe1bf627178a12269739 | Raushan117/Python | /B10_Function.py | 270 | 3.625 | 4 | # Python function always have () even if it does not
# take arugment. They are not optional.
def function(n = 1):
print(n)
# passing the value of 47
x = function(47)
# all function return something, in this case None
# the value represent nothing in python.
print(x) |
4f51b739fdc5e7e0deb156a8a21278ea01d6ed33 | Raushan117/Python | /040_Debugger.py | 403 | 4.0625 | 4 | # Chapter 10: Debugging
# https://automatetheboringstuff.com/chapter10/
# Using the IDE Debug Control Window to (Step)
# and monitor each variable's value
print('Enter the first number to add: ')
first_num = input()
print('Enter the second number to add: ')
second_num = input()
print('Enter the third number to add:... |
e77bbe516fc274f1e9cd3c8614f614ccfd4ab490 | Raushan117/Python | /014_Append_Mode.py | 827 | 4.5 | 4 | # Reference: https://automatetheboringstuff.com/chapter8/
# Writing in plaintext mode and appending in plaintext mode
# Passing a 'w' or 'a' in the second arugment of open()
# If the file does not exist, both argument will create a new file
# But remember to close them before reading the file again.
# About:
# Creati... |
0ec4208b74f5b970c3e580346215088b3f24c1f6 | Raushan117/Python | /029_Rename_Filename_Date_Format.py | 2,097 | 3.53125 | 4 | # https://automatetheboringstuff.com/chapter9/
# Project rename files with American style dates to Eurpoean style dates
# American style = MM-DD-YYYY
# European style = DD-MM-YYYY
# Write program that will handle it for you :)
# Step 01: Search all the filesname in current working directory for AM style
# Step 02: W... |
2a60b0dd58b9683c28426fe260718e39fd95cbb6 | Raushan117/Python | /026_Moving_Files.py | 494 | 3.625 | 4 | # Aautomate the boring stuff with python
# https://automatetheboringstuff.com/chapter9/
# Moving and renaming file/folders.
import shutil
# Making a new copy first
shutil.copy('./hello.txt', './hello_testing.txt')
# Renaing the new copy from hello_testing to bye_bye
shutil.move('./hello_testing.txt', 'bye_bye.txt')... |
516627d49fe6ebd3530fee47aeb9914ae72eca08 | Raushan117/Python | /050_Make_T500.py | 329 | 3.640625 | 4 | # Write a python script that will generate the SQL table T500.
# Table with name T500, (ID integer) with 500 insert statements.
with open('sql_t500.txt', 'w') as f:
f.write('CREATE TABLE T500 (ID INTEGER);\n')
for x in range(500):
f.write('INSERT INTO T500 VALUES ({0}); \n'.format(x+1))
print('Python Program Com... |
5f336d219fc9f204490e60550385f337342112f6 | shadyelia/CodeForcesProblems | /A. Beautiful Year/main.py | 228 | 3.671875 | 4 |
def main():
year = int(input(''))+1
while(1):
if len(str(year)) == len(set(str(year))):
break
else:
year = int(year) + 1
print(year)
if __name__ == "__main__":
main()
|
acf7939a3913d6d386c45e51534ab95ccdc3ed76 | l516q582/pythondemo | /Python_Demo/WEEK_EIGHT/GraphicsInterfaceDemo4.py | 1,561 | 3.65625 | 4 | from graphics import *
def insideRect(point, rect):
locals()
p1 = rect.getP1()
p2 = rect.getP2()
if p1.getX()>p2.getX():
highX = p1.getX()
lowX = p2.getX()
else:
highX = p2.getX()
lowX = p1.getX()
if p1.getY() > p2.getY():
highY = p1.getY()
lowY =... |
888bbae849b4ae5d9140dbabcbd3cd5ac395735e | l516q582/pythondemo | /Python_Demo/WEEK_FOUR/CalcBMI.py | 733 | 3.71875 | 4 | import sys
try:
weight, height = eval(input("请输入你的体重和身高(kg, m):"))
except:
print("数值输入错误,请重新运行程序!")
sys.exit()
BMI = weight/(height*height)
print("BMI : {0}".format(BMI))
if BMI < 18.5:
print("体重偏瘦")
elif BMI < 24:
print("体重正常")
elif BMI < 28:
print("体重偏胖")
else :
print("体重肥胖")
print("{0:^10... |
60b14589f7131d9f1ed62f4c4425042a4e4ef2e1 | pybokeh/jupyter_notebooks | /machine_learning/graham_wheeler/ex04-06.py | 769 | 3.515625 | 4 | # Calculate the mean age for each different type of animal.
print(ex3df.groupby('animal').age.mean())
# Count the number of each type of animal.
print(ex3df.animal.value_counts())
# Sort the data first by the values in the 'age' column in decending order,
# then by the value in the 'visits' column in ascending order.... |
c861335b6346028d3938ce981090f05f6a2977a0 | pybokeh/jupyter_notebooks | /oop/args_kwargs.py | 297 | 3.703125 | 4 | def function(*args):
print(type(args)) # args is of type tuple
for i in args:
print(i)
function(1, 2, 3, 4)
def function(**kwargs):
print(type(kwargs)) # kwargs is of type dict
for i in kwargs:
print(i, kwargs[i])
function(a=1, b=2, c=3, d=4)
|
ed395158ee729cf3b3194c223690da4241fa8d07 | Jasonmes/Jasonmes.oneday.com | /moreM.py | 429 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Jason Mess
__all__ = ["func", "count"]
def func():
pass
count = 0
# class Dog:
# pass
class God(object):
def __init__(self):
self.name = "上帝哦"
class Dod(object):
def __init__(self):
self.name = "多的"
class cat(object):
def eat(se... |
a2b1643ff6be9a31943e3af145199a32d80f39bc | dpaez16/Common-Functions | /Python/trie.py | 1,730 | 3.5 | 4 | class Trie:
def __init__(self):
self.root = Trie._TrieNode()
def insert(self, word):
curr = self.root
for i in range(len(word)):
c = word[i]
if c not in curr.children:
new_node = Trie._TrieNode()
new_node.is_terminal = i + 1 == le... |
5458edcc3d91337fd5d28b89617716e4fb646cbd | seyed-ali-mirzaee-zohan/Assignment-7 | /question3/translation.py | 4,402 | 3.734375 | 4 | import pyfiglet
from termcolor import colored
result = pyfiglet.figlet_format("google translation", font = "digital" )
print(result)
print(colored(' Hello, Welcome to the translator software ', 'red', attrs=['reverse', 'blink']))
print()
print(colored(' The following options are now available : ', 'white', attrs=... |
669786bc7fb97c7448626b0a5568609214e918a3 | robflowerday/DPLL | /dpll2.py | 5,482 | 3.734375 | 4 | import copy
# a sentence in conjunctive normal form is made up of a conjunction of clauses which in turn are made up of a disjunction of propositions
def get_propositions(sentence):
propositions = []
for clause in sentence:
for proposition in clause:
propositions.append(proposition... |
e60eae94a4a6976907841adb85a50e1ef500ef08 | Hank310/backup | /Practice2.py | 296 | 3.75 | 4 | # Hank Warner, P1
x = input("Enter 1st Number")
y = input("Enter 2nd Number")
print( x + " + " + y + " = ")
print(int(x) + int(y))
print( x + " - " + y + " = ")
print(int(x) - int(y))
print( x + " * " + y + " = ")
print(int(x) * int(y))
print( x + " / " + y + " = ")
print(int(x) / int(y))
|
2da9b3886307552c743883ecf1466ff798f7adf6 | mateuspontesm/rl-agents | /src/rl_agents/agents/core.py | 921 | 3.640625 | 4 | from abc import ABC, abstractmethod
class BaseAgent(ABC):
"""A base RL agent.
"""
@abstractmethod
def predict(self, state, eval=False):
"""Predict the next action the agent should take.
Parameters
----------
state : type
State information
eval : b... |
c267a2deec0eabfe9531413cfbb09c9d36ae6112 | mateuspontesm/rl-agents | /src/rl_agents/agents/mab/base.py | 1,194 | 3.953125 | 4 | from abc import ABC, abstractmethod
class BaseMAB(ABC):
"""
A basic Multi-Armed Bandit agent.
In reinforcement learning, an Agent learns
by interacting with an Environment.
Usually, an agent tries to maximize a reward signal.
It does this by taking "actions" and receiving "rewards",
and i... |
71534bc94ada07faf4972bbee82616753f32d73a | namankumarjangid/python-basic-programmes | /dicerandom.py | 204 | 3.546875 | 4 | import random
class Dice:
def roll(self):
first=random.randint(1,6)
second=random.randint(1,6)
return first,second
dice=Dice()
print(dice.roll()) |
ae4b19764104a693e1c05e36864c0e64c9ae1ab7 | mhhetu/EDM5240-devoir1 | /devoir1.py | 2,543 | 3.53125 | 4 | # coding:utf-8
# print(publications[0][3])
#partages = publications[0][3]
#reactions = publications[0][4]
#commentaires = publications[0][5]
#n = 0
#for publication in publications:
"""Ici, j'ai essayé de reverse-engineer la phrase finale
en prenant le premier élément de la liste publications en exemple."""
varMedi... |
0376c538cbe2850e02eb2ba26094a940348647b0 | 18660882015/py | /18.1.18/jiaoji.py | 979 | 3.8125 | 4 | #!usr/bin/python
#conding=utf-8
a_list=list(input('input a_list'))
b_list=list(input('input b_list'))
c_list=list(input('input c_list'))
def ab_two():
result=[]
for item in a_list:
if item in b_list:
result.append(item)
print (result)
def bc_two():
result=[]
for item in b_list:
... |
9c1e3b9a69863e0ab7f586447ade05c3e679ee2d | 18660882015/py | /8.19/1.py | 926 | 3.703125 | 4 | #!usr/bin/python
#内置函数sorted()的使用
phonebook={'linda':'7750','bob':'9340','carol':'5834'}
from operator import itemgetter
sorted(phonebook.items(),key=itemgetter(1))
[('carol','5834'),('linda','7750'),('bob','9345')]
sorted(phonebook.items(),key=itemgetter(0))
[('bob','9345'),('carol','5834'),('linda','7750')]
sorted(ph... |
8d36bb499acdaaace335aebe13b0231c0db13685 | 18660882015/py | /8.22/3.py | 494 | 3.984375 | 4 | #!usr/bin/python
#计算字符匹配的准确率
def Rate(origin,userInput):
if not(isinstance(origin,str)and isinstance(userInput,str)):
print('The two parameters must be strings.')
return
if len(origin)<len(userInput):
print('Sorry.I suppose the second parame string is shorter.')
return
right=... |
d3997481c6305db6f303e9aed0c0c6b3dd60c09a | lennon101/Spectrometer-Interface | /raspberry-pi-python-scripts/pythonCSV/PythonCSV.py | 738 | 3.78125 | 4 | import csv
def printCSV(fileName):
with open(fileName, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print row
csvfile.close()
def getCSVArray(fileName):
csvArray = []
with open(fileName, 'rb') as csvfile:
reader = csv.reader(csvfile)
for... |
6beca592164142ea3b6381ec9185b4791ca208ad | sagsh018/Python_project | /18_Tuple_unpacking_with_python_function.py | 2,410 | 4.625 | 5 | # in this lecture we are going to learn more about function, and returning multiple items from function using tuple
# unpacking
# Suppose we want to write a function, which takes in a list of tuples having name of employee and number of hrs worked
# We have to decide who is the employee of the month based number of hou... |
4b31604397b17724d8a249c691a7828d0c07719c | sagsh018/Python_project | /9_Logical_Operators.py | 1,242 | 4.78125 | 5 | # In This lecture we are going to learn how to chain the comparison operators we have learnt in the previous lecture
# We can chain the comparison operator with the help of below listed logical operators
# and
# or
# not
# Suppose we want to do two comparisons
print(1 < 2)
# True
print(2 < 3)
# True
# another way of d... |
acb345bad9c7a7be1c51586ca0587931d864b99b | sagsh018/Python_project | /14_List_comprehensions_in_python.py | 2,803 | 4.84375 | 5 | # List comprehensions are unique way of quickly creating list in python
# if you find yourself creating the list with for loop and append(). list comprehensions are better choice
my_list = []
print(my_list)
# [], so we have an empty list
for item in range(1, 10):
my_list.append(item)
print(my_list)
# [1, 2, 3, 4, 5... |
2e97e48539eaae2d4a43533487c5d263baa1e587 | sagsh018/Python_project | /12_While_loop_in_python.py | 1,948 | 4.4375 | 4 | # While loop will continue to execute a block of code while some condition remains true
# Syntax
# ===============================
# while some_boolean_condition:
# do something
# ===============================
# We can also combine while statement with the else statement
# ===============================
# ... |
b67420e180277e8abd7908d95a410427a30373ea | homanate/python-projects | /fibonacci.py | 711 | 4.21875 | 4 | '''Function to return the first 1000 values of the fibonacci sequence using memoization'''
fibonacci_cache = {}
def fibonacci(n):
# check input is a positive int
if type(n) != int:
raise TypeError("n must be a positive int")
if n < 1:
raise ValueError("n must be a positive int")
# che... |
8cedff63ebb07d190cb2ce9200e654165ef9ffe9 | kinshuk4/kaggle-solutions | /Recommendation-System/demo.py | 2,519 | 3.625 | 4 | from sklearn.externals import joblib
from common.fn import *
from classes.recommendation import Recommendation
'''
Download movies dataset
http://files.grouplens.org/datasets/movielens/ml-100k.zip
Place the unzip folder 'ml-100k' into 'datasets' folder in root directory of project.
'''
def loadMovieLens(path):
... |
c047775f02c6f9a4b46bf701e8baea7b6b79f7c4 | kinshuk4/kaggle-solutions | /Recommendation-System/classes/similarity.py | 951 | 4 | 4 | from math import sqrt
class Similarity:
'Various algorithms to calculate similarity score'
def euclidean(self, x, y):
'''Calculates euclidean score between two lists of same length'''
sum_square = sum([pow(x[i]-y[i], 2) for i in xrange(len(x))])
score = 1/(1+sqrt(sum_square))
return score
def pearson(s... |
9efa337edf541fb999d8fb7f63d5e1dd359048e6 | StToupin/remote-challenges | /chall02/stoupin.py | 666 | 4.03125 | 4 | #!/usr/bin/python3
import string
import sys
morse_code = {letter: code for letter, code in zip(string.ascii_lowercase, """.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
--
-.
---
.--.
--.-
.-.
...
-
..-
...-
.--
-..-
-.--
--..""".split())}
def encode_char(c):
return morse_code[c.lower()... |
47855bca72e44633ef4772d87d798ba6b099a646 | olanlab/python-bootcamp | /07-modules-functions/functions-04.py | 289 | 3.578125 | 4 |
PI = 3.14
def calCircleArea(radius) :
return ( PI * pow(radius, 2))
def calSquareArea(length, width) :
return length * width
def calTriangleArea(base, height) :
return base * height / 2
print(calSquareArea(10, 5) + calTriangleArea(10, 20))
print(calCircleArea(10)) |
ab58b7e5dc6154c21c89b647cfda70bc03cba0ad | olanlab/python-bootcamp | /08-errors-exceptions/errors-exceptions-04.py | 334 | 3.609375 | 4 | numbers = [1, 2, 3, 4, 5]
dict = {
"firstname" : "Olan",
"lastname" : "Samritjiarapon",
"hp" : 100,
"mp" : 50
}
try :
print(dict['sp'])
except IndexError :
print("IndexError")
except KeyError :
print("KeyError")
else : # NO ERROR OR NO EXCEPTION
print("No Error!!")
finally :
prin... |
044abb18139107ab00b632ea236c27cca5386357 | olanlab/python-bootcamp | /16-data/seaborn/seaborn-10.py | 248 | 3.5625 | 4 | import seaborn as sns
import matplotlib.pyplot as plt
# Load sample dataset
iris = sns.load_dataset("iris")
# Create a joint distribution plot
sns.jointplot(data=iris, x="sepal_length", y="sepal_width", hue="species")
# Show the plot
plt.show()
|
e39e6b47e2923eb0781f45f313e6883295c99662 | olanlab/python-bootcamp | /15-graphic/graphic-03.py | 440 | 3.515625 | 4 | from turtle import Turtle, colormode, Screen
import random
colormode(255)
t = Turtle()
def random_color():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return (r, g, b)
# CODE 5
directions = [0, 90, 180, 270]
t.pensize(15)
t.speed("fastest")
for _ in range(200):... |
83cff826412cb25b16d91a7f9a52533b9fa257a4 | olanlab/python-bootcamp | /02-varibles/words.py | 104 | 3.90625 | 4 | sentence = input("Enter a sentence: ")
words = sentence.split()
print("Number of words:", len(words))
|
c1af18321730e09b0da5f86d165639716a32b2e0 | olanlab/python-bootcamp | /16-data/pandas/pandas-04.py | 578 | 4.03125 | 4 | import pandas as pd
data = {'Name': ['John', 'Emma', 'Tom', 'Emily', "North", "Seen"],
'Age': [25, 28, 23, 27, 38, 38],
'City': ['New York', 'San Francisco', 'London', 'Paris', 'BKK', 'BKK']}
df = pd.DataFrame(data)
df['Salary'] = [50000, 60000, 45000, 55000, 20000, 30000] # Add a new column
# pri... |
80c73811cfaa128b701896b58524c631feaeadd0 | olanlab/python-bootcamp | /05-loop/prime-number.py | 214 | 3.984375 | 4 | number = int(input("Enter your number : "))
for i in range(2, (number + 1), 1) :
for j in range(2, i, 1) :
if (i % j == 0) :
break
else :
print(str(i) + " ", end = "")
|
6ea70ec00ea491c902ad83bec62b203dd7b2378a | olanlab/python-bootcamp | /13-gui/login.py | 2,455 | 3.96875 | 4 | import tkinter as tk
# Create main window
root = tk.Tk()
root.title("Login")
customer_frame = tk.Frame(root)
def login():
username = username_entry.get()
password = password_entry.get()
# Perform login validation here
if username == "admin" and password == "password":
root.title("Customer Re... |
8ea37257b88dd503e23d75faebdde7c75a013b02 | olanlab/python-bootcamp | /10-file-io/excel-01.py | 520 | 3.5 | 4 | from openpyxl import load_workbook
# READ
wb = load_workbook(filename = "students.xlsx")
sheet = wb.active
# READ SINGLE CELL
print(sheet['A1'].value)
print(sheet.cell(row=1, column=1).value)
# READ MULTIPLE CELLS
cells = sheet['A1' : 'C4']
for row in cells :
for cell in row :
print(cell.value, end = " "... |
56579e969680d0dabdb5094b91bd8e6e437ce836 | olanlab/python-bootcamp | /05-loop/line-01.py | 135 | 4.03125 | 4 | number = int(input("Enter your size of line : "))
i = 1
str = ""
while i <= number :
str += "*"
i += 1
else :
print(str)
|
668bfccda2a40d9264c03e5f3c0e50c4b21b0124 | olanlab/python-bootcamp | /16-data/matplotlib/matplotlib-06.py | 470 | 3.78125 | 4 | import matplotlib.pyplot as plt
import numpy as np
# Generate data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
# Create a 3D surface plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis')
# Cust... |
4a430af7cf230539a5b6710badb5a29d1a856e9a | olanlab/python-bootcamp | /04-condition/condition-02.py | 144 | 3.8125 | 4 | a = False
b = True
print("a = " + str(a), "b = " + str(b))
print("a and b is ", a and b )
print("a or b is ", a or b)
print("not a is", not a)
|
e9e63d87673ace7b9e57b528aff0b2e4199bfc36 | olanlab/python-bootcamp | /16-data/numpy/numpy-04.py | 458 | 3.890625 | 4 | import numpy as np
# Create an array
arr = np.array([1, 2, 3, 4, 5])
# Mean of the array
mean_val = np.mean(arr)
print("Mean:", mean_val)
# Standard deviation of the array
std_dev = np.std(arr)
print("Standard Deviation:", std_dev)
# Sum of the array
sum_val = np.sum(arr)
print("Sum:", sum_val)
# Maximum value in ... |
99b20b2526697a1eb6b5366aa9cef124f5cbab30 | olanlab/python-bootcamp | /15-graphic/graphic-04.py | 792 | 4.09375 | 4 | import turtle
# Set up the turtle screen
screen = turtle.Screen()
screen.setup(600, 600)
# Create the turtle object
t = turtle.Turtle()
# Define the data for the bar graph
data = [50, 75, 100, 85, 60]
# Set the size of the bar graph
bar_width = 50
bar_height = 200
# Set the starting position for the turtle
x_start... |
79f0cc528b5b889551433d376e781a8ad2082ca9 | olanlab/python-bootcamp | /16-data/matplotlib/matplotlib-05.py | 242 | 3.65625 | 4 | import matplotlib.pyplot as plt
# Data
labels = ['A', 'B', 'C', 'D']
sizes = [25, 30, 20, 25]
# Create a pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
# Customize the plot
plt.title("Pie Chart")
# Display the plot
plt.show()
|
ebd6e607a3ac90eafbf16b223b5c186f187939c9 | andreusjh99/CamCwk | /IA_Flood_Warning_System/floodsystem/station.py | 2,175 | 3.578125 | 4 | """This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id, label, coord, typical_range,
river, town... |
2857a9205b65cde37b54cf6e025287b897eee255 | cameronbracco/DS-3000-Final-Project-Pub | /src/data_to_industry_totals.py | 5,559 | 3.828125 | 4 | import pandas as pd
import sys
import os
# READ: This program accrues data from the csv's in ~/data/{industry}/{year} and saves the totals of how much each recipient received from
# this industry to a .csv file in ~/data-totals/accumulated-totals/{year}/{industry}-totals.csv as well as
# ~/data-totals/annual-totals/{... |
a1c4e25c5608a1097f71d22db51a3b51aabcafaa | RadchenkoVlada/tasks_book | /python_for_everybody/task9_2.py | 1,098 | 4.3125 | 4 | """
Exercise 2:
Write a program that categorizes each mail message by which day of the week the commit was done.
To do this look for lines that start with “From”, then look for the third word and keep a running count of each of
the days of the week. At the end of the program print out the contents of your dictionary (o... |
804ec370c29b1d0cafdae1cf1a2615abf4b3f766 | RadchenkoVlada/tasks_book | /python_for_everybody/task10_2.py | 1,521 | 4.3125 | 4 | """
Exercise 2:
This program counts the distribution of the hour of the day for each of the messages. You can pull the hour
from the “From” line by finding the time string and then splitting that string into parts using the colon character.
Once you have accumulated the counts for each hour, print out the counts, one ... |
4679cb3a8cdfb6386c4c6edf312dc9863c57fed2 | RadchenkoVlada/tasks_book | /CRUD_Student/Storage_json.py | 764 | 3.5 | 4 | import json
from Storage import Storage
from Student import Student
class StorageJSON(Storage):
def __init__(self):
self._file_name = "students.json"
def save(self, students):
with open(self._file_name, "w") as write_file:
# method dump() is used to write data to files
... |
86de60fccaa7393daa94e67f1e0e8c25e59f8e30 | RadchenkoVlada/tasks_book | /python_for_everybody/task7_2.py | 2,907 | 4.46875 | 4 | """
Exercise 2: Write a program to prompt for a file name, and then read through the file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:”
pull apart the line to extract the floating-point number on the line.
Count these lines and then compute ... |
36f1ba59cabda8456eec493e9211e0c1e2c52756 | RadchenkoVlada/tasks_book | /python_for_everybody/task5_1.py | 909 | 4.09375 | 4 | """
Exercise 1:
Write a program which repeatedly reads numbers until the user enters “done”.
Once “done” is entered, print out the total, count, and average of the numbers.
If the user enters anything other than a elem,detect their mistake using try and
except and print an error message and skip to the next elem.
Ent... |
e164e4a1b53cdc17bb06540817987c815e4610c0 | Jasonzyy9/PythonTraining | /weight converter.py | 336 | 4.15625 | 4 | print("What's your weight? ")
weight = int(input("Weight: "))
select = input("(L)bs or (K)g: ")
if select.upper() == "L":
weight = weight * 0.45
print(f"You are {weight} kilograms")
elif select.upper() == "K":
weight = weight * 2.2
print(f"You are {weight} pounds")
else:
print("Please type... |
af7cede9488b3ccbf48651f083527fe9d0b81eb9 | tomas-surik/IntegerProgramming | /Optimisation.py | 6,535 | 3.75 | 4 | """
OPTIMISATION FUNCTIONS
This code is based on my solution of an optimisation problem I had to solve.
It is an integer programming problem. The goal is to select options that
results in the lowest costs. Number of options that must be selected is set.
All available options have a set of three costs assigned to th... |
10ec91dd7721225830f0ce8d658188b389cc0b03 | Arverkos/GeekBrains-Homeprojects | /Lesson06/Lesson06.Task04.py | 2,262 | 4.15625 | 4 | class Car:
def __init__(self, speed, colour, name, is_police):
self.speed = speed
self.colour = colour
self.name = name
self.is_police = is_police
def go(self):
print(f'Машина {self.name} {self.colour} поехала')
def stop(self):
print(f'Машина {sel... |
5e61d15732b912b4314b57932120895426e7db4b | Arverkos/GeekBrains-Homeprojects | /Lesson04/Lesson04.Task04.py | 139 | 3.53125 | 4 | my_list = [1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
new_list = [el for el in my_list if my_list.count(el) == 1]
print(new_list)
|
78c291537577b6f374d7ac056881d2ce229ef9a4 | Arverkos/GeekBrains-Homeprojects | /py_intro01/Task04.py | 1,049 | 3.8125 | 4 | #Вводим число n
n = int(input('Введите число n (n - целое, положительное): '))
#Далее необходимо найти количество цифр в числе
figure_index = 10
number_of_figure = 1
while True:
if n // figure_index == 0:
break
else:
figure_index = figure_index*10
number_of_figure += 1
#Печатаем количество цифр в... |
27c1467acbdc44fae8595edb5047b09a68a81cfa | Arverkos/GeekBrains-Homeprojects | /Lesson05/Lesson05.Task05.py | 1,060 | 3.515625 | 4 | # Первая часть задачи - создание текстового файла
with open('task05.txt', 'w', encoding='utf-8') as f:
print(f'Файл {f.name} открыт для записи, выполняйте дальнейшие инструкции')
numbers = input('Введите последовательность чисел, разделенных пробелами: ')
f.write(numbers)
print(f'Данные записаны, п... |
8e2da82c11b1219244125bc5e61ec169ef7b3533 | Arverkos/GeekBrains-Homeprojects | /Lesson06/Lesson06.Task01.py | 1,132 | 3.8125 | 4 | from itertools import cycle
import time
class TrafficLight:
__colour = {'Красный': 7,
'Желтый': 2,
'Зеленый': 10}
def running(self):
number = int(input('Светофор начинает работу, введите количество циклов "КЖЗ": '))
c = 0
for el in cycle(sel... |
d4c6a4b1bc605f3ef3664e00308565590cb41148 | Arverkos/GeekBrains-Homeprojects | /Lesson08/Lesson08.Task03.py | 495 | 3.640625 | 4 | class NotNum(Exception):
def __init__(self, txt):
self.txt = txt
new_list = []
while True:
try:
inp_num = input('Введите число, либо "stop" чтобы закончить ввод: ')
if inp_num == 'stop':
break
if inp_num.isalpha():
raise NotNum('Вы ввели не... |
354ae4fc3abd7e779400202afd3804cf4f707a85 | WikiGenius/int_team | /oop.py | 808 | 3.515625 | 4 | class Person:
def __init__(self,name,address,phone):
self.name = name
self.address = address
self.phone = phone
def generatecode(self):
pass
def getName(self):
return self.name
def getAddress(self):
return self.address
def getPhone... |
342ec86d210a77162b489c42d788703070c8a694 | nd955/CodingPractice | /HighestProductOfThree.py | 858 | 4.15625 | 4 | import math
def get_highest_product_of_three(input_integers):
highest_product_of_3 = 0
highest_product_of_2 = 0
highest_number = 0
lowest_product_of_2 = 0
lowest_number = 0
for i in range(len(input_integers)):
highest_product_of_3 = max(highest_product_of_3, highest_product_o... |
d12bb7f15c87b5a9633ad03feaaa2aa2ccaec11e | ricardoabcd3/python | /medium_python/Untitled-1.py | 131 | 3.6875 | 4 | def main():
dic = {i: i**3 for i in range(1,101) if i % 3 != 0}
print(dic)
if __name__== '__main__':
main() |
4a95a1f10ff29f7745f2ccafa2ff2c83663e371c | green-fox-academy/fehersanyi | /python/dataStructures/d2.py | 869 | 4 | 4 | students = [
{'name': 'Rezso', 'age': 9.5, 'candies': 2},
{'name': 'Gerzson', 'age': 10, 'candies': 1},
{'name': 'Aurel', 'age': 7, 'candies': 3},
{'name': 'Zsombor', 'age': 12, 'candies': 5}
]
# create a function that takes a list of students and prints:
# - Who has got more candies th... |
486501ac24a31929fb1f621562a4f610de01c13c | green-fox-academy/fehersanyi | /python/dataStructures/l3.py | 533 | 4.125 | 4 | # Create a function called 'create_new_verbs()' which takes a list of verbs and a string as parameters
# The string shouldf be a preverb
# The function appends every verb to the preverb and returns the list of the new verbs
verbs = ["megy", "ver", "kapcsol", "rak", "nez"]
preverb = "be"
def create_new_verbs(preverb, ... |
4ee141f99c9add350460ffb6efd548b84ccce013 | sharonjanagal/Python_Tutorial_IITI | /addnumbers.py | 398 | 4.09375 | 4 | import sys
"""
This is simple python script to add numbers
as input from the terminal
"""
def AddPositiveNumbers(a, b, c=None):
if c == None:
c = 0
print "The sum of %f and %f is %f"%(a,b,a+b)
else:
print "The sum of %f, %f and %f is %f"%(a,b,c,a+b+c)
if __name__=="__main__":
a = ... |
9e49a190f863a0a375e5fcaee7d9e52d2cde6f18 | JuanPa09/EDD_2S2019_P2_201700450- | /Practica2/Menu.py | 5,991 | 3.5 | 4 | import os,sys
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from CargaMasiva import CargaMasiva
from Estructuras import Arbol
from Estructuras import ListaDoble
import json
class Menu():
def __init__(self,lista,server):
self.index=0
self.json_seleccionado=N... |
c37b89baa796da7e4ff9e43508a75c3f277cb76d | feifeidadi/python | /[py pour enfant]/star3.py | 229 | 3.515625 | 4 | import turtle
t = turtle.Pen()
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.left(90)
t.forward(50)
t.reset()
for x in range(1, 38):
t.forward(100)
t.left(175)
input("Press any key to continue")
|
7bba0ddb6fc195398f64ddc5d83f7ab02d51eabd | Cristiand19/Python---2020 | /15).py | 565 | 3.796875 | 4 | import numpy as np
N = int(input("Dimension"))
A = np.empty(N,dtype=int)
#Carga del vector
for i in range(0,N):
A[i] = int(input("Ingrese un numero:"))
#Buscar numero
c = 0
x = int(input("Ingrese el numero que desea buscar en el vector:"))
for i in range(0,N):
if A[i] == x:
print("El nu... |
87fbe9b832ecf321d9514a2f769d52a02ca17765 | jessymiyoshi/401-exercicios | /python.py | 1,033 | 4.15625 | 4 | # #PROGRAMA QUE CALCULA A MÉDIA
n1 = int(input("Digite a sua N1: "))
n2 = int(input("Digite a sua N2: "))
n3 = int(input("Digite a sua N3: "))
n4 = int(input("Digite a sua N4: "))
media = (n1+n2+n3+n4)/4
print("Sua média é {}" .format(media))
# #PROGRAMA ESTATISTICA DE LETRA
frase = input("Digite uma frase: ")
letra ... |
0786baf127c89c8ce2fcebd51a91562c4b4cd2ca | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Strings/1241 - Fit or Dont Fit II.py | 108 | 3.546875 | 4 | for _ in range(int(input())):
A, B = input().split()
print(['encaixa', 'nao encaixa'][A[-len(B):] != B]) |
2025eab3353ca06d36c4ed7daca9002c9f552859 | prudentprogrammer/Programming-Challenges-Solutions | /Codeforces/Education_Codeforces_Round_1/C_Nearest_Vectors.py | 798 | 3.609375 | 4 | from math import atan2, pi
vectors = []
for i in range(int(input())):
x, y = [int(x) for x in input().split()]
vectors.append((atan2(y, x), i + 1))
vectors.sort()
min_diff = float('+inf')
first_ind = second_ind = -1
n = len(vectors)
# print(vectors)
# The key here is to compare the difference between ith
# and... |
8409be2a484a56fefcfe5b8ed3dca74030dc803c | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Beginner/1042 - Simple Sort.py | 362 | 3.734375 | 4 | A, B, C = [int(x) for x in input().split()]
res = [A, B, C] # assumption C > A and C > B and B > A
if A > B:
res = [B, A, C]
if B > A and B > C:
if A > C:
res = [C, A, B]
else:
res = [A, C, B]
if A > B and A > C:
if C > B:
res = [B, C, A]
else:
res = [C, B, A]
for num in res:
print(num)
... |
813eb578d68322b044f0463e16633090bcb22f73 | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Strings/1263 - Alliteration.py | 411 | 3.765625 | 4 | while True:
try:
sentence = input()
prev = count = 0
in_group = False
seen = '#'
for word in sentence.split():
first_letter = word[0].lower()
if first_letter == seen:
in_group = True
else:
seen = first_letter
if in_group:
count += 1
in... |
96ef1ef26c4e439d9f82ee68ee34ed38ad1dfff5 | prudentprogrammer/Programming-Challenges-Solutions | /uvaProblems/12478 Hardest Problem.py | 1,587 | 3.625 | 4 | # Link: https://uva.onlinejudge.org/external/124/12478.pdf
from collections import Counter
# Easy solution: Accepted
# You just scan it by hand and print the answer.
# print('KABIR')
# REAL way ;)
# Programmer's don't cheat (especially when it comes to algorithms :D )
names = [ 'RAKIBUL', 'ANINDYA', 'MOSHIUR', 'SHIP... |
f4040fd406c8818eda7f6d79cdbe56dcbc509703 | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Beginner/1037 - Interval.py | 297 | 3.609375 | 4 | num = float(input())
if num < 0 or num > 100:
print('Fora de intervalo')
outputs = ['[0,25]', '(25,50]', '(50,75]', '(75,100]']
for ind, (a, b) in enumerate([[0, 25], [25.00001, 50], [50.00001, 75], [75.00001, 100]]):
if a <= num <= b:
print('Intervalo {}'.format(outputs[ind]))
break |
ec9d246afaf6001495e52fd13ffbd958d4e59e87 | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Beginner/1043 - Triangle.py | 196 | 3.59375 | 4 | A, B, C = [float(x) for x in input().split()]
if A + B > C and B + C > A and C + A > B:
print('Perimetro = {:.1f}'.format(A + B + C))
else:
print('Area = {:.1f}'.format( ((A + B) * C) / 2.0) ) |
3395fdecc6ca85ac31f98d423af09606aeb42b7d | prudentprogrammer/Programming-Challenges-Solutions | /uvaProblems/11172 Relational Operators.py | 250 | 3.609375 | 4 | # Problem: UVa 11172 - Relational Operators
# Link: https://uva.onlinejudge.org/external/111/11172.pdf
for _ in range(int(input())):
x, y = map(int, input().split(' '))
if x < y:
print("<")
elif x > y:
print(">")
else:
print("=") |
161125fea6ccc2dc226b9fbc98b77aadde88eb6b | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Beginner/1020 - Age in Days.py | 211 | 3.625 | 4 | age = int(input())
names = ['ano(s)', 'mes(es)', 'dia(s)']
for ind, unit in enumerate([365, 30, 1]):
count = int(age / unit)
print('{} {}'.format(str(count), names[ind]))
if count > 0:
age = age % unit |
2fef4b307ddaa7fd410201d4d14a5421d2d91104 | prudentprogrammer/Programming-Challenges-Solutions | /uriProblems/Beginner/1008 - Salary.py | 197 | 3.796875 | 4 | number = int(input().strip())
hours = int(input().strip())
amount_per_hour = float(input().strip())
print('NUMBER = {}'.format(number))
print('SALARY = U$ {:.2f}'.format(amount_per_hour * hours)) |
5feb8f74a6fbfb7665726d5abb0b1352a72e5110 | prudentprogrammer/Programming-Challenges-Solutions | /HackerEarth/1D/binaryQueries.py | 813 | 3.71875 | 4 | # Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/range-query-2/
from enum import Enum
# Make it more readable using enums
class QueryEnum(Enum):
EVENORODDQUERY = 0
FLIPBITQUERY = 1
n, q = map(int, input().split())
bitArray = list(map(int, input().split()))
for ... |
60230f33d4ee74fe4f70722fa443da99b47a05de | kitsmart/schoolwork | /olympics/olympics.py | 1,065 | 3.734375 | 4 | import csv
exists = False
rows = []
event = input("Input the name of the event: ")
gender = input("Input the gender of the competitor: ")
time_h = float(input("Input the hours taken: "))
time_m = float(input("Input the minutes taken: "))
time_s = float(input("Input the seconds taken: "))
time = time_h*3600+time_m*60... |
49b5e88a53fd9e1d0965ec3e72931135e06ab8d5 | Allien01/PY4E | /02-data-structure/files/01.py | 255 | 4.15625 | 4 | fname = input("Enter the name of the file: ")
try:
fhandle = open(fname)
except:
print("This is not a existing file!")
exit()
for line in fhandle: # imprime cada linha do arquivo em maiúsculo
line = line.rstrip()
print(line.upper())
|
588145befcd4018ac3aa1088a072e51af1d1ab22 | forevermankind/ControlSim | /modules/control.py | 3,063 | 3.53125 | 4 | from abc import ABC, abstractmethod
import numpy as np
class Controller(ABC):
@abstractmethod
def __init__(self, setpoint):
self.setpoint = setpoint
@ abstractmethod
def get_control_action(self, state_vector):
pass
class PID(Controller):
def __init__(self, K_p=1, K_i=1, K_d=1, ... |
a849a1b9c6be8502387d9a362fa65d0d526ba77f | alvaromb98/Curso-Python | /helloworld.py | 350 | 3.984375 | 4 | #este código imprime "Hello World por pantalla"
print("Hello world") # da igual
print('Hello world') # el tipo de comillas
print("""Hello world""") # y el número de éstas
print (type("Hello World")) # devuelve el tipo de dato que tiene dentro del paréntesis
print ("Hello" + "World") # ... |
2443271e07b6fd65241f6cab6e38fdb097b687b0 | alvaromb98/Curso-Python | /numbers.py | 488 | 3.90625 | 4 | print(2**3) #El operador ** equivale a la potencia ^. Devolverá 8
print(3//2) #Me devolverá el resto, 1. Equivale a 3%2
#Es muy común que tenga que trabajar con datos que introduce el cliente. Por eso usaremos la función input
age = input("Insert your age: ")
#Si ahora quisiera operar con ese número que ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.