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
32b5a848db2ed50cefc5c48f66a9771d1b7180df
purice93/Machine-Learn-In-Action
/unit03/trees.py
3,858
3.5
4
from math import log import operator ''' 机器学习实战-第三章(决策树) ''' # 创建数据集 def createDataSet(): dataset = [ [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no'] ] labels = ['good', 'bad'] return dataset, labels # 计算香农熵 def calcShannonEnt(dataset): numEntries = len(dat...
a839cd4695a901429f47eea90430c4a386490853
Joel-Quintyn/Python-Learning
/Salary Calculator.py
700
4.0625
4
""" SYNOPSIS: This Program Was Rewritten From C On My Learning Journey Of Python. """ print("\nThis Program Is Designed To Calculate Your Net Pay & Overtime") hours = int(input("\nEnter Your Hours Worked This Week:- ")) rop = int(input("Enter Your Rate Of Pay:- $")) if hours > 40: regularpay = hours*rop ove...
f2f6a8e2cfa58cd8b562d87848c3811bdd82857e
Joel-Quintyn/Python-Learning
/Random Stuff.py
163
3.828125
4
""" TODO: Encryption Program """ mystring = 'iloveyou' for letter in mystring: x = ord(letter) + 2 print("{} - {} {}".format(ord(letter), letter, x))
3b73a5d07d95211e911bba9f885fe79aa3e7844f
saraechary/Wstep-do-informatyki
/Laboratorium 1/zad6.py
682
3.5
4
import sys a = int(input("Wprowadź wybraną liczbę, aby sprawdzić czy jest to liczba pierwsza : ")) def czy_pierwsza(s): if s == 2 : return str(s) + " jest to liczba pierwsza" if s % 2 == 0 or s <= 1: return str(s) + " nie jest to liczba pierwsza" # pierw = int(s**0....
31e4bc52f6b37cb336d687dc008aba4daa5e7ee3
saraechary/Wstep-do-informatyki
/Laboratorium 1/zad3.py
406
3.53125
4
import sys n = int(input("Wprowadź liczbę, której pierwiastek chcesz otrzymać ze wzoru Newtona : ") ) def absolute(absol) : if absol < 0: return -absol else: return absol x = n / 2 epsilon = 0.000001 i = 0 while (absolute (x - (n / x))> epsilon ): x = (x + (n / x)) / 2 ...
3c718a60bb7ce7b9cdc1ac1b70993e6fe04a0f70
pgmabv99/pyproblems
/av11_stock.py
1,408
3.828125
4
# Say you have an array, A, for which the ith element is the price of a given stock on day i. # Design an algorithm to find the maximum profit. # You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). # However, you may not engage in multiple transactions a...
2a5e548a3fc800b80dd8dbeabcedfaecd88f1eaa
pgmabv99/pyproblems
/av14_list.py
2,778
3.59375
4
import math class node: def __init__(self,pv): self.v=pv self.next=None def list_2_num(self): if self.next==None : return self.v, 1 else : next=self.next num,pos=next.list_2_num() numa=self.v*(10**pos) pos2=pos+1 ...
48e7bb0c56c051a3170a83599ed895fed26f36b3
pgmabv99/pyproblems
/test3.py
924
3.734375
4
import pandas as pd import csv from IPython.display import display, HTML # Write your code herep df= pd.read_csv("./root/customers/data.csv") # Preview the first 5 lines of the loaded data # data.head() display(df) # --------- print("Total customers:") print(df['ID'].count()) # -------------? print("Customer...
10c5d473ec747fc6b36a77ff8e219960e07fee73
cristinasewell/python-challenges
/python-api-challenge/WeatherPy/main.py
11,603
3.765625
4
#!/usr/bin/env python # coding: utf-8 # # WeatherPy # ---- # # #### Note # * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. # In[2]: # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd imp...
48638c406d2b678416dd75dd04b22814d061013a
C-CCM-TC1028-102-2113/tarea-4-CarlosOctavioHA
/tarea-4-CarlosOctavioHA/assignments/10.1AlternaCaracteresContador/src/exercise.py
323
4.125
4
#Alternar caracteres num = int(input("Dame un numero")) cont = 0 variable_1= "#" while cont < num: cont = cont + 1 if variable_1 == "#": print(cont,"-", variable_1) variable_1= "%" else: variable_1 == "%" print (cont,"-", variable_1) variable_1= ...
840d02927a7cd63335063bfb27060f1507559c18
dlaperriere/misc_utils
/lib/md5.py
1,727
3.53125
4
""" Generate MD5 hash of a file or string """ from __future__ import print_function import hashlib import os import sys __version_info__ = (1, 0) __version__ = '.'.join(map(str, __version_info__)) __author__ = "David Laperriere dlaperriere@outlook.com" __all__ = ['md5sum'] # Python version compat ...
29cd39bb0f3f36027a6f69533905ba2ba3c667c7
jasonmiu/ex
/combinations/combinations.py
489
3.828125
4
#!/bin/env python3 def combin_iter(elements, r): combins = [] n = len(elements) for i in range(0, n): if r == 1: combins.append(list(elements[i])) else: for next in combin_iter(elements[i+1:n], r-1): combins.append(list(elements[i]) + next) ...
ed03cef20773b13070143965de70c7ae5bbff50e
aayush26j/DevOps
/practical.py
275
4.28125
4
num=int(input(print("Enter a number\n"))) factorial = 1 if num < 0: print("Number is negative,hence no factorial.") elif num ==0: print("The factorial is 1") else: for i in range(1,num+1): factorial=factorial*i print("The factorial is ",factorial)
87113d4992c010652180661eccca13bfb7419d3b
junzhiguavus/python
/Python Basic/jike_python_basic/closure_test3.py
704
3.828125
4
# a * x + b = y # without closure, two bad choice - poison # 1st poison, each repeat your mathematical formula # 2nd poison, make a and b also as variable, # so you could not think as mathematician because you cuold not use a and b math as parameter x_list = [i for i in range(10)] y_list = list(map(lambda x: 2 * x + 1...
9bce61e76d32beb31fc0199f7337243147d2a456
junzhiguavus/python
/Python Basic/jike_python_basic/closure_test2.py
584
3.828125
4
def add_one(current): return current + 1 num = add_one(1) next1 = add_one(num) next2 = add_one(next1) print(next2) # with closure, we don't need to manager variable, counter function 'cnt' will manage the variable for us, # maybe not so easy in this example, but more complicated math computation, it will become ...
0e623e754aab1ac383d925ac2812a56e272b73f2
junzhiguavus/python
/Python Basic/PycharmExercise/exercise1/main.py
320
3.859375
4
def main(): """ 主函数 """ a = ('a', 'b', 'c') b = (1, 2, 3) x = zip(a, b) print(list(x)) x = zip(a, b) print(dict(x)) c = zip(*zip(a, b)) print(list(c)) a1, a2 = zip(*zip(a, b)) print(tuple(a1)) print(tuple(a2)) if __name__ == '__main__': main()
8407b1b26f4a0d47d798721939caf55fed8113ae
csyanghan/algorithm-problems
/lcof/07-rebuild-binary-tree.py
943
3.828125
4
# @Author: Hanyang # @Date: 2020-11-18 from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: if ...
96d0353f4dc7c530b14ae7aae0349ebb8cfa59a0
csyanghan/algorithm-problems
/leetcode-cn/test.py
1,264
3.609375
4
# @Author: Hanyang # @Date: 2020-10-29 from typing import List class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: self.board = board self.dir_x: List[int] = [0, 1, 0, -1, 1, 1, -1, -1] self.dir_y: List[int] = [1, 0, -1, 0, 1, -1, 1, -1] x: int = click[...
3e1af0a9da13b23248cfcf44ff6ad696e2039d3e
csyanghan/algorithm-problems
/leetcode-cn/222-count-complete-tree-nodes.py
435
3.546875
4
# @Author: Hanyang # @Date: 2020-11-24 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 res = 1 if root.left: res += self.countNodes(root.left) ...
19d67fee8b0e2b0ca04aadca085835c61af921e8
csyanghan/algorithm-problems
/leetcode-cn/971-flip-binary-tree-to-match-preorder-traversal.py
1,025
3.75
4
# @Author: Hanyang # @Date: 2020-10-28 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def flipMatchVoyage(self, root, voyage): self.ans = [] self.voyage = voyage self.step =...
c3b1e0ba0d0208e6d47b6b4069d14967b83db967
sgolanka/A-December-of-Algorithms-2019
/December-08/Cheating_Probability.py
2,258
3.65625
4
"""Given an RxC Matrix in which each element represents the Department of a student seated in that row and column in an examination hall, write a code to calculate the probability of each student copying if a person from the same department sits: In front of him = 0.3 Behind him = 0.2 To his left or right = 0.2 In any ...
7381ce373cda29f56ff5b8fe0ef20aa666ea5473
KoSukun/PythonLearningWebProject201605
/bookstore/cgi-bin/customer-tbl.py
581
3.6875
4
import sqlite3 connection = sqlite3.connect("bookstore.sqlite") cursor = connection.cursor() cursor.execute("drop table customer_tbl") connection.commit() cursor.execute("""CREATE TABLE customer_tbl ( id TEXT NOT NULL, name TEXT NOT NULL, ...
48993704552f607038fc95df6254d31905752aed
umwizaJ/GuessAnumber
/random ex1.py
447
4.0625
4
import random RandomNum=random.randint(0,20) print(RandomNum) def guessedNum(): GuessNum=int(input("please guess a number between 0 and 20: ")) if GuessNum is range (0,20): print("please enter valid number") if GuessNum==RandomNum: print("your guess is right") elif GuessNum>RandomNum: ...
3bb5a216588c3251940c7633406038ffd6123249
akshaykashyap27/Python-Programming
/moduledemo.py
368
3.734375
4
def largest(a,b,c): if(a>b) and (a>c): return(a) elif(b>a) and (b>c): return(b) else: return(c) def year(age): if(age==100): return("You are 100 years old") elif(age<100): return ("You will turn 100 in " + str(2021 + (100 - age))) else: ...
44c3211bedddbac50def0080e2a7be661c15b09c
codingD-T/E_commerce
/e_commerce_part4.py
510
4.0625
4
# for # while # engineering 8 # for i in range(8): # print(i) # i =0 # while i<8: # print(i) # i +=1 n_stud = int(input("Enter number of students: ")) max_marks = -1 max_student_id = 0 for i in range(n_stud): x = int(input("Enter marks of student "+ str(i+1) +": ")) if x >= max_marks: max_...
ecb0fcd7b5843debc01afe56646dd0ad834db33b
jocassid/Miscellaneous
/sqlInjectionExample/sqlInjection.py
2,942
4.15625
4
#!/usr/bin/env python3 from sqlite3 import connect, Cursor from random import randint class UnsafeCursor: """Wrapper around sqlite cursor to make it more susceptible to a basic SQL injection attack""" def __init__(self, cursor): self.cursor = cursor def execute(self, sql, params=...
1d65524eb8333db33bb08e1c95e97a707742cf49
Alpharomeo180/Demo-
/gitpush.py
143
3.640625
4
holiday=input ("Thanksgiving weekend?") if holiday=="yes": print ("come over for the weekend") else: print ("Will catch up next week")
b9b32f3197132b22b01d1d6af0daab60bfe9df67
igorgeyn/sandbox_ig
/playing with python.py
1,533
4.0625
4
letters_list = ['a', 'b', 'c', 'd'] for letter in letters_list: print letter a = 8*7 div2_test values = [1, 58, 9928, 464637] for number in div2_test_valus: print(div2_add20(number)) test_list = list(range(15)) test_list for number in test_list # print (div2_add20(number)) print("I am...
ceae5ecd10beea291c6232abb633a84cd0592bed
SaintNerevar/Parameterized-Vertex-Coloring
/main.py
1,713
3.8125
4
from chromatic_number import chromatic_number from graph import input_graph, induced_subgraph, colorings, is_valid_coloring, remap print('Enter number of colors, q: ', end='') q = int(input()) print('Please note that q isn\'t part of the input.') print(f'\n...Commencing {q}-coloring algorithm...\n') graph = input_gra...
54120b81ec9897569bdf11ecd3fe6f9cd1dbd2af
PyRPy/Cantera_tutorials
/reactors _periodic_CSTR.py
3,389
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: ## Reactors - periodic CSTR # In[ ]: """ This example illustrates a continuously stirred tank reactor (CSTR) with steady inputs but periodic interior state. A stoichiometric hydrogen/oxygen mixture is introduced and reacts to produce water. But since water has a l...
96e7e179d2e44024235bd0db247710c877ecaa78
haritonch/march-leetcoding-challenge-2021
/23_3sum_with_multiplicity.py
446
3.671875
4
from collections import defaultdict class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: ans = 0 M = 10**9 + 7 ones = defaultdict(int) twos = defaultdict(int) for i, num in enumerate(arr): ans = (ans + twos[target - num]) % M ...
051b0018287fb9c056138dbda741368fea92893d
AndriyBandurak/Python
/Lab2.py
302
3.734375
4
print('Створення прикладних програм на мові Python, Lab2') print('Бандурак Андрій, Num2') print('Введи:') x = float(input('x = ')) y = float(input('y = ')) z = float(input('z = ')) result = ((((((z-23.1)*((pow(2,x)+2.2)))/(y-21.1))-3.2 print('Результат: ', result)
3d9afb50aa377e790a19cdabd9db440969fae7a8
jkaria/coding-practice
/python3/Chap_9_BinaryTrees/9.2-symmetric_binary_tree.py
1,627
4.25
4
#!/usr/local/bin/python3 from node import BinaryTreeNode def is_symmetric(tree): def check_symmetric(subtree_0, subtree_1): if not subtree_0 and not subtree_1: return True elif subtree_0 and subtree_1: return (subtree_0.data == subtree_1.data and check_s...
f53a2aa65c7cb44365c540b7c0003251d8e60956
jkaria/coding-practice
/python3/Chap-17_GreedyAlgosAndInvariants/17.5-find_majority_element.py
856
3.765625
4
#!/usr/local/bin/python3 def find_majority_element(data): if not data: return None candidate, count = None, 0 for val in data: if count == 0: candidate, count = val, 1 elif val == candidate: count += 1 else: # val != candidate count -= 1...
874107ac1f6343456798019cb5f95288f4efff10
jkaria/coding-practice
/python3/built_in_modules.py
607
3.921875
4
#!/usr/local/bin/python3 from functools import wraps def trace(func): @wraps(func) def wrapper(*args, **kwargs): res = func(*args, **kwargs) print("{}({}, {}) -> {}".format(func.__name__, args, kwargs, res)) return res return wrapper @trace def fibonacci(num): """Calculates fi...
3abb8bd7a09c7ea3a80f95e1cc2d207dd6fe6564
jkaria/coding-practice
/python3/Chap_14_BinarySearchTrees/14.2-find_in_bst_gt_k.py
913
3.734375
4
#!/usr/local/bin/python3 from node import BSTNode def find_first_node_gt_k_in_bst(tree, k): subtree, first_node = tree, None while subtree: if subtree.data > k: subtree, first_node = subtree.left, subtree else: subtree = subtree.right return first_node if __name_...
83866599548d770d14fb53192671bab809c165de
jkaria/coding-practice
/python3/Chap_5_Arrays/buy_sell_stock.py
1,048
3.78125
4
#!/urs/local/bin/python3 def buy_sell_twice(prices): if not prices: return 0 max_profit1 = max_profit2 = curr_profit = 0 min_price = prices[0] for i in range(1, len(prices)): # print(i, prices[i]) if prices[i] < prices[i-1]: if curr...
d283a00aab23dcc6049fc905395f7d067e418b68
jkaria/coding-practice
/python3/Chap_5_Arrays/5.3-multiply_precision_integer.py
786
3.921875
4
#!/usr/local/bin/python3 def multiply(A, B): # TODO: 1. handle negatives # 2. trim leading 0's """ Time -> O(m*n) """ res = [0] * (len(A) + len(B) + 1) for m, b_val in enumerate(reversed(B)): print(m, b_val) for i, a_val in enumerate(reversed(A)): print(i, a_v...
4624187ab7a7b27b3f93039affac46c8a5a42181
jkaria/coding-practice
/python3/Chap_5_Arrays/5.1-dutch_flag_partition.py
1,827
3.828125
4
#!/usr/local/bin/python3 RED, WHITE, BLUE = range(3) def dutch_flag_partition(pivot_idx, A): """Time complexity: O(2n) => O(n) Space complexity: O(1) Classifies in double pass """ pivot = A[pivot_idx] lt_idx = 0 for i in range(len(A)): if A[i] < pivot: A[lt_idx],...
d9cc027dee1bf550b9f27852a483aab511fcaa83
Zyzzyva0381/Physics
/physics.py
4,163
3.625
4
import pygame import sys import math from pygame.locals import * __author__ = "Zyzzyva038" class Vector(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): ...
9a3c939c18e9c648a02710031af7e5da96cc3374
krunal16-c/pythonprojects
/Days_to_years.py
440
4.3125
4
# Converting days into years using python 3 WEEK_DAYS = 7 # deining a function to find year, week, days def find(no_of_days): # assuming that year is of 365 days year = int(no_of_days/365) week = int((no_of_days%365)/WEEK_DAYS) days = (no_of_days%365)%WEEK_DAYS print("years",year, "\nWe...
55f75e8346809169c96cd1f80fe484c8356b9f61
omaraziz255/SortingAlgorithms
/main-file.py
941
3.5625
4
from Sort.sort import * from pylab import * from matplotlib import pyplot def list_generator(inputs): lists = [] for x in inputs: lists.append(generator(x)) return lists def comparison(lists, functions): times = [] for i in range(6): temp = [] for x in lists: ...
d0be1ee56eb65fa85980d26e3b249c88400d8c4a
morph8hprom/StanleyManor
/game/world.py
782
4.0625
4
#!/usr/bin/env python3 from map import * from player import * from items import * """ World class defining template for world and function used to generate world, taking map, player, and items arguments. """ class World(): """ Defines the template for the world """ def __init__(self, game_map, game_pl...
b659e5b83a6a1a7aff007318f17e5183c18874a1
carlosplanchon/outfancy
/outfancy/chart.py
19,294
3.96875
4
#!/usr/bin/env python3 from . import widgets from .window import Window from math import nan class LineChart: """Line Charts in terminal.""" def __init__(self): self.dataset_space = [] self.x_min = 0 self.x_max = 0 self.y_min = 0 self.y_max = 0 def get_list_of_el...
80611801e607d18070c39d9313bbf51586980f16
fominykhgreg/SimpleAlgorithms
/ALG9.py
1,281
4.15625
4
""" Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). """ print("Enter 'exit' for exit.") def average_func(): a = input("First - ") if a == "exit": return print("Good bye!") b = int(input("Second - ")) c = int(input("Third - ")) ...
a767178704fe17e742255d3aecdc39b30853c1a2
AdityaChirravuri/CompetitiveProgramming
/HackerRank/Project Euler/DigitFactorial.py
178
3.578125
4
fact={'0':1,'1':1,'2':2,'3':6,'4':24,'5':120,'6':720,'7':5040,'8':40320,'9':362880} n=int(input()) print(sum(i for i in range(10,n) if not sum(map(lambda x: fact[x],str(i)))%i))
91a3cb957a587fee435a303504220527b395b871
AdityaChirravuri/CompetitiveProgramming
/HackerRank/Python/Numpy/Arrays.py
125
3.828125
4
import numpy as np k = input().strip().split(' ') print(np.array(k[::-1], float)) #to reverse a list we use [::-1] function
fb57afb77e5486314a8cb3830c8a7622aa94bcdb
AdityaChirravuri/CompetitiveProgramming
/HackerRank/Python/DateandTime/TimeDelta.py
226
3.53125
4
import datetime n = int(input()) fmt = '%a %d %b %Y %H:%M:%S %z' for i in range(n): l = input() m = input() print(int(abs((datetime.datetime.strptime(l, fmt)-datetime.datetime.strptime(m, fmt)).total_seconds())))
130aee595a5c7aa78c89d5ee034129315afdbe10
mrkarppinen/the-biggest-square
/main.py
1,804
4.1875
4
import sys def find_biggest_square(towers): # sort towers based on height towers.sort(key=lambda pair: pair[1], reverse = True) # indexes list will hold tower indexes indexes = [None] * len(towers) biggestSquare = 0 # loop thorough ordered towers list for tower in towers: height ...
842727ead59c1c674c6a1e1d6b4226b9d54e8e9f
otan/COMP2041-15s2
/tut/6mon/phones.py
623
3.515625
4
#!/usr/bin/python2.7 names = {} streets = {} phones = {} towns = {} with open("people.txt", "r") as f: for line in f: (key, name, street, town) = line.strip().split(",") names[key] = name streets[key] = street towns[key] = town phones[key] = {} with open("phones.txt", "r") as f: for line in f...
88ed9aa6dcf05bb06cdb14321bf9b75fa244109f
shekharpandey89/scatter-plot-matplotlib.pyplot
/labels_title_scatter_plot.py
436
3.71875
4
# labels_title_scatter_plot.py # import the required library import matplotlib.pyplot as plt # h and w data h = [165, 173, 172, 188, 191, 189, 157, 167, 184, 189] w = [55, 60, 72, 70, 96, 84, 60, 68, 98, 95] # plot a scatter plot plt.scatter(h, w,) # set the axis lables names plt.xlabel("weight (w) in Kg") plt.ylab...
ef5cd85e749140fbb97696eac6c43bea2881e59b
AndrieiGensh/Python_SpaceInvaders
/Space_invaders.py
30,347
3.5
4
import random import pygame WHITE = (255, 255, 255) GREEN = (78, 255, 87) YELLOW = (241, 255, 0) BLUE = (80, 255, 239) PURPLE = (203, 0, 255) RED = (237, 28, 36) F_NAME = pygame.font.match_font("arial") DISPLAY_SCREEN = pygame.display.set_mode((800, 600)) def print_mes(screen, message, size, colour, x_pos, y_pos): ...
3508b5b5636704c553a4af102a053adabc5f7fb0
cbonilladev-onepage/gradeLevelApp
/readingLevel/gradeLevel.py
2,900
3.703125
4
from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup from math import log10, floor #credit to AbigailB (https://stackoverflow.com/users/1798848/abigailb) def syllables(word): count = 0 vowels = 'aeiouy' word = word.lower().strip(".:;?!") if word[0] in vowels: count...
e9e0c73b0516383e906176e546f056dba818ae01
Hoguey/CTI-110
/M6LAB_voids_Hogue.py
947
4.03125
4
# CTI 110 # M6LAB # Brandon H # 11/2 P_infant = 1 P_child = 13 P_teenager = 19 P_adult = 20 def main(): name = input('What is your name? ') greet(name) #greet('steve') #greet('bob') #greet('billy') age = int(input('What is your age? ')) print("you are a", ageCategory(age)) #ageCategor...
2ec18a16782cd78828a6ddcc8df353ace09d92c1
psrozek/python-training
/counter.py
566
3.78125
4
def wordcount(filename): counts = {'characters' : 0, 'words' : 0, 'lines' : 0} unique_words = set() for single_line in open(filename): counts['lines'] += 1 counts['characters'] += len(single_line) counts['words'] +...
cb5a46b1e6af91ed1aa1434fb884d0772eace4aa
MangoFisher/littleScripts
/python中如何使用mock.py
1,091
3.96875
4
# coding=utf-8 """ def multiply(x, y): return x * y + 3 def add_and_multiply(x, y): addition = x + y multiple = multiply(x, y) return addition, multiple """ import unittest from function import add_and_multiply import mock class MyTestCase(unittest.TestCase): """ ʹmockװ...
efd39925ce8ac3632cda410857083bd28ebef488
rob-by-w/Invent-with-Python
/Chapter_33_HackingMinigame/Hacking.py
2,400
3.703125
4
import random GARBAGE_CHARS = list('~!@#$%^&*()_+-={}[]|;:,.<>?/') PASSWORDS = ['RESOLVE', 'REFUGEE', 'PENALTY', 'CHICKEN', 'ADDRESS', 'DESPITE', 'DISPLAY', 'IMPROVE'] MEMORY_LENGTH = 16 NUM_OF_GUESS = 4 LEFT_INDENT = ' ' * 2 RIGHT_INDENT = ' ' * 6 def main(): print('Hacking Minigame') print("Fi...
36448baf2f844d8c838f73d11d69d20de0c96ce1
rob-by-w/Invent-with-Python
/Chapter_81_WaterBucketPuzzle/WaterBucketPuzzle.py
2,591
3.53125
4
import sys GOAL = 4 EMPTY = ' ' * 6 WATER = chr(9617) * 6 def display_buckets(bucket): waterDisplay = [EMPTY if bucket['8'] < i else WATER for i in range( 1, 9)] + [EMPTY if bucket['5'] < i else WATER for i in range(1, 6)] + [EMPTY if bucket['3'] < i else WATER for i in range(1, 4)] print(f'Try to g...
fd1cacf2dc8a356402c70183413a1cea203efafa
rob-by-w/Invent-with-Python
/Chapter_76_Tic-Tac-Toe/TicTacToe.py
2,010
3.859375
4
BLANK = ' ' PLAYER_X = 'X' PLAYER_O = 'O' def main(): print('Welcome to Tic-Tac-Toe!') print() gameBoard = [[BLANK for _ in range(3)] for _ in range(3)] turn = PLAYER_X print_board(gameBoard) while True: print(f"What is {turn}'s move? (1-9)") while True: playerMov...
2ae1ef6bc41d314b3f9f31d4ec17f38875804ece
rob-by-w/Invent-with-Python
/Chapter_25_FastDraw/FastDraw.py
1,097
3.9375
4
import time import random print('Fast Draw') print('''Time to test your reflexes and see if you are the fastest draw in the west! When you see "DRAW", you have 0.3 seconds to press Enter. But you lose if you press Enter before "DRAW" appears. ''') print() while True: input('Press Enter to begin...') print('\n...
7eac8aa1981fbbed6f1df80eecb3e387a092284e
rob-by-w/Invent-with-Python
/Chapter_34_HangmanAndGuillotine/Hangman.py
2,362
3.90625
4
import random BLANK = '_' CATEGORY = 'Animals' WORDS = 'ANT BABOON BADGER BAT BEAR BEAVER CAMEL CAT CLAM COBRA COUGAR COYOTE CROW DEER DOG DONKEY DUCK EAGLE FERRET FOX FROG GOAT GOOSE HAWK LION LIZARD LLAMA MOLE MONKEY MOOSE MOUSE MULE NEWT OTTER OWL PANDA PARROT PIGEON PYTHON RABBIT RAM RAT RAVEN RHINO SALMON SEAL SH...
bfc1783cbbb426d6111714535a08978c8f284977
rob-by-w/Invent-with-Python
/Chapter_3_BitmapMessage/BitmapMessage.py
949
3.5
4
def main(): print('Enter the message to display with the bitmap.') inputMessage = input_message() with open('bitmapworld.txt', 'r') as rawBitmap: bitmap = rawBitmap.readlines() print(''.join(replace_bitmap(bitmap, inputMessage))) def input_message(): while True: inputMessa...
eec9986b1a252dac05ebbf6c1395e644a626c7bb
rob-by-w/Invent-with-Python
/Chapter_53_PeriodicTableOfTheElements/PeriodicTable.py
2,304
3.5625
4
import sys import csv import re COLUMNS = ['Atomic Number', 'Symbol', 'Element', 'Origin of name', 'Group', 'Period', 'Atomic weight', 'Density', 'Melting point', 'Boiling point', 'Specific heat capacity', 'Electronegativity', "Abundance in earth's crust"] UNITS = {'Atomic weight': 'u', 'Density': ...
0ab0e8345b6cbefd85a92d7d27e30664f49eb54d
kavi234/GUVI
/Zen Class/day 9/countdigit.py
141
4.03125
4
#To count number of digits in a number n=int(input("enter number:")) count=0 while(n>0): count=count+1 n=n//10 print(count)
e1712bcc111a7d54e66eaa9b9bea7240e5fbab02
kavi234/GUVI
/Zen Class/day 6/divide.py
170
4.0625
4
val=int(input("enter a value:")) num1=int(input("divisible by 2:")) num2=int(input("divisible by 3:")) res1=(val/num1) print(res1) res2=(val/num2) print(res2)
6e27b4d7951c3754249a304e4c238b9e809ad63e
kavi234/GUVI
/day 9/printn1while.py
163
4.34375
4
#To print all natural numbers in reverse(from n to 1)-using while loop num=int(input("enter a number:")) i=0 while(num>0): print(num) num-=1
a7fa49a6de6cad5dc7653461484fc8241abb2422
kavi234/GUVI
/Zen Class/day 4/list.py
156
4
4
list1=[10,20,30,40,50] for i in list1: print(i) for i in range(0,len(list1)): print(list1[i]) for i in range(len(list1)-1,-1,-1): print(list1[i])
89f1785429f98d7e999a1d368120a53fd6405a5f
kavi234/GUVI
/Zen Class/day 1/studentmarks.py
586
3.921875
4
f=int(input("Enter no.of students: ")) for i in range(0,f): mark1=int(input()) mark2=int(input()) mark3=int(input()) mark4=int(input()) mark5=int(input()) tot=mark1+mark2+mark3+mark4+mark5 avg=float(tot/5) percentage=float((avg/100)*100) print(tot) print(avg) prin...
44e431c0652e0b8076ee19cc40a5fb513ac78efd
agordon/agordon.github.io-DISABLED
/files/py-subprocess/popen-shell.py
1,431
3.59375
4
#!/usr/bin/env python """ Python-Subprocess tutorial Copyright (C) 2016 Assaf Gordon <assafgordon@gmail.com> License: MIT See: http://crashcourse.housegordon.org/python-subprocess.html Example of subprocess.Popen (with shell=True). """ from subprocess import Popen,PIPE from random import choice import sys try: ...
012693b04c3c5902dd2d47bad8439eab40c2c6bc
twnaing/plasma5-wallpapers-dynamic-animecity
/convert-time.py
389
3.5
4
#!/usr/bin/env python3 import argparse from dateutil import parser as datetime_parser argument_parser = argparse.ArgumentParser() argument_parser.add_argument('input') arguments = argument_parser.parse_args() datetime = datetime_parser.parse(arguments.input) midnight = datetime.replace(hour=0, minute=0, second=0, ...
e03aee4abc1aa968a9467e7e0ae44d0ce58ffbdb
SkyFawkes/Framework
/BotSoftware/main/Bluetooth.py
2,421
3.640625
4
""" To set up a Bluetooth controller on a Raspberry Pi: sudo apt-get update sudo apt-get -y install python3-pip sudo pip3 install evdev sudo bluetoothctl scan on - turn controller on, set it to be discoverable - Wait for controller to appear with its address - for example E4:17:D8:CB:08:68 or 00:FF:01:00:1F:02 pair...
ebc5862604b82b26650ce4e506a31f4e17fbf902
RHIT-CSSE/catapult
/Code/DogBark/pygame_live_coding_solution.py
3,780
4.03125
4
# Created by Derek Grayless, 06/14/2019 # 2019 Operation Catapult Session 1 Introduction to PyGame Live Coding import pygame import math pygame.init() # TODO: 1. Create a PyGame window and give it a name frame_width = 750 frame_height = 750 frame = pygame.display.set_mode((frame_width, frame_height)) pygame.displ...
4239700e5be91ec7126fecc11dbc4ab405f22a3e
RHIT-CSSE/catapult
/Code/Raindrops/StevesObjectExamples/EmployeeClass.py
1,055
4.375
4
# First we define the class: class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary) # End of c...
71fbf6e09e5ab1c7876e47c60e9d6aaba74f5c6b
RHIT-CSSE/catapult
/Solutions/04-BouncingBall/BouncingBall.py
2,028
3.703125
4
import pygame import sys import random class Ball: def __init__(self, screen, x, y, color, radius): self.screen = screen self.color = color self.x = x self.y = y self.radius = radius self.speed_x = random.randint(-5, 5) # Note, it might pick 0, oh well self....
69e2a5128e5c34f2968e5bde4ea733630ef74134
RHIT-CSSE/catapult
/Code/DogBark/Session3FirstProgram.py
2,700
4.75
5
# This is an example of a whole program, for you to modify. # It shows "for loops", "while loops" and "if statements". # And it gives you an idea of how function calls would be used # to make an entire program do something you want. # Python reads the program from top to bottom: # First there are two functions. These...
976d521a3be1c874e95a031632e8ba926ad1a8a9
RHIT-CSSE/catapult
/Pygame Demos/pygameLearningTemplates/Level-5/GraphicsUtil.py
2,602
3.65625
4
import pygame WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) ORANGE = (255, 153, 0) BLUE = (0, 0, 255) PURPLE = (255, 51, 153) # ------------------------------ heroSprite = pygame.Surface((100, 70)) pygame.draw.rect(heroSprite, RED, (0, 0, 100, 60)) pygame.draw.circle(heroSprite, WHITE, (15, ...
ecc21ab9a440263702d65022612ee3b2ea63442a
briannawang/mathQuestionGenerator
/mathQuestionGenerator.py
2,762
3.765625
4
import random nums = [] nums = [None] * 2 wantInstruc = "" opNum = 0 opSym = "" score = 0 numQs = None rangeInts = None def calcAns(): if opNum == 1: print(str(nums[0]) + " + " + str(nums[1]), end="") return nums[0] + nums[1] elif opNum == 2: print(str(nums[0]) + " - " + str(nums[1]),...
8da6f0c71320fdc9e83774de78f7ea96c9afba4b
xjeebo/Project-Euler
/p7.py
926
3.828125
4
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the # 6th prime is 13 # What is the 10001st prime number? num = 1 flag = False cnt = 0 # the number of prime numbers found # 2 is the 1st prime number so the cnt < 10000 is finding the 10001th including the 2 while cnt < 10000: i ...
4911d6b1f1f7226feb3f482b754ff52b6a78e7d6
Saurabh910/snake-game
/snake.py
1,489
3.859375
4
from turtle import Turtle POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE = 20 UP = 90 DOWN = 270 RIGHT = 0 LEFT = 180 class Snake: # Create Starting Snake def __init__(self): self.segments = [] self.create_snake() self.head = self.segments[0] def create_snake(self): for p ...
69beb8bab0fe28d2e94cc6f12b60ecf73dba3852
dmaydan/AlgorithmsTextbook-Exercises
/Chapter4/exercise2.py
210
4.28125
4
# WRITE A RECURSIVE FUNCTION TO REVERSE A LIST def reverse(listToReverse): if len(listToReverse) == 1: return listToReverse else: return reverse(listToReverse[1:]) + listToReverse[0:1] print(reverse([1]))
fed6a07b09277d09461564d87d424828ab1e3001
dmaydan/AlgorithmsTextbook-Exercises
/Chapter3/exercise11.py
975
3.578125
4
# WRITE A PROGRAM THAT CAN CHECK AN HTML DOCUMENT FOR PROPER OPENING AND CLOSING TAGS from pythonds.basic.stack import Stack def are_tags_balanced(html): tagStack = Stack() for i in range(len(html)): character = html[i] if character == "<": already = False if not tagStack.isEmpty(): if tagStack.peek() =...
ac9f632f280832b6d736cc738efca9071dcad5bf
dmaydan/AlgorithmsTextbook-Exercises
/Chapter2/exercise4.py
323
3.71875
4
# GIVEN A LIST OF NUMBERS IN RANDOM ORDER, WRITE AN ALGORITHM THAT WORKS IN O(nlog(n)) TO FIND THE KTH SMALLEST NUMBER IN THE LIST inputList = [10, 6, 31, 78, 34, 18, 104, 23] def find_kth_smallest(list, k): list.sort() if ((k) > len(list)): return False else: return list[k-1] print(find_kth_smallest(inputList, ...
0cc02c8d3f8a59c29a8ef55ab9fee88a2f768399
Suiname/LearnPython
/dictionary.py
861
4.125
4
phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 phonebook["Jill"] = 947662781 print phonebook phonebook2 = { "John" : 938477566, "Jack" : 938377264, "Jill" : 947662781 } print phonebook2 print phonebook == phonebook2 for name, number in phonebook.iteritems(): print "Phone...
ecaf5be739790fe10a10371c9a381a657b8b3292
alexsunseg/CYPAlejandroDG
/funciones.py
1,491
4
4
def sumar (x,y): z=x+y return z def restar (x,y): return x-y def mi_print( texto): print(f"Este es mi print: {texto}") def multiplica (valor,veces): if veces==None: print("Debes enviar el segundo argumento de la función") else: print(valor*veces) def comanda(mesa,comensal,entrad...
5f0c396a0bde94b97a4cb8c9a30b39206407623d
alexsunseg/CYPAlejandroDG
/libro/problemas_resueltos/capitulo1/problema1_7.py
254
3.90625
4
L1=float(input("Ingrese el lado 1 del triangulo:")) L2=float(input("Ingrese el lado 2 del triangulo:")) L3=float(input("Ingrese el lado 3 del triangulo:")) S=(L1+L2+L3)/2 AREA=(S*(S-L1)*(S-L2)*(S-L3))**0.5 print("El area del triangulo es igual a:",AREA)
b5985a12fd88d0e2cef30594a8ea0ab3a8292878
alexsunseg/CYPAlejandroDG
/libro/problemas_resueltos/capitulo2/problema2_3.py
298
3.78125
4
A=float(input("Ingrese el coeficiente A:")) B=float(input("Ingrese el coeficiente B:")) C=float(input("Ingrese el valor de C:")) DIS=float((B**2)-4*A*C) if DIS >=0: X1=((-B)+DIS**0.5)/(2*A) X2=((-B)-DIS**0.5)/(2*A) print(f"Las raíces reales son {X1} y {X2}") print("Fin del programa")
daafa74d7a2cd3fbae350c62280cbfd1d00b053a
alexsunseg/CYPAlejandroDG
/libro/problemas_resueltos/capitulo3/Problema3_9.py
111
3.75
4
SERIE=0 N=int(input("Ingrese un número: ")) I=1 for v in range (0,N,I): SERIE+=I**I I+=1 print(SERIE)
4c367d471ff8b7aec104dfc54d5851ebeaae38fc
alexsunseg/CYPAlejandroDG
/libro/problemas_resueltos/capitulo2/problema2_6.py
189
4.03125
4
A=float(input("Ingrese un número:")) if A = 0: print("El numero es nulo") elif -1**A>0: print("El número es par") else: print("El número es impar") print("Fin del programa")
87a20f38284830dbe1d2345b7477424e19fa9609
alexsunseg/CYPAlejandroDG
/libro/Ejemplo2_7.py
270
3.8125
4
NUM = int(input("Ingresa un numero entero positivo:")) V= int(input("Ingresa otro nùmero entero positivo:")) VAL=0 if NUM==1: VAL=100*V elif NUM==2: VAL=100**V elif NUM==3: VAL=100/V else: VAL=0 print(f"El resultado es {VAL}") print("Fin del programa")
c85abcd28ef34ba657f74bece7bd4d2d9971698a
alexsunseg/CYPAlejandroDG
/libro/problemas_resueltos/capitulo3/Problema3_4.py
325
3.78125
4
NOM=0 SUE=float(input("Ingrese el sueldo del trabajador: ")) while (SUE!=-1): if SUE<1000: NSUE=SUE*1.15 else: NSUE=SUE*1.12 NOM+=NSUE print("$ ",NSUE) SUE=float(input("Ingrese el sueldo del trabajador (De no haber más sueldos ingrese -1): ")) print("El total de la nomina es de: $",N...
79f44b9cba827f6f98002e61d3ace969fa990e7b
maoyehui/Reptile
/test/downloadUrl.py
769
3.78125
4
import urllib.request # 下载网页,并设置重试次数 def download(url, num_retries=2): print('Downloading:', url) try: html = urllib.request.urlopen(url).read() except urllib.request.URLError as e: print('Download error:', e.reason) html = None i = 1 if num_retries > 0: ...
43baeba1fe91ef2618338da54b2822513109bbea
Vijaynw/VLiNK
/Question 3.py
532
3.765625
4
def findheight(s): height = 0 prev_height = 0 cnt = 0 for i in range(len(s)): if (s[i] == 'U'): height += 1 elif s[i] == 'D': height -= 1 if height == 0 and prev_height < 0: cnt += 1 prev_height = height return cnt n = input() s ...
360eac8cde1e02549e44de4668c4fce4cc6ee39c
Kensuke-Mitsuzawa/persian_preprocessing
/preproc_of_bijankhan_posdataset/dummy.py
1,310
3.5
4
#! /usr/bin/python # -*- coding:utf-8 -*- __author__='Kensuke Mitsuzawa' __version__='2013/7/6' import sys, codecs, re; def insert_dummy(line): """ This function inserts dummy tag prefix and suffix position of word column. This process is done because of the work of preper2.rb. The preper2.rb needs whi...
efca40e84ea9322135b4baead2b177c21901339e
Kensuke-Mitsuzawa/persian_preprocessing
/etc./stemmer_spell.py
16,266
3.59375
4
def stemmer(word,flex,pos): root='' #be nim fasele tavajoh konid #noun asli=word shakhsi1=['م','ت','ش'] shakhsi3=['مان','تان','شان'] shakhsi2=['ام','ات','اش'] shakhsi4=['يمان','يتان','يشان'] rabti1=['م','ي','د'] rabti2=['يم','يد','ند'] flag=0 if word[-2:] in rabti2: ...
ff9cd2e552231e617bfe95b2cada268a780aeabe
Michelleweb/LaMiscelaneadeCodigo-1
/PYTHON/tarea 1.py
116
3.796875
4
def function (numero): print numero if numero==0: return 1 else: return numero+1 factorial(10)
c9555f136e1d6a9799f09c0df9356747d9395cfd
five-hundred-eleven/DataStructures
/test_LinkedList.py
3,093
3.578125
4
import unittest from DataStructures import LinkedList class TestLinkedList(unittest.TestCase): def test_empty(self): ll = LinkedList() self.assertEqual(len(ll), 0) def test_len_3(self): ll = LinkedList(range(3)) self.assertEqual(len(ll), 3) def test_getitem(self): ...
455a2570e49116de0d29741d2296037cb53f89c0
ShaishavMaisuria/PythonConcepts
/OOPs/basics.py
2,503
3.890625
4
import pygame import random #this code used for reference purpose only and that I have learned all this concepts WIDTH = 800 HEIGHT = 600 WHITE = (255, 255, 255) BLUE = (0, 0, 255) RED = (255, 0, 0) STARTING_BLUE_BLOBS = 10 # creating the number of blue blobs STARTING_RED_BLOBS = 3# creating the number of red blobs #Th...
3e3a1af24d9e3510c0bf0e5ee9d24e8475a88b07
MaganaOscar/Hack_a_thon_Ninjas_VS_Pirates
/classes/ninja.py
1,094
3.59375
4
from random import seed from random import choice from random import randint class Ninja: grunts = ["Cowabunga!", "Hyaaaghhh!", "Wraahhh!"] seed(1) def __init__( self , name ): self.name = name self.strength = 10 self.speed = 5 self.health = 100 def show_stats( sel...
6354a49c85d6ef9d6cbdd3926671c085851b0b3a
N4A/papers
/books/scipy-lectures-scipy-lectures.github.com-465c16a/_downloads/stride-diagonals-answer.py
1,291
3.796875
4
""" Solution to the stride diagonal exercise ========================================= Solution showing how to use as_strided to stride in diagonal. """ import numpy as np from numpy.lib.stride_tricks import as_strided # # Part 1 # x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=n...
8df431d3b0baca9aced66bb90ef82ed902891b36
N4A/papers
/books/scipy-lectures-scipy-lectures.github.com-465c16a/_downloads/plot_boxplot.py
882
3.78125
4
""" Boxplot with matplotlib ======================= An example of doing box plots with matplotlib """ import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 5), dpi=72) fig.patch.set_alpha(0.0) axes = plt.subplot(111) n = 5 Z = np.zeros((n, 4)) X = ...