blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
74affd066024bc1bdd0f6f693349f533136b9e12 | Harman-12/Data-Analysis-c107 | /data-analysis.py | 293 | 3.546875 | 4 | import pandas as pd
import csv
import plotly.express as px
df = pd.read_csv("data-student vs level.csv")
mean = df.groupby(["student_id", "level"], as_index = False)["attempt"].mean()
fig = px.scatter(data_frame=mean, x="student_id", y="level", size="attempt", color="attempt")
fig.show() |
ddb22db291456440e84ca30fcb7bd75fce147f02 | ndombrowski20/work_in_progress | /ANNs/scrap/cleaning_data.py | 3,963 | 3.96875 | 4 | import csv
import os
# first we need to be able to tell if a list is a proper week
def check_week(a_list):
# first, cause i'm paranoid
if len(a_list) != 6:
raise Exception("It's monday to monday bruh")
# so first, we grab the number of the date which is the last value. This means we're limiting ... |
3d740557102dfab6aecc79cc58d3c41bd5aa4b08 | MEENUVIJAYAN/python | /python lab 5/name.py | 133 | 4.1875 | 4 | #Python program to print full name
a = str(input("Enter First Name:"))
b = str(input("Enter Second Name:"))
print(a + " " + b)
|
c55369455aa0cbee81b335757eb7b26ead4b225f | LezardWhiteGlint/Practice_backup | /Data filter.py | 723 | 3.859375 | 4 | def listgenerator():
import random
global listbefore
listbefore = []
for i in range(0,10):
num = random.randint(1,100)
listbefore = listbefore + [num]
print('It is the initial list')
print(str(listbefore))
def list_filter():
global listafterbig
global listaftersma... |
6ed3fd01f6c975af06047f48223e103737b61b64 | TechInTech/pCode | /pNode/node.py | 3,003 | 3.734375 | 4 | #!/usr/bin/python3
#-*- coding:utf-8 -*-
"""
File: node.py
Description: This file defines the class node
Author: Larry Yu
Initial Data: Oct 28th, 2018
"""
import sys
sys.path.append("/cygdrive/d/pCode")
class Node(object):
def __init__(self, data, next):
self._data = data
self._next = next
de... |
acf9e1e7ce17f77252fd7133164ad7865eaf5e6b | JenZhen/LC | /lc_ladder/Basic_Algo/graph-bfs-dfs/BFS/Rotting_Oranges.py | 2,294 | 3.578125 | 4 | #! /usr/local/bin/python3
# https://leetcode.com/problems/rotting-oranges/submissions/
# Example
# In a given grid, each cell can have one of three values:
#
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange... |
647c67ab8b03599efa9799a026566703546f66a9 | arindam-1521/moree | /this.py | 221 | 3.515625 | 4 | print("Hello world")
# This is a very basic code which shows how to print a statemnet in python.
print("Hello world")
print("Git hub is available")
print("GitHub is available")
print("This is a new and most usable stuff") |
729da2e49337117daa721f9551771a108c1af489 | luis-manuel352/AvancePIA-Programacion | /main.py | 1,001 | 3.796875 | 4 | # Acceso de datos a la clase Contacto
import re
# Validador de expresiones regulares
def RegEx(_txt,_regex):
coincidencia=re.match(_regex, _txt)
return bool(coincidencia)
# Expresiones regulares para cada campo.
telefonoRegEx="^[0-9]{10}$"
nombreRegEx=""
entidadValida=True
# Pregunta de teléfono que sea de ... |
dcf098eb229e805a41eb677416d57931ff383037 | ZenithClown/decompose | /pca.py | 2,503 | 3.96875 | 4 | # -*- encoding: utf-8 -*-
import numpy as np
class PCA(object):
"""Dimension Reduction using Principal Component Analysis (PCA)
It is the procces of computing principal components which explains the
maximum variation of the dataset using fewer components.
:type n_components: int, optional
:par... |
0e91628c903662971299334a6b88e3f524e1f9a7 | vedangmehta/Algorithms | /dp/longest_subsequence.py | 861 | 3.78125 | 4 | def longest_seq(seq):
""" returns the longest increasing subseqence
in a sequence """
count = [1] * len(seq)
prev = [0] * len(seq)
for i in range(1, len(seq)):
dist = []
temp_prev = {}
for j in range(i):
if seq[j] < seq[i]:
dist.append(count[j])
... |
d2635bd663319cb4415afd3c414db0b1cd4b2f7e | JHuraibi/Python_Assignment_02 | /Question_01.py | 9,591 | 4.09375 | 4 | # Author: Jamal Huraibi, fh1328
# Assignment 2
# Question 1
# Python sorted() Doc: docs.python.org/3/library/functions.html#sorted
import statistics # For .median() and .stddev()
# ----| Functions |--------------------------------------------------------... |
abefb67e9a24b4986a174d72fedaefb778e5ac7e | coditza/craps | /fizzbuzz.py | 329 | 3.671875 | 4 | def multi(max, mapping, separator):
result = []
for i in range(1, max + 1):
fbzz = ''.join([mapping[x] for x in mapping if i % x == 0])
result.append(fbzz if len(fbzz) else str(i))
return separator.join(result)
if __name__ == '__main__':
print("USAGE: multi(max, mapping, separator) -> ... |
c41487fe36c4664f2f3dfc04e40db46f218b5755 | JennyHWAN/box-paradox | /box paradox model.py | 2,230 | 4.59375 | 5 | '''
Bertand's Box Paradox: A Simulation
Version 0.3
further info: https://en.wikipedia.org/wiki/Bertrand%27s_box_paradox
'''
import random
goldright = 0
golddraw = 0
silverright = 0
silverdraw = 0
n = 0
print('''
This model will simulate Bertrand's Box Paradox in the following way:
It will randomly select one of the... |
5dbfa6abe1e6a724afa6ea02acbaba24131f2bb1 | LauritsStokholm/EksFysII | /ex4/Data/dataconverter.py | 706 | 3.609375 | 4 | # # # # # # # # Part 0 ~ Converting csv into good format # # # # # # # # # # #
""" BEWARE: ONLY RUN THIS ONCE!
This file is created to change csv formatting """
for item in data_dir:
# Read only
with open(item, "r") as file:
my_file = file.read()
my_file = my_file.replace(',', '.') # Changing... |
e8e731c0586e124974c802cf7f774dea242a7d26 | zywh/waterlooccc | /2016/Junior/p5.py | 524 | 3.53125 | 4 | vInput=['1','3','5 1 4','6 2 4']
vInput=['2','3','5 1 4','6 2 4']
#vInput=['2','5','202 177 189 589 102','17 78 1 496 540']
vQuestion=vInput[0]
vCount = int(vInput[1])
vList1 = [int(x) for x in vInput[2].split()]
vList2 = [int(x) for x in vInput[3].split()]
vList1.sort()
if ( vQuestion == '1'):
vList2.sort()
else... |
c0ad7ed37947fa684d9993461b8589200a3df729 | Nafani4/Home_work | /Calendar/calendar_modules/lesson-07.py | 1,916 | 3.8125 | 4 | """
SQL - Standart Query Language
- DDL - Data Definition Language
(CREATE TABLE)
- DML - Data Manipulation Language
(SELECT, INSERT, UPDATE, DELETE)
СУБД - Система управления базами данных
Primary Key (Первичный ключ)
Уникальный идентификатор
Может быть int, может быть str
Может быть составной (су... |
05aee30f1c578b9daac23be19fec53646e641131 | Richardmb89/Python-101 | /One Array a Rotation of Another.py | 1,168 | 4.0625 | 4 | # Implement your function below.
def is_rotation(list1, list2):
if len(list1) != len(list2) or len(list2) == 0:
return False
if not set(list1) <= set(list2) and not set(list1) >= set(list2):
return False
index = 0
while list1[0] != list2[index]:
index+=1
list2 = list... |
cb4c0afffa1b47f2bd03a8e89830cb9702057724 | HIRO-group/roboskin | /roboskin/calibration/convert_to_lowertriangular_matrix.py | 12,714 | 3.90625 | 4 | """
This is a python file containing a test case and a class to convert any matrix which is convertible Lower Triangular(LT)
Matrix to Lower Triangular Matrix
Algorithm:
*) As this is a binary matrix, and also lower triangular, the total sum of elements should be at max n(n+1)/2, else it
can't be a LT matrix
*) There c... |
4bf341bbd114f53be77dbf1d648ea22011f5f2bf | shayd3/Python | /Algorithms/BinarySearch.py | 1,061 | 3.9375 | 4 | import numpy as np
import math
# Creates an array of specified length with random integers from 0-9999
def create_array(arraySize):
return np.random.randint(10000, size=int(arraySize))
# Binary search algorithm
def binary_search(a, target):
# Number of comparisons while searching
comparisons = 0
min = 0
max = l... |
34af9edfefb3677ff9b8053981cf0d6c80e85ee9 | Aghyad1993/programming | /les6/les6_5.py | 144 | 3.71875 | 4 | def swap (lst):
if len(lst) > 1:
lst[0], lst[1] = lst[1], lst[0]
return lst
lst = [4, 0, 1, -2]
res = swap(lst)
print (res) |
db1875ffa7ce9d9ae79b194c44b6859c41f923f8 | fellipegpbotelho/design-patters-python | /src/behavioral/strategy/concept.py | 2,422 | 4.40625 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List
class Strategy(ABC):
"""The Strategy interface declares operations commom to all supported versions of
some algorithm.
The Context uses this interface to call the algotithm defined by Concrete Strategies.
"... |
a0d48d0082caf265096e353555facb7647663947 | ZhangArcher/aufgabenis | /regression/task2.py | 710 | 3.578125 | 4 | import matplotlib.pyplot as plt
import numpy as np
def w0(x: np.ndarray, y: np.ndarray):
return y.mean() - w1(x, y)*x.mean()
def w1(x: np.ndarray, y: np.ndarray):
return ((x*y).mean() - x.mean()*y.mean())/((x**2).mean() - x.mean()**2)
def hypothesis(xval, w0, w1):
return w0 + w1*xval
x = np.array([0... |
93f7561fd8fc4f5c28833aaa001c6edcc69810b1 | Rogerio-ojr/EstudosPython | /Exercicio27.py | 155 | 3.71875 | 4 | nome = input('Digite um nome: ')
nome = nome.strip()
for i in nome.split():
a = i
print(f'O primeiro nome e {nome.split()[0]}, e o Ultimo nome e {a}')
|
b92372005c418ea6a83bcc9a2d325c5b16ea8af5 | bjbean/python_study | /3_字符串.py | 2,186 | 4.3125 | 4 | tip ="""
python字符串示例
1.python语言,可以使用多种引号来引用。
双引号 "this is a string"
单引号 'this is a string'
2.多行文本,使用三个单引号或双引号引用。
var = '''this is a line
but have multi lines'''
3.文本中含有引号,可在前面使用转义符(\)
var_str='He said:"Are\\'t can\\'t shouldn\\'t would\'t"'
4.字符串嵌入值(%s)
myscore=100
message="I scored %... |
2fa034e0589bc9120733a0827ba96e608a486cc1 | randell/Project-Euler | /0001-multiples_of_3_or_5-a.py | 502 | 3.828125 | 4 | """
Project Euler Problem 1
Title:
Multiples of 3 or 5
Description:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get
3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Solution:
This version is a naive implementation using a loop... |
fff828c8f8761cc47bcce70944422aa5cc7073da | saranraj-git/pyJanaDay1 | /init_Example.py | 143 | 3.625 | 4 | class MyClass(v1,v2,v3):
def __init__(self,v1,v2,v3):
self.x1 = v1
self.x2 = v1
self.x3 = v1
p1 = MyClass(1,2,3)
print(p1.x1) |
42c5441b31e03e1a3139b184baa5708c5867506e | augusnunes/data-struc-py | /stack/stack_binary.py | 451 | 3.9375 | 4 | """
exemplo de como usar pilha pra passar
um número da base 10 pra base 2
"""
from stack import Stack
def mudaBinario(numero10):
s = Stack()
while numero10 > 0:
remainder = numero10%2
s.push(remainder)
numero10 //=2
numero2 = ""
while not s.is_empty():
numero2 += str(s... |
69d99375f3295bb2488fc43bdaf72870f4e08812 | PedroRamos360/PythonCourseUdemy | /kivy/aulas/Seção 12 - Estrutura de dados/OperaçõesListas.py | 411 | 4.21875 | 4 | l = list('abc')
# append para adicionar elementos
l.append('d')
print(l)
# insert para adicionar elementos em localizações específicas
l.insert(0, '0')
print(l)
# alterar items
l[0] = 'a0'
print(l)
# clear para tirar todos elementos de uma lista
l.clear()
l = list('abcde')
# pop para deletar um item
print(l.pop(-1... |
797d409ba7eda8e9d84d91633beccdbcdbf7602d | antichown/udemy_courses | /financial_analysis_py/3_python_crash_course/Python Crash Course Exercises - Solutions.py | 3,904 | 4.59375 | 5 | #!/usr/bin/env python
# coding: utf-8
# # Python Crash Course Exercises - Solutions
#
# This is an optional exercise to test your understanding of Python Basics. The questions tend to have a financial theme to them, but don't look to deeply into these tasks themselves, many of them don't hold any significance and are... |
ab4147ff177d67dad21cbbbef8798b8349a0b17c | melijov/course_python_essential_training | /kwargs-working.py | 392 | 3.671875 | 4 | #!\usr\bin\env python 3
#Keyword Arguments: diction instead of a tuple
def main():
kitten(Buffy='meow',Zilla='grr',Angel='rawr')
x = dict(Buffy='meow',Zilla='grr',Angel='rawr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k,kwargs... |
b834aa5b0ead3fdf3934d5c367a96b52f3ec4612 | Aquariuscsx/python | /homework/day17/person.py | 763 | 3.859375 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(self.name, self.age)
class Student(Person):
def __init__(self, name, age, grade):
Person.__init__(self, name, age)
self.grade = grade
class Worker(Person):
def __... |
865281468895281189d0466cb05db7b14b76095f | azozello/swe | /leetcode/medium/search_in_a_matrix.py | 2,408 | 3.796875 | 4 | def solve(matrix: [[int]], target: int) -> bool:
def find_index(start_index: int, is_vertical: bool):
local_index = -1
coords = [[start_index + j, j] for j in range(length)] if is_vertical \
else [[j, start_index + j] for j in range(length)]
for coord in coords:
if ... |
960ce48017ee9c7730a4e6471349ec2683d3167c | rahulb246/leetcode-may-challenge | /week-1/isCousins.py | 1,560 | 4.09375 | 4 | # In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
# Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
# We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
#... |
b3eed46abcdfe7a931c95601a8a4cc2d56ed2bf5 | jimtheguy/PY4E | /course2/week3/words.py | 436 | 4.625 | 5 | # Jim R
# Write a program that prompts for a file name, then
# opens that file and reads through the file, and print
# the contents of the file in upper case.
# Use the file words.txt to produce the output below.
#Get filename from user
fname = input("Enter file name:")
fhandle = open(fname)
#loop through lines in... |
21e80d0d76c198e785b1e62c003fb90ce4067ac5 | Shubham1304/Semester6 | /ClassPython/6.py | 1,795 | 4.3125 | 4 | #Class of 5th February 2019
#for loops
#file handling in python
#Why do we need files ? Persistence ie file stores the data permanently
#How to open and create a file in python?
# open : r,w,a
# perform certain operations
# close the file
#Errors that can be encountered if we dont close the file ? We can not ... |
5dae00ec88a28c97cd1f059259afd574c57ffe2f | manu-mannattil/nolitsa | /examples/delay/adfd_roessler.py | 1,026 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""ADFD algorithm using time series from the Rössler oscillator.
The time delay is taken to be the delay at which the derivative of the
ADFD falls to 40% of its initial value. The estimated time delay is 5.
Compare with Fig. 6 of Rosenstein et al. (1994).
"""
import num... |
6e35394b0453d96adf9896cf5449865013ca6de1 | zephyr2095/pynet-learning | /lesson5/exercises/exercise1b.py | 1,080 | 3.765625 | 4 | #!/usr/bin/env python3
'''
Expand on the ssh_conn function from exercise1 except add a fourth parameter 'device_type' with a default value of 'cisco_ios'.
Print all four of the function variables out as part of the function's execution.
Call the 'ssh_conn2' function both with and without specifying the device_type
... |
05f70859e996636b1da555985f91754d64950afe | Kor-KTW/PythonWorkSpace | /Basic/4_4_set.py | 459 | 4.1875 | 4 | #set : can't overlap, no order
my_set = {1,2,3,3,3}
print(my_set)
alphabet={"a", "b", "c"}
betabet= set(["b", "c", "d"])
# intersection
print(alphabet & betabet)
print(alphabet.intersection(betabet))
# sum of set
print(alphabet|betabet)
print(alphabet.union(betabet))
#differnce of set
print(alphabet-betabet)
print(... |
2c4cef117b929c8748e7bc13c3d55c78e74b98c1 | YSreylin/HTML | /1101901079/Tuple/Tuple17.py | 385 | 4.53125 | 5 | #write a Python program to unzip a list of tuple into individual lists
list_of_tuples = [(1,2,3),(4,5,6),(7,8,9)]
print("List of Tuple is:",list_of_tuples)
individual_list = [list(i) for i in list_of_tuples]
print('individual list created: ', *individual_list)
#the following still creates a list of tuples
#print... |
12da6468257f673c94549bb052d70ee15e1bb9e5 | meck93/hs17-datavis-ex | /ex3/ex3_task7.py | 4,853 | 3.875 | 4 | # -*- coding: utf-8 -*-
""" Data Visualization HS 17
Implemenation of Exercise 3
Moritz Eck - 14 715 296"""
import numpy as np
def readCSV(filename):
"""
Reads the .data file and creates a list of the rows
Input
filename - string - filename of the input data file
Output... |
fb6052f2350a2f45ebdf777bd1b58aac6937852d | bakunobu/exercise | /1400_basic_tasks/chap_4/4_135.py | 201 | 3.984375 | 4 | def which_season(x:int) -> str:
if 3 <= x < 6:
return('Spring')
elif 6 <= x < 9:
return('Summer')
elif 9 <= x < 12:
return('Fall')
else:
return('Winter') |
265ba7915f9dd05ed927da67179e2cfb0db65ae8 | amarbecaj/MidtermExample | /zadatak 5.py | 1,924 | 3.921875 | 4 | """
=================== TASK 5 ====================
* Name: Del Boy Millionaire
*
* Help Del Boy become a millionaire. Del Boy is
* trading bitcoins on crypto-exchanges with simple
* algorithm. He is buying where the price of bitcoin
* is the lowest and selling where the bitcoin is
* the most expensive. Write a fun... |
90301909212503c390145a814665f0b54ddc1538 | AhmedElsagher/algorithm-toolbox | /week3_greedy_algorithms/3_car_fueling/car_fueling.py | 781 | 3.65625 | 4 | # python3
import sys
def compute_min_refills(distance, tank, stops):
# write your code here
whats_left=tank
num_refils=0
for i in range(len(stops)-1):
if (whats_left>0 )and((stops[i+1]-stops[i])<whats_left):
whats_left-=(stops[i+1]-stops[i])
elif tank>(stops[i+1]-stops[i]):... |
d1b49c773cbd57414e720adb24b11ed68e571905 | catVSdog/design_patterns | /bridge.py | 1,259 | 4.46875 | 4 | """
桥接模式:
又名:柄体模式、 接口模式
使抽象部分与实现部分分离,使他们可以各自变化
但是根据UML类图看,感觉更像两个聚合关系类之间的结合
一个类作为另一个类实例的一个属性
"""
class Car:
def __init__(self):
self.color = None # A类持有 B类 二者时聚合关系, color类是Car类的一个属性.
# 当然也可以反过来,让car类作为color类的属性,但是颜色拥有汽车在尝试上讲不通啊.还是汽车拥有颜色比较合适
def set_color(self, color):
assert isinstanc... |
75044f537838abe39ed6f74decb96f6de9166d00 | qmnguyenw/python_py4e | /geeksforgeeks/algorithm/easy_algo/4_20.py | 7,888 | 4 | 4 | Check if the given string is K-periodic
Given a string **str** and an integer **K** , the task is to check whether the
given string is **K-periodic**. A string is k-periodic if the string is a
repetition of the sub-string **str[0 … k-1]** i.e. string **“ababab”** is
**2-periodic**. Print **Yes** if the given ... |
c2da391160141f98f15ac6d926a2a4bacfe9ad11 | royqh1979/PyEasyGraphics | /examples/animates/equilateral.triangles.py | 1,019 | 3.8125 | 4 | """
Rainbow
From "Math Adventures with Python" Part II, Chapter 5, "Drawing Complex Patterns Using Triangles"
"""
import sys
from easygraphics import *
import math
import random
def triangle(size):
"""
Draw an equilateral triangle
:param size:
"""
size_b = size * math.sqrt(3) / 2
size_c = s... |
5d045cbdf278885ed42cf7fd0b4ac5aafbf0d483 | Ramkrish26/PythonPractice | /primeNumber.py | 326 | 4.25 | 4 | # To check whether a number is prime or not
num = input("Enter the number: ")
flag=0
if(int(num)==1):
print("It is neither neother Prime nor Composite number")
for i in range (2,int(num)):
if(int(num)%i==0):
flag=1
if(flag==0):
print("It is a prime number")
else:
print("It is not a prime num... |
f20adf22959a59ecf9aa756f8d664395dbc2d215 | valefaraz/lab | /alumnos/58018-Valentin-Faraz/clase01/ejercicio5.py | 720 | 3.84375 | 4 | def fibo(n,a=0,b=1): #Este codigo muestra la serie de Fibonacci
while n!=0: #Mientras n sea distinto de cero se ejecuta la secuencia
return fibo(n-1,b,a+b) #N disminuye en uno, 'a' toma el valor de 'b' y 'b' toma el valor de 'a+b'
return a ... |
270f6b2dd1920c304e5ce9349c0d5ad631876975 | AndRoo88/Baseball-Flight-Calculator | /umba/umba1.py | 23,222 | 3.625 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
#This older version does not contain the SSW model but may still be
#useful for comparision
def main():
print("This baseball trajectory calculator models \
still air at sea level with about 60% humidity.\nThe ambient\
conditions are fixed c... |
5789dcd5033b670b406374d3a8d66020efb59566 | weguri/python | /listas_tipos/list/ordena_reverter.py | 241 | 4.125 | 4 | """
reverse()
Não reorganiza em ordem alfabética inversa;
ele simplesmente INVERTE a ordem da lista:
"""
fruits = ["oxicoco", "maça", "kiwi", "melon", "abacaxi", "banana", "mango", "ananás"]
fruits.reverse()
print(fruits)
|
335f43c5d8bfe4b41d5140bbe13d5c600498b1d4 | ArthurSpillere/AulaEntra21_ArthurSpillere | /Exercícios Resolvidos/Maykon/01-Exercicios/Aula008/Ex1.py | 1,404 | 3.96875 | 4 | #--- Exercício 1 - Funções
#--- Escreva uma função para cadastro de pessoa:
#--- a função deve receber três parâmetros, nome, sobrenome e idade
#--- a função deve salvar os dados da pessoa em uma lista com escopo global
#--- a função deve permitir o cadastro apenas de pessoas com idade igual ou super... |
dfac620d726ec88245af0acd532aa23bcb6d50fd | ArelyA/TC3048.2 | /Quad.py | 633 | 3.578125 | 4 | class Quad(object):
def __init__(self, op, left, right, dest):
"""
Creates quad dict with contents
OP | LEFT | RIGHT | DEST
"""
self.op = op
self.left = left
self.right = right
self.dest = dest
def reprQ(self, l):
#print(l)
return "".join(["{:^", str(l),"}"]).format(self.o... |
7211a3941efc1ab65e343a5cb865eec45bef7950 | luizortega27/Atividades-faculdade | /AC4-Quantidade de dígitos (função iterativa).py | 98 | 3.640625 | 4 | numero = str(input())
contador = 0
for i in numero:
contador = contador + 1
print(contador)
|
f1027bedc2ab107b40c833411cf663fdb8820361 | gmmann/MSPythonCourse | /complexconditions.py | 632 | 4.25 | 4 | # A student makes honour roll if their average is >= 85
# and their lowest grade is not below 70
gpa = float(input('What is your Grade Point Average? '))
lowest_grade = input('What is your lowest grade? ')
lowest_grade = float(lowest_grade)
if gpa >= .85:
if lowest_grade >= .70:
print('You made the h... |
8bc128efaee79f0fb6c17e7d3bf27963f0c53d86 | cm1819/carpentries | /hello.py | 146 | 3.921875 | 4 | num=154
if num>100 and num <150:
print("between 100 and 150")
elif num==100:
print ("Less than 100")
else:
print ("greater than 150")
|
4872b147ac8bd1a2fd8a3fc1983cecc90f2bac23 | joelrorseth/Snippets | /Python Snippets/Data Structures/union_find.py | 1,528 | 4.3125 | 4 | #
# Disjoint-Set (Union-Find) data structure
#
# The union-find tracks a set of elements, partitioned into a number of
# disjoint (non-overlapping) subsets. It essentially groups elements into
# subsets by maintaining array of parents for each element. Parents have
# parents, which have parents and so on. Eventually on... |
586bf3b38879f91b0c9405c127d5096c13ad7f32 | stofistofi/chess | /test_chessboard.py | 13,846 | 3.84375 | 4 | from chessboard import Chessboard
def test_create_board():
# test whether creating a board is as expected
expected_board = { 0:'R', 1:'N', 2:'B', 3:'Q', 4:'K', 5:'B', 6:'N', 7:'R',
8:'P', 9:'P', 10:'P', 11:'P', 12:'P', 13:'P', 14:'P', 15:'P',
16:' ', ... |
e5ee779f5b2df4abd73196eea1f675b782f5ff2f | jaroslawrutk/Python- | /09.05.2018/zadanie1.py | 562 | 3.5625 | 4 | import Tkinter as tk
import Tkfron as tkF
root = tk.Tk()
default_font=tkF.nameFront("TkDefaultFont")
default_font.configure(size=20)
root.option_add("*Front",default_font)
def read_v():
x=v.get();
if(v==1)
v=tk.IntVar()
rb1=tk.RadioButton(root,text="R",variable=v,value=1)
rb1.grid(column=0,row=0)
rb2=tk... |
39634af9c0bbad27d02b71d6d69e94003f2de4f6 | nitaicharan/UNIPE-P1-Sudoku | /limpa_digito.py | 784 | 3.625 | 4 | import curses
def limpa_digito(jogo):
menssagem = 'Deseja limpar jogo? (S/N): '
curses.cbreak()
curses.echo()
windowt = curses.newwin(2,100,15,0)
windowt.addstr(1,1,menssagem)
resposta = windowt.getch()
resposta = chr (resposta)
windowt.refresh()
if resposta in ['s', '... |
47e2b4fbc94a74fd70f53507511fd6d2f2566009 | ananya/HackerSkills | /Solutions/falconis/Task5/task5.py | 355 | 3.5 | 4 | import threading
def exp(x):
print("Square:", x**2)
def fact(x):
i = 1
ans = 1
while(i <= x):
ans *= i
i += 1
print("Factorial:", ans)
x = int(input())
thread1 = threading.Thread(target=exp, args=(x,))
thread2 = threading.Thread(target=fact, args=(x,))
thread1.start()
thread2.star... |
973174cb9b3971efcf3f91782a786809d2591de1 | NMCPLindsay/CIT228 | /Chapter6/rivers.py | 525 | 4 | 4 | print("===============6-5==============")
boardman={
"River":"Boardman River",
"State":"Michigan"
}
rioGrande={
"River":"Rio Grande",
"State":"Texas"
}
republican={
"River":"Republican River",
"State":"Kansas"
}
Rivers=[boardman, rioGrande, republican]
print("*****Rivers and States*****")
for r ... |
eb14c6f63d265a02e4a73c4750167f0bac32d4f1 | biosharp-dotnet-labs/ParOpt | /paropt/command.py | 626 | 3.859375 | 4 | """Command functions for use with external optimization functions"""
def format_fn(frmat):
"""Create a commandline function that builds a command line from a format string
Upon binding on parameters, String.format will be called to create a command line call.
Example:
>>> fn = format_fn("echo {1} {0... |
679efbb086a7e48811276ffd1e098b51567cc37a | ole511/hello_world | /44翻转单词顺序列.py | 535 | 3.8125 | 4 | # -*- coding:utf-8 -*- 将字符串转换成序列再调整的方法
class Solution:
def ReverseSentence(self, s):
# write code here
if not s: return ""
if s.isspace():return s
temp=s.split()
for i in range(len(temp)//2):
temp[i],temp[-i-1]=temp[-i-1],temp[i]
return ' '.join(temp)
... |
791c8ab37c6ad715df363fce87f30e8bbb80867b | gschen/sctu-ds-2020 | /1906101074-王泓苏/Day0324/test1.py | 2,121 | 4.15625 | 4 | class Node:
def __init__(self,value):
self.value = value #当前节点的值
self.next = None #下一个节点
class List:
def __init__(self):
#头节点
self.head = Node(-1)
#前插法创建单链表
def insert_before(self,data):
for i in data:
node = Node(i) #创建新节点
#判断头节点的下一个节点是否为空
if self.he... |
fbebd19801e0a734ff607d4ff4bd3e472f22bcdb | marcusvinysilva/detetetive | /detetive.py | 740 | 3.75 | 4 | resposta1 = int(input("Você telefonou para a vítima?\nDigite 0 para não ou 1 para sim: "))
resposta2 = int(input("\nVocê esteve no local do crime?\nDigite 0 para não ou 1 para sim: "))
resposta3 = int(input("\nVocê mora perto da vítima?\nDigite 0 para não ou 1 para sim: "))
resposta4 = int(input("\nVocê devia para a... |
72f23c50cf1f5edeccc7b11baab808f38f259ad4 | weezer/fun_scripts | /algo/208. Implement Trie (Prefix Tree).py | 1,781 | 3.9375 | 4 | class Node(object):
def __init__(self):
self.num = 0
self.hash_map = {}
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word):
"""
Inserts a word into the trie.
... |
aa28e719ce2fe95114296f3448fd76b1a7843a2b | jonnytaddesky/python | /Strength HW/game_sticks.py | 678 | 3.75 | 4 | counter_sticks = int(input('Общее колличество палочек: '))
player_number = 1
while counter_sticks > 0:
choise = int(
input(f'Сколько возьмете палочек? Осталось палочек {counter_sticks}: '))
if choise > 3 or choise < 1:
print(f"Вы взяли {choise} палочек. Дозвонлено взять 1, 2 или 3")
co... |
9b1407e584e51e4e2e2672c69d7a7b38be4c9736 | koooge/leetcode | /1603/1603.py | 460 | 3.8125 | 4 | class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.park = [big, medium, small]
def addCar(self, carType: int) -> bool:
if self.park[carType - 1] > 0:
self.park[carType - 1] -= 1
return True
else:
return False
obj = Parki... |
58f8d6803a9b4c10c0846a21de84af34941a3748 | gabriellaec/desoft-analise-exercicios | /backup/user_040/ch119_2020_03_23_22_42_43_666993.py | 181 | 3.671875 | 4 | from math import factorial
def fatorial(x):
math.factorial(x)
def calcula_euler(x,n):
euler=1
for y in range (1,n):
euler+=x**y/fatorial(y)
return euler |
345ecab190184efad54f4caa4e3a086c6b937ef6 | Audio10/Curso-Python | /Curso Basico de Python/saludos.py | 92 | 3.984375 | 4 | # -*- coding: utf-8 -*-
name = str(input('Whats your name? '))
print('Hola ' + name + '!') |
7bccf4f471dad7c60dd86ac0f2f5992ac94f8d9e | teppi1995/AtCoder | /GrandContest002/A-RangeProduct/solver.py | 452 | 3.765625 | 4 | import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
#logging.disable(logging.CRITICAL)
def main():
a, b = map(int, input().split())
logging.info("Hello!")
if a * b < 0:
print("Zero")
elif a > 0:
print("Positive")
else:
if (b - a + 1) % 2 == 1:
... |
f6aecdc9cd8b1f8e81603aef97423d970bd9d369 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2228/60724/288297.py | 176 | 3.796875 | 4 | target=abs(int(input()))
i=0
while i*(i+1)//2<target:
i+=1
if i*(i+1)//2==target or (i*(i+1)//2-target)%2==0:
print(i)
elif i%2==0:
print(i+1)
else:
print(i+2)
|
40a371135f4b835b521f73a44616f04314900406 | Awesome-Kirill/edu | /stepik/cal.py | 815 | 4.1875 | 4 |
arg_1 = float(input())
operand = input()
arg_2 = float(input())
'''
Поддерживаемые операции: +, -, /, *, mod, pow, div, где
mod — это взятие остатка от деления,
pow — возведение в степень,
div — целочисленное деление.
'''
def calc(arg1,arg2,ope):
try:
func_dict = {'+': lambda x, y: x + y,
'-': lambda x, y: x... |
11ac1dcd15a75c292d22fa52b9edf42d192ec5d2 | esther-soyoung/Coding-Challenge | /StackQueue/truck.py | 683 | 3.5 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
on_bridge = deque([])
time = 0
for i in truck_weights:
while True:
time += 1
# one truck passed the bridge
if len(on_bridge) == bridge_length:
on_bridge.popleft()
... |
80856e66a4a52a1594302aab6ca9bc540ea41b3d | GuiJR777/INE5603-01238A-20201---Programa-o-Orientada-a-Objetos-I | /strings/valida_cpf.py | 1,785 | 3.78125 | 4 | # Funções
def higienizador(string):
string = string.lower()
string = string.replace(' ','')
string = string.replace(',','')
string = string.replace('-','')
string = string.replace('.','')
return string
def checa_igualdade(lista):
repetidos = 0
for n in range(len(lista)):
if list... |
a847069fb5fc7b299857c1b42dd804f3af420db4 | thetheos/BAC1INFO1 | /mission7/Q6.py | 315 | 3.9375 | 4 | l = [{"City": "Bruxelles", "Country": "Belgium"}, \
{"City": "Berlin", "Country": "Germany"}, \
{"City": "Paris", "Country": "France"}]
def get_country(l, name):
for ct in l:
if ct["City"] == name:
return ct["Country"]
return False
print(get_country(l,"Toronto")) |
ce22776e7e8a3baea05c7a27c0b63888fb4a291c | akilmarshall/Fractals-and-Friends | /chaos_game/polygons.py | 4,440 | 4.28125 | 4 | '''
This file contains functions that create and concern polygons
Polygons are defined as a list of vertices
'''
from math import pi, cos, sin
from random import choice
import pygame
class Polygon():
"""Polygon implementaion"""
def __init__(self, h, k, r, n):
"""TODO: to be defined.
:h: x-... |
15cb4eaa06281d656b5063ddebf7b19b7da4b9de | sukritishah15/DS-Algo-Point | /Python/quicksort.py | 1,790 | 4 | 4 | """ Python program for implementation of Quicksort Sort
This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot"""
def partition(arr, low, high):
... |
ad460ff898942ce930655ce4109fe1b53acdc7e4 | dr-manhattan/ai_planning | /missionaries_cannibals.py | 2,513 | 3.71875 | 4 | # License: http://opensource.org/licenses/MIT
# complements of Max Kesin
from collections import namedtuple
Side = namedtuple('Side', ['missionaries', 'cannibals', 'destination'])
sideFrom = Side(missionaries=3, cannibals=3, destination=False)
sideTo = Side(missionaries=0, cannibals=0, destination=True)
start_state... |
6ab5075acf9a61745bb24e5c5cd47ea317eed9f9 | mrraj5911/python- | /a1.py | 199 | 3.96875 | 4 | a=input("enter the string: ").strip()
b=['raj','rana','bantu','thakur']
if a in b:
print(a,"is here")
else:
print(a,'not here')
option=input("to get more search type Y ")
if option!='Y':
continue
|
30fd21240ed6955fd16af4e294e6c0c4eadabeef | stewSquared/project-euler | /p062.py | 698 | 4.03125 | 4 | """The cube, 41063625 (345^3), can be permuted to produce two other
cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the
smallest cube which has exactly three permutations of its digits which
are also cube.
Find the smallest cube for which exactly five permutations of its
digits are cube."""
from it... |
a5bd15a865b610ec3891caab92d32d843d0ddb4b | entrekid/algorithms | /basic/11931/sort_reverse.py | 209 | 3.59375 | 4 | import sys
input = sys.stdin.readline
num = int(input().strip())
num_list = []
for _ in range(num):
num_list.append(int(input().strip()))
num_list.sort(reverse = True)
for elem in num_list:
print(elem) |
c80297399367c0404f5e2cd0fcb12f8abefee3af | Jsemko/project_euler_solutions | /Euler131.py | 382 | 3.640625 | 4 | def primes_under(m):
primes = [2]
for i in range(3,m,2):
if (i + 1)% 100000 == 0: print('done ' + str(i))
j = 0
while j < len(primes) and i >= primes[j]**2:
if i % primes[j] == 0: break
j+=1
else: primes.append(i)
return primes
primelist = pr... |
df61e6b7ad221bfd3c1d4f9607ad8a749abe05d1 | ehdqoddl6/coding-test | /dataSturcture/queue.py | 214 | 3.703125 | 4 |
from collections import deque
queue = deque()
queue.append(5)
queue.append(2)
queue.append(3)
queue.append(7)
queue.pop()
#queue.append(1)
#queue.append(4)
#queue.popleft()
print(queue)
print(queue.reverse()) |
a1e59e159e84e737f3ce33da970adf8af694db37 | TrellixVulnTeam/Python-Projects_4PU5 | /Linear Regression/bestfitline.py | 782 | 3.53125 | 4 | from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
xs =np.array([1,2,3,4,5,6],dtype=np.float64)
ys= np.array([5,4,6,5,6,7],dtype=np.float64)
def best_fit_slope():
num = (mean(xs)*mean(ys))-mean(xs*ys)
denom = (mean(xs)*mean(xs))- mean(xs*xs)
m = num/denom
c = mean(ys)-... |
29cfe6538743040903621c071fa0a64078e8f7b7 | ANAMIKA1410/DSA-Live-Python-March-2021 | /lecture-10/pivot.py | 297 | 3.6875 | 4 | def pivot(nums, start, end):
p = end
j = start
for i in range(start, end):
if nums[i] > nums[p]:
swap(nums, i, j)
else:
j += 1
swap(nums, p, j)
return j
def swap(nums, i, j):
t = nums[i]
nums[i] = nums[j]
nums[j] = t
|
dc54e2c8d3e9a4eb0a0a49140c6d83def21aac75 | Zhengrui-Liu/FireAlarmingSysCDA | /src/main/python/programmingtheiot/cda/sim/HvacActuatorSimTask.py | 1,619 | 3.59375 | 4 | #####
#
# This class is part of the Programming the Internet of Things project.
#
# It is provided as a simple shell to guide the student and assist with
# implementation for the Programming the Internet of Things exercises,
# and designed to be modified by the student as needed.
#
import logging
import random
from... |
5a14e5595cea4405010550b90e718cc4fdb07e29 | roodiaz/Curso-Python | /ejercicios/video17_ejercicio02.py | 250 | 4 | 4 | num1 = int(input("ingrese numero entero positivo: "))
suma=0
while(num1>0):
suma+=num1
num1 = int(input("ingrese numero entero positivo: "))
print("\nnumero negativo ingresado, fin del programa")
print("la suma de numeros ingresados es de ",suma) |
026ab609b1083a1f49cc83d7bada532ff3eaa8f8 | sny-tanaka/practicePython | /Practice/ProjectEuler/Problem17.py | 1,277 | 3.6875 | 4 | # coding: utf-8
'''
1 から 5 までの数字を英単語で書けば one, two, three, four, five であり, 全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている.
では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば, 全部で何文字になるか.
'''
def num2str(n): #数字を英単語に変換
units = ['','one','two','three','four','five','six','seven','eight','nine']
teens = ['ten','eleven','twelve... |
2dab900df30c1e565226154a5b91cc91ceae24ad | Sgggser/python_homework | /hw2.py | 134 | 3.703125 | 4 | a = 1
b = 2
result = (a*a + b*b) %2
print('Для значений a=%g b=%g результат функции: %g' % (a, b, result)) |
22586deaa41d4c8049d4911a2ab68293699e6aed | ntrang086/python_snippets | /search_optimize/common_ints.py | 292 | 4.0625 | 4 | """Find the common elements of 2 int arrays.
"""
def common_ints(array_1, array_2):
return set(array_1).intersection(set(array_2))
if __name__ == "__main__":
array_1 = [1, 4, 2, 3, 3]
array_2 = [5, 4, 6, 3, 3]
# Should return 3 and 4
print (common_ints(array_1, array_2)) |
b395b64be6b1dc5040a23c83dafb0243d4bc2130 | CodyDBrown/Physics-331 | /Physics 331/Textbook Programs/Chapter 4/euler_1d_3.py | 1,297 | 3.75 | 4 | def euler_1d_3(y0, t0, tf, dt, deriv_func):
from numpy import arange, zeros
"""
This is a third attempt at making euler_1d a little easier to work with. Inputs are the same as euler_1d_2
but the 'problem' with euler_1d_2 is that it didn't use a numpy array for the 'y' values. This used a np.array
T... |
16ee3a97ac173c2e5d3be96c04c4c5d9e57e8c78 | sanmen1593/InteligenciaArtificial | /ColoniaDeHormigas/ColoniaDeHormigas.py | 2,785 | 3.609375 | 4 | __author__ = 'Santiago Mendoza Ramirez'
import math
import random
import ast
class Coordenadas:
def __init__(self, x, y):
self.x = x
self.y = y
def distancia(self, punto):
ValorX = abs(self.x - punto.x)
ValorY = abs(self.y - punto.y)
formula = math.pow(ValorX, 2) + mat... |
d120c3ad58eb5d79044a0af706debe452d4bdabf | sivatmam/CCPS109 | /Problems/test.py | 209 | 4.03125 | 4 | import itertools
def is_ascending_generator(n):
for i in range(n):
for seq in itertools.permutations(range(n)):
yield [seq]
for j in is_ascending_generator(3):
print(j, end ="|||") |
eb7030ce69e68296b765ed0c8d32a08a00b782db | iitmaniac/The_Joy_Of_Computing_Using_Python | /Solve_the_Jumbled_word.py | 3,493 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 15 11:51:04 2019
@author: Shrikant Tambe
"""
"""
Here we are developing a game to find the answer of the jumbled word.
Here we are taking an input from user, and checks with the solution of the jumbled word.
If it is correct then a point is added to the player'... |
f2caef803fec6dc7b0898dc41ae5a35a03d7a652 | harman666666/Algorithms-Data-Structures-and-Design | /Algorithms and Data Structures Practice/LeetCode Questions/Algorithms Class Coursework/A9ShortestWordPath.py | 23,318 | 3.703125 | 4 | '''
This assignment has three parts: a written part (Q1), a programming part (Q2), and an
optional written bonus part (Q3). You need to hand them in separately as stated above.
The goal is to design and implement (that is, write a working program for) a shortest
path algorithm to solve a problem about word chains.
Plea... |
5033e1cda9da7351559e6e9ef30b1650afb48eae | Macielyoung/LeetCode | /110. Balanced Binary Tree/balanced.py | 1,109 | 3.828125 | 4 | #-*- coding: UTF-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def height(node, depth):
if not node:
... |
c5256a70419cb2d448c757ccc7d8372874c5635b | dipprog/Competitive-Programming | /DSA/4. Divide And Conquer/max_subarray_sum_dac.py | 965 | 3.84375 | 4 | # def max_of_three(a, b, c):
# if a >= b and a >= c:
# return a
# if b >= a and b >= c:
# return b
# return c
def max_crossing_sum_subarray(A, low, mid, high):
left_sum = -100000
sum = 0
for i in range(mid, low-1, -1):
sum = sum + A[i]
if sum > left_sum:
le... |
261e0e8c4905a0071850952e2132b4bd8a6b3e65 | talesritz/Learning-Python---Guanabara-classes | /Exercises - Module II/EX070 - Estatísticas em Produto.py | 1,594 | 3.84375 | 4 | #Crie um programa que leia o nome e o preço de vários produtos. O programa deverá pergntar se o usuário vai continuar. No final mostre:
#a) Qual é o total gasto na compra.
#b) Quantos produtos custam mais de R$1000
#c) Qual é o nome do produto mais barato.
print('\033[34m-=-'*11)
print('\033[33m EX070 - Estatís... |
2ff5c32c07f877d7efd0eff99113d7e017065ca5 | jruas/myWork | /week3/absolute.py | 231 | 4.375 | 4 | #This program takes in a number and give its absolute value
#Author: Joana Ruas
#Taking a number
a=float(input('Please insert a number'))
#Turning the number into absolute
b=abs(a)
print('The absolute value of {} is {}'.format(a,b)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.