blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
394a29566d4320dc22511e37a43b5655c1d390c6 | jdcanas/minesweeper | /game/Board.py | 2,915 | 3.53125 | 4 | from random import randint
from game import BoardState
from game.Cell import Cell
from typing import Dict
from game.Coordinate import Coordinate
from game.GameExceptions import InvalidBoardException
from game.BoardState import BoardState
class Board:
def __init__(self, sizeCoord: Coordinate, numMines: int):
... |
48973077235d5f9ef434188f6745a6035310ce32 | alfredhung/python_projects | /cross_entropy_function.py | 724 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Cross Entropy function
"""
import numpy as np
# We write a function that takes as input two lists Y, P,
# and returns the float corresponding to their cross-entropy.
def cross_entropy(Y, P):
ce = 0
for i in xrange(len(Y)):
if Y[i] == 1:
ce1 = - np.log... |
bc5a9d32901da77147d1745a51a2d0b2e87265e3 | lars-alfonse/pythonBinarySearchTree | /SearchTree.py | 545 | 3.75 | 4 | from node import node
class SearchTree:
type = "tree"
def __init__(self):
self.root = None
def add_data(self, data):
if self.root is None:
self.root = node(data)
else:
self.root.add_child(data)
def search(self, data):
if self.root is None:
... |
dd88c329d7f72d9e4fa37e0630bf11e49cea066b | liujb/hello-py | /syntax/raiseException.py | 548 | 3.671875 | 4 | # FileName:raiseException.py
class DefinedException(Exception):
def __init__(self, length, least):
Exception.__init__(self)
self.length = length
self.least = least
try:
s = raw_input('Enter something-->')
if(len(s) < 3):
raise DefinedException(len(s), 3)
#raise EOFError
else:
pass
ex... |
7bcce75f81f54e4027544dedac940f3e55fdc1e8 | liujb/hello-py | /basic/isAndIsNot.py | 215 | 3.53125 | 4 | # coding=utf8
#!/usr/bin/python
a = 30
b = 30
if(a is b):
print a, "is", b
else:
print a, "not is", b
if(id(a) == id(b)):
print a, b, "have the same identity"
else:
print a, b, "have different indentity"
|
3878781bbb54c249b45cfdd0f39943b96a435822 | liujb/hello-py | /syntax/if.py | 173 | 3.625 | 4 | number = 23
guess = int(raw_input('Enter a number: '))
if guess == number:
print 'success.'
elif guess > number:
print 'gather.'
else:
print 'less'
print 'plz retry'
|
af3087147b662325d74ca3a9ed56bbb664b483a1 | alexcarlos06/Automatize_Tarefas_Ma-antes | /Projetos_Praticos/Exibição_de_tabela.py | 939 | 3.96875 | 4 | # Programa que exibe um lista de listas na tela em formato de tabela
def printTable(array: list):
columwidth = 0
itemwidth = 0
for item in array:
if len(item) > columwidth:
columwidth = len(item)
for register in item:
if len(register) > itemwidth:
it... |
b91e476168f547628e0448043af6f4c16dce3a89 | yogvjti/Resume-Link | /Function.py | 1,843 | 3.9375 | 4 | print("** Assignment 2 **")
print("Ex1")
import Assignment2
def main():
a = int(input("Enter no1: "))
b = int(input("Enter no2: "))
add = Assignment2.Add(a,b)
sub = Assignment2.Sub(a,b)
mul = Assignment2.Mult(a,b)
div = Assignment2.Div(a,b)
print("Addition: ",add)
print("S... |
2be5ff41a0dd3029786f149dd7674ead6a9f07f1 | titojlmm/python3 | /Chapter2_Repetition/2_01_RockPaperScissors.py | 1,346 | 4.25 | 4 | import random
# This program plays the game known as Rock-Paper-Scissors.
# Programmed by J. Parker Jan-2017
print("Rock-Paper_Scissors is a simple guessing game.")
print("The computer will prompt you for your choice, ")
print("which must be one of 'rock', 'paper', or 'scissors'")
print("When you select a choice the c... |
ae336ca6c69aa941c1f4152723f1b1f9bb73c7e3 | khasimworld/lp3thw | /ex15.py | 340 | 3.5625 | 4 | from sys import argv #import method of sys-library
script, filename = argv #get argumens values
txt = open(filename) #open file
print(f"Here's your file {filename}") #print filename
print(txt.read()) #print file's content
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
prin... |
fc9a4b749a71f91c5f7e14e7cfad5313fe69dda0 | mrizkymaulana22/lanjutandasarpython | /model.py | 680 | 3.53125 | 4 | #Make a class of Student Model
class StudentModel(object):
def __init__(self, nim, name, address):
self.nim = nim
self.name = name
self.address = address
def get_nim(self):
return self.nim
def set_nim(self, nim):
self.nim = nim
def get_name(self):
retur... |
c42cbd069f0767ddf4080718265b98ae6c5a8c98 | viktapas/AlgoCasts_Python_JS | /exercises/fizzbuzz/index.py | 772 | 4.5625 | 5 | # --- Directions
# Write a program that console logs the numbers
# from 1 to n. But for multiples of three print
# 'fizz' instead of the number and for the multiples
# of five print 'buzz'. For numbers which are multiples
# of both three and five print 'fizzbuzz'.
# --- Example
# fizzBuzz(5);
# 1
# 2
# fizz
# ... |
e27d287ca9dcd50d682327b0c51c80707651a68a | Kron610/In-depthPython | /1/Sequence.py | 3,050 | 3.5 | 4 | import collections
class Sequence (list):
def __new__(cls, arg = None):
if (arg == None):
return super().__new__(cls)
if (isinstance(arg, collections.Iterable)):
for element in arg:
if (not isinstance(element, int)):
raise Exception("... |
3c91ed1bfb2ae75021ea79c6dee0871eaee8d20a | rvkeerthana/myprogram2 | /BB43.py | 89 | 3.65625 | 4 | s1=raw-input("enter the s1 string")
s2=raw-input("enter the s2 string")
s=s1+s2
print(s)
|
0bf7047c22d9f64c50e5c0bd7c0bef2f922c6b77 | rvkeerthana/myprogram2 | /BB44.py | 80 | 3.796875 | 4 | n=int(input("enter the num:"))
if(n>=1)&(n<=10):
print("yes")
else:
print("no")
|
2582c76e9d71cf485942636d495eacc09da2c54b | rvkeerthana/myprogram2 | /BB32.py | 114 | 4.15625 | 4 | n=raw_input("enter the words:")
word=1
for i in n:
if(i==""):
word=word+1
print("number of word is:")
print(word)
|
546bb1a1abd16b0bfb72542e190050623329da3b | rvkeerthana/myprogram2 | /BB26.py | 581 | 3.828125 | 4 | def merge(arr,l,r):
n1=m-l+1
n2=r-m
L=[0]*(n1)
R=[0]*(n2)
for i in range (),n1):
L[i]=arr[l+i]
for j in range(0,n2):
R[j]=arr[m+1+j]
i=0
j-0
k=1
while i < n1 and j <n2:
if L[j]<=R[j]:
arr[k]=L[i]
i+=1
else:
arr[K]=R[j]
j+=1
k+=1
while i<=n1:
arr[k]=L[i]
i+=1
k+=1
while j<n2:
arr[k]=R[j]
j+=1
k+=1
print("")
def mergeSor... |
3b7c4450b32e512e41941bff13102c142257b001 | pocanico/scripts | /python/coding.py | 571 | 3.5 | 4 | #分别验证在pycharm中和cmd中下述的打印结果
s=u'林' #当程序执行时,'林'会被以unicode形式保存新的内存空间中
print s
#s指向的是unicode,因而可以编码成任意格式,都不会报encode错误
s1=s.encode('utf-8')
s2=s.encode('gbk')
print s1 #打印正常否?
print s2 #打印正常否
print repr(s) #u'\u6797'
print repr(s1) #'\xe6\x9e\x97' 编码一个汉字utf-8用3Bytes
print repr(s2) #'\xc1\xd6' 编码一个汉字gbk用2Bytes
print type... |
8e616784d502fdcb9f874d394e8129137aaec025 | yungjas/Python-Practice | /even.py | 315 | 4.28125 | 4 | #Qn: Given a string, display only those characters which are present at an even index number.
def print_even_chars(str_input):
for i in range(0, len(str_input), 2):
print(str_input[i])
text = "pynative"
print("Original string is " + text)
print("Printing only even index chars")
print_even_chars(text) |
c628fe7ebf2e678bf24b8b32bb3537c3436f33b4 | esraazain/Parallel-Processing | /ParallelProject-main/Parallel rx part/db.py | 3,748 | 3.640625 | 4 | import sqlite3
from dataClass import News
command1 = """ CREATE TABLE IF NOT EXISTS firstData(
author text,
title text,
description text,
url text,
publishedAt text,
content text
);"""
command2 = """ CREATE TAB... |
f7956a024aab445d80c18b55921336dd9d5271f7 | syrenkafifi/naukaprogramowania | /semestr_2/quiz4/generator_pytan.py | 2,307 | 3.609375 | 4 | #importujemy pickle
import pickle
if __name__ == "__main__":
# prosimy o nazwe pliku gdzie zapiszemy wygenerowane pytania
sciezka_do_pliku = input("Podaj nazwe pliku gdzie zapiszesz pytania: ")
# sciezka_do_pliku = 'pytania'
lista_pytan = []
#dopoki nie wcisniemy k bedziemy generowac pytania
w... |
214a90d4252d0d4b904dbd85185465bc0192f8ad | DimetrikusK/Hyperskill | /Tic-Tac-Toe/Tic-Tac-Toe.py | 2,664 | 3.828125 | 4 | flag = -1
ceil = [[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']]
def print_board(ceil):
print("---------")
print('| {} {} {} |'.format(ceil[0][0], ceil[0][1], ceil[0][2]))
print('| {} {} {} |'.format(ceil[1][0], ceil[1][1], ceil[1][2]))
print('| {} {} {} |'.format(ceil[2][0], ceil[2][1], ceil[2][2]))
pr... |
da1b089a866869b0c29dfbd556917750e7307425 | DimetrikusK/Hyperskill | /Rock-Paper-Scissors/Rock-Paper-Scissors.py | 3,617 | 4.03125 | 4 | import random
def game(user_move, score):
paper = "paper"
rock = "rock"
scissors = "scissors"
computer = (paper, rock, scissors)
computer = random.choice(computer)
while user_move != "!exit":
if user_move == "!rating":
print(f'Your rating: {score}')
if computer == u... |
26cd68570e786943c6a0b9fb054b69a1f26fb491 | calvincramer/coding-presentations | /presentations/1/finished.py | 6,268 | 3.953125 | 4 | #!/usr/bin/python3
import time
# Default Dict
# Normal use of dictionary
my_dict = {}
for n in range(1000):
elm = n % 5
if elm in my_dict:
my_dict[elm] += 1
else:
my_dict[elm] = 1
print('Original:')
for k, v in my_dict.items():
print(f'{k} -> {v}')
# TODO Use defaul... |
9b58a83da4839d1953c0be5553825b23254ca430 | rpollock03/cs50-psets | /pset6/hello.py | 101 | 3.90625 | 4 | # Get user input
name = input("What is your name?\n")
# Print output
print("hello, {}".format(name))
|
85c4aac9111f46037dbba4530385b95615f51a24 | unixniu/pyAlgorithm | /imported/StackWithMin.py | 1,162 | 3.515625 | 4 | __author__ = 'william'
'''
ջݽṹҪһminܹõջСԪءҪminpushԼpopʱ临ӶȶO(1)
http://stackoverflow.com/questions/685060/design-a-stack-such-that-getminimum-should-be-o1
'''
class StackWithMin:
data = []
auxiliary = []
def push(self, val):
self.data.append(val)
if len(self.auxiliary) == 0:
sel... |
364c1474664f2bd98f540980a8f39e94b8be896f | 0xpython/CipherText | /algorithm.py | 904 | 4.09375 | 4 | #Mappings for each letter
from dictionary import *
#Algorith for Encryption
def encrypt(input):
encrypted_text = ''
for letter in input:
letter = letter.lower()
inum = index[letter] + shift
if inum > 27:
inum = inum - 27
encrypted_letter = index[inum]
encrypted_text = encrypted_text + en... |
d2b7c13ef108d7e67ff69446b236b73fe86d5360 | dscotton/worldtree_repo | /worldtree/statusbar.py | 2,851 | 3.578125 | 4 | """
Class for displaying information at the top of the screen.
Created on June 20, 2012
@author: dscotton@gmail.com (David Scotton)
"""
import os
import pygame
import environment
import game_constants
REGION_NAMES = {
'photosynthesis.ogg': 'High Branches',
'foreboding_cave.ogg': 'Ruins of Asg... |
60de3556e75cd9d000c62044979abb26741fc5e5 | NEHALGUPTA04/python-projects | /RollDiceSimulator.py | 428 | 4.09375 | 4 | import random
min_val = 1
max_val = 6
roll = input("Rolling the dice ???(yes or no) : ")
while True:
if roll== "yes":
print("Rolling The Dices...")
print("The Values are: ")
print(random.randint(min_val, max_val))
print(random.randint(min_val, max_val))
roll_again =... |
1a8438da17817a68e67b9dc11a69641aad123df8 | pranav6670/DS-and-Algo-implemetations | /Searching/linear.py | 148 | 3.671875 | 4 | a = [2, 3, 5, 6, 7]
def linear(z, x):
for i in range(len(z)):
if x == z[i]:
return i
return -1
print(linear(a, 7))
|
662c8193362ef1369c71e01f5a22207e924a32a6 | pranav6670/DS-and-Algo-implemetations | /math/first_last_digit.py | 213 | 3.6875 | 4 | import math
def firstDigit(n):
digits = int(math.log10(n))
n = int(n / pow(10, digits))
return n
def lastDigit(x):
return x % 10
n = 12345
print(firstDigit(n), end=" ")
print(lastDigit(n))
|
e343109ccceeba3a9650a7a8ab2d5d5e4a4ee919 | pranav6670/DS-and-Algo-implemetations | /math/num_digits.py | 411 | 3.765625 | 4 | from math import *
def num_digits_iterative(n):
count = 0
while n != 0:
n //= 10
count += 1
return count
print(num_digits_iterative(1021113))
def num_digits_recursive(n):
if n == 0:
return 0
return 1 + num_digits_recursive(n // 10)
print(num_digits_recursive(1021113)... |
b3a38002795e31527f6c6cf60921e4d02e194336 | basakrajarshi/EPI-Python | /LinkedList/ListNode.py | 698 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 13:54:48 2018
@author: rajar
"""
class ListNode:
def __init__(self, data = 0, next_node = None):
self.data = data
self.next_node = next_node
# Search for a key
def search_list(L, key):
while L and L.data != ke... |
6c45e66b756f8379c9a7c5b91792477cedde22b8 | colinmiller94/Project_Euler | /e46.py | 520 | 3.84375 | 4 | def is_prime(n):
if n < 2:
return False
if n == 2:
return True
i = 2
while i**2 <=n:
if n % i == 0:
return False
i += 1
return True
i = 9
stop = False
while not stop:
if is_prime(i):
i+=2
continue
j = 1
sq_term = 2 * j **... |
fdb55e99d873158b64498fee1ae073936ca34953 | colinmiller94/Project_Euler | /e56.py | 190 | 3.59375 | 4 |
max = 0
for a in range(1,100):
for b in range(1,100):
power = a**b
total = sum([int(i) for i in str(power)])
if total > max:
max = total
print(max) |
bbef8bcd58f4f7bb7c0249eb258df16bb7d5fcc8 | colinmiller94/Project_Euler | /e25.py | 338 | 3.890625 | 4 |
fib_dict ={}
def fibonacci(n):
if n in fib_dict:
return fib_dict[n]
if n == 1:
res =1
elif n == 2:
res = 1
else:
res = fibonacci(n-1) + fibonacci(n-2)
fib_dict[n] = res
return res
i = 1
while fibonacci(i) < 10**999:
#print fibonacci(i)
i +=1
print(fibo... |
8bb29d1bea6658d14ed0e4beb0330819f30ade77 | Bshiralilou/NUR2 | /one_c.py | 3,039 | 3.5 | 4 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import math
from one_b import normal_dist
#----- defining CDF of normal distribution
def normalCDF(x, mean, sigma):
return (1.0 + math.erf( (x - mean) / (np.sqrt(2.0) * sigma) )) * 0.5
#----- defining the sort fu... |
9068eb7eefeb6b1279f39fb237bf677e7865a1b4 | neonbadger/object-orientation-melons | /melons.py | 3,260 | 4 | 4 | import random, datetime
class TooManyMelonsError(ValueError):
"""Error when too many melons are ordered"""
def __init__(self):
"""initialize TooManyMelonsError using init method
from ValueError"""
super(TooManyMelonsError, self).__init__("No more than 100 melons!")
class AbstractMelo... |
878e7759ed852b18e61680e462e782934c55f198 | Tharakadhanushka/Monte-carlo-Simulation | /task_one_part_one.py | 1,278 | 3.65625 | 4 | import numpy as np
import random
def cal_possibility():
num_instances = 0
for dice1 in range(1,7):
for dice2 in range(1,7):
for dice3 in range(1,7):
for dice4 in range(1,7):
for dice5 in range(1,7):
for dice6 in range(1,7... |
64dfe70c6d41033e592b266b752961e298e89f16 | iculverr/PSet3 | /Q3.py | 1,063 | 3.734375 | 4 | import csv
import operator
File = open("/blue/bsc4452/share/Class_Files/data/CO-OPS__8729108__wl.csv", "r")
csvfile = csv.reader(File,delimiter=',')
sort = sorted(csvfile,key=operator.itemgetter(1))
a = sort.split(',')[1]
isitgreater=[]
line_num = 0
#Attempt at sorting specifically the water level column then finding t... |
e0d3f10a43a0aca02794b7665193c2be5ab5bc39 | d3fc0n1/algos | /102.binary_tree_level_order_traversal.py | 914 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[L... |
f392b8dca9dd8c809e20c64e867516530f7543de | snipzer/MathEpsi | /MathPython/dichotomi.py | 855 | 3.671875 | 4 | from math import exp, fabs
def f(x):
return (exp(x) - 2*x) - 3
def center(min, max):
return 0.5*(min + max)
def is_positif(x):
return x > 0
def is_negatif(x):
return x < 0
def is_inferior_range(min, max):
return (is_positif(f(min)) and is_negatif(f(center(min, max)))) or (is_negatif(f(min)... |
689c2548d367c6b27ccb3c7a69f63622d40a034f | ljcelib/CCNA_Dev | /Palindromo.py | 514 | 4 | 4 | num=int(input("Enter a number:"))
temp=num
rev=0
palin=0
while (num>0):
dig=num%10
#obtiene el ultimo numero de la variable num ------- saca el ultimo numero
rev=rev*10+dig
#Multiplica por 10 el
# ultimo valor de rev y le va aumntando el ultimo digito obtenido de num
num=num//10
#Eliminia e... |
83655407a288aa3d7c0192bc936e40eaaee5e22e | not-so-daily-practice/top-80-interview-algorithms | /strings_and_arrays/reverse_array_except_special.py | 554 | 4.15625 | 4 | def reverse_except_special(arr):
"""
Given an array, reverse it without changing the positions of special characters
:param arr: array to reverse
:return: reversed array
"""
arr = list(arr)
left = 0
right = len(arr) - 1
while left < right:
if not arr[left].isalpha():
... |
1688c1d301c19a630de76acefbcb36642ff9100d | not-so-daily-practice/top-80-interview-algorithms | /trees/maximum_sum_path.py | 1,057 | 3.9375 | 4 | curr = float("-inf")
def max_sum_path(root):
"""
Find path in tree that has largest sum possible
:param root: root node of tree
:return: max sum
"""
# base case
if root is None:
return 0
# recurse on left and right
left_sum, right_sum = max_sum_path(root.left), max_sum_pat... |
1ce26ff860b909d7f61db0e82b957103bc70519b | akshitsarin/python-files | /singlylinkedlistfinal.py | 1,587 | 4.34375 | 4 | # singly linked list final
class Node:
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
class LinkedList:
def __init__(self):
self.head = None # initialise head
def push(self, new_data):
new_node = Node(new_data)
... |
5e312195437fa17f05250debde43594bcf7e3f89 | afdecastro879/soccer_league | /main.py | 2,287 | 4.0625 | 4 | import fileinput
import sys
class SoccerLeague:
"""
Class to process a soccer league
"""
def __init__(self):
"""
Constructor method. It initializes an empty dictionary to hold the results
"""
self.results = {}
def add_result(self, match):
"""
Adds ... |
bfe4b65757dc94867be0a967a065830a2c7a54e5 | harshalitalele/ImageProcessing03 | /task2.py | 1,788 | 3.546875 | 4 | """
Denoise Problem
(Due date: Nov. 25, 11:59 P.M., 2019)
The goal of this task is to denoise image using median filter.
Do NOT modify the code provided to you.
Do NOT import ANY library or API besides what has been listed.
Hint:
Please complete all the functions that are labeled with '#to do'.
You are suggested to ... |
3afb937efff66a5dc57273be478e4591ca5bc4bf | kangbowen-927/KBW1112 | /login.py | 1,183 | 3.71875 | 4 | '''
编写一个程序,模拟用户注册,登录的数据库行为
'''
import pymysql
class User:
def __init__(self,database):
self.db = pymysql.connect(user = 'root',passwd = 'root',database = database,charset = 'utf8')
self.cur = self.db.cursor()
def register(self,name,passwd):
sql = "select * from user where name = %... |
6166067ee188ed7981f4add3ab0ceedd522ee38d | supvolume/codewars_solution | /5kyu/valid_parentheses.py | 371 | 4 | 4 | """ solution for Valid Parentheses challenge
find the valid order and number of parentheses"""
def valid_parentheses(string):
count = 0
for x in list(string):
if count < 0:
break
elif x == '(':
count += 1
elif x == ')':
count -= 1
if count == 0:
... |
550ae3935aaee4def1fa4c5d41472950d163000f | supvolume/codewars_solution | /6kyu/pyramid.py | 147 | 3.6875 | 4 | """ solution for Pyramid Array challenge"""
def pyramid(n):
floor = []
for i in range(n):
floor.append([1]*(i+1))
return floor |
f123538f0f80096aa5af0f27394d95d124767095 | supvolume/codewars_solution | /5kyu/make_readable.py | 496 | 4.09375 | 4 | """ solution for Human Readable Time challenge
convert second to human readable time"""
def make_readable(seconds):
HH = 0
MM = 0
SS = 0
SS = seconds % 60
minutes = seconds // 60
if minutes != 0:
MM = minutes % 60
hours = minutes // 60
if hours % 60 != 0:
HH ... |
1e20c6dddb10f9a9f819cbc9ab502cf7746ff931 | supvolume/codewars_solution | /5kyu/move_zeros_2.py | 362 | 4.09375 | 4 | """ solution for Moving Zeros To The End challenge"""
def move_zeros(array):
return_list = []
zero_list = []
for i in array:
if i == 0 and (type(i) == int or type(i) == float):
zero_list.append(i)
else:
return_list.append(i)
return return_list+zero_list
# test
... |
0cce8f2b81b2b0956c2fb2dca7444a352684d6b2 | supvolume/codewars_solution | /5kyu/move_zeros.py | 389 | 4.125 | 4 | """ solution for Moving Zeros To The End challenge
move zero to the end of the array"""
def move_zeros(array):
no_zero = []
zero = []
for a in array:
if a == "0":
no_zero.append(a)
elif (str(a) == "0.0" or str(a) == "0" or a == 0) and str(a) != "False":
zero.append(a... |
baff414c51cd0a61607cc40d494289a365f57bdd | supvolume/codewars_solution | /6kyu/fold_array.py | 534 | 3.84375 | 4 | """ solution for Fold an array challenge
sum the number of head with tail and sum the next number from head with previous number of tail
then if have middle number, append to the new array
repeat for runs times"""
def fold_array(array, runs):
for r in range(runs):
half = int(len(array)/2)
middle... |
9dc3a061623e04a76099e5e6dc55c1e4df91e032 | supvolume/codewars_solution | /7kyu/disemvowel.py | 304 | 4.09375 | 4 | # Solutions for Disemvowel Trolls challenge
def disemvowel(string_):
vowel = ['a', 'e', 'i', 'o', 'u']
no_vowel = []
for i in string_:
if i.lower() not in vowel:
no_vowel.append(i)
return ''.join(no_vowel)
print(disemvowel("This website is for losers LOL!"))
|
b7a5c24c85dbe1e8277dfb9f1b069ddb0c29b61a | johnphoward/coop_mornings | /weather.py | 1,069 | 3.84375 | 4 | # weather.py
# Get weather from Forecast API
import requests
import time
from geopy.geocoders import Nominatim
forecast_api_key = '1e51e3cae8556dc7c38f2881d074d957'
forecast_api_base = 'https://api.forecast.io/forecast/'
def getWeatherForAddress(address):
"""
Forecast API calls take the form below:
https://api.... |
ed6e826b892238502881c7260e5699f7c25312fa | dadams22/ChessEngine | /game.py | 3,840 | 3.890625 | 4 | """ This file should be run using python3 to start the game. """
import chess
from engine import *
class GameRunner():
""" Object to be created to run the game and store data. """
def __init__(self):
# Sets the board to a default board and sets the first turn to white
self.board = chess.Board()... |
37872afa235628ad4d5e7eabb1452bd349cfd0b4 | mlin367/RomanNumConversion | /RomanNumeral.py | 2,638 | 3.859375 | 4 | import re
def DecodeRomanNum(romanNum):
"""Decode roman numerals to normal numbers for values >0 and <4000"""
Definitions = {'MMM':3000, 'MM':2000, 'M':1000,
'CM':900, 'DCCC':800, 'DCC':700, 'DC':600, 'D':500, 'CD':400, 'CCC':300, 'CC':200, 'C':100,
'XC':90, 'LXXX':80, 'LXX':70, 'LX':60, 'L':50, '... |
db4ce0179b3ed8c7de80c25c72f9ddcc5281cad2 | arav02/tasklist_week1 | /ginortS.py | 362 | 3.765625 | 4 | s=input()
lower=[]
upper=[]
odd=[]
even=[]
a=sorted(s)
for i in a:
if i.islower():
lower.append(i)
elif i.isupper():
upper.append(i)
elif int(i)%2!=0:
odd.append(i)
else:
even.append(i)
lower=''.join(lower)
upper=''.join(upper)
odd=''.join(odd)
even=''... |
90277c45a669096b3dd174664aa3d1b4365e819f | provishalk/Python | /EXTRA/CountVolvels.py | 695 | 4.0625 | 4 | #This program Whill count number of vowel and consonant in name.
name = "Vishal Kumar"
#lengthOfString = len(name)
#i = 0
countVowel = 0
countConsonant = 0
for i in name:
print(i,end = '')
if i == 'a' or i == 'A' :
countVowel = countVowel + 1
elif i == 'e' or i == 'E' :
countVowel = countVo... |
2e3b67d3ce1177dec1e29f8c359773b528add74e | provishalk/Python | /EXTRA/WritingEx16.py | 638 | 3.84375 | 4 | from sys import argv
source , fileName = argv
print("Hello, today we are going to erase your file")
print("If you don't want to do that press control-c(c^)")
print("If you want to do that press enter")
input("?")
print("Opening the file")
txt = open(fileName,'w')
print("cotent erased")
#txt.truncate()
print("Enter t... |
68863a0fd52ddce4d306749ee22ca4e81cde8ba3 | provishalk/Python | /Linked List/LinkedList.py | 1,701 | 4.15625 | 4 | class LinkedList:
head = None
class Node:
def __init__(self, x):
self.value = x
self.next = None
def insert(self,value):
toAdd = self.Node(value)
if self.head == None:
self.head = toAdd
return
temp = self.head
while temp... |
899b9209fdddd08fbe4cd67d0a64fa2d5ffc18b8 | provishalk/Python | /Py_Sem_2/Python/CarPrivateExample.py | 910 | 4 | 4 | # class Car:
# # class variable , constant;
# carType = "HatchBack"
#
# def __init__(self,name,make):
# self.name = name
# self.make = make
#
# def toString(self):
# return f"This is a {self.name} carType is "
#
#
#
#
# c = Car("Polo", "Volkswagen")
# # print(Car("OOOO","AUDI").m... |
42ede3d64d9f2cf709a763054536d3deced56259 | hanghangzhang/python_learning | /fizzbuzz.py | 187 | 3.609375 | 4 | n=15
r=[]
for i in range(1,n+1):
if i%15==0:
r.append("FizzBuzz")
elif i%3==0:
r.append("Fizz")
elif i%5==0:
r.append("Buzz")
else:
r.append(str(i))
print r |
76f9c27e3ddcc3afc6e800a05882ff649f7d1ac2 | tristan1049/Dungeon-for-the-Bored | /Illustrations.py | 2,859 | 4.15625 | 4 | def dice1():
"""
Purpose: To make an illustration for the 1-side of a die
Output: List of each row in drawing
"""
rv = [" _______ ",
"| |",
"| * |",
"| |",
"|_______|"]
return rv
def dice2():
"""
Purpose: To make an illustratio... |
ed21dece61cf40afc5027108b770f345e7a66efb | adithimanjunath/Best-Enlist | /task8.py | 789 | 3.9375 | 4 | print("Choose the operation")
print("1 Addition \t 2 Subraction \t 3 Multiplication \t 4 Division")
c = int(input("Enter the choice "))
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
try:
if (c == 1):
d = a + b
except:
print("Not valid")
try:
if (c == 2):
... |
ba7cb756981686727f4c3c2722b3ac59fbf9d608 | yossibaruch/learn_python | /learn_python_the_hard_way/ex3.py | 855 | 4.34375 | 4 | # print some output
print "I will now count my chickens:"
# order of math
print "Hens", 25+30/6
# order of math
print "Roosters", 100-25*3%4
# print something
print "Now I will count the eggs:"
# math order, first multiply/div then add/sub, also what / and % do
print 3+2+1-5+4%2-1/4+6
# print something
print... |
b5886117f95e5062de50632a3267a8daf74a5972 | yossibaruch/learn_python | /learn_python_the_hard_way/ex11.py | 462 | 3.734375 | 4 | print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and weigh %r." % (age, height, weight)
print "How old are you?",
nage = int(raw_input())
print "How tall are you?",
nheight = i... |
31fcda60359c84eef9a6fe6bcc3b28b861fc5adb | yossibaruch/learn_python | /non-programmers/7-7BOOM.py | 324 | 3.90625 | 4 | print("""
# Ask user for integer
# Get user input
# print number from 1 to n,
# Substitute numbers divised by 7 or contain 7 as a digit with 'BOOM!'
""")
N = int(input("Please give me N so we can play 7BOOM: "))
for i in range(N):
if "7" in str(i) or i % 7 == 0:
print("BOOM!")
else:
print(str(... |
ece25778d428f34d312ed89566a52d317d4c3bf5 | yossibaruch/learn_python | /non-programmers/13-braces.py | 1,447 | 4.3125 | 4 | import string
print("""
# Iterate on characters from string
# Find opening braces and "remember" them in order
# Find closing braces and make sure it fits the last opening braces
# If "yes", forget last opening braces
# If "no", return False
# If memory of opening braces is not empty - return F... |
93591b970fa2e5f126666b380a5a155ba655b770 | realJDD/Python-Showcase | /PyBank/main.py | 2,625 | 3.78125 | 4 | # Dependencies
import csv
import os
# Specify the file
budget_csv = os.path.join("Resources", "budget_data.csv")
#Lists to store data
total_months = []
net_profit_loss = []
rate_of_change = []
#Open the CSV
with open(budget_csv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#Read the hea... |
d4a12ec70fa8c17f251d7461a7c83879ba16840f | harryw128/Anazaccrossespyton | /importingnames.py | 256 | 3.515625 | 4 | # opens crosses fill and read lines
with open('crosses.txt') as f:
lines = f.readlines()
print(lines)
# prints out names from txt file
# removes /n after all names
new_list = [s.replace("\n", "") for s in lines]
print(new_list)
# prints out new list
|
1d297eb9a23b1ce6ef69b6525e53ab355c5df9ac | Tarsiciosh/CS50A | /00_Search/02_tictactoe/tictactoe.py | 5,339 | 3.9375 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who h... |
6538b172081d329da0dce1813593e8cf79e8f2f1 | J00rdan/University | /Anul_2/IA/AI_Lab2/Algorithm/Entity.py | 766 | 3.71875 | 4 | '''
Created on Mar 17, 2020
@author: Razvan
'''
class BetweenTowns:
def __init__(self, muchieStart, muchieFinal, cost):
self.muchieStart = muchieStart
self.muchieFinal = muchieFinal
self.cost = cost
def get_muchie_start(self):
return self.muchieStart
def get_muchie_f... |
6228806152aae71c024208f94eb4a690f92ec1b6 | dbstein/apfft | /apfft/fft.py | 1,373 | 3.65625 | 4 | import numpy as np
import mpmath as mp
import apfft
def fft(yg):
"""
Performs an fft in arbitrary precision arithmetic
Arithmetic is implemented via the package mpmath
Precision should be set by setting the variable mp.mp.dps to the desired precision
Input:
yg: 1D numpy vector, with yg.shape[0... |
cf02ebbbb2aacc44685bc83f7e372d955bfef61e | susiewarchol/unit4_lesson5 | /problem7.py | 426 | 4.0625 | 4 | from turtle import *
import random
turtle = Turtle()
turtle.color("red")
turtle.pensize("5")
turtle.speed(5)
turtle.shape("turtle")
def drawstar():
for x in range(5):
turtle.forward(150)
turtle.left(144)
def row():
for x in range(3):
drawstar()
turtle.penup()
turtle.forward(60)
turtle.pendown()
for x ... |
7ed9e86432f2b1fdab6a00bf2f8d8e790a81c4c6 | FPU-CIS-312/Spring-2020-Mini-Project-2 | /MiniProject2_RodneyStogner_ChrisMehrtash_AbidanMartinez.py | 3,662 | 3.6875 | 4 | # Rodney Stogner, Chris Mehrtash, Abidan Martinez
# Recipe
regular_batch_of_brownies = 16
cups_of_sugar_per16_brownies = 1
sticks_of_butter_per16_brownies = 1
cups_of_flour_per16_brownies = 0.5
cups_of_unsweetenedcocoa_per16_brownies = 0.5
number_of_eggs_per16_brownies = 2
teaspoons_of_vanilla_per16_brownie... |
a14db8e1e2d329cca3ab6c87001b10343bba05f7 | aravindsrisai/project | /maxmin.py | 128 | 3.625 | 4 | def ara(n):
r=max(n)
print(f'maximum value {r}')
p=min(r)
print(f'minimum value {p}'}
n=[12,1,3,5,8]
r=ara(n)
print(r)
|
ed876ec74cfc89a60ebb891fae4ea303f0f20b8b | chrMenzel/tkinter | /database_example/database.py | 1,398 | 4 | 4 | import sqlite3
import os.path
class DB:
def initDB(self):
if not os.path.exists('sqldb.db'):
connection = sqlite3.connect('sqldb.db')
cursor = connection.cursor()
cursor.execute(
'''CREATE TABLE persons(name TEXT, forename TEXT)''')
return 'D... |
f4e768eb6cb7c92e53b3bc3901d3cf5827c7205d | jwgwalton/cvxgraph_public | /cvxgraph/tests/test_merge.py | 241 | 3.78125 | 4 | #!/usr/bin/env python3
import copy
g0={
1: {3,4},
3: {4,6,7},
4: {7},
6: {7}
}
g1={
0:{1,4},
1:{2},
2:{5},
5:{8},
8:{4}
}
g=copy.copy(g0) # needed
for i in g1:
g.setdefault(i,set()).add(g1[i])
print(g0)
print(g1)
print(g)
|
33a51e0a7999104ecd172f047c4db3e50845ef0a | AmmarAliHabib/github-demo | /math.py | 185 | 3.703125 | 4 | #Add
def add(x,y):
return x+y
#Subtract
def sub(x,y):
if(y>x):
return y-x
else:
return x-y
#multiply
def multiply(x,y):
pass
#divide
def divide(x,y):
pass |
2f9de45caa02b14ba917b1a23e8169da6645b3a4 | stoolrossa/OzriPythonSnippets | /UnitTests/mock_tests.py | 1,631 | 3.625 | 4 | import unittest
from mock import Mock
import datetime
import greeting as grt
class MyMockedTests(unittest.TestCase):
# test the greeting in the morning
def test_morning(self):
# mock the clock such that get_time passes back the time 9:52
clock = grt.Clock()
clock.get_time = Mock(retu... |
bf9ef92e2ba30730a514d7db1cde72709f49b276 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/examples/example_class3.py | 330 | 3.53125 | 4 | class Snake(object):
def __init__(self, name):
self.name = name
self.food = []
def eat(self, newfood):
self.food.append(newfood)
if __name__ == '__main__':
franz = Snake("Franz")
franz.eat("Apfel")
franz.eat("Maus")
franz.eat("Martin")
print franz.name
print f... |
5e286da0e4e0726d15320b8c42e819e54123284b | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Homework/Homework_Boni/Hundejahrerechner.py | 362 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
age = input("Alter des Hundes: ")
print
if age < 0:
print "Das stimmt wohl kaum!"
elif age == 0:
print "Das stimmt wohl kaum!"
elif age == 1:
print "entspricht ca. 14 Jahre"
elif age == 2:
print "entspricht ca. 22 Jahre"
elif age > 2:
human = 22 + (ag... |
cde4a7607e24dc0438be8f05de154cd3e5ccf817 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/Class16/Extra/BirthdaysReminder/birthdays.py | 733 | 3.53125 | 4 | import datetime
import operator
if __name__ == '__main__':
birthdates = {'Patrick':datetime.date(1987, 8, 22),
'Reini': datetime.date(1979, 12, 17),
'Boxi': datetime.date(1982, 1, 12),
'Thomas': datetime.date(1975, 11, 16),
'Marko': datetime.d... |
1fbc87a5b514de70a1ea92ae349fb08dae95e0ba | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/Class13-GUI/example_TKinter7_Show_MessageBox_On_Button.py | 768 | 3.59375 | 4 | import Tkinter
import random
import tkMessageBox
def show_msg_box():
tkMessageBox.showinfo("Result", "This is a messagebox")
# there is also showerror, showwarning
def show_warning_box():
tkMessageBox.showwarning("warning", "This is a warning!")
secret = random.randint(1, 100)
### TKINTER ELEMENTS ###
... |
ab7ac9f721ee6a9f7bea1fc512cbd7d5c7dc037e | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/Class10-Lottogenerator-Hauptstadtspiel/lottozahlen.py | 423 | 3.9375 | 4 | """Lottozahlen"""
import random
def lottozahlengenerator(zahlen):
Lottozahlenlist = []
zahlen = min([zahlen,49])
zahlen = zahlen if zahlen <= 49 else 49
while len(Lottozahlenlist) < zahlen:
zahl = random.randint(1, 49)
if zahl not in Lottozahlenlist:
Lottozahlenlist.append(za... |
2a893c36d94de96f0b197e6fd849fa00a11e36eb | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/PythonÜbungen/Kilometer in Meilen.py | 591 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
km = 1
meilen = 0.621371
print "Hi, ich helfe ihnen bei der Umrechnung von Kilometer in Meilen!"
while True:
try:
km = float(raw_input("Geben Sie die Kilometer als Zahl ein- Bei Dezimalzahlen verwenden sie Punkt: "))
print km * meilen,("Meilen")
... |
50018245c31e085a9a77ec467af79bfeeaff94be | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/examples/example_functions_lambda.py | 175 | 3.90625 | 4 | def add():
return lambda a,b: a+b
num1 = 10
num2 = 20
# add() returns a lambda function
adder = add()
print "add(%i,%i) returns: %i" % (num1, num2, adder(num1, num2))
|
81a223f209bd928365f397410e1a38c819503e0c | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Homework/6Homework 10.2 Guess the secret_random/SecretNumberGameRandom.py | 676 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
def generator():
secret = random.randint(1, 10)
while True:
try:
guess = int(raw_input("Errate die Geheimzahl bis 10:"))
if guess == secret:
print "Du hast es!"
print("Secret = " + st... |
882c85791e34ba7b7aaf5d84b8478159da495a4b | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/Class11-Klassen_Objekte/example_class_inheritance.py | 476 | 3.796875 | 4 | class Person(object):
def talk(self):
print 'I am a Person'
class Woman(Person):
def gender(self):
print 'I am female'
class Man(Person):
def gender(self):
print 'I am male'
if __name__ == '__main__':
anton = Man()
johanna = Woman()
# both classes have their own gen... |
1ce87822489b998406836e3d3d9e45e098c24f37 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/examples/Übung_TODO_program.py | 206 | 3.5625 | 4 | empty_list = []
print empty_list
list_with_items = ["erstes item", "zweites item", 34, 35.4]
print list_with_items
var1 = "first variable"
var2 = "second variable"
some_list = [var1, var2]
print some_list |
4dbef496f2b1a7f6a40083bb1851101865b2a8f0 | Muscularbeaver301/WebdevelopmentSmartNinja201703 | /Kursprojekte/Kursprogramm/examples/VehicleManager.py | 1,723 | 4.15625 | 4 | class Vehicle(object):
def __init__(self, brand, model, km, service_date):
self.brand = brand
self.model = model
self.km = km
self.service_date = service_date
def show(self):
print "{} {} {} {}".format(self.brand, self.model, self.km, self.service_date)
if __name__ == ... |
b1b08ca13b8f2875d692088e009198c100ec4a7c | seedbook/nlp100 | /1_8.py | 311 | 3.53125 | 4 | # -*- coding: utf-8 -*-
#お題の文章
sentence = "I am an NLPer"
#暗号化文章格納用
code = ""
#小文字をasciiコードに変換
for i in sentence:
if 97 <= ord(i) & ord(i) <= 122:
code += str(ord(i))
else:
code += i
#プリント
print code
|
2118ca9cb4b01dd409798932c764dc840ec22de1 | seedbook/nlp100 | /1_3.py | 537 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#お題の文章
sentence = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
#整形
sentence = sentence.replace(',', '')
sentence = sentence.replace('.', '')
#リストに分割
li_sentence = sentence.split(" ")
#リストの単語の文字数を格納するためのリスト
num_li_sentence = []
... |
311f8e570ef8b427d719da03cde2f0f515741a3b | fmaylinch/algorithms | /src/main/python/algorithms/exercises/GroupAnagrams.py | 490 | 3.96875 | 4 | import collections
def group_anagrams(words):
groups = collections.defaultdict(list)
for word in words:
key = make_counts_key(word)
groups[key].append(word)
return groups.values()
def make_counts_key(word):
count = [0] * 26
for c in word:
count[ord(c) - ord('a')] += 1
... |
fffbd08b8d1cc5a87319f1adce3d0a0330687229 | fmaylinch/algorithms | /src/main/python/algorithms/exercises/Sort3.py | 807 | 4 | 4 |
# Sorting a list with 3 unique numbers (1, 2, 3)
def sort3(list):
i = i1 = 0 # nums before i1 are 1's
j = j3 = len(list) - 1 # nums after j3 are 3's
def swap(a, b):
list[a], list[b] = list[b], list[a]
while i < j:
if list[i] == 1:
if i1 == i:
... |
87239ea114ccc5318be9527ef52343a59b250317 | fmaylinch/algorithms | /src/main/python/useful/UsefulPython.py | 5,237 | 3.9375 | 4 |
# Useful things to use when resolving algorithms.
# Type hints are optional.
from collections import OrderedDict, defaultdict, deque
import heapq
# from sortedcontainers import SortedList # https://pypi.org/project/sortedcontainers/
from typing import Dict, List, Set, Tuple
def lists():
# Creation
list1: L... |
05c7086567d61572fd0ff854d1fa49eac24f6796 | AdityaAshvin/amfoss-tasks | /task 2/codeforces/codeforces71A.py | 322 | 3.703125 | 4 | n = int(input())
for i in range(n):
word = input()
l = int(len(word))
if (l > 10):
first = word[0]
last = word[l-1]
final_word = (str(first)+str((l-2))+str(last))
print(final_word)
else:
print(word)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.