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 |
|---|---|---|---|---|---|---|
8ab27a2740fb89fe98d49ea63d334f7e5caec3c0 | kenu/g-coin | /gcoin/proof.py | 756 | 3.84375 | 4 | import hashlib
DIFFICULTY = 1 # number of digits is difficulty
VALID_DIGITS = '0' * DIFFICULTY
def valid_proof(last_proof, proof):
""" Validates proof
last digits of hash(last_proof, proof)
== VALID_DIGITS
Args:
last_proof (int): previous proof
proof (int): proof to validate
... |
86850fbb6c751efce65db5088fb83dee06b6ae84 | chrisullyott/wordsearch-solver | /app/file.py | 205 | 3.9375 | 4 | """
Helpers for files.
"""
def read_file_upper(filename):
"""Read a file as an uppercase string."""
with open(filename) as file:
contents = file.read().strip().upper()
return contents
|
d11c1c967cc19dff7e538080266d08eb9f148366 | GSacchetti/Segmentation-of-multispectral-and-thermal-images-with-U-NET | /Construction_data/excel_to_tif_array.py | 5,669 | 3.578125 | 4 | #######. This algorithm is to convert the excel files into tiff images and arrays. #######
#Our dataset were in the form of excel tables, to convert these tables into a tiff image, I created this Convert function.
#To perform this conversion, we have calculated a displacement step called "step",
#because this table... |
73097e79c8ed996ebe58bc1638b3dfc938750d0e | abishamathi/python-program- | /even numbers.py | 120 | 3.546875 | 4 | even = []
for n in l :
if(n % 2 == 0):
even.appened(n)
return even
print(even num([1,2,3,4,5,6,7,8,9]))
|
8b3f291d7d9b0ecd8bc8584833a650e913c94773 | abishamathi/python-program- | /number of spaces.py | 124 | 3.703125 | 4 | fname=input('Enter file name:')
words=line.splits()
if(letter.isspace):
k=k+1
print('Occurrance of blank spaces:')
print(k)
|
0a4cc84bd54d8e538b82324172d78b145d7df88e | abishamathi/python-program- | /largest.py | 226 | 4.21875 | 4 | num1=10
num2=14
num3=12
if (num1 >= num2) and (num1 >= num3):
largest=num1
elif (num2 >= num1) and (num2 >=num3):
largest=num2
else:
largest=num3
print("the largest num between",num1,"num2,"num3,"is",largest)
|
54ed98a7d0f6c1fdde317afe0b8ff53b0cefe343 | LucaRuggeri17/pdsnd_github | /script.py | 7,337 | 4.125 | 4 | # Explore Bikeshare data
# Data creation May 2020
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to anal... |
935f658529bd76c0f58a1dc795567d10ead00b20 | mhtarek/Uri-Solved-Problems | /1049.py | 648 | 3.78125 | 4 | x= input()
y= input()
z= input()
if x == "vertebrado":
if y=="ave":
if z=="carnivoro":
print("aguia")
elif z == "onivoro":
print("pomba")
elif y=="mamifero":
if z=="onivoro":
print("homem")
elif z == "herbivoro":
prin... |
cf3ef53dc91ea47ef1cdd9cc7c5fc36c05732d61 | mhtarek/Uri-Solved-Problems | /1216.py | 205 | 3.734375 | 4 | sum = 0
count = 0
while True:
try:
input()
sum+=int(input())
count+=1
except EOFError:
avg = float(sum/count)
print("%.1f" % avg)
break
|
033a7a9082b24b1ba9781d4ae26c98eac30cf805 | mhtarek/Uri-Solved-Problems | /1161.py | 249 | 3.5625 | 4 | def fact(m):
if m==1 or m==0:
return 1
else:
return m*fact(m-1)
while True:
try:
ar = [int(i) for i in input("").split()]
print(fact(ar[0])+fact(ar[1]))
except EOFError:
break
|
c289e68604c1ec7c15f08f2ab33b64e44a63983e | FuelDoks48/Project | /command_if.py | 1,410 | 3.515625 | 4 |
# Обработка специальных значений
# requsted_topping = ['mushrooms', 'green peppers', 'extra chesse']
# for requsted_topping in requsted_topping:
# print (f'Adding {requsted_topping}.')
# print(f'Finished make your pizza!')
# __________________________________________________________
#
# Проверка вхождений
# ... |
c76282a14c6a1c54f0566890377035a533786f6c | Engineering-Course/LIP_JPPNet | /get_maximum_square_from_segmented_image.py | 3,716 | 3.609375 | 4 | # This function is used to get the largest square from the cropped and segmented image. It can be further used to find patterns
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
from collections import namedtuple
import glob
def printMaxSubSquare(M):
"""" find the lar... |
da16b14210a67f0b8bff8212d023eff2040e5424 | AlifeLine/toolkit | /tools/quick_sort2.py | 617 | 4 | 4 | def quick_sort(arr, left=0, right=None):
if right is None:
right = len(arr) - 1
if left >= right:
return
l = left
r = right
key = arr[left]
while left < right:
while left < right and arr[right] >= key:
right -= 1
arr[left] = arr[right]
while... |
72a89c29b77bca2fcada96ce5a4b46cc965128c4 | AlifeLine/toolkit | /tools/lru.py | 815 | 3.8125 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class Lru(object):
def __init__(self, vals):
self._head = None
for val in vals:
node = Node(val)
if self._head:
self._head.next = node
else:
... |
bd001f39c500f13c409b9e4f22f41156cabc636d | leolion0/490-Lesson-3 | /question 1.py | 1,451 | 3.890625 | 4 | class Employee:
numEmployees = 0
def __init__(self, name="", family="", salary="", department=""):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.numEmployees += 1
def fillFromUser(self):
self.name = str(inpu... |
6ee056c951856f4bc7e8e6bd7d95b10865c3085b | rohitbapat/NQueensNRooks-Problem | /a0.py | 8,287 | 4.1875 | 4 | #!/usr/bin/env python3
# nrooks.py : Solve the N-Rooks problem!
#
# The N-Queens problem is: Given an empty NxN chessboard, place N queens on the board so that no queens
# can take any other, i.e. such that no two queens share the same row,column or are on the same diagonal
#
# Citations mentioned at the end of the cod... |
bad58f360c606e5a92312ffd2115872b42fffd57 | tenasimi/Python_thero | /Class_polymorphism.py | 1,731 | 4.46875 | 4 | # different object classes can share the same name
class Dog():
def __init__(self, name):
self.name = name
def speak(self): # !! both Nico and Felix share the same method name called speak.
return self.name + " says woof!"
class Cat():
def __init__(self, name... |
5cd6aae2bacc1b6626dafbc541c626c811e67aac | tenasimi/Python_thero | /Class_Inheritance.py | 717 | 4.15625 | 4 | class Animal():
def __init__(self):
print("ANIMAL CREATED")
def who_am_i(self):
print("I am animal")
def eat(self):
print("I am eating")
myanimal = Animal() #__init__ method gets automatically executed when you
# create Anumal()
myanimal.who_am_i()
myanim... |
ef64e2b1091b79e6c1df275002c49bb501b70759 | tenasimi/Python_thero | /test_test_test.py | 1,345 | 3.828125 | 4 | print(1 % 2)
print(2 % 2)
print(3 % 2)
print(4 % 2)
print(5 % 2)
print(6 % 2)
print(7 % 2)
print(8 % 2)
print(9 % 2)
def almost_there(n):
return (abs(100-n) <= 10) or (abs(200-n) <= 10)
print(almost_there(190))
print(abs(20-11))
#help(map)
print()
def square(num):
return num**2
print(square(6))
def up_low... |
6abeba2d5f744e34aa97a48fe06a5dac4cf27207 | tenasimi/Python_thero | /sec4_comparison_operators.py | 7,715 | 4.46875 | 4 | print(1 < 2 and 2 > 3)
print(1 < 2 and 2 < 3)
print('h' == 'h' and 2 == 2) # AND!! both of them must be true
print(1 == 2 or 2 < 3) # OR!! one of them must be true
print(not 1 == 1) # NOT !! for opposite boolean result
#
if True:
print('ITS TRUE!')
#
if False:
print('ITS False!')
else:
print('Its always Tru... |
def301bd04c9524897496e3935cc1b319b47c3dc | fgiraudo/aoc-2019 | /Sources/2019-4.py | 1,219 | 3.671875 | 4 | import math
import os
import copy
#Change Python working directory to source file path
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
def main():
count = 0
print(is_valid(112233))
print(is_valid(123444))
print(is_valid(112223))
for password in range(256310, ... |
147c00e912fdc1a94a01fdd2b558a67eaf5db87f | jaykaneriya6143/python | /day5/overriding.py | 211 | 3.59375 | 4 | class Parent:
def fun1(self):
print("This method is parent.......")
class Child(Parent):
def fun1(self):
print("This method is child.......")
c1 = Child()
c1.fun1() |
3f3241fe77bdc53edde180117cf4a7943f363411 | jaykaneriya6143/python | /day2/jk5.py | 142 | 3.78125 | 4 | name = "jay kaneriya"
print("Name is :",name)
print(name[0])
print (name[2:5])
print(name[2:])
print(name * 2)
print(name + "Hello") |
85361ac8a3ba55f2cbe9f0420c48f81dfe0127fb | DRV1726018/vehicle-testing | /gui-alpha/gui.py | 17,628 | 3.671875 | 4 | import math
import tkinter as tk
from tkinter import Label, ttk
from tkinter import font
from PIL import ImageTk,Image
from tkinter import filedialog
from tkinter import *
root = tk.Tk()
root.title("Centro de Gravedad")
root.geometry("1000x600")
root.iconbitmap(file="carro.ico")
#Panel para las pestañas
... |
69b00f30de1e437d363502c96cc4e0956416dddb | FelipeTacara/code-change-test | /greenBottles.py | 423 | 3.921875 | 4 | def greenbottles(bottles):
for garrafas in range(bottles, 0, -1):
# for loop counting down the number of bottles
print(f"{garrafas} green bottles, hanging on the wall\n"
f"{garrafas} green bottles, hanging on the wall\n"
f"And if 1 green bottle should accidentally fall,\n... |
6f0283e896b0a758c9eb88198b2c9718c564aa1b | SurabhiTosh/AI_MazeSolving | /mazedemo.py | 684 | 3.828125 | 4 | from PIL import Image
import numpy as np
# Open the maze image and make greyscale, and get its dimensions
im = Image.open('examples/small.png').convert('L')
w, h = im.size
# Ensure all black pixels are 0 and all white pixels are 1
binary = im.point(lambda p: p > 128 and 1)
# Resize to half its height and w... |
434f69b6fd36753ac13589061bec3cd3da51124a | Alex0Blackwell/recursive-tree-gen | /makeTree.py | 1,891 | 4.21875 | 4 | import turtle as t
import random
class Tree():
"""This is a class for generating recursive trees using turtle"""
def __init__(self):
"""The constructor for Tree class"""
self.leafColours = ["#91ff93", "#b3ffb4", "#d1ffb3", "#99ffb1", "#d5ffad"]
t.bgcolor("#abd4ff")
t.... |
1f4efdbabe7ec92db5d9a4d9f287de6c82988634 | scott-yj-yang/cogs118a-final | /data_cleaning.py | 3,909 | 3.59375 | 4 | import pandas as pd
from my_package import clean_course_num
def clean_all_dataset():
# Clean the adult dataset
columns = ["age", "workclass", "fnlwgt", "education", "education-num", "marital-status",
"occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week",
... |
e02add5ed76d468dc7ba4ec07060daeb1e069be3 | tjbonesteel/ECE364 | /Labfiles/Lab13/flow1.py~ | 2,174 | 3.53125 | 4 | #! /usr/bin/env python2.6
# $Author: ee364d02 $
# $Date: 2013-11-19 22:43:05 -0500 (Tue, 19 Nov 2013) $
# $HeadURL: svn+ssh://ece364sv@ecegrid-lnx/home/ecegrid/a/ece364sv/svn/F13/students/ee364d02/Lab13/flow.py $
# $Revision: 63131 $
from Tkinter import *
import os
import sys
import math
import re
fileIN = sys.argv... |
d94f04f820ec9c6a0eb6b19c3e998384966b55aa | ProgFuncionalReactivaoct19-feb20/practica04-royerjmasache | /practica4.py | 1,239 | 3.90625 | 4 | """
Práctica 4
@royerjmasache
"""
# Importación de librerías
import codecs
import json
# Lectura de archivos con uso de codecs y json
file = codecs.open("data/datos.txt")
lines = file.readlines()
linesDictionary = [json.loads(a) for a in lines]
# Uso de filter y función anónima para evaluar la condición requerida y f... |
8a39ae38331f518ac8c64d6d74dee4a89534f559 | lfarhi/scikit-learn-mooc | /python_scripts/feature_selection.py | 11,193 | 3.828125 | 4 | # ---
# jupyter:
# jupytext:
# cell_metadata_filter: -all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # ... |
c006402cf62530d0b685d5becf283a9f43d1796d | UCMHSProgramming16-17/file-io-HikingPenguin17 | /PokeClass.py | 344 | 3.5 | 4 | import random
class Pokemon(object):
def __init__(self, identity):
self.name = identity
self.level = random.randint(1, 100)
bulb = Pokemon('Bulbasaur')
char = Pokemon('Charmander')
squirt = Pokemon('Squirtle')
print(bulb.name, bulb.level)
print(char.name, char.level)
print(sq... |
002464d45f720f95b4af89bfa30875ae2ed46f70 | spencerhcheng/algorithms | /codefights/arrayMaximalAdjacentDifference.py | 714 | 4.15625 | 4 | #!/usr/bin/python3
"""
Given an array of integers, find the maximal absolute difference between any two of its adjacent elements.
Example
For inputArray = [2, 4, 1, 0], the output should be
arrayMaximalAdjacentDifference(inputArray) = 3.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer in... |
1283bc076c088f5f3ef66ba11af46cdb39aae2cd | cjohlmacher/PythonDataStructures | /37_sum_up_diagonals/sum_up_diagonals.py | 662 | 4 | 4 | def sum_up_diagonals(matrix):
"""Given a matrix [square list of lists], return sum of diagonals.
Sum of TL-to-BR diagonal along with BL-to-TR diagonal:
>>> m1 = [
... [1, 2],
... [30, 40],
... ]
>>> sum_up_diagonals(m1)
73
>>> m2 = [
.... |
2252436f7d0b24feb0c6e518ce47f4b85b68bd40 | saumak/AI-projects | /map-search-algorithm/problem3/solver16.py | 7,136 | 3.859375 | 4 | #!/usr/bin/env python
#
# solver16.py : Solve the 16 puzzle problem - upto 3 tiles to move.
#
# (1)
# State space: All possible formulation of the tiles in 16 puzzle problem.
# For example, a sample of the state look like this,
# S0 = array([[ 2, 3, 0, 4],
# [ 1, 6, 7, 8],
# [ 5, 10, 1... |
624fc12118833578813725bbb15e2477e04e587e | borisnorm/codeChallenge | /practiceSet/redditList/general/rotatedBSearch.py | 1,074 | 4 | 4 | #Binary Search on a Rotated Array
#Find the pivot point on a rotated array with slight modificaitons to binary search
#There is reason why the pivoting does not phase many people
#[5, 6, 7, 8, 1, 2, 3, 4]
def find_pivot_index(array, low, hi):
#DONT FORGET THE BASE CASE
if hi < low:
return 0
if hi == low:
... |
ecaa063b18366d5248e01f5392fcb51e59612c1e | borisnorm/codeChallenge | /practiceSet/levelTreePrint.py | 591 | 4.125 | 4 | #Print a tree by levels
#One way to approach this is to bfs the tree
def tree_bfs(root):
queOne = [root]
queTwo = []
#i need some type of switching mechanism
while (queOne or queTwo):
print queOne
while(queOne):
item = queOne.pop()
if (item.left is not None):
queTwo.append(item.left... |
d3ad65cbc6ec353c964cb8fb7202b0156f2fb150 | borisnorm/codeChallenge | /practiceSet/g4g/DP/cover_distance.py | 803 | 4 | 4 | #Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps.
#distance, and array of steps in the step count
#1, 2, 3 is specific - general case is harder because of hard coding
#RR solution
def cover(distance):
if distance < 0:
return 0
if distance = 0:
return 1
el... |
bd2ec1025a05a2b3b3a8cb0188762d620090c328 | borisnorm/codeChallenge | /practiceSet/intoToBinary.py | 407 | 3.828125 | 4 | #Math Way
def binary_to_int(number):
result = ""
while (number > 0):
result.insert(0, number % 2)
number = number % 2
return result
#BitShifting Way
def b_to_int(number):
result = []
for i in range(0, 32):
result.insert(number && 1, 0)
number >> 1
return result
#Python convert array of num... |
409c1452aaaa56dfc51186c75c8a1bbaefece675 | borisnorm/codeChallenge | /practiceSet/phoneScreen/num_reduce.py | 1,074 | 3.578125 | 4 | #Given a list o numbers a1/b1, a2/b2, return sum in reduced form ab
#Sum it in fractional form, or keep decimals and try to reverse
#This is language specific question
#(0.25).asInteger_ratio()
#Simplify
#from Fractions import fraction
#Fraction(0.185).limit_denominator()A
#A fraction will be returned
from Fractions... |
5efebfc8ae11c7ae96bfb8c263b5320e48a2a582 | borisnorm/codeChallenge | /practiceSet/redditList/trees/kOrderBST.py | 627 | 3.75 | 4 | #Find Second largest number in a BST
#Must be the parent of the largest number, logn time
def secondLargest(root):
if root.right.right is None:
return root.right.value
else:
return secondLargest(root.right):
#Find The K largest number in a BST
#Initalize counter to 1, could put it into an array, but was... |
74e6ec63b7f3f50cb964f5c0959e4b6b224bbf05 | borisnorm/codeChallenge | /practiceSet/g4g/graph/bridge.py | 759 | 3.53125 | 4 | #Given a graph find all of the bridges in the graph
#Remove every edge and then BFS the graph, fi not all veriicies touched then that is it
#get neighbors - would recursive solution be better here? Naieve solution
def dfs(source, graph, size):
visited = set()
stack = [source]
while stack:
item = stack.pop(... |
77806d17215fc004445465e5c06714662f4deadf | borisnorm/codeChallenge | /practiceSet/redditList/trees/printTree.py | 657 | 3.8125 | 4 | #Print Tree using BFS and DFS
def dfs_print(root):
if root is None:
return
else:
#shift print down, for pre, in, or post order
print root.value
dfs_print(root.left)
dfs_print(root.right)
def bfs_print(root):
queOne = [root]
queTwo = []
while (queOne && queTwo):
print queOne
while... |
1052e9187b6693114b6472dbfc4aebef9ec5e368 | borisnorm/codeChallenge | /practiceSet/unionFind.py | 937 | 3.765625 | 4 | class DisjoinstSet:
#This does assume its in the set
#We should use a python dictionary to create this
def __init__(self, size):
#Make sure these are default dicts to prevent the key error?
self.lookup = {}
self.rank = {}
self.size = 0
def add(self, item):
self.lookup[item] = -1
#Union by r... |
2c76d8ff3516b065bcf92f674a847640f0896153 | borisnorm/codeChallenge | /practiceSet/g4g/tree/bottom_top_view.py | 1,168 | 3.71875 | 4 | #Print the bottom view of a binary tree
lookup = defaultdict([])
def level_serialize(root, lookup):
queueOne = [(root, 0, 0)]
queueTwo = []
while (queueOne && queueTwo):
while (queueOne):
item = queueOne.pop()
lookup[item[1]].append(item[0].value)
if (item[0].left):
queueTwo.insert(0... |
7efe77de55bd3666271186c9e8537f4228eb300d | borisnorm/codeChallenge | /practiceSet/allPartitions.py | 808 | 3.71875 | 4 | def isPal(string):
if string = string[::-1]
return True
return False
def isPal(array):
lo = 0
hi = len(array) - 1
while lo < hi:
if array[lo] != array[hi]):
return False
return True
def arrayElmIsPal(array):
for i in range(len(array)):
if isPal(array[i]) is False:
return False
... |
15deda40cadaee36bf146665d48fd507d33baaad | borisnorm/codeChallenge | /practiceSet/g4g/stringArray/special_reverse.py | 364 | 3.671875 | 4 | #Reverse reverse then add back in
def s_rev(string, alphabet):
string_builder = ""
for i in range(len(string)):
if string[i] in alphabet:
string_builder += string[i]
rev = string_builder[::-1]
rev_counter = 0
for j in range(len(string)):
if string[j] in alphabet:
string[j] = rev[rev_count... |
bb6ec537a4019717fcb9f4d9be38d30bd84c31c5 | borisnorm/codeChallenge | /practiceSet/g4g/stringArray/count_trip.py | 370 | 3.921875 | 4 | #Count Triplets with sum smaller than a given value in an array
#Hashing does not help because there is no specific target to look for?
def count_trip(array, value):
counter = 0
for i in range(len(array)):
for j in range(len(array)):
for k in range(len(array)):
if array[i] + array[j] + array[k] <... |
07e6ccccbbd50cbb91199588006e07afc89887af | sbsreedh/DP-3 | /minFallingPathSum.py | 1,042 | 3.84375 | 4 | #Time Complexity=O(m*n)m-length of A, n-length of A[0]
#Space Complexity-O(m*n)
#we first initialize a 2D DP matrix, and then iterate the original matrix row by row. For each element in DP matrix, we sum up the corresponding element from original matrix with the minimum neighbors from previous row in DP matrix.Here ins... |
fe8abe9c0010c34ac01963ffa8032930c899625c | FailedChampion/CeV_Py_Ex | /ex049.py | 316 | 4.0625 | 4 | # Exercício Python 049: Refaça o DESAFIO 009, mostrando a tabuada
# de um número que o usuário escolher, só que agora utilizando um laço for.
num_escolhido = int(input('Insira o número que deseja ver a tabuada: '))
for a in range(1, 11):
print('{} x {} = {}'.format(num_escolhido, a, num_escolhido * a))
|
7d610d3df84b0abb5c39d03fd658cd1f0f0b0e81 | FailedChampion/CeV_Py_Ex | /ex006.py | 329 | 3.984375 | 4 | # Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada.
n1 = int(input('Digite um número: '))
dou = n1 * 2
tri = n1 * 3
rq = n1 ** (1/2)
print('\n O dobro de {} é: {}'.format(n1, dou), '\n \n O triplo de {} é: {}'.format(n1, tri), '\n \n A raíz quadrada de {} é: {:.3f}'.format (n1, rq)... |
65d580e0f81ba9c29d3e6aa97becd5c83bd36aaf | FailedChampion/CeV_Py_Ex | /ex30.py | 164 | 3.9375 | 4 | num = int(input('Insira um número: '))
res = num % 2
print('\n')
print(res)
print('\nSe o resultado for 1, o número é ímpar,\n se for 0, é par.')
|
81575a05e053e8fb26e75a18deeb4b2db6105a65 | FailedChampion/CeV_Py_Ex | /ex007.py | 357 | 4 | 4 | # Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média.
n1 = float(input('Insira a primeira nota: '))
n2 = float(input('Insira a segunda nota: '))
print('A média entre {:.1f} e {:.1f} é igual a {:.1f}.'.format(n1, n2, (n1 + n2 / 2)))
print('Com isso em mente, a média do aluno fo... |
7e9255240d93efca2d010bb9f290520d56dd9dad | FailedChampion/CeV_Py_Ex | /ex018.py | 422 | 4.03125 | 4 | # Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
from math import sin, cos, tan, radians
n = float(input('Insira um ângulo: '))
r = radians(n)
print('Os valores de seno, cosseno e tangente do ângulo {:.0f} são:'.format(n))
print('\nSeno: {:.2f}'.form... |
fd181116ec4204dc513a88bad5efbe5057fe2096 | FailedChampion/CeV_Py_Ex | /ex008.py | 387 | 4.09375 | 4 | # Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
m = float(input('Insira uma distância em metros: '))
dm = m * 10
cm = m * 100
mm = m * 1000
print('A medida de {}m corresponde a \n{:.3f} Km \n{:.2f} Hm \n{:.1f} Dam'.format(m, (m / 1000), (m / 100), (m / 10)))
p... |
4f99ebc36affe769b3f861b7353e26dd8bc61f17 | ANANDMOHIT209/PythonBasic | /11opera.py | 255 | 4.09375 | 4 | #1.Arithmatic Operators
x=2
y=3
print(x+y)
print(x-y)
print(x*y)
print(x/y)
#2.Assignment Operators
x+=2
print(x)
a,b=5,6
print(a)
print(b)
#3.Relational Operators-- <,>,==,<=,>=,!=
#4.Logical Operators-- and ,or,not
#5.Unary Operators--
|
ef1808200296b1e75862f604def553543e94c246 | ANANDMOHIT209/PythonBasic | /4.py | 209 | 3.765625 | 4 | x=2
y=3
print(x+y)
x=10
print(x+y)
name='mohit'
print(name[0])
#print(name[5]) give error bound checking
print(name[-1]) #it give last letter
print(name[0:2])
print(name[1:3])
print(name[1:])
|
21d5842cfc55a1ee5d742eab7ca8f4a89278de30 | usert5432/cafplot | /cafplot/plot/rhist.py | 3,128 | 3.546875 | 4 | """
Functions to plot RHist histograms
"""
from .nphist import (
plot_nphist1d, plot_nphist1d_error, plot_nphist2d, plot_nphist2d_contour
)
def plot_rhist1d(ax, rhist, label, histtype = None, marker = None, **kwargs):
"""Plot one dimensional RHist1D histogram.
This is a wrapper around `plot_nphist1d` fun... |
11ff9ab018629fccbc71bbde47158ae1c8f0a0af | bamundi/python-cf | /diccionario.py | 373 | 3.625 | 4 | #no se pueden usar diccionarios y listas
#no tienen indice como las listas
#no se puede hacer slidesing (?) [0:2]
#se debe hacer uso de la clave para llamar a un elemento
diccionario = {'Clave1' : [2,3,4],
'Clave2' : True,
'Clave00' : 4,
5 : False
}
diccionario['clave00'] = "hola"
print diccionario['Clave... |
925cdc22f6be9a7103ba64204e1c54aa31db0f4c | jpclark6/adventofcode2019 | /solutions/20day.py | 4,467 | 3.578125 | 4 | import re, time
class Puzzle:
def __init__(self, file_name):
self.tiles = {}
file = open(file_name).read().splitlines()
matrix = [[x for x in line] for line in file]
for y in range(len(matrix)):
for x in range(len(matrix[0])):
if bool(re.search('[#.]', ma... |
53f08e65cc83ea5040a6477e363a487a59d343ed | jpclark6/adventofcode2019 | /solutions/8day.py | 2,043 | 3.53125 | 4 | # For example, given an image 3 pixels wide and 2 pixels tall,
# the image data 123456789012 corresponds to the following image layers:
# Layer 1: 123
# 456
# Layer 2: 789
# 012
# The image you received is 25 pixels wide and 6 pixels tall.
def input():
return open("puzzledata/8day.txt", "r").read().rstrip('\n'... |
e27e14c82cf4b8a8a76981ae7ff87ec882ca35d8 | oarriaga/PyGPToolbox | /src/genBivarGaussGrid.py | 1,072 | 3.890625 | 4 | ## This code is modified from: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/
## How to use output:
## plt.figure()
## plt.contourf(X, Y, Z)
## plt.show()
import numpy as np
def genBivarGaussGrid(mu, cov, numSamples = 60):
size = np.sqrt(np.amax(cov))
X = np.linspace(mu[0]-4*si... |
0f41df799989322b73f8aad2a7d00cac3ecdd7e7 | nadyndyaa/BASIC_PYTHON5-C | /day3.py | 1,858 | 4.0625 | 4 | #For Loop = mengulang suatu program sebanyak yg kita inginkan
# fruits = ["apple","banana","cherry","manggis","buah naga"]
#print(fruits[0])
#print(fruits[1])
#print(fruits[2])
#print(fruits[3])
#fruits = ["apple","banana","cherry"]
#for x in fruits:
#print(x)
#range
#menggunakan batasan stop saja
#for ... |
a7da7e51ab20d1a4122af8458847451696bf500e | nadyndyaa/BASIC_PYTHON5-C | /func_example.py | 323 | 3.65625 | 4 | def luas_lingkaran(r):
return 3.14 * (r*r)
r = input('Masukan jari lingkaran :')
luas = luas_lingkaran(int(r))
print('Luasnya: {}'.format(luas))
def keliling_lingkaran(R):
return 2 * 3.14 *(R)
R = input( "masukkan keliling :")
keliling = keliling_lingkaran(int(R))
print('Kelilingnya :{}'.format(keliling)... |
582d85050e08a6b8982aae505cdc0acc273aec74 | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/4.Prototype.py | 1,661 | 4.1875 | 4 | # A prototype pattern is meant to specify the kinds of objects to use a prototypical instance,
# and create new objects by copying this prototype.
# A prototype pattern is useful when the creation of an object is costly
# EG: when it requires data or processes that is from a network and you don't want to
# ... |
1d55b37fbef0c7975527cd50a4b65f2839fd873a | Kyle-Koivukangas/Python-Design-Patterns | /A.Creational Patterns/2.Abstract_Factory.py | 1,420 | 4.375 | 4 | # An abstract factory provides an interface for creating families of related objects without specifying their concrete classes.
# it's basically just another level of abstraction on top of a normal factory
# === abstract shape classes ===
class Shape2DInterface:
def draw(self): pass
class Shape3DInterface:
de... |
4eb05cf9d3d3b4dba91e659cc75882b5d35f9955 | FunkMarvel/CompPhys-Project-1 | /project.py | 3,546 | 3.734375 | 4 | # Project 1 FYS3150, Anders P. Åsbø
# general tridiagonal matrix.
from numba import jit
import os
import timeit as time
import matplotlib.pyplot as plt
import numpy as np
import data_generator as gen
def main():
"""Program solves matrix equation Au=f, using decomposition, forward
substitution and backward ... |
ae0cc41da83e3c9babb8b2363ddab700cb375179 | drewthayer/intro-to-ds-sept9 | /week2/day05-strings_tuples/strings_tuples_lecture.py | 5,481 | 4.65625 | 5 | # create, analyze and modify strings
# strings are like immutable lists
# def iterate_through_str(some_str):
# for i, char in enumerate(some_str):
# print(i, char)
# # some_str_lst = list(some_str)
# # for char in some_str_lst:
# # print(char)
test_str = 'We need to pass something in thi... |
54b83e0a80cb5ddf23722b4170d671e6974686c8 | shahZ51/python-challenge | /PyPoll/main.py | 1,345 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[13]:
import os
import csv
import pandas as pd
# In[14]:
csvpath = ("Resources/election_data.csv")
df = pd.read_csv(csvpath)
df.head()
# In[15]:
total_votes = df['Voter ID'].count()
total_votes
# df.groupby('Candidate').sum()
# In[16]:
candidate_vote =df.groupby... |
e24fe24b95d36d74782e57d0754e6fac56007425 | tofuu/CSE-Novello-Final | /__main__.py | 676 | 3.84375 | 4 | # -*- coding: utf-8 -*-
#Before you push your additions to the code, make sure they exactly fit the parameters described in the project!
#Let's write delicious code. がんばってくらさい!
# Abirami
import math
def list_prime_factors(num):
n = int(num)
prime = []
k=1
if n%2==0:
prime.append(2)
... |
d40f8d250528001d359c09eecf6505e970cb426e | vbodell/ii1304-modellering | /simulation.py | 2,885 | 3.625 | 4 | from population import Population
class Simulation:
def __init__(self, N, probInfect, minDaysSick, maxDaysSick, probDeath,
initialSick, VERBOSE, SEED):
self.N = N
self.probInfect = probInfect
self.totalSickCount = len(initialSick)
self.totalDeathCount = 0
self.printIn... |
7b8625d7a26569c437a7ea560b2c56596db48fb1 | atomsk752/study | /180806_oop/dragon_game_item.py | 4,697 | 3.703125 | 4 | import random
class Dragon:
def __init__(self, lev, name):
self.lev = lev
self.hp = lev * 10
self.jewel = lev % 3
self.name = name
self.attack = self.lev * 10
def giveJewel(self):
return self.jewel
def attackHero(self):
print(self.name + ": 캬오~~... |
66484192d25bf31838df22abe82623a8e11567b9 | atomsk752/study | /180806_oop/lucky_box.py | 461 | 3.515625 | 4 | import random
class Item:
def __init__(self, str):
self.str = str
def __str__(self):
return "VALUE: " + self.str
class Box:
def __init__(self, items):
self.items = items
random.shuffle(self.items)
def selectOne(self):
return self.items.pop()... |
2350246ad0d7208ad8a2136740f6fb83f1b662bb | kenjirotorii/burger_war_kit | /autotest/draw_point_history.py | 781 | 3.5625 | 4 | #!/usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
import sys
def draw_graph(csv_file, png_file):
df = pd.read_csv(csv_file,
encoding="UTF8",
names=('sec', 'you', 'enemy', 'act_mode', 'event',
'index', 'point', 'before', ... |
7d5e1744f843893d418819a14cfc6c7f200de686 | yunakim2/Algorithm_Python | /프로그래머스/level2/짝지어 제거하기.py | 326 | 3.78125 | 4 | def solution(s):
stack = []
for char in s:
if not stack:
stack.append(char)
elif stack[-1] == char:
stack.pop()
else:
stack.append(char)
return 1 if not stack else 0
if __name__ == "__main__":
print(solution("baabaa"))
print(solution("cd... |
fb317af1c41098a48c682ba0ec9337d69b165fda | yunakim2/Algorithm_Python | /백준/재귀/baekjoon10872.py | 141 | 3.625 | 4 | num = int(input())
def fac (i) :
if(i == 1 ) : return 1
if(i ==0) : return 1
else :
return i*fac(i-1)
print(fac(num)) |
f422a1ef411b40fb0553d8e34ca2c780980dd223 | yunakim2/Algorithm_Python | /프로그래머스/level2/가장 큰 수.py | 457 | 3.5625 | 4 | def solution(numbers):
combi_number = []
bigger_number = ''
for number in numbers:
tmp_number = (str(number)*4)[:4]
combi_number.append([''.join(tmp_number), number])
combi_number.sort(reverse=True)
for _, item in combi_number:
bigger_number += str(item)
return str(int(bi... |
b0eb26a51875aaa4516f1e8db4c2d9a23ec444a0 | yunakim2/Algorithm_Python | /백준/실습 1/baekjoon10996.py | 105 | 3.953125 | 4 | a = int(input())
even = a//2
odd = a- a//2
for i in range(a) :
print("* "*odd)
print(" *"*even) |
93337a29ae77fba36b750bcbf5aeaa16e6e996ee | yunakim2/Algorithm_Python | /알고리즘특강/그리디_숫자카드게임.py | 292 | 3.515625 | 4 |
data = """3 3
3 1 2
4 1 4
2 2 2"""
data = data.split("\n")
n, m = map(int, data[0].split())
arr = []
small= []
arr.append(map(int,data[1].split()))
arr.append(map(int,data[2].split()))
arr.append(map(int,data[3].split()))
for i in range(n):
small.append(min(arr[i]))
print(max(small)) |
eb309a4c1f80124cfba320759ad9e35c5840c7d5 | yunakim2/Algorithm_Python | /코테/1.py | 1,044 | 3.578125 | 4 | '''
정렬 은 우선 빈도,
같으면 크기 순
'''
from collections import defaultdict
from collections import deque
def sorting(arr):
tmp_arr = []
for i in range(len(arr)):
size = arr[i][1]
for j in range(i+1,len(arr)):
if size != arr[j][1]:
break
else:
else:
... |
e98f224870424065636d98b986db536bb8fe0296 | yunakim2/Algorithm_Python | /프로그래머스/level1/세 소수의 합.py | 866 | 3.796875 | 4 | def solution(n):
def sieve(n):
is_prime = [True] * (n + 1)
is_prime[0] = False
is_prime[1] = False
for candidate in range(2, n + 1):
if not is_prime[candidate]:
continue
for multiple in range(candidate * candidate, n + 1, candidate):
... |
5f30daf7d6e6fca7a3d058e9834ce3d2faf63234 | yunakim2/Algorithm_Python | /프로그래머스/level4/버스 여행 - DFS.py | 725 | 3.796875 | 4 | def solution(n,signs):
def dfs(source, signs, visited_stations):
if len(visited_stations) == len(signs):
return
for destination in range(len(signs)):
if signs[source][destination] == 1 and destination not in visited_stations:
visited_stations.add(destination)
... |
424206f92ae36b0920b12bd37b657e4a432ef419 | yunakim2/Algorithm_Python | /프로그래머스/level2/전화번호 목록.py | 634 | 3.796875 | 4 |
def solution(phone_book):
phone_book.sort()
phone_book = dict([(index, list(phone)) for index, phone in enumerate(phone_book)])
for i in range(len(phone_book)):
size = len(phone_book[i])
for j in range(i+1, len(phone_book)):
if len(phone_book[j]) >= size:
if phon... |
6d2877bb66b8da148e0e06c272588b4e5bc2dfdf | yunakim2/Algorithm_Python | /카카오/2021 카카오 공채/6.py | 631 | 3.546875 | 4 | from collections import deque
def solution(board, skill):
for types, r1, c1, r2, c2, degree in skill:
for r in range(r1, r2+1):
for c in range(c1, c2+1):
if types == 1:
board[r][c] -= degree
else:
board[r][c] += degree
... |
adfa7b36c3cfef17161452849821e96b7a887607 | yunakim2/Algorithm_Python | /백준/실습 1/baekjoon10039.py | 109 | 3.6875 | 4 | sum = 0
for i in range(0,5) :
a = int(input())
if a<40 : sum+=40
else : sum += a
print(sum//5) |
89197c0273cfaf25f86785d59634cc8470f27713 | yunakim2/Algorithm_Python | /백준/1차원 배열/baekjoon4344.py | 270 | 3.578125 | 4 | num = int(input())
for i in range(num) :
data = list(map(int, input().split(' ')))
cnt = data[0]
del data[0]
avg = sum(data) / cnt
k = 0
for j in range(cnt) :
if(data[j]>avg) :
k+=1
print("%.3f"%round((k/cnt*100),3)+"%") |
4d4626a0cdfaf504bc794b78b806e2ac10cd1ee6 | yunakim2/Algorithm_Python | /프로그래머스/level1/짝수와 홀수.py | 96 | 3.671875 | 4 | def solution(num):
if num%2 !=0 : answer ="Odd"
else : answer = "Even"
return answer |
c264959d445653be32a98b1838bd10132ceaa205 | JinhanM/leetcode-playground | /19. 删除链表的倒数第 N 个结点.py | 607 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"... |
1994561a1499d77769350b55a6f32cdd111f31fa | Ajat98/LC-2021 | /easy/buy_and_sell_stock.py | 1,330 | 4.21875 | 4 | """
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve... |
0b19bc5f6af31fb9ef1e9b217e0f99405b139986 | mchristofersen/tournament-project | /vagrant/tournament/tournament.py | 9,965 | 3.578125 | 4 | #!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
# This file can be used to track the results of a Swiss-draw style tournament
# First use set_tournament_id() to generate a new tournament
# Register new players with register_player()
# Once all players are registered, assign pai... |
3b76875ec54479b956a45331c3863f956a61df9a | mounui/python | /examples/use_super.py | 643 | 4.125 | 4 | # -*- coding: utf-8 -*-
# super使用 避免基类多次调用
class Base(object):
def __init__(self):
print("enter Base")
print("leave Base")
class A(Base):
def __init__(self):
print("enter A")
super(A, self).__init__()
print("leave A")
class B(Base):
def __init__(self):
prin... |
7290d9abe62da81613c2bc7a12b0aead3b5e8ae4 | mounui/python | /examples/demo1.py | 387 | 4 | 4 | print('hello world!')
name = input('please enter your name:')
print('hello,',name)
print(1024 * 768)
print(5^2)
print('haha')
bmi = 80.5 / (1.75 ** 2)
if bmi >= 32:
print('严重肥胖')
elif bmi >= 28:
print('肥胖')
elif bmi >= 25:
print('过重')
elif bmi >= 18.5:
print('正常')
else:
print('过轻')
sum = 0
for... |
0b495e493aaf605222998fee8c76b4d02062a94a | RomanKlimov/PythonCourse | /HomeW_13.09.17/MultiTable.py | 136 | 3.609375 | 4 | def mt(number):
for i in range(1, 10):
print(str(number) + " x " + str(i) + " = " + str(number * i))
i += 1
mt(5)
|
ce6e1845c663b30f80d21a5481249fdf685cfef8 | ML-Baidu/classification | /ml/classfication/ID3.py | 4,407 | 3.75 | 4 | import numpy as np
import math
'''
@author: FreeMind
@version: 1.1
Created on 2014/2/26
This is a basic implementation of the ID3 algorithm.
'''
class DTree_ID3:
def __init__(self,dataSet,featureSet):
#Retrieve the class list
self.classList = set([sample[-1] for sample in dataSet])
if ((le... |
ac697cfc455c987e41da0e89fc33de44e13b7d28 | Raunaka/guvi | /ideone_JwxIRn.py | 201 | 3.71875 | 4 | x = int(input())
y = int(input())
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
hcf = i
print( hcf)
|
e8f2b3ddb028397e083bad8369be3589e3e73405 | Raunaka/guvi | /palin.py | 98 | 3.546875 | 4 | a=input()
a=list(a)
if a==a[::-1]:
while a==a[::-1]:
a[-1]=""
q=""
for i in a:
q=q+i
print(q)
|
63a9898b547389e60826521a27a60a8ca4c6d70b | rsirs/foobar | /dont_mind_map.py | 2,368 | 3.78125 | 4 | def answer(subway):
dest = [{},{},{}]
max_route_length = len(subway)
import itertools
directions = '01234'
for closed_station in range(-1, len(subway)):
for path_length in range(2,6):
current_directions =directions[:len(subway[0])]
for route in itertools.product(curre... |
aebfbbd797d10209adeca8e2005940939f7198f6 | bugmany/nlp_demo | /src/Basic_knowledge/Manual_implementation_neural_network/简单感知器.py | 1,481 | 4.03125 | 4 |
'''
1. 处理单个输入
2. 处理2分类
'''
class Perceptron(object):
'''
初始化参数lr(用于调整训练步长,即 learning),iterations(迭代次数),权重w 与 bias 偏执
'''
def __init__(self,eta=0.01,iterations=10):
self.lr = eta
self.iterations = iterations
self.w = 0.0
self.bias = 0.0
#'''
#公式:
#Δw = lr * (y - y') ... |
1e598b5c0e8208f88db6eda0aecddbc0f1b05b2c | Quyxor/project_euler | /problem_002/fibonacci.py | 526 | 3.9375 | 4 | '''
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
'''
... |
e4b6dd203d9d6cbb9a0da72e15f3e382cc765305 | jameslamb/doppel-cli | /doppel/PackageCollection.py | 3,609 | 3.59375 | 4 | """
``PackageCollection`` implements methods for comparing
a list of multiple ``PackageAPI`` objects.
"""
from typing import Dict, List, Set
from doppel.PackageAPI import PackageAPI
class PackageCollection:
"""
Create a collection of multiple ``PackageAPI`` objects.
This class contains access methods so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.