blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
713f27ced7d6e57dc790dc700c996d0046584b74 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/opt-lab-lcr-v2.py | 2,739 | 3.59375 | 4 | '''
Lab: LCR Simulator
https://github.com/PdxCodeGuild/2019-10-28-fullstack-night/blob/master/1%20Python/labs/optional-LCR.md
'''
import random
#this is the function for each player turn:
def player_roll(player_name, chips, player_L, player_R):
die_sides = ["L", "C", "R", "*", "*", "*"]
player_roll = []
if... |
ae03c569f2eb80951263f0556482c783d009e549 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/optional-labs/tic-tac-toe/tic_tac_toev2.py | 2,803 | 3.890625 | 4 | '''
Tic-Tac-Toe
'''
# import numpy
class Player:
def __init__(self, name, token):
self.name = name
self.token = token
class Game:
def __init__(self):
board = {
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
... |
2928ceeee16232bba71cac568fab3e3c19ee15bf | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab20.py | 649 | 3.640625 | 4 | def get_second_digit(num):
if num < 10:
return None
return num % 10
def validate_credit_card(cc_str):
if len(cc_str) != 16:
return False
cc = []
for i in range(len(cc_str)):
cc.append(int(cc_str[i]))
check_digit = cc.pop(-1)
cc.reverse()
for i ... |
eb0bf7381ff1ea3d9f11dec46d6e2ff775d65c7e | pjz987/2019-10-28-fullstack-night | /Assignments/dustin/lab23.py | 586 | 3.515625 | 4 | '''
By: Dustin DeShane
Filename: lab23.py
'''
songs = []
with open("songlist.csv", 'r') as song_list:
rows = song_list.read().split('\n')
headers = rows.pop(0).split(',') #set first row as headers/keys
#print(headers)
for row in rows:
row = row.split(',') #iterate through rows and split them in... |
abacfce7f2c434836cfdcbbe6f763df0dce691fe | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab09.py | 177 | 4 | 4 | import decimal
#user input
d_ft = int(input("Input distance in feet: "))
#conversion
d_meters = d_ft/0.3048
#equals
print("The distance in meters is %i meters." % d_meters)
|
c41cf49d568bee4f2e2caaf24483b0e032b247eb | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab11_v1.py | 146 | 3.640625 | 4 | operation = input("What operation would you like to do?")
num_1 = int(input("Enter first number."))
num_2 = int(input("Enter second number."))
|
8ed3fb8ef261e016ce96a2af1f955eab2003e599 | pjz987/2019-10-28-fullstack-night | /Assignments/jake/Python_Assignments/lab20-credit_card_check.py | 1,172 | 3.6875 | 4 | def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
... |
2d304bd9b8bcae2dc320a8a252ca066983467326 | pjz987/2019-10-28-fullstack-night | /Assignments/pete/python/lab23-contact-list/lab23-contact-list-v3.py | 3,638 | 3.828125 | 4 | '''
Lab 23: Contact List
Version3
When REPL loop finishes, write the updated contact info to the CSV file to be saved. I highly recommend saving a backup contacts.csv because you likely won't write it correctly the first time.
'''
with open('cities_list.csv', 'r') as cities:
#establish the rows
rows = cities.read... |
61902e6f6ac8f23acb98798c79228bab0c09d829 | pjz987/2019-10-28-fullstack-night | /Assignments/duncan/python/lab03_grading.py | 1,030 | 4.0625 | 4 | '''
A = range(90, 100)
B = range(80, 89)
C = range(70, 79)
D = range(60, 69)
F = range(0, 59)
'''
import random
print("Welcome to the Grading Program!")
user_grade = int(input("What is your numerical score?"))
# set up +/-
if user_grade % 10 in range(1,6):
sign = "-"
elif user_grade % 10 in range(6,11):
sig... |
b3a7d72bede78555fe345a47f43661641b90e65d | pjz987/2019-10-28-fullstack-night | /Assignments/andrew/python/lab12_v1.py | 265 | 3.984375 | 4 | import random
target = random.randint(1,10)
guess = ''
while True:
guess = input('guess the number! ')
guess = int(guess)
if guess == target:
print('that\'s correct!')
break
else:
print('that\'s incorrect!')
|
188fa1987331719b38bedc7fc2ecfa785328c1fd | harshidkoladara/Python_Projects | /PoliceComplainSystem/Template Files/mainconnection.py | 466 | 3.625 | 4 | import sqlite3
from sqlite3 import Error
def sql_connection():
try:
con = sqlite3.connect('mydatabase.db')
return con
except Error:
print(Error)
def sql_table(con):
cursorObj = con.cursor()
#cursorObj.execute('insert into data VALUES(1,0," "))')
cursorObj.ex... |
1d9b46c9cf7ecff4ea5e4ea41dc18f269dcf1ff6 | soupierbucket/Lets-Build | /Calculator_Using_Python/Calc_Using_Python.py | 4,608 | 4.125 | 4 | #Import section
from tkinter import *
#Funtion definations
def click(num):
"""
To display the number
num: input onclick parameter
"""
value = entry.get()
entry.delete(0, END)
entry.insert(0, str(value) + str(num))
return
def clear():
"""
To clear the screen
... |
3a495c4e7a920cda01b5805f0eaebc9f3fc455ae | n20002/Task | /0813.py | 2,637 | 3.734375 | 4 | import sys
from itertools import count
from random import randint
def checkfn(left, right, guess):
if left < right and guess == 'h':
return True
if left == right and (guess == 'h' or guess == 'l'):
return True
if left > right and guess == 'l':
return False... |
e128273e27389122b8d02b180980fa8562c940fb | jostaylor/Word_Search_Generator | /WordSearch.py | 7,628 | 4.125 | 4 | import random
import sys
# TODO What can I add?
# Make the program more user-friendly:
# Maybe if we get an infiniteError, allow the user to alter the words or the size of the grid and retry
# Add a file writer for the key to the word search
# Make it easier for the user to input without having to type them in all ove... |
e3131b62735d783016b26f1b6f25ca8754cb2458 | IamGianluca/algorithms | /ml/sampling/metropolis.py | 2,929 | 3.625 | 4 | import numpy as np
class MetropolisHastings(object):
"""Implementation of the Metropolis-Hastings algorithm to efficiently
sample from a desired probability distributioni for which direct sampling
is difficult.
"""
def __init__(self, target, data, iterations=1000):
"""Instantiate a *Metro... |
f008d73d640609771b8f2aaa149449a10f7706ee | aniroxxsc/Hackerrank-ProblemSolving-Python | /SuperReducedString | 632 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the superReducedString function below.
def superReducedString(s):
for i in range(0,len(s)-1):
if s[i]==s[i+1]:
s1=s[0:i]
if (i+2)<=len(s):
s2=s[i+2:]
else:
... |
fe82e7566405f33f301201bd5cce475c0147d805 | mohasinac/Learn-LeetCode-Interview | /Strings/Count and Say.py | 1,812 | 4.0625 | 4 | """
he count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nt... |
81ff46e99809f962f6642b33aa03dd274ac7a16e | mohasinac/Learn-LeetCode-Interview | /Strings/Implement strStr().py | 963 | 4.28125 | 4 | """
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empt... |
7e558fb4d31490ea5317a9b131c8e022e0504f20 | msam04/Assignment2.2 | /Python_Module2_2.py | 236 | 3.890625 | 4 |
# coding: utf-8
# In[19]:
for i in range (1, 6):
str = "*"
for j in range (1, i):
str = str + "*"
print(str)
length = len(str)
for j in range (1, len(str) + 1):
print(str[:length])
length -= 1
|
885a56023c3b3877e0d2bccf0db93f3c65351b95 | i2mint/stream2py | /stream2py/simply.py | 4,464 | 3.5625 | 4 | """
Helper Function to construct a SourceReader and StreamBuffer in one
Example of usage:
::
from stream2py.simply import mk_stream_buffer
counter = iter(range(10))
with mk_stream_buffer(
read_stream=lambda open_inst: next(counter),
open_stream=lambda: print('open'),
close_strea... |
78ae22f42201983039a2b6aba20195284063b3e4 | andrei10t/AdventOfCode | /AdventOfCode2020/day3.py | 968 | 3.546875 | 4 | def readFile(filename) -> list:
with open(filename, "r") as f:
return [line[:-1] for line in f.readlines()]
def readtest() -> list:
input = list()
with open("test.txt", "r") as f:
for line in f.readlines():
input.append(line)
return input
def part1(file):
counter = ch... |
997f0d32c5609f5e9dac7fb94b933f4e28d64809 | jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO | /exercicio11.py | 410 | 4.15625 | 4 | # 11. Altere o programa anterior para mostrar no final a soma dos números.
# Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01
num1 = int(input("Digite o primeiro número inteiro: "))
num2 = int(input("Digite o segundo número inteiro: "))
for i in range (num1 + 1, num2):
print(i)
for i in range (num2 ... |
2d0c69eabcd187406a0e982cbc343c88d88a26cb | jonathansilveira1987/EXERCICIOS_ESTRUTURA_DE_REPETICAO | /exercicio14.py | 601 | 3.96875 | 4 | # 14. Faça um programa que peça 10 números inteiros, calcule e mostre a
# quantidade de números pares e a quantidade de números impares.
# Desenvolvido por Jonathan Silveira - Instagram: @jonathandev01
import math
numero = [[], []]
valor = 10
for c in range(1, 11):
valor = int(input(f"Digite o {c}º valor: "))
... |
16cbb114d0a13ac1c2a25c4be46dd7c14db6584c | Divyendra-pro/Calculator | /Calculator.py | 761 | 4.25 | 4 | #Calculator program in python
#User input for the first number
num1 = float(input("Enter the first number: "))
#User input for the operator
op=input("Choose operator: ")
#User input for the second number
num2 = float(input("Enter the second number:" ))
#Difine the operator (How t will it show the results)
if op == '... |
1f8f158a5528bff42b1eb0876794211096386475 | gruenwalds/geekbrains | /Gruenwald_4_4.py | 396 | 3.921875 | 4 | digits = [int(element) for element in input("Введите числа: ").split()]
even_number = 0
sum_numbers = 0
for counter in digits:
if counter % 2 == 0:
even_number = even_number + counter
for nums in range(1, len(digits), 2):
sum_numbers = sum_numbers + digits[nums]
sum_numbers = sum_numbers + even_... |
006703a80291ab29120be71a5a713a213d8d45bc | DeFeNdog/LeetCode | /arrays_and_strings/first-unique-character-in-a-string.py | 667 | 4.0625 | 4 | '''
## First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's
index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
'''
from coll... |
b7ce6e275957e54ae4a4fd8e70f44a422396cbae | DeFeNdog/LeetCode | /linked_lists/add-two-numbers.py | 2,323 | 3.90625 | 4 | '''
## Add Two Numbers
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their nodes
contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the
... |
8a3f462060774d17383f404bf97467015cd94489 | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex053_detector_de_palindromo.py | 1,157 | 4.15625 | 4 | # Class Challenge 13
# Ler uma frase e verificar se é um Palindromo
# Palindromo: Frase que quando lida de frente para traz e de traz para frente
# Serão a mesma coisa
# Ex.: Apos a sopa; a sacada da casa; a torre da derrota; o lobo ama o bolo;
# Anotaram a data da maratona.
# Desconsiderar os espaços e acentos. Progr... |
51fba057f0a7253f1ad30a5c0d6c38171b888e77 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex082_dividindo_valores_em_varias_listas.py | 1,188 | 4.03125 | 4 | # Class Challenge 17
# Ler vaios números
# Ter duas listas extras, só com pares e ímpares
# Mostrar as 3 listas
# Dica: Primeiro le os valores, depois monta as outras duas listas
big = list()
par = list()
impar = list()
while True:
big.append(int(input('Enter a number: ')))
resp = ' '
while resp not in '... |
9d82ae750f0a2f3d2531e9832d9e32ae142a67ea | NathanaelV/CeV-Python | /Aulas Mundo 1/aula09_manipulando_texto.py | 4,673 | 4.34375 | 4 | # Challenge 022 - 027
# Python armazena os carcteres de uma string, as letras de uma frase, separadamente
# Python conta os espaços e a contagem começa com 0
# Para exibir um caracter específico só especificar entre []
# Fatiamento
frase = 'Curso em Vídeo Python'
print('\nFATIAMENTO!\n')
print('frase[9]:', fr... |
4d7ae2dfa428ee674fdd151230a36c39c09e7055 | NathanaelV/CeV-Python | /Aulas Mundo 3/aula19_dicionarios.py | 2,623 | 4.21875 | 4 | # Challenge 90 - 95
# dados = dict()
# dados = {'nome':'Pedro', 'idade':25} nome é o identificador e Pedro é o valor
# idade é o identificador e 25 é a idade.
# Para criar um novo elemento
# dados['sexo'] = 'M'. Ele cria o elemento sexo e adiciona ao dicionario
# Para apagar
# del dados['idade']
# print(dados.valu... |
c8ac81bcd8433c0749e3afc2330ff91a325b5180 | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex068_jogo_do_par_ou_impar.py | 1,810 | 3.921875 | 4 | # Class Challenge 15
# Make a game to play 'par ou impar' (even or odd). The game will only stop if the player loses.
# Show how many times the player has won.
from random import randint
c = 0
print('Lets play Par ou Impar')
while True:
comp = randint(1, 4)
np = int(input('Enter a number: '))
rp = str(in... |
1426a37e040bc9a849200f43c5cc612fee91e36e | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex040_aquele_classico_da_media.py | 1,058 | 3.875 | 4 | # Class Challenge 12
# Calcular a média e exibir uma mensagem:
# Abaixo de 5.0 reprovado, entre 5 e 6.9 recuperação e acima de 7 aprovado
cores = {'limpo': '\033[m',
'negrito': '\033[1m',
'vermelho': '\033[1;31m',
'amarelo': '\033[1;33m',
'verde': '\033[1;32m'}
n1 = float(input('Insi... |
c6bd3a2159ebf010f5a9e17f9e1b1c8a968f88f2 | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex005_antecessor_e_sucessor.py | 386 | 4.03125 | 4 |
# Class challenge 007
# Mostrar o antecessor e o sucessor de um numero inteiro
n = int(input('\nDigite Um numero inteiro: '))
a = n - 1
s = n + 1
print('O antecessor do numero {} é {}.'.format(n, a), end=' ')
print('E o sucessor é {}'.format(s))
# Exemplo do professor
n = int(input('Digite um número: '))
print('O a... |
1bc7549e958d98847832cc25cf3ce84a242bb458 | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex027_primeiro_e_ultimo_nome_de_uma_pessoa.py | 421 | 3.9375 | 4 | # Class Challenge 09
# Ler o nome completo de uma pessoa e mostar o primeiro e o último
nome = str(input('Digite o seu nome completo: ')).strip()
a = nome.split()
print('O primeiro nome é {} e o último é {}'.format(a[0], a[0]))
# Exemplo do Professor
print('\nExemplo do Professor\n')
print('Olá, muito prazer.')
pri... |
8ca33acd165cec49c7c84b75394da1cf6b7d1f0d | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex090_dicionario_em_python.py | 930 | 3.84375 | 4 | # Class Challenge 19
# Read name and media of several students
# Show whether the student has failed or passed
student = dict()
na = str(input('Enter the student name: '))
m = float(input('Enter the student media: '))
student['name'] = na
student['media'] = m
if m >= 7:
student['Situation'] = 'Aprovado'
elif 5 <=... |
1e8dc17f6182d9c87f9c60a56e49021c5c4c7114 | NathanaelV/CeV-Python | /Modulos Curso em Video/ex107_exercitando_modulos_em_python.py | 499 | 3.828125 | 4 | # Class Challenge 22
# Criar um módulo chamado moeda.py
# Ter as funções aumentar() %; diminuir() %; dobrar() e metade()
# Fazer um programa(esse) que importa e usa esses módulos
# from ex107 import moeda
from ex107 import moeda
num = float(input('Enter a value: '))
print(f'Double of {num} is {moeda.dobrar(num)}')
p... |
ee8ebbe66eaae522f183e71a96c5b6bf218b34ad | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex031_custo_da_viagem.py | 538 | 3.84375 | 4 | # Class Challenge 10
# Calcular o preço da passagem de ônibus
# R$ 0,50 para viagens até 200 km
# R$ 0,45 para viages acima de 200 km
d = int(input('Qual a distância da sua viagem? '))
if d <= 200:
p = d * 0.5
else:
p = d * 0.45
print('O preço da sua passagem é R$ {:.2f}'.format(p))
# Exemplo do professor
... |
d76dc80b873a755892779f45844e57ce177ac511 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex088_palpites_para_a_mega_sena.py | 1,652 | 4.0625 | 4 | # Class Challenge 18
# Ask the user how many guesses he wants.
# Draw 6 numbers for each guess in a list.
# In a interval between 1 and 60. Numbers can't be repeated
# Show numbers in ascending order.
# To use sleep(1)
from random import randint
from time import sleep
luck = list()
mega = list()
print('=' * 30)
pri... |
8ea4a1eae9758fac4e17895d3a290b4b5b7e56bf | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex024_verificando_as_primeiras_letras_de_um_texto.py | 839 | 4.0625 | 4 | # Class Challenge 09
# Ler o nome da Cidade e ver se começa com a palavra 'Santo'
cidade = input('Digite o nome da sua cidade: ')
minusculo = cidade.lower().strip().split()
# primeira = minu.strip()
# p = primeira.split()
print('Essa cidade tem a palavra santo?: {}'.format('santo ' in minusculo))
print('Santo é a pri... |
8e28da8e0eb769a6a9735bb6edf36567011b2a0a | NathanaelV/CeV-Python | /Aulas Mundo 3/aula20_funçoes_parte1.py | 1,450 | 4.1875 | 4 | # Challenge 96 - 100
# Bom para ser usado quando um comando é muito repetido.
def lin():
print('-' * 30)
def título(msg): # No lugar de msg, posso colocar qualquer coia.
print('-' * 30)
print(msg)
print('-' * 30)
print(len(msg))
título('Im Learning Python')
print('Good Bye')
lin()
def soma(... |
560596b12e9cda1ebdadfb4ab2b5c945ad0265d1 | NathanaelV/CeV-Python | /Exercicios Mundo 3/ex103_ficha_do_jogador.py | 1,173 | 4.21875 | 4 | # Class Challenge 21
# Montar a função ficha():
# Que recebe parametros opcionais: NOME de um jogador e quantos GOLS
# O programa deve mostrar os dados, mesmo que um dos valores não tenha sido informado corretamente
# jogador <desconhecido> fez 0 gols
# Adicionar as docstrings da função
def ficha(name='<unknown>', go... |
f1f9c6ff93b2e33c013618b98735aa2c128f980f | NathanaelV/CeV-Python | /Exercicios Mundo 2/ex051_progressao_aritimetica.py | 300 | 3.859375 | 4 | # Class Challenge 13
# Ler o primeiro termo e a razão da P.A. e mostrar os 10 primeiros números
print('{:=^40}'.format(' 10 TERMOS DE UMA PA '))
t = int(input('Digite o 1º termo: '))
r = int(input('Digete a razão da PA: '))
for a in range(t, t + 10*r, r):
print(a, end=', ')
print('\nFim!')
|
143b16bde692bfc1ace62443b270d9dd50d8185c | NathanaelV/CeV-Python | /Exercicios Mundo 1/ex003b.py | 357 | 4.09375 | 4 | # Class Challenge 006
# Para números Inteiros
a = int(input('Digite um número: '))
b = int(input('Digete outro número: '))
c = a + b
print('A soma entre {} e {} é: {}'.format(a, b, c))
#Para números Reais
d = float(input('Digite um número: '))
e = float(input('Digite outro número: '))
f = d + e
print('A soma entre {}... |
c0f6d267dcdcd1a2dc364976bb815a9e7a524cb9 | arjngpta/miscellaneous | /experiment.py | 239 | 3.5625 | 4 | import os
i = 0
n = [1,2,3]
file_list = os.listdir(os.getcwd())
for file_name in file_list:
i = i + 1
if i in n:
print "i is in n"
else:
print "i is not in n"
print i
print n
|
090e9e030c462324d39a04eab7f05a2e44e2c8a9 | Scuba-Chris/game_of_greed | /game_of_greed.py | 3,808 | 3.53125 | 4 | import random
from collections import Counter
import re
class Game:
def __init__(self, _print=print, _input=input):
self._print = print
self._input = input
# self._roll_dice = roll_dice
self._round_num = 10
self._score = 0
self.rolled = []
self.keepers = [... |
5d86ca4b127b79be2a7edc2a93e45dfc0502ccd7 | JiJibrto/lab_rab_12 | /individual2.py | 1,358 | 4.34375 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# Реализовать класс-оболочку Number для числового типа float. Реализовать методы
# сложения и деления. Создать производный класс Real, в котором реализовать метод
# возведения в произвольную степень, и метод для вычисления логарифма числа.
import math
class Number:
... |
c1ab809f56fb6edf4827b1978bdb32bc9b7bb532 | nickolasbmm/lista2ces22 | /ex11.py | 550 | 3.78125 | 4 | #Function with argument list
def square_sequence(*arglist):
print("Squared sequence: ",end="")
for x in arglist:
print("{} ".format(x**2),end="")
print("")
print("Example function with argument list")
print("Initial sequence: 1 2 3 4 5")
square_sequence(1,2,3,4,5)
#Functio with argument dictionary
... |
b765209f2c2fc302496ec89993d73d87e2d80d56 | rbngtm1/Python | /data_structure_algorithm/array/Plus_0ne.py | 464 | 3.90625 | 4 | given_array = [1, 2, 3, 4, 5]
# length = len(given_array)-1
#print(length)
# for i in range(0, len(given_array)):
# #print(i)
# if i==length:
# given_array[i]=given_array[i]+1
# else:
# given_array[i]=given_array[i]
# print(given_array)
############################################
m... |
0036738f5c4ebd10ed148ed836ff304ead8b66f0 | rbngtm1/Python | /data_structure_algorithm/array/contains_duplicate.py | 374 | 3.96875 | 4 | array = [1,2,3,4]
my_array = []
# for i in array:
# if i not in my_array:
# my_array.append(i)
# if array == my_array:
# print('false')
# else:
# print('true')
def myfunc():
for i in range(len(array)):
if array[i] in my_array:
return True
else:
my_array.... |
c80bffe95bc94308989cec03948a4a91239d13aa | rbngtm1/Python | /data_structure_algorithm/array/remove_duplicate_string.py | 398 | 4.25 | 4 | # Remove duplicates from a string
# For example: Input: string = 'banana'
# Output: 'ban'
##########################
given_string = 'banana apple'
my_list = list()
for letters in given_string:
if letters not in my_list:
my_list.append(letters)
print(my_list)
print (''.join(my_list))
## poss... |
ee2da66a029f7bc9afad26c6025573e21bea8ae9 | gyeongchan-yun/useful-python | /threading_event_queue.py | 679 | 3.515625 | 4 | import threading
from queue import Queue
evt_q = Queue()
def func():
number = int(threading.currentThread().getName().split(":")[1])
if (number < 2):
evt = threading.Event()
evt_q.put(evt)
evt.wait()
for i in range(10):
print ("[%d] %d" % (number, i))
if (number > 2)... |
1984969edc15b4e08db867aae9241e40ad8ff8ec | AbdAyyad/opensouq | /opensouqback/stringsapp/hamming_distance.py | 546 | 3.671875 | 4 | class hamming_distance:
def __init__(self, first_string, second_string):
self.first_string = first_string
self.second_string = second_string
self.initlize_disance()
def initlize_disance(self):
self.distance = 0
for i in range(len(self.first_string)):
if self.... |
30e54e336c427637344711d8f9646d2b1fd6d43e | wendyzou02/python-test | /demolib.py | 147 | 3.953125 | 4 | def sum_even(start_num, end_num):
sum = 0
for x in range( start_num, end_num+1 ):
if x%2==0:
sum += x
return sum
|
bee174e6985d80c2a2cceb86590b5db9dbc00af6 | ingridcoda/knapsack-problem | /src/model.py | 575 | 3.578125 | 4 | class Item:
def __init__(self, size, value):
self.size = size
self.value = value
def __str__(self):
return f"{self.__dict__}"
def __repr__(self):
return self.__str__()
class Knapsack:
def __init__(self, size=0, items=None):
self.size = size
self.items ... |
d2b48f3f46963d6b8a07c766acd0475e6adb4487 | jbloom04/python-test | /functions.py | 193 | 3.546875 | 4 |
batteries=[1,3,7,5]
def light(batt1,batt2):
# if batt1 % 2 == 0 and batt2 % 2 == 0:
if batt1 in batteries and batt2 in batteries:
return True
else:
return False
|
342c9e28fead18d6fc82c40892f6743b1926564a | sofieditmer/cds-visual | /assignments/assignment3_EdgeDetection/edge_detection.py | 4,205 | 3.578125 | 4 | #!/usr/bin/env python
"""
Load image, draw ROI on the image, crop the image to only contain ROI, apply canny edge detection, draw contous around detected letters, save output.
Parameters:
image_path: str <path-to-image-dir>
ROI_coordinates: int x1 y1 x2 y2
output_path: str <filename-to-save-results>
Usage:... |
bed107a24a36afeb2176c3200aec2c525a24a55a | Silicon-beep/UNT_coursework | /info_4501/home_assignments/fraction_class/main.py | 1,432 | 4.21875 | 4 | from fractions import *
print()
#######################
print('--- setup -----------------')
try:
print(f'attempting fraction 17/0 ...')
Fraction(17, 0)
except:
print()
pass
f1, f2 = Fraction(1, 2), Fraction(6, 1)
print(f'fraction 1 : f1 = {f1}')
print(f'fraction 2 : f2 = {f2}')
####################... |
04dbc79957d16af67ab89c8aa72796517db8b5a6 | madboy/adventofcode | /2015/days/twelve.py | 734 | 3.78125 | 4 | #!/usr/bin/env python
import fileinput
import json
def count(numbers, ignore):
if type(numbers) == dict:
if ignore and "red" in numbers.values():
return 0
else:
return count(numbers.values(), ignore)
elif type(numbers) == list:
inner_sum = 0
for e in numb... |
c1f76fc8405ea15ec3d9112ff8efc51c5801fcb5 | Nduwal3/Python-Basics-III | /academy-cli/academy/student.py | 2,517 | 3.703125 | 4 | import csv
class Student:
def __init__(self):
# this.mode = mode
# this.data = data
pass
def file_read_write(self, mode, data=None):
with open ('files/students.csv', mode) as student_data:
result=[]
if mode == 'r':
stude... |
7413ffdb53524a72e59fae9138e1b143a9a2e046 | quanghona/Caro2 | /board.py | 3,919 | 3.515625 | 4 | import os
import curses
import random
class CaroBoard(object):
"""A class handle everything realted to the caro board"""
def __init__(self, width, height):
self.width = width
self.height = height
self.board = [[' ' for x in range(self.width)] for y in range(self.height)]
self._turnCount = 0
def ConfigBoar... |
23aeff17e64ba6acfdcf8c85ae0dab9ae2ebf676 | divanescu/python_stuff | /coursera/webd/func_assn42.py | 926 | 3.765625 | 4 | # Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import urllib
from BeautifulSoup import *
global url
url = raw_input('Enter - ')
position = int(raw_input('Position: '))
def retrieve_url(url):
#url = raw_inpu... |
3474489ac3abf4439f4af04a6f2a69a743e168d6 | divanescu/python_stuff | /coursera/PR4E/assn46.py | 348 | 4.15625 | 4 | input = raw_input("Enter Hours: ")
hours = float(input)
input = raw_input("Enter Rate: ")
rate = float(input)
def computepay():
extra_hours = hours - 40
extra_rate = rate * 1.5
pay = (40 * rate) + (extra_hours * extra_rate)
return pay
if hours <= 40:
pay = hours * rate
print pay
elif hours >... |
a15be41097001cf7f26c42b7dbb076e8ed2bf45c | divanescu/python_stuff | /coursera/PR4E/assn33.py | 347 | 3.84375 | 4 | input = raw_input("Enter Score:")
try:
score = float(input)
except:
print "Please use 0.0 - 1.0 range !"
exit()
if (score < 0 or score > 1):
print "Please use 0.0 - 1.0 range !"
elif score >= 0.9:
print "A"
elif score >= 0.8:
print "B"
elif score >= 0.7:
print "C"
elif score >= 0.6:
prin... |
17d4df0314c967d5cb2192b274b40cf8c3abd248 | Eladfundo/task_1_18 | /Code/nnet/wbg.py | 1,412 | 3.625 | 4 | import torch
def weight_initialiser(N_prev_layer,N_current_layer,device='cpu'):
"""
Initializes the weight in the constructor class as a tensor.
The value of the weight will be w=1/sqr_root(N_prev_layer)
Where U(a,b)=
Args:
N_prev_layer: Number of element in t... |
a6dd4e5cf972068af342c8e08e10b4c7355188e6 | DivyaRavichandr/infytq-FP | /strong .py | 562 | 4.21875 | 4 | def factorial(number):
i=1
f=1
while(i<=number and number!=0):
f=f*i
i=i+1
return f
def find_strong_numbers(num_list):
list1=[]
for num in num_list:
sum1=0
temp=num
while(num):
number=num%10
f=factorial(numbe... |
fa798298cb31dce23c22393e07eaa94e0bb0a655 | DivyaRavichandr/infytq-FP | /ticketcost.py | 511 | 3.765625 | 4 | def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
ticket_amount=0
Rate_per_adult=37550
Rate_per_child=37550/3
ticket_amount=(no_of_adults*Rate_per_adult)+(no_of_children*Rate_per_child)
service_tax=0.07*ticket_amount
total_cost=ticket_amount+service... |
c60d478bce2ff6881160fa2045b2d10860d2730f | DivyaRavichandr/infytq-FP | /sumofdigits.py | 131 | 3.765625 | 4 | def sumofnum(n):
sum=0
while(n!=0):
sum=sum+int(n%10)
n=int(n/10)
return sum
n=int(input(""))
print(sumofnum(n))
|
4f7fdbff2edfa799c9db9ff345873be308face22 | anfauglit/recursion | /prntstr.py | 1,834 | 3.875 | 4 | import random
def print_str(n):
# decompose the integer n and prints its digits one by one
if n < 0:
print('-',end='')
print_str(-n)
else:
if n > 9:
print_str(int(n / 10))
print(n % 10, end='')
def digitsum(n):
# calculate the sum of all its digits
if n < 0:
return digitsum(-n)
else:
if n > 0:
... |
d9f949f598d68412fa4035e6fe8b613d006b4dc3 | AlfredKai/KaiCodingNotes | /LeetCode/Easy/Power of Three.py | 392 | 3.703125 | 4 | class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n == 1:
return True
powOf3 = 3
while powOf3 <= n:
if powOf3 == n:
return True
powOf3 *= 3
return False
a = Solution()
print(a.isPowerOfThree(27))
print(a.isP... |
67b9abf27cf5751ad6b1085fe81235d4b5880d64 | AlfredKai/KaiCodingNotes | /LeetCode/Medium/328. Odd Even Linked List.py | 1,258 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
... |
d31c7945dae63c6f6aff2d57588108bcbc3e492e | AlfredKai/KaiCodingNotes | /LeetCode/Hard/1044. Longest Duplicate Substring.py | 1,255 | 3.625 | 4 | from collections import Counter
class Solution:
def longestDupSubstring(self, S: str) -> str:
def check_size(size):
hash = set()
hash.add(S[:size])
for i in range(1, len(S) - size + 1):
temp = S[i:i+size]
if temp in hash:
... |
14dfc412b8f990b71480104de064457d69f91493 | AlfredKai/KaiCodingNotes | /LeetCode/Medium/Construct Binary Tree from Preorder and Inorder Traversal.py | 1,146 | 3.8125 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder) == 0:
... |
2ecc33dd88220ed4fe133c1260a92bb34a872e5d | AlfredKai/KaiCodingNotes | /LeetCode/Contests/185/1418. Display Table of Food Orders in a Restaurant.py | 1,306 | 3.921875 | 4 | from typing import List
class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
# ["David","3","Ceviche"]
foods = set()
tableNum = set()
tableDish = {}
for order in orders:
tableN = int(order[1])
if (tableN, order... |
72db36b3000749d043e69702b38ef7c345cc99ef | mathtenote01/python | /triple_step.py | 334 | 3.765625 | 4 | def pattern_of_triple_step(N: int):
if N < 0:
return 0
elif N == 0:
return 1
else:
return (
pattern_of_triple_step(N - 1)
+ pattern_of_triple_step(N - 2)
+ pattern_of_triple_step(N - 3)
)
if __name__ == "__main__":
print(pattern_of_tr... |
ccc3586c6e51d05a034f6f02781b0e307ae3a93e | Mariliacaps/teste-python | /CAP05/EXERCICIO05-13.py | 747 | 3.75 | 4 | divida=float(input("Valor da dívida: "))
taxa=float(input("Taxa de juros mensal (Ex.: 3 para 3%):"))
pagamento=float(input("Valor a ser pago mensal: "))
mes=1
if (divida*(taxa/100)>= pagamento):
print("O juros são superiores ao pagamento mensal.")
else:
saldo = divida
juros_pago=0
while saldo>pagamento:... |
763f30a67c364954d0b3539145857295a684329f | Mariliacaps/teste-python | /CAP03/EXERCICIO3-7.py | 264 | 3.890625 | 4 | #programa que peça 2 numeros inteiros e imprima a soma dos 2 numeros na tela
numero01=int(input("Digite o primeiro numero: "))
numero02=int(input("Digite o segundo numero: "))
resultado=numero01+numero02
print(f"o resultado da soma dos numeros é: {resultado} ")
|
5703e7ab721d71cb537c3eb659ea65352c81d4d1 | Mariliacaps/teste-python | /CAP04/programa4-3.py | 281 | 4.09375 | 4 | salario=float(input("Digite o salario para o calculo do imposto: "))
base=salario
imposto=0
if base>3000:
imposto=imposto+((base-3000)*0.35)
base=3000
if base>1000:
imposto=imposto+((base-1000)*0.20)
print(f"salario: R${salario:6.2f} imposto a pagar: R${imposto:6.2f}") |
be1ae90fe39e8bfdc0b0bc64ab50ba9c62650c8e | tobetobe/python_start | /hello.py | 504 | 4 | 4 | # for index, item in enumerate(['a', 'b', 'c']):
# print(index, item)
def printHello():
""" say Hello to the console
Just print a "hello
"""
print("hello")
# printHello()
# list = ['bca', 'abc', 'ccc']
# sorted(list)
# print(list)
# list = [v*2 for v in range(1, 10)]
# print(list)
list = ['... |
580a0daea555236dcc97ca069180fc26d3cb1093 | yangtuothink/Python_AI_note | /other_add/sock(key=) demo.py | 372 | 4 | 4 | """
sort() 函数内含有 key 可以指定相关的函数来作为排序依据
比如这里指定每一项的索引为1 的元素作为排序依据
默认是以第一个作为排序依据
"""
def func(i):
return i[1]
a = [(2, 2), (3, 4), (4, 1), (1, 3)]
a.sort(key=func) # [(4, 1), (2, 2), (1, 3), (3, 4)]
# a.sort() # [(1, 3), (2, 2), (3, 4), (4, 1)]
print(a)
|
87f3692eb4df2e6e113a4c71f00a09712d29b89c | MrWater/XPyTest | /Python/GUI/test_listbox.py | 1,019 | 3.546875 | 4 | import tkinter
root = tkinter.Tk()
# selectmode: single multiple browse(移动鼠标进行选中,而不是单击选中) EXTENDED支持shift和ctrl
listbox = tkinter.Listbox(root, selectmode=tkinter.MULTIPLE)
listbox.pack()
for i in range(19):
listbox.insert(tkinter.END, i)
listbox = tkinter.Listbox(root, selectmode=tkinter.BROWSE)
listbox.pack()
... |
1d1a37c8933d54fe5f697a5718b13d09233dda7c | MrWater/XPyTest | /cv/test.py | 121 | 3.546875 | 4 | #-*-coding:utf8-*-
import numpy as np
arr = np.random.random((2, 2, 2, 3))
print(arr)
np.random.shuffle(arr)
print(arr) |
1e629e6a649ca028d7eef107d2e51f98a96c0f46 | D4N-W4TS0N/Python-Lockdown | /while_loops.py | 75 | 3.671875 | 4 | i = 1
while i <= 10:
print(i * "this is a while loop")
i = i + 1 |
4d4c2670577d87081d1404c1414ecda037d8f769 | psk264/rock-paper-scissors | /game.py | 3,680 | 4.15625 | 4 | # game.py
# Rock-Paper-Scissors program executed from command line
#import modules to use additional third party packages
import random
import os
import dotenv
#Input command variation, using print and input
# print("Enter your name: ")
# player_name = input()
#Above statements can be reduced to single line of cod... |
ecbd94b636438891fa11ed64943fa66eef961d00 | ezeutno/All_Comp_Math_Assignment | /Exam Simulation/Data.py | 2,014 | 3.84375 | 4 | from sympy import *
import numpy as np
import math as m
import matplotlib.pyplot as plt
#Latihan Exam BiMay
#Number 1
def fact(num):
res = 1
for i in range(1,num+1):
res *= i
return res
def Maclaurin(x,n):
res = 0
if type(n) is np.ndarray:
data = []
for a in np.nditer(n):... |
caded9115b67830a704ea736272a43d4923b7a90 | Jeduroid/intermediate-python-course | /dice_roller.py | 537 | 3.953125 | 4 | import random
def main():
dice_rolls = int(input('\nHow many dice you want to roll : '))
dice_size = int(input('\nHow many sides a dice have : '))
dice_sum = 0
for i in range(0,dice_rolls):
roll = random.randint(1,dice_size)
dice_sum += roll
if roll == 1:
print(f'You rolled a {roll} ! Critic... |
f0b385abec60ac9edaa7d68ea9cceb83c52062e1 | ktheylin/ProgrammingForEveryone | /Python-GettingStarted/assg4-6.py | 278 | 3.828125 | 4 | def computepay(hrs, rate):
if hrs <= 40:
gross_pay = hrs * rate
else:
gross_pay = 40 * rate + ( (hrs - 40) * (rate * 1.5) )
return(gross_pay)
hrs = float(raw_input("Enter Hours: "))
rate = float(raw_input("Enter Rate per Hour: "))
print computepay(hrs,rate)
|
3abb8b828e114b048fd19d232e858e0f204f2901 | ktheylin/ProgrammingForEveryone | /Python-WebAccessData/week4-followLinks.py | 733 | 3.5 | 4 | # Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import urllib
from BeautifulSoup import *
tag_index = 17
loop = 7
count = 0
#url = 'http://pr4e.dr-chuck.com/tsugi/mod/python-data/data/known_by_Fikret.... |
36f889bbd9010c826012a2e0b12600aba9ab9ee3 | Leo-Simpson/c-lasso | /classo/stability_selection.py | 5,674 | 3.59375 | 4 | import numpy as np
import numpy.random as rd
from .compact_func import Classo, pathlasso
"""
Here is the function that does stability selection. It returns the distribution as an d-array.
There is three different stability selection methods implemented here : 'first' ; 'max' ; 'lam'
- 'first' will compute the w... |
bb18f87d4e9fe1d0489fe3f833200955d9d80e80 | ysabhi1993/Python-Practice | /Queue_imp.py | 1,305 | 3.953125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.nextnode = None
class Queue:
def __init__(self):
self.head = None
self.size = 0
def IsEmpty(self):
return self.head == None
def enqueue(self, data):
currentnode = None
... |
c4c527c574ca40c828dacc7da03a6216a946f53c | ysabhi1993/Python-Practice | /useful_functions.py | 7,609 | 3.984375 | 4 | #Checks if a number is even or odd
def checkOE():
num = int(input("Enter a number:"))
if num%2 == 1:
print('The number you entered is odd')
elif num%4 == 0:
print('The number you entered is divisible by 4')
else:
print('The number is even')
#prints out a string th... |
47358be77fec8fc5229dfb73736cb8a92f74e406 | nan0314/RRTstar | /RRTstar.py | 12,203 | 3.640625 | 4 | import pygame
import random as r
import pylineclip as lc
############################################
## Constants
############################################
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
PURPLE = (128,0,128)
#... |
4f32d0b2293ff8535a870cd9730528ecf4874190 | comedxd/Artificial_Intelligence | /2_DoublyLinkedList.py | 1,266 | 4.21875 | 4 | class LinkedListNode:
def __init__(self,value,prevnode=None,nextnode=None):
self.prevnode=prevnode
self.value=value
self.nextnode=nextnode
def TraverseListForward(self):
current_node = self
while True:
print(current_node.value, "-", end=" ")
... |
85f7053fa27c235f58c6042f625a691c47f622c0 | comedxd/Artificial_Intelligence | /0-13-Nested_Function_NON_Local_variables.py | 297 | 3.578125 | 4 | # Defining the nested function only
def print_msg(msg):
def printer():
print(msg) #nested function is accessing the non-local variable 'msg'
printer()
print("i am outer function")
printer() # calling the nested function
# driver code
print_msg("this is message") |
b45abb8df2533c41170f40dcbd293c6c58ab29fc | comedxd/Artificial_Intelligence | /0-5-dataprotection.py | 403 | 3.890625 | 4 | class Square:
def __init__(self):
self._height = 2
self._width = 2
def set_side(self,new_side):
self._height = new_side # variables having name starting with _ are called protected variables
self._width = new_side # protected variable can be accessed outside class
square = Squar... |
76348acf643b1cd9764e1184949478b3b888b014 | jdipendra/asssignments | /multiplication table 1-.py | 491 | 4.15625 | 4 | import sys
looping ='y'
while(looping =='y' or looping == 'Y'):
number = int(input("\neneter number whose multiplication table you want to print\n"))
for i in range(1,11):
print(number, "x", i, "=", number*i)
else:
looping = input("\nDo you want to print another table?\npress Y/y for yes and... |
e6e94d3d50a56f104d1ad9993d78f8c44394b753 | jdipendra/asssignments | /check square or not.py | 1,203 | 4.25 | 4 | first_side = input("Enter the first side of the quadrilateral:\n")
second_side = input("Enter the second side of the quadrilateral:\n")
third_side = input("Enter the third side of the quadrilateral:\n")
forth_side = input("Enter the forth side of the quadrilateral:\n")
if float(first_side) != float(second_side) and flo... |
a7b9b32d1a9e5ee6c7cf1a3b1556a5140a0c98d9 | jdipendra/asssignments | /mine calculator.py | 4,012 | 4.46875 | 4 |
import sys
menu = True
def calculator():
print("You can do the following mathematical operations with BRILLIANT-CALCLATOR APP")
print("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Square Root\n6.Square\n7.Exponential\n8.nth Root")
choice = int(input("Enter Your choice"))
condition = 'Y'
... |
a45c34fe97086442b252db0c6f9fd373d5cb6100 | potroshit/Data_science_basic_1 | /home_work_1/home_work_1_Avdeev.py | 644 | 3.859375 | 4 | # задание 1
arr = [1, 2, 3, 4, 5, 6, 7, 8]
for i in arr:
if i % 2 == 0:
a1 = i
a2 = [i] * i
print(a1, a2)
# задание 2
x = int(input())
y = int(input())
if -1 <= x <= 1 and -1 <= y <= 1:
print("принадлежит")
else:
print("нет")
# задание 3
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
... |
bacbbfa0ee5a53bbf8d572568d0555d2696e0514 | potroshit/Data_science_basic_1 | /home_work_1/Клачев_Максим_10И2.py | 760 | 3.609375 | 4 | #a = input('Ввести имя: ')
#a = list(a)
#a = a[1:-1]
#b = input('Ввести класс: ')
#a.append(b)
#c = input('Ввести фамилию: ')
#a+=c
#print(a)
#1
j = [1, 2, 3, 4, 5, 6, 7]
u = [[i]*i for i in j if i % 2 == 0]
print(j[i], u)
#2
x = int(input())
y = int(input())
if -1<= x <= 1 and -1 <= y <= 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.