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 |
|---|---|---|---|---|---|---|
3e0e6bf77e7657a4acd451c63f61ad7c8e4beb61 | RevansChen/online-judge | /Codewars/6kyu/data-reverse/Python/solution1.py | 177 | 3.71875 | 4 | # Python - 3.6.0
def data_reverse(data):
b = 8
num = len(data) // b
rev = []
for i in range((num - 1) * b, -1, -b):
rev += data[i:i + b]
return rev
|
9a952d658f65dc3434e77079622434299fd61be0 | RevansChen/online-judge | /Codewars/6kyu/lotto-6-aus-49-6-of-49/Python/test.py | 1,356 | 3.609375 | 4 | # Python - 3.6.0
Test.describe('Basic tests')
winning_numbers = number_generator()
Test.assert_equals(len(winning_numbers), 7, 'The method must return an array of 7 numbers.')
Test.assert_equals(winning_numbers[6] >= 0 and winning_numbers[6] <= 9, True, 'The Superzahl must be between 0 and 9.')
Test.assert_not_equals(... |
e5d0fc7328d627df03132cce1b850b0c0636dffc | RevansChen/online-judge | /Codefights/arcade/intro/level-12/54.sumUpNumbers/Python/solution1.py | 111 | 3.5625 | 4 | # Python3
import re
def sumUpNumbers(inputString):
return sum(map(int, re.findall(r'\d+', inputString)))
|
48394dd68432ba18150e70a7c98a9ec8f5b0944e | RevansChen/online-judge | /Codewars/8kyu/crash-override/Python/solution1.py | 254 | 3.65625 | 4 | # Python - 3.6.0
def alias_gen(f_name, l_name):
f = f_name[0].upper()
l = l_name[0].upper()
if (f in FIRST_NAME) and (l in SURNAME):
return f'{FIRST_NAME[f]} {SURNAME[l]}'
return 'Your name must start with a letter from A - Z.'
|
c1d5a8b21107b2db3ea0dd327fd61172b2ae2736 | RevansChen/online-judge | /Codewars/5kyu/secret-knock/Python/solutions1.py | 779 | 3.5625 | 4 | # Python - 3.4.3
#def knock(arg=None):
# def openDoor():
# pass
# def lineCount():
# pass
# def deliverLine():
# if lineCount() == 2:
# openDoor()
# else:
# pass
# return deliverLine
# if arg == knock:
# print('"Knock knock."')
# print(... |
85ffa771570725eb6a1847dee8c4b23d45f5c4a7 | RevansChen/online-judge | /Codewars/7kyu/linked-lists-append/Python/test.py | 2,948 | 3.734375 | 4 | # Python - 3.6.0
def push(head, data):
newNode = Node(data)
newNode.next = head
return newNode
def build_one_two_three():
head = None
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
return head
def build_four_five_six():
head = None
head = push(head, 6)
head... |
6060deac305109612cb7786f9086c08885014f48 | RevansChen/online-judge | /Codefights/interview-practice/linked-lists/reverseNodesInKGroups/Python/solution1.py | 529 | 3.78125 | 4 | # Python3
# Definition for singly-linked list:
# class ListNode(object):
# def __init__(self, x):
# self.value = x
# self.next = None
#
def reverseNodesInKGroups(l, k):
curr, selected = l, []
while curr:
selected.append(curr)
if len(selected) >= k:
for left in range(k >> 1... |
a4048edd7ae866ca833da2e1adeaef73c1371169 | RevansChen/online-judge | /Codewars/4kyu/pyramid-slide-down/Python/solutions1.py | 226 | 3.515625 | 4 | # Python - 2.7.6
def longest_slide_down(pyramid):
for i in range(1, len(pyramid)):
x = pyramid[-i]
for j in range(len(x) - 1):
pyramid[-(i+1)][j] += max(x[j], x[j + 1])
return pyramid[0][0] |
d33fbba05b0955c65de664710be28d6d82987730 | RevansChen/online-judge | /Codefights/arcade/python-arcade/level-6/37.College-Courses/Python/test.py | 1,301 | 3.640625 | 4 | # Python3
from solution1 import collegeCourses as f
qa = [
(7, ['Art', 'Finance', 'Business', 'Speech', 'History', 'Writing', 'Statistics'],
['Art', 'Business', 'Speech', 'Statistics']),
(5, ['Botany', 'Earth', 'Public Water Works', 'Biology', 'Zoology', 'Combat'],
['Botany', 'Public Water Works', '... |
b38d0ed6eb44bd0941784115ee73b82fa62bab55 | RevansChen/online-judge | /Codefights/arcade/python-arcade/level-2/17.Permutation-Cipher/Python/solution1.py | 191 | 3.609375 | 4 | # Python3
# 有限制修改區域
def permutationCipher(password, key):
table = str.maketrans(''.join(map(chr, range(ord('a'), ord('z') + 1))), key)
return password.translate(table)
|
598d0d5e490e4ceebad9fee6162fc29e7ed62334 | RevansChen/online-judge | /Codewars/7kyu/pernicious-numbers/Python/solution1.py | 286 | 3.5625 | 4 | # Python - 3.6.0
pernicious = lambda n, isPrime = lambda n: (n == 2) or (n > 2) and (n & 1) and len([i for i in range(3, int(n ** 0.5) + 1, 2) if n % i == 0]) == 0: [i for i in range(3, __import__('math').floor(max(n, 0)) + 1) if isPrime(bin(i).count('1'))] or 'No pernicious numbers'
|
75f80147b1c2b3076bc37dfef532bc7b3cbf3993 | RevansChen/online-judge | /Codefights/arcade/intro/level-12/54.sumUpNumbers/Python/test.py | 565 | 3.65625 | 4 | # Python3
from solution1 import sumUpNumbers as f
qa = [
('2 apples, 12 oranges', 14),
('123450', 123450),
('Your payment method is invalid', 0),
('no digits at all', 0),
('there are some (12) digits 5566 in this 770 string 239', 6587)
]
for *q, a in qa:
for i, e in enumerate(q):
prin... |
13f91588f9fac26dcd1eede662f8529842ac069c | RevansChen/online-judge | /Codewars/6kyu/surrounding-primes-for-a-value/Python/solution1.py | 447 | 3.84375 | 4 | # Python - 2.7.6
def isPrime(num):
if (num == 2):
return True
if (num & 1) == 0:
return False
for i in range(3, int(num ** 0.5) + 1, 2):
if (num % i) == 0:
return False
return True
def prime_bef_aft(num):
befPrime = num - 1
aftPrime = num + 1
while not i... |
9dcfb71780adabfb6c474f6fa949c6476ac8e369 | RevansChen/online-judge | /Codewars/7kyu/sort-by-last-char/Python/test.py | 596 | 3.515625 | 4 | # Python - 3.6.0
Test.describe('Basic Tests')
Test.assert_equals(last('man i need a taxi up to ubud'), ['a', 'need', 'ubud', 'i', 'taxi', 'man', 'to', 'up'])
Test.assert_equals(last('what time are we climbing up the volcano'), ['time', 'are', 'we', 'the', 'climbing', 'volcano', 'up', 'what'])
Test.assert_equals(last('... |
3d0f6f445dc243abba3fc1b5ebcf7eb78547c967 | RevansChen/online-judge | /Codewars/8kyu/man-in-the-west/Python/solution1.py | 233 | 3.578125 | 4 | # Python - 3.4.3
def check_the_bucket(bucket):
# 逐一檢查bucket內是否有 'gold', 有則傳回True
for e in bucket:
if e == 'gold':
return True
# 若都沒有則傳回False
return False |
b95fd409c5e407c0a3e8ca3ba2472c11ad35aa96 | RevansChen/online-judge | /Codewars/8kyu/how-many-stairs-will-suzuki-climb-in-20-years/Python/solution1.py | 147 | 3.5 | 4 | # Python - 3.4.3
def stairs_in_20(stairs):
# 計算出一年走過的階梯數再乘上20
return sum(sum(stair) for stair in stairs) * 20
|
80f43b58cc71cf9dbae4442601127431d90abe79 | RevansChen/online-judge | /Codefights/arcade/intro/level-9/38.growingPlant/Python/solution1.py | 165 | 3.5 | 4 | # Python3
from math import ceil
def growingPlant(upSpeed, downSpeed, desiredHeight):
return max(1, ceil((desiredHeight - upSpeed) / (upSpeed - downSpeed)) + 1)
|
8e3503d951eda7daf48a55a2cab1a54826b55307 | RevansChen/online-judge | /Codewars/6kyu/area-of-a-shape/Python/test.py | 472 | 3.734375 | 4 | # Python - 3.6.0
import math
EPSILON = 0.01
def circular_area(x, y):
if (x - 0.5) ** 2 + (y - 0.5) ** 2 <= 0.25:
return True
return False
def full_shape(x, y):
if 0 < x < 1 and 0 < y < 1:
return True
return False
Test.expect(abs(area_of_the_shape(circular_area) - 0.25 * math.pi) <= ... |
45a784706ebcd497342651c63da65f40fc8bdcc9 | TarunSaraswat/Agile | /circle.py | 209 | 3.796875 | 4 |
def circlearea(r):
if r>0:
return r*3.14
else:
raise ValueError("Negative Radius Provided")
if __name__ == "__main__":
r=[1,2,46,-3,0]
for i in r:
print(circlearea(i)) |
7d6d389cf2ef185c629054350b9a38ec7c08c51a | gnmarten/pipe2py_test | /scraper.py | 2,949 | 3.65625 | 4 | import scraperwiki,urllib,json,simplejson
# pipe2py test
# This minimal example shows how to grab a Yahoo pipe json definition, then compile and run the pipe in process
#(example lifted more or less from https://github.com/ggaughan/pipe2py/blob/master/compile.py )
# Thoughts:
##1) populate a scraperwiki table with p... |
a1f9b67547501ca47b38b8f56a6106c8a05952bd | PyFilesystem/pyfilesystem2 | /examples/find_dups.py | 473 | 3.53125 | 4 | """
Find paths to files with identical contents.
Usage:
python find_dups.py <PATH or FS URL>
"""
import sys
from collections import defaultdict
from fs import open_fs
hashes = defaultdict(list)
with open_fs(sys.argv[1]) as fs:
for path in fs.walk.files():
file_hash = fs.hash(path, "md5")
... |
2bdcf0983d36b227ebfea1cd78b163ff3cfd0530 | playgamelxh/ML | /test/pandas_test.py | 260 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
if __name__ == "__main__":
dates = pd.date_range('20181123', periods=6)
print(dates)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
|
e9f7b429443920c2a26366b8f44a570b2ce20878 | playgamelxh/ML | /other/KNN/index.py | 2,772 | 3.53125 | 4 | # encoding=utf-8
'''
脚本说明:kNN算法,分类器
'''
import numpy as np
import operator as oper
import collections
import matplotlib.pyplot as plt
'''
函数说明:构造数据
'''
def createData():
data = np.array([[1, 2], [2, 3], [7, 8], [9,8]])
labels = [1, 1, 2, 2]
return data, labels
'''
函数说明:特征缩放
最大值法:X/最大值,分布到[0, 1]之间
均值归一:(X-... |
d19c258239fcc7203b21139d5fb0bf82cf7df6cf | amaltaro/ProductionTools | /dupFiles.py | 1,305 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Scan two directories and prints the name of the files found in both directories
"""
from __future__ import print_function, division
import sys
import os
from pprint import pprint, pformat
def main():
mainDir = "/Users/amaltaro/Pictures/Bento/"
listDirs = os.lis... |
2d1d1e4146a8ef9dad3a0e0829085db0d8bc0345 | orvindemsy/coursera-machine-learning | /coursera-ml-homework-py/ex4-Neural_Network_Learning/ex4.py | 19,605 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Exercise 4: Neural Networks Learning
# In[1]:
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame as dframe
# ## Neural Network
# ### Visualizing the Data
# In[2]:
# Setup the parameters you wi... |
94749c839b49c4d0a4b3325c65b62ce4b4a6971e | gzhdev/data_struc_test_01 | /LinearList/ex_sll_01.py | 2,352 | 3.765625 | 4 | # 节点类描述
class Node(object):
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# 单链表类描述
class LinkList:
def __init__(self):
self.head = Node() # 构造函数初始化头节点
def creat(self, l, order):
if order:
self.creat_tail(l)
else:
... |
635cb1cd5edd91462cc29e31efa3aa68b9a50dfc | CommanderTvis/wandering-without-intersections | /cli.py | 420 | 3.53125 | 4 | from main import probability
_is_debug_input = input("Turn on debug mode (y/n)? ")
if _is_debug_input == "y":
is_debug = True
_n_times_input = int(input("Enter the quantity of times to run the algorithm: "))
_size_of_field_input = int(input("Enter the size of field: "))
_probability = probability(_n_times_input,... |
0035e656e85b20301a152c8e982c6b296c269c6a | sdarbucks/pyworks | /day32/re_ex/re_ex2.py | 321 | 3.859375 | 4 | # group()은 매치된 문자열을 돌려준다.
# start()은 시작위치
# end()는 끝위치
# span()은 (시작, 끝) 튜블 구조
import re
p = re.compile('[a-z]+')
m = p.match("hello")
print(m.group()) # 문자열
print(m.start()) # 시작위치 0
print(m.end()) # 끝 위치 5
print(m.span()) # (0, 5)
|
16601a5729847fb073643b1ab2a571600586eec9 | ismpere/Python-Examples | /Práctica 1/practice-python-1.py | 1,399 | 3.65625 | 4 | #Extrae la dimensión de la sopa de entrada.
def extrae_dimension(soup):
"""Extrae la dimensión de la sopa de números"""
return soup.count('\n') + 1
#Devuelve el caracter en la posicion [fila, columna] de la sopa, dada la dimension de la misma
def char_at_position(soup, dim, fila, columna):
return soup[(dim... |
d19bec2ebdbc2f6879ec01d8b9910bd0c1096194 | archimonde-code/pyspace | /NumberType/string.py | 280 | 3.984375 | 4 | '''
list_string = []
dict_string = {}
i = 1
while i <= 3:
lists = input("请输入第"+str(i)+"字符:\n")
list_string.append(lists)
i += 1
print(list_string)
'''
M = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
cole = [row[2] for row in M]
print(cole)
dicts = {}
|
9d5340bc48eadae0695b625e18f68af8915f9ce8 | mnavaidd/Python-Practice | /function.py | 173 | 3.578125 | 4 | def greetuser():
person = input("Enter your name")
print("Hello", person,"!")
greetuser()
def sumnumbers(a,b):
return a + b
sum = sumnumbers(5,5)
print(sum)
|
1f32946d0984382376f2e97ea455b759fb8b8832 | mnavaidd/Python-Practice | /Assigment/20Jan2018.py | 610 | 3.640625 | 4 | def build_person(first_name, last_name, age=''):
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', '27')
artists = build_person('nasir', 'asad')
print(musician)
print(artists)
##
def make_album(artist_name, artist... |
7e5d15b64766fd912fcd0211336fc43f461a792e | ducang/python | /session9/mh1.py | 165 | 3.921875 | 4 | color = ['red','blue','white']
print('Our color list:')
print(*color,sep=',')
color.append(input('Enter new color:'))
print('New color list:')
print(*color,sep=',') |
cfc9d5eebdb755df25763e4848a024b52d7f8a32 | ducang/python | /session8/word_guessing.py | 1,461 | 3.875 | 4 | from random import shuffle
from random import choice
fruit = ['apple', 'orange', 'grape', 'guava']
point = 0
while True:
i = choice(fruit)
if i == 'apple':
char = list(i)
shuffle(char)
print(*char,'\n', sep='')
a = input('what is it?')
if a == 'apple':
... |
51aa3ba6d3a00bac27d769173f52009b3323672a | ducang/python | /session2/con_rua.py | 235 | 3.796875 | 4 | from turtle import *
shape("turtle")
color("green")
for i in range(10000):
forward(100)
left(90)
forward(100)
left(90)
left(90)
forward(100)
left(90)
forward(100)
left(1)
speed(-1)
mainloop()
|
2f9d4ac69211dc5a62ae0243de16cf95c66dfa7c | ducang/python | /session7/p1/mh4.py | 103 | 3.796875 | 4 | from turtle import *
radius= int(input("enter raidus:"))
shape("turtle")
circle( radius )
mainloop () |
9a4374b3e3d6ef7651fdfbcd279af9c0d7cb2556 | ducang/python | /session5/validate_input.py | 749 | 4.1875 | 4 | '''check ten ko co so'''
# while True :
# name = input("enter your name:")
# if name.isalpha() :
# break
# else:
# print("error, please enter a valid name.")
'''check pass co chua so'''
# while True:
# pas= input("enter password:")
# if pas.isalpha():
# print("password must... |
574429f546856a9c5988352cddb22a191cfea714 | stormning/learn-python | /dict.py | 362 | 4.0625 | 4 | mydict = {'name': 'storming', 'age': 16}
print mydict['age']
name = (["first", "Google"], ["second", "Yahoo"])
print dict(name)
print mydict.keys()
print mydict.values()
print mydict.items()
for k in mydict:
print mydict[k]
print [mydict[k] for k in mydict]
print mydict.get("name")
mydict.pop("name")
prin... |
0505938ba64330d91dae96c73e3ee52e1c7e345c | satyakamuju72/ML_Lab | /week2/exp2.py | 1,085 | 3.546875 | 4 | import mysql.connector
#create database
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mllab")
#Create table
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mllab"
... |
191ce4a91dde400ff43493eea3a1b1a4f9ea08c9 | HaminKo/MIS3640 | /OOP/OOP3/Time1.py | 1,646 | 4.375 | 4 | class Time:
"""
Represents the time of day.
attributes: hour, minute, second
"""
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def print_time(self):
print('{:02d}:{:02d}:{:02d}'.format(self.hour, self... |
04c359f3e674466994f258820239885690299c21 | HaminKo/MIS3640 | /session10/binary_search.py | 1,143 | 4.1875 | 4 | import math
def binary_search(my_list, x):
'''
this function adopts bisection/binary search to find the index of a given
number in an ordered list
my_list: an ordered list of numbers from smallest to largest
x: a number
returns the index of x if x is in my_list, None if not.
'''
pass
... |
42f4fe057bd6951563d205d62ffa130259af1294 | HaminKo/MIS3640 | /session08/exercise2.py | 312 | 3.953125 | 4 |
# word = 'New England Patriots'
# count = 0
# for letter in word:
# if letter == 'a':
# count = count + 1
# print(count)
def counter(word, letter):
count = 0
for l in word:
if l == letter:
count = count + 1
return count
# print(counter("a", "New England Patriots")) |
f17d59ca9bfa82848ec6a599e98f759449ccdd14 | ofirhodara/MySpecailCalculator | /test_extra.py | 8,479 | 3.53125 | 4 | """
test_extra.py:
In this file i wrote extra tests to my calculator program.
Divided to some main parts:
- Math Errors Tests (divide in zero, factorial, complex numbers)
- Test with edge cases of minus (operator / sign)
- Big results tests: expression that their result
... |
9f41d6f167198d34c0d80ea08f117ca0cbccd70f | grayrhinos/competitive_programming | /best_practices.py | 2,721 | 4.0625 | 4 | # Relatively fast way to read line in CodeForces
# Tip #1
'''
- Use alias for the functions that are called too many times.
* 'Local variable lookups are much faster than global or built-in variable lookups: the Python "compiler" optimizes most function bodies so that for local variables,
no dictionary lookup is nece... |
141f785e4f38f575455188ebd08ec8c39609edd9 | AhmedKhalil777/courses | /data_structures_and_algorithms/Thebes-1st-2018-2019/Lectures/Lecture-03/Student.py | 264 | 3.640625 | 4 | # بسم الله الرحمن الرحيم
class Student:
def __init__(self,id, name):
#print('A new object has been created')
self.id = id
self.name = name
def attend_lecture(self):
print('I have attended a Lecture')
|
7687f8e58712ee7631f492e13e3f289baf1a121a | AhmedKhalil777/courses | /data_structures_and_algorithms/Thebes-1st-2018-2019/Lectures/Lecture-07/array_replacement.py | 255 | 3.84375 | 4 | # بسم الله الرحمن الرحيم
# -*- coding: utf-8 -*-
a = []
for i in range(10):
x = int(input())
if x <= 0:
a.append(1)
else:
a.append(int(x))
for i in range(10):
print("X[{}] = {}".format(i,a[i])) |
47b9e54b2b400bf8981920e4924a38c8091392ac | AhmedKhalil777/courses | /data_structures_and_algorithms/Thebes-1st-2018-2019/Lectures/Lecture-06/run.py | 1,163 | 4.3125 | 4 | # بسم الله الرحمن الرحيم
from Set import Set
mahmoud = Set()
mahmoud.add("CSCI-112")
mahmoud.add("MATH-121")
mahmoud.add("HIST-340")
mahmoud.add("ECON-101")
Eslam = Set()
Eslam.add("POL-101")
Eslam.add("ANTH-230")
Eslam.add("CSCI-112")
Eslam.add("ECON-101")
# Determine if two students are taking:
common_courses... |
faa4c791cbb6ec7257810bd7cf3c8a5077448cbe | Titowisk/estudo_python | /exercicios_estagio/vetores_3.py | 813 | 3.6875 | 4 | # coding=utf-8
# 3. Tentando descobrir se um dado era viciado,
# um dono de cassino honesto (ha! ha! ha! ha!) o lançou n vezes.
# Dados os n resultados dos lançamentos, determinar o número de ocorrências de cada face.
import random
list_results = []
dice_faces = [1, 2, 3, 4, 5, 6]
ocurrences = [0, 0, 0, 0, 0, 0]
... |
048d6f09f5f60f6ce6d2f7212cf6955dc9cb0e87 | Titowisk/estudo_python | /exercicios_estagio/vetores_2.py | 1,459 | 4.03125 | 4 | # coding=utf-8
"""
2. Deseja-se publicar o número de acertos de cada aluno em uma prova em forma de testes.
A prova consta de 30 questões, cada uma com cinco alternativas identificadas por
A, B, C, D e E. Para isso são dados:
o cartão gabarito;
o número de alunos da turma;
o cartão de respostas para ca... |
2730c8b241f4ab4bccae41b5e9fac189958890df | Titowisk/estudo_python | /book_mark_summerfield/cap04/list_keeper.py | 3,546 | 3.6875 | 4 | import os
def main():
print("\nList Keeper Software\n")
filename, filename_items = get_file()
def get_file():
all_files = os.listdir(".") # returns a list of all filenames
lst_files = [x for x in all_files if x.endswith(".lst")] # creates a list of strings with all filenames that ends with .lst
... |
0757693b76c6ccf62eb380198ab10365d6a2c016 | Titowisk/estudo_python | /meus_programas/04-desafio1.py | 457 | 4.15625 | 4 | # coding: utf-8
#desafio 1
#nome = input("Digite seu nome: ")
#print("Bem-vindo", nome)
#desafio 2
#dia = input("Digite o dia do seu nascimento: ")
#mes = input("Digite o mês do seu nascimento: ")
#ano = input("Digite o ano de seu nascimento: ")
#
#print("Você nasceu em", dia,"/",mes,"/",ano)
#desafio 3
a = float(i... |
0a20ce2debd205be607be028c4832206d395ec97 | Titowisk/estudo_python | /meus_programas/letter_counter.py | 344 | 3.671875 | 4 |
def letterCounter(inputString):
letter_quantity = dict()
for l in inputString:
if l not in letter_quantity:
letter_quantity.setdefault(l, 1)
else:
letter_quantity[l] += 1
return letter_quantity
answear = letterCounter('titowisk')
print(answear)
for k in answea... |
cbe5a94fb692b559fc0f3f69c5f1d42bef953b19 | Titowisk/estudo_python | /book_al_sweigart/cap07/localizador.py | 1,760 | 3.546875 | 4 | # coding=utf-8
#Author: Vito Ribeiro
# This program is for searching e-mails and phone numbers (Brazil) and return
# what is found.
# Common Mobile Phonenumber from Brazil: 55 (71) 9 9956-5726
# Common Phonenumber from Brazil: 55 (71) 3382-9364
# Common e-mail: something@something.com.br
import pyperclip
import re
... |
21c43fdd0d170d446643789a4cccf629c61cfb65 | Titowisk/estudo_python | /machine_learning/decision_tree_movies_genre.py | 178 | 3.546875 | 4 | import panda as pd
names = ['Gender', 'Age', 'Genre']
df = pd.read_csv('movies.data', names=names)
print("Linhas: {}, Colunas: {}".format(len(df), len(df.columns)))
df.head() |
5152c50255dec22d48d3484a0ac69ff2114711d4 | junyeong-youn/Jungle_feat.JY | /Algorithm/WEEK01/7.py | 94 | 3.53125 | 4 | a = int(input())
n = 0
while n<9:
n = n + 1
i = a*n
print("%d * %d = %d"%(a,n,i))
|
4f61007f65cf300163942f785ac9d56993972474 | junyeong-youn/Jungle_feat.JY | /Algorithm/WEEK01/9.py | 71 | 3.609375 | 4 | a = int(input())
n = 0
while n < a :
n+=1
x="*"*n
print(x)
|
88a39d8c6d882f4f297a608dc6445c900d60e7bd | jdogg6ms/project_euler | /p058/p58.py | 2,057 | 3.921875 | 4 | #!/usr/bin/env python
# Project Euler Problem #58
"""
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 ... |
cc9cf015699a1a295f847c7a2c848f6d1c23360b | jdogg6ms/project_euler | /p030/p30.py | 1,127 | 3.96875 | 4 | #!/usr/bin/env python
# Project Euler Problem #30
'''
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers ... |
fb16eda74a1e4ab4b412c9b206273839e3c8049c | jdogg6ms/project_euler | /p009/p9.py | 885 | 4.1875 | 4 | #!/usr/bin/env python
# Project Euler Problem #9
"""
A Pythagorean triplet is a set of three natural numbers.
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from math import sqrt
def test_triplet(a,b,c):
re... |
ebe3b0e5d231f08a77d283015b439f0e5922ae61 | jdogg6ms/project_euler | /p046/p46.py | 1,666 | 4.03125 | 4 | #!/usr/bin/env python
# Project Euler Problem #46
'''
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2*1^2
15 = 7 + 2*2^2
21 = 3 + 2*3^2
25 = 7 + 2*3^2
27 = 19 + 2*2^2
33 = 31 + 2*1^2
It turns out that the conjecture was fal... |
7fb5dc2f16515efb5a17a578f5f85626999967a3 | jdogg6ms/project_euler | /p029/p29.py | 981 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project Euler Problem #29
"""
Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any re... |
98fc973d836094280cad746c8fa12b46efcbcc50 | jdogg6ms/project_euler | /p044/p44b.py | 1,295 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project Euler Problem #44
"""
Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 22 = 48, is not p... |
9b8a2b5e764a6267c9668ec042133e9dfb99d227 | jdogg6ms/project_euler | /p022/p22.py | 847 | 3.625 | 4 | #!/usr/bin/env python
# Project Euler Problem #22
def string_value(string,dict,index):
name = map(str.lower,[char for char in string.strip('""')])
return index * sum([dict[char] for char in name])
if __name__ == "__main__":
#build dictionary of alphabet values
alphaValue = {}
for i... |
b6d07a114a7340347edc365a30bc486c75b81569 | UW-ParksidePhysics/python-functions-and-branching-PeterK-UWP | /f2c.py | 279 | 3.53125 | 4 |
def C(F):
C = (5.0/9) * (F - 32)
return C
dF = 10
F = 68
print(f'{"F":>5s} {"C(F)":>5s}')
while F <= 100:
print( '%5.1f %5.1f' % (F, C(F)))
F += dF
print('-----')
def F(c):
F = ((9.0/5) * c) + 32
return F
c = 4
print(f'{"C(F(c))":>3}')
print('%5.1f' % (C(F(c))))
|
8450b0665e2176a6d4fb451d85309c4cde5d3087 | william-dvlpr/python3-cv2 | /exercises/ex041.py | 263 | 3.9375 | 4 | idade = int(input('Qual a sua idade? '))
print('Sua categoria é', end=' ')
if idade <= 9 :
print('Mirim.')
elif idade <= 14 :
print('Infantil.')
elif idade <= 19 :
print('Junior.')
elif idade <= 20 :
print('Sênior.')
else:
print('Master.') |
8ea5df2fa0184be47fa0d6a4136d392a65664997 | cavallera2000/ML_email_classifier | /model_eval.py | 6,736 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import re
import time
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords, wordnet
from string import punctuation
from nltk.stem import WordNetLemmatizer
from nltk.tag import pos_tag
from n... |
8eed6d615beb2485f99026cfddd566b9051748b8 | utk09/open-appacademy-io | /1_IntroToProgramming/2_Arrays/7_reverse_range.py | 536 | 4.09375 | 4 | """
Write a method reverse_range(min, max) that takes in two numbers min and max. The function should return an array containing all numbers from min to max in reverse order. The min and max should be excluded from the array
"""
def reverse_range(minimum, maximum):
new_range = []
new_nums = []
for i in ra... |
3513114b3ba94e2481ac242c87d4c5488a55cffa | utk09/open-appacademy-io | /1_IntroToProgramming/1_Loops/4_sum_nums.py | 340 | 3.953125 | 4 | # Write a method sum_nums(max) that takes in a number max and returns the sum of all numbers from 1 up to and including max.
def sum_nums(max_val):
count = 0
for i in range(max_val+1):
count = count + i
return count
print(sum_nums(4)) # prints 10
print(sum_nums(5)) # prints 15
print(sum_nums(1... |
446ec5e2a5dbd48dc3bdbef44b7ff3fdf1ac21a3 | utk09/open-appacademy-io | /1_IntroToProgramming/3_Enumerables_Ranges/2_first_in_array.py | 446 | 4.0625 | 4 | """
Write a method first_in_array that takes in an array and two elements, the method should return the element that appears earlier in the array.
"""
def first_in_array(arr, el1, el2):
if arr.index(el1) < arr.index(el2):
return el1
else:
return el2
print(first_in_array(["a", "b", "c", "d"],... |
0f8bc6d325c0e7af4cae255b3815e10be59148cb | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/10_prime_factors.py | 1,096 | 4.1875 | 4 | """
Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number.
"""
def prime_factors(number):
final_list = []
prime_list_2 = pick_primes(number)
for each_value in prime_list_2:
if number % each_value == 0:
final_lis... |
6ea5413956361c5ce26f70079caefca87f352112 | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/14_sequence.py | 1,120 | 4.46875 | 4 | """
A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in a two numbers: start and length. The method should return... |
daefcebae519c3511728968bd9d82cca2a802c92 | utk09/open-appacademy-io | /1_IntroToProgramming/4_Nested_Loops_2D_Arrays/3_two_d_sum.py | 491 | 4.09375 | 4 | """
Write a method two_d_Sum that takes in a two dimensional array and returns the sum of all elements in the array.
"""
def two_d_sum(arr):
sum_all = 0
try:
for i in arr:
for j in i:
sum_all = sum_all + j
return sum_all
except:
return "Please Enter a 2D... |
88f52244e93514f9bab7cbfb527c1505f298925b | utk09/open-appacademy-io | /1_IntroToProgramming/2_Arrays/2_yell.py | 481 | 4.28125 | 4 | # Write a method yell(words) that takes in an array of words and returns a new array where every word from the original array has an exclamation point after it.
def yell(words):
add_exclam = []
for i in range(len(words)):
old_word = words[i]
new_word = old_word + "!"
add_exclam.append(... |
f737fe1edc1d4837154537fd3e8a55da0ada12c7 | utk09/open-appacademy-io | /1_IntroToProgramming/6_Advanced_Problems/1_map_by_name.py | 895 | 4.125 | 4 | """
Write a method map_by_name that takes in an array of dictionary and returns a new array containing the names of each dictionary key.
"""
def map_by_name(arr):
map_list = []
for each_dict in range(len(arr)):
map_dict = arr[each_dict]
for key, value in map_dict.items():
if key =... |
ac6ddb7a5ff88871ed728cc8c90c54852658ce30 | utk09/open-appacademy-io | /1_IntroToProgramming/2_Arrays/12_sum_elements.py | 586 | 4.15625 | 4 | """
Write a method sum_elements(arr1, arr2) that takes in two arrays. The method should return a new array containing the results of adding together corresponding elements of the original arrays. You can assume the arrays have the same length.
"""
def sum_elements(arr1, arr2):
new_array = []
i = 0
while i... |
62ce0f61beda367fc19f6980a51f7e341217b473 | daithimarkham/Pands-Problem-Set | /solution-1.py | 832 | 4 | 4 | # David Markham 2019-02-17
# Solution to problem number 1
# Write a program that asks the user to input any positive integer
# And outputs the sum of all numbers between one and that number.
# Asks the user to input a positive integer number
i = int(input("Please enter a positive integer"))
# This will prevent the u... |
6a11b6edb17d6abc4a0fdef4102b79d693ab2008 | QuangTrungNguyen/INFT1004 | /Programming Project.py | 14,684 | 3.640625 | 4 | # INFT1004 Introduction to Programming - Assignment 1
# Task: Fix the QR codes that the question provided.
# Author: Nguyen Quang Trung & Cheng Zixin
# Start Date: 24 Feb 2014
# End Date: 18 March 2014
def fixCodes(size):
# Run each of the required functions in turn, displaying the resulting QR codes at the given s... |
ea38595e24f1e41a78189dfa3cafce54c0c31945 | MAviles-Baquero/CPSC322_Project | /mysklearn/mypytable.py | 26,178 | 3.9375 | 4 | # Name: Tristan Call
# Assignment: PA4
# Date: 2/28/20
# Description: This mypytable is a table designed to hold a number of rows
import copy
import csv
import math
import re
import mysklearn.myutils as myutils
from tabulate import tabulate # uncomment if you want to use the pretty_print() method
# install... |
d6382fcf0172d9856e9c3a0fa0974f11bac1f051 | mmirovic/advent-of-code-2017 | /puzzle17/puzzle17.py | 985 | 3.671875 | 4 | #!/Users/mmirovic/venv/bin/python3
# Advent of code 2017 by mmirovic
def part1(data):
l = [0]
i = 0
for el in range(1, 2018):
i = (i + data) % len(l)
l = l[:i+1] + [el] + l[i+1:]
i += 1
return l[i+1]
def part2(data):
# pre-allocate memory
iter = 50000000 + 1
l... |
74392a19ef39af9e1142021eb5bfdd5dd627f6b7 | jaclynmariefrench/Python-Server | /models/customer.py | 347 | 3.671875 | 4 | class Customer:
"""class for new customer dictonary"""
def __init__(self, id, name, address, email= "", password= ""):
self.id = id
self.name = name
self.address = address
self.email = email
self.password = password
new_customer = Customer(
6, "John Smith", "111 So... |
205556a3bd7809b4c6231afc111a3948103685dd | gcoffin/pyorbital | /gameloop.py | 4,053 | 3.625 | 4 | import pygame
from pygame.locals import *
ONCE_IN_A_WHILE=10
KEYPRESSED_EVENT=42
SCREEN_WIDTH, SCREEN_HEIGHT = (1200, 800)
'''a simple game framework that provides some support
to manage events and the loop'''
class eventhandler(object):
def __init__(self):
self.map={}
self.pressedkeys=set()
... |
198b82e6959454bbaac57664873745e3838a0111 | CirXe0N/AdventOfCode | /2020/08/python/puzzle_02.py | 1,137 | 3.546875 | 4 | def run_instructions(instructions):
accumulator = 0
position = 0
visited = []
while True:
try:
instruction = instructions[position]
operation, argument = instruction.split(' ')
if operation == 'acc':
accumulator += int(argument)
... |
9984fe1d6be5fb9535faf51077db0208a6148e57 | CirXe0N/AdventOfCode | /2020/02/python/puzzle_01.py | 616 | 3.71875 | 4 | def calculate_valid_passwords(lines):
amount_valid = 0
for line in lines:
policy, password = line.split(': ')
letter = policy[-1]
min_occurrence, max_occurrence = policy[:-2].split('-')
min_occurrence = int(min_occurrence)
max_occurrence = int(max_occurrence)
co... |
21cda70292078b48532e2d8a3659d6ed217b6075 | CirXe0N/AdventOfCode | /2019/01/puzzle_02.py | 474 | 3.84375 | 4 | import math
def calculate_fuel(amount: int) -> int:
return math.floor(amount / 3) - 2
def calculate_module_fuel(mass: int) -> int:
fuel = mass
module_fuel = 0
while fuel > 0:
fuel = calculate_fuel(fuel)
module_fuel += fuel if fuel > 0 else 0
return module_fuel
total_fuel = 0
... |
990606d7308fe1e5db2f129225c4b3b88bfb899e | emmas0507/lintcode | /valid_palindrome.py | 626 | 3.875 | 4 | def valid_palindromen(str):
flag = True
i = 0
j = len(str) - 1
while i <= j:
if not str[i].isdigit() and not str[i].isalpha():
i = i + 1
elif not str[j].isdigit() and not str[j].isalpha():
j = j - 1
else:
print('position i is {} and position j ... |
d97407dd2166f3c08a96600a7941a1ef0120634e | emmas0507/lintcode | /sum_of_square_numbers.py | 380 | 3.953125 | 4 | import numpy as np
def sum_of_square_numbers(n):
if n < 0:
return False
else:
k = int(np.floor(np.sqrt(n/2)))
for i in range(k, 0, -1):
if i * i == n:
return True
else:
j = np.sqrt(n - i*i)
if j * j + i * i == n:
return Tru... |
5d6d300e04d055f8752c7a201ee8d44acba2a47e | emmas0507/lintcode | /validate_complete_binary_tree.py | 1,180 | 4 | 4 | # count the number of nodes, and then order nodes by their level, from left to right
# to see if all index from 0 to the number of nodes all filled
class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def count_number_... |
ad3bcc015fb017ce5dd98ca2991b6742b70930b6 | emmas0507/lintcode | /remove_n_node.py | 762 | 3.953125 | 4 | def remove_n_node(linked_list, n):
header = linked_list
node = linked_list
for i in range(n+1):
node = node.next
print('node is {}'.format(node.value))
print('header is {}'.format(header.value))
while node is not None:
header = header.next
node = node.next
header.next... |
9adcfc6a45a4bad71555161e9618f2e84aed94c1 | emmas0507/lintcode | /unique_paths.py | 252 | 3.5625 | 4 | def unique_paths(i, j):
if i == 1:
return 1
elif j == 1:
return 1
else:
left_value = unique_paths(i, j-1)
upper_value = unique_paths(i-1, j)
return left_value + upper_value
print(unique_paths(4, 5))
|
9017e3896fb48063ab70ad928dd4aee46d402896 | emmas0507/lintcode | /binary_tree_paths.py | 646 | 3.78125 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def binary_tree_paths(root, path, allpaths):
path = path + [root.value]
if root.left is not None:
path, allpaths = binary_tree_paths(root.left, path, ... |
ec6876e91862e47189f281dad99cbd25de5e3a10 | emmas0507/lintcode | /flatten_binary_tree_to_linked_list.py | 1,245 | 3.921875 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def flatten_binary_tree_to_linked_list(root):
tail = root
if root.left is not None: # get left flatten list
flatten_left_head, flatten_left_tail = fl... |
3fda77aa011002e74948f85d8c55c803915e8ef5 | emmas0507/lintcode | /balance_tree.py | 1,083 | 3.890625 | 4 | def balance_tree(tree):
def balance_tree(tree):
# tell if a tree is balanced, for any node,
# length of left node and length of right node less or equal than 1
if tree is None:
return (0, True)
else:
left_height = balance_tree(tree.left)
right_heig... |
1b31d200afb0b7f6afc23dade1c92933baffadfc | emmas0507/lintcode | /clone_tree.py | 943 | 3.859375 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def clone_subtree(root, new_root):
if root.left is not None:
new_left = Node(root.left.value)
new_root.left = new_left
clone_subtree(root.... |
16d844a49ba7e2baafe9ebe022f4d7ae0ddaf191 | emmas0507/lintcode | /search_2D_matrix.py | 821 | 3.890625 | 4 | def search_2D_matrix(matrix, target):
# (num_rows, num_cols) = matrix.shape
def search_rows(alist, target):
index = 0
if alist[0] > target:
return 0
for index in range(len(alist)-1):
if alist[index] <= target and alist[index+1] > target:
return in... |
76c2de00d98d877cdb3c035f952563dc01e34bab | emmas0507/lintcode | /delete_node.py | 529 | 4 | 4 | def delete_node(head, target):
while head.next is not None and head.next.value != target:
head = head.next
head.next = head.next.next
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(head):
while head is not None:
... |
de66efae8b75e042f2b0d1ee7b60f1dd55c84afa | emmas0507/lintcode | /paint_fence.py | 396 | 3.734375 | 4 | def paint_fence(n, k):
# n is the number of post
# k is the number of colors
if n == 1:
return k, 0
if n == 2:
return k*(k-1), k # ways if two posts are different, ways if two posts are the same
diff_n_1, same_n_1 = paint_fence(n-1, k)
diff, same = same_n_1 * (k-1) + same_n_1 * ... |
545982196c291546729b7787d4f8b84ea3d5fddc | silouko/CIS-101 | /KostitsPasialiSilouaniDicePython4.py | 348 | 4.0625 | 4 | #Ttake an input
#2 eandom 1,6
#matches user input
import random
answer = int(input("what value do you want the roll dice to have?:"))
total = 0
times = 0
while answer != total:
x = random.randint(1,6)
y = random.randint(1,6)
total = x + y
times = times + 1
#times += 1
print ("you rolled the dice... |
cccc910dbd47e356000239dd6fcf4c013e5c3d8a | maoxiandemeng/python_demo | /test.py | 435 | 3.609375 | 4 | def add():
# i = int(input("请输入第一个数字:"))
# j = int(input("请输入第二个数字:"))
i = int(one())
j = int(two())
print(type(i))
print(i + j)
def one():
i = input("请输入第一个数字:")
if i.isdigit():
return i
else:
one()
def two():
i = input("请输入第二个数字:")
if i.isdigit():
... |
c11cc8a35f22753cf104ea02f4a77a0f3f16b8e7 | kgori/enigma | /enigma/enigma.py | 5,992 | 3.53125 | 4 | import string
class SubstitutionCipher(object):
def __init__(self, cipher):
self.cipher = cipher
self.alphabet = string.ascii_lowercase
def __repr__(self):
return '{}("{}")'.format(self.__class__.__name__, self.cipher)
def __str__(self):
return 'IN: {}\nOUT: {}'.format(se... |
086ed855f74612d9ef8e28b2978ae7ffe5bf62f4 | Mzomuhle-git/CapstoneProjects | /FinanceCalculators/finance_calculators.py | 2,602 | 4.25 | 4 | # This program is financial calculator for calculating an investment and home loan repayment amount
# r - is the interest rate
# P - is the amount that the user deposits / current value of the house
# t - is the number of years that the money is being invested for.
# A - is the total amount once the interest has been a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.