blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
df48114e849a2c9b48d3d0aaa7768594d5d30b77 | yonima/python-source-code-of-my-book | /第六章/6.13_dict_parameter.py | 1,358 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
字典参数:
需求:解决存储未知信息时
目前得知:
刘德华,年龄30,男性,喜欢去故宫 来自香港,职业是自由职业者,
如果添加:
收入
"""
def customer(**information):
print(type(information))
for key,value in information.items():
print(f'{key}:{value}')
# 未知用户的信息时
customer(name='刘德华', age='30', love='故宫',
place='香港', profession='自由... |
8fd27e01014ac665813733e4ec2a25aea8194fc1 | mattprintz/omnipod | /omnipod/utils.py | 178 | 3.515625 | 4 | # Helper functions
def clean_string(string):
output = []
for i in string:
if i == 0:
break
output.append(chr(i))
return ''.join(output)
|
23fe55ffc4aca59c22dbcb0f7526ff3b2c704dcd | subwo0fer/homework | /task_palindrome.py | 208 | 3.734375 | 4 | def is_palindrome(s):
s = str(s)
s = s.replace(',', '')
s = s.replace('.', '')
s = s.replace(' ', '')
s = s.lower()
if s == s[::-1]:
return True
else:
return False
|
592c70971ec6e4373a913eef944a76982becb56f | subwo0fer/homework | /task_average.py | 137 | 3.734375 | 4 | def average(lst):
d = 0
for i in range(len(lst)):
d += float(lst[i])
d = d/len(lst)
d = round(d, 3)
return d
|
aaff80815e2992cfb3c74b855f94c31703f37d6f | rileym/utils | /function_tools.py | 747 | 3.71875 | 4 | from itertools import izip
def dict_map(f, d):
'''Return a new dictionary with key-value pairs (k, f(d[k])) where k is a key in d.'''
return dict( (k, f(v)) for k,v in d.iteritems() )
def tuple_map(fn, *iterables):
'''Apply function to every item of iterable and return a tuple of the results.'''
return tuple(map(... |
95bf78cfc2208e196c0e1c20f62df944bddab1c5 | fbuihuu/digraph | /digraph.py | 7,679 | 3.59375 | 4 | #! /usr/bin/env python
import sys, __builtin__
__all__ = ["DirectedGraph", "transpose", "condensate", "dot", "open"]
# Directed graph built out of sets and dictionaries.
class DirectedGraph(object):
def __init__(self, name):
self.name = name
self.vertices = {}
def __str__(self):
retur... |
e86cfff67a203a71fb27aaafb85e4f6cc3af1195 | Dhan-shri/more_exercise | /max_in_list.py | 703 | 3.828125 | 4 | # Yeh ek list mein andar aur lists hain. Andar waali list mein har bache ke saare subjects mein marks hain. Ek max_marks naam ka function banao jo ki ek aisi list le aur har students ke maximum marks print kare.
# Jaise agar main aapke max_marks function ko upar waali list ke saath call karunga ,
marks = [[45, 21, 41... |
bbe05b73b6296b3840f9a24b3c11461a89e5bedd | ManuelBlaze/EvaluacionNTecnologias | /main.py | 1,402 | 4.0625 | 4 | '''
Manuel Alejandro Escobar Mira - Grupo 2
'''
nombre = str(input('Ingrese su nombre \n'))
salario = float(input('Ingrese su salario \n'))
he = int(input('Ingrese las horas extra trabajadas \n'))
hd = int(input('Ingrese las horas dominicales trabajadas \n'))
vDia = (salario/30)
vHora = (salario/240)
vHoraE = vHora *... |
e5e9c870b5cc422a40f0bbd64890d9dff3df678a | MIQBALMAULANA/praktikum | /labspy02.py | 286 | 3.875 | 4 | a = int(input("Masukan Bilangan A :"))
b = int(input("Masukan Bilangan B :"))
c = int(input("Masukan Bilangan C :"))
if a > b and a > c:
terbesar = a
else:
if b > c and b > a:
terbesar = b
else:
terbesar = c
print("Jadi bilangan yang terbesar adalah :",terbesar) |
70370124dedd6185676ded616d0fe4422de88708 | NaiveSolution/Data-Services-Engineering | /Tutorials/Tutorial 4/lol.py | 222 | 3.578125 | 4 | import pandas as pd
df = pd.read_csv('Books.csv')
df = df.set_index('Identifier')
def lol(id):
if id in df.index:
print(f'{id} is in df')
else:
print(f'{id} not in df')
lol('206')
lol('216')
lol('50')
|
0c6c6867dc1e4d9f2985e52fdd64f1a6cf7897cc | adrianmfi/ProjectEuler | /python/P85.py | 672 | 3.515625 | 4 | def countRectangles(width,height):
combinations = []
total = __countInstanceRectangles(width,height,width,height,combinations)
return total
def __countInstanceRectangles(width,height,totalWidth,totalHeight,combinations):
if (width,height) in combinations: return 0
combinations.append((widt... |
2f1cb295cfe1b74f110748be5e06cb95e232c995 | qvinhprolol/Dict-Minihack | /skill_game.py | 1,246 | 3.953125 | 4 | import random
champ = {
'Name': 'Light',
'Age': 17,
'Strength': 8,
'Defense': 10,
'HP': 100,
'Backpack': 'Shield, Breadloaf',
'Gold': 100,
'Level': 2
}
spell_list = [
{
'Name': 'Tackle',
'Minimum level': 1,
'Damage': 5,
'Hit rate': 0.... |
4744c472a6b86ec08cb2932d368c813267fff832 | DeividZavala/cinta_roja | /merge_sort.py | 703 | 3.90625 | 4 | """ Merge sort by everyone """
def get_merge(lst1, lst2):
merge_list = []
while len(lst1) > 0 and len(lst2) > 0:
if lst1[0] < lst2[0]:
merge_list.append(lst1.pop(0))
else:
merge_list.append(lst2.pop(0))
if len(lst1) > 0:
for i in range(len(lst1)):
merge_list.append(lst1.pop(0))
else:
for i in r... |
2a02d765d3edf92f9008da23a632095d4b430520 | DeividZavala/cinta_roja | /factorizar.py | 348 | 3.703125 | 4 | """Chicharronera"""
import math
a = input('valor de a ')
b = input('valor de b ')
c = input('valor de c ')
if (math.sqrt(math.pow(b, 2)-(4*a*c))) >= 0:
formula1 = (-b + (math.sqrt(math.pow(b, 2)-(4*a*c))))/(2*a)
formula2 = (-b - (math.sqrt(math.pow(b, 2)-(4*a*c))))/(2*a)
else:
print "no pasa"
print 'X1 = ', form... |
e212cf0603b9dc71e5b144a97063aa5a3df5483d | PWalis/DS-Unit-3-Sprint-2-SQL-and-Databases | /module1-introduction-to-sql/buddymove_holidayiq.py | 641 | 3.5 | 4 | import sqlite3
import pandas as pd
df = pd.read_csv('buddymove_holidayiq.csv', index_col=None)
# print('df shape', df.shape, df.info())
bh_conn = sqlite3.connect('buddymove_holidayiq.sqlite3')
curs = bh_conn.cursor()
query = 'DROP TABLE IF EXISTS review'
curs.execute(query)
df.to_sql('review', con=bh_conn)
query... |
eea4fdb1572783ff5eb2f8f6ba5f8336384f4b52 | Data-Science-kosta/Forecasting-air-pollution-LSTM-model-and-Regression-trees-model | /pipeline/model_LSTM.py | 12,013 | 3.703125 | 4 | import os
import joblib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.layers import Input, LSTM, Multiply,Dropout,Dense
from keras.optimizers import Adam,SGD
from keras.models import load_model, Model
from keras.models import load_model
from keras.regularizers import l2
from pipeli... |
d965a75271cc230032be827b137fc775aa08658d | Bram94/MAIO | /code/functions.py | 1,695 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 10:48:10 2018
@author: bramv
"""
import math
def string_to_list(s, separator=','):
l = []
index = s.find(separator)
while index!=-1:
l.append(s[:index].strip())
s = s[index+len(separator):]
s = s.strip()
index = s.find(sep... |
90499005784610fd2d801ce0551a2e4486e238fb | tomhaoye/LetsPython | /test.py | 3,694 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
if 1:
print 'true'
else:
print 'false'
'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''
"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""
print 'aa'
print 'aaa'
'''
-------------------------------
'''
str = 'Hello World!'
print str # 输出完整字符串
print str[0] # 输出字... |
65e5ef82673c6ce9e6681c68db14338b10e985e4 | tomhaoye/LetsPython | /practice/practice13.py | 177 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(100, 1000):
f = i / 100
s = (i / 10) % 10
t = i % 10
if f ** 3 + s ** 3 + t ** 3 == i:
print i
|
22084045954a40ae64578ba46fb244d97add9739 | tomhaoye/LetsPython | /practice/fibonacci.py | 489 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a
print fib(10)
def rec_fib(n):
if n == 1 or n == 2:
return 1
return rec_fib(n - 1) + rec_fib(n - 2)
print rec_fib(10)
def th_fib(n):
if n == 1:
retur... |
bd4bc4c500b1b1dda11ef8672e66d03765b76e77 | tomhaoye/LetsPython | /practice/practice46.py | 297 | 3.9375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
TRUE = 1
FALSE = 0
def SQ(x):
return x * x
print 'little than 50 then stop'
again = 1
while again:
num = int(raw_input('input a num:'))
print 'result = %d' % (SQ(num))
if num > 50:
again = TRUE
else:
again = FALSE
|
eac649da027655adc31033c63464b4d39e15b234 | tomhaoye/LetsPython | /practice/practice49.py | 286 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
MAXIMUM = lambda x, y: (x > y) * x + (x < y) * y
MINIMUM = lambda x, y: (x > y) * y + (x < y) * x
if __name__ == '__main__':
a = 10
b = 20
print 'the large one is %d' % MAXIMUM(a, b)
print 'the lower on is %d' % MINIMUM(a, b)
|
4bc003c5070c268204b7e0a3be1ec73911667639 | tomhaoye/LetsPython | /practice/practice29.py | 224 | 3.8125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def backward(s, l):
if l == 0:
return
print s[l - 1]
backward(s, l - 1)
x = raw_input("请输入一个数:\n")
print '%d 位数' % len(x)
backward(x, len(x))
|
674e811f5b6351027b641f4f88696ac072ed162f | matthias-wright/sarcos | /models/random_forests.py | 3,355 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
This module implements the random forests algorithm.
"""
import numpy as np
from . import decision_tree
class RandomForest:
def __init__(self, X_train, Y_train, num_trees, training_set_size, min_nodes):
"""
:param X_train: Training set
:param Y_train: Output ... |
751b84dc78618b4c673521a0b8a794ea4fb59bbe | ahmedbally/Sorting-LL | /Main.py | 3,037 | 3.765625 | 4 | from random import randrange
from time import time
class Node:
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def setData(self, data):
self.data=data
def getNext(self):
return self.next
def... |
dc61f461739c06515c46f567cc77a3c75d93f2e1 | DSLYL/Python_One_Hundred | /python小题练习/test13.py | 317 | 3.671875 | 4 | # 用*号输出字母C的图案。
# spaceNum = [30, 25, 18, 15, 12, 10, 8, 6, 5, 4, 3, 3]
spaceNum=[20,18,16,14,12,10,8,6,4,3,3,3,]
space = ' '
star = '*'
for i in range(1, len(spaceNum)):
print(spaceNum[i] * space, star)
spaceNum.reverse()
for i in range(1, len(spaceNum)):
print(spaceNum[i] * space, star) |
24f13c269f90ccf68b73becbc57b5438f3c64e29 | DSLYL/Python_One_Hundred | /python实验/mypy01.py | 555 | 3.671875 | 4 | # a= 3.55553
# print("%7.3f"%a)
#
# import numpy as np
# x = np.ones(3)
# m = np.eye(3)*3
# m[0,2] = 5
# m[2,0] = 3
# print("矩阵{0}和\n矩阵{1}\n相乘的结果是{2}:".format(x, m, x@m))
#
# x=['aaa', 'bc', 'd', 'b', 'ba']
# print(sorted(x, key=lambda item:(len(item),item)))
#
# 所提交的代码
# 输入一位三位数,输出它的百位,十位,个位
x= (input())
a, b, c = m... |
2e54efabc4548c701f5a6bd9b830dc02b099e28d | DSLYL/Python_One_Hundred | /python小题练习/取小数点位数.py | 409 | 3.75 | 4 | # python保留小数位的三种实现方法
# 符合四舍五入
# print('{:.3f}'.format(1.23456))
# # 1.235
# print(format(1.23456, '.2f'))
# # 1.23
# print('{:.3f} {:.2f}'.format(1.23456, 1.23456))
# # 1.235 1.23
# 后面的必须是整数
# >>> print('%.2f' % 1.23456)
# 1.23
# 暂时不是很懂
print(round(1.23456,3))
# 1.235
print(round(2.355,2))
# 2.35
print(round(2.5))
... |
41cd1170cc0ed937ca4b8ec07af400fe512f9290 | DSLYL/Python_One_Hundred | /python文件/study_4.py | 150 | 3.671875 | 4 | #CSV读取学习
import csv
with open(r"ee.csv","r") as f:
r1=csv.reader(f)
print(r1)
# print(list(r1))
for i in r1:
print(i) |
521a0426f89e4f184ebd5d6800804c8636b46a5e | DSLYL/Python_One_Hundred | /python对象/study_2.py | 801 | 4.21875 | 4 | # 测试私有属性
# 在变量或方法前面加上__(俩个下划线)的时候,就成为私有方法或私有变量,
# 要想在类外访问它们,必须使用对象名._类名__变量名或方法名
#访问私有类变量时,是 类名._类名__变量名
#私有的 在类内是可以随意调用的
class Student:
__Teacher=1 #私有类变量
def __init__(self, name, age):
self.name = name
self.__age = age # 私有属性
def __work(self):
print("加油!")
print(self.... |
de4a0592197953efe82a51cbaac639f53a238525 | ahbaid/kids-code-camp | /lesson-002/Answers/cel2far.py | 203 | 4.25 | 4 | print ("\nCelsius to Farenheit:")
print ("========================")
t = input("Enter temperature in degrees celsius: ")
t = int(t)
f = (t*9/5.0)+32
print ("Temperature in Farenheit is: ",f)
print ()
|
0759c9f40493697d2a66a90fe75f20ba79a6568f | ahbaid/kids-code-camp | /lesson-002/nicetomeetyou.py | 85 | 3.75 | 4 | name = input("What's your name? ")
print ("Hello ", name, " it's nice to meet you!")
|
9660e3134ad31aa40439819789383f8b8619103f | Accitri/PythonModule1 | /(1) 01.11.2017/Class work/RandomNumberGame.py | 606 | 3.96875 | 4 |
import random
minimum = int(input("Enter the lower range: "))
maximum = int(input("Enter the higher range: "))
maxTries= 4
myRandomNumber = random.randint(minimum,maximum)
guessedNumber = int(input("Guess a number between 1 and 6: "))
tries = 0
while(tries < maxTries):
if(guessedNumber != myRandomNumber):
... |
4fe16b312f72b931743d74d10805aa3446951398 | Accitri/PythonModule1 | /(4) 06.12.2017/Class work/dataVisualisationWithTurtle.py | 2,854 | 4.1875 | 4 |
import turtle
myTurtle = turtle.Turtle
#defining a function for the basic setup of the turtle
def setupTurtle():
myTurtleInsideFunction = turtle.Turtle()
myTurtleInsideFunction.penup()
myTurtleInsideFunction.setpos(-300, 0)
myTurtleInsideFunction.pendown()
myTurtleInsideFunction.color('red')
... |
f4878b9bd8f9859f61da88cf7bdf528df80592c4 | Accitri/PythonModule1 | /(6) 10.1.2018/Class work/FileOperations.py | 1,547 | 4.0625 | 4 |
#reading a file
def readMyDataFile(dataFileName):
with open(dataFileName, mode = 'r') as myDataFile:
items = myDataFile.read().splitlines()
print(items)
return items
readMyDataFile("somedata.txt")
#writing to a file
def writeMyDataFile(dataFileName):
with open(dataFileName, mode = ... |
6b20fc5e4beeb11e620a807926d3cd3e5de679af | RaNxxx/checkio_answerforpython | /electronic-station/brackets.py | 613 | 3.859375 | 4 | def checkio(expression):
BRACKETS = ["(", ")", "[", "]", "{","}"]
brackets_list = [ element for element in expression if element in BRACKETS]
temp_list = []
left_side = ["(", "[", "{"]
right_side = [")", "]", "}"]
for element in brackets_list:
if element in left_side:
tem... |
533347055db2714ab2786ac604a65f29b1158cc7 | RaNxxx/checkio_answerforpython | /scientific_expedition/verify-anagrams.py | 630 | 3.96875 | 4 | def verify_anagrams(first_word, second_word):
first_list = [element.lower() for element in first_word if element != " "]
second_list = [element.lower() for element in second_word if element != " "]
check_list = []
for element in second_list:
if element in first_list and second_list.count(elem... |
9aba598c5e855ed6e21a26eda8436c5dfaa678dc | RaNxxx/checkio_answerforpython | /home/house-password.py | 1,104 | 3.71875 | 4 | def checkio(data):
#passwordのtextを、listに変化
pw_list = [ element for element in data ]
#数字、大文字、小文字の出現したかどうかをチェック
check_list = []
for element in pw_list:
if element.islower() == True :
check_list.append("小文字")
elif element.isupper() == True :
check_list.append... |
71d6d806e44d60a094533aef86ea92799c54c89e | larainema/Interview-questions | /linked-list/doubly_linked_list.py | 2,991 | 3.546875 | 4 | class DoublyLinkedList(object):
class Node(object):
def next(self):
return self.__next
pass
def setNext(self, node):
self.__next = node
pass
def pre(self):
return self.__pre
pass
def setPre(s... |
32ddc69f132e58c60816d6944a418021b5a63883 | PulsarEtcher/Stocksera | /scheduled_tasks/miscellaneous.py | 3,546 | 3.515625 | 4 | import sqlite3
import requests
from bs4 import BeautifulSoup
import yfinance.ticker as yf
import pandas as pd
conn = sqlite3.connect(r"database/database.db", check_same_thread=False)
db = conn.cursor()
def get_high_short_interest():
"""
Returns a high short interest DataFrame.
Adapted from https://github... |
7e58a8a8e89768abd35dfaee426edfba5af50c58 | HarshaYadav1997/100daychallange | /day-6/pushzerotoend.py | 355 | 4.03125 | 4 | def pushzerotoend(array,n):
count=0
for i in range(n):
if array[i]!=0:
array[count]=array[i]
count=count+1
while count<n:
array[count]=0
count=count+1
array = [3, 0, 1, 0, 5, 9, 0, 6, 7]
n = len(array)
pushzerotoend(array, n)
print("Array after pushing all zer... |
a7e4955daf0d8d355bed55be5d43df8fffff872c | HarshaYadav1997/100daychallange | /day-5/matrixtranspose.py | 481 | 4.1875 | 4 |
rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
matrix.append(list(map(int, input().rstrip().split())))
"tranpose of a matrix is"
for i in matrix:
... |
e07c29f396c93600cac2c5555a6eac35610908a3 | HarshaYadav1997/100daychallange | /day-2/celsius.py | 88 | 3.5 | 4 | celsius =int(input("enter a no"))
fahrenhiet = (celsius * 9 / 5) + 32
print(fahrenhiet)
|
7d5f296530235616b91c78a5c4244ea1ae7b3434 | HarshaYadav1997/100daychallange | /day-19/takeinputfromuserinmatrix.py | 442 | 4.09375 | 4 | n =int(input ('enter the no of rows,n= '))
m =int(input ('enter the no of coloumns, m= '))
matrix=[]; coloumn=[]
"initialize the no of row nd coloumn"
for i in range(0,n):
matrix+=[0]
for j in range(0,m):
coloumn+=[0]
"initiakize the matrix"
for i in range(0,n):
matrix[i]=coloumn
for i in range(0,n):
for j... |
8b32244285f14dce0d1028495d6cb2394fa38840 | HarshaYadav1997/100daychallange | /day-25/ageing game.py | 195 | 3.921875 | 4 | name = input("enter your name")
age = int(input("enter ur age"))
thisyear = int(input("what is dis year"))
year=str((thisyear-age)+100)
print(name + " will be 100 years old in the year " + year)
|
f3f5d8f50592f4d4cb642061f6e4bb57bbe74329 | gbartomeo/mtec2002_assignments | /class11/labs/my_fractions.py | 1,500 | 4.40625 | 4 | """
fractions.py
=====
Create a class called Fraction that represents a numerator and denominator.
Implement the following methods:
1. __init__ with self, numerator and denominator as arguments that sets a numerator and denominator attribute
2. __str__ with self as the only argument... that prints out a fraction as nu... |
5e4abdc4bb35aa3cad8a8b740f422f2e4f53b590 | gbartomeo/mtec2002_assignments | /class5/greetings.py | 580 | 4.40625 | 4 | """
greetings.py
=====
Write the following program:
1. Create a list of names and assign to a variable called names
2. Append another name to this list using append
3. Print out the length of this list
4. Loop through each item of this list and print out the name with a greeting, like "hello", appended before it
For e... |
30c50a50acc91a51c11226d6e7d05a19e7579d17 | rishabh-1004/projectEuler | /Python/euler023.py | 891 | 3.625 | 4 |
import time
import math
def divisors(n):
yield 1
largest = int(math.sqrt(n))
if largest * largest == n:
yield largest
else:
largest += 1
for i in range(2, largest):
if n % i == 0:
yield i
yield n // i
def is_abundant(n):
if ... |
95f7741d16dd9558032c9886f4563e4e4f8e1fae | rishabh-1004/projectEuler | /Python/euler010.py | 495 | 3.5625 | 4 | import time
def sumofprimes(n):
primeList=[True]*(n+1)
p=2
while(p*p<=n):
if primeList[p]==True:
i=p*2
while i<n:
primeList[i]=False
i+=p
p=p+1
sum=0
for i in range (2,n+1):
if (primeList[i]):
sum=sum+i
return sum
if __name__ == '__main__':
start=time.perf... |
906158860f2143c0faff04db893c33b3b88ef2c9 | h-atkinson/cs20-S16-lab03 | /lab03.py | 3,203 | 4.3125 | 4 | #lab03.py for Hannah Atkinson and Brittany Wilson
#CS20, Spring 2016, Instructor: Phil Conrad
#Draw some initials using turtle graphics
import turtle
import math
import random
friend = turtle.Turtle()
friend.up()
friend.color("blue")
red = turtle.Turtle()
red.up()
red.color("red")
def drawH(Turtlefriend, width, hei... |
bb0007a5421d1c2694ee1c8192d4a1e954d7df9b | divinepromise/lab_3 | /task4.py | 206 | 3.6875 | 4 | def multiples_of_five():
holder=[]
lst_numbers = [1,5,10,13,25,89,90,120]
for value in lst_numbers:
if value%5==0:
holder.append(value)
return holder
result = multiples_of_five()
print(result)
|
5eef645a29fc847e67f611feebcf60258732ff1d | divinepromise/lab_3 | /task12_2.py | 728 | 3.859375 | 4 | def hist(string):
new_dict = {}
for key in string:
if key not in new_dict:
new_dict[key] = 1
else:
new_dict[key] += 1
return new_dict
def inverse_dict(dictionary):
new_dict_invert={}
for key in dictionary:
value = dictionary.setdefault(key, None)
new_dict_invert[value].append[key]
return new_dict... |
4f69b0e56daa9f1db5ddd319ecefff3d268baa9e | wittywatz/Algorithms | /Hackerank/repeatedString.py | 380 | 3.671875 | 4 | def repeatedString(s, n):
length_str = len(s)
a_count = 0
remainder_count = 0
remainder = n % length_str
value = n // length_str
for val in s:
if val == 'a':
a_count +=1
if remainder !=0:
for i in range(remainder):
if s[i] == 'a':
... |
2c6f5d75d5a749a332ffafb990764c00e7fd4cb2 | wittywatz/Algorithms | /Algorithms Python/validMountain.py | 597 | 4.375 | 4 | def validMountainArray(arr):
'''
Returns true if the array is a valid mountain
'''
if (len(arr)<3):
return False
index = 0
arrlen = len(arr)
while ((index+1)<=(arrlen-1) and arr[index]<arr[index+1]):
index +=1
... |
f4530363012067f8961718f5b7c515d5163ff3c7 | nicolas0p/Programming-Challenges | /minimalString/minimalString_test.py | 1,685 | 3.71875 | 4 | import unittest
import minimalString as m
class minimalStringTest(unittest.TestCase):
def test1(self):
text = "cab"
obj = m.MinimalString(text)
result = obj.result()
self.assertEqual("abc", result)
def test2(self):
text = "acdb"
obj = m.MinimalString(text)
... |
5f51484eb464a79cc1d4b49b8dd8475ee10bd203 | popshia/Algorithm_Homework_1 | /binarySearchTree.py | 1,994 | 3.90625 | 4 | # 演算法分析機測
# 學號: 10624370/10627130/10627131
# 姓名: 鄭淵哲/林冠良/李峻瑋
# 中原大學資訊工程系
# Preorder to Postorder Problem
# Build a binary tree from preorder transversal and output as postorder transversal
class Node():
def __init__(self, data): # initial node
self.data = data
self.left = None
self.right = None
self.isChar ... |
432090f4218b127fbb67dd9240c3a3ae1edc19ff | zverinec/interlos-web | /public/download/years/2018/reseni/P9s-solution.py | 557 | 3.578125 | 4 | #!/usr/bin/env python3
def digit_sum(num):
return str(num - (9 * ((num-1) // 9)))
def tlesk(num, last, last_digit_sum):
return (num % last) == 0 or last_digit_sum in str(num)
def play(n):
row = [i + 1 for i in range(n)]
last_len = 0
last_num = 3
while len(row) != last_len:
last_len = ... |
75cfddd299526fa438eff331f8189b60e9cbe86f | zverinec/interlos-web | /public/download/years/2022/reseni/megaBludisko-solution.py | 4,555 | 3.5625 | 4 | from collections import deque
from heapq import heappush, heappop
DR = [-1, 0, 1, 0]
DC = [0, -1, 0, 1]
class Vertex:
def __init__(self):
self.dist = None
self.next = []
def bfs(maze, si, sj):
if maze[si][sj] == "#":
return None
r = len(maze)
c = len(maze[0])
dist = [[None... |
5f6f2d8e3feb52ac48c05ad6b00d4fa52e035487 | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 4/chapter4_pg_116.py | 1,033 | 4.46875 | 4 | #4.10
pizzas = ['veggie', 'meat', 'cheese', 'BBQ', 'buffalo']
print(f"The first three items in the list are: ")
for pizza in pizzas[:3]:
print(pizza)
print("")
print("Three items from the middle of the list are")
#get the middle position
middle = int(len(pizzas)/2)
for pizza in pizzas[middle-1:middle+2]:
print(pizza)... |
2e0aa2205e04ac9b8249833d2bf484d64a97108e | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 6/pizza.py | 232 | 3.984375 | 4 | def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make"""
print(f"\n Making a {size}-inch pizza with the following {len(toppings)} toppings:")
for topping in toppings:
print(f"- {topping}") |
5c9fa10d12c9d3386e0109b03306acdabe313ea4 | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 5/chapter5_pg_131.py | 1,750 | 3.53125 | 4 | #5.1
favouriteColor = 'white'
print("Is favouriteColor == 'white'? I predict True")
print(favouriteColor == 'white')
print("\nIs favouriteColor == 'red'? I predict False")
print(favouriteColor == 'red')
sport = "soccer"
print("\nIs sport == 'soccer'? I predict True")
print(sport == 'soccer')
print("\nIs sport == 'rugb... |
35cb2241ea940b7b2ccd87532c9893446421bb88 | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 6/chapter6_pg_163.py | 560 | 3.75 | 4 | #6.5
rivers = {
'Nile' : 'Egypt',
'Bangala' : 'Zim',
'Tokwe' : 'Masvingo'
}
for key, value in rivers.items():
print(f"{key} runs in {value}")
print("\n")
for river in rivers.keys():
print(river)
print("\n")
for country in rivers.values():
print(country)
print("\n")
#6.6
favourite_languages = {
'Peter' : 'Java',... |
c5e0be71af5836d668b0169d2204be968f61bba1 | EmmanuelTovurawa/Python-Projects | /Data Visualisation/Chapter 15/rw_visual.py | 705 | 3.71875 | 4 | import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
#Make a random walk
rw = RandomWalk(5_000)
rw.fill_walk()
#Plot the points in the walk
plt.style.use('classic')
fig, ax = plt.subplots(figsize = (15, 9))
point_numbers = range(rw.num_points)
ax.plot(rw.x_values, rw.y_values, line... |
1ae005031a741bb896fdd8a9cf8aee17ed85ee91 | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 2/chapter2_pg_71.py | 601 | 4.1875 | 4 | # 2.3
name = "Emmanuel"
print(f"Hello {name}, would you like to learn some Python today?")
# 2.4
name_1 = "Emmanuel"
print(name_1.lower())
print(name_1.upper())
print(name_1.title())
# 2.5
print('Dale Carnegie once said, "The successful man will profit from mistakes and try again in a different way"')
# 2.6
famous_p... |
89ca1d1cffe4a6bfec060d0230da428e2844e458 | EmmanuelTovurawa/Python-Projects | /Class_Work/Chapter 10/chapter10_pg_265.py | 405 | 3.9375 | 4 | #10.3
name = input("Enter your name")
file_name = 'guests.txt'
with open(file_name, 'a') as file_object:
file_object.write(name)
#10.4
def guest_book():
while True:
name = input("Please enter your name")
if name == 'q':
break
else:
print(f"Greetings {name}, welcome\n")
file_name = 'guest_book.txt'
... |
907eee5583cbfc24d57e08d728f4593a3a6a3e70 | wmalisch/Digital-Signature-Encryption-Algo | /main.py | 2,282 | 3.75 | 4 | """
Main function for digital signature authentication.
@author Sajal Saha & Kirk Vander Ploeg
"""
import sys
import key_pair_generator
import hash_code_generator
import digital_signature
def main():
message1 = "WESTERN" # authentic message
message2 = "UNIVERSITY" # unauthentic message
authent... |
0cfa74e319ea2cb59f67e272f773a4663021087a | abhipil/learn | /algo/python/sort/quicksort_equals.py | 1,153 | 3.515625 | 4 | from random import randint
import time
def parition(A, p, r):
x = A[r]
i = p-1
k = p-1
for j in range(p,r):
if A[j] <= x :
k = k + 1
if A[j] == x :
swap(A, k, j)
if A[j] < x :
i = i + 1
swap(A, i, j)
swap(A,... |
3597e3802a9a5c400dce4c82f2504bd24d440204 | capi-bgu/oratio | /oratio/database/DataHandler.py | 279 | 3.5 | 4 | from abc import ABC, abstractmethod
class DataHandler(ABC):
def __init__(self, path):
super().__init__()
self.path = path
@abstractmethod
def save(self, data):
pass
@abstractmethod
def create_data_holder(self, i=-1):
pass
|
5a4dcc4b6cfa86eb40b6fb4e7cd49c47af179bca | cs-fullstack-fall-2018/python-review-ex2-cgarciapieto | /classWork1.py | 349 | 3.875 | 4 |
import random
randomNumber = random.randint(0,10)
while True:
userInput = int(input("Guess the Number!"))
if userInput == randomNumber:
print("Good Job")
break
else:
print("WRONG")
continue
userInput = int(input("Guess the Number!"))
... |
f88171ba3078c7a9b83f333a0d0737328b2ed236 | byj0410/sw_study | /code/20190123_백이주_문제풀이_ver_02.py | 472 | 3.953125 | 4 | # Q2. 10 미만의 자연수에서 3과 5의 배수를 구하면 3, 5, 6, 9이다.
# 이들의 총합은 23이다.
# 1000 미만의 자연수에서 3의 배수와 5의 배수의 총합을 구하라.
n=1
sum=0
while n < 1000:
if n%3==0:
sum+=n
print("3의 배수:", n)
n+=1
elif n%5==0:
sum+=5
print("5의 배수:", n)
n+=1
n+=1
print("\n1부터 1000 미만의 숫자 중 3과 5의 ... |
018180c41b27bdd3582dedfa279c0e8f8532fa53 | rbunch-dc/11-18immersivePython101 | /python101.py | 2,768 | 4.40625 | 4 | # print "Hello, World";
# print("Hello, World");
# print """
# It was a dark and stormy night.
# A murder happened.
# """
# print 'Hello, World'
# print 'Khanh "the man" Vu'
print 'Binga O\'Neil\n'
# # Variables
# # - strings, letters, numbers, or any other stuff
# # you can make with a keyboard
# # a vari... |
e50f64e8a117186ebf66b550df6e7a7802b7bdfd | rbunch-dc/11-18immersivePython101 | /dictionaries.py | 1,559 | 4.21875 | 4 | # DICTIONARIES
# Dictionaries are just like lists
# Except... instead of numbered indicies, they
# have English indicies
greg = [
"Greg",
"Male",
"Tall",
"Developer"
]
# If I wanted to know Greg's job, I have to do greg[3]
# No one is going to expect that
# A dictionary is like a list of variables
nam... |
abfe0ff3fa540f6c4effe61cb044bed200c429bd | achiu2/softdev-hw | /hw07/qsort.py | 627 | 3.921875 | 4 | """
**********************
HOMEWORK: 4/6/16
==============
Quicksort
==============
1. Pick a pivot
2. Partition into 2 lists
*all values < p are LH
*all values > p are RH
*pivot in correct position
3. qsort(LH)+p+qsort(RH)
"""
import random
def populate():
return [random.randint(0,50) for x in range(10)]
de... |
bf9a2ebdfa76f1e6b3164877eda18e1c3e827e3a | Jcih/lc2019 | /lc766.py | 504 | 3.59375 | 4 | class Solution:
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
m = len(matrix)
n = len(matrix[0])
if m == 1 or n == 1:
return True
for i in range(m-1):
for j in range(n-1):
... |
3f469d477d71984ce20c7dd8553b2959718ffc66 | Mcszorongat/PyTrnng | /ob_recaman_write.py | 884 | 3.671875 | 4 | import sys
from itertools import count, islice
def sequence():
"""Generates Recaman's sequence."""
seen = set()
a = 0
for n in count(1):
yield a
seen.add(a)
c = a - n
if c<0 or c in seen:
c = a + n
a = c
def write_sequence(filename, num):
"""... |
44027951f96277d99347015815fbdc7a0f17a0b3 | Mcszorongat/PyTrnng | /o_fileIO.py | 1,387 | 3.5625 | 4 | import sys
print(f"Default encoding: {sys.getdefaultencoding()}") # default encoding of different systems can be also differ
f1 = open("o_textfile.txt", mode= 'wt', encoding='utf8') # w - write r - read a - append t - text b - binary
print(f1.write("1st line, ")) # returns the character written into the file
... |
09121966ac5b02a6ace44666b854083013082639 | Hannemit/dog_breed_classifier | /src/utils/un_normalize_image.py | 709 | 3.765625 | 4 | class UnNormalize(object):
"""
Class to un-normalize a tensor in order to visualize the image
"""
def __init__(self, mean=None, std=None):
if mean is None:
mean = [0.5, 0.5, 0.5]
if std is None:
std = [0.5, 0.5, 0.5]
self.mean = mean
self... |
1824379a8f18f442b4bed890398ea1cde5062afc | dunn-cwu/CS557_project1_perceptron | /main.py | 2,619 | 4 | 4 | # Assignment: Project 1
# Course: CS557 Computational Intelligence and Machine Learning
# Instructor: Dr. Razvan Andonie
# Student: Andrew Dunn
# Date: 4/30/2020
# File: main.py
# Desc: Program entry point. Creates the perceptron object and runs experiments.
import perceptron as per
import experiment as exper
def mai... |
0184e7f8497172c0a50cf7f1f40e5e7052e737dd | NaserWhite/STEP2017 | /Loops.py | 247 | 3.5625 | 4 | import random
secret = random.randint(0,10)
# Loop here
#while counter < 100:
#number = number + 5
#counter = counter + 1
#print("counter: {} number: {}".format(counter, number))
for i in range (100):
print(i)
|
6f9d88d25edbbf0303d51140822f8f790e048c44 | NaserWhite/STEP2017 | /Review.py | 504 | 4.15625 | 4 | age = int(input("Enter your age => "))
# 30 < 3 = False
if age < 3:
print("Toddler")
# 30 > 20 = True and 30 < 30 = False ----- True and False --- False
elif age > 20 and age < 30:
print("You're in your 20's") ... |
b0c0714cba07a45f5e85fba990620240bdd0788e | BrennanT/Tetris | /Tetris Lab/In Lab Session.py | 798 | 3.5 | 4 | import turtle
def init():
turtle.home()
turtle.up()
def draw_board():
turtle.down()
turtle.fd(100)
turtle.left(90)
turtle.fd(200)
turtle.left(90)
turtle.fd(100)
turtle.left(90)
turtle.fd(200)
turtle.up()
def draw_block():
turtle.down()
turtle.begin_fill()
tu... |
d04530a768bd0bc1e482eee5c4c3e6e8405f55f0 | diegorobalino16/EjerciciosPython | /recursividad3.py | 425 | 3.6875 | 4 | #contar numeros pares
#n=int(input("n:"))
#def cuentaPares(n):
# if (n<10):
# return 1 - (n % 2)
# else:
# m = n // 10
# return 1 - ((n % 10) % 2) + cuentaPares(m)
#print(cuentaPares(n))
#contar numeros impares
n=int(input("n:"))
def cuentaImpares(n):
if (n<10):
return (n % 2)... |
31d5ff5f9b3ecd2de6c05f359d3bc1799519e437 | diegorobalino16/EjerciciosPython | /suma de n.py | 117 | 3.953125 | 4 |
n =int(input("ingrese un numero entero:"))
suma=0
while 0 < n :
suma = suma + (n)
n=n-1
print (suma)
|
a520cdaff6c77a3f7027f4e75fd108a76bbdc82a | diegorobalino16/EjerciciosPython | /nuevo3.py | 172 | 3.703125 | 4 | # Este prog calcula ara del cilindro)
import math
radio = float(input("radio:"))
altura = float (input ("altura:"))
print ("el area es:",2*3.1416*radio*(altura + radio))
|
595e3051d0296587b69177eff63f3f73e50f0044 | diegorobalino16/EjerciciosPython | /codigo de tres cifras.py | 272 | 3.890625 | 4 |
cod = input("engrese el codigo de tres numero:")
x = len(cod)
if x <= 3:
y = int(cod[0])*int(cod[1])
z=y%10
if z==int(cod[2]):
print ("esta codificado")
else:
print ("no esta codificado")
else:
print ("el num ingresado no es valido")
|
55365facf28a1eb0b830a6621c4c516f522f9b67 | diegorobalino16/EjerciciosPython | /recursividad_invertir_cadena.py | 231 | 4.0625 | 4 | #funcion recursiva que inviert el orden de una cadena
cad=str(input("ingrese la caden a invertir:"))
def invertit(cad):
if len(cad)<2:
return cad
else:
return cad[-1]+invertit(cad[:-1])
print(invertit(cad)) |
84430f16801faae70447f36e8b8f84f36fb7b391 | Cianidos/Euler_Project | /Euler/11-20/18 Maximum path sum I.py | 1,439 | 3.6875 | 4 | def max_path_sum(triangle):
#Transformation de la chaîne de caractère en une liste contenant
#des sous listes (représentant les lignes) qui contiennent
#les nombres de chaque ligne
triangle = [[int(j) for j in i.split()] for i in triangle.split("\n")]
for i in triangle:
print(i)
p... |
0f1d19a2838d77206ac751d46497f15604998a2a | jtk5aw/ProjectEuler | /Python/HighlyDivisibleTriangularNumber.py | 676 | 3.921875 | 4 | # Defines method to find divisors
def findDivisors(number):
divisors = []
for n in range(1, (int)(number**(1/2))):
if(number % n == 0):
divisors.append(number/n)
divisors.append(number/(number/n))
return divisors
#Will check all triangular numbers#
#Variables
n = 0
currTria... |
a664ab75f80e57b442303ad1bd703722be7c394d | swdevdave/The-Tech-Academy-BootCamp | /Python/Drill 2/Datetime drill.py | 759 | 3.96875 | 4 | # Date time Exercise
# Autohor: Dave King
# 03/24/2016
# Python 3.6
from datetime import datetime
now = datetime.now()
hr = (now.hour)
mn = (now.minute)
NYC = int(hr + 3)
TOD1 = NYC %24
if TOD1 >12:
NTA = "PM"
if TOD1 <12:
NTA = "AM"
London = int(hr + 7)
TOD2 = London %24
if TOD2 <1... |
c59556760fce2bdb2cc045b411aebf78e8214b3a | mesaye85/Calc-with-python-intro- | /calc.py | 1,171 | 4.21875 | 4 | def print_menu():
print("-"* 20)
print(" python Calc")
print("-"* 20)
print("[1] add ")
print("[2] subtract")
print("[3] multiply")
print('[4] Division')
print("[5] My age")
print('[x] Close')
opc = ''
while( opc!= 'x'):
print_menu()
opc = input('Please choose an option:'... |
fb1641c07c3b178cd82dd17af1877e52be56788a | rvbb/pylearn | /demo/common.py | 2,420 | 3.546875 | 4 | import json
class Parent:
def override_method(self):
print('parent "Override" method')
def overload_method(self):
print('parent method')
class Child(Parent):
def fn(self, a):
print("this is a=", a)
class Common:
def json(self):
x = '{ "name":"John", "age":30, "city... |
21820256d8998f22a09edb69a36e4b68bb3f0771 | dubian98/Cursos-Python | /lazarexcepciones.py | 706 | 3.890625 | 4 | #crear excepcione
def evalua_edad(edad):
if edad<0:
raise TypeError("las edades no pueden ser negativas")
if edad < 20:
return "eres muy joven"
elif edad < 40:
return "eres joven"
elif edad < 65:
return "eres maduro"
elif edad < 100:
return "cuidate"... |
b2f6cb594b4e1c6c16f4d2e2603a56daac259bfb | dubian98/Cursos-Python | /interfaces graficas/texto_graficos.py | 431 | 3.59375 | 4 | from tkinter import *
raiz=Tk()
raiz.title("Ventana de pruebas")
raiz.iconbitmap("icono.ico")
raiz.config(bg="gray")
miframe = Frame(raiz, width=500, height=400)
miframe.pack()
miframe.config(bg="red")
#milabel = Label(miframe, text="hola mundo nuevo")
#milabel.place(x=100,y=200)
miimagen=PhotoImage(file="desca... |
533b524df2134a52a702cfa92c58a8825505ca74 | dubian98/Cursos-Python | /100 ejercicios/ejercicio10.py | 195 | 3.65625 | 4 | def sum_pos_divisor(num):
sum=0
for i in range(1,num):
if num%i == 0:
sum+=i
if sum==num:
n=True
else:
n=False
return n
sum_pos_sivisor(28) |
4f75eb1e8c2b54024634b9d1cf98f355dd5e264a | dubian98/Cursos-Python | /prueba_excepciones.py | 914 | 3.953125 | 4 | def suma(num1, num2):
return num1+num2
def resta(num1, num2):
return num1-num2
def multiplica(num1, num2):
return num1*num2
def divide(num1,num2):
try:
return num1/num2
except ZeroDivisionError:
print("no se puede dividir entre cero")
return "operacion erronea"
while True:
try:
op1=(int(input("Introd... |
7dc1132a57ced234231908ee140b7397d960961a | dubian98/Cursos-Python | /funciones finales/documentacion_pruebas.py | 1,064 | 3.8125 | 4 | # primer ejemplo
"""
def areatriangulo(base,altura):
"""
calcula el área de un triangulo dado
>>> areatriangulo(3,6)
'el area del triagulo es: 9.0'
>>> areatriangulo(4,5)
'el area del triagulo es: 10.0'
>>> areatriangulo(9,3)
'el area del triagulo es: 13.5'
"""
return "el area ... |
6fc6733dfdc91d12a7998121e66c82d95811b2fb | TamaraGBueno/Python-Exercise-TheHuxley | /Atividade Continua 1/Loja.py | 1,615 | 4.0625 | 4 |
#Imagine que você fora contratado para fazer um programa para uma loja de tintas, com o objetivo de calcular quantas latas de tinta são necessárias para pintar uma determinada área e calcular o preço final da compra.
#A loja trabalha com latas de tinta de:
#24 litros, vendidas a R$91,00 cada e,
#5.4 litros, vendidas ... |
76191c55ec6b572b1c2cd21faf810b3f66052944 | TamaraGBueno/Python-Exercise-TheHuxley | /Atividade Continua 2/Média.py | 1,017 | 4.125 | 4 |
#descreva um programa que receba as notas e a presença de um aluno, calcule a média e imprima a situação final do aluno.
#No semestre são feitas 3 provas, e faz-se a média ponderada com pesos 2, 2 e 3, respectivamente.
#Os critérios para aprovação são:
#1 - Frequência mínima de 75%.
#2 - Média final mínina de 6.0 ... |
054354fd0cdddccf9c1ef800a41aee6ca6ce1b31 | TamaraGBueno/Python-Exercise-TheHuxley | /Atividade Continua 4/Tabuada.py | 272 | 3.796875 | 4 | #Faça um programa que leia um número inteiro e imprima a tabuada de multiplicação deste número. Suponha que o número lido da entrada é maior que zero.
cont = 1
numero = int(input())
while cont<=9:
print(numero, "X", cont, "=", numero * cont)
cont = cont+1 |
a3084a28500218e31bedc115e84ec832bd02f338 | thecodingsophist/practice | /helloworld.py | 1,170 | 3.96875 | 4 | #Exercises
# print Hello World
print("check check hello world")
# : fizz buzz : classic do you know it or do you not know it interview coding question: write a function that takes in a number (N) and prints numbers 1..N, and if the num is divisible by 3, return 'fizz', divisible by 5, return buzz, divisible by 3 & 5,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.