blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9243641cfc8c49e539536b9c3156e844ca1c294a | rednur01/ProjectEuler | /050/main.py | 1,156 | 3.640625 | 4 | # Consecutive prime sum
from math import sqrt, ceil
def is_prime(n: int) -> bool:
if n < 2:
return False
elif n == 2 or n == 3 or n == 5:
return True
elif n % 2 == 0 or n % 3 == 0 or n % 5 == 0:
return False
else:
for i in range(6, ceil(sqrt(n))+1, 6):
# Only check upto sqrt(n) since at l... |
a6a5a340ce29a4e292711e9227919fd3948edaf5 | semicolonTransistor/housing-visualization | /state_init.py | 449 | 3.546875 | 4 | import sqlite3
def main():
connection = sqlite3.connect("data/housing.sqlite")
cursor = connection.cursor()
with open("states.txt") as f:
data = map(lambda x: (x[0], x[1], int(x[2])),
map(lambda line: tuple(map(lambda s: s.strip(), line.split("\t"))), f))
cursor.execute... |
b91075688c511bea9d0fc82246b6f21774726a1a | Ajay2521/Python | /ADVANCE/Functions/Built in Function/bytearray( ).py | 593 | 3.953125 | 4 | # In this lets see about the "Built-in functions" in python.
# Built-in function is defined as the functions whose functionality is pre-defined in the python compiler.
# Lets see about "bytearray( ) bilt-in function" in python.
# bytearray( ) - Used to returns a bytearray object and can convert objects into by... |
85c4fe653f7ee3c652cfa8386fc409b11b389e6b | Gporfs/Python-s-projects | /exercicio043.py | 761 | 3.828125 | 4 | maior = menor = 0
cont = 1
n = int(input('Digite um valor: '))
continuar = str(input('Deseja continuar[S/N]? ')).strip().upper()
soma = n
while continuar in 'Ss':
if cont == 1:
menor = n
maior = n
else:
if maior < n:
maior = n
if menor > n:
me... |
428f75d5d397e745eec773e5343f3a9a01dcaa21 | bandiayyappa/pythonprograms | /sortNumbersInTextFile.py | 262 | 3.515625 | 4 | # sort numbers in a text file
fh = open('numbers.txt','r')
data = fh.read().strip().split()
fh.close()
data = list(map(int,data))
data.sort()
str_data = list(map(str,data))
str_data = ' '.join(str_data)
fh = open('output.txt','w')
fh.write(str_data)
fh.close()
|
10d7b0c8373f0647a6bc654024bef86ceb85569c | Tijauna/CSC180-Python-C | /lab8/conwaylib1.py | 1,894 | 3.5625 | 4 | # coding: utf-8
from random import randint
class conway:
def __init__(self,sizeY, sizeX, typeInit):
#sizeY is row
#sizeX is col
self.sizeX = sizeX
self.sizeY = sizeY
if(typeInit == 'zeros'):
self.store = [[0 for i in range(sizeX)] for j in range(sizeY)]
if... |
e637715b1411f9bacf1c1c3d00b225c265915e35 | zhan01/guess-numbers | /guess_number.py | 426 | 3.9375 | 4 |
number = 77
guess = input("\nGuess: ")
guess = int(guess)
counter = 1
while guess != number :
if guess > number :
print("Guess lower!")
else:
print("Guess higher!")
print("-------------")
guess = input("\nTry again: ")
guess = int(guess)
... |
c3b270511b5b364d18225be4c7cc2911d8020c13 | pervejalam/python-930pm | /loops/while-if-break.py | 212 | 3.984375 | 4 | #!/usr/bin/python
while True:
print ("Enter a digit")
num=input()
#var=str(num)
if(ord(num) in range(48,58)): # Decimal 0-9
break
#continue
print ("We are out of the while loop")
|
92a819cfeac2c910a86e325b1a8928e95a4bcc2d | balonovatereza/Pyladies-repository | /02/porovnani.py | 296 | 4.03125 | 4 | pravda = 1 < 3
print(pravda)
nepravda = 1 == 3
print(nepravda)
print(True)
print(False)
tajneHeslo = 'Abrakadabra'
tipUzivatele = input('Zadej tajne heslo: ')
if tipUzivatele == 'Abrakadabra':
print('V patek jsem videla cerneho havrana.')
else:
print('Spatne heslo, zkus to znova.')
|
3fd951e0aff1ee6075022b0243134da2bd50cc8d | everbird/leetcode-py | /2015/LinkedListCycle_v0.py | 864 | 3.859375 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
p2 = p1 = head
while p1 and p2:
... |
e1b9d0e08d99364a4468c6e3744ec6c63cc56ab8 | NotaRobotexe/RoboticArm | /RoboticArm/Scripts/bruteForceArm.py | 1,287 | 3.5 | 4 | import math
def AngToRad(angle):
return angle*math.pi/180
def float_range(start,stop,step):
x = start
my_list = []
if step > 0:
while x < stop:
my_list.append(x)
x += step
else: # should really be if step < 0 with an extra check for step == 0
while x > sto... |
a46c28ee0b4fa70d73a3dd0ebca08d407a6eff6a | AlfredoAndrade14/AprendendoPython | /Mundo 1/soma_simples.py | 139 | 3.8125 | 4 | A = int(input("Digite um número: "))
B = int(input("Digite outro número: "))
SOMA = A + B
print ("A soma desses números é = %i"%SOMA)
|
265a851c6f386867b3c08fa60e4875862645d203 | ebachmeier/School | /Python/PoisonPenny.py | 2,608 | 4.09375 | 4 | # Eric Bachmeier
# Date Compleetd: October 7, 2011
print "Poison Penny"
print "------------"
print
print "Poison penny is a game for two players. Twelve pennies and a nickel"
print "are laid out. Each player can take one or two pennies, alternating"
print "turns until only the nickel (the poison) is left. Whoe... |
91ae27756c1abac1bbe1a431656f3a54bab987fb | gustavo-detarso/engenharia_de_software | /concluidas/logica_de_programacao_e_algoritmos/Aula_3/c3_ex_2.py | 387 | 3.84375 | 4 | # Ler dois valores numéricos inteiros e caso seja par imprimir uma mensagem informando, do mesmo jeito caso seja ímpar
# Passo 1: Definindo strings
num = float(input('Digite um número: '))
# Passo2: Montando o algoritmo
if num%2 == 0:
print('O número digitado é par.')
else:
print('O número digitado é ímpar.')... |
bfc3f24db2ef8a04021fe06f63ec9f1f97841799 | cobed95/cs-coach | /algorithms/sorting/answers/insertion_sort_fp.py | 928 | 4 | 4 | def insert(int_list, key):
if len(int_list) == 0:
return [key]
else:
if int_list[0] <= key:
return [key] + int_list
else:
return [int_list[0]] + insert(int_list[1:], key)
def iterate(loop_invariant, todo):
if len(todo) == 0:
return loop_invariant
... |
0342dbc6a3fba24b9d2ba09d9386f957400f29b5 | MSCapeletti/MC906-Projeto1 | /informed_search.py | 3,603 | 3.53125 | 4 | from Problem import Node
class PriorityQueue:
def __init__(self, maxsize=5000):
self.maxsize = maxsize
self.items = []
self._index = 0
def append(self, item, priority):
if len(self.items) < self.maxsize:
self.items.append((item, priority))
def pop(self):
... |
3be2ed5126fbf43036e9f05a71e31e3d9ceae5b4 | fahaddd-git/programmingProblems | /20_ValidParentheses.py | 2,116 | 3.90625 | 4 | # ID: 20
# URL: https://leetcode.com/problems/valid-parentheses/
# Difficulty: Easy
# Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
# An input string is valid if:
# -Open brackets must be ... |
b6629d24fae32ac439da7861fc86b3910eae4d03 | YuMi-coding/pcapCounters | /src/helpers.py | 172 | 3.875 | 4 | # The general helper functions
def insert_to_dict(dict, key, item):
if key in dict:
dict[key].append(item)
else:
dict[key] = [item]
return dict |
6263a032629c0ef2a0329afabf2756f05150b477 | raj-ankit744/Python-assignments | /Test/3.py | 1,259 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 14:06:22 2018
@author: user
"""
import operator
file = "C:/Users/user/Desktop/ARG/Test/Input.txt"
students = []
with open(file,'r') as f:
x = f.readline()
while(x!=""):
students.append(tuple(x.split()))
x = f.readline()
f.close()
... |
51c95c36482f24b9e28628d1638a86a9bc4c7cb0 | vishali0044/MoTask | /app.py | 1,915 | 4.21875 | 4 | import tkinter as tk #Tkinter is basically a package to run python code, this will help to create GUI
from tkinter import filedialog, Text # it will help to pick the Apps
import os
root = tk.Tk()
apps = []
if os.path.isfile('save.txt'):
with open('save.txt', 'r') as f:
tempApps = f.read()
tem... |
f218d9959d67041c6dc289f9a9aba23630053edc | pythongim/Gabaritos | /Primeira Lista de Exercícios/7.py | 442 | 4.0625 | 4 | # -*- coding: utf-8 -*-
day = input("Digite um dia em 2013: ")
if day > 365 or day <= 0:
print("O ano de 2013 tem apenas 365 dias.")
if day % 7 == 1:
print("Terça-feira")
elif day % 7 == 2:
print("Quarta-feira")
elif day % 7 == 3:
print("Quinta-feira")
elif day % 7 == 4:
print("Sexta-feira")
elif... |
7b70745b7c4da3a408204e2d510901fa22861550 | DerDoktorFaust/PackageDeliveryPathFindingAlgorithm | /main.py | 6,223 | 3.84375 | 4 | '''Main entry point into the program. It has four main functions. 1) load data from CSV files (data
originally created in excel_data_parser.py. The data parser must be run separately, this main program
only reads data from CSV files. 2) Print reports that show the status of all packages at any time
selected by the user... |
71b9a057f7906dfb5896975978b0a55f9cee46b0 | aoyono/sicpy | /Chapter2/exercises/exercise2_37.py | 1,735 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
https://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_thm_2.37
"""
from operator import add, mul
from Chapter2.exercises.exercise2_36 import accumulate_n
from Chapter2.themes.lisp_list_structured_data import cons, lisp_list, print_lisp_list
from Chapter2.sequences_as_conventional_... |
9aafbb29fcaa22e785baba0ab66a6964923f61ea | aluhrs/HB_OOP_Lesson | /game.py | 9,644 | 3.53125 | 4 | import core
import pyglet
from pyglet.window import key
from core import GameElement
import sys
#### DO NOT TOUCH ####
GAME_BOARD = None
DEBUG = False
KEYBOARD = None
PLAYER = None
######################
GAME_WIDTH = 10
GAME_HEIGHT = 10
#### Put class definitions here ####
class Rock(GameElement):
IMAGE = "Rock"... |
f318ff53769a1436fc283e91aa95dc6d8958282a | JoseCarlosNF/Uri.Python | /aula8_Exercicio2.py | 226 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# Aula 8 - Exercicio 2
def multi(n1, n2):
if n1 == 0:
return 0
else:
return multi(n1-1, n2) + n2
# Main
x = int(input('Num1: '))
y = int(input('Num2: '))
print(multi(x, y))
|
37f807dab3bee9c6d123bd162b48abc26829232c | osvaldoc/misiontic | /semana3/misFunciones.py | 653 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 19:17:03 2021
@author: Osvaldo
"""
import math
import random
def esPrimo (n):
if n % 2 == 0: #Si un numero es par, no es primo
return False
i = 3
while i <= math.sqrt(n):
if n % i == 0:
return False
i = i + 2
return True
def comienzaC... |
ead80ae6e5f8d6ae14e000d1410c42d01ab38aff | Ifeanyi30/Tutor_project | /payroll.py | 879 | 3.5 | 4 |
class Payroll(object):
def __init__(self, name, idNumber, hourlyRate, hoursWorked, grossPay):
self.name = name
self.idNumber = idNumber
self.hourlyRate = hourlyRate
self.hoursWorked = hoursWorked
self.grossPay = grossPay
def getName(self):
return self.name
... |
8f8c0ce000bb4dac569252b7d13d15108c0f8979 | GauravAmarnani/Python-Basics | /com/college/viva/exp14.py | 510 | 4.0625 | 4 | # WAP to Create a List, Add Elements into List and find the Sum of all Elements inside the List.
listName = [] # Creating List.
listName.extend([1, 2, 3]) # Adding Element using extend().
listName.insert(1, 1.1) # Adding Element using insert().
listName.insert(2, 1.2)
listName.append(4) # ... |
5abf240423abe02287acf63e977fb92b4e63316a | likes2addfunctions/CodeSamples | /Math/On_NDim_ChessBoard_VarLen.py | 2,928 | 4.03125 | 4 | #start 11:12
## This program computes the average number of moves it would take a rook
## to move off of an n-dimesional chess board. Each move is still two dimensional
## with the dimensions chosen at random.
import random
import matplotlib.pyplot as plt
def run_trial(n):
## set random initial coords
coo... |
b4046c13aef00a100553463a8cbcce1ada22bfa3 | Muttakee31/solved-interview-problems | /leetcode/492.construct-rectange.py | 336 | 3.6875 | 4 | import math
class Solution:
def constructRectangle(self, area: int) -> List[int]:
"""
https://leetcode.com/problems/construct-the-rectangle/
"""
root = math.floor(math.sqrt(area))
while(root>0):
if area % root == 0:
return [area//root, root]
... |
0471f77af8310764e6dbea2481cdbdf713b97a77 | johnhuzhy/MyPythonExam | /src/senior/func_decorator.py | 998 | 3.546875 | 4 | # Decorator デコレーター
import time
def print_time():
print(time.time())
def f1():
print('this is f1!')
# print_time()
# f1()
# ①
def pre_f1(func):
print_time()
func()
# ②
def decorator(func):
def wrapper():
print_time()
func()
return wrapper
# ③
@decorator
def f3():
pri... |
ac15ec2f8468b960716c043eb614a6adc12baa87 | yunnyisgood/Tensorflow | /keras1/keras16_summary.py | 884 | 3.609375 | 4 | import numpy as np
# 1. data
x = np.array([range(100), range(301, 401), range(1, 101),
range(100), range(401, 501)])
x = np.transpose(x) # (100, 5)
print(x.shape)
y= np.array([range(711, 811), range(101, 201)])
y = np.transpose(y)
print(y.shape)
# 2. modeling
from tensorflow.keras.models import Sequenti... |
c38f3a31f608a71326f31742bf43bc0e57f6a079 | dikoko/practice | /1 Numerics/1-04_fibo_gen.py | 460 | 3.953125 | 4 | # 1-04. Fibonacci Generator
# Given N, find all fibonacci numbers equal or less than N
def fibo_gen(N):
if N < 0: return []
def _gen_fibo(n):
prev_prev = 0
prev = 1
fibo = 1
while fibo <= n:
yield fibo
prev_prev = prev
prev = fibo
... |
42392314fd745cf01d5d54d67ce30f9e57fb3d1a | ethanbyeon/scripted | /imago.py | 1,786 | 3.671875 | 4 | from PIL import Image
# ASCII characters used by level of intensity for the output text
ASCII_CHARS = ['$', '@', 'B', '%', '8', '&', 'W', 'M', '#',
'*', 'o', 'a', 'h', 'k', 'b', 'd', 'p', 'q', 'w', 'm',
'Z', 'O', '0', 'Q', 'L', 'C', 'J', 'U', 'Y', 'X',
'z', 'c', 'v', 'u', 'n', 'x', 'r', 'j', 'f', 't',
... |
f69a7ca0da9bc7199d779e3e7aefc4e26fc3da96 | ankitomss/python_practice | /trie.py | 846 | 3.859375 | 4 | class TrieNode(object):
def __init__(self, s=None):
self.child = [None for _ in range(26)]
self.val = s
class Trie(object):
def __init__(self):
self.head = TrieNode()
def add(self, s):
tmp = self.head
for i in range(len(s)):
idx = ord(s[i]) - ord('a')
... |
0d9d9b3c2e8f6ae2b3377a09c763faff683c5ba0 | obsc/flight-planner | /util/mergefile.py | 4,007 | 3.515625 | 4 | import tempfile
import argparse
'''
compare function for lines, converts first two components of line to
an int that is well ordered (sorts by flight IDs and ordinals)
'''
def sorter(line):
stuff = line.split(' ')
return int(stuff[0]) * 1000 + int(stuff[1])
asdiposition = lambda x: int(x.split(',')[7]... |
d3719a75a8ff8781cbe827308347eb8334b8d6f1 | kblicharski/python-scripts | /misc_sec_scripts/divider.py | 812 | 3.59375 | 4 | import time
times = []
for z in range(100):
start = time.time()
[print(i,'Y') if i and not (i&(i-1)) else print(i,'N') for i in range(1000000)]
end = time.time()
times.append(end - start)
total = 0
for val in times:
total += val
algo_one = total/len(times)
print(str(algo_one) + ' seconds')
times... |
6cbbcdef1cfe7ebcf8d480a19ddb3a5f62637661 | samatachai/SoftwareLAB | /Python/ch01-01.py | 115 | 3.84375 | 4 | height = int(input('Enter height: '))
base = int(input('Enter base: '))
print('Answer is ',0.5*height*base)
|
51aab730071fc8ef1699b193a29174f12aeedff0 | negative0101/Python-Advanced | /exam-prep/02.Minesweeper Generator.py | 2,752 | 3.625 | 4 | def create_blank_matrix(n):
m = []
for _ in range(n):
m.append([])
for _ in range(n):
m[-1].append(0)
return m
def same_row_left(row, col, matrix):
if 0 <= col - 1 < len(matrix):
if matrix[row][col - 1] == '*':
matrix[row][col] += 1
... |
16c35c82daa5992b2ff8e1fdd31e6e0bb3a84fc3 | Vimlesh073/mynewrepository | /Python 24th Jan/nestedLoop.py | 341 | 3.6875 | 4 | '''
123
123
123
123
'''
'''
r = 1
c =1
c =2
c = 3
------
r =2
c=1
c=2
c=3
-----
r =3
c=1
c=2
c=3
----
r =4
c=1
c=2
c=3
'''
#nested loop
for r in range(1,5): # for row / height
#4 times
for c in range(1,4): # for col/ width
#..4 *3
print(c,end='')
print()
... |
4fc1ad6cc8236e0a77364b0e74e15581340f1785 | jadilson12/studied | /python/45 - GAME Pedra Papel e Tesoura.py | 1,188 | 3.90625 | 4 | # Ano 2018
# exercício realizado durante o curso
# @jadilson12
from random import randint
from time import sleep
itens = ('Pedra','Papel','Tesoura')
pc =randint(0,2)
print('''Suas opção
[ 0 ] - Pedra
[ 1 ] - Papel
[ 2 ] - Tesoura''')
jogador = int(input('Qual é sua jogada: '))
print('JO')
sleep(1)
pri... |
c56c67276c77f33d483cf08643630a0ec0be6ec4 | peterrenshaw/thisnote | /hours.py | 218 | 3.6875 | 4 | #!/usr/bin/env python3
# ~*~ coding: utf-8 ~*~
import time
import datetime
HHMM = "%H%M"
# what is the time LOCALTIME now?
today = datetime.date.today()
hhmm = today.strftime(HHMM)
print("{}".format(hhmm))
# eof
|
3900d1aee64b30b0bd2e615cf16bad60c732fc83 | helbertsandoval/trabajo06_sandoval_maira | /multiples1.py | 1,046 | 3.90625 | 4 | import os
#CALCULAR EL AREA DEL TRIANGULO
#DECLARARCION DE VARIABLES
area,base,altura=0.0,0.0,0.0
#INPUT
base=float(os.sys.argv[1])
altura=float(os.sys.argv[2])
# PROCESSING
area=(base*altura)/2
#VERIFICADOR
area_total1=(area>200)
area_total2=(150<=area<200)
area_total3=(50<=area<90)
# OUTPUT
prin... |
bf3dd29f5c3624a773d1d70815eb4096f69445bf | MaskedDevil/All_programs | /Python/demo.py | 1,319 | 4.40625 | 4 | # # Print a patient's data
# patientName = 'John Smith'
# age = 20
# status = 'new'
# print(patientName, age, status)
# # Take an input and print
# name = input('What is your name? ')
# print('Hello', name)
# # Type Conversion Demo...int(), float(), bool(), str()
# birthYear = input('What is your birth year? ')
# age... |
918f659cbc6f4ce0b2c2587f73ebc1bb53f0f218 | ErhardMenker/MOOC_Stuff | /Python4Everybody/chap_10_hw.py | 1,530 | 4.15625 | 4 | fname = input("Input file name: ")
fhandle = open(fname) #create file handle
d = dict() #initialize an empty dictionary
for iterated_line in fhandle:
line = iterated_line #rename iterated line to avoid computing errors
if line.startswith("From "):
line = line.split() #split the iterated line into a list... |
a6b2e12ba868f747e4457ef9a4c2beca86e76d68 | dchu07/MIS3640 | /Session09/word.py | 5,174 | 3.875 | 4 | # fin = open("session09/words.txt")
# line = fin.readline()
# word = line.strip()
# print(word)
# for line in fin:
# word = line.strip()
# print(word)
def find_long_words():
"""
prints only the words with more than 20 characters
"""
f = open("Session09/words.txt")
for line in f:
w... |
c91b154bdd98e17bbc3f31bff608cca3821935d9 | pedrillogdl/ejemplos_python | /DatosPersonales.py | 402 | 3.8125 | 4 | Nombre=input("Por favor, podrias proporcionar tu nombre: ")
Direccion=input("Por favor, podrias proporcionar tu Direccion: ")
Telefono=input("Por favor, podrias proporcionar tu Telefono: ")
ListaGeneral=[Nombre, Direccion, Telefono]
print("Los Datos Personsales Proporcionados son: ")
print("Nombre: " + ListaGeneral[0]... |
af6e576eec5f54b915c4130a7f0d8ecb0e53695d | ziweiwu/MIT-introduction-in-computer-science | /week1/problem-2.py | 139 | 3.703125 | 4 | s= 'azcbobobegghakl'
count=0
for i in range(len(s)-2):
if s[i:i+3]=='bob':
count=count+1
print(count)
|
e7ce31e7d75edfe38e9910edef9baf7465cc7caf | hwrdyen/python_lab3 | /LAB 3/Lab_3_5.py | 750 | 3.5 | 4 | def rgb_to_grayscale(rgb_image_array):
vector = []
row_number = len(rgb_image_array)
for i in range(0,row_number):
vector.append([])
for j in range(0,row_number):
vector[i].append([])
for k in range(0,3):
if k == 0:
q = 0.2989*(rgb_... |
a4411149762415264fe47480cbcd988a8705414d | loftina/LexicalAnalyzer | /front.py | 1,335 | 3.546875 | 4 | def main():
file = open('front.in', 'r')
for line in file:
current_line = unicode(line)
index = 0
while (index < len(current_line)):
if current_line[index].isalpha():
current_ident = current_line[index]
index = index + 1
while (current_line[index].isalpha() or current_line[index].isnumeric()):
... |
bf1d89c47aa147233fa5908f91b9c10b4c3b834d | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/pllker016/question1.py | 156 | 3.828125 | 4 | height=eval(input("Enter the height of the rectangle:\n"))
j=eval(input("Enter the width of the rectangle:\n"))
for i in range (height):
print(j*"*") |
24fc2a3e30153393b84ace414a3ffc59de64ed94 | kendfss/misc | /2021/stacking/lottohelper_using_getopt.py | 2,103 | 3.90625 | 4 | """
https://stackoverflow.com/questions/66192897/develop-a-module-to-help-generate-lottery-tickets-in-python
"""
import random, getopt, sys
def make_ticket(length, maximum):
"""
Generate a ticket of a given length using numbers from [1, maximum]
return random.sample(range(1, maximum+1), length)... |
39156137dba02055d19e279c62f4ba53e10a9961 | mdugot42/N-puzzle | /neural_network/trainingDataReader.py | 1,339 | 3.53125 | 4 | import re
def checkData(line, nl):
if len(line) != 10:
print("Error : line " + str(nl) + " : wrong size in training data input/output")
exit()
if len(line[0:9]) > len(set(line[0:9])):
print("Error : line " + str(nl) + " : same value in training data input")
exit()
i = 1
result = []
for n in line:
if n.i... |
9d409ae0b127c2cdf2b4481e8a81bb953f6050c7 | Aasthaengg/IBMdataset | /Python_codes/p03079/s624247118.py | 478 | 3.5 | 4 | from sys import stdin
## input functions for me
def ria(sep = ''):
if sep == '' :
return list(map(int, input().split()))
else: return list(map(int, input().split(sep)))
def rsa(sep = ''):
if sep == '' :
return input().split()
else: return input().split(sep)
def ri(): return int(input(... |
ce2585850f8f61a8814d6be5d762c7885db6baeb | aubinaso/Python | /face_detection.py | 926 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 1 22:49:27 2021
@author: aubin
"""
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# detect if there is a face not whose face it is which is face recognition
# https://github.com/opencv/opencv/tree/master/data/haarcascades
img = cv.imread("test.png... |
842f47ecad4f4598da4e5fad5200cd738991e323 | archdr4g0n/CSC221 | /BATCHELR m2t1 gold.py | 4,575 | 4.125 | 4 | ##Tracy Batchelor
##M2T1- Guessing game
##18 Sep 2017
##csc-221
import random
def main():
print('Here are your choices ')
print('1 = Find the number ')
print('2 = Pick the number ')
pick = input('Pick a game: ')
if pick == '1':
guess_game()
elif pick == '2':
comput... |
4f177464928af4d078028eabf047bc6a720aa6c8 | sloongz/Programm_Language | /Python/1.2_list_tuple_dict_set.py | 1,715 | 3.8125 | 4 | #!/usr/bin/env python
str = "12345678abcdef"
print str[3]
print str[2:10:2] #sname[start:end:step]
#list
print "\n================list================"
list1=[1,2,3,4,5, "hello", 2.3]
print list1
print list1[2:4:1]
del list1
list2=[1,2,3]
list3=["one", "two", "three"]
list4=list2+list3
print list4
list4.append("add... |
be4b6f51d9f847d3c6af500cd471e7dc9ee08410 | Sandeep8447/interview_puzzles | /src/main/python/com/skalicky/python/interviewpuzzles/calculate_angle_between_clock_hands.py | 796 | 4.1875 | 4 | # Task:
#
# Given a time in the format of hour and minute, calculate the angle of the hour and minute hand on a clock.
#
# def calcAngle(h, m):
# # Fill this in.
#
# print calcAngle(3, 30)
# # 75
# print calcAngle(12, 30)
# # 165
from math import floor
def calculate_angle_between_clock_hands(hours: int, minutes: in... |
a19898b3ed6e42660dcf472446bb1391e685f26f | bpiggin/codewars-katas | /python/string_to_camel.py | 273 | 4.15625 | 4 | def to_camel_case(text):
nextUpper = False
newStr = ""
for char in text:
if (char == "-" or char == "_"):
nextUpper = True
continue
if (nextUpper):
newStr += char.upper()
nextUpper = False
else:
newStr += char
return newStr |
8f1d22c3a11ed32ad379d19dec6ab126937b689f | Stevekerr3310/Python304 | /ticTacToe.py | 2,142 | 4.09375 | 4 | import random
def print_board(board):
print("-----")
print("{}|{}|{}".format(board[0], board[1], board[2]))
print("-----")
print("{}|{}|{}".format(board[3], board[4], board[5]))
print("-----")
print("{}|{}|{}".format(board[6], board[7], board[8]))
print("-----")
def is_win_or_lose(boar... |
ca65f9ab3a29ae0c2c08fca62af9559fe86187f2 | abhinavjha126/Python | /PythonTuts/FOR.py | 284 | 3.765625 | 4 | """list1=[["ABHI",1],["PRIYA",5],["APARNA",7],["RANJU",2]]
dict1=dict(list1)
print(dict1)
#for a,b in dict1.items():
#print(a,b)
for a in dict1:
print(a)"""
list1=["ABHI","2","**",9,56,86,678,"AB9","9ABHI","+",int,float]
for a in list1:
if str(a).isalnum():
print(a) |
e5a0cc802f69dce6badca7182ba637527726c96a | WeiPromise/study | /day10_面向对象基础/08-私有属性的使用.py | 817 | 3.765625 | 4 | #!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/9/29 14:24
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
self.__money = 1000 # 私有变量
def set_money(self, num):
# 验证逻辑
self.__money = num
def get_money(sel... |
5dfe173ec115420d75ce9f273cef7f9de5469d5a | vincent507cpu/Comprehensive-Algorithm-Solution | /LeetCode/easy - Hash Table/599. Minimum Index Sum of Two Lists/solution.py | 997 | 3.6875 | 4 | class Solution:
def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
# concisest solution
# https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/322322/2-lines-python
dct = {x: list1.index(x) + list2.index(x) for x in set(list1) & set(list2)}
... |
518c83b2145517f42de25d6a4c3f9579572def90 | jarrm5/python_progs | /comparisons.py | 2,243 | 4.1875 | 4 | def middle_value(a,b,c):
#Return the middle value of 3 numbers
#Assumes that a,b,c are distinct
largest = a
second_largest = b
#switch the values if b is larger than a
if(b > a):
largest = b
second_largest = a
#Now compare the values of largest and second_largest with c
... |
0724094d8db348e6c67fb7d65921de262b949e4d | davidnhuang/Learning-Python-For-Designers | /Week_5/Randomizing_Indexes.py | 618 | 3.75 | 4 | # David Huang
# Computer Programming for Designers and Artists
# Week 5 - Oct 11 2017
# ID 0239637
import random
#Variables
brady_bunch = ["Mike", "Carol", "Greg", "Jan", "Marsha", "Bobby", "Peter", "Cindy"]
plots = ["was late", "was sick", "got in trouble", "won a contest", "sang a song", "had a date"]
# generate p... |
9bc6b4f8540315636ef84eb6ddd6742978eb6279 | chinskiy/LabsNumericalMethods | /lab2.py | 2,880 | 3.609375 | 4 | def print_matrix(matr):
for _ in range(len(matr)):
for j in range(len(matr[_])):
print(format(matr[_][j], ',.4f'), end=' ')
print()
print()
def find_main(matr, k):
a_main = (matr[k][k], (0, 0))
for _ in range(len(matr)):
for j in range(len(matr[_]) - 1):
... |
cdfab7743c25ce0fd02df7248af7e470b1265801 | poojagmahajan/Data_Analysis | /Data Analytics/Panda/Functions_in_Dataframe.py | 1,074 | 4.75 | 5 |
# sum(axis=0) : This function calculates the sum of each column of a DataFrame.
# sum(axis=1) : This function calculates the sum of each row of a DataFrame.
# min(axis=0) : This function returns the minimum value from each column.
# min(axis=1) : This function returns the minimum value from each row.
# idxmin(axis=0) ... |
e4daf3264f17b89caab6c88f2d18b6961389afdf | brotherhuang/notebook_leetcode | /python/Number_of_Islands.py | 1,821 | 3.6875 | 4 | """ Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
E... |
8ba6187cae94f255e601b6b71fee1d72ef4e4827 | saikiranmaivemula1005/CSPP1Assignments | /M5/p4/square_root_newtonrapson.py | 347 | 3.953125 | 4 | """kkk"""# Write a python program to find the square root of the number
# using Newton-Rapson method
def main():
"""kk"""
STEP_ = 0.01
Y_ = int(input())
GUESS_ = Y_/2.0
NOG_ = 0
while abs(GUESS_*GUESS_ - Y_) >= STEP_:
NOG_ += 1
GUESS_ = GUESS_ - (((GUESS_**2) - Y_)/(2*GUESS_))
print(str(GUESS_))
if __name__... |
7990ca2c7c90a8902974c58857353360eaddae6e | ssb2920/SEM-6 | /ML/2. Least Square Method-Linear Regression/linear_regression.py | 3,085 | 4.03125 | 4 | # LINEAR REGRESSION
#
# y = b1 * x + b0
#
# To find b0 and b1 there are 2 ways:
#
# 1. Karl's correlation coeff
# 2. Least square method
#
# Steps (using Least Square Method):
# 1. Find mean of X (x")
# 2. Find mean of y (y")
# 3. Find x - x" and y - y"
# 4. Find (x - x") ** 2
# 5. Find b1 using formula
# 6. Find b0 us... |
2832b66234fa5ab5e0bd48e369d40c2e0401a6e1 | yuchun921/CodeWars_python | /8kyu/Find_numbers_which_are_divisible_by_given_number.py | 174 | 3.78125 | 4 | def divisible_by(numbers, divisor):
arr = []
for i in range(0, len(numbers)):
if numbers[i] % divisor == 0:
arr.append(numbers[i])
return arr
|
c0a2ec6bfd2863a65fdd5e63a19d076c5b18c72f | littlejoe1216/Chapter-8-Exercises | /Chapter 8 Exercises/Python_8_1.py | 422 | 4.0625 | 4 | #Joe Gutierrez - 2/1/18 - Chapter 8 - Exercise 1
#Write a function called chop that takes a list and modifies it, removing the first and last elements, and returns None.
#Then write a function called middle that takes a list and returns a new list that contains all but the first and last elements.
a = ['a', 'b... |
c60e6ca4b8931d4ddde4d8ba79981cb989e4ed5b | emzatos/Random-Coding | /Pal.py | 597 | 3.703125 | 4 | size = int(input())
string = input()
def check_pal(n):
if n == n[::-1]:
return False
n = list(n)
for i in range(len(n)//2):
if n[i] == n[-i-1]:
n[i] = ""
n[-i-1] = ""
else:
pass
n = "".join(n)
if len(n) == 2 or len(n) == 3:
return True
else:
return False
count = 0
offset = 2
strs = []
while ... |
27c7e6e9bc5eba6ac761b989204dda74dadd5555 | gabrielwai/Exercicios-em-Python | /ex062.py | 826 | 3.875 | 4 | A1 = int(input('Digite o primeiro termo de uma PA: '))
r = int(input('Digite a razão dessa PA: '))
continuar = 1
cont = 1
total = 10
print('Os primeiros 10 termos dessa PA são: ')
while cont != 11:
print('A{} = '.format(cont), end='')
print(A1 + (cont - 1) * r, end='')
print(', ' if cont != 10 else... |
255e13684231f6258958b6da62ff4a8548a13ac0 | Olumuyiwa19/aws_restart | /Moisture_Estimator_Script.py | 1,665 | 3.78125 | 4 | #This code estimate the
Yes = True
while Yes:
Grain_Type = str(input("Enter the type of your grain: "))
Wg = float(input("What is the weight of your grain? "))
MC_Wg = int(input("what is the moisture content of your wet grain? "))
MC_Dg = int(input("what is your desired final moisture content for the ... |
98170d5fe8f0a1f4d842c1dcc5d908abd5a2a9ee | Etyre/project_euler | /PE51.v2.py | 2,718 | 3.671875 | 4 | # PLAN:
# 1. make_prime function
# 2. All templates for number of length n.
# (templates for 1: 0, 1. 2: 00, 01, 10, 11)
# 3. loop through templates
# loop through digits
# and replace every digit coresponding to a 1 on the template with the digit.
# check if the result is prime, if so, save.
#... |
c7a048d9de13d6a8d64bff3e9cb75d750331af8d | Bidhampola/password_generator | /password_generator.py | 535 | 4.15625 | 4 | ### week 1 project... password generator
import string
import random
print("Welcome to password generator! ")
#input the length of the password
length=int(input('\n Enter the length of the password: '))
#defining data
num=string.digits
lower=string.ascii_lowercase
upper=string.ascii_uppercase
symbols=string.punctua... |
0a8d6ce385008ba0da50d1795b96851ca0dc5c21 | IOLevi/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 549 | 3.515625 | 4 | #!/usr/bin/python3
'problem 8'
class BaseGeometry():
'base geo class'
def area(self):
'prints area'
raise Exception("area() is not implemented")
def integer_validator(self, name, value):
'validates integers'
if not isinstance(value, int):
raise TypeError("{} ... |
eb8c9f5509ddbab317ed0d27956c5ea1bc1dc6f9 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/space-age/60919e0172d344d2898562e626577005.py | 1,046 | 3.984375 | 4 | earth_year_seconds = 31557600
planet_year_dictionary = {"mercury": 0.2408467,
"venus": 0.61519726,
"earth": 1.0,
"mars": 1.8808158,
"jupiter": 11.862615,
"saturn": 29.447498,
... |
b5c5056fe2952ba716c6a62d275193d38a6be62c | liyzcj/god | /god/utils/file_utils.py | 1,135 | 3.796875 | 4 | """A Module about file utilities."""
import os
from pathlib import Path
from tempfile import TemporaryDirectory
class TempDir(object):
"""
Similar with TemporaryDirectory, except:
* May chdir when use `with` statement
* yield variable is a Path object when use `with` statement
* `name` attribute... |
1d7be1f4bd6c1356ec2c1966478850bea3c4132d | polkapolka/py511SFBay | /py511SFBay/utils.py | 3,377 | 3.53125 | 4 | import curses
import curses.textpad
import os
import pdb
class Window(object):
"""Wrapper for the curses module."""
COLOR_ORANGE = 0
y = 0
spacing = 0
total_columns = 0
width = 0
window = None
def __init__(self, refresh_interval, total_columns):
"""Initialize the window with v... |
0a5ea04c4f3461e58679b8c67bde7402f299614d | sharmavaibhav7/CS579_IIT | /a3/a3.py | 9,802 | 3.75 | 4 | # coding: utf-8
# # Assignment 3: Recommendation systems
#
# Here we'll implement a content-based recommendation algorithm.
# It will use the list of genres for a movie as the content.
# The data come from the MovieLens project: http://grouplens.org/datasets/movielens/
# Please only use these imports.
from collectio... |
f099c403d8b645d711240b6f51d25503255707dd | bsilver8192/cs521-project | /process_regions.py | 4,610 | 3.609375 | 4 | #!/usr/bin/python3
# Creates a domestic_region_locations.csv with latitude+longitude for all
# the domestic regions. The first column is the code and the other columns are
# the latitude/longitude pairs or a redirect. For multiple pairs, we will
# verify they are all "close" (20 miles or something like that) and then ... |
e2d5e6afe2873254ab07c5bcd15024a4134ae95b | CaioHenriqueMachado/Contribuindo_com_Python | /Funções/Distancia_levenshtein.py | 269 | 3.921875 | 4 | #Link para outros tipos:https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
def lev(a, b):
if not a: return len(b)
if not b: return len(a)
return min(lev(a[1:], b[1:])+(a[0] != b[0]), lev(a[1:], b)+1, lev(a, b[1:])+1)
|
eacc422092892f58b11da086d6d093ddd613a304 | AS-AmanSinghal/PythonLearning | /TeslaExercise.py | 341 | 3.703125 | 4 | def Checker(age):
if age < 18:
return "Sorry,you are too young to drive this car.Powering off"
elif age == 18:
return "Congratulations on your first year of driving. Enjoy the ride!"
else:
return "Powering On. Enjoy the ride."
print(Checker(17))
print(Checker(18))
print(Checker(19)... |
ea055c5e6cc63de1122d12d1ea0ee1157aa81f43 | henrydeng2002/HoldEm | /Card.py | 950 | 3.796875 | 4 | class Card:
# basic card structure
def __init__(self, value, suit):
self.value = value
self.suit = suit
# all the comparison methods
def __eq__(self, card):
return (self.value == card.value)
def __ne__(self, card):
return not (self.value == card.value)
def __lt... |
3aa5f7104fba31cab4fe2640e635e76eb1eb57d1 | 1712danish/OS_priorityScheduling | /priority_Scheduling.py | 1,111 | 3.59375 | 4 | def waitingTime(processes, n, wt):
wt[0] = 0
for i in range(1, n):
wt[i] = processes[i - 1][1] + wt[i - 1]
def turnAroundTime(processes, n, wt, tat):
for i in range(n):
tat[i] = processes[i][1] + wt[i]
def findavgTime(processes, n):
wt = [0] * n
tat = [0] * n
waitingTime(processes, n, wt)
t... |
ba3a89390d03b895f7fc4130ceb81e14ca21272e | pforshay/MAST-HLSP | /PREP_CAOM/util/check_log.py | 789 | 3.609375 | 4 | """
..module:: check_log
:synopsis: Examines the log file at the end of processing to provide some
feedback on how many errors and warnings were logged.
"""
import os
#--------------------
def check_log(filepath):
""" Count errors and warnings in the log file and print the results.
:param filepath... |
d931e1d82bc6bdfd95fc49c2bfe017b5a062a9ac | thinkreed/lc.py | /algo/first/p735_asteroid_collision.py | 465 | 3.59375 | 4 | class Solution:
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
s = []
for asteroid in asteroids:
while len(s) > 0 and 0 < s[-1] < -asteroid:
s.pop()
if len(s) == 0 or asteroid > 0 ... |
134fc4849bde869a3a36fea76e5793beec74f1e0 | nayana09/python | /file2.py | 4,521 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#if conditions
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
# In[3]:
#evaluating variable
print(bool("Hello"))
print(bool(15))
# In[4]:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
# In[5]:
de... |
72f54697375d47fb7013603211162648c5fd6ab3 | SmithWenge/pythonTest | /返回函数0617/test1.py | 1,654 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-06-15 10:11:33
# @Author : Sullivan (1980849329@qq.com)
# @Link : https://github.com/SmithWenge
# 函数作为返回值
# 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
num = calc_sum(1,2,3)
p... |
407bea2b15d6545cb944fc4f7bd1cb5b6af8812d | TerryOShea/algorithms | /interview_cake/max_stack.py | 1,285 | 4.0625 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
if not self.items:
return None
return self.items... |
c930f23466e8bce9e2ddbece229be81abacea35e | Sanijg/mitx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Enigma/ps6.py | 15,335 | 4.21875 | 4 | import string
### DO NOT MODIFY THIS FUNCTION ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, thi... |
eb5906f5de7c9c7e00f8fbff2590036c2dccaa79 | imageadhikari/Mini-project | /main.py | 1,238 | 3.703125 | 4 | import numpy as np
from utils import getXY
from plot import myPlot
#set the seed
np.random.seed(111)
#set the values
MAX_LENGTH = 10**3
STEP = 50
#generating the random array
array = np.random.randint(1,high=500,size=(MAX_LENGTH))
#for the worse case we need array sorted in decending order, so reversing
reversed_a... |
164bdff68567cf9e59b2c555aaa70792bfcbdfaa | helloworld767/alogrithm | /permutation.py | 313 | 3.546875 | 4 | def permutation(nums, subset, res):
if not nums:
res.append(subset.copy())
for i in range(len(nums)):
permutation(nums[: i] + nums[i + 1:], subset + [nums[i]], res)
return
n = 4
nums = [i for i in range(1, n + 1)]
res = []
permutation(nums, [], res)
for list in res:
print(list)
|
7f32f9eaf26b0a947c691f8d215812d18013e8a1 | ShimSooChang/exerciosparatreino | /exercios2/10.py | 248 | 3.953125 | 4 | num = int(input("Digite um número para saber se é primo: "))
cont = 0
x = 0
while x <= num or cont < 2:
x += 1
d = num % x
if d == 0:
cont += 1
if cont <= 2:
print("é numero primo")
else:
print("não é primo")
|
870c3d5cc1f37de9add719a39b6d2788eb7c2b2b | parkje0927/atom-workspace | /basic/0424.py | 4,983 | 3.609375 | 4 | # 파이썬 스타일 코드 I
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors)
print(result)
items = 'zero one two three'.split()
print(items)
example = 'python, jqeury, javascript'
example.split(",")
print(example)
a, b, c = example.split(",")
print(a, b, c)
result = ' '.join(colors)
print(result)
result = ',... |
9c8b92f8cdc094740df61ddb6b77aff56e2350ad | AdamZhouSE/pythonHomework | /Code/CodeRecords/2147/60647/301543.py | 2,921 | 3.5625 | 4 | def findAllPath(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
paths = [] # 存储所有路径
for node in graph[start]:
if node not in path:
newpaths = findAllPath(graph, node, end, path)
for newpath in newpaths:
paths.app... |
fc3b721891e09d71fb31dd07c8513b5606f65b5a | eserebry/holbertonschool-higher_level_programming | /0x06-python-classes/100-singly_linked_list.py | 1,023 | 3.53125 | 4 | class Node:
def __init__(self, data, next_node=None):
if isinstance(data, int) is False:
raise TypeError("data must be an integer")
if next_node is not None or not Node:
raise TypeError("next_node must be a Node object")
self.__data = data
self.__node = node
... |
9c8e484cea78e82a32439dadfff19d57abfc53b2 | EliasJRH/COMP-1405Z-Problem-Set-Solutions | /Set 1 - Introductory Python, Variables, Input, Output, and Calculations/P7 - Simple Guessing Game.py | 653 | 4.03125 | 4 | import random
num_to_guess = random.randint(1,100)
player_guess = input('Guess the number from 1 to 100: ')
while (not player_guess.isdigit()):
print('Input an integer')
player_guess = input('Guess the number from 1 to 100: ')
player_guess = int(player_guess)
if (player_guess == num_to_guess):
print... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.