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 |
|---|---|---|---|---|---|---|
3178608f5b504ac53838c4276d36da2a18c161a2 | mcardos/project-3-healthfy | /main_menu.py | 8,200 | 3.75 | 4 | import pygame
import sys
import model
import view
import controller
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500))
font = pygame.font.SysFont(None, 20)
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (27, 133, 27)
grey = (80, 80, 80)
def text_objects(text... |
ff552246fb7bd6075c2bc2b0b622ab735fdf60d9 | AT1924/Homework | /hw3/frequencyAnalysis.py | 613 | 3.59375 | 4 | def sort_dict(dic):
return [(key, dic[key]) for key in sorted(dic, key=dic.get)]
def incr(key, dic):
try:
dic[key] += 1
except KeyError:
dic.setdefault(key, 1)
def main():
resultDict = {}
# read file
with open('breakfast.txt', 'rb') as afile:
for line in afile.readli... |
0493b5cd7e50e3b1acd3487d7f0db5c13e9c6e15 | AT1924/Homework | /hw10/functional.py | 1,772 | 4.15625 | 4 | class InvalidInputException(Exception):
def __str__(self):
return "Invalid Input Given."
def apply_all(f_list, n):
"""apply_all: [function], number -> [number]
Purpose: applies each function in a list to a single number
Consumes: a list of functions and a number
Produces: a list of numbers ... |
9f6aae39f0a3c1f3e8a0087a8dcdc20afdd2f851 | johnhuzhy/StellaPythonExam | /src/practiceTest/t17.py | 673 | 3.90625 | 4 | def function8_1():
while True:
try:
x=input("数字を入れてください")
break
except ValueError:
print("あちら!これは有効な数字ではありません。もう一度")
#else 是和try一起的,try里没有异常时才会走else,如果try里报错了,不会走else。finally是都会走的
def divide(x,y):
try:
result=x/y
# raise KeyError
except Ze... |
85cef5237316e10538fcad4e59729ebccf53f3b8 | johnhuzhy/StellaPythonExam | /src/practiceClass/c4.py | 770 | 4 | 4 | #类最基本作用是封装代码
#类里不要去调用代码,对类的调用放在外面
#实例化
#和Java不同点总结
#在方法里即使是无参方法,也要写self ,在用的时候,要self.调用
#实例化时不需要用new
#类变量与实例变量 类变量与类相关的变量,实例变量与对象相关的变量
class Student():
#类变量
name='qiqiyue'
age=0
#有参构造函数
def __init__(self,name,age):
#实例变量
self.name=name
self.age=age
def print_fil... |
7f3708514b761122f10c8e258b1ca3e61f4b601e | johnhuzhy/StellaPythonExam | /src/practiceList/l3.py | 911 | 3.796875 | 4 | #列表是苦力工,什么类型元素都可以装
#多维列表
#这个列表的元素是另外四个列表
matrix=[[1,2,3],[4,5,6],[7,8,9],[10,11,12,14]]
print(matrix[0][1]) #2
print(matrix[3][3]) #14
mult=[[1,2,3],['a','b','c'],'d','e',{5,6,7,8},(9,10)]
# print(mult[3][1]) # 报错
print(mult[3][0]) #e
# print(mult[4][3]) #TypeError: 'set' object is not subscriptable 集合是没有下标的,不能索引和切片 ... |
a7e17d4089ecbf3b150b6f924d1a66268ff30774 | johnhuzhy/StellaPythonExam | /src/practiceClass/c6.py | 769 | 4 | 4 | #在实例方法中访问实例变量和类变量
#访问实例变量用self. 访问类变量用类名. 也可以self.__class__.
class Student():
#类变量
name='qiqiyue'
age=0
sum=2
#有参构造函数
def __init__(self,name,age):
#实例变量
self.name=name
self.age=age
print(self.name) #访问实例变量最好加上self
# print(name) #虽然结果和上面相同,但是他们... |
468b9dbc987acacbb952a645e0e9759cf804b1ca | johnhuzhy/StellaPythonExam | /src/C3/3-5.py | 195 | 3.75 | 4 | '''
循环语句 while for
'''
# while condition:
# 代码块
#可以加else 当为false时就走else里
counter=1
while counter<=10:
counter+=1
print(counter)
else:
print('EOF')
|
4e05a48c68ceb3c8454099c2bdc00f6b88c7823c | johnhuzhy/StellaPythonExam | /src/practiceFunction/h9.py | 581 | 3.578125 | 4 | # {'bj': '32c', 'xm': '23c', 'sh': '31c'}
# <class 'dict'>
# def city_temp(**param):
# print(param)
# print(type(param))
# city_temp(bj='32c',xm='23c',sh='31c')
#.items 不能掉
# def city_temp(**param):
# for key,value in param.items():
# print(key,':',value)
# city_temp(bj='32c',xm='23c',sh='31c')
#*... |
0c2cf147d0724b5e02f7059ce46453b2df1bfc36 | s1lya/secutiryScriptsMIPT | /9.2.py | 3,326 | 3.625 | 4 |
# coding: utf-8
# In[2]:
print('Введите модуль схемы Шамира p:')
p = int(input())
print('Введите первый многочлен:')
x1 = int(input())
y1 = int(input())
print('Введите второй многочлен:')
x2 = int(input())
y2 = int(input())
print('Введите третий многочлен:')
x3 = int(input())
y3 = int(input())
def minusOneMod(exp... |
2b1cc99f964e619797ceae8ad5da63913413c077 | s1lya/secutiryScriptsMIPT | /Mill.py | 3,126 | 3.515625 | 4 |
# coding: utf-8
# In[4]:
#перевод из 10 в 2 систему исчисления (без поворота bin = bin[::-1]) т.к. схема справа налево)
def DecToBin(a):
t = a
bin = []
print('Перведем число',a,'в двоичный вид:')
while a != 0:
if a % 2 == 0:
bin.append(0)
print(a, '0')
a /... |
5463864d5969765af54156c9a19bde20de80b71e | wwyywg/Py3 | /02_python核心编程/01_Python核心编程/ww_07_iterable.py | 628 | 4.125 | 4 | from collections.abc import Iterable, Iterator
if __name__ == '__main__':
# 判断是否可以迭代
# print(isinstance([], Iterable))
# print(isinstance({}, Iterable))
# print(isinstance('abc', Iterable))
# print(isinstance((x for x in range(10)), Iterable))
# print(isinstance(100, Iterable))
# 迭代器
p... |
a3f31a5ee46fde2bdea836f6f2e4c255e8393d2e | wwyywg/Py3 | /01_python基础/公共方法.py | 912 | 3.828125 | 4 | from operator import eq, le, ne, ge, gt
# 运算符
print("hello"+"itcast") # 字符串、列表、元组
print([1,2]+[3,4]) # 字符串、列表、元组
print(('a','b')+('c','d')) # 字符串、列表、元组
print(3 in [1, 2]) # 字符串、列表、元组、字典
print(4 in (1, 2, 3, 4)) # 字符串、列表、元组、字典
# cmp 注意:cmp在比较字典数据时,先比较键,再比较值。
# python 3.4.3 的版本中已经没有cmp函数,被operator模块代替,在交互模式下使用时,需... |
0351ad55306573c4d38d43bbe8f8e3edd9c1878c | shreyasdamle/HTTP-Server-handling-multi-form-data | /sample_pub_enc.py | 1,336 | 3.515625 | 4 | #Use this code as a reference to implement public key encryption
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA256
clientmap = {} #List for multiple clients, name and public key
print 'Generating RSA keys ....'
server_privkey = RSA.generate(4096, os.urandom)
serve... |
33655816cfafa233b306d61f4534338cebeced0a | Lord-Gusarov/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 514 | 4.21875 | 4 | #!/usr/bin/python3
"""
Task 1
Write a class Square that defines a square by
>Private instance attribute: size
>Instantiation with size (no type/value verification)
>You are not allowed to import any module
"""
class Square:
"""
A class that defines a Square
"""
def __init__(self, size):
"""I... |
5e4eb9f01a9a74e2eaa024a676679ec71958d1f2 | Lord-Gusarov/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 195 | 3.65625 | 4 | #!/usr/bin/python3
for i in range(0, 10):
for ii in range(i + 1, 10):
print("{:d}{:d}".format(i, ii), end="")
if i * 10 + ii != 89:
print(", ", end="")
print("")
|
3f48b004bfa01617330bbcc06c11751187786c86 | Lord-Gusarov/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-write_file.py | 319 | 4.1875 | 4 | #!/usr/bin/python3
"""Task: Write to a file
"""
def write_file(filename="", text=""):
"""writes to a file, overtwiting it if it exist
Args:
filename (str): desire name of the output file
text (str): what is to be written
"""
with open(filename, 'w') as f:
return f.write(text)
|
7a674fa7937628745e0b4f478ea558ce93e543d2 | Lord-Gusarov/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,325 | 4.09375 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""Testing callss for funct max_integer
"""
def test_max_integer(self):
"""Asserts the output of certain arguments is as expected
... |
8d1790bb1a6a145f1d4e62c968c189d5aafb7bce | Lord-Gusarov/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,735 | 3.953125 | 4 | #!/usr/bin/python3
"""Task: And now, the Square!
Modules defines a Square class that inherits from the Rectangle class
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""Square class than Inherits from Rectangle and Rectangle inherits
from Base
"""
def __init__(self, size, x=0, y=... |
f636dc47edfa679588c09af316acb7a9fc07db5e | Lord-Gusarov/holbertonschool-higher_level_programming | /0x06-python-classes/2-square.py | 960 | 4.46875 | 4 | #!/usr/bin/python3
"""Task2
Write a class Square that defines a square by
Private instance attribute: size
Instantiation with optional size: def __init__(self, size=0):
Size must be an integer, otherwise raise a TypeError exception with the
message size must be an integer
If size is less than 0, raise a V... |
6b0596a0d967be5e6acfc977df985eeb0a74d656 | Lord-Gusarov/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 532 | 3.75 | 4 | #!/usr/bin/python3
"""
Test Driven Development, Task 0
Write a function that adds 2 integers.
You are not allowed to import any module
"""
def add_integer(a, b=98):
"""Exceptions thrown if the args types are not 'int' or 'float'
a, b (int, float): the two integers to add
Returns: int: the addittion of the... |
a1862d987952687d29fd56cfc1f40b6a2241e42a | sujitkc/itpact | /itpact1/sessions/session-09-04-2020/solution/sum_n.py | 161 | 4.09375 | 4 | sum = 0
count = 1
n = int(input("Enter the number to which you wish to add: "))
while(count <= n):
sum = sum + count
count = count + 1
print("sum = ", sum)
|
50107ad59def6a3eada2797d34872cace5021dc5 | gmzgmzz/BBY162 | /uygulama01.py | 1,887 | 3.765625 | 4 | puan= 0
#soru1
print("Türkiyede kaç yaşından itibaren ehliyet sahibi olabilirsiniz?")
cevap=input("Cevabı yazınız: ")
if cevap=="18":
puan+=20
print("Cevabınız doğrudur.")
print("Mevcut puan durumunuz:"+" "+str(puan))
else:
print("Cevabınız yanlış")
print("Bu soru için hiç puan toplayamadı... |
ba3527eae3177fd5208e73bcc32a380c9f1228c1 | gopib4599/DevOps-1 | /PythonAssignment1/slicing.py | 342 | 4.03125 | 4 | #! /usr/bin/env python
# slicing is defined as taking some amount of data from the whole input by using 3 parameters named [start:stop:step]. we can slice lists, arrays, touples, strings, etc....
#Example for slicing a string
str1 = "hello World"
str2 = slice(0,6)
print str1[str2]
list1 = [1,2,3,4,5,6,7,8]
list2 = sli... |
708f10ee4d560a5ba59d27546dd77fa2e7b81b24 | mlarocca/Algorithms | /simulated_annealing.py | 5,283 | 4.03125 | 4 | from copy import deepcopy
from random import randrange
''' Defines the base class that models a generic solution found by Simulated Annealing
to a generic problem.
Solution objects MUST have:
* A 'score' method (returning either a float or an int, must express how well
a solution solves the pr... |
57be56233a0b08f25b40320c3089fa3863a28627 | AhaanvGithub/Competitive-Programs | /Introduction/python-if-else.py | 284 | 3.78125 | 4 | # Python If-Else
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if (n % 2 == 1) or (n % 2 == 0 and 6 <= n <= 20): print("Weird")
elif (2 <= n <= 5) or (n > 20): print("Not Weird")
|
e38e998dba656061bb5af65d2cd338e0bd30de8b | xinyifuyun/-Python-Programming-Entry-Classic | /chapter_three/02.py | 310 | 4.21875 | 4 | a = ("first", "second", "third")
print("The first element of the tuple is %s" % a[0])
print("The second element of the tuple is %s" % a[1])
print("The third element of the tuple is %s" % a[2])
print("%d" % len(a))
print(a[len(a) - 1])
b = (a, "b's second element")
print(b[1])
print(b[0][0])
print(b[0][2])
|
2a5a976eb8ab446221ec29bce08bdd10411964a7 | franBec/Prog2-Python | /Ej19.py | 497 | 3.984375 | 4 | #Listas, tuplas, diccionario
print()
print ("///Ejercicio 19///")
print()
#No estoy 100% seguro de porque funciona. Saque la funcion de StackOverflow
def insertarEnDiccionario(clave, valor, diccionario):
if not clave in diccionario:
diccionario[clave] = [(valor)]
else:
diccionario[clave].append((valor))
... |
d3df20280175a392f143bc4f49b26d16ec7aa620 | franBec/Prog2-Python | /Ej2.py | 290 | 4.03125 | 4 | #Casteo
print("")
print("///Ejercicio 2///")
print("")
entero = int(input("Ingrese entero: "))
print (entero)
flotante = float(entero)
print (flotante)
string = str(input("Ingrese numero: ")) #obviamente ingresar una letra aca rompe el programa
entero = int(string)
print (entero) |
4720c622c4759744b9298a78da72a119b4d24b54 | Ikshitkate/java-html-5-new-project | /python/vigenere_decryption.py | 945 | 3.96875 | 4 | def decrypt_fun(input_string,k):
st=""
for i in range(len(input_string)):
if input_string.islower():
shift=97 #ord(97)=a
else:
shift=65 #ord(65)=A
s=(((ord(input_string[i]))-(ord(k[i])))%26)+shift #here we need to subtract the ord(key) rest is same as encrypt... |
05f35a29af104b94106636069921df9aabc97686 | Ikshitkate/java-html-5-new-project | /python/WordSuggestion/wordsuggestion.py | 4,046 | 3.609375 | 4 | import csv
import argparse
class TNode():
def __init__(self):
# Init a trie node
self.child_nodes = {} # Create child nodes dict
self.leaf = False # Set leaf node property as false
class Trie():
suggestSet=set()
def __init__(self):
# Creating the trie data structure... |
32d096e826b1a762f03a39ee4e5229d436c8dd1d | Ikshitkate/java-html-5-new-project | /python/Prime.py | 357 | 4.03125 | 4 | def is_prime(a):
flag = True
for i in range(2,a//2+1):
if(a%i == 0):
flag = False
break
return flag
number = int(input('Enter a Number to which You want to find Prime Numbers : '))
if(number < 2):
print('No Prime numbers < 2')
else:
for i in range(2, number):
... |
1dea5b8a083f27942fdd8ede9cffd9f0a2d7d21a | Ikshitkate/java-html-5-new-project | /python/Health_Reminder.py | 2,041 | 3.71875 | 4 | import datetime
from pygame import mixer
import time
def playing_alarm(msg, alarm_file):
mixer.init()
mixer.music.load(alarm_file)
mixer.music.set_volume(0.7)
mixer.music.play()
while True:
user_input=input("Press 's' to stop alarm and 'q' for quit")
if user_input == "s" or user_i... |
c78a57806954a5fbd3730c8a939969fd55c8b2b7 | Ikshitkate/java-html-5-new-project | /LeetCode/Python/palindrome_number.py | 467 | 3.703125 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
y = int(x)
r = 0
while x > 0:
r *= 10
r += x % 10
x //= 10
print(r)
if r == y:
return True
else:
... |
35b1580d0700a73830034f43c9a035b6a85a6abb | Ikshitkate/java-html-5-new-project | /LeetCode/Python/longest_common_prefix.py | 641 | 3.765625 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
strs = sorted(strs, key = len)
common = ''
if len(strs) == 0:
return common
else:
for i, char in enumerate(strs[0]):
... |
0acd26efcde82a0c8f4745baf307565b2d1eb036 | Ikshitkate/java-html-5-new-project | /python/bogosort.py | 238 | 3.734375 | 4 | import random
def sorted(x) -> bool:
n = len(x)
for y in range(0,n-1):
if x[y] > x[y+1]:
return True
return False
def bogosort(list) -> list:
while sorted(list):
random.shuffle(list)
return list
print(bogosort([1,4,3,2,5])) |
f540b7fa15bd454ff8fedca039f72754d0d0c8fb | Ikshitkate/java-html-5-new-project | /python/Arrange/arrange.py | 1,005 | 3.671875 | 4 | import os # Using system functions
import shutil # Moving file to different folders.
# Changing the folder location.
os.chdir(os.getcwd())
cwd = os.getcwd()
# For listing files from the folder.
l = [f for f in os.listdir(cwd) if os.path.isfile(f)]
l2 = []
# Get the extension of file from list l.
for valu... |
f6568d0cecef38406016d82249b846b7e86efa32 | Ikshitkate/java-html-5-new-project | /python/krishnamurthyNo.py | 778 | 4.15625 | 4 | # Python program to check if a number
# is a krishnamurthy number
# function to calculate the factorial
# of any number
def factorial(n) :
fact = 1
while (n != 0) :
fact = fact * n
n = n - 1
return fact
# function to Check if number is
# krishnamurthy/special
def isKrishnamur... |
48bd7bf50eb4d892bf01ef8f94c8d4f1a1fb77b6 | Ikshitkate/java-html-5-new-project | /python/Best_Time_to_Buy_and_Sell_Stock.py | 1,015 | 3.75 | 4 | """
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
... |
a6d0bc00c2c9a9b48ac33964eba694199285a0d4 | Joeonome/Class---Objects-Assignment | /Class & Objects 2.py | 2,849 | 3.90625 | 4 | class Budget:
"""
This is a Budget class, as prepared for my Zuri assignment
"""
def __init__(self, category, amount):
self.category = category
self.amount = amount
def deposit(self):
isdepositAmount = False
while isdepositAmount == False:
... |
98d9efccbcaa1082f1e4500223ea6ec27d65eb0c | segloff23/Advent-Of-Code-2015 | /23/solution.py | 1,553 | 3.546875 | 4 |
def loadProblem():
with open("problem.txt") as problemFile:
problem = [[line[:3], line[3:].split(", ")]
for line in problemFile.readlines()];
for row in problem:
row[1] = [x.strip() for x in row[1]];
return problem;
def hlf(registers, ip, args):
registers[args[0]]... |
12a75d3e435998dda66a2e11f4f4d971ab75926b | YellowSpoonGang/WeeklyCode | /9-20-20/Viperouskahn.py | 842 | 3.625 | 4 | import sys
import math
def zeroMatrix():
matrix = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,0]]
N = len(matrix)
print(matrix)
for i in range(N):
for j in range(N):
if matrix[i][j] == 0:
for k in range(N):
... |
4b33a8be892ec1b5cf1f98861522dd3898c8b7c8 | JoelSchott/MST | /Base Converter.py | 1,562 | 3.734375 | 4 | import math
in_num = 'f100'
in_base = 16
out_base = 2
digit_additions = ['a', 'b', 'c', 'd', 'e', 'f']
def convert_to_num(digit):
try:
return int(digit)
except ValueError:
if digit == '.':
return '.'
return digit_additions.index(digit) + 10
in_digits = []
for digit_index ... |
618b66470ce59c2bf831622fa0e40d29478774d3 | FedeNavoni/ProjectEu | /Problem5.py | 209 | 3.53125 | 4 | Encontrado = False
x = 20
while Encontrado == False:
i = 0
for y in range(1, 21):
if x % y == 0:
i += 1
if i == 20:
Encontrado = True
else:
x += 20
print(x)
|
0e72feae9b9151267e15882a1207be2841874ea5 | kamilklimek/shortest-path-graph | /dijsktra.py | 1,951 | 3.640625 | 4 | import sys
INFINITE = sys.maxint
class Dijkstra:
def __init__(self, graph):
self.graph = graph
self.length = len(graph)
def get_min_distance_vertex_index(self, distances, visits, counter):
min = INFINITE
for vertex_index in range(0, len(distances)):
counter += ... |
2fb08879f9e0d721f20df43e768bdc174067606b | Mario-Zuniga/Numerical-Integration | /Numerical_Integration_2.py | 1,915 | 3.765625 | 4 | #Seccion 2 Integracion de una función desconocida
#Importacion de paquetes
from scipy import *
from numpy import *
from sympy import *
#Creamos el simbolo t para la funcion
t = Symbol('t')
#Declaramos la funcion
f = exp(-t)
#Rangos de la integracion
#Agregar .0 a los valores ayuda a evitar numeros com... |
e935fecac261a43ecd561404f2de719af93e492e | Hegemege/advent-of-code-2019 | /06/solution.py | 2,288 | 3.578125 | 4 | class Node:
def __init__(self, identifier):
self.identifier = identifier
self.parent = None
self.children = []
self.depth = 0
def set_depth(self, depth):
self.depth = depth
for child in self.children:
child.set_depth(depth + 1)
def get_ancestors(... |
0d66c5e14a33a298174c70a0f8104c91d4430e9c | Hegemege/advent-of-code-2019 | /02/solution.py | 1,310 | 3.65625 | 4 | def run_program(memory):
pc = 0
while True:
if execute_instruction(memory, pc) != 0:
return
pc += 4
def execute_instruction(memory, position):
if memory[position] == 99:
return 1
operator = int.__add__ if memory[position] == 1 else int.__mul__
operand1 = memory[... |
4226dba34eb2675e4ec98106e3c11eaa0a98f8ce | disha2sinha/Data-Structures-and-Algorithms | /DATA-STRUCTURES/Stack/InfixToPostfixConversion.py | 1,325 | 4.21875 | 4 | def precedence(operator):
if operator == '+' or operator == '-':
return 1
if operator == '*' or operator == '/':
return 2
if operator=='^':
return 3
def postfix(expression):
stack = []
p = ''
stack.append('(')
exp_list.append(')')
for i in range(0, l... |
15f7b0081888eb9eed9b132c0065f63e1d518da9 | disha2sinha/Data-Structures-and-Algorithms | /DATA-STRUCTURES/Linked_list/Singly_linked_list/Implemented in Python/Deletion.py | 3,237 | 3.96875 | 4 | class Node:
def __init__(self):
self.value=None
Node.next=None
class LinkedList:
def __init__(self):
self.start=None
def append(self):
item = int(input("Enter Item:\n"))
newnode = Node()
newnode.value=item
if self.start == None:
... |
34f98b4edecb21ed5283037c1748328cf6e1b94a | disha2sinha/Data-Structures-and-Algorithms | /DATA-STRUCTURES/Tree/Traversals (Inorder, Postorder , Preorder, levelorder)/LevelOrder_Spiral.py | 1,155 | 4.0625 | 4 | class Node:
def __init__(self,item):
self.left=None
self.right=None
self.value=item
def spiralLevelOrder(root):
stack1=[]
stack2=[]
stack1.append(root)
while stack1 or stack2:
while stack1:
current=stack1.pop()
print(current.value,e... |
e2a70884baf690bc1aa364a614300d878e4528eb | gangagtm/ciss441 | /a4/top2018_csv_reader.py | 814 | 3.8125 | 4 | import csv # import csv python module
top2018_spotify=[] # create an empty list var
row_count=0 # count var for if logic and showing row num on print statement
# open csv file as that can be ref from csv_fi
with open('top2018.csv', 'r') as csv_fi:
reader=csv.DictReader(csv_fi) # use the cs... |
5450e152e7ff05d2f3ce5e6bd794f8a5c1d33588 | artsyone/Final_Exam- | /Football_SavShav1/score_tester.py | 826 | 3.546875 | 4 | data_file = 'score.txt'
def load_scores():
global name
with open(data_file, 'r') as f:
lines = f.read().splitlines()
name = input
return name
with open(data_file, 'r') as f:
lines = f.read().splitlines()
scores = []
for line in ... |
fbe43d182aa2c4d35b6319f9af703d3ac143d8c0 | jeffersonSA/DevTest | /Projeto2/sort.py | 392 | 3.796875 | 4 | class Sort:
def bubble_sort(self,vetor):
tamanho_vetor = len(vetor)-1
ordenado = True
while ordenado:
ordenado = False
for i in range(tamanho_vetor):
if vetor[i] > vetor[i+1]:
vetor[i], vetor[i+1] = vetor[i+1], ve... |
b188e64661bb1810d8bb59f5a5bff7abdff1cba4 | Cerious/NewEuler | /multi_3_5.py | 443 | 3.6875 | 4 | def multi_3_5(num):
one = 0
two = 0
three = 0
lyst = []
for i in range(num):
if i%3 == 0 and i%5 == 0:
lyst.append(i)
one += i
if i % 3 == 0 and i%5 != 0:
lyst.append(i)
two += 1
elif i % 5 == 0 and i % 3 != 0:
lyst.... |
71d761e5a67df172c5516846a65f3cbb51547446 | nguyenhvili/inteview-exam | /app.py | 153 | 3.53125 | 4 | import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.linspace(0, 2 * np.pi, 3), [np.sin(i) for i in np.linspace(0, 2 * np.pi, 3)])
plt.show()
|
3197852fdb15af7b1bf27762c69c58b69c07131e | nguyenhvili/inteview-exam | /TASK4_valid_brackets/solution/app.py | 1,572 | 3.921875 | 4 | # Task 4 finished at 22:28 27.6.2020
class Solution:
def isValid(self, s):
# my code (it doesn't work)
open_brackets = ['{', '(', '[']
close_brackets = ['}', ')', ']']
'''print(s)
if not bracket_type == -1:
print('Close: ' + close_brackets[bracket_type])
... |
eb51206a91b5ce54af44c7cb631a463552ba8235 | ManuelS0usa/KMeans-Clustering | /kmeans.py | 4,997 | 3.859375 | 4 | from numpy import load, savez, array, arange, tile, random, delete, exp, dot
# import math
import numpy as np
def kmeans(X, k):
'''
KMEANS ALGORITHM procedure:
1 - Initialize the center of each cluster to a different randomly selected training pattern.
2 - Assign each training patte... |
0a171e7b70560728837047bc976f01c145fcc474 | sartorileonardo/Curso-Intro-Python-Univali | /Aula01/aula01EstruturaRepeticaoWhileFactorial.py | 495 | 4.25 | 4 | print("Teste WHILE")
#O numero factorial é como 5 = 5*4*3*2*1
factorial_number = input("Entre com um número:")
factorial_number = int(factorial_number)
if factorial_number > 0:
step = factorial_number
total = factorial_number
while step > 1:
step -= 1
total *= step
print("O fatori... |
4d5100673e0f2e9a6647e200d5cbe52f6e17ae42 | NachoBokita/Ejercicios | /EjercicioClase5/ejercicio5.py | 969 | 4.15625 | 4 |
"""
=> Ejercicio 5:
Realizar una función asociar() que reciba como parametro dos listas
de la misma longitud de elementos y devuelva un diccionario de pares
clave-valor asociando cada elemento de ambas listas segun su indice.
Ej:
empleado = ['Juli', 'Carlos', 'Roberto', 'Marta']
... |
6b17656587aeab7f1cfbff66e0a692888ff0b118 | NachoBokita/Ejercicios | /EjercicioClase5/ejercicio2.py | 872 | 3.96875 | 4 | """
=> Ejercicio 2:
Realiza una función que tome como parametro una frase y devuelva una
lista de palabras en mayuscula.
Ej:
mi_frase = "Este sabado tenemos el ultimo encuentro online"
palabras = convertir(mi_frase)
print(palabras)
>>> ["ESTE", "SABADO", "TENEMOS", "... |
0d9ea7a15271686b1856f9df94f695bf83185709 | generaldave/ControllerVisualizer | /app/controller/Controller.py | 1,729 | 3.578125 | 4 | '''
David Fuller
1/4/2018
'''
import pygame
from .NES import NES
from .N64 import N64
class Controller(object):
'''
Sets up a Controller class.
'''
def __init__(self, app_directory):
'''
Controller's init method.
Decides whether or not a controller... |
fa2172b42ff1f6b312eca41e360de6bf6e8ecdc8 | Guillethecoder/RouteOptimize | /heap.py | 3,436 | 3.984375 | 4 | lass Heap_Item:
"""
Heap item data structure.
"""
def __init__(self, k, v):
"""
Generates a heap item with key k and value v.
"""
self.key = k
self.value = v
def __repr__(self):
"""
Represents a heap item.
"""
return "({},{})... |
c8ca7dfa7466d3c1d4a39262044d47e02328e468 | bimeshupreti/new-work | /mean calculation.py | 185 | 3.71875 | 4 |
my_list = [1, 2, 3 , 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 25, 30, 35, 45, 50, 55]
average = sum(my_list)/len(my_list)
print("the mean is" + str(round(average, 2)))
# In[ ]:
|
a6a99be4aae7f7d0f7133a06d7bf5a957296eff3 | ZakiaIslam/Codeforces | /112 A-Petya and Strings.py | 684 | 3.5625 | 4 | #import math
s1 = input()
s1 = s1.lower()
s2 = input()
s2 = s2.lower()
li1 = [ord(x) for x in s1]
li2 = [ord(x) for x in s2]
lis1=0
lis2 =0
c=0
for i in range(len(li1)):
lis1 += li1[i]
for i in range(len(li1)):
lis2 += li2[i]
#else:
for i in range(len(li1)):
if li1[i]>li2[i]:
... |
1212af76473ba367e6f4724d7b16d952858c1792 | ZakiaIslam/Codeforces | /96A-Football.py | 348 | 3.5625 | 4 |
li = input()
def com(li,num): #1000000001 0
c = 0
for i in li: #1
if int(i)==num: #1==0 0==0
c+=1
if c >= 7:
return True
break
else:
c=0
return False
if com(li,0) or com(li,1):
print("YES")
... |
b050f7dcbcc0a529ec03ac638af6c04cac4e6026 | Aneeka-A/Basic-Python-Projects | /addition_problems.py | 1,561 | 4.5625 | 5 | """
File: addition_problems.py
-------------------------
This piece of code will create addition problems (with 2 digit numbers).
New problems will continue to be displayed until the user gets 3 correct answes in a row.
"""
import random
# Declaring the minimum and the maximum numbers that can appear in the question.
... |
5ac6173cfe6758863c551ed36ae9a94b1719cb00 | qodlsrud20712/my_project | /test/pytorch_study.py | 643 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
x_data = [1.0,2.0,3.0]
y_data = [2.0,4.0,6.0]
w = 1.0
def forward(x):
return x * w
def loss(x,y):
y_pred = forward(x)
return (y_pred - y) * (y_pred - y)
w_list = []
mse_list = []
for w in np.arange(0.0,4.1,0.1):
print("w=",w)
l_sum = 0
for x... |
04ab341c79040c4bfae09e215cc6e55f3dca9ce0 | Pratikpatil28/pythonClass | /5th.py | 147 | 3.75 | 4 | from numpy import *
arr=array([
[1,2,3,4],
[2,3,4,4]
])
arr1=arr.reshape(2,2,2)
arr2=arr.flatten()
print(arr2)
print('')
print(arr1) |
4f788c3f6dd4c527e2f63dd9950401c4f5366deb | Pratikpatil28/pythonClass | /13th.py | 431 | 3.921875 | 4 | # Recursion
#general means a function will call itself like a loop
#How to see recrison limit
#sol-
import sys
print(sys.getrecursionlimit())
#Can we exceed the limit?
import sys
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
#Factorial by Recursion
x=int(input("Enter the value"))
def fact(n):
globa... |
f8bec963a9eaf6b6a48bc09c317a3d438cbdeb3f | jesusdavidgomezrobles/actividad1 | /programa3.py | 372 | 3.75 | 4 |
num = int(input("Ingrese un numero====>"))
def numero_perfecto(num):
suma = 0
for i in range(1, num):
if num%i==0:
suma += i
return suma == num
if (numero_perfecto(num)==True):
print("El numero ingresado=>(" + str(num) + ")<=es perfecto")
else:
print("El num... |
1a8f543f0a0595c938e5bf13494ad8f038d2b9e4 | francescofresta/atm-cash-machine-simulator | /classe_contocorrente.py | 4,808 | 3.546875 | 4 | '''Francesco Fresta - Matricola: 453710
'''
import time
class ContoCorrente:
def __init__(self, _numeroconto, _correntista, _eta, _saldo, _datastipula):
#inizializza le variabili di istanza
self._numeroconto = _numeroconto
self._correntista = _correntista
self._eta = _eta
self._saldo = _saldo
self._datasti... |
a807f17b019d1ca7e1c21aa4e5837f3acb750f6c | J0315C-human/Old-Python-sandbox | /turtleblocks.py | 1,239 | 3.703125 | 4 | import turtle
from math import sin, cos
from random import randint, choice
#some random block drawing.
turtle.bgcolor("black")
turtle.color((.1, .5, .9))
turtle.hideturtle()
turtle.tracer(0, 0)
def square(x, y, height, heading=0):
turtle.pu()
turtle.goto(x, y)
turtle.setheading(heading)
turtle.pd()
... |
2afcb843c1414085cded9ccb6473449e4500ea94 | tamjidimtiaz/Machine-Learning-Optimization-Algorithms | /Fibonacci_Search.py | 734 | 3.96875 | 4 | # Fibonacci search with n function evaluations to minimize an univariate objective function in the interval [a,b]
import math
def fibonacci_search(a, b, n):
for i in range(n,1,-1):
phi =1.61808
p = (int(round((phi**i - (1-phi)**i) / 5**0.5)))/(int(round((phi**(i+1) - (1-phi)**(i+1)) / 5**0.5))... |
501b656483ec595b39624824fdc454912fa7e71a | JacksonYu92/boilerplate-arithmetic-formatter-2 | /arithmetic_arranger.py | 1,363 | 3.90625 | 4 | def arithmetic_arranger(problems, solve=False):
if len(problems) > 5:
return 'Error: Too many problems.'
line1 = ""
line2 = ""
line3 = ""
line4 = ""
for i, problem in enumerate(problems):
num1 = problem.split()[0]
operator = problem.split()[1]
num2 = problem.spli... |
199d7434c6aa018a2d8a726813fca67e5058344c | rsister88/Marzo-FizzBuzz | /NachE/__init__.py | 344 | 3.75 | 4 | #!/usr/bin/env python
# by J.A. Nache <nache.nache@gmail.com>
for i in range(1,101):
fizz = True if (i%3 == 0) or (str(i).count("3") > 0) else False
buzz = True if (i%5 == 0) or (str(i).count("5") > 0) else False
if fizz & buzz:
print "FizzBuzz?"
elif fizz | buzz:
print "Fizz" if fizz else "Buzz" #corregido, ... |
602b82043f3eaae3aaac4ae9603b98782b3c3711 | archcemacs/python_practise | /chapter02/title06/exercise.py | 239 | 3.90625 | 4 | #!/usr/bin/python2
if __name__ == '__main__':
a = raw_input('Enter a number:')
num = int(a)
if num > 0:
print '%d > 0' % (num)
elif num < 0:
print '%d < 0' % (num)
else:
print '%d = 0' % (num)
|
354218723f5fee3a46e88ae7e653533fa6f333da | Only1Loatheb/odometria | /odometria/Odometry.py | 1,464 | 3.6875 | 4 | from math import atan2, pi, sqrt, cos, sin
class Odometry():
def __init__(self,p,r,d):
self.position = p
self.wheel_r = r
self.track_d = d
def getPosition(self):
return self.position
def distance(self, t):
return sqrt( (self.position[0] - t[0]) * (self.position[0] - t... |
c9c247ac6550c0107fb9cffccb786d0a59830997 | jskim3889/WebProgrammingStudy | /Week02/HS/practice40.py | 414 | 3.875 | 4 | def prime_number_generator(start, stop):
num = start
while num < stop:
rt = int(num**0.5)
isPrime = True
for i in range(2, rt+1):
if num % i == 0:
isPrime = False
if isPrime:
yield num
num += 1
start, stop = map(int, input().split(... |
d5d2936b2cde224157972a5003cf4562c9cb505f | Vuochlang/CS_351_MySQL-read-a-movie-database | /code/dictionary.py | 3,906 | 3.703125 | 4 | import csv
import json
# parse multi-values attributes into dictionaries
class Dictionary:
def __init__(self):
self.movie_dictionary = {} # ('id':{}{})
self.genre_dictionary = {} # ('id': 'name')
self.keywords_dictionary = {} # ('id': 'name')
self.production_companies_dictionary... |
21e8d9944882158f78e948ba3b3f86064c1273c6 | GamingBaron/OverWatch-Heros | /OverWatch Hero classes/OverWatch Mei.py | 856 | 3.859375 | 4 | class Mei():
def __init__(self, name, age):
"""Initalize name and age attibutes."""
self.name = name
self.age = age
def Ice Blaster(self):
"""sulate a caricter shotting a Ice Blaster in a responce to commond."""
print(self.name.title() + " is now shotting.")
def Cryo-Frezze(self):
"""simulate a ca... |
680390a8e356489a977b21a3aa9acec6337b84be | GamingBaron/OverWatch-Heros | /OverWatch Hero classes/OverWatch Symmetra.py | 1,037 | 3.703125 | 4 | class Symmetra():
def __init__(self, name, age):
"""Initalize name and age attibutes."""
self.name = name
self.age = age
def Photon_Projector(self):
"""sulate a caricter shotting Photon Projector in a responce to commond."""
print(self.name.title() + " is now shotting.")
def Turret(self):
"""simul... |
ceab7cd6a8237477c686d46e1cef8f8df4ef465a | shentonfreude/Presentation-For_Those_About_To_Mock | /unittest_twice_single.py | 348 | 3.5 | 4 | from unittest import TestCase, main
def twice(x):
return x + x
class TestTwice(TestCase):
def test_twice(self):
got = twice(42)
self.assertEqual(got, 84)
got = twice('a')
self.assertEqual(got, 'aa')
with self.assertRaises(TypeError):
twice(None)
if __name_... |
e3d93082e02229e0723365df2f15d2705bc4f625 | RawOnion/AlgorithmLearning | /Algorithm/quickSort.py | 1,007 | 4.28125 | 4 | '''
快速排序
1.选择基准点
2.将列表分成两个子列表:小于基准点元素的列表和大于基准点列表的元素
3.对两个子列表分别进行快速排序
'''
import random
def quick_sort(arr):
if len(arr)<2:
return arr
else:
pivot=random.choice(arr)
pivot_index=arr.index(pivot)
#所有小于基准值的元素组成的子列表
i=0
less=[]
greater=[]
while i<len(a... |
30de2bded5b5dd855ccb54d97ea89e2d5a02c5a8 | RawOnion/AlgorithmLearning | /Algorithm/LongestCommonSubstring.py | 1,963 | 3.53125 | 4 | '''
最长公共子串
字符串中的子串的字符是连续的
时间复杂度为O(m*n)
两个字符串的长度之积
思路:
采用动态规划,从第一个子串开始遍历第二个子串
如果相等就在左上角值的基础上加一
'''
import numpy as np
class LongestCommonSubstring(object):
def __init__(self,str1,str2):
self.string1=str1
self.string2=str2
#保存字符串的长度
self.string1_len=len(str1)
self.string2_len=... |
e7e0ed051b3fc36d88441a600be3ccb5b99c9efb | ScorpJD/PDP-T | /pdpt.py | 11,576 | 3.734375 | 4 | #!/usr/bin/env python
from vehicle import Vehicle
import networkx as nx
import matplotlib.pyplot as plt
from Solution import Solution
import math
import random
class PDPT:
"""Pickup and delivery with Transfers Class.
This class has the PDPT model.
Attribuetes:
N (int): The tota... |
47f1d49e414fb4bd1ff037672837d86f20d6f1ad | criscujia/Electiva_BD_Tarea3 | /main.py | 1,232 | 3.984375 | 4 | from library.ejercicios import*
from os import system
def main():
while True:
print ("Selecciona una opción")
print ("\t1 - Insertar")
print ("\t2 - Mostrar")
print ("\t3 - Buscar")
print ("\t4 - Eliminar")
print ("\t5 - Salir")
opcionMenu = input("... |
7d731c0e706d4832cf03a04d5aa379a687d95eed | w3api/cssdoc-parser | /elementos.py | 1,116 | 3.75 | 4 | class ElementoCSS:
nombre = ""
sintaxis = []
categorias = []
versiones = []
valores = set()
def __init__(self):
self.nombre = ""
self.sintaxis = []
self.categorias = []
self.versiones = []
self.valores = set()
def nombre(self,nombre):
se... |
eae58ac3c4f7ac0e5154c09be1d2d90109c1003f | superfuji57/datasci | /assignment3/nonsymmetric.py | 784 | 3.625 | 4 | import MapReduce
import sys
from collections import Counter
"""
Non-Symmetric Friends Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
def mapper(record):
# key: friend 1
# value: friend 2
key = record[0]
value = record[1]
mr.emit_intermediate(key, value)
mr.emit_intermediate(val... |
6a2623fdc73d0bc16e5e4c2c6b0285a45cc37b9b | bhavinmoriya/Algorithms_Cormen | /DailyCoding.py | 3,305 | 4.125 | 4 | '''Given a positive integer n, find the smallest number of squared integers which sum to n.
Daily Coding Problem: Problem #670'''
def getMinSquares(n):
import math
if n<=3:
return n
elif math.sqrt(n)%1 == 0:
return 1
else:
k = 1
result = n
while k*k <=n:
result = min(result, 1+getMinS... |
9b3d298c00b012f239570c16dc6ed7f01b9877e3 | ok-git/py_training | /lesson_1/task_1.py | 540 | 3.796875 | 4 | # sec = '' # define var
# waiting for digits only
# while not sec.isdigit():
# sec = input("Input time in seconds:")
# sec = int(sec) # change str to int
sec = 3661
# variant 1
hours = sec // 3600
minutes = sec // 60 % 60
seconds = sec % 60
print(f"v1 {sec} seconds is equal to {hours} hour(s), {minutes} minut... |
9dd8b32204bcca0ad92111871413e021ad41f34b | ok-git/py_training | /lesson_6/task_4.py | 3,453 | 3.5 | 4 | """
Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево).
А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда).
Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. До... |
2459dabc67e21a2f372f8f5b6377783464806a1d | cbrnr/aoc2019 | /day02.py | 1,949 | 3.9375 | 4 | def run_intcode(intcode, noun, verb):
"""Run Intcode program.
Parameters
----------
intcode : list of int
The Intcode program as a list of integers.
noun : int
Value which overwrites Intcode address 1.
verb : int
Value which overwrites Intcode address 2.
Returns
... |
44127e2d502993513b3c21ab391aadd1a0511341 | nuruddinsayeed/myData_Structure_and_Algo_Python | /BJIT_algo_test_alt.py | 1,118 | 3.625 | 4 | participant_num = int(input())
arr = []
single_arr = []
total_score = 0
for i in range(participant_num):
x = int(input())
y = int(input())
z = int(input())
sum_num = x + y + z
arr.append((i, sum_num))
total_score += sum_num
single_arr.append(sum_num)
def sort_tuple(tup):
# getting l... |
db4ce4da18ef173675cdf42a59b8a43f626c274d | nuruddinsayeed/myData_Structure_and_Algo_Python | /decorators.py | 1,175 | 3.75 | 4 | import time
import datetime
def decorator_function(funnc):
"""takes a function and return another function"""
def wrapper(*args, **kwargs):
print("Started function 1")
funnc(*args, **kwargs)
print("Ended function 1")
return wrapper
@decorator_function
def hello(message, me):
... |
27b09e53a26ce872a77a525a14ce0f4e06eeacf3 | mikeful/aoc_2018 | /03/fabric_overlap.py | 832 | 3.5 | 4 | from data import parts
from time import time
start_time = time()
max_width = 1000
max_height = 1000
# Using ranges avoids having to use short syntax "[0] * max_width * max_height" which creates copies of same list
# See more at https://stackoverflow.com/a/6667529
overlap_counts = [[0 for x in range(max_width)] for y... |
a056f0379aaa7a8bddf1d0a5f05c587dfe3d56d7 | doom2020/matplotlib-learn | /simple_bar_plot1.py | 846 | 3.5 | 4 | import matplotlib.pyplot as plt
def one_bar_method():
labels = ['G1', 'G2', 'G3', 'G4', 'G5'] # 相当于x坐标
men = [20, 35, 30, 35, 27] # 相当于y坐标
width = 0.35 # 条形图的宽度
fig, ax = plt.subplots()
ax.bar(labels, men, width, label='men') # 显示legend
ax.set_ylabel('score')
ax.set_title('tit... |
152dcf87250fe86bfa9d8ddb1282dc3fbe567e93 | AlexC08/BeginingpythonExercices | /Chapter2/ex2.py | 304 | 3.5625 | 4 | print("Including an integer works with %%d like this: %d" % 10)
print("An integer converted to a float with %%f: %f" % 5)
print("A normal float with %%f: %f" % 1.2345)
print("A really large number with %%E: %E" % 6.789E10)
print("Controlling the number of decimal places shown: %.02f" % 25.101010101) |
9bf3230a0e3e8be35aa70321b01b4a233251d471 | paulpatault/Algorithmic | /Various/roman_num.py | 1,029 | 3.5625 | 4 | class Solution:
nums = {
"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC": 90,
"C": 100,
"CD": 400,
"D": 500,
"CM": 900,
"M": 1000,
}
def romanToInt(self, num: str) -> int:
res ... |
420b5c14b3c7619dbcc0b8774e89f2d4fa6ff886 | paulpatault/Algorithmic | /Lists/add_in_list.py | 617 | 3.953125 | 4 | '''
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
class Solution:
def addInList(self, liste, k):
for i, e in enumerate(liste):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.