blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
efb1dd3c0a9998d6ea84032a7c53785b3d85dfaf | Naga-kalyan/Competitive_Programming | /HackerRank/ValidatingPhoneNumber/ValPhNo.py | 169 | 3.6875 | 4 | import re
a=int(input())
for i in range(a):
b=input()
z=re.match('[7-9]\d{9}',b)
if (z) and (len(b)==10):
print('YES')
else:
print('NO')
|
656d556e321a5db8c22474c509c9f433039cbd85 | jiangchb/StructuralVariantAnalysis | /everythingSV/filterAnnotatedSVs.py | 2,945 | 3.53125 | 4 | import sys
import re
import argparse
def parse_args():
"""
Parse command-line arguments
Returns
----
Parser argument namespace
"""
parser = argparse.ArgumentParser(
description="This script filters a set of annotated SVs output from everythingSV.py based on overla... |
005324a5eec9892ad682b02799796d18058da6b0 | LeoChen21/01_line | /draw.py | 1,657 | 4.25 | 4 | from display import *
import math
def draw_line( x0, y0, x1, y1, screen, color ):
#makes it so the line is always drawn from left to right regardless of which x is bigger
if x1 < x0:
x, y, x1, y1 = int(x1), int(y1), int(x0), int(y0)
else:
x, y, x1, y1 = int(x0), int(y0), int(x1), int(y1)
... |
92f8161a6bf4e2908e0d0546a2aa88be4b4bc69f | derianpt/python-code | /codewars/7kyu/square_digits.py | 478 | 4.125 | 4 | def square_digits(num):
# use a string to build answer
square_digits_string = ""
# extract digits as per normal using the mod 10 approach, until num becomes 0
while num > 0:
least_significant_digit = num % 10
# square digit and prepend it to string
square_digits_string = "{}".fo... |
953e49fa0dbb60e9709b587c7a600f673c9505c7 | derianpt/python-code | /codewars/7kyu/middle_character.py | 188 | 3.640625 | 4 | def get_middle(s):
word_length = len(s)
mid_index = (word_length-1) // 2
if word_length % 2 == 0:
return s[mid_index:mid_index+2]
else:
return s[mid_index]
|
cb5bc3312d2995d02a6b57a6ca4ec852036ba49b | derianpt/python-code | /udemy_python_for_absolute_beginners/8-loops/more_for_loops.py | 3,096 | 4.71875 | 5 | """
1.Iterating through a string using range() and a for loop
a.create a string and assign it to a variable
b.use a for loop without a range() to iterate through and print the contents of the string from step 1.a.
c.use a for loop with a range() to iterate through and print the contents of the string from step 1.a.
"""... |
81c493c8aa832ee40bed4852f02e1ece08b872d9 | kentarospin98/pset6 | /crack.py | 1,086 | 3.578125 | 4 | from crypt import crypt
import sys
def main():
if len(sys.argv) != 2:
print("Usage : crack.py [hash]")
exit(1)
else:
crack(sys.argv[1], sys.argv[1][:2])
def crack(chash, csalt):
for l in range(1, 5):
cpass = []
last = []
for x in range(l): cpass.append(... |
0f4f445627580da2f98ff32c8c3250c2604a0a4a | AENaucano/MyDarklands | /reader_cty.py | 7,583 | 3.546875 | 4 | from collections import OrderedDict
from utils import bread, sread
cityTypes = ('Free City', 'Ruled City', 'Capital')
def readData(dlPath):
fname = dlPath + '/darkland.cty'
data = map(ord, open(fname).read())
dataLen = len(data)
#print fname, dataLen, 'B'
pos = 0
cnt = data[pos]
#print c... |
e2fef1744a06e6c2a1b9b7b6aac9c4d2655c3c4b | stakodiak/pystats | /stats.py | 1,868 | 3.765625 | 4 | # stats.py - Statistics utility module.
import math
def main ():
s = Series ([1, 2, 3])
print s.mean
# Functions:
def avg (series):
return mean (series)
def mean (series):
m = sum (series) / float (len (series))
return m
def variance (series):
m = mean (series)
v = sum ([(s - m)**2 for ... |
049c42970407bfbf3837a0926d19ba088d391e02 | pbhusari/idtechstuff | /demos_pranav_bhusari/game.py | 4,246 | 3.921875 | 4 | import pygame
from math import pi, sin, cos, radians, degrees
pygame.init()
def cross(x1, y1, x2, y2):
return x1*y2 - y1*x2
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
size = [100, 100]
#player position
player_x= 50
player_y = 50
thet... |
5412471429fc03b1c5b900837e927bac1be2fbe1 | adevesa/Retos-Euler | /reto euler 14.py | 1,496 | 4.0625 | 4 | ##Longest Collatz sequence
##Problem 14
##The following iterative sequence is defined for the set of positive integers:
##
##n → n/2 (n is even)
##n → 3n + 1 (n is odd)
##
##Using the rule above and starting with 13, we generate the following sequence:
##
##13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
##It can be seen t... |
b4e1a8ca3976cfef4a6fe32c90ecb431e18a91e7 | adevesa/Retos-Euler | /reto euler 5.py | 1,115 | 3.65625 | 4 | ##Smallest multiple
##Problem 5
##2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
##What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def problema2():
producto = 1
for i in todos_los_primos_de(20):
... |
1f0d775fe3320aefbeaa8a93d75fb8c9618884f7 | adevesa/Retos-Euler | /reto euler 3.py | 1,091 | 3.546875 | 4 | ##Largest prime factor
##Problem 3
##The prime factors of 13195 are 5, 7, 13 and 29.
##What is the largest prime factor of the number 600851475143 ?
def factorizar_nro(nro,primox):
if nro/primox == 1: return primox
if nro % primox == 0:
return factorizar_nro(nro/primox, primox)
else:
retu... |
a075e4c57ed059b7a438791e687cc1b481cea535 | Krishnakumar-c/HackerRank | /Python/factorial.py | 865 | 4.40625 | 4 | #Task
#Write a factorial function that takes a positive integer, as a parameter and prints the result of ( factorial).
#Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of .
#Input Format
#A single integer, (the argument to pass to factorial)... |
10d9126fd647583532ec7faf3688d2204873fa06 | fuzzyblankets/Advent_2019 | /Day6/Part1.py | 1,715 | 3.890625 | 4 | """
https://adventofcode.com/2019/day/6
"""
import nested_lookup
from collections import ChainMap
def main(puzzle_input):
orbit_map = {}
orbit_map = puzzle_split(puzzle_input, orbit_map)
total_orbits = 0
for orbit_key in orbit_map.keys():
for orbit in orbit_map[orbit_key]:
total_or... |
03f4c6bf52b96cde141a409add19e481a652156e | DonCebsi/codechallenges | /AoC/2020/Day3/AoC_Day3.py | 298 | 3.671875 | 4 | if __name__ == '__main__':
# get input
entries = [line.strip() for line in open("input_1.txt", "r")]
# traverse
position = 0
count = 0
for i in entries:
if i[position] == "#":
count += 1
position = (position+3) % len(entries[0])
print(count)
|
2995d6e38ce623cf9a649cfc720f7a5b74ef88ce | clulab/releases | /lrec2020-pat/utils.py | 1,990 | 3.5625 | 4 | import re
import math
def normalize(word, to_lower = True):
"""returns a normalized version of the given word"""
if re.fullmatch(r'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?', word):
return '<num>'
elif to_lower:
return word.lower()
else:
return word
def chunker(sequence, size)... |
5878a3de0abd2fe817706af73a71d76065852e1c | shireesha-reddy/hp | /OneDrive/PROSTACK/FRONT END/range.py | 200 | 4.09375 | 4 | ''' for x in range (1,5):
print("A" * 3)
for x in range (1,10):
print("A" * 3) '''
for x in range (5):
print("5" * x)
for x in range (5):
print( " A " * x)
|
d546877044e699f3cf7c25d899721a4ee6db6495 | paulovictorfds/atividades-intro | /snake/prova.py | 788 | 3.671875 | 4 | import random
perguntas = [
("Quanto é 5 + 3? ", 8),
("Quanto é a raiz quadrada de 16? ", 4),
("Quanto é 3 * 3? ", 9),
("Quano é 28 - 13? ", 15),
("Quanto é 20 / 4? ", 5),
("Quanto é 5 ^ 3? ", 125)
]
respostas = []
perguntasAleatorias = random.choices(perguntas, k = 3)
for x in range(len(pergu... |
7881f307eb9071b9e1a9980601a76de1743f47d1 | hugoyervides/pypl-meter-api | /calculateDistances.py | 4,228 | 3.6875 | 4 | #Script para calcular las cordenadas de los dispositivos dentro del plano con la senal
from classes import Point
import math
import random
#Function de trilateration
def trilateration(point1,r1,point2,r2,point3,r3):
A = 2*point2.x - 2*point1.x
B = 2*point2.y - 2*point1.y
C = r1**2 - r2**2 - point1.x**2 + p... |
987b62ba44e7ef7e85b02f437329cef808f2f6d5 | KrisAsante/Unit-8-03 | /car.py | 2,883 | 4.03125 | 4 | # Created by: Chris Asante
# Created on: 7-May-2019
# Created for: ICS3U
# Unit 8-03
# This main program will create a car object
class Car:
def __init__(self):
#private fields
self.__license_plate_number = "TY4SDF3"
self.__colour = "orange"
self.__number_... |
ec33abe916b8cc2b0fe5861174c922b2ca82be60 | juhisb/Algorithms | /Course 3/huffman.py | 987 | 3.5 | 4 | import heapq
from collections import defaultdict
def encode(weight):
heap = [[w, [symbol, '']] for symbol, w in weight.items()]
heapq.heapify(heap)
while len(heap) > 1:
lo = heapq.heappop(heap)
hi = heapq.heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair... |
32be30da4c60bb0340bb70f7fcba261d8e03c988 | amuraddd/Classification | /KNN and Perceptron Classifiers/perceptron.py | 2,984 | 3.6875 | 4 | import numpy as np
import pandas as pd
def perceptron(x, y, decay_rate=0.1):
"""
The function takes as input:
x: data
y: class labels for the data
Return:
w: perceptron weight vector
"""
w = np.ones(x.shape[1]+1)
instances = x.shape[0]
for j in range(100): #outer... |
634acbc7e402b1ba7b03f7d50daefc7644c8ddf7 | kalishguru/Python | /dictdepth.py | 371 | 3.921875 | 4 | dictval = {"key 1": 1,"key 2":{ "key 3": 1, "key 4": { "key 5": 4 }}}
def recursion_depth(dict_, depth):
for k in dict_:
print "{0} = depth:{2}".format(k, dict_[k], depth)
if type(dict_[k]) == dict:
actual_depth = recursion_depth(dict_[k], depth+1)
if actual_depth > depth: depth += 1
... |
a3680e4de07bf8493e1bb5de3cefa7db2c5fac7e | s4r4h/my_simple_project | /jenis_akar.py | 928 | 4.125 | 4 | import math
print("Selamat Datang! Ini adalah program untuk mengetahui jenis akar persamaan kuadrat dan nilai akar-akarnya (jika merupakan akar nyata)")
a= int(input("Masukkan nilai a: "))
b= int(input("Masukkan nilai b: "))
c= int(input("Masukkan nilai c: "))
p= input("Masukkan variabelnya: ")
print("Maka persamaanny... |
23e6149f2fb52665015e0f7554d11df7c51a9d3f | RangerHuyijun/Python-Crash-Course | /VSCode_work/chapter3/chapter3_3_5.py | 1,014 | 3.828125 | 4 | # 创建列表
invited_persons = ['dad','mother','sister','cui ping']
# 打印邀请消息
print("Dear " + invited_persons[0].title() + "," + " can you have dinner with me?")
print("\nDear " + invited_persons[1].title() + "," + " can you have dinner with me?")
print("\nDear " + invited_persons[2].title() + "," + " can you have dinner wit... |
e6722583e79395a0b0cd8cc51c1447cfe4bdf161 | RangerHuyijun/Python-Crash-Course | /VSCode_work/chapter6/chapter6_6_11.py | 584 | 3.984375 | 4 | # 创建字典
cities = {
'beijing': {
'country': 'china',
'population': '1100000',
'fact': 'capital',
},
'shanghai': {
'country': 'china',
'population': '122434',
'fact': 'financial',
},
'hangzhou': {
'country': 'china',
... |
a930e79bc1457b785cff15c625d37383281fc492 | otoukebri/competitive-programming | /basic_algorithms/Knuth-Morris-Pratt.py | 1,068 | 3.96875 | 4 | # https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
def makeTable(word):
'''
makes jump-back table
i.e. for word 'abcabc' and search is 'abcabcabc'
we need to return 3 steps back after matching 6 letters
'''
table = [0] * (len(word) + 1)
for i in range(... |
0df45b1223510016685dc3cca6783c18567fb4dc | IkonenkoDanil/cs102 | /homework2/Sudoku.py | 7,758 | 3.8125 | 4 | import random
from typing import Tuple, List, Set, Optional
def read_sudoku(filename: str) -> List[List[str]]:
""" Прочитать Судоку из указанного файла """
digits = [c for c in open(filename).read() if c in '123456789.']
grid = group(digits, 9)
return grid
def display(grid: List[List[str]... |
68127c37ee0824acd2f78bb4127fd7e668c25831 | Jasonon/python_learning | /Python_Advanced/01Iterator.py | 1,371 | 4.0625 | 4 | # 1、迭代器的介绍
a = iter([1,2,3])
print(a)
try:
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
except StopIteration:
print('遍历完毕')
# # 一、无限迭代器
# 2、迭代器模块itertools
# itertools包自带三个可以无限迭代的迭代器
print('①count(初值=0,步长=1)')
from itertools import count
for i in count(10,2):
if i > 20:
... |
b4c3a78f1cd36460a0ebc8510e24fe7ae46cd019 | KaprianZ/IFPI | /Python/Atividades - DOT/Ativ. Sem. 02/Q12 - Somatória.py | 193 | 3.90625 | 4 | def somatorio(n):
s = 0
for i in range(1, n+1):
s += i
return s
n = int(input("Digite um número inteiro e positivo: "))
print(f"A somatória de {n} é {somatorio(n)}.")
|
a980fe8a26d1abbfcec6f021f15fb24577aa1ec1 | liyjie00/Morris_Game_AI | /MiniMaxGameBlack.py | 1,158 | 4.09375 | 4 | """
Generate a move for black in the Midgame and Endgame phases
by using MINIMAX algorithm
@author: Yuanjie Li, yxl174431@utdallas.edu
"""
import sys
import MorrisGame
from MiniMaxGame import MaxMinMidEnd, MinMaxMidEnd
def MiniMaxGameBlack(root, depth):
""" use MINIMAX algorithm to generate a move for black """... |
28e506775d2b0b35e95fc10fe18142d517fc1dc0 | jsoto3000/js_udacity_Intro_to_Python | /pick_odd.py | 552 | 4.25 | 4 | import numpy as np
# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).
# Afterwards use Boolean indexing to pick out only the odd numbers in the array
# Create a 5 x 5 ndarray with consecutive integers from 1 to 25 (inclusive).
X = np.arange(1, 26).reshape(5, 5)
print()
print('Origi... |
ff3c271427301d6ea6a92116d07d9e062d560656 | jsoto3000/js_udacity_Intro_to_Python | /expquiz.py | 94 | 3.546875 | 4 | # print e to the power of 3 using the math module
import math
e_3 = math.exp(3)
print(e_3)
|
cc73436fbbb085fc1f114b6033b16433d2eb8046 | jsoto3000/js_udacity_Intro_to_Python | /udacity_python_notes.py | 285,748 | 4.59375 | 5 | # LESSON 01
# Introduction
# Programming In Python
# As you learn Python throughout this course, there are a few things you should
# keep in mind.
# 1. Python is case sensitive.
# 2. Spacing is important.
# 3. Use error messages to help you learn.
# Lesson 2: Data Types and Operators
# 1. Data Types: Integers, Float... |
930195c7dfc4d9a4f62351cdf36e99e718dc2460 | jsoto3000/js_udacity_Intro_to_Python | /pandas_intro.py | 740 | 4.59375 | 5 | # We import Pandas as pd into Python
import pandas as pd
# We create a Pandas Series that stores a grocery list
groceries = pd.Series(data = [30, 6, 'Yes', 'No'], index = ['eggs', 'apples', 'milk', 'bread'])
# We print some information about Groceries
print('Groceries has shape:', groceries.shape)
print('Groceries ha... |
ef5f41d52b3cf7c3f667b6cf9b844db0565aa172 | jsoto3000/js_udacity_Intro_to_Python | /finally_clause.py | 980 | 4.1875 | 4 | # why python needs finally clause
# code below will continue to run even when press ctrl-c
while True:
try:
x = int(input('Enter a number: '))
break
except :
print('That\'s not a valid number!')
finally:
print('\nAttempted Input\n')
# code below will interrupt when press c... |
6afb1cb51fc6681dd2a0661166bbc210198ab45b | l-anastasia/study | /19_counting_vowels.py | 619 | 4.1875 | 4 | # create a function, that takes a string
# and returns how many vowels in it
def counting_vowels(string):
result = 0
for letter in string.lower():
if letter in 'aeiou':
result += 1
return result
def counting_vowels_comprehension(string):
return sum([1 for letter in s... |
7784d7353f3edefe1952167a75be43b7f4c77d49 | Denali101/CCC-21-Junior | /J3_Secret_Instructions.py | 901 | 4.34375 | 4 | previous = "" # For when the first two nums = 0
while True:
nums = input() # Has to be string because there can be 0 in the beginning
if nums == "99999":
break
choice = int(nums[0]) + int(nums[1]) # Adds the first two nums of the input
direction = ""
if choice == 0:
directi... |
580583e64c62047907751fc2bcec0c8004bbf5e5 | oshlern/MiscellaneousWork | /physics_sym.py | 934 | 3.625 | 4 | from abc import ABC
class Vec:
def __init__(self, *args, shape=None):
if len(args) == 0:
if shape == None:
raise Exception("Need coords or shape to initialize")
if len(args) == 1:
if type(args[0]) == list:
args = args[0]
s... |
53cc3a22798598008be87c72cc7b9aed3f4acc18 | zobac/adventOfCode | /advent.py | 884 | 3.515625 | 4 | def getPaper(l, w, h):
return (2*((l*w) + (w*h) + (l*h)))+(smallestPaper(l, w, h))
def smallestPaper(l, w, h):
nums = [l, w, h]
largest = max(nums)
nums.remove(largest)
return (nums[0] * nums[1])
def getLineTotal(line):
l, w, h = line.split('x')
l = int(l)
w = int(w)
h = int(h.str... |
0520a546907ff3bde55624db79be876145a0503e | silviasoares/Python-Tests- | /Lista 01/exer01.py | 353 | 3.6875 | 4 | #coding: utf-8
def cacular_segundo(dias, horas, minutos, segundos):
print(segundos + (minutos * 60) + (horas * (60 * 60)) + (dias * (24 * (60 * 60))))
dias = input("Digite os dias: ")
horas = input("Digite os horas: ")
minutos = input("Digite os minutos: ")
segundos = input("Digite os segundos: ")
cacular_segundo(di... |
d68f5bc03538782037847b22982f37c35f3804cd | AlexCecconi/Aulas_py | /aula_1/exercicio_3.py | 344 | 3.734375 | 4 |
exit()
# ex2
idade = input('Digite sua idade: ')
letras = '1234567890'
string = ''
for ler in idade:
if ler in letras:
string += ler
print(string)
exit()
# ex1
idade = input('Digite sua idade: ')
letras = '1234567890'
for ler in idade:
if ler not in letras:
print('Jumento')
exit()
else:
... |
2e5ef0b7a8c14dee1f573f54c64e80e2ff0412a4 | brunomatt/ProjectEulerNum12 | /ProjectEulerNum12.py | 1,044 | 3.71875 | 4 | #The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
#1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,... |
c471eda76ce0dfb52f684c933bf49b71dd186667 | siavashkavousi/AI-course | /project1/solver/solver.py | 508 | 3.546875 | 4 | from abc import ABCMeta, abstractmethod
from problem.problem import Problem
class Solver(object):
__metaclass__ = ABCMeta
def __init__(self, problem: Problem, tree_search=False):
self.problem = problem
self.tree_search = tree_search
@abstractmethod
def solve(self):
pass
... |
d8279b02e3bbda9076c43f64efb8b0923f8f3c8b | siavashkavousi/AI-course | /project1/solver/dfs.py | 2,496 | 3.53125 | 4 | from problem.problem import Problem
from .solver import Solver
import math
class Dfs(Solver):
def __init__(self, problem: Problem, tree_search=False, is_iterative=False, depth_limit=math.inf):
super().__init__(problem, tree_search)
self.depth_limit = depth_limit
self.is_iterative = is_iter... |
c6bfb45f3a80ed61a5e1a44b6ae37d07e6d03a34 | siavashkavousi/AI-course | /project1/solver/bfs.py | 1,312 | 3.671875 | 4 | from collections import deque
from problem.problem import Problem
from .solver import Solver
class Bfs(Solver):
def __init__(self, problem: Problem, tree_search=False):
super().__init__(problem, tree_search)
self.frontier = deque([problem.init_node])
self.explored = set()
self.mem_... |
c5a21bb6333d27ce8aa695a5c7d2de85ce92187b | SGiuri/isbn-verifier | /isbn_verifier.py | 271 | 3.53125 | 4 | def is_valid(isbn):
# 3-598-21508-8
isbn_cypre = []
for number in isbn:
if number.isdecimal():
isbn_cypre.append(int(number))
if isbn[-1] == "X":
isbn_cypre.append((10))
print(isbn_cypre)
pass
is_valid("3-598-21508-8") |
392af7256d8b4b134c4c61405568a205edac53c6 | CraftSpider/CraftBin | /Python/adventofcode2017/day4.py | 176 | 3.546875 | 4 |
with open("input.txt") as file:
phrases = [line for line in file]
valid = list(filter(lambda x: len(set(x.split())) == len(list(x.split())), phrases))
print(len(valid))
|
41fd8cd042799cf36cdaf4da5947ff161434e390 | CraftSpider/CraftBin | /Python/smb2rel/ppc_decomp.py | 407 | 3.828125 | 4 | """
Take in bytes objects and decode them as PowerPC instructions
"""
def decode(data):
for byte in data:
print(byte)
def bits(bytes, reverse=True):
if reverse:
for byte in reversed(bytes):
for i in range(8):
yield (byte << i) & 1
else:
for byte in... |
899b6d427b2ef625a8a7cf37d3b728c7613664f2 | CraftSpider/CraftBin | /Python/adventofcode2017/day1.py | 400 | 3.625 | 4 | """
Day 1
Author: Rune Tynan
"""
result = 0
prev = ""
instr = input("> ")
for i in instr:
if i == prev:
result += int(i)
prev = i
if instr[0] == instr[-1]:
result += int(instr[0])
print("Result: " + str(result))
result = 0
length = len(instr)
for i, c in enumerate(instr):
if c == instr... |
3fd6aac0777ed883c00efe6ca3f95d01d2a9e8e5 | CraftSpider/CraftBin | /Python/interpreters/calculator.py | 7,619 | 3.90625 | 4 | """
Acts like a normal calculator, just much less efficient.
An excuse to practice stack execution and interpreting input.
Author: CraftSpider
"""
import utils.interp as interp
from calc.loader import *
variables = {
'pi': '3.14159265',
'e': '2.71828182',
}
class Calculator(interp.Interpreter)... |
e6c49de16c5b5c45cf62837b8351174d59592408 | yuli5/python3.1 | /Actividad5/ejercicio22.py | 337 | 4 | 4 | #ejercicio 22
#convertir una distancia en metros a pies y pulgadas
PIES = 3.28
PULGADAS = 39.37
metros = 0
metros = int(input("ingrese cuantos metros desea convertir:."))
pies = metros * PIES
pulgadas = metros * PULGADAS
print("la distancia en pies es de:.{}".format(pies))
print("la distancia en pulgadas es de:.{}".f... |
fb72f466182ca5b8473be3f5f578d2573b46443d | yuli5/python3.1 | /Actividad5/ejercicio7.py | 660 | 3.8125 | 4 | #en un hospital exsiten 3 areas: urgencias, pediatria y traumatologia. el
#presupuesto anual del hospital se reparte de la siguiente manera:
#urgencias 37%
#pediatria 42%
#traumatologia 21
urgencias = 0
pediatria = 0
traumatologia = 0
presupuesto = 0
presupuesto = float(input("ingrese presupuesto anual para el hospit... |
7fe7253758b4b4983f08586f21df6c12a25ba317 | yuli5/python3.1 | /Actividad5/ejercicio12.py | 269 | 3.65625 | 4 | #calcular el nuevo salario de un empelado si se le descuenta el 20% de su
#salario actual.
salario = 0
Descuento = 0
salario = float(input("Ingrese salario actual:."))
Descuento = salario * 0.20
print("Salario total menos el descuento del 20%:.",(salario-Descuento))
|
05ac131ee62edf35e4594a3e7e20251c5b092e33 | Tolo5star/Data-Structures-with-Python | /linked list.py | 1,049 | 4.0625 | 4 | class node:
def __init__(self):
self.data=None
self.next=None
def setdata(self,d):
self.data=d
def setnext(self,n):
self.next=n
def disp(self):
return self.data
'''
s=node()
s1=node()
s2=node()
s.setdata(5)
s1.setdata(2)
s2.setdata(0)
s.setn... |
1edb0d3d71d56b03bde5213beb60c2e67e7f1547 | Ezhil-Language-Foundation/open-tamil | /tamil/quantum.py | 1,664 | 3.671875 | 4 | # (C) 2021 Muthiah Annamalai
# This file is part of open-tamil project
from itertools import product
from .utf8 import get_letters_elementary, shorten
def get_superposition_representation(word, raw=False):
"""
Treat word as a Vowel + Consonant representation and compute Kronecker product:
e.g.
... |
a692b43c9b7adca08da096da267d5f6e09d078b8 | Ezhil-Language-Foundation/open-tamil | /transliterate/algorithm.py | 9,048 | 3.875 | 4 | ## -*- coding: utf-8 -*-
# (C) 2013 Muthiah Annamalai
#
# Implementation of transliteration algorithm flavors
# and later used in TamilKaruvi (2007) by your's truly.
#
import tamil
def reverse_transliteration_table(table_in):
"""
transliteration table from Tamil -> English.
"""
table_ou... |
d172a2a3cdaf67a33db9e3ac99e67c611312d21e | Ruslan5252/algorithms | /algorithms/Бинарный поиск.py | 575 | 3.75 | 4 | nums = [12,56,876,1234,876,123,54,3,5]
print(nums)
nums.sort()
print(nums)
search_for = int(input("Какое число ищем ? >>"))
lowest = 0
highest = len(nums)-1
index = None
while (lowest<=highest) and (index is None):
mid = (lowest+highest)//2
if nums[mid] == search_for:
index = mid
else:
i... |
13c39ddab19fa764655a4259cc2c0f1b14548939 | devopsuser6251/Learning-the-Python-3.X | /basicpy.py | 535 | 4.03125 | 4 | print('Python is easy')
#This is a small python script
'''
Multi line comment
'''
a=10
k=20.23
s="Done"
a=13
b=100
c=-66
print(a,b,c)
print(type(k))
d=3+5j
print(type(d))
e=0B1010
print(e)
print(type(e))
f=0XFF
print(f,type(f))
g=True
print(type(g))
print(9>10)
print(bool(0))
print(bool(1))
print(int(k))
i=float("22.5"... |
dd84cb4fafdc9c4132ff8c21bf78ec5cad9dbb93 | TheDarktor/criptografia_py | /APS 2SEMESTRE PAULISTA - MURILLO MARIANO (LIDER).py | 3,657 | 3.859375 | 4 | # A criptografia utilizada é a ROT 13, onde cada letra é substituída por uma letra que esteja 13 casas a frente
import os
print('-'*70)
print('Escolha uma das funções:')
print('(1) - Criptografar\n(2) - Descriptografar ') # Usúario decide se o programa vai criptografar ou descriptografar
print('')
funcao = int(in... |
d7215c00e2344ea3cf8fb4778ae17e012638592d | advertronics/python-codes | /understanding-modulo.py | 943 | 4.0625 | 4 | """making sense of modulo in python. When I started out, I used to struggle with understanding this operator, especially when it came to negative(-) numbers.
After a couple of research I discovered a trick which I am sharing here to save another person the trouble"""
"""
modulo(%) is the remainder when one number is di... |
e3c8a331012bf6b3ad8cbd4fbe715aeca29cf21b | bliakher/20_21_malgym_7AG | /kod_z_hodin/septima_29_3.py | 1,788 | 3.53125 | 4 |
a = 3
if a > 0:
a = a - 1
else:
a = a + 1
a = 3
a = a - 1
a -= 1
a += 1
a /= 2
a *= 3
# absolutni hodnota
# program nacte cislo, spocita abs. hodnotu a vypise vysledek
"""
a = int(input())
if a < 0:
#result = a - 2*a
result = -a
else: # a >= 0
result = a
print(result)
# typ trojuhelnik... |
fa065120a88dacc312058f5e64b489569e786e05 | bliakher/20_21_malgym_7AG | /kod_z_hodin/septima_8_3.py | 595 | 4.0625 | 4 | """
x = 5
y = 7
z = x + y
print(z)
print(z * 2)
print(x, y, x+y)
print("Vysledek je:", x + y)
"""
"""
cela cisla - integers - int
slova - retezce - strings - str
"3" int("3") -> 3
str(456) -> "456"
"""
"""
a = "ab"
b = "b"
c = a + b # konkatenace
d = a * 3
print(c, d)
"""
number = int(input("Write a number")) #... |
8ad7354a05519ceca81ba59fd692fcd4cdfd575a | bliakher/20_21_malgym_7AG | /skupina_s2/kod_z_hodin/septima__14_12.py | 1,366 | 3.640625 | 4 |
cisla = [1, 2, 3, 5, 4, 12, 5]
# prvek na indexu 3 - cisla[3]
# vypsat suda cisla z pole
#1
#2
#3
"""
print(cisla)
for cislo in cisla:
if cislo % 2 == 0:
print(cislo)
for index in range(6):
prvek = cisla[index]
if prvek % 2 == 0:
print(prvek)
a = 4
if a % 2 == 0:
print(a)
"""
cis... |
e8185f8140ba9864e676230fce4a099e7c19fc76 | bliakher/20_21_malgym_7AG | /skupina_s2/zadani/14_hodina_reseni.py | 1,314 | 3.765625 | 4 | # pole obecne --------------------------------------------
#pole je datová struktura, do které můžeme uložit prvky
#pole = []
#přidání prvku: "název pole".append("prvek")
#přistoupení k prvku na indexu: "název pole"["index"]
#délka pole: len("název pole")
#count, index, min, max...funkce prochazi pole
# zvetsit ka... |
7dff09bac5d65ed986c641c4a4e0ddb6ecc8b152 | weilin2018/CS_ML_DL_Courses | /Deep_Learning_A_Z_Hands_On_ANN_(Udemy)/a2_CNN/cnn_building.py | 1,505 | 3.59375 | 4 |
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
# initiallize classifier
clf = Sequential()
# step 1: convolution
# input_shape 3,256,256 takes too long, here 3 is 3 color channels.
clf.add(Convolution2D... |
f8929887750569f4654a2c42f6e591446fc95360 | weilin2018/CS_ML_DL_Courses | /ML_A_Z_Hands_On_Python_And_R_(Udemy)/dev/dev_py/bp_poly_regress.py | 1,670 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Author : Bhishan Poudel; Physics PhD Student, Ohio University
# Date : May 09, 2017
# Last update :
#
# Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mp
# Get the data Position_Salaries.csv
dataset =... |
12c4293ce81fc352872acd84ca1e7ef1aec5390c | joestarhu/jhulearn | /机器学习/linear_mode/linear_regression.py | 3,598 | 3.5 | 4 | """
Author:Jian.Hu
UpdateInfo:
---2020.03.23:-------------------------------------------
线性回归的实现
实现点:
1) 优化算法分别使用了Normal Equation和Gradient Descent
2) 代价函数使用的是MSE
3) 求导用了2种方式
- 直接求导,用导数来计算
- 数值微分求导
4) 对于梯度下降算法的迭代次数做了限制
- 所有的更新值都小于1e-7时候,认为已经收敛,结束下降
- 任意一个更新至大于1e7时候,认为学习率过大,不再进行迭代
"""
import numpy... |
812e39d535cfecadbd6b5105bf918899c2635a85 | Ratnakarn5/myrepo | /MyBlog/posts/multiarg.py | 771 | 4.03125 | 4 | class Duck():
# USING simple assigning of the indiviual value
# def __init__(self, color='white'):
# self._color = color #_color make a local variable for our understaning
# another way using constructor with keyword arguement
# def __init__(self, **kwargs):
# self._color=kwargs.get('color', 'white')
# best w... |
a345feb8c65bcfe561f2ddc4eddecfc32ce88a3e | KomissarovAliaskar/task6_part3_true | /tusk1.py | 289 | 3.78125 | 4 | str = input()
verh = 0
niz = 0
for i in range(0, len(str)):
if str[i].isupper():
verh = verh + 1
elif str[i].islower():
niz = niz + 1
print("Заглавных букв: ", verh * 100 / len(str) , '%')
print("Прописных букв", niz * 100 / len(str),'%')
|
bc0bd4eab411522610ea7b0ecde47de73e40fe51 | laurelmachak/pythonProjects | /rectPracticeViolet.py | 625 | 3.5 | 4 | import pygame
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (246, 255, 0)
BLUE = (0, 0, 255)
ORANGE = (255, 106, 0)
VIOLET = (128, 80, 175)
GREEN = (26, 114, 35)
PINK = (229, 91, 227)
color1 = (255, 0, 255)
pygame.init()
size = [500, 500]
screen = pygame.display.set_mode(size)
done = False
cloc... |
2e16c657561a83f05d12254a7ce515f28f556542 | laurelmachak/pythonProjects | /game01.py | 607 | 3.515625 | 4 | import pygame
from math import pi
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
BLUE = ( 0, 0, 255)
pygame.init()
size = (600,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Noche of Stars')
done = False
clock = pygame.time.Clock()
... |
afcc9bc4722c1f21819d1170d4755e20d493b15e | Piotr-Pietruszka/Numerical-Methods | /4_Newton_Raphson/Metoda_graficzna.py | 585 | 3.9375 | 4 | """
y = -x**2 - x + 3
y = x**2 + x*y
y = -x**2 - x +3
y = (x**2)/(1-x)
Metoda graficzna
# Układ ma 3 rozwiazania (metoda graficzna, więc w przyblliżeniu):
# x = -1.9, y = 1.25
# x = 0.7, y = 1.75
# x = 2.2, y = -4
"""
import numpy as np
from matplotlib import pyplot as plt
x_1 = np.a... |
f3633c4e8af369e4c12b05809315dbc86528a5a9 | Piotr-Pietruszka/Numerical-Methods | /1_taylor/taylor_tabela.py | 989 | 3.546875 | 4 | """
sinh x, tabela dla różnych n, gdzie n to liczba wyrazow rozwiniecia w szereg Taylora
"""
import numpy as np
import math
from matplotlib import pyplot as plt
from scipy.special import factorial
def rozw (n, x):
counter = np.arange(0, n, 1) # licznik
den = np.arange(0, n, 1) # mianownik
c... |
2045fccf3371b1df5060f3b1653f9ccac01b62bc | lingqinx/leedcode | /array/119.py | 400 | 3.53125 | 4 | #!/usr/bin/python
#coding=utf-8
class Solution(object):
def genRow(self, rowIndex):
"""
:type numRows: int
:rtype: List[List[int]]
"""
List = [[1]]
for x in range(1,rowIndex+1):
List += [map(lambda x,y: x+y, List[-1] + [0], [0] + List[-1])]
return List[r... |
79a7fa7c4d7bdde303072a1237f0bc045b4dcedd | lingqinx/leedcode | /tree/112.py | 1,085 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
#it... |
1898eb091a4785e4b1c447b190210f80d88fdd21 | FPDPanda/Challenges | /Beginner Challenge 2.py | 629 | 4.3125 | 4 | print("This program tests a number to check if it is PRIME\n\n")
c = 0
while True:
number = input("Please input the number you would like to test: ")
try:
number = int(number)
except ValueError:
print("Please input a valid number.")
continue
if number < 0:
pri... |
2a4fdc8bb84e16a5c39aa6b025ef42e32e85f69d | macostea/info-labs | /An 1/Sem 1/FP/Lab 2-4/Bank Account Management (modular)/utils/check.py | 1,112 | 4.0625 | 4 | '''
Created on Oct 26, 2012
@author: Mihai Costea
The check module groups together all the validation methods in the app
'''
from types import ListType, StringType, IntType
def check_parameter(parameter, expected_type):
"""
Checks if the parameters are of the expected types
parameter is the parameter to ... |
585067fef1ba4dad79c7a8c06a4af1441c981bda | macostea/info-labs | /An 1/Sem 1/FP/Simulare/Domain/Rent.py | 993 | 3.75 | 4 | '''
Created on Jan 16, 2013
@author: mihai
'''
class Rent:
"""
Rent class
"""
def __init__(self, car, nrDays):
"""
Constructor
car is an instance of a car
nrDays is an int
"""
self.setCar(car)
self.setNrDays(nrDays)
def setCar(self, car)... |
722a0edcc3afe44310c1cfe75c8baff3d0c42ebb | macostea/info-labs | /An 1/Sem 1/FP/Lab 11/mergeSort.py | 1,086 | 3.890625 | 4 | '''
Created on Dec 16, 2012
@author: mihai
'''
def mergeSort(listToSort, compareFunction):
if len(listToSort) == 1:
return listToSort
left = list()
right= list()
middle = len(listToSort) / 2
for i in range(middle):
left.append(listToSort[i])
for i in range(middle,... |
d968ffe452556f95eed1913ec620f04707134266 | yandrea888/ejercicios_momento2 | /Ejercicio3.py | 362 | 4 | 4 | #3. Pide números y mételos en una lista, cuando el usuario meta un 0 ya dejaremos de insertar. Por último, muestra los números ordenados de menor a mayor.
lista = []
salir = False
while(not salir):
numero = int(input("Digite un número: "))
if(numero == 0):
salir=True
else:
lista.append(... |
78970b57e446f289bc33d8ae99f1aefac702d3b0 | bayram98/APME_class | /module02_alg_analysis/part02_student_manager/student_manager.py | 3,595 | 4.34375 | 4 | """
Your task is to complete the implementation of a simple "Student Manager" application
for a university.
This programme allows to keep track of a student academic progress, i.e., doing exams, calculate GPA etc.
The Student Manager is implemented as a "class", that is, using the "object-oriented" paradigm.
You shoul... |
dfb8df273ecb703abf9ef56ed85afe26265931f1 | nickrsan/arcproject-wq-processing | /arcproject/waterquality/utils.py | 1,052 | 3.578125 | 4 | import numpy
import six
from . import classes
import os
def make_tables():
print("Creating tables")
classes.Base.metadata.create_all(classes.db_engine)
def recreate_tables():
try:
os.remove(classes.db_location)
except WindowsError:
print("---------------WARNING-------------------:\n Database not recreated!... |
765a8b28eae28004b66f91b0eafaccc6c533b778 | brpo01/test-1 | /lonecalculator.py | 6,120 | 4.03125 | 4 | print("welcome to Lapo mfbank")
rate = float(input("what is your company's rate? "))
rate_frac = rate
principal = float(input("please enter the amount you want N"))
print("you requested %f" %principal)
if (0 < rate_frac <= 5) and (principal <= 200000):
time = int(input("For how many years? "))
timeInYears = (time ... |
8a73b3d50d492db29eef34c2dad901a6e0528128 | brpo01/test-1 | /loancalculator.py | 1,935 | 3.984375 | 4 | print("Welcome to Lapo MFBank")
rate=float(input("What is your company's rate in percent? "))
rate_fraction=rate/100
print("Your company's rate is %.2fpercent" %rate)
principal=float(input("Please enter the amount you want "))
print("you requested N%.2f" %principal)
if 0 < rate <= 5 and principal <= 200000:
time=in... |
9e74d64440fac1469a549cedd7b88b252ca01dc4 | horeilly1101/Aiden-lab-coding-challenges | /num_to_word.py | 9,145 | 3.578125 | 4 | # Hugh O'Reilly
# Aiden Lab Coding Challenge
# 1B Number to String Challenge
import sys
def find_arithmetic_sequence(num_seq):
'''
Takes a sequence of digits as input and outputs a sequence of
tuples, where the digits in the tuples are the indices of the
inputted sequence where there are arithmetic sequences.
I... |
ff4617897e478456eedc60a7f1b7e3606cfc96a9 | harishkalwad/APS-2020 | /Sequence Equation.cpp | 1,495 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the findDigits function below.
def findDigits(n):
count = 0
print(list(str(n)))
for i in list(str(n)):
if int(i) != 0 and n % int(i) == 0:
count += 1
return count
if __name__ == '__... |
4a14f4ce8f10dc80eecc98b6dfde661c5fbf711b | harishkalwad/APS-2020 | /Happy Ladybugs.py | 1,650 | 3.59375 | 4 | #!/bin/python3
import sys
if __name__ == '__main__':
q = int(input().strip())
for a0 in range(q):
n = int(input().strip())
configuration = input().strip()
ladybugs = dict()
there_is_empty_cell = False
already_happy_ladybugs = True
for i in range(... |
11246464084b4f5d0f7a8aa27cf0c23543b17b57 | charles-ah/work3-graphics | /main.py | 1,017 | 3.609375 | 4 | from display import *
from draw import *
screen = new_screen()
color = [ 0, 255, 0 ]
'''
matrix = new_matrix()
matrix[0][0] = 250
matrix[0][1] = 250
matrix[0][2] = 0
matrix[0][3] = 1
matrix[1][0] = 500
matrix[1][1] = 500
matrix[1][2] = 0
matrix[1][3] = 1
'''
m = []
add_edge(m,250,500,0,500,250,0)
add_edge(m,500,250... |
0b34b70b37b9c9feaa14d5f31be03033ecf2579c | MorganeBourgeois/Game-of-life | /animation.py | 1,478 | 4.1875 | 4 | # How to create an animation using the function animation() from matplotlib or not
# Two examples
# run --> %matplotlib qt
# in IPython before the code
#______________________________________________________________________________________________________
# ANIMATION WITH THE FUNCTION animation()
import numpy as np
... |
abcaa5edb0d6563284028c3c6aa12f16048f9468 | agrawalyuvraj/subway-surfers-AI-main | /moving_avg.py | 911 | 3.609375 | 4 | # Return the moving average of last 100 observations.
# To gauge the performance of our model in the last 100 steps at the end of every epoch.
# 100 is a random number , can be anything.
import numpy as np
# Making the moving average on 100 steps
class MA:
def __init__(self, size):
self.size = size #Size ... |
e86d2fb64359f5661bf72d0a89f957b17d488703 | jshah3110/Machine-Learning-A-to-Z | /1) Data Preprocessing Tools.py | 1,910 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Data Preprocessing Tools
# ## Importing the libraries
# In[30]:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# ## Importing the dataset
# In[31]:
dataset = pd.read_csv(r"C:\Users\Dell\OneDrive\Desktop\Machine Learning A-Z\All Codes & Files\Pa... |
6d7db6d0540aaa2fcb6ef2a3c865fd120c7d32b1 | Seth-Joseph/standard-deviation | /StandardDeviation.py | 661 | 3.78125 | 4 | import math
import csv
with open('data.csv',newline = '')as f :
reader = csv.reader(f)
data = list(reader)
d = data.pop(0)
#Finding Mean
def mean(d):
n = len(d)
total = 0
for i in d :
total = total+int(i)
mean = total/n
return mean
... |
65f8d141915edebd8fd90a296aac5441e748c2b4 | mvinoba/stylo | /stylo/utils.py | 5,711 | 3.8125 | 4 | from inspect import signature
def bounded_property(
name,
bounded_above=None,
bounded_above_by=None,
bounded_below=None,
bounded_below_by=None,
):
"""Factory function to define a bounded property.
This function writes a property definition for a numeric bounded property.
It can be bou... |
61be334530fc1d43ca7b6a62ba150bba7ad5f232 | BurnLai/myPython | /dict_calc.py | 1,134 | 3.671875 | 4 | # # simple dictionary addition
# inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
#
# def check_qty(stuff):
# total = 0
# print('Inventory:')
# for k, v in inventory.items():
# total = total + v
# print(v, k)
# print(f"The total inventory are : {tot... |
91757cb8851f42a5bf55275cf7abe8b6a7844834 | JasonYang545/YHack_CollegeWreck | /scripts/parser.py | 2,719 | 3.5 | 4 | #! python3
#parses college "database" and writes results to results.html
import os
import sys
gpa = input()
scoreType = input()
score = int(input())
collegeFile = open('..\\colleges.txt')
collegeContent = collegeFile.readlines()
cc = {}
i = 0
for college in collegeContent:
cc[i] = college.split('\t')
i+=1
w... |
52d2c04d82d51e743f214d96623fcb0f8c7c5eea | catomania/new-coder | /dataviz/MySourceFiles/graph.py | 3,390 | 3.859375 | 4 | """
Data Visualization Project
Parse data from an ugly CSV or Excel file, and render it in
JSON-like form, visualize in graphs, and plot on Google Maps.
Part II: take the data we just parsed (from parse.py) and visualize it
using popular Python math libraries
"""
from collections import Counter #standard library mod... |
5caedda873c6a333f66254060b659befa36ff8d2 | Jun0414/Python-Programming-Notes | /else/dynamic_programming.py | 715 | 3.734375 | 4 |
# Dynamic Programming
# 분할 정복법과 차이
# 계산한 값을 저장하고 재활용하여 효율을 높인다
# 피보나치 수열 적용
# 반복적 표현 (이 경우는 재귀보다 효율적임)
def fibo(num):
data = [0 for index in range(num + 1)]
data[0] = 0
data[1] = 1
if num <= 1:
return data[num]
for index in range(2, num + 1):
data[index] = data[index - 1] + data[index - 2]
... |
d2682f3bd1d166ca086a6338c7cff2789a9fc946 | derek-ripper/gpio | /humidity/snippets/mytimer.py | 432 | 3.546875 | 4 |
import time
class timerx(object):
def __init__(self):
self.starttime = time.time()
def elapsedtime(self):
elasped = self.currenttime() - self.starttime
return elasped
def currenttime(self):
ct = time.time()
return ct
def waitforme(self,waittime... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.