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 |
|---|---|---|---|---|---|---|
5a671561bf7fc62429eb13bb9f94e9fc3bbbf82d | brianb1/2017Challenges | /challenge_6/python/sarcodian/src/challenge_6_tests.py | 1,075 | 3.578125 | 4 | # we start by importing the unittest module
import unittest
# Next lets import our function that we intend to do testing on
#
# **We could also import all functions by using * or just import the module
# itself but for now lets just import the function
from challenge_6 import ranges, print_range
# lets define our sui... |
5d20217a2a0f13c33ae33cf1740758eb6a518013 | brianb1/2017Challenges | /challenge_7/python/bryantpq/find_missing_number.py | 398 | 3.703125 | 4 | #!/usr/bin/python3
def find_num(a):
total = sum(range(len(a) + 1))
for n in a:
total = total - n
return total
def main():
print(find_num([1, 3, 4, 0]))
print(find_num([0, 1, 2, 4]))
print(find_num([1, 2, 3]))
print(find_num([0, 1, 2, 3, 4]))
print(find_num([0]))
print(fi... |
b13af56b8162f3a252ef1b9cae7e4fa43989adcf | brianb1/2017Challenges | /challenge_2/python/sarcodian/src/challenge_2.py | 526 | 3.96875 | 4 | def pick_char(array0):
'''
array0: list, the array that is entered with one unique char
returns: char, a single element string or int that was unique in the array
'''
unique = []
duplicate = []
for i in array0:
if i in duplicate:
pass
elif i in unique:
... |
36f83826f63be4c166fceab769d1c38b4ba16d83 | alka10/internity-python | /broadcasting_manipulation.py | 463 | 3.515625 | 4 | import numpy as np
arr1=np.array([1,2,7,5,9,3,4,2])
arr2=7
arr=arr1+arr2
print(arr)
#broadcasting
arr1=np.array([[10,19,12],[8,5,3]])
arr2=6
arr=arr1+arr2
print(arr)
#3.
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
a.shape = (3,2)
print(a)
#4.
v = np.array([10, 20, 6])
w = np.array([10, 15])
print(np.res... |
3e5b773c10c1caf6ebf391cb4e408b57775851d6 | alka10/internity-python | /regularex.py | 699 | 3.921875 | 4 | #find string that has a followed by zero or one b
import re
s='my 2 nd most favourite number is 10'
print(re.findall('[0-9]+',s))
#search regular expressions
import re
p=re.compile('[b-g]')
print(p.findall("the cat is walking in the garden"))
#find all five character word
import re
text='the quick brown dog... |
9eb8ad471b2a47d1c55435bfd6f376d383de0a94 | hellokrishnarao/Compressor | /Decompression.py | 1,531 | 3.671875 | 4 | class Decompressor():
hash_pairs = []
hash_d = {}
n_file_data = []
final_file = ""
a=[]
# read hash file and store in a list the key,value pair
def map_hash(self):
hashFile = open("hash_file.txt", "r")
for i in hashFile.readlines():
e = i.split()
se... |
736e45216c866c9f547cafbbc7792e751af535bb | cliffgla/ocr_python_puzzle_solutions | /01_think_twice.py | 914 | 3.640625 | 4 | shift = 2
english_alphabet = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
]
coded_message = "map"
decoded = " "
code = {}
# german_alphabet
#
alphabet = english_alphabet
list_length = len(alphabet)
# take index position and printin... |
8556f266361021035ba1e08d288ebd11588d13fa | marinabarbu/RFIA | /nn_1.py | 3,509 | 4.03125 | 4 | import numpy as np # helps with the math
import matplotlib.pyplot as plt # to plot error during training
# input data
import pandas as pd
dataset = pd.read_excel(io="trainx.xlsx", sheet_name='train')
x1i1 = dataset.iloc[2:20,0].values
x2i1 = dataset.iloc[2:20,1].values
x1i2 = dataset.iloc[2:20,2].values
x2i2 = data... |
a2bc4a35e26f590c738178bdaffac36e42b56993 | hitendrapratapsingh/python_basic | /user_input.py | 229 | 4.28125 | 4 | # input function
#user input function
name = input("type your name")
print("hello " + name)
#input function type alwase value in string for example
age = input("what is your age") #because herae age is string
print("age: " + age) |
de7f99dacd204db2b154e498edb09081698fda7d | hitendrapratapsingh/python_basic | /center_method.py | 114 | 3.828125 | 4 | # name = "govind"
# print(name.center(8,"|"))
name = input("enter your name")
print(name.center(len(name)+8,"*")) |
60a18917f5e46365b47305657658fca38938e159 | hitendrapratapsingh/python_basic | /test3.py | 1,180 | 3.9375 | 4 | # name = "Gaurav"
# print(f"{name}")
# print(name[::-1])
# print(name[6::-1])
# name = input("enter your name")
# reserve = name[-1::-1]
# print(f"reserve of your name is {name[-1::-1]}")
# print(f"reserve of your name is {reserve}")
# name, chars = input("enter your name comma seprate: ").split(",")
# print(f"length... |
a58796f98485808719412c050fe618aee6a34798 | Elewei/sync-data | /apply_excel.py | 4,320 | 3.734375 | 4 | '''
作者: 张启卫
时间: 2018年12月5号
功能:Python 处理Excel 文件
参考文档: http://www.python-excel.org/
xlrd
pip install xlrd
wlwt
pip install xlwt
'''
import xlrd
import xlwt
import configparser
# 加载配置文件
config = configparser.ConfigParser()
# 写入配置文件
config.read('conf.ini', encoding='utf-8')
filename_prefix... |
7aac72a2d4bbf34a2f797fb8110a1a7f6a760405 | n16107/exam201602 | /exam/exam.py | 2,128 | 4.03125 | 4 |
# 1からnumberまでの合計を出力してください
def sum_from_1_to(number):
pass
# numberの階乗(factorial)を出力してください
def factorial(number):
pass
# リストdataの各要素(整数)を3乗した結果をリスト型として返してください
def cubic_list(data):
pass
# 底辺x,高さyの直角三角形(right angled triangle)の残り1つの辺の長さを返してください
def calc_hypotenuse(x, y... |
e319c36c5feb6fb46bc6df865c5a3e51663a1e09 | ViliusAudinis/pwp-capstones | /ViliusAudinis_TomeRater/TomeRater.py | 5,732 | 3.921875 | 4 | class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
print("{name}'s email address has been changed to {email}".... |
91760f99922a35d8ee00c6800e9a11a23019edb6 | functioncall/rescue-habit | /commons/logger.py | 1,857 | 3.890625 | 4 | import inspect
import json
def pretty_log(function_name, args):
"""
Pretty prints <dict>
Each argument is in a new line.
:param function_name: name of the function being logged
:param args: arguments to be logged
:return: None
"""
print("=" * 100)
print(" " * 40 + "In function: " +... |
e8d250718861f2ddb3379fda8277d2d63bf4a6f5 | DiegoJRivera/OpenCV | /OpenCVLynda/script6.py | 3,334 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 02:01:00 2019
@author: diegorivera
From: Lynda.com - OpenCV for Python Developers. by Patrick W. Crawford.
Chapter 2: Basic Image Operations
"""
# ************************** Scale and rotate iamges **************************
import cv2
img = cv... |
509fac8937ebdd101314b8f529b5981c35df1b3a | DiegoJRivera/OpenCV | /OpenCVLynda/script10.py | 1,194 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 24 19:15:53 2019
@author: diegorivera
From: Lynda.com - OpenCV for Python Developers. by Patrick W. Crawford.
Chapter 3: Object Detection
"""
# **************************** Simple thresholding ****************************
import numpy as np
import... |
6c570c14383829974317ad591dc19772b9b53d75 | NexyS03/ACS-PREP | /task3.py | 659 | 3.921875 | 4 | while True:
try:
pre_ma = float(input("Input the car mileage the last time the car was filed."))
break
except:
print("Enter a number")
while True:
try:
now_ma = float(input("Input the car mileage now."))
break
except:
print("Enter a number")
while True:
try:
... |
f8a4027602600565f06de80d1d29e61ba0e5e5a9 | nuzhamusyafira/knn-classification-from-scratch | /knn.py | 3,099 | 3.609375 | 4 | import math
import numpy as np
# we extract the last column as it appears to be the class and name it as y_train,
# y_train indicates what our predicted class will be compared to
y_train = np.genfromtxt('pima.csv', usecols = (-1), delimiter = ",")
# then we define the rest, which are predictors, as x_train
x_train = n... |
a67992e084bc4e1250ec15e171c61642a931d0af | sanopi/my-atcoder-log | /agc0/agc03/agc034/a.py | 416 | 3.734375 | 4 | if __name__ == '__main__':
split = input().split(' ')
n = int(split[0]) - 1
a = int(split[1]) - 1
b = int(split[2]) - 1
c = int(split[3]) - 1
d = int(split[4]) - 1
s = input()
isOK = False
if c < d:
isOK = not ('##' in s[a:c] or '##' in s[b:d])
else:
isOK = (not (... |
12ec5372fc13dbc68182cb36b0a35d667d078849 | niyonikagaur/tip-calculator | /tip-calculator.py | 309 | 4.0625 | 4 | print("Welcome to the tip calculator")
bill=input("What was the total bill?")
b=float(bill)
per=input("What percentage would you like to give?")
p=int(per)
split=input("How many people to split the bill")
s=int(split)
total=((b/s)*p)
t= float(total)
r=round(t,2)
print(f"Each person should pay:{r}") |
2779bca412bf551973f62812dcdc4bb58bc7b94d | Cmoadne/python_learn | /function.py | 1,887 | 3.65625 | 4 | import math
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x < 0:
return -x
else:
return x
# 必选参数 默认参数
def my_move(x, y, step=0, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
# 默认参数... |
750900f9be03aac96ec39601a667b6c3948c0ad3 | injoon5/C3coding-python | /2020/04/22/02.py | 388 | 4.125 | 4 | height =int(input("your height : "))
if height<110:
print("Do not enter!")
if height>= 110:
print("have a nice time!")
if height == 110:
print("perfect!")
if height != 110:
print("Not 110.")
if 100 <= height <110:
print("Next year~")
print("Booltype = ", height< 110,height >= 110, heigh... |
4d2c47891151f1faaa872eda0509cc215764c956 | injoon5/C3coding-python | /2020/05/27/1.py | 228 | 4.0625 | 4 | for num in range(1, 10+1):
if(num % 3) == 0:
continue
print(num, end='+1 = ')
print()
for num in range(20,50+1):
if(num %2) == 0 and (num %3)==0:
print(num, end=". what?!?!")
break
|
6eff541190581caffe0f5d3cd92337f68f588da3 | injoon5/C3coding-python | /2020/10/07/4.py | 553 | 3.78125 | 4 | class Car:
color = ''
speed = 0
def upSpeed(self, value):
self.speed = value
Car1 = Car()
Car2 = Car()
Car3 = Car()
Car1.color = '검정'
Car2.color = '빨강'
Car3.color = '파랑'
Car1.upSpeed(70)
Car2.upSpeed(90)
Car3.upSpeed(50)
print('자동차 1의 색깔은', Car1.color, '이고, 속도는 ', Car1.speed, 'km 이... |
fffdeabaff5d54b653374b82bca110a832c0f008 | chansonzhang/FirstNLP | /syntactic/final_question_20.py | 827 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# Author Zhang Chen
# Email ZhangChen.Shaanxi@gmail.com
# Date 2018/11/21
import nltk
from nltk import load_parser
sentences=['fall leaves fall',
'fall leaves fall and spring leaves spring',
'the fall leaves left',
'the purple dog left',
'the dog and c... |
ae9f86de357ddd3fb05f01017cd605a57285d90d | aryaburke/orgs-data-consolidator | /dataconsolidator_year.py | 2,052 | 3.609375 | 4 | #a second script, designed to be run after the first, to include additional year data.
import csv
YEAR = 2019
R = "c_year.csv"
W = "consolidation_new_year.csv"
"""We're importing a file with the format:
0 first_name,
1 last_name,
2 email,
3 zip,
4 bad year field,
5 bad year field,
6 bad year fiel... |
c1a3c8305447e8ef79212e07731b4744759074f7 | shakibaSHS/pythonclass | /s3h_1_BMI.py | 245 | 4.15625 | 4 | weight = int(input('input your weight in kg\n weight='))
height = float(input('input your height in meter\n height='))
def BMI(weight , height):
B = weight / (height ** 2)
return B
print(f'Your BMI is= {BMI(weight , height)}')
|
defdf85fc51d5df8dd323fde8d3b2af67d12f828 | bijjalauday/test-repository | /crea.py | 426 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import sqlite3
def create():
conn=sqlite3.connect("data.db")
cur=conn.cursor()
create_table="create table if not exists users(id INTEGER PRIMARY KEY,username text,password text)"
cur.execute(create_table)
create_table="create table if not exists item... |
b2b54b45e806acff0d0d7efee18c0bf5b6b4d0b0 | abhishek5135/Python_Projects | /snakewatergun.py | 1,550 | 4.125 | 4 | import time
import random
def turn(num):
player_1=0
player_2=0
listcomputer=['snake','water','gun']
computer=random.choice(listcomputer)
num2=0
while(num2!=num):
print("snake","water","gun")
players_inpu = input("Player 1 Enter your choice from above ")
print... |
492a46aa63f153660ff482bc980997dd8ebf9d1c | jonathankohen/python | /fundamentals/OOP.py | 1,086 | 3.5625 | 4 | class House:
def __init__(self, numGarages, dogName):
# attributes
self.numLivingRooms = 1
self.numBaths = 3
self.numBedrooms = 4
self.numBackyard = 1
self.garageCount = numGarages
self.nameOfOwner = dogName
self.solarPanels = 0
def addSolarPower(... |
5303c0011c0154c7cf40b54bc528c0d7040b0727 | jonathankohen/python | /fundamentals/functions_2.py | 811 | 3.75 | 4 | def countdown(num):
newArr = []
for i in range(num, -1, -1):
newArr.append(i)
return newArr
print(countdown(5))
def p_r(list):
print(list[0])
return (list[1])
print(p_r([1, 2]))
def f_p(list):
return list[0] + len(list)
print(f_p([1, 2, 3, 4, 5]))
def greaterThanSecond(list):... |
4c79742f96b92448c5cb2e28c54be19dfdb0c207 | jonathankohen/python | /fundamentals/users.py | 834 | 3.8125 | 4 | class User:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def make_deposit(self, amount):
self.balance += amount
return self
def make_withdrawal(self, amount):
self.balance -= amount
return self
def display_user_balance(self... |
16cf1423d8a7840f49b7ad206f0f8b9f5104a514 | meet29in/Sp2018-Accelerated | /students/mathewcm/lesson04/trigrams.py | 1,217 | 4.125 | 4 | #!/usr/bin/env Python
"""
trigrams:
solutions to trigrams
"""
sample = """Now is the time for all good men to come to the aid of the country"""
import sys
import random
words = sample.split()
print(words)
def parse_file(filename)
"""
parse text file to makelist of words
"""
with open(filename) as i... |
cc68a6845871ba1bd01fbf736331f0d90f108194 | pahbs/HRSI | /gen_chunks.py | 3,276 | 3.625 | 4 | #! /usr/bin/env python
import csv, math
import argparse
"""Generate chunks (subsets) of an input list of files to process based on a second list
AVOID ERROR: create vmList.txt in linux
This script breaks up a CSV into smaller sub-CSVs
1. according to number of VMs that will be used to process sub files
... |
4d969998b3efc49348ba8a3f859d057e0b218e05 | Jihyeonji/Mypython | /ch3/p08.py | 178 | 3.640625 | 4 | weight=float(input('무게를 입력 하세요.킬로그램'))
v=float(input('속도를 입력하세요.미터/초'))
energy=1/2*weight*v**2
print('운동에너지=',energy)
|
8605f6d27c5050a6c56da00fec742dcf80a12b3e | Jihyeonji/Mypython | /ch3/vudrbs.py | 236 | 4 | 4 | first=int(input('첫번쨰 수를 입력하세요'))
second=int(input('두번쨰 수를 입력하세요'))
third=int(input('세번쨰 수를 입력하세요'))
avg=(first+second+third)/3
print(first,second,third,'의 평군:',avg)
|
86a0ed2dc670ba6c38d44ade58dbeb8eda050025 | Jihyeonji/Mypython | /ch3/lab.py | 194 | 3.75 | 4 | weight=float(input('몸무게를 kg단위로 입력하세요'))
height=float(input('키를 미터 단위로 입력하시오'))
bmi=weight/height**2
print('당신의 BMI=',bmi,'입니다')
|
137490215713661f108d5a5d28fac06ebaefb415 | psathyanarayan/Data-Structure-Lab | /Sorting/heap.py | 658 | 3.703125 | 4 | def heapify(ls, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and ls[l] > ls[largest]:
largest = l
if r < n and ls[r] > ls[largest]:
largest = r
if largest != i:
ls[i], ls[largest] = ls[largest], ls[i]
heapify(ls,n,largest)
def heapSort(ls, n):
... |
b4cca0911369c806eb536057439d7340a694ee86 | 596718125/store | /test3-1.py | 4,767 | 3.828125 | 4 | #dict = {"k1":"v1","k2":"v2","k3":"v3"}
#1、请循环遍历出所有的key
'''
for a in (dict):
print(a)
'''
#2、请循环遍历出所有的value
'''
print()
for a in (dict):
print(dict[a])
'''
# 3、请在字典中增加一个键值对,"k4":"v4"
'''
print()
dict["k4"]="v4"
print(dict)
'''
#请将上面的数据存储到字典里,可以根据水果名称查询购买这个水果的费用,用水果名称做key,金额做value,创建一个字典
'''
info = {"苹果":32.8,"香... |
e26fb1fadf81c957e39d7ad4eb0f27a080da8796 | TheJayesh99/AddressBookPython | /AddressBookFileService.py | 4,378 | 3.671875 | 4 | from AddressBookConsoleService import AddressBookConsoleService
import json
from Contacts import Contact
import csv
class AddressBookFileService:
JSON_FILE = "resources/address_book.json"
CSV_FILE = "resources/address_book.csv"
def write_in_json(self):
"""
Method to write all conatct... |
90b7a04ce7983971ad39a26568693ac3f50cafea | sangmain/Sudoku-Solver | /project_py/sudoku_solver.py | 2,974 | 3.90625 | 4 | import numpy as np
SIZE = 9
matrix = []
x_list = []
#function to print sudoku
def print_sudoku():
# for i in matrix:
# print (i)
sudo = []
for i in range(len(matrix[:])):
string = ""
for j in range(len(matrix[i])):
if x_list[i][j] != "0":
string += ... |
d660142695fc6dca1a2f4b6e38c4814c021ff32c | SFE311T-GROUP-5-ASSIGNMENT/PermutaionTesting | /nextPTest.py | 685 | 3.796875 | 4 | import unittest from nextPermutations import nextPermutations
class nextTest(unittest.TestCase):
#test the output of the correct value
def test_next(self):
#list to test
myList = [1,2,3]
#function call to be tested
result = nextPermutations(myList)
#assert
... |
7d19b5423b0c4c51195547c067f5fff9fd04e7ec | olincollege/ultimate-snake | /unit_tests.py | 10,057 | 3.578125 | 4 | """
Unit tests for snake_model
"""
import pytest
from snake_model import Board, Snake, Item
test_snake = Snake()
test_food = Item()
test_potion = Item()
test_speed_boost = Item()
test_board = Board(test_snake, test_food, test_potion, test_speed_boost)
def check_snake_property(_):
"""
Check that the Board cl... |
1b6cf6a38093541a2a0571d3156b57e3dc263dad | magakoos/fogstream_python_course_homeworks | /homeworks/03__01__check_correct_brackets/main.py | 1,178 | 3.84375 | 4 | # coding=utf8
checked_list = [
'(asdfasdf)',
'[asdfa(sf]',
'{asfdsagsaf}',
'(asdfasdf(fafa)]',
'(safdasfd[fasdf]fasfd)',
'(asdfa{sdfsa[asf{asd}fasd]fsafas)',
'(asdf{}asdf)',
'{asfas)fasdas}',
'fasfdas[asdfasdf{fasdfas(fasf'
]
brackets = {
'(': ')',
'[': ']',
... |
e84165a17541cbf3a18d2b082add8111bfb290e9 | EdTeKLA/Cree-Tutor | /CreeTutorBackEnd/common_to_apps/subtitle_readers.py | 4,663 | 3.8125 | 4 | """
File contains a class which aids views that need to process srt files that will be shown to the user.
"""
import re
class SubtitleReader:
"""
Class was created to aid views that need to process srt files in activities such as transcription and shadowing.
"""
@staticmethod
def read_file(file_pa... |
ab0f90f4dafe3c8c3c38b0e289696b4fe36c0cbe | EdTeKLA/Cree-Tutor | /Linguistics/analyze_words.py | 1,637 | 3.625 | 4 | # -*- coding:utf-8 -*-
"""
Created on Wed Jul 04 2018
This is a script that analyzes words.txt and creates two files.
1. a list of lemmas called lemmas.txt
2. a list of gram_codes called gram_codes.txt
This system will need to be replaced by a better system.
Please don't add new words to words.txt
"""
import os
imp... |
91c740e50dac4e543f50e516ebcbc685397cb9a5 | Sashi445/DatastructuresandAlgorithms | /Leetcode/500_keyboardrow.py | 2,012 | 3.515625 | 4 | # Problem link
# https://leetcode.com/problems/keyboard-row/
# Problem Number - 500
# MySolution
class Solution:
def findRow(self, keyboard: List[str], word: str) -> int:
for i in range(len(keyboard)):
row = keyboard[i]
letter = word[0]
if letter in row:
... |
d57de0f6a30331e626be65f97662b0b5252acf5a | rotwem/ex9 | /board.py | 6,777 | 4.28125 | 4 | from car import Car
class Board:
"""
A class of board objects:
each board is a list of lists of ints that represents the rows of the board -
each empty block represented by 0 and onces a car is added to a coordinate it contains the name of the car.
each board also has a list of empty cells and a l... |
26f0d3c5fb36f440f6485f3f49795014cba545ae | Jerryhe1995/Data-Science-Projects | /392-6/392_4.py | 967 | 3.609375 | 4 | # Noah Davis & Je Hie
# CSC 392
# Assignment: Pie Chart
# References: that link in the assignment and pandas docs
# Import stuff
import matplotlib.pyplot as plt, pandas as pd, numpy as np
# Read csv values
df = pd.read_csv("states.csv") # not hardcoded, see the csv value in the zip.
# Get the first letter of each ab... |
8ee82bddd24429079aca9c629ad45af7c3e4ad88 | thuanhoa29031999/th4-ban-hoan-thien | /bai 25.py | 123 | 3.515625 | 4 | a=input("nhập dãy số các nhau bằng dấu phẩy:")
s=[x for x in a.split(",")if int(x)%2!=0]
print(",".join(s))
|
78dfd10fbc3a1aee7caa15c5051c94a9b546e55a | coding-corgi/homework-prac-week3 | /반복문.py | 343 | 3.546875 | 4 | fruits = ['사과','사과','사과','사과', '배', '감', '귤']
# #사과 세기
# count = 0
# for i in fruits:
# if i =='사과':
# count +=1
# print(count)
# 과일 세는 함수
def fruit_name(name):
count =0
for i in fruits:
if i == name:
count +=1
return count
print(fruit_name('사과')) |
0fe89d64ae8d7add26149ce0c5b3950aef1e5aa8 | Heino25/Python-matplotlib | /Chapter2/p1.py | 163 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = x
plt.plot(x, y, label='linear')
plt.legend()
plt.savefig("foo.png")
plt.show() |
4e38cc0ea1349ca04336259204474f6e62a68290 | dkratzert/FinalCif | /finalcif/cif/reference.py | 2,466 | 3.640625 | 4 | # ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# Daniel Kratzert <dkratzert@gmx.de> wrote this file. As long as you retain
# this notice you can do whatever you want with this stuff. If we meet some day,
# and you think this stuff is wo... |
0d4f31505fdad463001ae773631bbf0f3ec18e11 | HARSHA4499/Quiz_In_Python | /quiz_Python/python_quiz.py | 1,593 | 4 | 4 | from random import shuffle
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
name=input("WELCOME...ENTER YOUR NAME TO START THE GAME ")
print("HELLO ",name, " HAVE FUN")
print("*******************************************************")
... |
f9e3583d89ca4431fe117b57b8a52b2c7718af33 | PhakineeS/CP3-Phakinee-Sirisukpoca | /collection.py | 629 | 3.609375 | 4 | def small(a):
res = ''
for i in range(len(a)):
if ord('A') <= ord(a[i]) <= ord('Z'):
res += chr(ord(a[i])+32)
else:
res+=a[i]
return res
menuDic = []
while True:
menu = input('Enter Menu : ')
menu = small(menu)
if menu == 'exit':
break
else:
... |
db09581540642a971cf0a59381b77c45333dd4e0 | PhakineeS/CP3-Phakinee-Sirisukpoca | /Function2.py | 128 | 3.5625 | 4 | def vatCalculater(n):
return n+(n*0.07)
#n = int(input("Enter Price : "))
print(vatCalculater(int(input("Enter Price : ")))) |
2ddd20e6210f26565e282f49389f0e8c8de5c8ce | SaretMagnoslove/coursera_python-for-everybody | /coursera python data/09_04.py | 440 | 3.5 | 4 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emails = dict()
for line in handle:
if line.startswith('From '):
line = line.split()
email = line[1]
emails[email] = emails.get(email,0)+1
bigcount = None
bigemail = None
for email,count in emails.ite... |
358301dcc4c5c9fa06e0f92b5b51616c59fcf66f | chihun21c/chihun21c | /pset6/pset6/readability.py | 481 | 3.78125 | 4 |
text = input("Text: ")
L = 0
W = 0
S = 0
n = len(text)
if text[0] >= 'A' and text[0] <= 'z':
W += 1
for i in range(n):
if text[i] >= 'A' and text[i] <= 'z':
L += 1
if text[i] == ' ':
W += 1
if text[i] == '.' or text[i] == '!' or text[i] == '?':
S += 1
g = round(0.0588 * (... |
a36a754dd82c0e4b38feb1cbe6a0be69c3961f1e | Nielshlaustsen/bjsim | /bj/hand.py | 2,866 | 3.546875 | 4 | from collections import namedtuple
class Hand(namedtuple('Hand', 'ace osum fst snd')):
"""A hand of cards.
Attributes:
ace:
Whether we have an ace. (We only care about having one ace, since
we never make two aces both worth 11).
osum:
Sum of all cards, excluding the ace if we have one. This value will
... |
c3d438bb6a08206aafd4371647e4c92d5c50530f | Cons19/Conway-Game-of-Life | /mvc/view.py | 5,809 | 3.84375 | 4 | import tkinter as tk
from tkinter import *
class GameOfLifeView:
def __init__(self, controller):
self.controller = controller
self.window = tk.Tk() # make an instance of the Tkinter class
self.window.title("C&P's Game Of Life")
self.window.geometry("1000x705")
# GUI Fram... |
a1da7eaba857ccc96ca680854a8820c949e56a1c | lidxhaha/suisui | /evaluate_keras_augmentation.py | 825 | 3.65625 | 4 | # дһչʾ Data Augmentation Чij
# ڴģCNN磬ҪһӺ Data Augmentation
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
img1 = Image.open('3.jpg')
img2 ... |
a3ac015d28cee2a8e6d04f47ed76bbe6a6a35a19 | fagan2888/personal_learning | /coursera_interactive_python/03 Examples.py | 3,873 | 4.0625 | 4 | # convert xx.yy to xx dollars and yy cents
def convert(val):
dollars = int(val)
cents = int(100 * (val - dollars))
return str(dollars) + " dollars and " + str(cents) + " cents"
# Tests
print convert(11.23)
print convert(1.12)
print convert(1.01)
print convert(0.01)
print convert(0)
print convert(-1.40)... |
f4dd8e9959bd1ac883639477ee94dc1ca24cd08f | ShadowStorm0/College-Python-Programs | /word_Counter.py | 714 | 4 | 4 | #Open file and Input Valiadation (User input)
fileName = input('What is the name of the file you want to open? ') # mbox-short.txt
try:
fileOpen = open(fileName)
except:
print('File not found. Please try again.')
exit()
#Create Dictionary
counts = dict()
for line in fileOpen:
words = line.split()
#Count... |
3580488590a479d85b7e0bce53567e00608b2d61 | ShadowStorm0/College-Python-Programs | /day_Of_The_Week.py | 824 | 4.34375 | 4 | #Day of Week List
Week = ['I can only accept a number between 1 and 7. Please try again.', 'Sunday', 'Monday', 'Tuesday', 'Wedensday', 'Thursday', 'Friday' ,'Saturday']
#Introduce User to Program
print('Day of the Week Exercise')
print('Enter a number for the day of the week you want displayed.')
#Input prompt / Inpu... |
969d5b040c98d5b09689223c174fe00640b9b2e6 | runnablek/python-study-code | /test04.py | 174 | 3.5625 | 4 |
class Student:
name = "choi"
def info(self):
print("my name is " + self.name +"!!")
inst = Student()
print(type(inst))
#inst.info()
print("aaaa")
print("bbbbs")
|
069a7c1832e3f1888d08126bb210ba483d1884bb | jonasrk/interview_cake_solutions | /PalantirFirstPhoneScreen/game.py | 2,558 | 3.5625 | 4 | class Expression:
# This is only an interface
def __init__(self, first, second, sum):
self.first = first
self.second = second
self.sum = sum
def get_chars(self):
s = set()
for char in self.first:
s.add(char)
for char in self.second:
s.... |
d2399788566829e056de53d91192004433c9cbae | jonasrk/interview_cake_solutions | /Q43-merge-sorted-arrays/merge-sorted-arrays.py | 497 | 3.859375 | 4 | def merge_lists(listA, listB):
result = []
while len(listA) + len(listB) > 0:
if len(listA) == 0:
result = [listB.pop()] + result
elif len(listB) == 0:
result = [listA.pop()] + result
else:
if listA[-1] > listB[-1]:
result = [listA.pop()] + result
else:
result = [listB.pop()] + result
ret... |
8276527694ca85a52ab08c2976eb4280c396f2a2 | jonasrk/interview_cake_solutions | /Q30-permutation-palindrome/permutation-palindrome.py | 544 | 3.828125 | 4 | def permutation_palindrome(input):
occs = {}
for char in input:
if char in occs:
occs[char] += 1
else:
occs[char] = 1
count_uneven = 0
for occ in occs:
if occs[occ] % 2 != 0:
count_uneven += 1
if count_uneven > 1:
r... |
dbdead594fa632335c3918e888bedc844e0bd9c6 | jonasrk/interview_cake_solutions | /Q20-largest-stack/largest-stack.py | 1,056 | 3.984375 | 4 | import sys
class Stack(object):
def __init__(self):
"""Initialize an empty stack"""
self.items = []
self.max = -sys.maxsize
self.popped_after_max = False
def push(self, item):
"""Push new item to stack"""
self.items.append(item)
if item > self.max:
self.max = item
de... |
2134aa6692ed8dd477ebf74f4465cb5b0de429c5 | patrxon/SnowballGenerator-3 | /tuple_operations.py | 645 | 3.625 | 4 | def flip(tuple_, first=False, second=False):
if first:
t1 = -tuple_[0]
else:
t1 = tuple_[0]
if second:
t2 = -tuple_[1]
else:
t2 = tuple_[1]
return t1, t2
def add_up(tuple_a, tuple_b):
return tuple(map(sum, zip(tuple_a, tuple_b)))
def subtract(tuple_a, tuple_b)... |
7f214ef303bf68f1bfe6bab3206532a33115b09c | HoenikkerPerez/ase-19 | /lesson1/FOOCalculator.py | 379 | 3.859375 | 4 | import lesson1.calc.calculator as c
# prova pull req
class FooCalculator:
def __init__(self):
pass
def sum(self, m, n):
return c.sum(m, n)
def div(self, m, n):
return c.divide(m, n)
my_calc = FooCalculator()
print(my_calc.sum(3, 5))
print(my_calc.div(3, -1))
print(my_calc.div(... |
9ff1e7a9875df38ebd9f84ded6cad594cfdfe9cc | pricillanestha/basic-phyton-b6-b | /3.7 Function-Parameter.py | 773 | 3.90625 | 4 | # Function Parameter / Argument
def Sapa() :
print ("Hello")
def say_hay() :
print ("Hai")
def tanya_kabar() :
print ("Apa Kabar ?")
def perkenalan (nama,umur) :
print ("Nama saya adalah " +nama)
print ("Nama saya adalah " ,umur)
# perkenalan("Nafi",22)
# perkenalan("Jon",23)
# perkenalan("Joni",24)
# Bisa di... |
be0ec0cebaf91ae6638b53aa756141a3a0953491 | pricillanestha/basic-phyton-b6-b | /1.3-Tipe-Data.py | 1,256 | 4.03125 | 4 | # Python Tipe Data
# Nama = "Pricilla"
# Umur = 22
# Tinggi = 170
# Nilai = 8.9
# Cara Cek Tipe Data
# Kalau tipe data String "Str" itu untuk kalimat /huruf
# Tipe Data Integer "Int" itu untuk yang angkanya bulat tidak ada koma
# Titik itu untuk pembatas dalam penulisan syntaks sedangkan koma untuk pemisah
# Float it... |
e58606a66a8865fe7a429d5cbcba9492d84e635b | percentcer/interview_prep | /logic/stacks.py | 8,476 | 3.515625 | 4 | __author__ = 'percentcer'
# Chapter 4
# Stacks and Queues
from logic.linked_lists import Node
class CommonStack(object):
def __init__(self):
self._count = 0
def __len__(self):
return self._count
def __eq__(self, other):
# this is all quite silly
if not isinstance(other, ... |
21c60dadf07db0f4b2a91411838ecfd2b97ee2e5 | tedyeung/Python- | /100Exercise/12.py | 356 | 3.671875 | 4 | # Question: Complete the script so that it produces the expected output. Please use my_range as input data.
my_range = range(1, 21)
#Expected output:
# [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
my_range = list(range(1,21))
new_list = []
for i in my_range:
ne... |
1da1011ff0343dd9e08e291df541299ff1fdde7b | tedyeung/Python- | /Bootcamp/prime_number.py | 385 | 3.984375 | 4 | import math
question = input('Please add number and check if the number is Prime? ')
num_input = int(question)
def prime_number(number):
if (number % 2 == 0):
return False
for i in range(3, int(number**0.5) + 1, 2):
if (number % 1 == 0):
return False
return True
prim... |
b464034c111831c03898046451c250a9d5c2d941 | tedyeung/Python- | /python_cc/func2.py | 701 | 3.8125 | 4 | # simple func with 2 arg
def city_coutry (city, coutry):
print(coutry.title(), ',' , city.title())
city_coutry('Belgrade', 'Serbia')
city_coutry('new york', 'usa')
city_coutry('london','england')
# write a simple func that outpu is dic
def make_album(artist, song):
album = {
'name': artist,
... |
99fe4e60a3b8a73b5abc82e2c77e00219328b88d | tedyeung/Python- | /python_cc/dic.py | 476 | 3.71875 | 4 | # Dictiaries
users = {
'first_name': 'Slvko',
'last_name': 'Popovic',
'age': 35,
'city': 'Pompano Beach'
}
print (users['first_name'])
print (users['last_name'])
print (users['age'])
print (users['city'])
print (users)
# loop
print('************ LOOP ************************************')
for k... |
d2b85bd3b7183b645646d8616f49b1797f1ef61b | tedyeung/Python- | /100Exercise/26.py | 165 | 4 | 4 | '''
Question: Make a script that prints out numbers from 1 to 10
Expected output:
1
2
3
4
5
6
7
8
9
10
'''
a = list(range(1,11))
for number in a:
print(number) |
ca1abcd7e0688640ffd1feeb1989a2d4f6961dba | tedyeung/Python- | /basics/variables.py | 985 | 4 | 4 | # simple string variable
print("******************* Variables ****************************")
name = "Slavo" # string varibale
print(name)
print(type(name))
print("******************* numbers ****************************")
a = 2
b = 3
print (a , b)
print (type(a), type(b))
print("******************* float *************... |
c392fa969e5f479032507a0b0cfeccfc5519e8f2 | tedyeung/Python- | /basics/t.py | 92 | 3.828125 | 4 | name = input("What is your name? ")
anw = ',you are doing smart thing now'
print(name, anw) |
010f9e4c68b48509e29a67990d9dd15f18281959 | tedyeung/Python- | /python_cc/test_case/city_func.py | 320 | 3.640625 | 4 | def city_country (city, country, population=0):
formated_place = city.title() + ',' + country.title()
if population:
formated_place += ' - population ' + str(population)
return formated_place
print (city_country('belgrade', 'serbia', 7000000))
print (city_country('new york', 'usa', 24000000))
|
afc3350b3d6adfb297714f0faeb50c24633d6dfa | tedyeung/Python- | /basics/my_functions.py | 226 | 3.828125 | 4 | # function
def minutes_to_hours (minutes):
hours = minutes / 60
return hours
print (minutes_to_hours(60))
def seconds_to_hours (sec):
hours = sec / 3600
return hours
print (seconds_to_hours(56000), 's')
|
da73a3c8b5bbf1851e12a174aa7ec03e164ebd2a | tosmun/Python-LinkedList | /unittest/test.py | 1,321 | 3.75 | 4 | import unittest
from linked_list import LinkedList
class TestCase(unittest.TestCase):
def test_add_first(self):
l = LinkedList()
l.add_first(1)
l.add_first(2)
self.assertEquals(2, len(l))
self.assertEquals("[2,1]", str(l))
def test_add_last(self):
l = LinkedList()... |
daaa48eac63299d8ce07a82914d0b66078a0d63f | pritam1997/python-test-6 | /q7.py | 125 | 3.75 | 4 | def inputstring():
s1=input("Enter 1st string : ")
s2=input("Enter 2nd string : ")
return s1+s2
print(inputstring()) |
9a623d8edbf1e22533521447f726d1d22c4b0bd3 | percent4/Dynamic_Programming_examples | /subset_sum.py | 1,673 | 3.859375 | 4 | import numpy as np
# A Dynamic Programming solution for subset sum problem
# Returns true if there is a subset of set with sum equal to given sum
def isSubsetSum(st, n, sm):
# The value of subset[i, j] will be
# true if there is a subset of
# set[0..j-1] with sum equal to i
subset = np.array(... |
88ea717f1ec74075702facef5e62f60f5913970c | Daniel123jia/Pytorch_study | /Linear_Regression.py | 3,605 | 3.71875 | 4 | import torch
import matplotlib.pyplot as plt
# 创建数据集
def create_linear_data(nums_data, if_plot=False):
"""
Create data for linear model
Args:
nums_data: how many data points that wanted
Returns:
x with shape (nums_data, 1)
"""
x = torch.linspace(0, 1, nums_data)
x = torch.un... |
3ae96a151c8fd6626c562dc699a2eed5d10a40a9 | KAVILSHAH1101/Extra_m | /practical10/p10_03.py | 571 | 4.0625 | 4 | class Account:
rate=2.5;
def input(self,p,n):
self.p=p;
self.n=n;
def operation(self):
interest=(self.p*Account.rate*self.n)/100;
return interest;
def modify(cls):
Account.rate=3;
a1=Account();
a1.input(2000,2);
print("interst of a1 before ... |
37ae383a7821063f29e3345b6ce653d9354cc3b4 | food-computer-program/raspberry-pi-farm | /grow_lights.py | 938 | 3.90625 | 4 | #control grow lights for the food computer from a Raspberry Pi
import RPi.GPIO as GPIO
from time import sleep
#identify where the lights are connected to the Raspberry Pi
# in this case, we’re attaching it to the GPIO Pin 7
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7, GPIO.OUT)
#set the schedule for... |
28f71fd44b477792488a87f776ec290beec38ef9 | EricKoegel/learningpython | /Test/com/PracticeWork/BreakTime.py | 772 | 3.578125 | 4 | '''
Created on Feb 24, 2016
@author: michael.f.koegel
'''
"""
This is a simple program to tell me I need a break after a certain period of time.
"""
import webbrowser #needed to work with the webbrowser.open_new function
import time #needed to work with the current time - aka ctime()
count = 0 #counter for the while ... |
2ee963bde933f3392917040401eb33f178d5b6b6 | EricKoegel/learningpython | /Test/com/PracticeWork/median.py | 313 | 3.765625 | 4 | '''
Created on Feb 26, 2016
@author: michael.f.koegel
'''
def median(values):
values = sorted(values)
length = len(values)
index = ((length - 1) // 2)
if (length % 2 == 0):
return values[index]
else:
return (values[index] + values[index + 1]) / 2.0
median([2,7,1,4,9,3]) |
8c8fd42b7a63c4da91c9a8b36a2c5fdb0124b70b | KenyC/Exh | /examples/tutorial/Tutorial.py | 11,701 | 3.8125 | 4 | # %%
"""
# Tutorial
## Imports
"""
from exh import *
from exh.utils import jprint # for fancy displays in Jupyter Notebook
import exh # This import is just to access the version
print(exh.__version__)
# %%
"""
## Create formulas
Formulas are created from propositions (0-ary predictates) and predicates.
Both of ... |
5a23259cdbe9ec509986f7d3a5f8d47d3f0182d3 | Mgallimore88/NatureOfCode | /4_1_Mover_object/Mover.py | 1,225 | 3.53125 | 4 | from p5 import *
class Mover:
def __init__(self, width, height, start_x, start_y):
self.location = Vector(start_x, start_y)
self.velocity = Vector(0, 0)
self.mass = 1.5
self.acceleration = Vector(0.01, 0.01)
def applyForce(self, force):
self.acceleration += force / sel... |
a9a960f5ef0773d92d401b7ff59381f9a759ea37 | anibalvy/katas | /004-find_the_divisors.py | 1,162 | 4.0625 | 4 | '''
Create a function named divisors/Divisors that takes an integer n > 1 and returns
an array with all of the integer's divisors(except for 1 and the number itself),
from smallest to largest. If the number is prime return the string '(integer) is prime' (null in C#)
(use Either String a in Haskell and Result<Vec<u3... |
7304085def68b8e64734dc0003b28272efb1b243 | hunkydoryrepair/farkle-sam | /farkle/scoredice.py | 7,457 | 3.796875 | 4 | """This module computes the correct way to score the given dice
"""
class Payout:
"""The types of matches we can have with the dice
"""
Kind6Of = 1
Kind5Of = 2
Kind4Of = 3
Kind3Of = 4
ThreePair = 5
Straight6 = 6
SumDice = 7
class ComboPoints:
"""Represents a scoring combinat... |
8e6293fcb33e2626a8cd935e3e230e5fb68f40dc | arkitpawar/healthcare_credit | /rough.py | 854 | 3.84375 | 4 | import csv
with open('data.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
data = list(csv_reader)
headers = data[0]
data = data[1:]
def match_rows(speciality = None, city = None, state = None, zip_code = None):
for row in data:
# ['2', 'B', 'Vision', 'Trenton', 'HD', '... |
bc2c02f711d041524939ea1dee14a51be2cf8878 | broocklyn/PY-1-6388-HW | /lesson03/home_work/hw03_normal.py | 2,379 | 3.75 | 4 |
__author__ = 'Учускин Павел Валерьевич'
# Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
fib_p_p = 1
fib_p = 1
fib = 0
if n == 1:
print(fib_p_p, fib_p, end = ' ')
elif n == 2:
print(fib_p, end = ' ')
for... |
4dcaabf16d2a0e0354d9954ee3b05306f19d1591 | goonming/Programing | /5_9.py | 504 | 4.40625 | 4 | #creating and accessing and modifying a dict
#ereate and print Dict
emptyDict={}
print "the value of emptyDict is :", emptyDict
#creat and print Dict with initial values
Dict={'Name':'chenming','age':100}
print "this is chen ming: ", Dict
#accessing and modifying the Dict
age_2= raw_input("please input a age: ")
Dic... |
a022c17c6f397e7892ba83cc60c53538b87a3721 | busbyra/Polaris_Sheet | /stats.py | 6,080 | 3.890625 | 4 | # Character stats, starting with primary attributes
# Primary Attributes start at 7 and go up from there. Attribute points start at 38 and are adjusted later
class Character(object):
name = ''
attributePoints = 38
strength = 7
constitution = 7
coordination = 7
adaptation = 7
perception = 7
intelligen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.