blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
551a25425818e122db29d3b8ead73766e5d9c8df | JabariBooker/10th-grade-Computer-Programming-Class-Code-10CPCC | /nim.py | 987 | 3.671875 | 4 | from math import *
def play_nim(nHeaps, itemsPerHeap):
heaps = [itemsPerHeap for i in xrange(nHeaps)]
while True:
heaps = auto_nim(heaps)
if sum(heaps) == 0:
print "Human wins!"
return
heaps = human_nim(heaps)
if sum(heaps) == 0:
print "Comput... |
07dba529e2dee5aabf3673c0b4d469f58131c5b1 | JabariBooker/10th-grade-Computer-Programming-Class-Code-10CPCC | /heap_sort.py | 1,360 | 4.15625 | 4 | from math import *
def heap_push(heap,value):
heap.append(value)
i = len(heap) - 1
parent = int(ceil(i/2.0))-1
while heap[i] > heap[parent]:
heap[i], heap[parent] = heap[parent], heap[i]
i, parent = parent, int(ceil(i/2.0))-1
def heap_pop(heap):
out = heap[0]
heap = heap[1:]
... |
f0edcafdb0828802d990f71f984c0df0fdabe442 | Yocia/Metody_numeryczne | /Lista1.py | 1,172 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
from numpy import *
from numpy.random import *
from matplotlib.pyplot import *
from decimal import *
y=[]
for x in range(56, 101):
y.append(2*x**2 + 2*x + 2)
print(y)
# In[25]:
from numpy import *
from numpy.random import *
from matplotlib.pyplot import *
from ... |
d3051b4dba6791f3254e53f90d2681c594348717 | RakeshKumar045/Artificial_Intelligence_Complete_1 | /Artificial_Intelligence/Complete_AI_DS_ML_DL_NLP/Complete-DS-ML-DL-PythonInterview/code_challenges-master/zig_zag.py | 1,611 | 4.09375 | 4 | '''
A sequence of integers is called a zigzag sequence if each of its elements is
either strictly less than all its neighbors or strictly greater than all its
neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2
and 3 8 6 4 5 aren't. Sequence of length 1 is also a zigzag.
For a given array of in... |
ba347076e581274efbb3cb6283ce345afe2758d6 | RakeshKumar045/Artificial_Intelligence_Complete_1 | /Artificial_Intelligence/Complete_AI_DS_ML_DL_NLP/Complete-DS-ML-DL-PythonInterview/code_challenges-master/construct_array.py | 852 | 4 | 4 | '''
Given an integer size, return an array containing each integer from 1 to size in the following order:
1, size, 2, size - 1, 3, size - 2, 4, ...
Example
For size = 7, the output should be
constructArray(size) = [1, 7, 2, 6, 3, 5, 4].
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer size
A p... |
9e32163c8a68155df8886948c3a334c4bf0d07f1 | eugenern/Advent-Of-Code | /2016/7/7-1.py | 1,849 | 3.71875 | 4 | """
Given a list of IP addresses, determine how many of them support Transport Layer Snooping
"""
# -------
# imports
# -------
import sys
import re
# -----
# check
# -----
def check(iters):
"""
given iterators over the hypernet sequences and over the other parts, determine whether ABBAs are placed appropriately
... |
b19f16d8dede2567737f0606102c413d77f6dfc8 | eugenern/Advent-Of-Code | /2016/11/11_raw_input_parser.py | 1,657 | 3.71875 | 4 | """
Given a description of the locations of the generators and the microchips, form the input to solve the problem in clingo syntax
"""
#!/usr/bin/env python3
# -------
# imports
# -------
import sys
from element_symbols_dict import element_symbols
# -----
# parse
# -----
def parse(line, prev, writer):
"""
each ... |
b9bda5baeefcccefd2156fbbb79ba5e116b8a295 | strawnp/apcsp-19-20 | /unit4/p4.py | 414 | 3.890625 | 4 | def random():
return 4
print("hello, world")
print(random())
for i in range(1, 11, 2):
print(i)
x = 42
x = 'B'
x = 3.14
nums = [1,2,3,4,5]
nums_size = len(nums)
for i in range(nums_size):
print(nums[i])
for num in nums:
print(num)
num1 = input("Num 1: ")
num2 = input("Num 2: ")
if num1 > num2:
... |
b06e0c9cdd2f8c59c28bb1d018b7a327e2f4bb3b | den01-python-programming-exercises/exercise-1-9-story-chamberlainr4 | /src/exercise.py | 409 | 4.0625 | 4 | def main():
first = input('Hello we are going to write a story. Would you like to join me:')
second = input('Cool. What does the main character do:')
third = input('What is their name:')
print("Once upon a time there was a person called " + third + ", who ")
print("loved being a " + second + ".")
... |
c34ffcd1da2f87d53ce903fec17a3ad97023cf01 | QueraltSM/QuadraticEquation | /.idea/QuadraticEquation.py | 924 | 3.953125 | 4 | from math import sqrt
def QuadraticEquation(a, b, c):
if (b*b<4*a*c):
return ("\nThe solution belongs to the Complex Numbers field.");
elif ((a!=0) and ((b*b)>(4*a*c))) :
solution = "\nFirst Solution: " + str((-b+sqrt(b*b-4*a*c))/(2*a)) + \
"\nSecond Solution: "+ str((-b-sqr... |
12d32af27a937d26a5b16732623ba162ca444575 | LiYuanyuanFighting/BioInformatics | /lab2/Exercise3/Ex4.py | 1,476 | 3.5625 | 4 | '''
Given a tag file named tags.txt and a file storing all the known miRNAs sequences named
mirna.fa, write a python program that:
(1) For each human miRNA (labeled as hsa within mirna.fa file) identifies the seed sequence and check its presence in the provided tags (stored in tags.txt file)
(2) If the seed is found in... |
6b4ca7c23140c232ea34feaa5dc5ac3ae1e42e88 | lvbronco/random | /sort_tup.py | 496 | 3.921875 | 4 | # data = [('Jervie',12,'M'),('Jaimy',11,'M'),('Tony',23,'M'),('Jaimy',11,'F')]
# # and so define a lambda that returns a tuple that describes priority, for instance
# print sorted(data, key=lambda tup: (tup[1],tup[0]) )
# # print sorted(data, key=lambda tup: tup[1] )
# # print sorted(data)
# # [(1, 1, 4), (1, 2, 1), (... |
ddbcefd58840bf8ff02cedf955fcebde21a92fa1 | lvbronco/random | /trie.py | 334 | 4.09375 | 4 | _end = '_end_'
def make_trie(word, root=dict()):
current_dict = root
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return root
trie = dict()
print make_trie('foo', trie)
print make_trie('bar', trie)
print make_trie('baz', trie)
print make_trie... |
b756301bcaadf046eabe18b3b1438723a74ae8ed | assementsov/Python_learn | /Lesson3.py | 4,452 | 3.890625 | 4 | #1.Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
#Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def div(*args):
try:
arg1 = int(input("Введите Делитель "))
arg2 = int(input("Введите Делитель "))
res = arg1 ... |
31282d25d1d8b008cc9a084596c280b218bbf3ee | dixoncrews/ncsu-fall16-csc505 | /quicksort_base_case_comparison/qsort.py | 2,542 | 3.578125 | 4 | # qsort.py
# Author: Dixon Crews
# CSC 505-001, Fall 2016
# Homework 2, #4
###############################################################################
# Import needed libraries
import time, sys
###############################################################################
# Define the getMilliseconds() functio... |
44ef03d1866a338245480aba7de84e0d431e2c4c | sunsongqiao2018/Python_Practice | /ClassAB.py | 1,399 | 3.703125 | 4 | # class derive
class A(object):
def show(self):
print 'base show'
class B(A):
def show(self):
print 'derived show'
obj = B()
# Aobj = A()
obj.show()
obj.__class__ = A
obj.__class__ = B
obj.show()
class C(object):
def __init__(self,a,b):
self.__a = a
self.__b = b
def myprint(self):
print 'a = ', self.__a... |
a9d0085cf7fce0a51c5d4dfa06178ee0370b09c5 | Gubaidan/reptilePython | /main.py | 8,205 | 3.8125 | 4 | '''
str2 = 'night'
str2.capitalize()
print(str2.capitalize())
def what():
words = 6
def whatinit():
nonlocal words
for i in range(10):
for j in range(10):
print(words+(i+j))
return whatinit()
what()
g = lambda x: x*x+1
print(g(4))
g = list(filte... |
0f284e06e69ba6fa60b74c17cb0b020fa2e1b15b | wonkwonlee/likelion-k-digital-training-AI | /Data-Structure-and-Algorithm/practice/12c_lootMaximumFood.py | 1,257 | 3.671875 | 4 | """
Loot Maximum Food
Given N number of food storages, each stored with K food, return the maximum
food available.
If you loot one food storage, you cannot loot any neighboring storages (i+1, i-1)
Input: N number of food storages
K food stored in each storage
Output: Maximum food available
# E... |
9bd82f57493bc8b5d00be8e60f81ea3203b286a6 | wonkwonlee/likelion-k-digital-training-AI | /Data-Structure-and-Algorithm/practice/00a_Fibonacci_Card.py | 807 | 4.3125 | 4 | """
피보나치 수열을 출력하는 프로그램
조건 1. 함수를 활용하여 문제에서 언급한 피보나치 알고리즘을 작성하시오.
조건 2. for 반복문과 range() 함수를 통해 출력을 제어하시오. (최소 8항의 값 21까지 출력 )
"""
# Recursive method
def fibonacci(n):
if n <= 1:
return n
else:
return (fibonacci(n - 1) + fibonacci(n - 2))
print("========재귀문 방식========")
for i in range(8):
... |
a201b9fbf093b980e0834b395108f6c4d2cd38cd | wonkwonlee/likelion-k-digital-training-AI | /Data-Structure-and-Algorithm/practice/10d_binarySearch.py | 708 | 4.1875 | 4 | """
Binary Search
Use binary search to find target element in the array.
"""
# N number of elements and the target value
n, target = map(int, input().split())
array = list(map(int, input().split()))
start = 0
end = len(array) - 1
# Binary search using recursion
def binary_search(start, end, target):
mid = (sta... |
bca22f2f488cb10fb868bf929b2efb0ab76e80f2 | wonkwonlee/likelion-k-digital-training-AI | /Data-Structure-and-Algorithm/practice/25a_icecreamDFS.py | 1,096 | 3.53125 | 4 | """
Icecream DFS Search
# Example
4 5
00110
00011
11111
00000
>> 3
15 14
00000111100000
11111101111110
11011101101110
11011101100000
11011111111111
11011111111100
11000000011111
01111111111111
00000000011111
01111111111000
00011111111000
00000001111000
11111111110011
11100011111111
11100011111111
>> 8
"""
# N row, M... |
024c2997a3cc44484572f44554d3cab7e7c32ee4 | predator1019/CTI110 | /P2HW1_CelsiusConverter_AlexVanHoof.py | 349 | 4.5 | 4 | # Converts temperature to celcius
# 9/5/18
# CTI-110 P2HW1 - Celsius Fahrenheit Converter
# Alex VanHoof
#
#get the degrees to convert
degrees = float(input('enter the Fahrenheit degrees:'))
#calculate the degrees into celcius
degrees = F=9/5*degrees+32
#display the degrees.
print('the degrees in celci... |
4285e272193be96ad7312196817da3a93c6bc3b0 | topi-chan/Misc_projects | /new_tetris.py | 10,291 | 3.5 | 4 | import random
class Tetris:
'''A simple game.'''
def __init__(self):
self.i_shape = [[1, 1, 1, 1]]
self.l_shape = [[1], [1], [1, 1]]
self.j_shape = [[0, 1], [0, 1], [1, 1]]
self.s_shape = [[0, 1], [1, 1], [1, 0]]
self.o_shape = [[1, 1], [1, 1]]
self.current_sha... |
2950aca54c9daaa00cf5e09e86ae5d37ba050116 | CraigCaseyContreras/ECELabCrypto | /CryptoLab1/cryptoLab2.py | 1,304 | 3.875 | 4 | import os
import io
# Program to show various ways to read and
# write data in a file.
fname = "myfile.txt"
fname2 = "myfile2.txt"
path = os.path.abspath(fname)
path2 = os.path.abspath(fname2)
file1 = open(fname,"w")
L = ["I am Craig\nI like football\nI am a grad student at the University of Miami\n"]
# \n is place... |
af06904ccd3edb38daecac264f5b01d7b51f84a2 | SanyamYadav/Python_ | /Inf2A_Prac2_template.py | 11,613 | 3.671875 | 4 |
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# PART A: Processing statements
def add(item,lst):
if (item not in lst):
lst.insert(len(lst),item)
class Lexicon:
"""stores known word stems of various part-of-speech categories"""
# add code h... |
53a9fc849c61a5a050135a23268f9d44a80bbf34 | hashito/learning2python | /teach/001/2020-01-11/2020-01-11.1.py | 80 | 3.625 | 4 | a = [0, 1, 2, 3]
a.append(4)
print(a)
a = [0, 1, 2, 3, 4, 5]
del(a[2])
print(a) |
062e05b181e2c27c633a7f3806c8a78fcd7d22e0 | hashito/learning2python | /teach/001/2020-05-09.1.py | 512 | 3.96875 | 4 |
nums=[]
while(True):
i = input("number add('q'=end)>")
if(i.isdecimal()):
pass
elif(i=="q"):
pass
else:
pass
print("command is")
print(" max")
print(" min")
print(" ave")
print(" all")
print(" len")
print(" q")
while(True):
i = input("command >")
if(i=="max"):
... |
0c6cf7dbfce967626d73ce42193332df500bc1e7 | Kindred393/python_2020_projects1.2 | /critters/game_functions.py | 2,653 | 3.796875 | 4 | #difficulty settings (define difficulty)
def dificulty():
question = input("what difficulty would you like Easy, Medium, Hard ")
#
if question.startswith("M") or question.startswith("m"):
difficulty = "Medium"
elif question.startswith("H") or question.startswith("h"):
difficulty = "Hard"... |
068387d77ed9d2b81f2efc848436639d0e581984 | Kindred393/python_2020_projects1.2 | /Random number game.py1.2.py | 4,053 | 4.0625 | 4 | #Ethan Eash
#9/20
#guess my number 1.0
import random
##theNumber = random.randint(1,maxNumber)
#print(theNumber)#for testing remove when finished
#setting variables
maxNumber = 10
numTrys = 3
diff = 1
win = False
print("\twelcome to 'guess my number'")
#difficulty settings
question = input("what difficulty owu... |
0e980cb13bbd091276054c293210db147223d162 | nbrown-dsl/-1-tkinter_codingbat_exercsies | /2 string1 combo string.py | 722 | 3.75 | 4 | #coding bat exercise
# https://codingbat.com/prob/p194053
from tkinter import *
root = Tk()
e = Entry(root, width=25, borderwidth=15,font=("Courier", 44))
e.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
f = Entry(root, width=25, borderwidth=15,font=("Courier", 44))
f.grid(row=1,column=0,columnspan=3,padx=10,... |
fc637ac12ef014336b00fac127f2599d58e70cbb | ShiekhRazia29/Extra_Questions | /Hackathon1.py | 1,591 | 4.1875 | 4 | # Q6 Maximum of three numbers
a = int(input("Enter First number:"))
b = int(input("Enter Second number:"))
c = int(input("Enter Third number:"))
if a > b and a > c:
print(" A is maximum")
elif b > a and b > c:
print("B is maximum")
else:
print("C is maximum")
# Q7 A number divisible by 11 and 5
n... |
26ea64ef9516ecb355d98a442e345579d376d271 | ShiekhRazia29/Extra_Questions | /sevenStepsq.py | 1,054 | 4.28125 | 4 | # Number divisible by 5 or not
raw_input = int(input("Enter a number"))
if raw_input % 5 ==0:
print("Divisible by 5")
else:
print("Not divisible by 5")
#Greater number among two inputs by the user
num1 =int(input("Enter first number:"))
num2 =int(input("Enter second number:"))
if num1 > num2:
prin... |
9f4506897a4c369853ce9a11b1bf2f9efad4852b | HongYhong/python_practice | /thread_test.py | 491 | 3.703125 | 4 | import time,threading
def loop():
print('thread(%s) is running.'%threading.current_thread().name)
n = 0
while n<5:
n += 1
print('thread (%s) > %d'%(threading.current_thread().name,n))
time.sleep(1)
print('thread (%s) ended.'%threading.current_thread().name)
print('thread %s is ... |
9382a1f0b0572d29456fa0b639b925cc05091565 | HongYhong/python_practice | /mydict_test.py | 658 | 3.53125 | 4 | import unittest
from my_dict import Dict
class TestDict(unittest.TestCase):
def test_init(self):
d = Dict(a = 1,b = 'test')
self.assertEqual(d.a,1)
self.assertEqual(d.b,'test')
self.assertTrue(isinstance(d,dict))
def test_key(self):
d = Dict()
d['hong'] = 1
... |
b8b12ed59209ce09ab1ed262bf5151820ffdb675 | gegemonTV/for_cycle | /ex1.py | 88 | 3.703125 | 4 | x = int('9' * int(input()))
print(x)
for i in range(x//2-1):
x -=2
print(x - 2)
|
8d44124be1190c341cbb8cbb3aef17ef17447306 | miraceti/Python_codes | /openpyxl/openpyxl1.py | 505 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 19:07:11 2020
@author: eric
"""
import openpyxl
path ="/media/eric/GLIESE/outil/python/github/mygithub/openpyxl/data3.xlsx"
workbook=openpyxl.load_workbook(path)
sheet = workbook.active #workbook.get_sheet_by_name("Sheet1)
rows = sheet.max_ro... |
2101e19eb4ab56e1fd00f44e90047e804073d400 | brianvs18/Nuevas_Tecnologias | /clase_021420/main.py | 326 | 3.9375 | 4 | #nombre = "Brian"
#print("Su nombre es: " + nombre)
#nombre = input("Ingrese su nombre: ")
#edad = input("Ingrese edad: ")
#print("Su Nombre es: " + nombre)
#print("Su edad es: " + edad)
num1 = float(input("Ingrese numero 1: "))
num2 = float(input("Ingrese numero 2: "))
total = num1 + num2
print("El total es: " + str(t... |
28b5b546bd2cb2261691debf299b2598de56b0f2 | efirvida/the-name | /the_name.py | 1,086 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
from collections import defaultdict
from os import path
from typing import Tuple, Dict, List
def the_name() -> Tuple[str, str]:
names = defaultdict(int) # type: Dict[str, int]
name_owners = defaultdict(list) # type: Dict[str, List[str]]
results ... |
02862048566445ef96e8948c9b93d2bf5acb89d3 | sunshine-sjd/LeetCode | /Longest Palindrome.py | 1,593 | 4.03125 | 4 | '''
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abcc... |
337ff929ec47d568756b9f215d73c5eff964a964 | sunshine-sjd/LeetCode | /Excel Sheet Column Number.py | 502 | 3.640625 | 4 | '''
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
'''
def titleToNumber(s):
result = 0
s_length = len(s)-1
for s_str... |
69daf87b8519d600b0aa4addeb97c245af0a943c | sunshine-sjd/LeetCode | /Minimum Moves to Equal Array Elements.py | 577 | 3.984375 | 4 | '''
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] => [2,3,3] ... |
0bb6a3efa6a2c598344579326c5b859c52f60447 | YuPo13/py_pizza1 | /pizza1.py | 1,502 | 4.40625 | 4 | """This program depicts process of pizza recipes creation"""
class Pizza:
"""This is parent class that features unique list of ingredients
and standardised recipe creation procedure"""
def __init__(self):
"""Initiate the list of ingredients"""
self.list_of_ingredients = ["ham", "tomatoes",... |
51b62db7227b523e07135bce017f0d4ebd10f64c | Bhushanbk/mypython | /objfunc.py | 847 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 11:31:11 2019
@author: hp
"""
class student:
database="student"
def get_details(self,aname,arno,afee):
self.name=aname
self.rno=arno
self.fee=afee
def put_details(self):
print("name is:",self.name)
pri... |
b58a4855ea374de5bb0d7fc648ee2251b6785ffd | Bhushanbk/mypython | /exceptfile.py | 465 | 3.84375 | 4 | import os
filename=input("enter the filename")
f=open(filename,"w+")
f.write("helo \nhi\nwelcome")
try:
f=open(filename,"r")
for line in f:
print(line,ends="")
f.close()
except FileNotFoundError:
print("file not found")
except PermissionError:
print("dont have permision")
except... |
4b15418f5f99d92090868318fe1674818c9cc41e | Bhushanbk/mypython | /func.py | 107 | 3.78125 | 4 | def sum():
a=int(input("enter no."))
b=int(input("enter no."))
res=a+b
print(res)
|
b03295c26e718194b5f2e6ddb3b2ea3eda78b51c | Bhushanbk/mypython | /nested if.py | 270 | 3.984375 | 4 | a=int(input("enter your no."))
b=int(input("enter your no."))
c=int(input("enter your no."))
if (a>b):
if(a>c):
print("a is greater")
if (b>c):
if (b>a):
print ( "b is greater" )
else:
print("c is greater")
|
0e45b2a6e10ed92083a03ea453d65b4335079ce5 | Bhushanbk/mypython | /operatoroverload.py | 402 | 3.78125 | 4 | class operatorovr():
def __init__(self,a=0,b=0):
self.a=a
self.b=b
def __str__(self):
return"({0}),{1})".format(self.a,self.b)
def __sub__(self,other):
a=self.a - other.a
b=self.b - other.b
return operatorovr(a,b)
obj1=operatorovr(2,3)
obj2=operator... |
60c9d6f06eb36ad354dd5b82757ce81389bcb620 | Brooks79/Lab5 | /Square_Root.py | 607 | 4.09375 | 4 | __author__ = 'Ray'
#after the class i realized this is not what you wanted, and yes I know using to the power of .5 is the same thing as
#square root, but the amount of time I spent trying to get this to work is far more than you probably think I should be
#spending.
while True:
Q1 = raw_input("Please choose a num... |
ccbb4940e910ee3c60cc3346f55dc4e850bf448b | jdarthur/projecteuler | /python/4.py | 428 | 3.96875 | 4 | def is_palindrome(number) :
string = "{0}".format(number)
for i in range(len(string) / 2) :
if(string[i] != string[len(string) - 1 - i]) :
return False
return True
def largest_palindrome(largest) :
lp = 0
for i in range(0, largest + 1) :
for j in range(0, largest + 1) :
if i*j > lp and is_palindrome(... |
355ef5b69f91431b71d019bdd9e26c976cb7e13d | danroth-nyt/project_benson | /python_code/mta_locate.py | 3,681 | 3.640625 | 4 | import pandas as pd
import requests
def geoGoogle(search, key, infolist):
"""Function to receive and address' geocode data from Google Maps."""
# Set up your Geocoding url
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?address={}".format(search)
if key is not None:
geocode_ur... |
162ea2c6155db5d9d73d81d289ca3af48ab93594 | XuChongBo/pydemo | /common/testAbstractMethod.py | 381 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class A(object):
def __init__(self):
print "init A."
def foo(self):
raise NotImplementedError("Please Implement this method")
class B(A):
def __init__(self):
A.__init__(self)
print "init B."
def foo(self):
print "fo... |
8f6866f73ce8dda9ecd7f26299b9063d0c213728 | XuChongBo/pydemo | /my_computer_vision/show_img.py | 611 | 3.546875 | 4 | """
open an image file and show it.
"""
import sys
from PIL import Image
from pylab import imshow,show,axis
# load the image file
img = Image.open(sys.argv[1])
#img = Image.open('../../data/cv_data/empire.jpg')
print img.width, img.height
img.show()
# plot the image
imshow(img)
# not plot the axises
axis('off')
... |
6ef15b86cd7bcb83979d3d4c40f19bacb76e895d | XuChongBo/pydemo | /common/read_utf8.py | 820 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import codecs
filepath = "xx.txt"
### handle chinese file path
descFilePath = os.path.join(config.UPLOAD_FOLDER, chinese_in_unicode, u"desc.txt")
print descFilePath, type(descFilePath)
print descFilePath.encode("utf-8")
f = open(descFilePath.encode("utf-8"), "r")
#... |
9a36e53d87bbb6efc9aa635fc3e3cb956565f267 | IvanKurkov/PythonAlgorithms | /7 Сортировки/Сорт пузырьком.py | 1,191 | 3.96875 | 4 | # 1. Отсортируйте по убыванию методом пузырька одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный и отсортированный массивы.
# Примечания:
# a. алгоритм сортировки должен быть в виде функции, которая принимает на вход массив данных,
# b. постарайтесь сде... |
1109ba7a3273e9cbe0ec1d0f509328384f605eba | IvanKurkov/PythonAlgorithms | /2 Циклы, рекурсия, функции/Угадай число.py | 1,004 | 4.0625 | 4 | # В программе генерируется случайное целое число от 0 до 100.
# Пользователь должен его отгадать не более чем за 10 попыток.
# После каждой неудачной попытки должно сообщаться, больше или меньше загаданного введенное пользователем число.
# Если за 10 попыток число не отгадано, то вывести его.
import random
number = r... |
09983451581f94dfbc589411dd1eef843ee57f32 | Twilight-Hacker/SydokuPythonSolver | /Sudoku/drive/driverC.py | 12,714 | 3.71875 | 4 | import sys
from math import floor
from copy import deepcopy
from _collections import deque
class Sudoku():
def __init__(self, tabl):
if(len(tabl)==81):
self.table = [str(x) for x in tabl]
else:
print len(tabl)
raise Exception("Illegal Input")
... |
a00911d9463c410c0a3a1f489d2d4c90d484135a | rowansharman/ToolBox-WordFrequency | /frequency.py | 2,542 | 4.34375 | 4 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
import re
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the bo... |
3d180d691e1f31f47cc2785305069416a390869e | lewisKit/lagom | /lagom/transform/centralize.py | 1,545 | 3.515625 | 4 | import numpy as np
from .base_transform import BaseTransform
class Centralize(BaseTransform):
r"""Centralize the input data to zero-centered.
Let :math:`x_1, \dots, x_N` be :math:`N` samples, the centralization does the following:
.. math::
\hat{x}_i = x_i - \frac{1}{N}\sum_{j=1}^{N} x... |
cc4c6c9a18d8d5f09a358454cf3e44264a2ffa22 | manishkumarmailbox/manish | /first.py | 110 | 4.1875 | 4 | x=int(input())
if(x%2==0):
print("the no is divisible by 2")
else:
print("the no is not divisible by 2")
|
7d29390ade1496e7c3c34cb0dfba6d2ed13b8143 | dazhxu/CodeLib | /LeetCode-Cpp/reverseint.py | 548 | 3.609375 | 4 | def reverse(x):
xCopy = x
flag = 1
if x < 0:
flag = -1
xCopy *= flag
ret = ''
s = xCopy/10
ret += str(xCopy%10)
while s > 0:
ret += str(s%10)
s /= 10
if float(ret) > 2147483647:
return 0
retX = flag * int(ret)
return retX
def reverse2(x):
... |
e65fc26016b9afa42bc74423f6234c3b0839518f | dazhxu/CodeLib | /LeetCode-Cpp/twosum.py | 760 | 3.8125 | 4 |
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ret = [] #store the result
hashtbl = {} #using hash tabel to store the index of item
for i in range(len(nums)):
n = hashtbl.get(nums[i]) #get the index of nums[i]
if n == None: ... |
21152dd8ad88205459bb95626d71e18c33a63cb2 | aditya-gune/CIFAR-10-Neural-Net | /MLP_Skeleton.py | 6,279 | 3.5 | 4 | """
Aditya Gune
"""
from __future__ import division
from __future__ import print_function
import sys
import math
import cPickle
import numpy as np
# This is a class for a LinearTransform layer which takes an input
# weight matrix W and computes W x as the forward step
class LinearTransform(object):
def __init... |
e1fc6286ba54d46ca2d78152bf233913151cf1ec | contraslash/curso_rapido_backend_python | /ejercicios/clase_02/calculadora/00_implementacion_tradicional.py | 446 | 3.875 | 4 | class Calculadora(object):
def sumar(self, a, b):
return a + b
def restar(self, a, b):
return a - b
def multiplicar(self, a, b):
return a * b
def dividir(self, a, b):
return a / b
calculadora = Calculadora()
print(calculadora.sumar(1, 2))
print(calculadora.restar... |
6f94c6fa258d5492326f83507547aaa52487f54e | contraslash/curso_rapido_backend_python | /ejercicios/clase_02/calculadora/02_implementacion_con_herencia.py | 847 | 3.90625 | 4 | class Operador(object):
def __init__(self, operador1, operador2):
self.operador1 = operador1
self.operador2 = operador2
class Suma(Operador):
def sumar(self):
return self.operador1 + self.operador2
class Resta(Operador):
def restart(self):
return self.operador1 - self.ope... |
9d9589931f4f8dd7432441d6d7d6b37edc88637d | AlessandroToschi/GameTheoryAssignment2 | /auction.py | 9,079 | 3.8125 | 4 | from buyer import Buyer, Distribution, OfferResult
import threading
BUYERS = 10
class Auction(object):
"""
This class models a simply abstract auction with a reserve price.
"""
def __init__(self, reserve_price=0):
"""
Initialize the auction with an optional reserve price, othe... |
746219e6895f80cd0e545b3e2d16e1f99639d213 | JustAManPassingBy/TensorflowTools | /Train/Collect_Prediction/CP_machine.py | 6,736 | 4 | 4 | import pandas as pd
import numpy as np
import csv
'''
- Note : We consider given prediction's feature with :
1. size_of_prediction is 1
-> Program thinks prediction is results of specific amount
- Ex : increase of market price.
2. else
-> Program thinks prediction is results of solving classifi... |
981d38d75570577daf1e9f3cb14610a2457a4ed6 | Tecnicas-de-programacion-Equipo-1/Examen-2 | /Views/MainView.py | 5,119 | 3.6875 | 4 | from tkinter import Tk, Canvas, Label, N, S, E, W
class MainView(Tk):
class Constants:
title = "PIZARRA MAGICA"
heigth_outside = 700
width_outside = 800
center_main_window = N + S + E + W
height_inside = 500
width_inside = 600
advance = 1
width_line =... |
86e3f1d848c02c60917cdedfa7bd667303a838b4 | vrinceanu/shared-jupyter | /homework-4.py | 733 | 3.890625 | 4 | #
# Solution for Homework 4:
# Feb 18, 2021
# Find the sum of the first 1000 prime numbers
# execute from CLI:
# python3 homework4.py
#
# primality test by brute force: try all numbers smaller than \sqrt{n}
# to see if they divide n, in other words, the reminder of the division is 0
import sys
def is_prime(n):
f... |
64994339a04249981d378b99d77b9aeb8aee7e55 | guangcity/learning-algorithm | /Archer/239. Sliding Window Maximum/239. Sliding Window Maximum.py | 2,870 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 方法一、利用队列的思想,先进先出,不断滑动窗口[i:i+k]
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
win = []
n = len(nums)
if nums != []:
... |
be5f1297d2caa4a17eb7892a3b231be5c5201598 | guangcity/learning-algorithm | /光城/sort_list/direct_sort.py | 534 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
l = []
while head:
l.append(head.... |
26e3c09ec5f5de29a507213b004960838f150881 | guangcity/learning-algorithm | /光城/mutiply_number/string_multipy.py | 1,088 | 3.53125 | 4 | class Solution:
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
s1_len = len(num1)
s2_len = len(num2)
if s1_len == 0 or s2_len == 0 or num1 == '0' or num2 == '0':
return '0'
res_list = [0 for i i... |
6865aec2c88e9d9fec3c54a6ae98e103b9e1a0c0 | guangcity/learning-algorithm | /光城/xuanzhan_link/digui_xuanzhuan.py | 762 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k == 0 or head ... |
6db04ac5cdb1ebc338deed109df8972bd2a4c050 | guangcity/learning-algorithm | /miss-ann/add-two-number/al/al.py | 713 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
... |
98284ddd135c1b53e78e34d55a8d235fd971a46f | guangcity/learning-algorithm | /光城/sort_list/maopao_sort.py | 688 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = head
size = 0
while p:
... |
9acc292c7770fdfadc0de55fb06864b07de29393 | s-andromeda/DP-5 | /Problem2.py | 1,372 | 3.59375 | 4 | class Solution:
"""
Name : Shahreen Shahjahan Psyche
Time : Recursive: O(4^MN)
Dynammic : O(MN)
Space: O(MN)
Passed All Test Cases : Yes
"""
# Recursive Solution
def recursive(self, m, n):
# ... |
6fc483e2b2b3152bcae81ad0b1a81ef8097a0878 | yamogi/Python_Exercises | /ch03/ch03_exercises/ch03_ex02.py | 701 | 4.21875 | 4 | # ch03_ex02.py
#
# Write a program that flips a coin 100 times and then tells you the number of
# heads and tails.
#
import random # import the random module
# initialising values
flip_count = 0
coin = 0
heads = 0
tails = 0
while flip_count < 100: # while flipping 100 times
coin = random.randint(1, 2) # coin is ... |
56ad1fb6c32e704a5161b1c4b2e40aa8aa788fd9 | yamogi/Python_Exercises | /ch03/ch03_exercises/ch03_ex01.py | 735 | 4.3125 | 4 | # ch03_ex01.py
#
# Write a program that simulates a fortune cookie. The program should display
# one of five unique fortunes, at random, each time it's run.
#
import random # importing the random module
fortune = random.randint(1,5) # pick a random number between 1 and 5
print("\n\t", end="")
if fortune == 1:
p... |
2a0e3718e2a98928823a5a83146de03076952c69 | yamogi/Python_Exercises | /ch04/ch04_exercises/ch04_ex03.py | 2,067 | 4.625 | 5 | # ch04_ex03.py
#
# Improve "Word Jumble" so that each word is paired with a hint. The player
# should be able to see the hint if he or she is stuck. Add a scoring system
# that rewards players who solve a jumble without asking for a hint.
#
import random # importing random module
# initialise tuple of possible words
... |
3298bd1bffdfa753a90f3af48e60ddae222b4768 | yamogi/Python_Exercises | /ch05/hero_inventory3.py | 2,390 | 4.28125 | 4 | # Hero Inventory 3.0
# Demonstrates lists
# create a list with some items and display with a for loop
inventory = ["sword",
"armor",
"shield",
"healing potion"]
print("Your items:")
for item in inventory:
print("\t", item)
# get the length of a list
print("You have", len(in... |
6f3d26ffab005417f671a38b297aeb83bb7a4266 | srushtiE/university-grading | /uniData.py | 542 | 3.515625 | 4 | import os
import csv
# function to get the names of the universities from the complete training data set
def names():
uniNames=[]
fn = os.path.join(os.path.dirname(__file__), 'FullTraining.csv')
with open(fn, 'rt', encoding='ISO-8859-1') as csvfile:
lines = csv.reader(csvfile)
dataset = lis... |
ffc76de09f7ad709c72a191994805c3bc64a4041 | iizakharov/algo_and_structures_python | /Lesson_5/2.py | 1,015 | 4 | 4 | """
2. Написать программу сложения и умножения двух шестнадцатеричных чисел.
При этом каждое число представляется как массив, элементы которого это цифры
числа. Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и
[‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’],
произведение - [‘7... |
9b016bfce5a8c6aea07a6a4e06b352c6a5e420d1 | iizakharov/algo_and_structures_python | /Lesson_2/1.py | 2,312 | 3.78125 | 4 | """
1. Написать программу, которая будет складывать, вычитать, умножать или делить
два числа. Числа и знак операции вводятся пользователем. После выполнения
вычисления программа не должна завершаться, а должна запрашивать новые данные
для вычислений. Завершение программы должно выполняться при вводе символа '0'
в качес... |
5a9087aa2b0fe7775ebe91fa65ce07d3eb2cfd7b | iizakharov/algo_and_structures_python | /Lesson_8/2.py | 852 | 4.3125 | 4 | """
2*. Определение количества различных подстрок с использованием хэш-функции.
Пусть дана строка S длиной N, состоящая только из маленьких латинских букв.
Требуется найти количество различных подстрок в этой строке.
"""
S = str(input("Введите строку: "))
print("Строка \'%s\' имеет длину: %d сиволов." % (S, len(S)))
... |
5b5a18f6d083c60ef2a2282230065cab3927024f | iizakharov/algo_and_structures_python | /Lesson_1/3.py | 618 | 4.15625 | 4 | # 3. По введенным пользователем координатам двух точек вывести
# уравнение прямой вида y = kx + b, проходящей через эти точки.
x1 = float(input('Введите координату x1: '))
y1 = float(input('Введите координату y1: '))
x2 = float(input('Введите координату x2: '))
y2 = float(input('Введите координату y2: '))
k = (y2 - y... |
c7053bd54fe49959003e8fbd314cce708b6efbf8 | iizakharov/algo_and_structures_python | /Lesson_7/Коды для урока/Алгоритм шейкерной сортировки.py | 1,182 | 3.875 | 4 | import random
import timeit
# Шейкерная сортировка
'''
разновидность пузырьковой сортировки.
Отличается тем, что просмотры элементов выполняются
один за другим в противоположных направлениях,
при этом большие элементы стремятся к концу массива,
а маленькие - к началу.
'''
def cocktail_sort(orig_list):
... |
710d6ee88ef984e07d4450ae417a264f354f9d9a | ahmedpato/HomeWork_Python- | /HomeWork14.py | 749 | 4.21875 | 4 | # By : Ahmed Mohammed Ali / 20184020
first = int(input("Enter First Number :"))
last = int(input("Enter Last Number :"))
sum_even = 0
avg_even = 0 # Average Even Number = Sum Even Number / Len Even Number
sum_odd = 0
avg_odd = 0 # Average Odd Number = Sum Odd Number / Len Odd Number
len_even = 0
len_odd =... |
79edb849596b262472af7d53714cc5b55696e35c | rkrishan/Pyhton_programs | /oops.py | 547 | 3.734375 | 4 | class A:
def __init__(self):
print("class A constructor")
def abc(self):
print("class A method is called")
class B(A):
def __init__(self):
print("class B constructor is called")
def abc(self):
print("class B method is called ")
def pqr(self):
print("clas... |
d23b8a371cda03420e6176ce66b2fe62597731b3 | Knevari/thingsfromudacity | /color_selection_code_example.py | 839 | 3.6875 | 4 | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
# Read an image file
image = mpimg.imread('test.jpg')
# Print some image stats
print('This image is: ', type(image), image.shape)
# Grab the x and y sizes
ysize = image.shape[0]
xsize = image.shape[1]
# Make a copy of the image
colo... |
4b25497ad121ad0c641cd2b6d65b2ea0c55d5110 | sethips/python3tutorials | /variableScope.py | 270 | 3.890625 | 4 |
num1 = 10
def addToNum(num2):
global num1
num1 += 20
print(num1+num2)
addToNum(12)
print("num1: ", num1)
def addToNumber(num2):
gnum1 = num1 # gnum1 is a local variable
print(gnum1+num2)
return gnum1
x = addToNumber(12)
print("num1: ", x)
|
ac8cd875f0939db379f1507e8a4daf0522535799 | zrshi/Elections-Analysis | /Python_practice.py | 1,737 | 4.1875 | 4 | counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == "Denver":
print(counties[1])
#What is the score?
score = int(input("What is your test score? "))
# Determine the grade.
if score >= 90:
print('Your grade is an A.')
else:
if score >= 80:
print('Your grade is a B.')
else:... |
5e0af14c2ff6b20d2fd7946f73959a90885b9e63 | mzhr/latimes_search | /minheap.py | 1,467 | 3.671875 | 4 | import math
class MinHeap:
def __init__(self, heapsize):
self.heap = [(0, 0)]*(heapsize +1)
def push(self, el):
if el[1] > self.heap[1][1]:
self.heap[1] = el
# self.heap.append(el)
self.heapifyList(self.heap)
def pop(self):
self.heapifyList(self.heap)
... |
94df6f9ce3aeac32ab45462105c4038ee9e4f348 | Goldlightdrake/AircraftFlightSimulator | /lib/gui/menu.py | 6,080 | 3.75 | 4 | import pygame
class Menu():
"""
Menu class was made to store the necessary data and create graphics:
- simulation
From this class inherit:
- MainMenu(Menu)
- OptionsMenu(Menu)
- CreditsMenu(Menu)
example init: Menu()
"""
def __init__(self, simulat... |
e198ae9303ecb2c1edea4559e0a1c6c9492112af | anusha2398/Python-Projects | /prog3.py | 90 | 3.921875 | 4 | a=input ("enter a num:")
a=int(a)
if a % 2 == 0:
print("weird")
else:
print("not weird") |
8873487dd853ea8542bfa124da538b4535c0ad55 | anusha2398/Python-Projects | /HW/prog9.py | 113 | 4.03125 | 4 | a = {1:"Speckbit", 2:"World", 3:"Quiet"}
b = input("enter the word:")
if b==a:
print (True)
else:
print (False) |
632ae6976274598034ad11cd073a10ebb839a91b | anusha2398/Python-Projects | /clothing.py | 676 | 3.953125 | 4 | import sqlite3
con = sqlite3.connect("clothing_db.sqlite3")
cur = con.cursor()
try:
cur.execute("CREATE TABLE clothing (id INTEGER PRIMARY KEY, name TEXT, price INTEGER, quantity INTEGER, availability TEXT)");
except sqlite3.OperationalError:
print("Table already exists...")
cur.execute("""INSERT INTO clothing VAL... |
31c0b0b6148732cdfcd80f1b2aa052de62efd5a7 | anusha2398/Python-Projects | /prog9.py | 125 | 3.953125 | 4 | list1=[1, 1, 2, 3, 4, 64, 35, 93, 35, 87, 4, 3]
list2=[]
for i in list1:
if i not in list2:
list2.append(i)
print (list2) |
0d223557f1b787cf312d83d9da653bc872d3dbb7 | anusha2398/Python-Projects | /events (2).py | 503 | 3.9375 | 4 | events_dict = {'1':'CS', '2':'Google it', '3':'Treasure Hunt'}
participant_details={}
def add_participant():
name = input("participant name")
event = input("event name:\n\
1) CS\n\
2) Google It\n\
3) Treasure it\n")
participant_details[name] = events_dict[event]
return participant_details
def see_participant... |
41fd389c67cb6444aff5ba822c4a8a50215ce7ac | zhechenw/recommender_system | /score_generators.py | 9,903 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 13 13:29:34 2019
@author: septe
This code contains all functions for score generator
you can also run this code to save scores for future use
to run this code, you need to provide k range, user list, and similarity functions
"""
import os
import pandas as pd
import nump... |
a2b2d31a332333371e5c310e4d5a045f0f08e1ce | devchandansh/python-bubble-sort | /bubble_sort.py | 833 | 4.21875 | 4 | """
@Author: Chandan Sharma.
@GitHub: https://github.com/devchandansh/
"""
"""
Here, bubble sort algorith is implemented by taking user inputs.
It sorted in Ascending Order of the given Input.
"""
print("How many numbers you want to add.?")
size = input()
unsorted_data = []
print("")
print("Enter the Numbers::")
fo... |
1201ad2a7a178929322692424f3339b9a0d878ab | Nassim-L/U.S.A-name-stats-map | /brain.py | 2,478 | 3.71875 | 4 | import pandas
from turtle import Turtle, Screen
import turtle
import time
name_show_in_the_map = []
name_left = []
class Brain(Turtle):
def __init__(self):
super().__init__()
self.screen = Screen()
self.ht()
self.data = pandas.read_csv('50_states.csv')
self.states = self.d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.