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 |
|---|---|---|---|---|---|---|
f22ca8d2b1a965d1416e4f44c315740b9df473a5 | Yasmin-Core/Python | /Mundo_2(Python)/elif/aula12_desafio38.py | 256 | 3.953125 | 4 | n1= int(input('Digite um numero: '))
n2= int(input('Digite outro número: '))
if n1 > n2:
print ('O primeiro valor é MAIOR')
elif n2 > n1:
print ('O segundo valor é MAIOR')
else:
print (' NÃO existe valor maior, os dois são iguais.')
#
|
6807c9a84dfa40b4ab9b2a7a4bc94dacaadfb9e1 | Yasmin-Core/Python | /Mundo_2(Python)/while/aula14_desafio63.py | 698 | 4.09375 | 4 | #Sequencia de fibonacci -> serão a soma dos dois números anteriores
print('***** Sequencia de Fibonacci******')
n= int(input('Quantos numeros voce quer que mostre na sequencia de fibonacci?:'))
# A sequencia de fibonacci sempre começa com zero e um
i1 = 0
i2 = 1
print('{} -> {} -> '.format(i1, i2), end='')
# Entao o c... |
3bfa8dd579f61c17926216f85ed9881fca867f80 | mvsharma77/pythonproject | /Multiclass_model-master/src/classification/model/create_pip.py | 1,810 | 3.578125 | 4 | """
create the pipeline for the Xgboost model.
In this pipeline 2 steps are applied: pre processing and xgb model.
In the pre processing step there is a pipeline given by:
1. Column selector: select just the features contained in the config
2. column transformer that apply different steps to categorical and numerical f... |
d31e65ed292149656f154daaef6fbb42e0622f3c | Anushree176/hello-world-1 | /Python/hello_world.py | 273 | 3.640625 | 4 | # For Python 2
# Here print is not considered as a function
print "Hello World!"
# For Python 3
# Here print is a function - paranthesis used
print("Hello World!")
# References to learn Python
# https://www.learnpython.org/
# https://www.programiz.com/python-programming |
a188842c6efdcd00ca513674399e941c0efa7770 | MartinsSam/Python | /CursoEmVideoAulas/src_aulas/aula06.py | 456 | 4.09375 | 4 | #SFM 05/2019
# A versão 3.7 do Python utiliza uma nova forma de formatação
# Python sempre recebe o valor como String. É necessário conversão para poder realizar a soma.
n1 = int(input('Digite o primeiro valor:'))
n2 = int(input('Digite o segundo valor:'))
s = n1+n2
#print('A soma entre ' + n1 + 'e' + n2 + 'vale' + s)
... |
376fa5a904c9dc8e0da37ce85d1d87f1e4f71989 | MartinsSam/Python | /CursoEmVideoAulas/src_exercicios/aula07_desafio08.py | 398 | 4.0625 | 4 | numero = float(input('Digite um valor(em metros):'))
#print('O valor {}, convertido para centimetros é {:.0f} ' .format(numero, numero*100))
# km hm dam m dc cm mm
km = numero/1000
hm = numero/100
dam = numero/10
dc = numero*10
cm = numero*100
mm = numero*1000
print('O valor {}, corresponde a \n {}km, \n {}hm \n {}dam... |
99350014092fb66c640162b0d583719ea0677447 | mahaV503/cuddly-couscous | /binarySearch.py | 644 | 3.8125 | 4 | def binarySearch(arr,targ):
#Initlizing the pointers
firstPointer=0
lastPointer=len(arr)
while(firstPointer<=lastPointer):
#dividing at midpoint
midPointer=(firstPointer+lastPointer)//2
if arr[midPointer]==targ:
#if value at midpoint equals target variable
... |
5aa6a3ebcf5b9a4f33312b287d7947b1b36b1740 | KevinYu222/ics3u-classwork | /coding_practice_2020_11_20.py | 634 | 4.0625 | 4 | color = input("What is your favourite color? ")
print(f"Wow! {color}?! That is also my favourite color!")
cans_per_pack = int(input("How many cans are in a pack? "))
pack = int(input("How many packs are there? "))
print(f"You have total of {cans_per_pack * pack} cans.")
length = float(input("Length: "))
width = float... |
d108f6ba9edcc714067c3f29bc37039e335a6f2a | Mr-Coxall/Unit-8-09 | /transportation.py | 881 | 3.9375 | 4 | # Created by: Mr. Coxall
# Created on: Sep 2016
# Created for: ICS3U
# This class is used to define a transportation object
#from abc import ABCMeta, abstractmethod, abstractproperty
class Transportation:
# this class defines a transportation object
#__metaclass__ = ABCMeta
# class variable shared by all... |
78da65bb478ebb9655194df0a009e04010d9ca4e | HEC2018/Interview_Practice_Questions | /pmath340_a6.py | 243 | 3.859375 | 4 | #!/usr/bin/python3
import math
s = int(input("Input to check if sum of squares:"))
x = math.sqrt(s)
x = math.floor(x)
for i in range(2,x):
for j in range(2,x):
if i*i + j*j == s :
print(i)
print(j)
|
501baef0616f58abdd26eb4f6a960d8e2fc821fb | HEC2018/Interview_Practice_Questions | /leetcode_Sep_challenge_Insert_intervals.py | 2,702 | 3.515625 | 4 | class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[List[int]]
:type newInterval: List[int]
:rtype: List[List[int]]
"""
l = len(intervals)
for i in range(l):
if newInterval[1] < intervals[i][0]:
... |
2f2cff2b6b2fa1cd808d307a3876c71673fd1ea8 | indika2000/wordsearch | /wordsearch.py | 3,214 | 3.71875 | 4 | __author__ = 'Indy'
class WordSearch():
def __init__(self, lettermatrix):
self.lettermatrix = lettermatrix
self.solutionmatrix = self.__initialisesolutionmatrix(len(lettermatrix))
self.path = 1
def __initialisesolutionmatrix(self, size):
return [[0 for x in range(0, size)] for... |
6dca24c079ceeeec6ca644dbfcec7e4d07acce19 | Nikhil483/ADA-lab | /lab1(1).py | 373 | 4.0625 | 4 | def square_root(n):
low = 0
high = n
while low<=high:
mid = int((low+high)/2)
diff = mid*mid-n
if diff == 0:
return mid
else:
if diff>0:
high = mid-1
else:
sqrt = mid
low = mid+1
return sq... |
891b2242066c92fba0b8d87059249af92edd955b | maxflex/coursera | /data-structures/week4/phone_book/phone_book.py | 2,115 | 3.578125 | 4 | # python3
import random
class HashNode:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
class Hastable:
def __init__(self):
self.m = 10000000
self.p = 10000019
self.a = random.randint(0, self.p - 1)
self.b = random.randint(1, self.p... |
71acc7d964ce85625db4503fbe530aba63138966 | CristianRodrigoGuarachiIbanez/neurocomputing | /cross_validation/exercise_solutions/CrossValidation.py | 5,138 | 3.65625 | 4 | """
Created on Fr Nov 13 2020
@author: Cristian Rodrigo Guarachi Ibanez
CrossValidation
"""
#Exercise 4 - Cross-validation
# Polynomial regression
"""Polynomial regression consists of fitting some data (x,y)(x,y) to a nn-order polynomial of the form:
y=f(x)=w0+w1⋅x+w2⋅x2+...+wn⋅xn
By rewriting the unidimensional input... |
ed2daa15200760247653877342eb7caf3cb8d8b5 | CristianRodrigoGuarachiIbanez/neurocomputing | /multiLayerPerceptron/exercise_solutions/MultiLayerPerceptron.py | 31,966 | 3.734375 | 4 | """
Created on Fr Nov 13 2020
@author: Cristian Rodrigo Guarachi Ibanez
Multi-layer perception
"""
#Exercise 5 : Multi-layer Perceptron
"""
1 - Structure of the MLP
A.- The output neuron sums its inputs with KK weights W2W2 and a bias b2b2 . It uses a logistic transfer function:
a) y=σ(∑j=1KW2j⋅hj+b2)
B .- with ... |
d064c635389f767606f56ae246d695d7b1af6ecf | kevindsteeleii/HackerRank_InterviewPreparationKit | /00_WarmUpChallenges/jumpingOnClouds_2019_02_20.py | 1,712 | 4.28125 | 4 | """
Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number... |
3bf18e01d1e3fbbac3ca7a8cb35afc759256434c | LiT-BRo/SHIS-HHW-Rohan-Kurup-XI-B-CS | /Custom-Projects/Project-1/Time-Converter.py | 906 | 3.96875 | 4 | #This is a time converting program which converts the input entered in seconds into the format (DAYS:HOURS:MINUTES:SECONDS)
#Debugged to avoid any faulty inputs.
print("\n\n========== Welcome to LiTBRo's Time Converter ==========\n")
def progres(): #progres - program reset
inp = str(input("\nWould you like ... |
0960052799083a325c3f8fe9bfacd9708e3eb328 | LiT-BRo/SHIS-HHW-Rohan-Kurup-XI-B-CS | /Custom-Projects/Project-3/Ar,Peri,SA&Vol-Calc.py | 13,920 | 4.15625 | 4 | #This is a 2D and 3D shape Area, Perimeter, Surface Area & Volume caluculator.
#It includes the following shapes: Square, Rectangle, Cirle (& its types), Triangles (& its types), Cube, Cuboid, Sphere (& its types).
wroval = "\n⚠️ Invalid value entered! Please try again...\n"
#wroval -> Wrong Value "String"
th... |
331cb0d0b838d3fadba15931ee5a9b2566955044 | dapine/tcc | /tagger.py | 804 | 3.515625 | 4 | import nltk
from nltk.corpus import floresta
from nltk import word_tokenize
def simplify_tag(t):
if "+" in t:
return t[t.index("+")+1:]
else:
return t
texto = "François-Marie Arouet, mais conhecido pelo pseudônimo Voltaire (Paris, 21 de novembro de 1694 — Paris, 30 de maio de 1778), foi um esc... |
0915df88be07251462464e301bec6535ac91626d | tarjantamas/Virtual-Controller-CNN | /src/common/util.py | 1,590 | 4.5625 | 5 | def getArgumentParameterMap(argv):
'''
Maps arguments to their list of parameters.
:param argv: list of arguments from the command line
:return: a map which maps argument names to their parameters.
If the program is run in the following way:
python main.py --capturedata param1 param2 param3 --othercommand p... |
a7e5fa73081958365bb4ddf377862562317b9975 | hirekatsu/MyNLTKBOOK | /ch03_09.py | 3,524 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
import nltk, re, pprint
from nltk import word_tokenize
print("""
----------------------------------------------------------------------
3.9 Formatting: From Lists to Strings
-----------------------------------------... |
4591f57531faeaaf80238383f150a2e42e1db663 | matrix-construct/construct | /tools/synapse.db.py | 434 | 3.53125 | 4 | #!/usr/bin/python
import os
import sys
if len(sys.argv) < 2:
print "Usage: %s <sqlite3 dump file>" % sys.argv[0]
sys.exit(1)
file = sys.argv[1];
for line in open(file):
if not line.startswith("INSERT"):
continue
line = line.split(" ", 3)
line = line[3].rstrip(");\n")
line = line.lstrip("VALUES(")
line = li... |
6cf7d0d75086b229388e6f53b4642a0e59c1b5ac | DjangoGirls/djangogirls | /djangogirls/utils/sanitize.py | 2,557 | 3.875 | 4 | # pylint: disable=inconsistent-return-statements
def sanitize(value, output_type):
"""
Handy wrapper function for individual sanitize functions.
:param value: Input value to be sanitized
:param output_type: Class of required output
:type output_type: bool or int
"""
# pylint: disable=no-e... |
319b68f9897e2e0e292b89d0cff16b288d966d42 | someshjaishwal/Machine-Learning | /templates/regression_template.py | 1,475 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# Regression Template
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:, 2].values
# taking care of missing data
# dummy vars for categorial data
# ... |
4e32c759c0480ca9c611f6c3fa59421f12dea330 | someshjaishwal/Machine-Learning | /Part 2 - Regression/2.1_simple_linear_regression.py | 1,429 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 16:56:52 2018
@author: somesh
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('../dataset/Salary_Data.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 1].values
... |
4cbf74398c58cd4041f1da40056cd9401ef86704 | EnumCZ/Brainfuck | /Tokenizer.py | 246 | 3.53125 | 4 | class Tokenizer:
@staticmethod
def tokenize(string):
token_list = []
for char in string:
if char in ["+", "-", "<", ">", ".", "[", "]", ","]:
token_list.append(char)
return token_list
|
a8d2ef1e332bc1d1732e806b19157af24514a040 | sean7218/api-dev | /kb_blocks/kb_blocks/blocks/form/email.py | 405 | 3.65625 | 4 | from .input import Input
import re
class Email(Input):
VALIDATE_REGEX = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
EXCEPTION_MESSAGE_BAD_EMAIL = "Please enter a valid email address"
def validate(self,state,data):
value = self.getValue(state,data)
if not re.match(self.VALIDATE_... |
68c46e358369df4ff3f31ce848531dd82991a884 | BrandonSherlocking/python_document | /网易云课堂/继承,类.py | 568 | 3.78125 | 4 | class Father:
money = 10000000
__money = 1000000000000
def drive(self):
print('i can drive a car!!')
class Father1:
money1 = 1000000000
class Son(Father):
def drive(self):
print('i can drive tank!')
return super().drive() # 超类,super函数, 特殊的构造方法
def pay(self):... |
99ed1b1257b1558829d0fdf14976dd2346ada5d0 | BrandonSherlocking/python_document | /turtle画图/粗线条。(蟒蛇).py | 607 | 3.953125 | 4 | #待解决问题,如何让用户输入参数,自定义
Setup=input('do you want to draw a snke? \npleae input some redius,angle,length :')
import turtle
def drawSnake(radius,angle,length):
turtle.seth(-45)
for i in range(length):
turtle.circle(redius,angle)
turtle.circle(-redius,angle)
turtle.circle(redius,angle/2)
turt... |
98089a7382a4ae4b68b8303489dc7d1b4f8c6d3d | BrandonSherlocking/python_document | /小作业/重复元素判断.py | 351 | 3.640625 | 4 | def judgeWord():
while True:
rescive = input('请输入一些东西(输入q或quit退出):')
lsre = list(rescive)
if rescive == 'q' or rescive == 'quit':
break
elif len(set(lsre)) == len(lsre):
print('你输入的字符没有重复')
else:
print('True')
judgeWord()
|
8b158eab3dbd4c00b8b775e0079ce385c20c1415 | BrandonSherlocking/python_document | /format使用/回文数判断.py | 472 | 3.984375 | 4 | #本人代码
backnumber = input('请输入一串符号(数字或字母):')
n = str(backnumber)
if n[0:-1] == n[-1:0:-1]:
print('你输入的数字是回文数')
else:
print('你输入的数字不是回文数')
# 大神代码
a = input('please input some word: ')
def is_palindrome(n):
n = str(n)
m = n[::-1]
return n == m
if is_palindrome(a) is True:
print('you input word is ... |
a2779027a93ecacca781a29535c5306173ab86cd | BrandonSherlocking/python_document | /小作业/乒乓球.py | 1,808 | 3.5625 | 4 | from random import *
def main():
description()
print()
ppA, ppB, n = getInput()
winsA, winsB = nGame(ppA, ppB, n)
print()
printSummary(winsA, winsB)
def description():
print('{:*<43}'.format(''))
print('{:<13}{:^}{:>12}'.format('*', '这里是乒乓球大赛现场', '*'))
print('{:<6}A和B的能力值(以0到1之间的... |
31632170fed588446b7e6426f5a94fe2c09219e9 | BrandonSherlocking/python_document | /练习/1到n求和.py | 341 | 3.890625 | 4 | while 1:
n = input('please input some number :')
if n == 'q' or n == 'quit':
break
Sum = []
for i in range(1, int(n) + 1):
Sum.append(i)
print('you sum result is:', sum(Sum))
'''
n=input('please input some number :')
Sum=0
for i in range(1,int(n)+1):
Sum+=i
print('you sum resu... |
33ad6a298cc3d9b5e85b5cc0f428a26e5587599d | kiranraavilla/letsupgrade | /Day06_Assignment01.py | 1,147 | 4 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class bank:
def __init__(self,owner_name,balance):
self.owner_name=owner_name
self.balance= balance
def deposit(self):
amount=int(input("enter the amount to be deposited "))
print("customer name ",self.owner_name)
... |
f9de0658517d735b7b2e9d38a8d16086c0ff2ead | RajdevShivam/ML | /Regression/16AE30018_AS1_Part_1and2.py | 2,526 | 3.6875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df_train=pd.read_csv('train.csv') #You should enter the location of you data files
df_test=pd.read_csv('test.csv') #in the brackets given.
# print("Train is:")
# print(df_train.head())
# print("Test is:")
# print(df_test.head())
colu... |
0db71d83915161810b8bdcbea54c9009a83682a0 | Paula1991/python_bootcamp | /dzien2/cwiczenie_5.py | 372 | 3.5625 | 4 | Miasto_A = input("Miasto A: ")
Miasto_B = input("Miasto B: ")
dystans = int(input(f"Dystans {Miasto_A}-{Miasto_B}: "))
Cena_paliwa = float(input("Cena paliwa: "))
Spalanie = float( input("Spalanie na 100 km : "))
print()
koszt = (dystans /100)* Spalanie * Cena_paliwa
koszt = round(koszt, 2)
print(f"Koszt przejazdu War... |
485a18634f4b8192ed28db96ab43c26d54df3ab7 | epc0037/URI-CS | /CSC110/Python Functions/lists_functions.py | 1,211 | 3.84375 | 4 | # CSC 110 - Spring 2016 - Section 1
# Week 4 (Functions) - Class Activities (Tuesday)
# Exercise 3
#listMax Function
# Take a list of numbers and return the maximum value
def listMax(inputList):
max = inputList[0]
for i in range(len(inputList)):
if inputList[i] > max:
max = inputList[i]
... |
3e6ed94805508deb35bcca43815600f14e59266b | epc0037/URI-CS | /CSC110/Introduction to Computer Science/Lab1/Basicshit2.py | 150 | 3.96875 | 4 | r = float(input("Enter the radius of the base circle."))
h = float(input("enter the height of the cone."))
v = (1/3)*pi*r**2*h
print(v)
print("Exit")
|
0cb1eb4245d4d82b15e885ab5b7374b0c419e6e0 | epc0037/URI-CS | /CSC110/Python Lists/HW3/problem1.py | 878 | 4.40625 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 3 - Problem 1
# This program will generate a list containing
# all the odd numbers between 100 and 500 except 227 and 355.
# create an empty number list & set the values we wish to remove from the list
numList = []
a = 227
b = 355
... |
d4bef012025e263f3740ce2e425bc7be7cf8d577 | epc0037/URI-CS | /CSC110/Numerical Analysis/Lab13/matrices.py | 4,021 | 3.84375 | 4 | # Evan Carnevale & Jonathan Reyes
# Professor Albluwi
# CSC 110: Survey of Computer Science
# Week 13 : Numberical Analysis
# Lab 13 : Matrices
def isVector(matrix):
if not isinstance(matrix,list):
return False
for i in range(len(matrix)):
if isinstance(matrix[i],list):
return False... |
2869a4a804531ff82b8957a250082d0eaecfdd07 | epc0037/URI-CS | /CSC110/Python Functions/HW4/stocks.py | 2,179 | 4.25 | 4 | # Evan Carnevale
# CSC 110 - Survey of Computer Science
# Professor Albluwi
# Homework 4 - Problem 1
# This program will get create two lists for stock names and prices,
# which will be entered by the user using a loop. I will utilize 3 functions:
# the main function, the searchStock function and the printStock functio... |
7ae980faf8126223178b401bc5238ec914c5243d | epc0037/URI-CS | /CSC110/Numerical Analysis/numerical_analysis.py | 1,174 | 3.71875 | 4 | # Evan Carnevale
# CSC 110 : Survey of Computer Science
# Professor Albluwi
# Week 13 : Numerical Analysis
# Class Activitis (Tuesday)
def isVector(m):
isList = False
if isinstance(m,list) == True:
for i in range(len(m)):
if isinstance(m[i],list) == True:
return False
... |
1f97e7a5f66552f012f3c95e05152ac9f9747640 | epc0037/URI-CS | /CSC110/Python Basics/HW2/problem3.py | 404 | 4.375 | 4 | #Evan Carnevale
#CSC 110 - Survey of Computer Science
#Professor Albluwi
#Homework 2 - Problem 3
TOTAL_BUGS = 0
DAYS = 1
while DAYS <= 7:
print("Day", DAYS, ": Did you collect a lot of bugs today?")
today_bug = int(input("Enter the number of bugs collected today"))
TOTAL_BUGS += today_bug
DAYS +=1
... |
2986db38903a40a7e2a776431475e53f60a74e0b | UdemyPythonFrom0toPro/2.3_animals_legs | /sum_animals_legs.py | 190 | 3.890625 | 4 | chickens = int(input("How many chicken\n> "))
pigs = int(input("How many pigs\n> "))
cows = int(input("How many cows\n> "))
total_legs = chickens * 2 + pigs * 4 + cows * 4
print(total_legs)
|
1fd728ec390c208e40b35b7022e17c060462f367 | raturusi/python | /Lesson2/1Task.py | 1,862 | 3.84375 | 4 | my_str = "lesson2"
my_list = list(my_str)
my_list.insert(0, 5)
my_list.append(my_str)
my_list.extend((5.5, 10, "2020", "GeekBrains"))
print(my_list)
my_list.pop(4)
print(my_list)
for el in my_str:
if my_list.count(el) != 0:
my_list.remove(el)
else:
print(f'{el} - не найден')
print(my_list)
for e... |
88a1754180c1f77a1ae3618e397243948a1455f9 | L0rd1k/FreeTimeCraft | /Testing/Zip-Map.py | 159 | 3.90625 | 4 | a = [1,2,3,4,5]
b = [1.2, 1.4, 1.5, 0.5, 1.92]
c = 'abcde'
result = zip(a, b, c)
# LIST --> ZIP
# print(list(result))
col1,col2,col3=zip(*result)
print(col2)
|
6f5da01a7629c241207370b07ae8d051f05a0d0c | aarrico/directory_tree | /models.py | 4,349 | 3.6875 | 4 | from __future__ import annotations
from typing import Dict, List, Optional, Tuple
class FileSystem():
"""Supports four basic operations on a file system. It contains a repo parameter that allows the
data structure to be switched out as long as the repo class implements the appropriate methods:
-find(p... |
37f8e6afb525ba4a613aba376f312ab89bd9a501 | katherfrain/dictionary-practice | /word-histogram.py | 459 | 3.921875 | 4 | def word_histogram(sentence):
wordhistogram = {}
for word in sentence:
if word == " ":
del wordhistogram[word]
elif word not in wordhistogram:
wordhistogram[word] = 1
else:
wordhistogram[word] = wordhistogram[word] + 1
return wordhistogram
histogr... |
096f9440dbad0564bc49ff851d495cb1dbac1267 | paladinescamila/Laboratorio-2-CC | /unidad_3.py | 10,864 | 3.765625 | 4 | # UNIDAD 3: MÍNIMOS CUADRADOS
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Función auxiliar: Método de Sustitución Sucesiva hacia atrás
def sucesiva_hacia_atras(A, b):
"""
Entrada: una matriz triangular superior A y un vector b.
Salida: un vector x tal que Ax = b.
... |
59eee549512380c092ca65c0e7e639f7977a06ff | gegner2015/PythonCode | /Learning/hanoi.py | 327 | 4 | 4 | def hanoi(n,x,y,z):
if n==1:
print(x,"-->",z)
else:
hanoi(n-1,x,z,y) #将前n-1个盘子从x移动到z上
print(x,"-->",z) #将最下面的盘子从向移动到z上
hanoi(n-1,y,x,z) #将n-1个盘子从y移动到z上
n=int(input('请输入汉诺塔的层数:'))
hanoi(n,'X','Y','Z')
|
8aa7e5fed57c621df14ef0c43798949b58e761f8 | beninato8/coding-challenges | /ctci-python/chapter-01-arrays-and-strings/rotate_matrix.py | 824 | 3.828125 | 4 | #!/usr/bin/env python3
'''
Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes,
write a method to rotate the image by 90 degrees. Can you do this in place?
'''
from pprint import pprint
def rotate_matrix(matrix):
# reverse matrix rows then transpose
return [list(x) for x in ... |
fdb18fdbe9c689c3450bd7d5cab9a956c9c46b9d | Meet5161/bank-format- | /factorial py.py | 153 | 4.09375 | 4 | def factorial(a):
if a == 0:
return 1
else:
return a * factorial(a-1)
a = int(input(" Enter the number: "))
print(factorial(a))
|
59e6690fb48204d2914c7850b811e5d40ebbea3c | MishaLatyshev/Individual-Work-8 | /id8.py | 916 | 3.9375 | 4 | #Перевод из 10 в 2 и 8 систему счисления
try:
n = int(input("Введите число:"))
base = int(input("Введите целевую систему счисления(2 или 8):"))
except ValueError:
print("Ошибка!")
else:
if n <= 0:
print("Введенное число не является положительным!")
else:
def number_inbase():
... |
3d945ea4f80ad8178c379796d29501cfec679518 | krishnasai21/ELEMENTS-OF-PROGRAMMING-INTERVIEWS-IN-pyhton | /reverse_digits.py | 208 | 3.765625 | 4 | def reverse(x: int) -> int:
result, x-remaining = 0, abs(x)
while x_remaining:
result = result * 10 + x_remaining % 10
x_remaining // = 10
return - result if x < 0 else result |
52ca0214d5b7583b1d7505cb87376e724614e9da | alifsyr/Willy-Wangky-System | /F02_savefile.py | 723 | 3.609375 | 4 | import csv
def save(data, names):
import modules
folderDirectory = "data/"
for i in range(modules.panjang(names)): # Melakukan looping berdasarkan panjang array names
name = str(folderDirectory + input("Masukkan nama file " + str(names[i]) + " :")) # input nama file csv
writeFile(n... |
a30da2333811df567735d317a551eacd2aa666ac | fbertoli/TelAzPython | /shifts.py | 7,720 | 3.609375 | 4 | import parameters
import itertools
from datetime import datetime
import utilities
import collections
'''
An object is a list of namedtuple (shift).
'''
ShiftTuple = collections.namedtuple('Shift', ['name', 'mandatory', 'day', 'week', 'id'])
# id: identifier. Equals position in shifts
class Shift(ShiftT... |
2ddb9b51df06848d1473efa60f7031acdaf1b147 | GGMagenta/exerciciosMundo123 | /ex076.py | 465 | 3.90625 | 4 | # Crie uma tupla com nomes e preços de produto e mostre de forma tabulada
lista = ('Caneta', 3.05, 'Borracha', 4, 'caderno', 15.5, 'mochila', 80.99, 'livro', 150.52)
print('-'*30)
print('{:^30}'.format('Lista de Preços'))
print('-'*30)
for item in range(0, len(lista), 2):
print(f'{lista[item]:-<20} R${lista[i... |
4d2057482e6711b76d94eaeff48d52ae787ca22e | GGMagenta/exerciciosMundo123 | /ex067.py | 413 | 4.125 | 4 | # Pegue um número e mostre a tabuada ate o usuario digitar um número negativo
while True:
numero = int(input('Digite um número inteiro e \033[1;32mpositivo\033[m: '))
if numero < 0:
break
for i in range(1, 11):
print(f'{numero} X {i} = {numero * i}')
i += 1
print('='*20)
... |
9bebf80303f4e38428ad2169aa9f5a0f479883cd | GGMagenta/exerciciosMundo123 | /ex053.py | 758 | 3.828125 | 4 | # pegue uma frase e diga se é um palíndromo
frase = input('Digite uma frase: ').strip().lower()
frase = ''.join(frase.split())
erro = -1
for i in range(0, len(frase)):
j = len(frase) - 1 - i
# print(frase[i], ' ', frase[j])
if frase[i] != frase[j] and erro == -1:
erro = i
if erro == -1:... |
9b0a181a84a1afaa4639a12de3ee2d91e4ee1b61 | GGMagenta/exerciciosMundo123 | /ex056.py | 1,262 | 3.6875 | 4 | # Pegue nome, sexo e idade de 4 pessoas e mostre:
# media das idades
# nome do homem mais velho
# quantas mulheres com menos de 20
idades = 0
maisVelhoNome = ''
maisVelhoIdade = 0
mulheresJovens = -1
for i in range(0, 4):
nome = input('Digite o nome: ').strip()
idade = int(input('Digite a idade: '))
... |
7f4807a1428556df76de25d96cfba832b4709c7d | GGMagenta/exerciciosMundo123 | /ex005.py | 125 | 3.9375 | 4 | n1 = int(input('digite um numero'))
print('voce digitou {}, seu sucessor e {} e seu antecessor e {}'.format(n1,n1+1,n1-1))
|
0e7d3d7cd4d5ca04532a32ee0212366be2b44424 | GGMagenta/exerciciosMundo123 | /ex041.py | 607 | 3.90625 | 4 | # Pegue o ano de nascimento e calcule a classe de acordo com a idade
# ate 9 - mirim ate 14 - infantil ate 19 - junior ate 25- senior acima - master
from datetime import date
ano = int(input('Informe o ano do seu nascimento: '))
anoAtual = date.today().year
idade = anoAtual-ano
print('Você tem {} anos. '.form... |
7c881e6d321b62f18aef17f0042a16030a599edd | GGMagenta/exerciciosMundo123 | /ex095.py | 1,560 | 3.78125 | 4 | # refazer o 93 com varios jogadores e selecionar o jogador que quiser ver
jogadores = []
jogador = {}
while True:
jogador['nome'] = input('Nome do jogador: ')
partidas = int(input('Quantas partidas jogou? '))
gols = []
totalGols = 0
for p in range(0, partidas):
n = int(input(f'Quant... |
f4df3eead30a18694dfc608ea9a6e1174212e32c | GGMagenta/exerciciosMundo123 | /ex008.py | 188 | 3.75 | 4 | # Pegue uma media em metros e converta em centimetros e milimetros
n1 = int(input('Quantos metros? '))
print('{} metros tem {} centimetros e {} milimetros'.format(n1, n1*100, n1*1000))
|
36f7f2fa194efe4de0298cc1137021d2e75183ed | GGMagenta/exerciciosMundo123 | /ex033.py | 443 | 4.03125 | 4 | # Ler 3 números e mostrar o maior e o menor
n1 = int(input('Digite o primeiro número: '))
maior = n1
menor = n1
n2 = int(input('Digite o segundo número: '))
if n2 > maior:
maior = n2
if n2 < menor:
menor = n2
n3 = int(input('Digite o terceiro número: '))
if n3 > maior:
maior = n3
if n3 < menor:
... |
70b9f0cd268f24ad8317f72514c54cf8e11a5b36 | GGMagenta/exerciciosMundo123 | /ex037.py | 1,016 | 4.15625 | 4 | # Pegue um numero e pergunte para qual base deseja converter
# 1 - Binário 2 - Octal 3 - Hexadecimal
n = int(input('Digite o número que deseja converter: '))
opcao = int(input('Digite \033[31m1\033[m para converter para \033[31mbinário\033[m, \033[32m2\033[m'
'para \033[32moctal\033[m, e \033[33... |
929b71b2691d0bad4b64593858a4f6e7fd817973 | GGMagenta/exerciciosMundo123 | /ex102.py | 717 | 3.921875 | 4 | # criar função fatorial que calcula o fatorial de um número
# com um valor opcional show que vai mostrar ou não resolvendo na tela
from time import sleep
def fatorial(numero, show=False):
"""
calcula fatorial
:param numero: número a ser calculado
:param show: se vai mostrar na tela a conta in... |
4bfc8436606c6a525d4c650e93ed6d6724daddf8 | GGMagenta/exerciciosMundo123 | /ex061.py | 268 | 3.875 | 4 | # Pegue o primeiro termo de uma PA e a razão e mostre até o 10 termo usando while
primeiro = float(input('Digite o primeiro termo da PA: '))
razao = float(input('Digite a razão:'))
termo = 0
while termo < 10:
print(primeiro + razao * termo)
termo += 1 |
31bde7b0180f79fa830c8bc7333469898dd91552 | GGMagenta/exerciciosMundo123 | /ex055.py | 464 | 3.78125 | 4 | # Pegue 5 pesos e mostre o maior e o menor
peso = float(input('Digite o peso em Kg: '))
maior = peso
menor = peso
for i in range(0, 4):
peso = float(input('Digite o peso em Kg: '))
if peso> maior:
maior = peso
elif peso < menor:
menor = peso
if maior == menor:
print('Parece qu... |
40cafceec89a2905f79d0d54291279dc43ac8859 | pedramsafaei/Robot-Operating-System-for-Beginners | /chapter3/functions/robot_move.py | 848 | 4.09375 | 4 | #!/usr/bin/env python
def forward():
print("Robot moving forward")
def backward():
print("Robot moving backward")
def left():
print("Robot moving left")
def right():
print("Robot moving right")
def main():
'''
This is the main function
'''
stop = False
while not stop:
... |
02cc3cf77855954aa9d9fbec28a6282b5615deef | RedHoodGuy/pictionary | /pictionary.py | 349 | 3.96875 | 4 | import random
array = []
randnum = 0
file = open("pictionary", "r")
for x in file:
array.append(x)
def pick_word():
again = "Y"
while again != "N" and again != "n" and again == "Y" or again == "y":
randnum = random.randint(0, len(array))
print(array[randnum])
again = raw_input("Play... |
04f32bd58e463c3b614a6c68216e54a86c1ac4ca | faizkhan12/LeetCode | /Merge K sorted lists.py | 528 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
self.nodes = []
head = point = ListNode(0)
for i in lists:
while i:
... |
f673c2bf877d35fa0e7bf7dff2b3d53a5f621fbd | Nathansbud/Wyzdom | /Students/Abdullah/eating.py | 1,031 | 3.96875 | 4 | from collections import Counter
import sys
import __main__ as main
def num_frequency():
try:
frequency = Counter([int(n) for n in sys.argv[1:]]).most_common()
print(f"Most frequent: {frequency[0][0]} ({frequency[0][1]})" if len(
frequency) > 0 else "Must have at least 1 number as input!... |
db0c5a43933e5f1a257eaca2e3003a3a3cd7a40d | Nathansbud/Wyzdom | /Students/Suraj/quiz.py | 513 | 4.125 | 4 | students = ["Jim", "John", "Jack", "Jacob", "Joseph"]
grades = []
for student in students:
passed = False
while not passed:
try:
grade = float(input(f"Input a quiz grade for {student} (0-100): "))
if not 0 <= grade <= 100: raise ValueError()
grades.append(grade)
... |
a5df9e9886c92083c7a21ea1830de84d7d87a655 | junjy007/precloc | /src/marker_calib.py | 13,123 | 3.515625 | 4 | import cv2
# import cv2.cv as cv
import numpy as np
class LocatablePattern:
"""
This represents an object, which has an anchor point. The anchor can be
precisely determined in an input image (given that the input image contains
this pattern) by comparing to the reference image of the pattern.
NOTE... |
06b2ba8142faea1538e8a3956f5885311d6f5b13 | JerryChii/PycharmProjects | /PythonIntroduction/lesson2/task5/arithmetic_operators.py | 155 | 3.859375 | 4 | number = 9.0 # float number
result = number/9.0
remainder = number % 9.0
print("result = " + str(result))
print("remainder = " + str(remainder))
|
bd5f67911906b6591d9e31959aeed62389d06d90 | Isabellarossi/PythonProjects | /venv/DiceRoller.py | 255 | 3.8125 | 4 | import random
MIN = 1
MAX = 6
roll = True
while roll:
input_from_keys = input("Do you want to roll a dice? Y or N ")
if input_from_keys == 'Y':
print(random.randint(MIN, MAX))
else:
print("Fine, go on then")
break
|
f96acbe187f4ad1fa32754a51928421946a804ec | JuanjoAlegria/NeuralPython | /ActivationFunctions/Rectifier.py | 968 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import numpy as np
from AbstractActivationFunction import AbstractActivationFunction
class Rectifier(AbstractActivationFunction):
"""Función de activación rectificadora, definida como
.. math::
f(x) = max(0,x)
y con derivada igual a
.. math::
f'(x) =
... |
249d2e81adb9c248a2f30fd1804971de996df98b | JuanjoAlegria/NeuralPython | /ActivationFunctions/AbstractActivationFunction.py | 1,332 | 3.671875 | 4 | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class AbstractActivationFunction:
"""Clase base para todas las funciones de activación
"""
__metaclass__ = ABCMeta
@abstractmethod
def function(self, vector):
"""Calcula la función de activación sobre el vector entregado
... |
242de37729927487e233ec2a540470e1ea8f1a95 | saurabhLearns/30-day-leetcoding-challenge-answers | /30_check_if_a_string_is_a_valid_sequence_from_root_to_leaves_path_in_a_binary_tree.py | 769 | 3.8125 | 4 | #contest url:https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/532/week-5/3315/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def is... |
5400803351b919d33e0fb004031f104dd06c4d13 | Marzahh/Python2020 | /prog alused/tund 4 ex 2.py | 463 | 3.9375 | 4 | rangestart = int(input("Sisesta vahemiku alguse "))
rangeend = int(input("Sisesta vahemiku lõppu "))
inimeseguess = 0
while inimeseguess != arvutiarv:
arvutiarv = randint(1,10)
inimeseguess = int(input("insert your number guess "))
if arvutiarv == inimeseguess:
print("Õige!")
if arvuti... |
7b95b9682a8e72bdc0482c5b879bb2f21208d98c | Marzahh/Python2020 | /prog alused/last class/cats. find color and tail average.py | 1,708 | 3.609375 | 4 | # Ülesanne 3 Kassiklubi
# Kassiklubi Felix vajab abiprogrammi oma kiisukeste andmete töötlemiseks. Iga kassi kohta on tekstifailis
# nimi, värvus ja saba pikkus. Viimane on eriti suure tähtsusega ;) Andmed on faili felix.txt
# Kirjuta programm, mis aitab klubi omanikul leida teda huvitavat värvi kasside keskmine sabap... |
2895b1347bb81d51fd751a692d15ac6cf82c7dbf | rajdharmkar/Python2.7 | /rqurd_args2.py | 478 | 3.640625 | 4 | # program to show that two arguments declared in definition of function are REQUIRED ARGUMENTS. If one or more of these not passed, error is shown
def requiredArg(str, num):
print str, num
requiredArg('Hello')
# Traceback (most recent call last):
# File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/rqurd_a... |
49f9fe9f6f2e695223c8c73ed60d7dc01a41d0ff | rajdharmkar/Python2.7 | /sortwordsinalbetorder1.py | 527 | 4.53125 | 5 | my_str = input("Enter a string: ")
# breakdown the string into a list of words
words = my_str.split()# here separator is a space between words
print words
# sort the list
words.sort()
# display the sorted words
for word in words:
print(word)
my_str = input("Enter a string with words separated ... |
17e86708d5b2a0476756c63ab8d0cd12a77eba92 | rajdharmkar/Python2.7 | /initmethd1.py | 1,676 | 4.625 | 5 | class Human:
# def __init__(self): pass # init method initializing instance variables
#
# def __str__(): pass # ??
#
# def __del__(self): pass # ??...these three def statements commented out using code>> comment with line comment..toggles
def __init__(self, name, age, gender): # self m... |
d771e569e2764575b55e335d3a297c33fbc9540b | rajdharmkar/Python2.7 | /math/primebtw1.py | 355 | 4.09375 | 4 | #prints all the prime numbers between the lower and upper numbers inputed
lower = int(raw_input("Enter a number:"))
upper = int(raw_input("Enter a number:"))
for num in range(lower+1,upper):
if num > 1:
for i in range(2,num):
if (num % i)==0:
break
else:
... |
def4e7d74619c49aa29b364d6106c7d1d8cacc0e | rajdharmkar/Python2.7 | /multiple inheritance.py | 547 | 4.0625 | 4 | #Example of multiple inheritance
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
class First(object):
def __init__(self):
super(First, self).__init__()
print("first")
class Second(object):
def __init__(self):
super(Sec... |
53ebcd324577f722da9407c61ea2adf9dc66bed1 | rajdharmkar/Python2.7 | /math/fibo.py | 1,296 | 4.28125 | 4 |
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b, # comma in print statement acts like NOT newline , all numbers are printed in one line..a row of numbers
# without comma or anything everytime there is a new line; we get a colu... |
16c0d9db5c7237b6f7dace39bdaf2b949d0b070e | rajdharmkar/Python2.7 | /assertXpl2.py | 2,214 | 4.40625 | 4 | class B: # class declaration with keyword class, class object B created
# class object; instance object; function object; method object
x = 10 # this is a class attribute
def __init__(self, name): # this is a __init__ method, also called a constructor that initializes default values of instance
... |
b20e8e5fc85924d740d9c0ea38f22e43fecf3147 | rajdharmkar/Python2.7 | /continueeX.py | 486 | 4.34375 | 4 | for val in "string":
if val == "i":
continue
print(val),
print("The end")
#The continue statement is used to skip the rest of the code inside a loop for
#the current iteration only. Loop does not terminate but continues on with the
#next iteration.
#Syntax of Continue
#continue
#We co... |
13bcc351d18826e483b62b4a7eb9e94f85cdb0c6 | rajdharmkar/Python2.7 | /Exception handling/NameError3.py | 684 | 4.5 | 4 | s = raw_input('Enter a string:') # raw_input always returns a string whether 'foo'/foo/78/'78'
# n =int(raw_input(prompt))); this converts the input to an integer
n = input("Enter a number/'string':")# this takes only numbers and 'strings'; srings throw errors ..it also evaluates if any numeric expression is given
p... |
54489e11fa630a2dfd23f5563fef5d0092dfd174 | rajdharmkar/Python2.7 | /classes/property1.py | 760 | 3.96875 | 4 | class P:
def __init__(self, x): # init method
self._x = x # could be equal to None
@property # property is a special attribute of a class
def x(self): # property method and setter method have same name ; example of method overloading
return self._x
@x.setter
def x(self, x)... |
ea81c1667ac5b76d19d935cf2e009a85fbf12b9f | rajdharmkar/Python2.7 | /Exception handling/runtimeerror2.py | 76 | 3.640625 | 4 | a = input('Enter a number:')
b = input('Enter a number:')
c = a*b
print c |
d3db4014449d6b02a3c6a99d7101ffc793e87048 | rajdharmkar/Python2.7 | /usinganyorendswith1.py | 583 | 4.4375 | 4 | #program to check if input string endswith ly, ed, ing or ers
needle = raw_input('Enter a string: ')
#if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'):
# print('Is valid')
#else:
# print('Invalid')
if needle in ('ly', 'ed', 'ing', 'ers'):#improper code
... |
ecc67dc6fbc3d725071502c16e6314c1a515faa3 | rajdharmkar/Python2.7 | /classes/classdef1.py | 821 | 3.8125 | 4 | class MyClass:
var = 45 # class variable
def foo(self): # bound class method of MyClass that returns None cos there is no return statement in this method # print("Hello from function foo")
print("Hello from function foo")
def bar(self):# is this a bound class method of MyClass?
retu... |
2be6e85839802e5365e65ee47d09f914d388f198 | rajdharmkar/Python2.7 | /methodoverloading1.py | 606 | 4.25 | 4 | class Human:
def sayHello(self, name=None):
if name is not None:
print 'Hello ' + name
else:
print 'Hello '
# Create instance
obj = Human()
# Call the method
obj.sayHello()
# Call the method with a parameter
obj.sayHello('Rambo')
#obj.sayHello('Run', 'Lola')... |
b8de9e2d5aea3da53773cefe63597ef4a9962186 | rajdharmkar/Python2.7 | /vowconsofilter1.py | 611 | 3.921875 | 4 | alphabets =['a','b','c','d','f','j','k','i','m','n','p']
vowels = ['a','e','i','o','u']
def filtervowels1(x):
for i in vowels:
if i in x:
print i,
def filtervowels2(z):
for i in vowels:
if i not in z:
print i,
filtervowels1(alphabets)
print '\n'
filtervowe... |
a1570be63b4b7b80e3acde074c7280eed8211625 | 18cyoung/SoftwareDev1 | /EX1DNA/SplicingOutIntrons.py | 781 | 3.6875 | 4 | Sequence = '''ATCGATCGATCGATCGACTGACTAGTCATAGCTATGCATGTAGCTACTCGATCGATCGATCGA
TCGATCGATCGATCGATCGATCATGCTATCATCGATCGATATCGATGCATCGACTACTAT'''
# Made the Exons of correct fragments
Exon1 = Sequence[0:64]
Exon2 = Sequence[91:125]
# Prints Sequence without Intron
print(Exon1 + Exon2)
### PART 2
#Find lengths of seque... |
7f9b862c311e3a3962eaede0c578e8929ab2c483 | 18cyoung/SoftwareDev1 | /HolidayTask1/DNA1.py | 678 | 3.5 | 4 | #Set variables to each file
Fragment = open("Fragment1.txt")
DNA = open("Suspect1.txt")
#Reads the files and sets as same variables
Fragment = Fragment.read()
DNA = DNA.read()
#Finds the location of the first letter of the fragment
Sus = DNA.find(Fragment)
#Analyses if fragment is in the suspect DNA then calculate t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.