blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8c7c80f28aef485def3bfc7d055a896e8186e356 | nguyentienlong1106/tranning_git | /yearmonthday.py | 289 | 4.125 | 4 | day=int(input())
month=int(input())
year=int(input())
print("the next day is: ")
if month==1:
if day<31:
print(day+1 , '/' , month , '/' ,year)
else:
if month==12:
print(1, '/', 1, '/', year+1)
else:
print(1, '/', month+1, '/', year) |
a5bb85bc5e18b305041a87786c03ff0e9440e5ed | Borys-S/Python | /BT_homework/hw_21_without_task_3_5.py | 1,967 | 4.25 | 4 | """
Task 1
from typing import Optional
def to_power(x: Optional[int, float], exp: int) -> Optional[int, float]:
Returns x ^ exp
>>> to_power(2, 3) == 8
True
>>> to_power(3.5, 2) == 12.25
True
>>> to_power(2, -1)
ValueError: This function works only with exp > 0.
"""
# def to_power(x... |
23802bcf5149645c71511a074dc9841e9bcef37b | everydaytimmy/seattle-python-401d16 | /class-18/demo/crypto/number_cipher.py | 871 | 3.84375 | 4 | def encrypt(plain, key):
encrypted = ""
for char in plain:
num = (int(char) + key) % 10
encrypted += str(num)
return encrypted
def decrypt(plain, key):
return encrypt(plain, -key)
if __name__ == "__main__":
encrypted = encrypt("1234", 1)
assert encrypted == "2345"
ass... |
342cbeb593468470586cc862f39e833bf2bfbef6 | chanyeoh/datastructure | /python/stack.py | 673 | 3.796875 | 4 | #!/usr/bin/python
import sys
class StackNode:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
class Stack:
def __init__(self, data):
self.stack = StackNode(data)
def Push(self, data):
if self.stack == None:
self.stack = StackNode(da... |
db9a633679718f872cd3d0644cb32e07ae50755f | JeremyBrightbill/Project_Euler | /15.py | 480 | 3.65625 | 4 | """Lattice paths
Starting in the top left corner of a 2×2 grid, and only being able to move
to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
Algorithm: It's the number of permutations of SIDE + SIDE, divided by
(2 * permutations of S... |
7ec29897d6ba95f86528889a3f3d8d9933e4360e | DinhPQ/1.-Learning-python | /Basic_Visual_studio/6. String input.py | 1,047 | 4.4375 | 4 | user_input = input("Type in your name: ")
message = "Hello %s! Welcome to python" %user_input
print(message)
#To print the multiple input
name = input("Type in your name: ")
surname = input("Type in your surname: ")
message_string = "Hello %s %s!" % (name, surname)
print(message_string)
def foo(name):
return "Hi ... |
7f407f95f989379f488edc1b4554448903270902 | DinhPQ/1.-Learning-python | /Basic_Visual_studio/10. Infinite_number_non_key_word_argument.py | 407 | 3.9375 | 4 | #An *args parameter allows the function to be called with an arbitrary number of non-keyword argument
#The term *args define the indifinite number of numbers as argument
def defi(*args):
return sum(args) / len(args)
#Return the indefinite number that contain string value by return it in uppper case and sorted in... |
8b29d55c9d7effa0b881787e635f1be38b4568dd | vikpandher/cse415 | /Project/BombermanSource.py | 20,325 | 3.59375 | 4 | '''
Vikramjit Pandher, Chloe Nash, CSE 415, Spring 2016, University of Washington
Instructor: S. Tanimoto.
Project: Bomberman
Status of the implementation:
Working computer player with min max statespace search and alpha beta cutoffs
Working computer vs computer matches and human vs computer matches with optional
cus... |
97216feac533d47f23f4deee762f231784bc75f6 | jaeheeLee17/DS_and_Algorithms_summary | /Matrix_ADT/matrix_structure.py | 3,277 | 3.546875 | 4 | import sys
sys.path.append("H:\DS_and_Algorithms_summary\Array_ADT")
# Implementation of the Matrix ADT using a 2-D array.
from array_structure import Array2D
class Matrix:
# Creates a matrix of size numRows x numCols initialized to 0.
def __init__(self, numRows, numCols):
self._theGrid = Array2D(numR... |
38244fc022e6d90eacee5b205cd81eed1cca6ea7 | jaeheeLee17/DS_and_Algorithms_summary | /Array_ADT/letter_counter.py | 912 | 3.984375 | 4 | # Count the number of occurrences of each letter in a text file.
from array_structure import Array, _ArrayIterator
def main():
# Create an array for the counters and initialize each element to 0.
theCounters = Array(127)
theCounters.clear(0)
# Open the text file for reading and extract each line from ... |
b6515588ac50db48eb6902b29f595de484cb2cfe | matthieuchoplin/jwg-python | /exercises/count_letter_url.py | 626 | 3.796875 | 4 | from pprint import pprint
from string import ascii_lowercase
import urllib.request
def count_each_letter(file):
dict_of_letter = {}
for line in file:
for letter in line.lower():
if letter in ascii_lowercase:
if letter in dict_of_letter:
dict_of_letter[let... |
bdcdc945c5fa2a723596df56f011b1a074344fe1 | Nguyen-Trung-Kien/RSA | /rsa.py | 2,725 | 3.71875 | 4 | import math
import random
import numpy as np
import tkinter as tk
from tkinter import messagebox
#print(math.gcd(20,8))
def is_prime(number):
count = 0
if number == 2:
return True
if number < 2:
return False
if number % 2 == 0:
return False
for i in range(1,number+1):
if number % i == 0:
count +=1
if ... |
de5d977ec464e79adc8ad809c6ce1965c2f252a1 | kateriska/7.-semestr-FIT | /BIF/proj/bifProject.py | 15,336 | 3.640625 | 4 | from Bio import Phylo
from Bio import SeqIO
import csv
'''
function for converting list into string
Source:
***************************************************************************************
* Title: Python program to convert a list to string
* Author: author of geeksforgeeks with nickname "Shivam_k" ->... |
fcccf0005a388eea2c33a55460b49bcec790fe05 | uestcwm/search | /Sort/countsort.py | 801 | 3.5 | 4 | #! /usr/bin/env python
#coding=utf-8
'''
桶排序
复杂度O(n)
'''
def countsort( A, d ): #A待排数组, d位数 如果位置需要先修改一下知道A中最多位数
for k in range(d): #k轮排序
s[ [] for i in range(10) ] #数字0~9,建10个桶
'''对于数组中的元素,首先按照最低有效数字进行
排序,然后由低位向高位进行'''
for i in A:
s[ i//(10**k)%10 ].append(i)
... |
307dbc7bc61631be3bebde97117fc3e902c17a45 | NIDHISH99444/CodingNinjas | /CN_StringAlgorithms/BasicPatternMAtching.py | 338 | 3.5625 | 4 | def patternMatch(s,p):
n=len(s)
m=len(p)
for i in range(n-m+1):
isFound=True
for j in range(m):
if s[i+j]!=p[j]:
isFound=False
break
if isFound==True:
return True
return False
#time complexity -->O(n*m)
print(patternMatc... |
843960192de19e22b84204afec1c6ceca7cb5611 | NIDHISH99444/CodingNinjas | /matrix/longestincreasingPathInMatrix.py | 913 | 3.546875 | 4 | import sys
class Solution(object):
def __init__(self):
self.max_len =0
self.table ={}
def longestIncreasingPath(self, matrix):
def dfs(x ,y ,prev):
if x < 0 or x>= len(matrix) or y < 0 or y >= len(matrix[0]) or matrix[x][y] <= prev:
return 0
if (... |
42b5671f8862cf14ca9ee1e27c13dc1766659294 | NIDHISH99444/CodingNinjas | /FlipkartPrep/MaximumPathSumLinkedList.py | 2,806 | 4.25 | 4 | # Python program to construct a Maximum Sum Linked List out of
# two Sorted Linked Lists having some Common nodes
class LinkedList(object):
def __init__(self):
# head of list
self.head = None
# Linked list Node
class Node(object):
def __init__(self, d):
self.data = d
self.next = None
# Method to adjust... |
922aab997f1a7860467be822a30156b05a094126 | NIDHISH99444/CodingNinjas | /CN_DynamicProgramming1/minCostMatrrix.py | 523 | 3.515625 | 4 | def minCost(matrix,m,n):
dp=[[0 for i in range(n)] for j in range(m)]
dp[m-1][n-1]=matrix[m-1][n-1]
for i in range(m-2,-1,-1):
dp[i][n-1]=matrix[i][n-1]+dp[i+1][n-1]
for j in range(n-2,-1,-1):
dp[m-1][j]=matrix[m-1][j]+dp[m-1][j+1]
for i in range(m-2,-1,-1):
for j in range(n-... |
4a354e53f4dfa3bffbc8e7ae5f840dad863fcbef | NIDHISH99444/CodingNinjas | /tree/BinarySearchTree.py | 934 | 3.5625 | 4 |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def lca(root, n1, n2):
if root is None:
return None
if (root.data > n1 and root.data > n2):
return lca(root.left, n1, n2)
if (root.data < n1 and root.data < n2):
... |
11739f80192df67d02b2c23403878ecfe91a3d64 | NIDHISH99444/CodingNinjas | /CN_Graph/LargestPiece.py | 660 | 3.59375 | 4 | def largestPiece(matrix,i,j):
if i<0 or i>=len(matrix) or j<0 or j>=len(matrix[0]) or matrix[i][j]=='0':
return
if matrix[i][j] == '1':
matrix[i][j] = '0'
cnt[0] += 1
largestPiece(matrix,i,j-1)
largestPiece(matrix,i-1,j)
largestPiece(matrix,i,j+1)
largestPiece(matrix,i+... |
9aab68a109558aa1a54db5cf7a2a0cfe0dbbc55d | NIDHISH99444/CodingNinjas | /CN_Assignments/PowerOfNumber.py | 115 | 3.640625 | 4 | def powerOfNumner(x,n):
if n==0:
return 1
return x*powerOfNumner(x,n-1)
print(powerOfNumner(3,0))
|
50533371a560a49e7fa5956de1bc655329361c63 | NIDHISH99444/CodingNinjas | /recursionBacktracking/minStepsTo1.py | 534 | 3.84375 | 4 |
def getMinSteps(n, memo):
if (n == 1):
return 0
if (memo[n] != -1):
return memo[n]
res = getMinSteps(n-1, memo)
if (n%2 == 0):
res = min(res, getMinSteps(n//2, memo))
if (n%3 == 0):
res = min(res, getMinSteps(n//3, memo))
# store memo[n] and return
memo[n] = 1 + res
return memo[n]
# This function ... |
0d5dbc040aecffa789a2496194e564cab46d9b09 | NIDHISH99444/CodingNinjas | /CN_BasicRecursion/checkNumber.py | 600 | 4 | 4 | # Given an array of length N and an integer x, you need to find if x is present in the array or not. Return true or false.
# Do this recursively.
# Input Format :
# Line 1 : An Integer N i.e. size of array
# Line 2 : N integers which are elements of the array, separated by spaces
# Line 3 : Integer x
# Output Format :
... |
ac9e2f81b54c661c029ab5353698ed4ae5e07fa7 | NIDHISH99444/CodingNinjas | /CN_DynamicProgramming1/sumOFsubString.py | 276 | 3.6875 | 4 | def subStringSum(arr):
total=arr[0]
last=arr[0]
for i in range(1,len(arr)):
last=last*10+arr[i]*(i+1)
total+=last
return total
#formula = (last)*10+(value at i)*(index+1)
string="123"
arr=[int(ele) for ele in string]
print(subStringSum(arr)) |
3b176b887a1621948e05617a99d1ff1e72ccf440 | NIDHISH99444/CodingNinjas | /recursionBacktracking/generateParanthesis.py | 305 | 3.796875 | 4 | def generateParanthesis(n):
generate(n,str="",open=0,close=0)
def generate(n,str="",open=0,close=0):
if len(str)==2*n:
print(str)
if open <n:
generate(n, str+"(", open+1, close)
if close<open:
generate(n, str + ")", open, close+1)
print(generateParanthesis(3))
|
427bb07c81d9166a7aef913085608b5d9abfebbd | NIDHISH99444/CodingNinjas | /CN_Backtracking/ratMaze.py | 916 | 3.5625 | 4 | # def printFinal(matrix):
# for i in range(len(matrix)):
# for j in range(len(matrix[0])):
# print(matrix[i][j],end=" ")
# print()
def ratMazeUtil(matrix,solution,x,y,n):
if x==n-1 and y==n-1:
solution[x][y]=1
print(solution)
solution[x][y]=0
return
i... |
16c864ef08f84ec154347225b541d506f6b68e51 | NIDHISH99444/CodingNinjas | /recursionBacktracking/getFloor.py | 436 | 3.625 | 4 | def getFloor(arr,low,high,x):
if x<arr[low]:
return -1
if x>=arr[high]:
return arr[high]
mid=(low+high)//2
if mid==low:
return arr[mid]
if arr[mid]==x:
return arr[mid]
elif arr[mid]<x:
return getFloor(arr,mid,high,x)
else:
return getFloor(arr,l... |
dd25bf47f7607007c5c0a50766f1d514a83c9869 | ashlynkaran/VSA-SAVY-projects | /proj04_lists/proj04.py | 895 | 4.40625 | 4 | # coding=utf-8
# Name:
# Date:
"""
proj04
practice with lists
"""
#Part I
#Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements of the list that are less than 5.
#Part II
# Take two lists, say for example these two:
b = [1, 1,... |
3748db936726064aebe4bfb2453ca22f9b36f1e9 | AlexDellinger/python-1 | /oldtimer | 347 | 3.5 | 4 | #!/usr/bin/env python3
import time
import colors as c
seconds = 1
def show():
print(c.clear)
print(c.yellow + '[Press ctrl c to stop!]' + c.reset, end=': ', flush=True)
print(c.cyan + seconds)
#---------------------------------------------------------------------
show()
while True:
time.sleep(1)
... |
7bee4dd5e89334120a5b71ac5ec30e856124c2d5 | eannis1/toy-projectEA | /first_file.py | 235 | 3.5 | 4 | print('Hello, world! This is my first git file.')
list1 = ['dog', 'cat', 'horse', 'parakeet', 'chinchilla']
for k in list1:
print(list1[k])
print(list1[2])
list2 = [1, 2, 3, 4, 5]
for n in list2:
print(list2[n])
print(list2[3])
|
0e802994e886507f50ceaf4a62f7436ec8190ad6 | lelong03/leetcode_30_days | /move_zeroes.py | 951 | 4.125 | 4 | # Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
#
# Example:
#
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
#
# Input: [5,1,0,3,12,0,8]
# Output: [5,1,3,12,8,0,0]
#
# Note:
#
# You must do this in-place without making a copy of the ... |
cfcb4fee0d4329976790a32c9ca301dc05551d6a | bluegraybox/examples | /bowling/python/Frame.py | 1,225 | 3.5625 | 4 | class Frame(object):
def __init__(self):
self.balls = []
self.extraBalls = []
def is_strike(self):
return len(self.balls) == 1 and sum(self.balls) == 10
def is_spare(self):
return len(self.balls) == 2 and sum(self.balls) == 10
def add_ball(self, pins):
if self.... |
d95eeb5b600276f73b47f6bcb9ece675f623ade0 | alcibiadesBustillo/djangoRest_WebScrapping | /web_scrapper/main.py | 1,665 | 3.78125 | 4 | """Web scrapper
This script allows the user scraping and print to the console all
the links of a website. It is assumed that the possible website are in
the config.yaml file.
This tool accepts comma separated value websites.
This script requires that `beautifoulsoup4, yaml` be installed within the Python
environme... |
eb585083e9ab45cac9d5598f5ab991b5345ba4ad | minikuma/DeepLearning | /NeuralFunction/Network.py | 1,948 | 3.65625 | 4 | ################################################################
# Perceptron - 인공신경망모델링 3층 신경망 (신호의 전달)
# 3층 신경망 구현
# A = XW + B -> 벡터의 내적
# A = (a1, a2, a3), X = (x1, x2), B = (b1, b2, b3)
# W = [ w11, w21, w31]
# w12, w22, w32
############... |
020fb5626f44f28d2109f1aa8b89973953ce2308 | Loxfran/PythonProgrammingPractice-PPP.- | /01-python/06-装饰器-2.py | 429 | 3.6875 | 4 | #语法糖
def w1(func):
def inner():
print("-----正在进行验证-----")
key = input("请输入验证密码:")
if key == "123123":
func()
else :
print("没有权限")
return inner
@w1
def f1():
print("-----f1-----")
@w1
def f2():
print("-----f2-----")
@w1
def f3():
print("-----f3--... |
4c2513064dde9ac222da20e52f225777311a9d03 | Loxfran/PythonProgrammingPractice-PPP.- | /01-python/02-property-2.py | 312 | 3.671875 | 4 | class Test(object):
def __init__(self):
self.__num = 100
@property
def num(self):
print("-----get_num-----")
return self.__num
@num.setter
def num(self,new_num):
print("-----set_num-----")
self.__num = new_num
t=Test()
t.num=200
print(t.num)
|
6f637884c0f856e54ab478b5b0afc6548730fd5f | Loxfran/PythonProgrammingPractice-PPP.- | /03-python/06-使用互斥锁.py | 545 | 3.71875 | 4 | #使用互斥锁
from threading import Thread,Lock
import time
num = 0
def test1():
global num
metux.acquire()
for i in range(1000000):
num += 1
print("------test1--%d---"%num)
metux.release()
def test2():
global num
metux.acquire()
for i in range(1000000):
num += 1
print("... |
d37d77a438ac8b21fb49143bb37dd5e023cdbd1d | Loxfran/PythonProgrammingPractice-PPP.- | /03-python/Test/mkfl.py | 362 | 3.5 | 4 | import os
file_name_list=[]
for i in range(200):
file_name = "test"+str(i)+".txt"
file_name_list.append(file_name)
#print(file_name_list )
for i in file_name_list:
new_file = open(i,"w")
new_file.write("""-----------------------
此文件为了验证多文件copy程序而创立
文件名为:%s"""%i)... |
ce034eb903f45aed6b47fe6b9a9603e223080b04 | Loxfran/PythonProgrammingPractice-PPP.- | /01-python/04-闭包-2.py | 142 | 3.765625 | 4 | def func(a,b):
def num(x):
return x*a+b
return num
test_a = func(3,2)
for i in range(10):
a = test_a(i)
print(i,a)
|
75cd4250904ebd376f95d1624af83c78b2b047df | ralcant/jibo_tts_names_fix | /filenames_handler.py | 1,267 | 3.625 | 4 | import os
import glob
def format_name(audio_file):
"""
Assumes
file extension = .mp3
"""
all_lower_but_type = audio_file[:-3].lower()
first_upper = all_lower_but_type[0].upper()
return "{}{}{}".format(first_upper, all_lower_but_type[1:-1], ".mp3")
def change_format_audios():
root = "students_correct"
for readi... |
a07043a7e717e85a3f52f915a595e8fb2f268af7 | daryllft19/schelling | /exam.py | 4,448 | 3.59375 | 4 | #! /usr/bin/python
from __future__ import division
import numpy
import random
'''
Grid object
'''
class Grid(object):
'''
Initialization
'''
def __init__(self, array):
self.array = array
self.x = (array == 'X').sum()
self.o = (array == 'O').sum()
self.vacant = (array == ' ').sum()
self.length, self.w... |
0de0d10faf9c39b79ac605ec75213a8bbaeee5fa | nick-kopy/Challenges | /toeplitz.py | 820 | 4.15625 | 4 | # checks if a matrix is a toeplitz matrix
# should have numbers repeating diagonally down-right
import numpy as np
def isToeplitz(arr):
"""
@param arr: int[][]
@return: bool
"""
# in case input is a list
arr = np.array(arr)
# will iterate over rows to check toeplitzness
rows, cols = a... |
71c3bc74fa2a2eaf32885bcf8896d88a7d858d16 | rituc/Programming | /geesks4geeks/array/missing_num.py | 445 | 3.984375 | 4 | # http://www.geeksforgeeks.org/find-the-missing-number/
def main():
print "Enter number of test cases"
T = int(input())
for t in range(T):
print "Enter number"
n = int(input())
a = []
for i in range(n-1):
a.append(int(input()))
print find_missing_num(a, n)
def find_missing_num(a, n):
true_sum = n*(... |
f0de8bfc7af2d3db84cb01e5ce6a0f55d93929ef | rituc/Programming | /geesks4geeks/array/search_num.py | 567 | 4.09375 | 4 | # http://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/
def main():
print "Enter number of test cases:"
T = int(input())
print "Enter array size"
for t in range(T):
n = int(input())
a = []
for i in range(n):
a.append(int(input()))
print a
print find_pivot(a, n)
def find_pivot(a... |
067277c0843f13b87974283e6d1ea9948241b370 | rituc/Programming | /geesks4geeks/array/alternating_sequence.py | 379 | 3.78125 | 4 | def main():
print "Enter number of test cases"
T = int(input())
for t in range(T):
print "Enter array size"
n = int(input())
a = []
for i in range(n):
a.append(int(input()))
print alternating_sequence(a, n)
def alternating_sequence(a, n):
a.sort()
j = n-1
for i in range(n/2):
temp = a[i]
a[i] = ... |
b86aa48079b59ec942c25fc544f93408dbc7e48a | rituc/Programming | /geesks4geeks/array/odd_occuring_num.py | 421 | 4.0625 | 4 | # http://www.geeksforgeeks.org/find-the-number-occurring-odd-number-of-times/
def main():
print "Enter number of test cases"
T = int(input())
for t in range(T):
print "Enter array size"
n = int(input())
a = []
for i in range(n):
a.append(int(input()))
print find_odd_occuring_num(a, n)
def find_odd_occu... |
2e7515446248551ba69b37b03fb910fb5fa2137f | inceptor-slack/trabalho-LdPeAlg | /exercício-1.py | 1,323 | 4.21875 | 4 | """
Proposta do exercício era gerar um conceito de nota a partir da entrada da nota
"""
entrada = int(input('Deseja inserir uma nota: 0-Não 1-Sim:'))# entrada da condição do laço
while entrada == 1:# condição do laço
# ------------| ENTRADA DE DADOS DO ALUNO |-------------
nome = input('Digite o nome do aluno:')
... |
045a177950f9b60106a024e1f87309625890b2c6 | ofk16fsm/DVG304 | /Assignment_1/Simple_assignment.py | 551 | 3.921875 | 4 | import csv
def unique_values_counter(csv_file, header_name):
read_csv = open(csv_file, 'r')
reader = csv.reader(read_csv) # Create the reader object
headers = next(reader)
index_headers = headers.index(header_name)
uniq = []
# If statement will check if headername is inside headers
if header_name in headers:
... |
de0d16cf9325655966a55ecec3e658c9e9d27a5f | ofk16fsm/DVG304 | /Assignment_1/Assignment_simple.py | 341 | 3.78125 | 4 | import csv
f = open(r'USCounties.csv','r')
reader = csv.reader(f) #creating the reader object
headers = next(reader) #getting the list of headers
print (headers)
r = list(reader)
uniq = []
for row in r:
STATE_NAME = row[1]
if STATE_NAME not in uniq:
uniq.append(STATE_NAME)
for i in uniq:
print(i)... |
f9d342b9b9d32b30957490643f3629c2809978bc | dj-on-github/RNGBook_Code | /random_walk_2d.py | 623 | 3.609375 | 4 | #!/usr/bin/env python
import random
import math
repetitions = 10000
steps = 30
finaldistance = [0 for x in range(-30,31)]
for i in xrange(repetitions):
state = [0.0,0.0]
for j in xrange(steps):
x = random.uniform(-1.0,1.0)
state[0] += x
if random.choice([True,False]):
state[... |
78fc388f33737845e582d8cdd381a1216c4bba42 | dj-on-github/RNGBook_Code | /small_modulus.py | 469 | 3.75 | 4 | #!/usr/bin/env python
import math
import random
rs = random.SystemRandom()
def rand_range(maxrand):
number_of_bits = int(math.ceil(math.log(maxrand+1,2))) + 64
x = rs.getrandbits(number_of_bits)
x = x % 12
return x
histogram = [0 for x in range(16)]
for i in xrange(1000000):
result = rand_range(... |
9d35651b396e6e1a90c456b5f18226ce9cfff3da | dj-on-github/RNGBook_Code | /debiterator.py | 260 | 3.609375 | 4 | #!/usr/bin/env python
bits = "11001100000101010110110001001100111000000000001001001101010100010001001111010110100000001101011111001100111001101101100010110010"
thing = list()
for ch in bits:
thing.append(ch)
that = ','.join(thing)
print that
|
2377cd4ffd7f15884092eca56a24f60e17810e7f | cmorga13/class-work | /week3/5.2.py | 384 | 4.25 | 4 | largest = 0
smallest = 0
while True:
test = raw_input("enter a number: ")
if test == "done" : break
try:
num = float(test)
except:
print("invalid input")
continue
if largest is 0 or num < largest:
largest = num
if smallest is 0 or num > smallest:
smallest ... |
08bad325963fc9e28034ef7fec8d61b188572467 | alvarocalle/MapReduce | /multiply.py | 1,647 | 3.890625 | 4 | '''
Problem 6: matrix multiplication
Two matrices A and B in a sparse matrix format (i,j,value)
Design a MapReduce algorithm to compute the matrix multiplication A x B
'''
import MapReduce
import sys
mr = MapReduce.MapReduce()
a_row_max = 5 # Maximum number of rows in matrix A
b_col_max = 5 # Maximum number of colum... |
6c0038a8b19317a0a766a4987aa4bd6fd6f7f648 | l593067749/learn-python | /www/number1/MethodTypeTest.py | 706 | 3.640625 | 4 | # -*- coding: UTF-8 -*-
'给实例或类绑定方法'
from types import MethodType
class MethodTypeTest(object):
__slots__ = ('setName','name','age') # 用tuple定义允许绑定的属性(方法)名称
pass
def setName(self,name):
self.name=name
methodTypeTest=MethodTypeTest()
methodTypeTest.setName=MethodType(setName,methodTypeTest,MethodTypeTest)#... |
92e04436eabd612ecbe211aeee106e7179d81350 | igoroya/pycodingkatas | /katas/april2018/selectionsort.py | 778 | 3.828125 | 4 | '''
Created on 19 Apr 2018
@author: igoroya
'''
from random import randint
def sort(values):
position = 0
size = len(values)
while position < size - 1:
minimum = values[position]
position_minumum = position
for i in range(position, size):
if values[i] < minimum:
... |
c79ec220599121711f80325e08c5747b1ede7a5c | ShriRachana/Python-practice | /General Practice/while_loop.py | 94 | 3.546875 | 4 | count = 0
while count < 5: #notice the colon!
print 'looping -', count
count += 1
|
6410cf5f577ee95d4528815bee481d3f828dd707 | ShriRachana/Python-practice | /Assignments/filter_by_type.py | 517 | 3.765625 | 4 | sI = [1,43,6,65]
type(sI)
if (type(sI) == int and sI>=100):
print "That is a big number"
elif (type(sI) == int and sI<=100):
print "Not a big number"
elif (type(sI) == str and len(sI)>50):
print "That is a big sentence"
elif (type(sI) == str and len(sI)<50):
print "That is a okay sentence"
eli... |
6d45f194f82a0715a4fd8b42ccb4ffb9c427e02f | sarahmhale/RobbyTheRobot | /lib/Timer/Timer.py | 265 | 3.625 | 4 | import time
class Timer:
startTime = 0
stopTime = 0
def startTimer(self):
self.startTime = time.time()
def stopTimer(self):
self.stopTime = time.time()
print ('Time passed ', self.stopTime-self.startTime, ' secondes')
|
79b7a73c4f05ef6b2ac2d550303bde112a06c94a | rakshith15717/assignment | /reducer.py | 687 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 10 16:22:26 2020
@author: rakshith
"""
#!/usr/bin/python
import sys
import os
wordcount = {}
# Get input from stdin
for line in sys.stdin:
line = line.strip()
# parse the input from mapper.py
word, count = line.split('\t', 1)
# conve... |
7a11d2c0c3cecf8e92f246896e008083325b6667 | DMurray-Chadfield/hangman | /hangman.py | 1,301 | 3.84375 | 4 | import ascii_art as art
art_dict = {0:art.zero, 1:art.one, 2:art.two, 3:art.three, 4:art.four, 5:art.five}
word = input('Player one, choose a word: ')
word = word.lower()
length = len(word)
guess = '_' * length
def find_all(string, letter):
indices = []
index = string.find(letter)
while index != -1:
... |
7886acd61b86546a6df1f0a40c00a1e596902843 | Gabriel-Albuquerque-repo/algoritmos | /QuickSort.py | 787 | 3.6875 | 4 | def quick_sort(lista, inicio = 0, fim = None):
if fim is None:
fim = len(lista) - 1
if inicio < fim:
p = partition(lista, inicio, fim)
quick_sort(lista, inicio, p - 1)
quick_sort(lista, p + 1, fim)
return lista
def partition(lista, inicio, fim):
pivot =... |
ee82c01db2506f9073ad4926376e5683fff71b3a | siFeiden/riskasecond | /risk/board.py | 1,257 | 3.65625 | 4 | from collections import defaultdict
class Country(object):
"""A Country in a Risk Map"""
def __init__(self, name, owner=None, troops=0):
self.name = name
self.owner = owner
self.troops = troops
def __eq__(self, other):
return self.name == other.name
def __ne__(self, o... |
37ab734d930760a520cbc975dc01e4931293ed6e | angela-laien/leetcode_problems | /Palindrome_Number.py | 660 | 4.25 | 4 | # Given an integer x, return true if x is palindrome integer.
# An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
# Input: x = 121
# Output: true
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to lef... |
a5a3a311a21e8202036e8701b54333a165972a25 | angela-laien/leetcode_problems | /Squaring_Sorted_Array.py | 577 | 3.734375 | 4 | # Given a sorted array, create a new array containing squares of all the numbers of the input array in the sorted order.
# Input: [-2, -1, 0, 2, 3]
# Output: [0, 1, 4, 4, 9]
def make_squares(arr):
squares = [0 for i in range(len(arr))]
first = 0
last = len(arr)-1
highestSquareIdx = len(arr)-1
while first <=... |
f456aa8d8c169efb2690948157d1660b2292a665 | sabrina-32-SUST/PythonLearning | /lecture47Class&Object.py | 437 | 3.71875 | 4 | # Class = Template
class Student:
roll = ""
gpa = ""
rahim = Student()
# here rahim is a object of Student Class
print(isinstance(rahim,Student))
rahim.roll = 101
rahim.gpa = 3.44
print(f"Roll : {rahim.roll}, GPA : {rahim.gpa}")
karim = Student()
# here kahim is a object of Student Class
p... |
61adb98b7aab62c223d03bf6c85c5e224d59ed10 | sabrina-32-SUST/PythonLearning | /Exercise.py | 318 | 3.609375 | 4 | class Triangle:
base = ""
height = ""
def __init__(self, base, height):
self.base = base
self.height = height
def displayArea(self):
area = 0.5*self.base*self.height
print( "Area : ", area)
t1 = Triangle(10,20)
t1.displayArea()
t2 = Triangle(20,30)
t2.displayArea() |
59d72c0e4db462b194cd8fcd8251db1e71d14d54 | ed1rac/design-patterns-python | /comportamentais/iterator/main.py | 1,454 | 3.875 | 4 | class RadioStation:
def __init__(self, frequency):
self.__frequency = frequency
@property
def frequency(self):
return self.__frequency
class StationList:
def __init__(self):
self.__stations = list()
self.__counter = 0
def add_station(self, radio_station):
... |
f9dea1739eed60b3779d1f3386d0162b86f639c1 | Sruthi-hemadri/python | /src/assign24b.py | 158 | 3.6875 | 4 | my_str='mom'
my_str=my_str.casefold()
rev_str=reversed(my_str)
if list(my_str)==list(rev_str):
print("palindrome")
else:
print("not palindrome") |
ed51454731ad55edfe8ca93da27451e1a96acbca | Ingynnmon/Python | /listComprehensions.py | 557 | 3.8125 | 4 | >>> cube = []
>>> for i in range(10):
... cube.append(i**2)
...
>>> cube
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> for i in range(3):
... cube.append(i**2)
...
>>> cube
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4]
>>> for i in range(3):
... cube.append(i**3)
...
>>> cube
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81,... |
f0191f4366dd5fd1890c57df8ddfdcaa34d0705c | Realdo-Justino/infosatc-lp-avaliativo-02 | /exercicio-01.py | 148 | 3.75 | 4 | lista=[2,3,4,5,6,7]
resultado=0
contador=0
for i in lista:
resultado+=lista[contador]
contador+=1
print("O resultado da soma é ",resultado) |
ebc166a6432f49de7903e7fcff271abe4be0db2f | grcxxi/Feedforward-NN | /xor_example.py | 394 | 3.5 | 4 | import neural as ai
import numpy as np
# XOR test data set
i = np.matrix([[0, 0],
[1, 0],
[0, 1],
[1, 1]])
t = np.matrix([[1],
[0],
[0],
[1]])
# Run
nn = ai.NeuralNetwork(2, 3, 1)
nn.train(i, t)
while True:
# Get input and return evaluation
sample = input("Enter a... |
cbd5bfbb663516bbe2627a301ba5123b53dd8583 | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /ex038.py | 377 | 3.78125 | 4 | a = int(input('Digite um número inteiro: \033[1;34m'))
b = int(input('\033[mDigite outro número inteiro: \033[1;35m'))
if a > b:
print('\033[mO primeiro valor (\033[1;34m{}\033[m) é maior.'.format(a))
elif b > a:
print('\033[mO segundo valor (\033[1;35m{}\033[m) é maior.'.format(b))
else:
print('\0... |
0c0a9a6a037cbbcbf35069caf85dd04d9909e165 | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /desafio066aula15.py | 230 | 3.796875 | 4 | q = s = 0
while True:
numero = int(input('Digite um número inteiro (999 para parar): '))
if numero == 999:
break
q = q + 1
s = s + numero
print(f'Você digitou {q} números e a soma deles é {s}')
|
b0d2cceaade2eeedd77c772678c5885dcd431bba | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /ex041.py | 722 | 4 | 4 | import datetime
ano = int(input('Digite o ano de nascimento do atleta: '))
anoatual = datetime.date.today().year
idade = anoatual - ano
if 0 <= idade <= 9:
print('Em {}, o atleta tem/terá {} ano(s).\nCategoria: MIRIM'.format(anoatual, idade))
elif 9 < idade <= 14:
print('Em {}, o atleta tem/terá {} ano(s... |
98e472244ffbfd75be34eab81c681ce755f45fa0 | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /ex051.py | 391 | 3.765625 | 4 | pa = 0
primeirotermo = int(input('Digite o primeiro termo da Progressão Aritmética: '))
razao = int(input('Digite a razão da Progressão Aritmética: '))
termo10 = primeirotermo + (10-1) * razao
print('Segue a PA com os 10 primeiros termos, com primeiro termo {} e razão {}:'.format(primeirotermo, razao))
for c in ra... |
0bc9e88542b2265f6f0c1b461e14e04aad336295 | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /desafio036aula12.py | 600 | 3.859375 | 4 | casa = float(input('Digite o valor da casa: R$'))
salario = float(input('Digite seu salário: R$'))
anos = float(input('Em quanto(s) ano(s) irá pagar o empréstimo? '))
meses = anos * 12
parcelamensal = casa / meses
print('Valor da casa: R${:.2f}\nSalário informado: R${:.2f}\nTempo: {} ano(s)'.format(casa, salar... |
4fd1cb46f53a5a96651fa19dbccdc182efe0cfdd | augustomy/Curso-PYTHON-02-03---Curso-em-Video | /desafio071aula15.py | 1,387 | 3.875 | 4 |
while True:
nota50 = nota20 = nota10 = nota1 = 0
sobra1 = sobra2 = 0
valor = int(input('Digite o valor a ser sacado: R$'))
if valor >= 50:
nota50 = valor // 50
sobra1 = valor % 50
if sobra1 >= 20:
nota20 = sobra1 // 20
sobra2 = sobra1 % 20
... |
af8b36f3d78bb911388c57ff7643d4e310d369f8 | TimothySaunders/compare | /start_code/tests/compare_test.py | 472 | 3.890625 | 4 | import unittest
from src.compare import compare
class TestCompare(unittest.TestCase):
def test_compare_3_1_returns_3_is_greater_than_1(self):
self.assertEqual("3 is greater than 1", compare(3, 1))
def test_compare_1_3_returns_1_is_les_than_3(self):
self.assertEqual("1 is less than 3", compar... |
1c56c32b3e1ac1a379f61c8236793d8ec8db7d8a | DanielAtSamraksh/sketchbook | /boole/validity_smallerfirst.py | 1,810 | 3.609375 | 4 | """
Propositional validity checker.
From validity.py but hopefully faster. (I haven't benchmarked it.)
For AND and OR we test the simpler argument first.
In the original code we always went left to right instead.
"""
def is_valid(expr): return satisfy(expr, 0) == False
def satisfy(expr, value):
return expr(value,... |
f98b52444f98100b2680049975c0548028727a7d | illume/numpy3k | /numpy/lib/arraysetops.py | 11,769 | 3.71875 | 4 | """
Set operations for 1D numeric arrays based on sorting.
:Contains:
ediff1d,
unique,
intersect1d,
setxor1d,
in1d,
union1d,
setdiff1d
:Deprecated:
unique1d,
intersect1d_nu,
setmember1d
:Notes:
For floating point arrays, inaccurate results may appear due to usual round-off
and floating point com... |
853a8ad5a95e2e30e28297188e3bc055881d6779 | tom2002965/Algo | /Day_16_NoConditionSwap.py | 113 | 3.703125 | 4 | def swap(x, y):
s = x < y
return x * s + y * (1 - s), y * s + x * ( 1 - s)
print swap(3, 15),swap(15, 3) |
c0e9ec29816ad459ead647ab06140d89e117886e | KarinK689/Engr-216-Lab-Group-B-Code | /Lab 1.py | 3,545 | 3.953125 | 4 | # Juan Hayward
# Engr Lab 1: Error Propogation
# Data code
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# import the csv into pandas for easy access of information
df = pd.read_csv("example_4.csv")
def error_add(*errors):
"""
This function computes error for adding and subtrac... |
166adf08a1a91be2a004d12afeee2aabdc17d324 | singingjy/Python | /20200827_거북이게임.py | 745 | 3.890625 | 4 | import turtle as t
def turn_right():
te.setheading(0)
def turn_up():
te.setheading(90)
def turn_left():
te.setheading(180)
def turn_down():
te.setheading(270)
def space():
te.forward(100)
te = t.Turtle()
te.shape("turtle")
te.color("green")
te.forward(100)
te.setheading(90)
... |
2017e13262c64d5b705ad946c264342e338b3928 | eastsidepyladies/learnpython3thehardway | /kellyc/ex38.py | 2,633 | 4.15625 | 4 | # Doing things with lists
# This assigns a string to variable ten_things
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait, there are not ten things in this list. Let's fix that.")
# this splits the string assigned to ten_things by empty spaces, creating a list
stuff = ten_things.split(' ')
# Tr... |
868604fd9ef9c266b9ac3a01de9f5f8001b5f840 | eastsidepyladies/learnpython3thehardway | /Jami/ex40a.py | 629 | 4.03125 | 4 | # dict style
#
# mystuff = { 'apple': "I AM APPLES!"}
# print (mystuff['apple']) # get apple from dict
# module style
#
# import mystuff
# mystuff.apple() # get apple from module
#
# print(mystuff.tangerine) #get tangerine from module, only now its a variable
# class style
# instead of import, you in... |
e68a7367a94e3179660f0c41cd35a0f786e898b6 | eastsidepyladies/learnpython3thehardway | /KristinS/ex2.py | 187 | 3.84375 | 4 | print "hens", 25+30/6
print "Roosters", 100-25*3%4
print "now I will count the eggs"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7?"
print 3+2<5-7
print "what is 3+2?", 3+2 |
9882935968976c40aedf8e4ba63488c2cf15276a | eastsidepyladies/learnpython3thehardway | /Jami/ex5.py | 652 | 4.125 | 4 | my_name = 'Zed A. Shaw'
my_age = 115 # Now a Hobbit
my_height = 36 # inches or 3 feet
my_weight = 180 # better not skip second breakfast
my_eyes = 'Green'
my_teeth = 'Ivory'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("... |
5ee88fecdfc3bad7c3568119dce48fe8b7547b2b | eastsidepyladies/learnpython3thehardway | /Jami/ex14.py | 880 | 4.0625 | 4 | from sys import argv
script, user_name = argv
prompt = '> '
print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")
print(f"Would you swipe right on my profile?")
likes = input(prompt)
print("Do you take the red pill or the blue pill?")
pill = input(prompt)
print(f"{user_nam... |
e36aebb8021754533488051e6aeb4775167d4279 | eastsidepyladies/learnpython3thehardway | /kellyc/ex32.py | 1,369 | 4.5625 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this takes each item in the list and prints the statement below
# the individual items in the list are all assigned to the variable "number"
for number in the_count:
print(f"This is ... |
130b700ecf0021e0348dcf392b31da6f4ab9f399 | yu4763/CodingInterview | /3.스택_큐/3.4.py | 879 | 3.828125 | 4 | from stack import Stack
class MyQueue:
def __init__(self):
self.s1 = Stack()
self.s2 = Stack()
def enqueue(self, data):
self.s1.push(data)
def dequeue(self):
if self.s2.isEmpty():
if self.s1.isEmpty():
print("empty")
return
... |
fa85d6e52bcb2c7ac2e2599f086b1676392f823a | yu4763/CodingInterview | /1.배열_문자열/1.4.py | 756 | 3.65625 | 4 | from collections import Counter
if __name__ == "__main__":
string = input()
string = string.replace(" ", '')
string = string.lower()
counter = Counter(string)
possible = True
palindrome = True
for c in counter:
if counter[c] % 2 != 0:
if possible:
possi... |
d27ff8894620795b4848ec76a0ecfc27ddca430d | yu4763/CodingInterview | /3.스택_큐/3.6.py | 1,751 | 3.96875 | 4 | class Animal:
order = None
def __init__(self, name):
self.name = name
class Cat(Animal):
def order(self, order):
self.order = order
class Dog(Animal):
def order(self, order):
self.order = order
class Queue:
def __init__(self):
self.cat = []
self.dog = []
... |
82df452de4ca89cab6b86c33d394e173d1c603bb | RosaIss/advent_of_code | /2020/d1_1.py | 672 | 3.53125 | 4 | """--- Day 1: Report Repair ---"""
import sys
def sum2020():
expenses = set()
input_expenses = []
for line in sys.stdin:
line = int(line[0:-1])
input_expenses.append(line)
expenses.add(line)
for exp1 in input_expenses:
exp2 = 2020 - exp1
if exp2 i... |
20caeef835cfa7a4209f16662f3b471ad96768ac | RosaIss/advent_of_code | /2017/d7_2.py | 3,310 | 3.640625 | 4 | """Day 7: Recursive Circus part 2"""
import sys
import re
program_dict = {}
def insert_in_program_dict(line):
program_att = re.split("[, ]+", line)
if program_att[0] not in program_dict:
program_dict[program_att[0]]={}
program_dict[program_att[0]]["repeated"]=0
else:
program_dict[... |
5202a5649f82e73be44dd2d0043c3e199bdb1e38 | RosaIss/advent_of_code | /2017/d3_2.py | 2,488 | 3.65625 | 4 | """--- Day 3: Spiral Memory part 2---"""
import math
# set the size to a number that, divided by 2,
# results in 2 symetrical partitions.
# eg. size = 3, 2 arrays of 1 element
# size = 5, 2 arrays of 2 elements
size = 900
mtx = [0] * (size * size)
Y = 0
X = 1
def sum_cord_pos_val(pos, card_pos):
if ca... |
abbb972270c71225051fd344d181e34920ac60e6 | ruisunyc/leetcode_Solution | /leetcode/1026.节点与其祖先之间的最大差值/1026-节点与其祖先之间的最大差值.py | 664 | 3.5625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
self.ans = 0
if not root:return self.ans
def dfs(root,mins,maxs... |
da10cb3d62895f2ff92c0aa89c9563ad7c147692 | ruisunyc/leetcode_Solution | /leetcode/剑指Offer26.树的子结构/剑指Offer26-树的子结构.py | 614 | 3.953125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
# if not A and not B:return True
if not A or not B:return Fal... |
7441e38e895421e06ce057e7f18d8dc03d4721e2 | WSF-P2019/Python | /Exercices/exo3.py | 2,780 | 4.15625 | 4 | # Q1.2
class Voiture(object):
pass
#Q1.3
renault = Voiture()
#Q1.4
print renault
#Q1.5
class Voiture(object):
def __init__(self, arg):
super(Voiture, self).__init__() # Bonne pratique ;)
#Q1.6
class Voiture(object):
color = 'red' # Définition d'un attribut
name = 'basicName'
def __init__(self, arg):
... |
584f7f3b856b57582882f506d1f06acc11d3eac8 | daffuna91/Data-Structure-and-Algorithm-Quiz | /1_findNumber.py | 802 | 3.5625 | 4 | def findNumber(myList, m):
'''
myList 내에 숫자 m이 존재하면 True, 아니면 False를 반환하는 함수
만약 myList = [1, 3, 2, 5, 4]이고, m = 7이라면 False를 반환한다.
'''
return m in myList
def main():
'''
이 부분은 수정하지 마세요.
'''
myList = [int(v) for v in input().split()]
m = int(input())
print(findNumber(myList... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.