blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
febcd0ffccaaae5d6ca072db5433f7d3ff8fc96f | TheElementalOfDestruction/creatorUtils | /creatorUtils/forma.py | 4,802 | 3.65625 | 4 | """
Formatting package of creatorUtils.
"""
import os
import hashlib
import math
import sys
import time
from creatorUtils.compat.types import *
#Constants
LITTLE = True # Marker for little endian
BIG = False # Marker for big endian
##-------------------STRING-------------------##
def divide(strin... |
620350ad0044b57481be8073fba61c60acb8ebdd | Rhosid/PythonWars | /Projects/sumList.py | 964 | 3.828125 | 4 | """
Name: sumList.py
Description: sums all the digits in the list
Version: 1.0.0
Python: 3.3.5
"""
__author__ = "Spencer Dockham"
__date__ = "10/29/2014"
# DEF
def checkString(string):
for ch in string:
if ch not in numbet:
return False
return True
def addString(string):
total = 0
... |
0be3b5597b8245be7571c59259a1aaec5bcafba6 | fob413/TicTacToeApi | /app/main/utils/validation.py | 869 | 3.9375 | 4 | def board_is_present(board):
"""validate board exists"""
if board:
return True
else:
return False
def validate_length(board):
"""validate length of the board"""
if len(board) is 9:
return True
else:
return False
def validate_characters(board):
"""validate player and server characters"""
allowed_cha... |
0f7c3ae3ca9f584cdeb424c04b1f6b2a9a8317d5 | gitStudyToY/PythonStudy | / name_cases.py | 736 | 4.21875 | 4 | message = "Eric"
print("Hello " + message + ", would you like to learn some Python today?" )
print(message.title())
print(message.upper())
print(message.lower())
message = "Albert Einstein once said, 'A person who never made a mistake never tried anything new.'"
print(message)
famous_person = "Albert Einstein"
famou... |
2d002aa39b0ef845d7044f52ecfec05ac0497429 | dxab/SOWP | /ex2_11.py | 342 | 3.84375 | 4 | #Male and Female Percentages
males = float(input('How many men are in your class?'))
females = float(input('How many women are in your class?'))
totalclass = males + females
percentm = males / totalclass
percentf = 1-percentm
print(format(percentm, '.1%'), "of students are male in your class, and", format(percentf, '.... |
aaf077c666e7c6d687e953d9b3e7d35596e7f430 | dxab/SOWP | /ex2_9.py | 427 | 4.5 | 4 | #Write a program that converts Celsius temperatures to Fahrenheit temp.
#The formula is as follows: f = 9 / 5 * C + 32
#This program should ask the user to enter a temp in Celsius and then
#display the temp converted to Fahrenheit
celsius = float(input('Please enter todays temperature (in celsius): '))
fahr = 9 / 5 *... |
c6e8a77fe5d0c2d061bcf1c7af24913ee304935f | davsingh/SI206 | /madlibhw3.py | 1,879 | 3.671875 | 4 | # Using text2 from the nltk book corpa, create your own version of the
# MadLib program.
# Requirements:
# 1) Only use the first 150 tokens
# 2) Pick 5 parts of speech to prompt for, including nouns
# 3) Replace nouns 15% of the time, everything else 10%
# Deliverables:
# 1) Print the orginal text (150 tokens)
# 1)... |
af0f2e3a6375ce20afcb04e0df1b971d679685f4 | jocoder22/PythonDataScience | /OOP/try_except.py | 1,348 | 3.765625 | 4 | #!/usr/bin/env python
from printdescribe import print2
class SalaryError(ValueError):
pass
class HourError(ValueError):
_message = "Hours out of range!"
def __init__(self):
ValueError.__init__(self)
def __str__(self):
print(HourError._message)
return HourError._message
... |
5e24782f10d7f439c435626f5ff82b722a09101c | jocoder22/PythonDataScience | /NewPackages/mypackage/util.py | 2,721 | 3.5625 | 4 | from collections import Counter
import matplotlib.pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
import string
def print2(*args):
"""
Function that print descriptive s... |
bb2c7002901bab1dbf1280e4572663fb0a07ec3e | jocoder22/PythonDataScience | /OOP/operators.py | 1,089 | 3.515625 | 4 | #!/usr/bin/env python
from printdescribe import print2
class Patients:
def __init__(self, name, id, gender):
self.name = name
self.id = id
self.gender = gender
def __eq__(self, other):
return self.name == other.name and self.id == other.id\
and type(self) == type(... |
b09564d1645c3fd85fe53ca794e2d20a31a253bf | jocoder22/PythonDataScience | /importingData/localData/jsonfile.py | 562 | 3.671875 | 4 | #!/usr/bin/env python
import json
def print2(*args):
for arg in args:
print(arg, end='\n\n')
params = {"sep":"\n\n", "end":"\n\n"}
with open('myfile.json', 'r') as json_file:
jsonData = json.load(json_file)
type(jsonData) ## dict
for key, value in jsonData.items():
print(f'{key... |
f5e52e4e521318372d7cc14698bf3e07fa10d440 | jocoder22/PythonDataScience | /functions.py/decorator3.py | 1,036 | 4.03125 | 4 | #!/usr/bin/env python
import os
from functools import wraps
def print2(*args):
for arg in args:
print(arg, end='\n\n')
sp = {"sep": "\n\n", "end": "\n\n"}
def mycounter(func):
"""
"""
@wraps(func)
def mywrapper(*args, **kwargs):
result = func(*args, **kwargs)
mywrapp... |
72930c1545845fb65cdbccf0c0d5dd75b4bada43 | jocoder22/PythonDataScience | /computational_finance/cva.py | 6,541 | 3.734375 | 4 | #!/usr/bin/env python
import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random
import progressbar, tqdm
from scipy.stats import norm
def print2(*args):
for arg in args:
print(arg, sep="\n\n", end="\n\n")
# 1. Write a function which takes a risk-free rate, ... |
d23baf8c78e7feb95ea7c95b2e919f8c1959e339 | jocoder22/PythonDataScience | /importingData/relationalDB/sqlalchemy/connecting.py | 981 | 3.546875 | 4 | #!/usr/bin/env python
# Import necessary module
import os
from sqlalchemy import create_engine, MetaData, Table, select
print(engine.table_names()) # ['Person', 'Site', 'Survey', 'Visited']
"""
survey = Table('Survey', metadata, autoload=True, autoload_with=engine)
ssmt = select([survey])
print(ssmt)
results... |
50282feebd1d39828b1c619b6db0839103161941 | jocoder22/PythonDataScience | /pandas/datamgt/stringManipulation.py | 723 | 3.53125 | 4 | from pandas import DataFrame
import re, string
from datetime import datetime
eassy = """This is the begining of time. But with all good and noble
intention comes failure, only work hard as you and others
can and expect the best. Be careful while going slowly
on a journey of life."""
... |
55198f51c0659fa110caa69f069dace6c8f41ffb | jocoder22/PythonDataScience | /DataFrameManipulation/indexing.py | 974 | 3.96875 | 4 |
# Import pandas
import matplotlib.pyplot as plt
import pandas as pd
# Reindex weather1 using the list year: weather2
weather2 = weather1.reindex(year)
# Print weather2
print(weather2)
# Reindex weather1 using the list year with forward-fill: weather3
weather3 = weather1.reindex(year).ffill()
# Print weather3
print... |
6ce847483d6be92cf458476bf21cb51c7542483d | jocoder22/PythonDataScience | /importingData/relationalDB/sqlalchemyQuery.py | 25,650 | 3.578125 | 4 | # #####################creating database
from sklearn import preprocessing
import pandas as pd
from PIL import Image
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
from sqlalchemy import Table, Column, String, Integer, Float, Boolean
import os
path = 'D:\PythonDataScience\importingData\webDa... |
2bd5e2556a3706a7f186ff01dd0d641005a7a508 | snehaa2632000/Scientific-Computing | /Newton_Raphson.py | 1,001 | 3.8125 | 4 | import numpy as np
from sympy import *
x = symbols('x')
#inp = input('Enter the exp :')
expr = 2 * x**3 - 2 * x - 5
print("Given expression : {}".format(expr))
expr_diff = expr.diff(x)
print("Derivative of expression with respect to x : {}".format(expr_diff.doit()))
f = lambdify(x,expr,'numpy')
f_diff ... |
729f34288c56863ac66284f3a1b1ae7e9edc56ce | SoumyadeepDey2002/MachineLearning_and_DeepLearning | /Python basics for ML 1/18_birthday.py | 106 | 4.03125 | 4 | birthday = input('What\'s your birthday?')
age = 2021 - int(birthday) -1
print(f'your age is {age}') |
3626abcfc689afecdd6d74aca9ed4ebdbc157ed2 | SoumyadeepDey2002/MachineLearning_and_DeepLearning | /Python basics for ML 1/07_bin_complex.py | 198 | 3.96875 | 4 | complex
#data type to store complex numbers
print(bin(7))
print(bin(5))
# decimal to binary
# 0b represents that it's binary
print(int('0b101',2))
#convert base 2 to 10 which is decimal
|
fe0ed51cf0cdab74d7d87b9f8317e18776d0c27d | ostanleigh/csvSwissArmyTools | /dynamicDictionariesFromCSV.py | 2,363 | 4.25 | 4 | import csv
import json
from os import path
print("This script is designed to create a list of dictionaries from a CSV File.")
print("This script assumes you can meet the following requirements to run:")
print(" 1) The file you are working with has clearly defined headers.")
print(" 2) You can review the headers ('.h... |
0635e54f09efc07afe7d10dd199422e4923ff5cf | Lee7goal/lee7_2019 | /python高级/lee7_创建property属性的方式装饰器.py | 927 | 3.5625 | 4 | # coding = utf-8
# Version:Python3.7.3
# Tools:Pycharm 2017.3.2
__date__ = '2019/4/21 0021 21:21'
__author__ = 'Lee7'
class Goods:
def __init__(self):
# 原价
self.original_price = 100
# 折扣
self.discount = 0.8
@property
def price(self):
# 实际价格 = 原价 * 折... |
860e71a0d01ad592ff68ba81394f3fafcaac97a8 | Lee7goal/lee7_2019 | /Machine_learning/05_07_02demo.py | 427 | 3.765625 | 4 | # coding=utf-8
# Version:3.6.3
# Tools:Pycharm
__date__ = ' 2019/5/7 12:37'
__author__ = 'lee7goal'
# strings = ['a', 'as', 'bat', 'car', 'dove', 'python']
# print([x.upper() for x in strings if len(x) > 2])
some_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
flattened = [x.__float__() for tup in some_tuples for x ... |
7726ff58eed732d19877462105b37b8b1e24b538 | StefanTobler/HeavyFailure | /hack.py | 2,045 | 3.84375 | 4 | # Hacking Maintenance closet to get tool box
import paths
import parts
import maze
import random
import os
import time
clear = lambda: os.system("cls")
# Simple algebra problem, I wish I could make it more interactive
def hacking():
# Creates 2 numbers num2 can be anywhere between 1 and 5 times larger than num1... |
418886582c9050a100c75b3105b181d53cf3ad1b | SakaiMasato/pythonTest | /task/demo/renameDates.py | 948 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' file traverse then rename the date from MM-DD-YYYY to MM-DD-YYYY '
__author__ = 'Bob'
import os, re
path = os.path.join(os.path.abspath('.'), 'renameDatesDatas')
filePaths = os.listdir(path)
def findAmericanDate(str):
regex = r'''
((0\d)|(1[012])) ... |
b17242db6b0538bc876043e7bdde6e9c7b5f5a37 | SakaiMasato/pythonTest | /task/chapter6_task_displayInentory.py | 709 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' display inventory '
__author__ = 'Bob Bao'
def displayInventory(dic):
print('Inventory:')
totalNum = 0
for k, v in dic.items():
print(k,' ',v)
totalNum += v
print('Total number of items: ', totalNum)
def addToInventory(inventory, addedI... |
338448b8a3a314d1a45bcdef05ebefb03b7d3123 | on-merrit/ON-MERRIT | /WP3/Task3.3/src/utils/file_utils.py | 1,882 | 3.78125 | 4 | """Utilities for working with files (e.g. creation of dated folders)
"""
import os
from datetime import datetime
class FileUtils(object):
@staticmethod
def ensure_dir(dir_path: str) -> None:
"""Create directory (including parent directories) if it does not exist.
:param dir_path: dir... |
32ed93f11b342e7ff62bc9eaa83d7e3f5ed41e2c | zhogan85/zth_new_coder | /dataviz/graph.py | 2,814 | 3.65625 | 4 | import csv
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter
MY_FILE = "sample_sfpd_incident_all.csv"
def parse(raw_file, delimiter):
"""Parses a raw CSV file to a JSON-like object."""
#open csv file
opened_file = open(raw_file)
#read csv file
csv_data = csv.reader(opened_file,... |
9d9418791dd153f6df877edbb8d35f64c56360bd | Rubyroobinibu/pythonpractice | /python 15.09.19/inheritance.py | 969 | 3.75 | 4 | class A:
def m1(self):
print("method 1")
def m2(self):
print("method 2")
class B(A): #B class acquires properties of A #single inh
def m1(self): #mtd overriding
print("called from B")
def m3(self):
print("method 3")
def m4(self):
return "method 4... |
77aeacb8eec0dac1b258e9cba1b78c8f32a2577b | pauldubois98/PrimesGame | /primes.py | 907 | 3.609375 | 4 | from random import choice
def primeRange(mini, maxi):
###fonding primes
#init
l=[True for i in range(maxi)]
#case 0 & 1
l[0], l[1]=False, False
#extraction of the primes numbers
for a in range (2,int(maxi/2)+1):
if l[a]:
for i in range (a*a,maxi,a):
if l... |
c21fae89fda3395df34e09a78cfefa990836159a | Aafreen29/digit_recognition_opencv | /model_build.py | 2,232 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 4 09:08:41 2018
@author: Aafreen Dabhoiwala
"""
# importing keras libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.utils.np_util... |
355e2f783c7d3928436eef46e0c94d31125fe899 | ravi501/dataanalyst-udacity | /p2-investigatingadataset/final-project/titanic-data-analysis-pandas.py | 4,008 | 3.859375 | 4 | import unicodecsv
import pandas as pd
import matplotlib.pyplot as plt
"""
Load Data from CSVs
The first step in the process would be to load the data from the CSV file into our data dictionary.
"""
def read_csv_file(filename):
with open(filename, 'rb') as f:
reader = unicodecsv.DictReader(f)
retur... |
1cc2d81fb38544d7e6d8f195f47bdc1c5aa5d6fe | duckietown-udem/udem-fall19-public | /notebooks/code/exercise_03_control/controller.py | 2,319 | 3.53125 | 4 | import numpy as np
class Controller():
def __init__(self):
self.gain = 2.0
pass
def angle_control_commands(self, dist, angle):
# Return the angular velocity in order to control the Duckiebot so that it follows the lane.
# Parameters:
# dist: distance from the cente... |
89ec0897f99163edb014c185425b3054332f6dbe | RamyaRaj14/assignment5 | /max1.py | 258 | 4.25 | 4 | #function to find max of 2 numbers
def maximum(num1, num2):
if num1 >= num2:
return num1
else:
return num2
n1 = int(input("Enter the number:"))
n2 = int(input("Enter the number:"))
print(maximum(n1,n2)) |
cbb74e2a3e69c3c27ecda584ac2f632c0820db49 | jaynarayan94/API-Applications-Projects | /Stock News/main.py | 2,988 | 3.515625 | 4 | import requests
from twilio.rest import Client
STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
STOCK_API_KEY = "STOCK_API_KEY"
NEWS_API_KEY = "NEWS_API_KEY"
account_sid = "account_sid"
auth_token = "auth_token"
... |
0dee971d88bf1e2b93e1f006407c4c987dfe3a69 | manon2012/python | /work/leetcode/testunknown.py | 838 | 3.65625 | 4 | def findRestaurant( list1, list2):
for item in list1:
if item in list2:
return item
r=findRestaurant(["Shogun","Tapioca Express","Burger King","KFC"],["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"])
print (r)
# filter=["av","japan","xiaodao"]
# content=input... |
483709ef78d4f9b384100aace775e562ee79ab32 | manon2012/python | /work/leetcode/square.py | 308 | 3.71875 | 4 | def isPerfectSquare(num):
"""
:type num: int
:rtype: bool
"""
if num == 1:
return True
for i in range(num):
if i * i == num:
return True
return False
r1=isPerfectSquare(16)
r2=isPerfectSquare(1)
r3=isPerfectSquare(15)
print (r1)
print (r2)
print (r3) |
606bcf541577b92fa7b328d4ab8b502e77850d3e | manon2012/python | /work/Do/testsort3.py | 1,318 | 3.71875 | 4 | <<<<<<< HEAD
=======
>>>>>>> fa18662c7df3c24470bfae36b878e5cf1d7121a0
def bubble_sort(n):
for i in range(len(n)-1):
for j in range(len(n)-i-1):
if n[j]>n[j+1]:
n[j],n[j+1]=n[j+1],n[j]
<<<<<<< HEAD
return n
print (bubble_sort([3,2,1,100]))
=======
return n
print (bubbl... |
1769bc8b3639e3683fc8b12bcda8e0266cae127d | manon2012/python | /test/test1.py | 651 | 3.53125 | 4 |
import unittest
class TestCount:
def __init__(self,a,b):
self.a=a
self.b=b
def doadd(self):
return self.a + self.b
class TestUt(unittest.TestCase):
def setUp(self):
print ("before...")
def testdoadd(self):
i=TestCount(1,2)
print (i)
self.ass... |
e7b628c275951b76de5644dbb20ffa055ce3403d | manon2012/python | /work/Do/testUT.py | 752 | 3.671875 | 4 | import unittest
class cal():
def __init__(self, a, b):
self.a = int(a)
self.b = int(b)
def caladd(self):
return self.a + self.b
def caldiv(self):
return (self.a)/(self.b)
class test_unit(unittest.TestCase):
def setUp(self):
print("before everyrun")
def tea... |
860396ad50c09af0162141639cce177da0db17dc | manon2012/python | /work/leetcode/restr.py | 2,314 | 3.796875 | 4 | def restr(str):
r=str.split(" ")
rr=[i[::-1] for i in r]
return ' '.join(rr)
r=restr("hi hello world")
print (r)
def all(str):
return str[::-1]
r=all("hi hello world")
print (r)
"""Input : str = "geeks quiz practice code"
Output : str = "code practice quiz geeks"""
def a1(str):
a=str.split(" ... |
5969ccbe82c1dc36934636e7a9e2a2beda7b2cb2 | VieuxChameau/pythonCoursera | /assignment.4.6.py | 200 | 3.875 | 4 | def computepay(h, r):
if h <= 40:
return h * r
else:
return (40 * r) + ((h - 40) * r * 1.5)
hrs = float(input("Enter Hours:"))
rate = float(input("Enter Rate:"))
print(computepay(hrs, rate))
|
7a78c1adc57f43aeed0f304f39199656e69d8c03 | hahastudio/Algorithms | /primality.py | 1,024 | 3.90625 | 4 | import math
import random
def primality1(n):
"""give a positive integer n, testing primality.
It proclaim n a prime as soon as it have rejected all candidate up to sqrt(n).
"""
for i in xrange(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def primality2(n):... |
5755031ab15c2429980d5f7def1f26cd1a59a8d5 | hahastudio/Algorithms | /bfs.py | 832 | 3.9375 | 4 | """
约定:图的存储方法
这里的图采用邻接表的方法存储。有两种可行的方式:
1. 边无权重:
采用集合存储该点可到达的点集
2. 边有权重:
采用字典(点:边的权重)存储该点可到达的点集
例:
V = a, b, c, d, e, f, g, h = range(8)
E = [
set([b, c, f]),
set([e]),
set([d]),
set([a, h]),
set([f, g, h]),
set([b, g]),
set(),
set([g])
]
G = (V, E)
"""
from collections import deque
inf = float("inf")
def bfs... |
7d0b02264a79f998560f83e92d4377719e763351 | qiusiyuan/adventofcode | /2019/day6/day6.py | 1,076 | 3.515625 | 4 | with open("input.txt", "r") as fd:
inputlines = fd.read().splitlines()
def splitr(route):
jj = route.split(")")
main = jj[0]
ob = jj[1]
return main, ob
all_dict = {}
for route in inputlines:
main, ob = splitr(route)
if ob not in all_dict:
all_dict[ob] = main
dp = {}
def count(ob... |
3eeb5bd250346b47af7ceb28ca46b9a5bb5f8514 | ncdunker/python-challenge | /good_movies.py | 1,245 | 3.78125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Dependencie
import pandas as pd
# In[2]:
# Load in file
movie_file = "Resources/movie_scores.csv"
# In[3]:
# Read and display the CSV with Pandas
movie_file_pd = pd.read_csv(movie_file)
movie_file_pd.head()
# In[4]:
# List all the columns in the table
movi... |
163c1b4beb8cd62c23abacd9ed1fb1cdf51929dd | EYandura/Artificial-Intelligence-Group-T3 | /PEX2-MultiAgent/multiAgents.py | 15,987 | 3.71875 | 4 | # ##############################
#
# Reece Clingenpeel, Eric Yandura
#
# DOCUMENTATION:
# ~ The Python Doc was used throughout this file in order to explore the built in Python structures and functionality.
# ~ The class text and Notes were used throughout the assignment.
# I followed along with a similar problem onlin... |
1715d9a7c8af4c221ec1027ca51ef13a8d269058 | Arcadonauts/BES-2018 | /email_myself.py | 1,683 | 3.515625 | 4 |
"""Send an email message from the user's account.
"""
#!/usr/bin/python2.7
from email.mime.text import MIMEText
import httplib2
import base64
from apiclient import discovery
import credentials
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API serv... |
4735d3a958dab66d6b2f0710a92a4300619ff3df | Horlando-Leao/geradorRelatorioInteligente | /src/Util.py | 2,629 | 3.609375 | 4 | import re
class Util():
def __init__(self):
pass
def detectarDataExpressaoRegular(texto):
date_pattern = re.compile('''
([12][0-9]|3[0-1]|0?[1-9]) # to detect days from 1 to 31
([./-]) # to detect different separations
(1[0-2]|... |
c3eb6412b70b6627a0bbf0ff50b86e64cdd22fe0 | Horlando-Leao/geradorRelatorioInteligente | /src/test/detectarData2.py | 1,552 | 4 | 4 | import re
def date_is_valid(day: int, month: int, year: int) -> bool:
return (month not in (2, 4, 6, 9, 11) # 31 days in month (Jan, Mar, May, Jul, Aug, Oct, Dec).
or day < 31 and month in (4, 6, 9, 11) # 30 days in month (Feb, Apr, Jun, Sep, Nov).
or month == 2 and day == 29 and year % 4 == 0 and (year... |
f8ec2566b82d611fe6e8ae0ecff036978de9a002 | ayaabdraboh/python | /lap1/shapearea.py | 454 | 4.125 | 4 | def calculate(a,c,b=0):
if c=='t':
area=0.5*a*b
elif c=='c':
area=3.14*a*a
elif c=='s':
area=a*a
elif c=='r':
area=a*b
return area
if __name__ == '__main__':
print("if you want to calculate area of shape input char from below")
... |
f0ff04904913946057b156dbde69511b11015a63 | GeoGateway/BuriedSAFSlip2010 | /daynum2k.py | 2,023 | 3.796875 | 4 | # Date to day past y2k
def daynum2k(date):
"""
Function daynum2k:
date: string in format dd-Mmm-yyyy ie 13-Nov-2009
return day past y2k start (01-Jan-2000 => 1)
Note: good for years 2000-2023 (easily generalized)
"""
yearc = [366,365,365,365,366,365,365,365,366,365,365,365,
... |
9151027c3ddbb445db1602733a81712e1396a7af | retzstyleee/chapter-08-protek | /Praktikum8.1.py | 235 | 3.8125 | 4 | try:
jumlah = int(input("Jumlah : "))
data = []
for i in range(jumlah):
data.append(int(input("Data ke {} : ".format(i+1))))
data.sort(reverse=True)
print(data)
except:
print("Input tidak Valid") |
0d40a49c5c13f3d2dfb56fd63fa8a7ea708a8da8 | retzstyleee/chapter-08-protek | /Praktikum8.3.py | 292 | 3.703125 | 4 | try:
jumlah = int(input("Jumlah : "))
data = []
for i in range(jumlah):
data.append(input("Data ke {} : ".format(i+1)))
data.sort()
for i in data:
print("[{}] {} ({} karakter)".format(data.index(i),i,len(i)))
except:
print("Input tidak Valid") |
87696c2adf3314acbc96db79addb184b010915fb | natallia-zzz/labs_python | /n7_lab_2_6.py | 2,882 | 3.578125 | 4 | def extract_file(file_name):
txtfile = file_name + 'txt'
f = open(txtfile, "r")
return from_json(str_gen(f))
def str_gen(s):
for ch in s:
yield ch
def from_json(obj):
ch = next(obj)
if ch.isdigit() or ch == "-":
return json_num(ch, obj)
elif ch.isalpha():
val = js... |
832cf97e515ef6358319cbb03ee6cfed43486558 | aanwar5/Data_Analytics_Python_Test | /Tables Calculator.py | 279 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
#Making a multiplication table on Python
j=1
while (j<=10):
i = 1
print("Printing the following table of ", j)
while(i<=10):
print( j, "times", i, j*i)
i=i+1
j =j+1
# In[ ]:
|
83190ab93ab688c07c57e3e17889c9b671d0589b | madisonmay/SoftwareDesign | /ai_v_ai.py | 673 | 3.53125 | 4 | import tictactoe, ankur
import sys
def unpack(b):
l = [1,2,3,4,5,6,7,8,9]
for elem in b['x']: l.remove(elem)
for elem in b['o']: l.remove(elem)
return {' ':l,'x':b['x'],'o':b['o']}
def printboard(board):
nboard = unpack(board)
for j in range(3):
for i in range(1+3*j,4+3*j):
... |
d9141766341e0f20c31c53bbe4f2aa7fd29b7254 | ss666/leetcode-practice | /ReorderList.py | 1,262 | 4.0625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
... |
7e4503ab4bfd9f18557b6d0b4b3e3d5a4f5d4820 | virginiayung/UW | /amath583_scientific_computing/homework3/intersections.py | 1,538 | 4.03125 | 4 | """
solving g1(x)=g2(x) or equivalently solving for zeros of the
function f(x)=g1(x)-g2(x) by using newton.solve
"""
import numpy as np
from pylab import *
interactive(True)
from newton2 import solve
#Graph to find intersections to use as x0
x = np.linspace(-10,10, 1000)
ylim(-3,3,0.01)
g1 = x*np.cos(np.pi*x)
g2= ... |
eb07e42211c4d4576e43c3614de7385b0d63e4c8 | Sparrow612/PythonCodePrac | /DFS/exist_word.py | 986 | 3.8125 | 4 | from typing import List
def exist(board: List[List[str]], word: str) -> bool:
if not board or not board[0]: return False
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def check(i, j, k):
if word[k] != board[i][j]: return False
if k == len(word) - 1: return True
visited.add((i, ... |
f93efab3989b4e17054543a315e62b71bfa105e9 | Sparrow612/PythonCodePrac | /Competition/parking_system.py | 603 | 3.828125 | 4 | # class Car:
# def __init__(self, t):
# self.carType = t
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.spaces = [big, medium, small]
def addCar(self, carType: int) -> bool:
if self.spaces[carType - 1]:
self.spaces[carType - 1] -= 1
... |
cecf0a359662e808478965729e6563be79b0e312 | Sparrow612/PythonCodePrac | /Tree/BST_2_GRT.py | 1,594 | 3.828125 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
本题中要求我们将每个节点的值修改为原来的节点值加上所有大于它的节点值之和。这样我们只需要反序中序遍历该二叉搜索树,记录过程中的节点值之和,并不断更新当前遍历到的节点的节点值,即可得到题目要求的累加树。
关键词:反序中序遍历
中序遍历是从小到大,那么从大到小反过来即可
PS:这题是看答案看来的
"""
sum_of_val = 0 # 遍历和
def convertBST(root: Tr... |
142250fa8db529bee7c8f758baa797ccd3c26d06 | Perfectly-Purple/CSES-python | /Permutations.py | 176 | 3.890625 | 4 | x=int(input())
if(x==1):
print("1")
elif(x>1 and x<4):
print("NO SOLUTION")
else:
for i in range(2,x+1,2):
print(i, end=" ")
for i in range(1,x+1,2):
print(i, end=" ")
|
7963ad9983277a0306758115fa5c01f63ec08cc1 | Sahbetdin/ACMP | /rucode/oper.py | 238 | 3.75 | 4 | #кол-во операций
def f(n):
if n == 0:
return 1
else:
index = n - 1
sum = 1
while (index >= 0):
sum = sum + f(index)
print("index = " , sum)
index = index - 1
#print("~~~~~~~")
return sum
print(f(30))
|
b5d6e17221eb7f62196a18fdbe0f92839c253a8b | symbolr/python | /demo/6.py | 101 | 3.5 | 4 | def fact(n):
if n==1:
return 1
return n*fact(n-1)
print(fact(1))
print(fact(5))
print(fact(100)) |
538b835102d5dec7ff140c72725be5adb7efa851 | symbolr/python | /demo/debug.py | 628 | 3.859375 | 4 | # 第一种打print
# def foo(s):
# n = int(s)
# print('>>>n = %d' %n)
# return 10/n
# def main():
# foo('0')
# main()
# 第二种断言
# def foo(s):
# n = int(s)
# assert n!= 0 ,'n is zero'
# return 10/n
# def main():
# foo('0')
# main()
# 第三种 logging
#
# logging.basicConfig(level=logging.INFO)
# def foo(s):
# n = in... |
419ab4ff6ec8b2241d2a242cd3d3cdb448cfa4c3 | bekahbooGH/oo-desserts | /desserts.py | 2,053 | 3.796875 | 4 | class Cupcake:
"""A cupcake."""
# Class attribute
cache = {}
# INSTANCE METHOD::
def __init__(self, name, flavor, price):
self.name = name
self.flavor = flavor
self.price = price
self.qty = 0
self.cache[name] = self
def add_stock(self, amount):
... |
2d15daa653ac971c8c916848d2ffdc507572a528 | cloudmesh/cloudmesh-pi | /cloudmesh/pi/grove_speaker.py | 2,303 | 3.53125 | 4 | import grovepi
import time
import sys
class GroveSpeaker:
def __init__(self, pin = 3):
"""
use digital pin as output pin for speaker
pin 3 by default
connect to port D3 of grove pi hat
"""
self.speaker = 3
self.high = 0
self.low = 0
grovepi.pinMode(self.speaker,"OUTPUT")
grovepi.digitalWrite(self.... |
ad75fca23576922d2cb4e36658a86bce443e2fc7 | cloudmesh/cloudmesh-pi | /cloudmesh/pi/led.py | 1,635 | 3.640625 | 4 | """Usage: led.py [-h] pin=PIN
Demonstarte a blining LED on given PIN
Arguments:
PIN The PIN number [default: 3].
Options:
-h --help
"""
from docopt import docopt
import time
import grovepi
import sys
class LED(object):
def __init__(self, pin=3):
"""
Connect the LED to a digital port. 3... |
4601288128d4c43f69a2bb9b0ef6c8a28d67ee55 | cloudmesh/cloudmesh-pi | /cloudmesh/pi/led_bar.py | 903 | 3.765625 | 4 | import time
import grovepi
class LedBar:
def __init__(self, pin=3, color = 0):
"""
color = 0 starts counting led 1 from the Red LED end
color = 0 starts counting led 1 from the green LED end
"""
self.ledbar = pin
grovepi.ledBar_init(self.ledbar,color)
def setLevel(self,level = 0):
"""
le... |
28295bc71fba86b113b197459dbf24cbb4ffaf41 | prasad2012/longtime | /src/squares.py | 245 | 4.09375 | 4 | def my_square(x):
"""takes a value and returns the square of it
by using **
"""
return(x ** 2)
def my_square2(y):
"""takes a value and returns the square of it
by using **
"""
return(y ** 2)
print(my_square(5))
print(my_square2(6))
|
20a3f9fa7dfe64042baf3ba500d6f2a583b4c324 | alex7071/AOC | /Day2P1.py | 788 | 3.78125 | 4 | import numpy as np
def read_strings():
filepath = "Day2P1.txt"
stringList = []
with open(filepath) as fp:
for line in fp:
stringList.append(line)
return stringList
def frequency_count(text):
#elem is an array of the unique elements in a string
#and count is its correspondin... |
eabf59ece386cef321e8a639ee6fb75af265df83 | dotXem/pcLSTM | /postprocessing/rescaling.py | 415 | 3.6875 | 4 | def rescaling(results, mean, std):
"""
Scale back the results that have previously been standardized.
:param results: results of shape (None, 2)
:param mean: vector of mean values (one per initial feature)
:param std: vector of std values (one per initial feature)
:return: re... |
ef3f6373867dbacee7aae3af141d9fcd1edbd311 | PabloG6/COMSCI00 | /Lab4/get_next_date_extra_credit.py | 884 | 4.28125 | 4 | from datetime import datetime
from datetime import timedelta
'''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward)
would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because
28 is not a month.
'''
def GetNextDate(day, month, year, num_days_forward):
num_days_forward = int... |
e5b776388e4d7ae5bab7891ed36d53ae14dfdc4d | PabloG6/COMSCI00 | /Lab2/kind_of_a_big_deal.py | 209 | 3.9375 | 4 | minutes = float(input("Minutes: "))
num_hours = minutes//60
num_minutes = minutes%60
num_seconds = 60*(num_minutes%1)
print(int(num_hours), "hours", int(num_minutes), "minutes", int(num_seconds), "seconds")
|
af817ff14fbc1b00968c49da3f427ddb3d75622d | PabloG6/COMSCI00 | /Lab2/moon_earths_moon.py | 279 | 4.125 | 4 | first_name = input("What is your first name?")
last_name = input("What is your last name?")
weight = int(input("What is your weight?"))
moon_gravity= 0.17
moon_weight = weight*moon_gravity
print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon") |
81d8c252747fb1a2f801e779a5c378f1f79b3dd3 | irfanki/HackerRanker | /machine_learning/compute_Karl_Pearson’s_coefficient.py | 492 | 3.53125 | 4 | from math import *
x = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3]
y = [10, 25, 17, 11, 13, 17, 20, 13, 9, 15]
# Calculating the mean
x_mean = sum(x)/len(x)
y_mean = sum(y)/len(y)
diff_x_mean = [(i - x_mean) for i in x]
diff_y_mean = [(i - y_mean) for i in y]
xx = sum([(i - x_mean)**2 for i in x])
yy = sum([(i - y_mean)**2 fo... |
683ce144348dbb8d1f15f38ada690d70e9b1a22f | joeschweitzer/board-game-buddy | /src/python/bgb/move/move.py | 827 | 4.3125 | 4 |
class Move:
"""A single move in a game
Attributes:
player -- Player making the move
piece -- Piece being moved
space -- Space to which piece is being moved
"""
def __init__(self, player, piece, space):
self.player = player
self.piece = piece
self.space =... |
5d04f60a21a7c031213744c2ae2e779a223e2ca2 | 2020668/api_automation_course | /util/base/list_demo.py | 280 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
=================================
Author: keen
Created on: 2020/8/7
E-mail:keen2020@outlook.com
=================================
"""
# 索引取值 从前到后 从0开始 反向从-1开始
b = [1, 2, 3, 4]
print(b[0])
print(b[1])
print(b[-1])
|
e88ec5b3aa79dfa449dad5726912937eddbdeb96 | 2020668/api_automation_course | /util/thread_demo.py | 1,631 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
=================================
Author: keen
Created on: 2020/7/27
E-mail:keen2020@outlook.com
=================================
"""
import time
import threading
def demo1():
for i in range(2):
print("正在加载中...")
# 获取当前执行的线程
print("当前活跃的线程有:{}".format(thr... |
38e2624ef1a24be287c62b638819a8338ec6fbb3 | junyi1997/python-class | /20190321/20190321.py | 267 | 3.6875 | 4 | # -*- coding: utf-8 -*-
import turtle
#from turtle import*
t=turtle.Turtle()
s=turtle.Screen()
'''
t=Turtle()
s=Screen()
'''
def my_rect():
t.begin_fill()
for i in range(4):
t.forward(100)
t.left(90)
t.end_fill()
my_rect()
s.mainloop()
|
d34b71724d35e5e90fe9181bcaa23d4be637d072 | h4x0rlol/PythonLabs | /lab_3_4_5/2.py | 117 | 3.5 | 4 | n = int(input('n: '))
sum = 0
# 1
while (n > 0):
sum += n
n -= 1
# 2
for i in range(0, n+1):
sum += i
|
2b0293a0bd0452e9e94a7c6aea0d13a803cc9dbd | Demesaikiran/MyCaptainAI | /Fibonacci.py | 480 | 4.21875 | 4 | def fibonacci(r, a, b):
if r == 0:
return
else:
print("{0} {1}".format(a, b), end = ' ')
r -= 1
fibonacci(r, a+b, a+ 2*b)
return
if __name__ == "__main__":
num = int(input("Enter the number of fibonacci series you want: "))
if num =... |
856baf6c40ff468515c09acab0971498025ad832 | zhongyusheng/store | /旅游导航.py | 6,298 | 3.5 | 4 |
def goshoping() :
money = input("请输入您的支付宝余额:")
money = int(money)
laoganma = 1
lenovo = 1
shop = [
["劳力士手表", 200000],
["Ipone 12X plus", 12000],
["lenovo PC", 6000],
["HUA WEI WATCH", 1200],
["Mac PC", 15000],
["辣条", 2.5],
["老干妈",... |
95b08d13183f9aebc8a6ac5fa10284a33bc6a517 | hauckc21/python-challenge | /PyPoll/main.py | 2,176 | 3.890625 | 4 | import os
import csv
#Define variables
total_votes = 0
candidates = {}
#Store csv file path
csvpath = os.path.join('Resources', '02-Homework_03-Python_Instructions_PyPoll_Resources_election_data.csv')
#Open csv in read mode
with open (csvpath) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
... |
f8488e9528758acba0a6aa5833eea6c6ba13b98c | wakashijp/study-python | /Learning-Python3/Chapter10/Section10-1/dice_game2.py | 603 | 3.78125 | 4 | from random import randint
# サイコロを定義する
def dice():
num = randint(1, 6)
return num
# 2個のサイコロを振るゲーム
def dicegame():
dice1 = dice() # 1個目のサイコロを振る
dice2 = dice() # 2個目のサイコロを振る
sum_number = dice1 + dice2 # 2個のサイコロの目の合計
if sum_number % 2 == 0:
print(f"{dice1}と{dice2}で合計{sum_number}、偶数")... |
f914ab7f5a515256e17c49a1878fd7d889d1e8ba | wakashijp/study-python | /Learning-Python3/Chapter05/Section5-1/if_or.py | 554 | 4 | 4 | # randomモジュールのrandint関数を読み込む
from random import randint
size = randint(5, 20) # 5〜20の乱数を生成する。
weight = randint(20, 40) # 20〜40の乱数を生成する。
# 判定(どちらか片方でもTrueならば合格)
if (size >= 10) or (weight >= 25): # orで連結しているので、2つの条件のどちらか一方でもTrueならば式はTrueになります。
result = "合格"
else:
result = "不合格"
# 結果の出力
text = f"サイズ{size}、重... |
9f66c93bebd85232ea3646b96a3c6a5ff877ba2c | wakashijp/study-python | /Learning-Python3/Chapter05/Section5-2/while_else.py | 663 | 3.9375 | 4 | # randomモジュールからrandint関数を読み込む
from random import randint
numbers = [] # 空のリスト
# numbersの値が10個になるまで繰り返す
while len(numbers) < 10:
n = randint(-10, 90) # -10〜90の乱数を生成する
if n < 0:
# nがマイナスならばブレイクする
print("中断されました")
break # elseブロックを実行せずに終了します
if n in numbers:
# nがnumbersに含ま... |
760684cec3d5bb0b3f4d81e136a9bd83301e43d0 | wakashijp/study-python | /Learning-Python3/Chapter02/Section2-3/if.py | 112 | 3.734375 | 4 | a = 10
if a >= 0:
print('0以上の値です')
else:
print('負の値です')
print('判定終わり')
|
edd965cb5e4cd40f651a2ed14f0b422a708e4635 | wakashijp/study-python | /Learning-Python3/Chapter05/Section5-3/for_else_break.py | 439 | 3.953125 | 4 | numlist = [3, 4.2, 10, "x", 1, 9] # 文字列が含まれている
sum_value = 0
for num in numlist:
# numが数値でない時は処理をブレイクする
if not isinstance(num, (int, float)):
print(num, "数値ではない値が含まれていました。")
break # ブレイクする
sum_value += num
else:
# breakされなかった時は合計した値を出力する
print("合計", sum_value)
|
8aa75c2d3c2bde564d5a5baa30666d8f9d002985 | Picolino66/resmat-1-2 | /Resmat1/Natan/trampo.py | 5,773 | 3.734375 | 4 | from math import* #importa funções matemáticas
import math
#Função para pegar os valores do arquivo
def criar_arq(): #funcao para ler os dados dos arquivos
print ("Digite o nome do arquivo: ")
arq=input()
arqentrada = arq + '.dat' #junção de string para ler o nome do arquivo
f = open(arqentrada, 'r') #abrir arquiv... |
3c342d2651d4a45ceb042119999f3532221493ad | Rekkuj/pygame | /game.py | 2,641 | 3.84375 | 4 | # player_name = 'Rekku'
# player_attack = 10
# player_heal = 16
# health = 100
# List:
# player = ['Rekku', 10, 16, 100]
# you can change the values in list:
# player[1] = 11
# print(player['attack'])
game_running = True
while game_running == True:
new_round = True
# Dictionaries (key: value -pairs):
pl... |
066eb39f5220714b49df4cf8a52267f1e59b52db | holtsho1/CS1301xIII | /CourseInfo.py | 298 | 3.640625 | 4 | def course_info(tup_list):
course_dict={}
course_dict["students"]=[]
average=0
for tup in tup_list:
course_dict["students"].append(tup[0])
average=average+tup[1]
average=average/len(tup_list)
course_dict["avg_age"]=average
return course_dict
|
f19dab35f971baf9a8a62a0c92c36d775ab73365 | kgolezardi/simulation-project | /pqueue.py | 893 | 3.671875 | 4 | import heapq
import itertools
class PriorityQueue:
def __init__(self):
self.heap = []
self.counter = itertools.count()
self.entry_finder = {}
self._size = 0
def size(self):
return self._size
def push(self, priority, x):
count = next(self.counter)
e... |
bb50b8feabc4e027222ed347042d5cefdf0e64da | abtripathi/data_structures_and_algorithms | /problems_and_solutions/arrays/Duplicate-Number_solution.py | 1,449 | 4.15625 | 4 | # Solution
'''
Notice carefully that
1. All the elements of the array are always non-negative
2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2)
3. There is only SINGLE element which is present twice.
Therefore let's find the sum of all elements (current_sum) of... |
daddf0cf3602340d5b377400e31df7a681d110ea | CHB94git/Retos-Python-Ciclo1 | /Reto1/CalcSquare.py | 303 | 3.71875 | 4 | def CalculadoraRectangulo(ancho:float, largo:float)->str:
perimetro = (ancho*2) + (largo*2)
area = ancho*largo
print("El cuadrado tiene un perímetro de: " +str(perimetro) +" y un área de: " +str(area))
#Ingresar los parámetros con un solo decimal
CalculadoraRectangulo(3.0, 2.5)
|
26d6e211c524aae3668176e7f54638f589b9226c | nicholasrokosz/python-crash-course | /Ch. 15/random_walk.py | 945 | 4.25 | 4 | from random import choice
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
self.num_points = num_points
# Walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in a walk.""... |
6405fb18f932d4ef96807f2dc65b04401f32e5be | nicholasrokosz/python-crash-course | /Ch. 10/favorite_number.py | 467 | 4.125 | 4 | import json
def get_fav_num():
"""Asks a user for their favorite number and stores the value in a .json file."""
fav_num = input("What is your favorite number? ")
filename = 'fav_num.json'
with open(filename, 'w') as f:
json.dump(fav_num, f)
def print_fav_num():
"""Retrieves user's favoite number and prints ... |
fe05cab40de57a35592c9273d23dd67e9f06a4ba | nicholasrokosz/python-crash-course | /Ch. 5/hello_admin.py | 221 | 3.9375 | 4 | users = ['admin', 'Nick', 'Nicole', 'Al', 'Pete', 'Michaela']
for user in users:
if user == 'admin':
print("Hello admin, would you like to see a status report?")
else:
print(f"Hello {user}, thanks for logging in.") |
423045af400951a00f9e952f0e92757c77c2ff29 | nicholasrokosz/python-crash-course | /Ch. 10/programming_poll.py | 265 | 3.5625 | 4 | prompt = "Why do you like programming? (enter 'q' to exit)\n\t"
keep_going = True
while keep_going:
reason = input(prompt)
if reason != 'q':
with open('programming_poll.txt', 'a') as file_object:
file_object.write(f"{reason}\n")
else:
keep_going = False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.