blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bff790e5a9b5828431838523c0d22b350f3978a0 | PatZino/CADE_Project | /random_samples.py | 781 | 3.65625 | 4 | import numpy as np
from numpy import array
A = array([[1, 3, 0], [3, 2, 0], [0, 2, 1], [1, 1, 4], [3, 2, 2], [0, 1, 0], [1, 3, 1], [0, 4, 1], [2, 4, 2],
[3, 3, 1]])
idx = np.random.randint(10, size=3)
print("idx: ", idx, "\n")
print("A[idx, :] : ", A[idx, :])
print("A.shape: ", A.shape)
print("A[np.ran... |
fd9f18e70413a127bbc081b749f271407a5fb1ff | ronicst/advpyDec2020 | /interactions.py | 335 | 4.0625 | 4 | import sys
# sys.path.append() # we could add extra places for python to look
entry = input('Enter name and age ') # assume a comma
fn, age = entry.split(', ')
if not fn.isalpha():
print(f'{fn} needs to be alphabetic')
sys.exit(-1)
if not age.isdigit():
print(f'{age} needs to be numeric')
sys.exit(-1)
... |
310630a2d5e42b7ee88868f259a79044d9c90faf | ChiragSinghai/450-Questions | /Chirag/Matrix/spiral matrix.py | 744 | 3.6875 | 4 | def spiral(L):
r=len(L)
if r==0:
return 0
c=len(L[0])
row=column=0
while row<r and column<c:
for i in range(column,c):
print(L[row][i],end=' ')
row+=1
for i in range(row,r):
print(L[i][c-1],end=' ')
c-=1
if not(row<r and column<... |
115b1156793dbf505ebebd60ec0d1931fc820740 | N-a-n-a/shiyanlou-code | /jump7.py | 144 | 3.75 | 4 | a=0
int(a)
while a <= 100:
a += 1
if a%10 == 7 or a%7 == 0 or a//10 == 7:
continue
if a == 101:
break
print(a)
|
bb54272543ab426c8c34bbbe2703558a13217285 | sheilapaiva/LabProg1 | /Unidade4/classifica_letra/classifica_letra.py | 394 | 3.671875 | 4 | # coding: utf-8
# Aluna: Sheila Maria Mendes Paiva
# Matrícula: 118210186
# Unidade 4 Questão: Classifica Letra
palavra = raw_input()
for i in range(len(palavra)):
letra = palavra[i]
if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u" or letra == "A" or letra == "E" or letra == "I" or ... |
bf5a8bcf168a41d61ae97573df52de22c698e4ff | OhenebaAduhene/globalcode-classbook2019 | /even_list.py | 131 | 3.71875 | 4 | def even_list(x,y):
result = []
for i in range(x,y):
if i%2==0:
result.append(i)
return result |
8d24536c863727ff2fc516f339193e283e06b39d | uglyboxer/challenge_submissions | /compress_challenge_cole.py | 1,303 | 3.84375 | 4 | """ Written by Cole Howard
Takes a string of characters and compresses them if possible
"""
import sys
def compress_string(str1):
"""Take a string
return the string or a compressed one
"""
new_string = ""
for i in str1:
a = [i, str1.count(i)]
if str1.count(i) > 2 and i not in new... |
d531376d79516b07afb0109c98c441fbd200e545 | lmun/competitiveProgramingSolutions | /kattis/judgingmoose.py | 157 | 3.734375 | 4 | from math import *
x,y=map(int,input().split())
eve=""
if x==y:
if x==0:
print("Not a moose")
exit(0)
eve="Even"
else:
eve="Odd"
print(eve,2*max(x,y)) |
5d91a8b0c663ef1e08ebd2c845dcecefdd45f521 | yorkypy/selise-intervie | /string/split.py | 336 | 3.859375 | 4 | def splt(str):
arr = list(str.split(' '))
print(arr)
splt('nina nvisd vsdnvs')
string = '''nin sinids ninvsd nindsvm\nnsdinsd insdvn nn\nnvdsinvs vsdv svd\nvnsd vsinv vnisnv vnisn'''
print(string.splitlines())
string = 'Hello 1 World 2'
vowels = ('a','e','i','o','u')
print(''.join([c for c in string if c ... |
a671d9f69c9ebbc471b4254e75112f4bf03d58aa | KritoCC/Sword | /ex28.py | 7,175 | 4.34375 | 4 | # 习题二十八
# 上题我们学习了不少逻辑表达式,但是他们还有另一个更正式的名字——布尔逻辑表达式(boolean logic expression)。
# 它们无处不在非常重要,所以本题将要练习它们。
# 我们要做的是判断下列表达式的结果是 True 还是 False,并在 python 环境中验证结果:
# True and True
# False and True
# 1 == 1 and 2 == 1
# “test” == “test”
# 1 == 1 or 2 != 1
# True and 1 == 1
# False and 0 != 0
# True or 1 == 1
# “test” == “testin... |
ea6de24be4a8583c0d581305f44da9bb982b3373 | arthurDz/algorithm-studies | /leetcode/palindrome_pairs.py | 1,188 | 3.90625 | 4 | # Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
# Example 1:
# Input: ["abcd","dcba","lls","s","sssll"]
# Output: [[0,1],[1,0],[3,2],[2,4]]
# Explanation: The palindromes are ["dcbaabcd"... |
9509ba9d8c00023ebb546ffd0cdd7741ea92ff00 | lisboa-prog/Ocean_Exercicio_11_2020 | /Exercicio20.py | 2,197 | 3.953125 | 4 | """
Exercício 20
Nome: Números primos
Objetivo: Criar um for (loop) para detectar se um número é primo ou não.
Dificuldade: Avançado
Os números primos são aqueles números divisíveis APENAS por ele mesmo e por um.
Ele NÃO PODE ser divisível por qualquer número entre esses.
Por exemplo:
2 é primo pois ele é divisível a... |
533204143900d3529b6522961ca3e1129ccc19ea | tranngocanh91/python | /pythonfull/bai 4.py | 151 | 3.5625 | 4 | from math import pi
r= float(input('ban kinh hinh trong = '))
print(r)
print('dien tich hinh tron co ban kinh ' + str(r) + ' la '+ str(pi*r**2)) |
2c3418bdadbc70d6c003a945bec394771a9cbd67 | desamsetti/Python | /WhileLoop.py | 330 | 4.125 | 4 | x = 0
while x < 10:
print("X is currently: ",x)
x+=1
else:
print("All done")
x = 0
while x < 10:
print("X is currently: ",x)
print("X is still less than 10, adding 1 to x")
x+=1
if x==3:
print("Hey x equals 3!")
else:
print("Continuing...")
... |
dae36bdb39f6fdabae07c6fae91134ac7e9b704c | NicolasBologna/frro-soporte-2019-27 | /practico_04/ejercicio01.py | 2,604 | 3.96875 | 4 | ## 1 Ejercicio Hacer un formulario tkinter que es una calculadora, tiene 2 entry para ingresar los valores V1 y V2.
## Y 4 botones de operaciones para las operaciones respectivas + , - , * , / ,
## al cliquearlos muestre el resultado de aplicar el operador respectivo en los V1 y V2 .
import tkinter as tk
calculador... |
a997b0f7ef118adba269f81b3931f850890dbe9e | keemsunguk/PythonTutorial | /quiz1-3.py | 520 | 3.546875 | 4 | def kthDigit(n, k):
if n < 0:
n = -1*n
#print(n)
res = 0
upper = (n//(10**(k+1)))*(10**(k+1))
lower = n-upper
res = lower//(10**k)
return res
def testKthDigit():
print("Testing kthDigit()...", end="")
assert(kthDigit(0,0) == 0)
assert(kthDigit(789, 0) == 9)
ass... |
308ff83c6f7dd87edb09b4aa07832b3d4194e40a | ShanEllis/pythonbook | /_build/jupyter_execute/content/05-classes/practice.py | 10,150 | 4.3125 | 4 | # Practice: Classes
In this set of practice problems, it's all about classes, really putting together everything discussed up to this point, including how to create our own classes of objects, with their own associated attributes and methods.
As for all practice sections, each question will include a handful of `asse... |
e4c05bf23ddd9c3b9ddbf9130bf4fe15ced964ba | lovekeshmanhas/PythonWork | /PythonTut/tutorial26.py | 357 | 3.75 | 4 | # Time module
import time
t = time.time()
print(t)
i=0
while (i<5):
print("test performance")
i+=1
print("while loop time in", time.time() - t)
t2 = time.time()
for i in range(5):
# time.sleep(1)
print("test performance")
print("For loop time in", time.time() - t2)
localtime = time.asctime(time.loc... |
a099891555ed7bda2b61bc9db2865cbc502bec0f | AayushSabharwal/SocialSimulations | /InfectionSimulation/utility.py | 1,475 | 3.671875 | 4 | from enum import Enum
from typing import Tuple
class InfectionState(Enum):
"""
Enum to represent possible states of an agent
"""
SUS = 1 # susceptible
INF = 2 # infected
REC = 3 # recovered (immune)
VAC = 4 # vaccinated (also immune)
def sqr_toroidal_distance(a: Tuple[int, int], b: T... |
dc390acbd29caf5a1a9ff350147b44a6e450eb66 | hpatel86/string_exercises | /count_words.py | 755 | 3.6875 | 4 | import sys
import string
from collections import defaultdict
DELIMITER = " "
ALPHABET = set([
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
])
def count_words(lines):
word_count = defaultdict(int)
for line in lines:
word = ""
... |
7d481b424be7bce96fef0782f8725be293d11265 | changchingchen/leetcode | /725_SplitLinkedListInParts/solution.py | 1,001 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
new_list = [None] * k
if not root:
return new_list... |
e40cf69be89cc034bcf8f956e7cc99d673c9852e | chrisxue815/leetcode_python | /problems/test_0726.py | 2,433 | 3.671875 | 4 | import unittest
import collections
def _read_element(formula, i):
i += 1
while i < len(formula) and formula[i].islower():
i += 1
return i
def _read_num(formula, i):
num = ord(formula[i]) - ord('0')
i += 1
while i < len(formula) and formula[i].isdigit():
num = num * 10 + ord(f... |
7a119268ab8b32a0d80328d07bae02aab69286f8 | TheNetRunner/filtermath-django | /filtermath.py | 1,426 | 3.5625 | 4 | from django import template
register = template.Library()
@register.filter(name='intconvertion')
def convert_to_int(number):
return int(number)
@register.filter(name='floatconvertion')
def convert_to_int(number):
return float(number)
@register.filter(name='add')
def add(number_one, number... |
7b8bbfde106271dc0721a5b3c200922b99326c66 | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/15_15.py | 2,803 | 4.5 | 4 | Python | Get all substrings of given string
There are many problems in which we require to get all substrings of a string.
This particular utility is very popular in competitive programming and having
shorthands to solve this problem can always be handy. Let’s discuss certain
ways in which this problem can be... |
606429528517e46cb10a651b388eb0b4a85b7f37 | Rony82012/Python_proj | /sorting/binarysearch.py | 414 | 3.890625 | 4 | def binarysearch(alist, num):
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint] == num:
return True
else:
if num<alist[midpoint]:
return binarysearch(alist[:midpoint],num)
else:
return binarysearch(alist[midpoint+1:],num)
testlist = [90, 11, 32, 28, 13, 47, ... |
e102891436604d12ebaab57a81ab34c57d1848a6 | fabianr8a/ProyectosOperacionalYNumericos | /Proyectos/Juan_Buendia-Fernanda_Toloza-David_Paez/Código RK/RK4-SegundaOpcion.py | 599 | 3.53125 | 4 | #Implementación del método RK4 y algunos casos de salida
import numpy as np
import matplotlib.pyplot as plt
def test1(x, y): # dy/dx = x^2 - 3y
return x**2 - 3*y
def f(x, y): #dy/dx = y - x^2 +1
return y-x**2+10
def RK4(f, a, b, y0, h):
x = np.arange(a, b+h, h)
n = len(x)
y = np.zeros(n)
y[0] = y0
fo... |
2322dc67b8d83ccca8ead34e578b318dff8d4b2e | venkateshmoganti/Python-Programes | /Task21.py | 166 | 3.90625 | 4 | # Exponent
def find_exponent(base, exp):
i = 1
result = 1
while i <= exp:
result *= base
i += 1
print(result)
find_exponent(23, 2)
|
825f08ce57335fde4fa43a13bd6e7381ed7a79b9 | SR0-ALPHA1/hackerrank-tasks | /ProjectEuler/005_smallest_multiple.py | 679 | 3.515625 | 4 | """
Task: Project Euler #5:
"""
def find_delims(n, a={}):
for i in range(2,n):
if n % i == 0:
if i not in a:
a[i] = 0
a[i] += 1
return find_delims(n/i, a)
if n not in a:
a[n] = 0
a[n] += 1
return a
def smallest_multiple(N):
i ... |
8715937ea81e82dcbd55b71299ab195fc380ac8d | avinash3699/NPTEL-The-Joy-of-Computing-using-Python | /Week 11/Programming Assignment 3 Numbers.py | 395 | 4.15625 | 4 | # Programming Assignment-3: Numbers
'''
Question : Write a program, which will find all such numbers between m and n
(both included) such that each digit of the number is an even number.
'''
# Code
a=input().strip()
m,n=map(int,a.split(","))
l=[]
for i in range(m,n+1):
i=str(i)
for j in i:
... |
411756724c7d1a3e8942c0eb1384b6fc46e8391e | upasek/python-learning | /string/string4.py | 250 | 3.859375 | 4 | #Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).
def char(string):
return string[-2:]*4
string = input("Input the word :")
print("new string :",char(string))
|
0192459cf9941d10841bc3f70eb89ce4734d11a0 | AlanRoMC/claseAlfas | /clase1.py | 812 | 3.921875 | 4 | '''
# Entrada de datos
nombre = input("Ingresa tú nombre: ")
edad = int(input("Ingresa tú edad: "))
print("Hola ", nombre, " tu edad es: ", edad)
print("Tú edad en 10 años será: ", (edad+10))'''
'''
# Variables globales y locales
x = "global"
def miFuncion():
x = "local"
global x
x = "CD"
print("Hola ... |
b7fdd3728c3ee4cf8439eabe529e0cdf6c0b0390 | ReDI-School/redi-python-intro | /theory/Lesson6-Dictionaries/code/sets_operations.py | 866 | 4.34375 | 4 | # Lesson6: Sets
# source: code/sets_operations.py
# Input data
python_languages = ['russian', 'french', 'arabic', 'arabic', 'arabic', 'arabic', 'farsi']
java_languages = ['english', 'kurdish', 'arabic', 'arabic', 'french']
# How many different languages do we have in each class?
python_set = set(python_languages)
jav... |
7966e38c11b6d1855f52be65f5738d51d11877dc | iryna-pak/Python_GB | /Lesson05_Teacher/Task1_Teacher.py | 542 | 4.25 | 4 | """
1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
input_str = input("Введите следующую строку: ")
with open("File", "a") as file:
while input_str:
file.write(input_str+'\n')
input... |
77e7aa46bb65c41a572708e77e2f221f6cbab241 | rare-potato/wumpus | /Map.py | 10,082 | 3.78125 | 4 | ########################################################################
## PROBLEM : Create a text based game that is based off of Hunt the Wumpus
##
## ALGORITHM :
## 1. Magic
##
## ERROR HANDLING:
## Checks to see if the person has valid inputs
## Checks to see if the person attempts to go off ... |
c7e6dcbeb97d8bc7dcd77a55b748d3621bbaf012 | Confuzerpy/checkio_solve | /home/to_encrypt.py | 419 | 3.96875 | 4 | from string import ascii_letters
alfavit = ascii_letters.lower()
alfavit = sorted(list({i for i in ascii_letters.lower()}))
def to_encrypt(text, delta=3):
text = text.lower()
shifr = ""
for letter in text:
if letter in alfavit:
ind = alfavit.index(letter)%len(alfavit)
shifr ... |
436b97fa4c02770501e1fbcbab44a5c47c6c8a75 | yuhao-lin007/Advent-of-Code-2020 | /Day 9/day_9.py | 909 | 3.875 | 4 | def get_valid_contiguous_set(numbers, total):
for length in range(2, len(numbers)+1):
for offset in range(len(numbers)-length+1):
contiguous_set = numbers[offset:offset+length]
if sum(contiguous_set) == total:
return contiguous_set
with open("input.txt", "r") as file:
numbers = list(map(int, file.read().... |
82e636b934ce0075f61e58808d1889ee3d65489b | Jayendu/Chatbot | /chat.py | 788 | 3.8125 | 4 | print('Hey I am Chappie, A Simple Chatbot.')
name = input('So Whats your name? ')
print('Nice to meet you ' + name)
age = input('How old are you? ')
print("Ohh... Unfortunately I dont have any age... :)")
print('I was porgrammed by a boy called Jayendu...')
print('He made me for an experiment.')
interests = inpu... |
a6e1b2c2c494bcc7371ab3eda952a7ba1ec4424a | pvolnuhi/CSC-225 | /Assign1/hexadecimal_tests.py | 598 | 3.53125 | 4 | #Learn more or give us feedback
# Tests operations on hexadecimal numbers.
# CSC 225, Assignment 1
# Given tests, Winter '20
import unittest
import hexadecimal as hx
class TestHexadecimal(unittest.TestCase):
def test01_binary_to_hex(self):
msg = "Testing basic binary-to-hex conversion"
self.asser... |
b4e8d5574b158b0780f84f94ebd39c4feb6b6901 | ja95aricapa/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 2,656 | 3.984375 | 4 | #!/usr/bin/python3
"""
Base Class
"""
import json
class Base:
"""
Creates a class Base for do some operations
atributes:
*__nb_objects (int): The number of instance.
"""
__nb_objects = 0
def __init__(self, id=None):
"""
Initialize a Base object
parametters:
... |
6548e0114773f33328f55812534c843f0302e6a2 | Deiarodrigues/programacao-orientada-a-objetos | /listas/lista-de-exercicio-05/questao-04.py | 133 | 3.703125 | 4 | def caracterie(x):
if x >0:
print("P")
elif x <=0:
print("N")
elemento=int(input())
y =caracterie(elemento)
|
497dec96a6b4761a9626e6e076f3fbebe2d1d021 | ralevn/Python_scripts | /PyCharm_projects_2020/Fundamentals/Exam_prep/pirates.py | 2,437 | 3.84375 | 4 | cities = {}
inp_city = input()
while inp_city != 'Sail':
city = inp_city.split('||')[0]
population = int(inp_city.split('||')[1])
gold = int(inp_city.split('||')[2])
if city not in cities:
cities[city] = [population, gold]
else:
cities[city][0] += population
citie... |
c67c58824d068f8332b95d9e3fd33cf89a3aade9 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 3/Ex082.py | 829 | 3.890625 | 4 | #Crie um programa que vai ler varios numeros e colocar em uma lista.
# Depois disso crie duas listas extras que vão conter apenas os valores pares e os impares digitados, respectivamente.
# No final, mostre o conteudo das tres listas geradas.
cont = ''
lis = []
par = []
impar = []
while cont != 'N':
num = ... |
e6284175d4549ab95c315a9582619b76e6b6b44f | fjpolo/ThinkPython | /Code/ThinkPython_4_3.py | 1,264 | 4.1875 | 4 | from swampy.TurtleWorld import *
import math
"""
world = TurtleWorld()
bob = Turtle()
print(bob)
#
for i in range(200):
fd(bob, 2*i)
lt(bob)
#
wait_for_user()
"""
#
# square
#
def square(t, length):
for i in range(4):
fd(bob, length)
lt(bob)
#
# polyline
#
... |
0a9379e73822632e09f954a9cd05d3e86a2ae35c | SApsalamov/psupyis202s | /les2/func2.py | 339 | 3.953125 | 4 | def sum(a, b=0): # b имеет значение по умолчанию
c = a + b
return c
print(sum(2, 3))
print(sum(2))
# args - список аргументов в порядке указания при вызове return args
# тип данных кортеж
def func1(*args):
return args
print(func1('ddd',111, 222, '4444')) |
891ba254bc5bbd92f8ca5cfe12eda121c4de577d | HarakaRisasi/python_code | /code_study/python_learn/010_1_class.py | 17,245 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import os
os.system('cls' if os.name == 'nt' else 'clear')
# A class is a blueprint for objects
# one class for any number of objects of that type.
# Also call it an abstract data type.
# Interestingly, it contains no values itself,
# but it is like a prototype for objects.
# Многие объектно-о... |
eaba9f7b1bc068972de9069e873593803dc4cc9c | newcaolaing/web_auto | /otherdemo/python高级编程/深入类和对象/1_判断类包含方法及抽象类的创建.py | 572 | 3.515625 | 4 |
class conpany():
def __init__(self,list):
self.list =list
def __len__(self):
return len(self.list)
# 判断类型
com = conpany(["b1",'b2'])
print(hasattr(com,"__len__"))
# 方法二
from collections.abc import Sized
print(isinstance(com,Sized))
# 抽象类实现
import abc
class a(metaclass=abc.ABCMeta):
@a... |
b6ac3a04c654c61055ab1b7109893e1617cf160b | terrenceliu01/python1 | /src/function/function.py | 1,492 | 3.84375 | 4 | """
A function is a block of organized, reusable code
that is used to perform a single, related action.
1. Python built-in functions
print()
len()
sum()
2. User defined function
circleArea()
"""
def printName(firstName, lastName):
print(f"First name: {firstName}, last name: {lastName}")
# call function
printNam... |
bdbf23d895721584182b259060862fd87b1ef1f5 | baranshad/projects | /leecode/reverseinteger.py | 410 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 27 23:55:58 2020
@author: user
"""
#%% easier version
def reverse1(x):
y = list(str(abs(x)))
y.reverse()
z= ''.join(x for x in y)
if x > 0 and int(z) <= (2**31-1):
return (int(z))
if x == 0:
return 0
if x < 0 and int(z) <= (2**... |
6dc31934b01e5d3770044a7762752d8bbcb56d2c | ringalls2020/Senior-Design | /Shuffle_Songs.py | 1,231 | 3.5 | 4 | import random
import pygame
#This module shuffles songs
#songs must list of file paths when called
#and current_song must = None
def play_song(songs,current_song):
next_song = random.choice(songs)
while next_song == current_song:
next_song = random.choice(songs)
current_song = next_song
return ... |
c0341ad0e0e218dea5d9bd3d0c640811834ba00d | MichaelHancock/Programming-Challenges | /AdventOfCode2018/Day-05-Part-01/program.py | 1,431 | 3.71875 | 4 | def findReactionPair(dataString):
pairIndex = -1
for index, character in enumerate(dataString):
characterToCompare = ""
if (character.isupper()):
characterToCompare = character.lower()
else:
characterToCompare = character.upper()
if (characterMatchesToTh... |
8ce650034b26d85f77338f6154143119fc021fe5 | elroyg1/QuantQual | /QuanQual.py | 1,297 | 3.6875 | 4 | import csv
from collections import Counter
import itertool
#User will identify the input file location, variable to be analyzed and output file location
inputfile = raw_input("Please identify your file directory: ")
fileVariable = raw_input("Please enter your variable of interest: ")
outputfile = raw_input("Please ide... |
525a19a404bc0452b849c9161ee8fd71adbad3b9 | coocos/leetcode | /leetcode/735_asteroid_collision.py | 3,906 | 4.40625 | 4 | from __future__ import annotations
import unittest
from typing import List, Optional
class Node:
"""Linked list node"""
def __init__(self, value) -> None:
self.value = value
self.next: Optional[Node] = None
self.previous: Optional[Node] = None
@classmethod
def from_list(cls, ... |
cb1272f8872c246a4e9dab3082809d94db13bce9 | 1Riyad/hue_sms | /src/testinput.py | 793 | 3.546875 | 4 | from hue_controller import HueController
from name_converter import clean_name
from data_writer import writeFile,colorPercent,firstEntryDate
controller = HueController()
file = "data.csv"
def go():
test = "."
while (test != ""):
test = input("Please enter a color: ")
color_name = clean_name(tes... |
e3368bc5ae72b178f90d85bdaaa366fd24d0724e | kal-g/SummerResearch | /Abstract Landmarks/FeatureDetectors.py | 15,942 | 3.5625 | 4 | from numpy import *
from math import degrees, sin, cos, hypot, atan2, pi
import random
from scipy.optimize import curve_fit
from cv2 import *
"""All classes Has to contain a get_landmark class which returns landMarks
Has to contain a landmarkType member containing the type of landmark"""
class RANSAC(object):
"""C... |
0aa40b1c467b5fa0458f7de03fab0e86d1a5e5eb | warrior-graph/UECE | /Trabalho-2-PEOO/elemento.py | 808 | 3.765625 | 4 | from abc import ABCMeta
class Elemento(metaclass=ABCMeta):
# Atributo que representa o nome de um objeto elemento
__nome = ""
# Atributo que representa o nome
__tipo_elemento = None
def __init__(self, nome="", tipo_elemento=None):
self.__nome = nome
self.__tipo_elemento = tipo_ele... |
16c2851fab10d33612a704787a871aae15930894 | ReDI-School/redi-python-intro | /theory/Lesson2-Interactive-programs/code/numbers_operators.py | 444 | 4.0625 | 4 | # Lesson2: Operators with numbers
# source: code/numbers_operators.py
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print ("Line 2 - Value of c is ", c )
c = a * b
print ("Line 3 - Value of c is ", c)
c = a / b
print ("Line 4 - Value of c is ", c )
c = a % b
print ("Line 5 - Value of c i... |
c9b6764685de1cd07aa71b28a8f5631d277ec116 | haijiwuya/python-collections | /base/5.set/SetUse.py | 1,723 | 3.875 | 4 | """
集合和列表非常相似
不同点:
1、集合中只能存储不可变对象
2、集合中存储的对象是无序的
3、集合中不能出现重复的元素
"""
s = {1, 2, 3, 4}
print(s, type(s))
# 空集合只能通过set()函数来创建
s = set()
print(s, type(s))
# s = set([1, 2, 3, 4, 5])
s = {1, 2, 3, 4, 5}
print(s, type(s))
# 使用set()将字典转换为集合只包含集合中的键
# s = set({'a': 1, 'b': 2, 'c': 3})
s = {'a':... |
6e345e73fc7e9364761b0b7df7f4ab792f2d9b9e | AasifMdr/LabExercise | /LabOne/Qn9.py | 236 | 4.1875 | 4 | '''
Write a python program to find sum of the first n positive integers.
sum = (n*(n+1)) / 2
'''
num = int(input("Enter a positive integer: "))
sum = (num * (num + 1)) / 2
print(f'The sum of the first {num} positive integers is {sum}') |
9a95a643324d3f5d6609195ef2e04e6150b9c750 | sf-burgos/BasicProgrammingWithPython | /soluciones/semana9/dnasort.py | 2,350 | 3.96875 | 4 | from sys import stdin
def quickSort(alist):
#Pre: Una lista ordenable
#pos: Una lista ordenada """
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
#pre: una lista ordenable,con un pivote y una lista de salida
#returnara un marcador derecho o pivote """
if first<last... |
767d87e12859c198637bbb5567e053bfb7e35948 | jbascunan/Python | /1.Introduccion/24.raise.py | 340 | 3.609375 | 4 | class TinyIntError(Exception):
pass
def tyni_int(val):
return val >= 0 and val <= 255
try:
numero = 400
if tyni_int(numero):
print("el numero es correcto")
else:
raise TinyIntError(
"este es un mensaje para los numeros que no son tyni_int")
except TinyIntError as erro... |
a76e7f5de7eaeea7f3b88e4eefe31a1bca55dc23 | LukaLiu/fulpropalgo | /utils.py | 1,098 | 3.5 | 4 | import math
from math import factorial as fac
import scipy.stats as ss
#factorial function
# fac(n) / (fac(k) * fac(n - k)) * p**k * (1-p)**(n-k)
#caculate binominal probability
def binominal(k,n,p):
return ss.binom.pmf(k,n,p)
#caculate_right or left bondary, which is the sum of binominal probs
def cal_bond(bond, to... |
cea1c70816d1ad9b3eec72061a491694acd31141 | Alkagdy/dzien3 | /Zadanie2.py | 477 | 3.796875 | 4 | #czy liczba jest podzielna przez 3, 5 lub 7
#input
liczba = input("Podaj liczbe:")
#spr czy tylko cyfry
if liczba.isdigit():
#jesli podzielna przez 3
if int(liczba) %3==0:
print("Podzielna przez 3")
# w przeciwnym wypadku czy podzielna przez 5
elif int(liczba) %5==0:
print("Podzielna przez 5")... |
e3d0507ad6e0377d29125bd3b2544d76fb0627d7 | sidtrip/hello_world | /CS106A/week4/sec4/trim_crop.py | 1,170 | 3.921875 | 4 | from simpleimage import SimpleImage
def main():
image = SimpleImage('images/karel.png')
trimmed_img = trim_crop_image(image, 30)
trimmed_img.show()
def trim_crop_image(original_img, trim_size):
"""
This function returns a new SimpleImage which is a trimmed and
cropped version of the original ... |
3938042f21cbe4285b623c0be875f36ca641884f | Adam-Albert/cp1404practicals | /prac_04/lists_warmup.py | 786 | 4.09375 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
# numbers[0] = 3
print(numbers[0])
# numbers[-1] = 2
print(numbers[-1])
# numbers[3] = 1
print(numbers[3])
# numbers[:-1] = 3 1 4 1 5 9
print(numbers[:-1])
# numbers[3:4] = 1
print(numbers[3:4])
# 5 in numbers = true
print(5 in numbers)
# 7 in numbers = false
print(7 in numbers)
# "3" i... |
292e9cca4adccb0174dae45816db7d75d8642bd9 | jsygal/TrainPy | /Python/exercise/Udemy/FIleOperations/file2.py | 853 | 3.5625 | 4 | #!/usr/bin/env python3
'''
Requirement:
Create a program that opens file.txt. Read each line of the file and prepend it with a line
number.'''
import time
with open('/Users/jishnusygal/VSCode/myCode/pythonBegin/exercise/Udemy/FIleOperations/animals.txt') as file:
animals=[];
for line in file:
animals... |
b79db6d1ab13b9cebd20c378e0d930898fb79b40 | rasyidev/Google-IT-Automation-with-Python | /Course 1 - Crash Course on Python/21-letter-frequency.py | 188 | 3.859375 | 4 | def get_freq(text):
res = {}
for letter in text:
if(letter not in res):
res[letter] = 0
res[letter] += 1
return res
res = get_freq("hello world!")
print(res) |
34a2e2a11dc2c7531ad358ca2deea00fb66958b1 | emanuel-mazilu/python-projects | /timer/timer.py | 556 | 3.890625 | 4 | import tkinter as tk
window = tk.Tk()
window.title("Timer")
def countdown(count):
mins, secs = divmod(count, 60)
if mins >= 60:
hours, mins = divmod(mins, 60)
else:
hours = 0
label1['text'] = str(hours).zfill(2) + ":" + str(mins).zfill(2) + ":" + str(secs).zfill(2)
if count > 0:
... |
dac8d916a2a7d28e24ca2388757ec021ff48297c | LeetCodeSolution/ListNode | /delete_according_to_value.py | 382 | 3.75 | 4 | def delete_according_to_value(head, value):
if not head:
return None
if head.value == value:
return None
node = head
prev = None
while node and node.value != value:
prev = node
node = node.next
if not node:
return head
if node.value... |
21846fa3a05c7170508887418a6305da900f9fa3 | genzai0/HIKKOSHI | /suburi/gener/ex1.py | 232 | 3.703125 | 4 | def count_up():
x = 0
while True:
yield x
x += 1
def fib():
a,b = 0,1
while True:
yield b
a,b = b,a+b
for i in fib():#enumerate(fib()):
print(i)
if i == 10**9:
break
|
8c65db2e94b515e5fb723bd910ffc45cf941bdcc | noob-tactics/ML-Project | /Predicting-Fantasy-Football-Points-Using-Machine-Learning-master/rmse_bar_plot.py | 1,729 | 3.515625 | 4 | """
This program reads two csv files, rmse.csv and FantasyData_rmse.csv, and
construct bar plots to compare prediciton RMSE and FantasyData RMSE.
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""
Read prediction RMSEs and FantasayData's RMSEs
Find min RMSE for each position
"""
path = "d... |
ba708a5fa5f61c9815ba676d0f739331a38808e4 | tokareff/xlrd-nameSalary-demo | /info.py | 2,113 | 3.71875 | 4 | import xlrd
#from xlrd import cellname #this is not needed unless you want to use the name of cell e.g A1
def open_xlBook(file_name, sheet_name):
data = xlrd.open_workbook(file_name)
sheet = data.sheet_by_name(sheet_name)
return sheet
def print_contents(sheet):
for row_index in range(sheet.nrows):
... |
b2d057122ee5588fc1115beada6c0ddeabda72c0 | benjaminpotter/HatchProjects | /So Many Words/base.py | 661 | 3.890625 | 4 | word = "SOMANYWORDS"
mainColor = color(255,255,255)
secondaryColor = color(255,0,0)
coloredWord = 7
backgroundColor = color(0,0,0)
wordSize = 15
multipleWords = []
counter = 0
wordLength = word.length
background(backgroundColor)
def combineText():
for i in range (0, 300):
multipleWords = multipleWords + word
com... |
2e2785f482816fe56847c751911afe13d41e851f | kyana1234/Back_to_the_Loonaverse | /bullet.py | 912 | 3.53125 | 4 | import pygame
import constant_movement
class Bullet(constant_movement.ConstantMovement):
"""Projectiles that the players shoot to destroy the aliens.
Subclass of ConstantMovement
Attributes:
Please reference constant_movement.py for attributes
Functions:
get_img()
"""
img: ... |
93b504520b8dbb07d500b33fddc1aabeec8f54c6 | SiddhiPevekar/Python-Programming-MHM | /prog22.py | 166 | 4.34375 | 4 | #program to print table of a given number
n=int(input("enter any number to print the table for:\n"))
i=1
while i<=10:
print(n,"*",i,"=",n*i)
i+=1
|
0d66b868859d2ba1644ad71ee8aee871fb620ef3 | yorkypy/selise-intervie | /problems/binarySearch.py | 257 | 3.734375 | 4 | #Binary Search
from typing import Sized
def binarySearch(arr,n):
size=len(arr)
for i in range(size):
if arr[(size/2)]==arr[i]:
return arr[i]
elif n>arr[(size/2)]:
pass
if __name__ == "__main__":
pass
|
afc3704a2f8fc05431661bbc14d90181233d4cb6 | robin8a/udemy_raspberry_machine_learning | /Codes/Course_codes_image/4.4-Varying_Brightness.py | 1,170 | 3.625 | 4 | # Varying Brightness of Images using Add and Subtract Operations
# Import Computer Vision package - cv2
import cv2
# Import Numerical Python package - numpy as np
import numpy as np
# Read the image using imread built-in function
image = cv2.imread('image_4.jpg')
# Display original image using imshow built-in funct... |
8d906e3fb5539b24114e2f9f887e92a8403a4807 | Klakurka/BattleShip | /BattleShip.py | 11,257 | 3.734375 | 4 | from sys import exit
from random import randint
class player(object):
def __init__(self):
self.ship_Board = gameBoard()
self.ship_Board.initialize_Ships()
self.firing_Board = gameBoard()
self.shot_Log = []
self.firing_Queue = []
self.boat_Hit_Log = []
self.rand_Queue = []
def shots_Fired(self... |
e6c57c7a2d5f3ecae3b1e4fd269416f972079835 | cjmcv/hpc | /coroutine/asyncio/base_hello_world.py | 747 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
brief:
Hello world.
Record the basic usage of async, await and loop.
async: It is used to declare a coroutine function.
await: It is used to suspend its own coroutine and wait for another to complete.
loop: The event loop is the core of every asyncio a... |
65af14afb38898ac4e6690fa7960872df045cb60 | jonathenzc/Algorithm | /LeetCode/iter1/python/CoutingBits.py | 383 | 3.515625 | 4 | class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
bitLst = []
if(num>=0):
bitLst.append(0)
for i in range(1,num+1):
bitLst.append(bitLst[i>>1]+(i&1));
return bitLst
... |
e4021908627f1d0b9ad6d1cbcc8179214a040bfd | chasemp/sup | /suplib/durations.py | 789 | 3.5 | 4 | import os
import time
class Timer(object):
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
"""http... |
def63c138ed6722668bc8eeca2936f3713278fc2 | acharles7/problem-solving | /strings/max_numerical_value.py | 332 | 4 | 4 | #Extract maximum numeric value from a given string
def extractMaximum(S):
num, res = 0, 0
for i in range(len(S)):
if(S[i] >= '0' and S[i] <= '9'):
num = num * 10 + int(S[i])
else:
res = max(res, num)
num = 0
return res
S = 'abchsd2031sdhs'
print(extract... |
f15923c1032052598e9eb46427892131443ff55b | andylamgot/handwriting-digi-recognition | /handwritten_digit_recognition.py | 1,106 | 3.71875 | 4 | '''
This dataset is made up of 1797 8x8 images.
Each image is of a hand-written digit.
In order to utilize an 8x8 figure,
we have to first transform it
into a feature vector with length 64.
'''
# Import dataset
from sklearn.datasets import load_digits
# Import the sklearn for SVM
from sklearn import... |
5d02513ae81556f8700e7860d91050aa8e93edc2 | RaphaelMolina/Curso_em_video_Python3 | /Desafio_52.py | 492 | 3.734375 | 4 | from Titulo import Titulo
d = Titulo(52, 'Números primos!!!')
d.Desafio()
n = int(input('Digite um número: '))
t = int()
for contador in range(1, n + 1):
if n % contador == 0:
print('\033[34m', end=' ')
t += 1
else:
print('\033[31m', end=' ')
print('{}'.format(contador), end=' ')
... |
c2df64b708c5065bb57ff1b3ed28310eb71a7a90 | jawhelan/PyCharm | /PyLearn/Exercise Files/Other/Sets.py | 536 | 4.0625 | 4 | groceries = {"milk", "bread","bear","juice", "apples","bear"} # sets will not print dups
groceries2 = ["milk", "bread","bear","juice", "apples","bear"] # list will print all and are imutable
groceries3 = ("milk", "bread","bear","juice", "apples","bear") # tupels will print are and is mutable
print(groceries)
pr... |
6d50b8c2d78c53983c01687d3498bbcde2be2b7e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2498/60782/270702.py | 794 | 3.84375 | 4 | """
题目描述
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
"""
"""
输入描述
一个非负整数数组。
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
"""
"""
输出描述
排序后的数组
"""
the_array = eval(input())
odd = []
even = []
answer = []
for i in t... |
8b12cbc814aedc7643f4ed605bebd205254cc2a0 | CyberCrypter2810/CFPython | /code102/ch_6/average_temperature.py | 1,068 | 4.1875 | 4 | # average_temperature.py
'''
Program displays results from temperature.txt file
and then calculates the average of the results.
'''
# main function
def main():
# Sets up accumulator
total = 0
average = 0
try:
# Open temperature.txt
temp = open('temperature.txt', 'r')
... |
a87ba2a557ca288c16c45e8ebe776e8a331ce7b5 | abhisheksethi02/Hackerrank | /Html_Parser.py | 863 | 3.6875 | 4 | '''
You are given an HTML code snippet of N lines.
Your task is to print start tags, end tags and empty tags separately.
'''
import re
from html.parser import HTMLParser
if __name__ == "__main__":
class MyHTMLParser(HTMLParser):
def handle_comment(self, data):
return super().handl... |
17fce39561babd3ed54d8ca13b0020b297cee228 | tnakaicode/jburkardt-python | /r8lib/p00_f.py | 8,185 | 3.578125 | 4 | #! /usr/bin/env python
#
def p00_f ( prob, n, x ):
#*****************************************************************************80
#
## P00_F evaluates the function for any problem.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John ... |
d9f84025a58936165f37d0dcf3f8e22aa5135202 | hhfcode/Code-Projects | /Face Tracking Camera/Python/Camera.py | 6,193 | 3.546875 | 4 | """ This is the Class for the Camera -- Henrik"""
import cv2, Servo, time
import numpy as np
from datetime import datetime
#Frame Setup is X, Y - WE CAN USE THIS DATA TO GET TO KNOW CENTRER AND CREATE A CENTRE SQUARE THAT we AIM TO ACHIEVE
FrameX = 1080 # 200 + and - should make a centrer box from half
FrameY = 640... |
785d40f3dea2288e3867612fc34342aba54b3375 | Hamim30/Password-Mangement | /main.py | 1,083 | 3.59375 | 4 | from cryptography.fernet import Fernet
def load_key():
file= open("key.key","rb")
key=file.read()
file.close()
return key
# def write_key():
# key=Fernet.generate_key()
# with open("key.key","wb") as key_file:
# key_file.write(key)
# write_key()
key= load_key()
fer=... |
2e44597ea19895b45d2f5d0912e2092719ea3a7e | thomasdeneux/xplor | /xplor/xdata.py | 111,032 | 3.59375 | 4 | """xdata module is a module to define a structure to store the data in the
form of an N dimensional array as well as the description of the data and each
of the dimensions (names, types, units, scale, ...)
This module uses:
- pandas as pd
- numpy as np
- operator
- abc
There are 6 classes in this m... |
af6f8328f1e6a304734b2e31c7f70405bb4ad2bb | jhoneal/Python-class | /tuition.py | 256 | 3.5 | 4 | """Suppose that the tuition for a university is $10,000 this
year and tuition increases 7% every year. In how
many years will the tuition be doubled?"""
year = 0
tuition = 10000
while tuition < 20000:
tuition = tuition * 1.07
year+=1
print(year)
|
c88ddb412c2866c3dec02904916afebe2a70ef5c | stephen-weber/Project_Euler | /Python/Problem0128_Hexagonal_Tile_Differences.py | 5,646 | 3.703125 | 4 | """
Hexagonal tile differences
Problem 128
A hexagonal tile with number 1 is surrounded by a ring of six hexagonal tiles, starting at "12 o'clock" and numbering the tiles 2 to 7 in an anti-clockwise direction.
New rings are added in the same fashion, with the next rings being numbered 8 to 19, 20 to 37, 38 to 61, and ... |
832b19d9240c1eaba514a954983dbd3a4b09f90c | PacktPublishing/Mastering-OpenCV-4-with-Python | /Chapter10/01-chapter-content/k_means_color_quantization.py | 2,269 | 3.859375 | 4 | """
K-means clustering algorithm applied to color quantization
"""
# Import required packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
def show_img_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = c... |
1f39ae582667b7a12e07d832ea04b6643431fdb3 | skanwat/python | /learnpython/fibonacciseries.py | 218 | 3.625 | 4 | def fibo(x):
if x == 1:
return 1
elif x == 0:
return 0
else:
return (fibo(x-1) + fibo(x-2))
list=[]
for x in range(1,10):
z=fibo(x)
list.append(z)
print(z)
|
714e830023ebcc948a0ff84c9a4c3e668623bbf4 | ngxson/storeData | /controle3/ex2.py | 364 | 3.625 | 4 |
def ed(L,M=[]):
if not(L):
return M
a = L.pop(0)
if a not in M:
M.append(a)
return ed(L,M)
def ed_iterative(L):
M=[]
for a in L:
if a not in M:
M.append(a)
return M
L = [2,3,2,6,8,9,9,10,9,3,6,7,8,8,9]
print(ed(L))
L = [2,3,2,6,8,9,9... |
3457645d7c25b94e4d323124d595133f60dad9b9 | cp4011/Algorithms | /LeetCode/4_寻找两个有序数组的中位数.py | 2,955 | 3.5 | 4 | """给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
"""
''' left_part | right_part
A[0], A[1], ..., A[i-1] | A[i], A[i+1], ..., A... |
c2f37e427da1f1dc7fcc775a034c27dcc86f2e06 | NotOrca22/learning_algorithms | /sorting.py | 8,708 | 3.96875 | 4 | from random import randint
from timeit import repeat
# # import statistics
# #
def run_sorting_algorithm(algorithm, array):
# Set up the context and prepare the call to the specified
# algorithm using the supplied array. Only import the
# algorithm function if it's not the built-in `sorted()`.
setup_cod... |
3328b4aac1afac8fd81bd84f7ddd9363d62baf59 | fanzhihai/Data-Structure-Algorithms | /Sorting Algorithm/bubble_sort.py | 699 | 4.15625 | 4 | # -*- coding:utf-8
"""
# 冒泡排序
# 将数组当中的左右元素,依次比较,保证右边的元素始终大于左边的元素,保证最大的在右边,就像冒泡一样,大的气泡在下面
# @author:BigOceans
# https://github.com/fanzhihai
"""
def bubble_sort(lists):
count = len(lists)
for i in range(count):
for j in range(i+1,count):
if lists[i] > lists[j]:
... |
3a375f4463b0d0b9948dc72241c0868fa7907476 | fatima-rizvi/CtCI-Solutions-6th-Edition | /Ch1-Arrays-and-Strings/02_check_permutation.py | 617 | 3.890625 | 4 | # Given two strings, check if one is a permutation of the other
def check_permutation(str1, str2):
freq1 = {}
freq2 = {}
for char in str1:
if freq1.get(char):
freq1[char] += 1
else:
freq1[char] = 1
for char in str2:
if freq2.get(char):
freq2[char] += 1
else:
freq2[char... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.