blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
f639ea72b2d14b05d3439a521f86379e2590af76 | simplylizz/trash | /interviews/nplan_hr2.py | 1,048 | 3.75 | 4 |
def number_of_sub_paths(a):
row_sum = [0] * len(a[0])
row_sum[0] = 1
for row in range(len(a)):
for col in range(len(a[0])):
if row == 0 and col == 0:
continue
if not a[row][col]:
row_sum[col] = 0
else:
if col > 0... |
567a0222228c2ec89621b09d2f5c7500dfad1f4e | Neyzoter/Algorithm_OJ | /Algorithm_py/atoiFun_py/atoi.py | 1,340 | 3.71875 | 4 | '''
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。若整数超出了32位整数的范围,如果是正整数则返回 INT_MAX(2147483647),或者如果是负整数则返回 INT_MIN(-2147483648)。
格式:
输入行每一行输入一个字符串,最后每一行输出经过转换后得到的整数。
样例输入
"10"
"-1"
"123123123123123"
"1.0"
样例输出
10
-1
2147483647
1
'''
import re
import math
def atoi(string):
positiveBIGEST = int(... |
17aeb081b24147badad1e1945acae197fe287d43 | BawangGoh-zz/ELEC0088-Lab | /Exercise2.py | 1,122 | 4.125 | 4 | ## Part 1) Implement a DNS querying program that stores the mapping between the names
## into IP addresses. Explicitly define the name of the network into the databases
## Part 2) Allow for the user to query several types of NS record (NS, MX, etc).
# IP addresses query
def IPquery(dct, string):
return dct.get(stri... |
c9cbdfe4bf4f59152605c79c34ab40b4ce8248f7 | SpawNKZ/pycoingecko | /task1.py | 416 | 3.75 | 4 | def permutations(arr):
arr1 = arr.copy()
print(" ".join(arr1), end=" ")
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
p... |
0ac9ea93dd1a9cc31946535c2b6982052f6e7c60 | moosuchot/handyscripts | /pyscript/add_list.py | 473 | 4.25 | 4 | #!/usr/bin/env python
#coding:utf-8
'''
得到n个相同长度list的对应位置的和后的list.
比如:
a = [1,2,3,4]
b = [5,6,7,8]
求两个list的和.
结果为:
c = [6,8,10,12]
'''
def add_list(*lsts):
merged_list = []
for i in xrange(len(lsts[0])):
merged_list.append(sum([lst[i] for lst in lsts]))
return merged_list
if __name__ == '__main__'... |
fb6dc41965bf477fdaa75b40a216f95e61dace88 | lou024/BinaryHexConverter | /BinaryHexConverter.py | 1,064 | 3.734375 | 4 |
def DecimalToBinaryRec(num, out):
if num >= 1:
out+=DecimalToBinaryRec(num//2,out)
out+=str(num%2)
return out
def DecimalToBinary(num):
out = DecimalToBinaryRec(num,"")
print(out)
def DecimalToHexRec(num, out):
if num < 0:
out+="0"
elif num <= 1:
out+=s... |
ff746957eac224baeb7c47522ea4eb4edb576f0e | Ahisanz/luizacode | /python/ana_sanz_adivinha2.py | 1,331 | 4.125 | 4 | import random
print("Seja bem vindo! Qual é o seu nome?")
user_name = input()
print(f"Prazer, {user_name}, vou te explicar as regras do jogo, primeiro eu vou pensar em um número de 1 a 20.")
random_number = random.randint(1, 21)
print()
print("Pronto, pensei! Agora eu vou te dar 6 chances para acertar qual é o número... |
222ff971a2cd98b5e876a9b3d9c9e4c7ec891793 | Ahisanz/luizacode | /python/exercio1_dia1.py | 577 | 4.25 | 4 | '''
Crie um programa que peça o nome do usuário, diga que é um prazer conhecê-lo e pergunte a idade dele.
O programa se apresentará como um robô - pode inventar o nome - e dirá quantos anos mais velhos que o usuário ele é.
O robô tem 107 anos
Não se preocupar se o usuário já fez aniversário ou não
'''
print("Olá, qu... |
9645553e9439806422e4224f7107f8d7402cbb21 | Aleks4920/Python_Algorithms | /Sort/BubbleSort.py | 346 | 3.984375 | 4 |
def bubble(list):
indexeingLength = len(list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexeingLength):
if list[i] > list[i+1]:
sorted = False
list[i], list[i+1] = list[i+1], list[i]
return list
print(bubble([5,8... |
63ddb2acd37a397a35f4ce9ff68bd2277a920366 | Sa911-rgb/server-connection-and-load-management-using-Python-OOP | /serverConnLoad_man.py | 3,244 | 3.703125 | 4 | #Begin Portion 1#
import random
class Server:
def __init__(self):
"""Creates a new server instance, with no active connections."""
self.connections = {}
def add_connection(self, connection_id):
"""Adds a new connection to this server."""
connection_load = random.random()*10+1
... |
8c681b4a606cef9e70aa5c3cb3bb0bf253502aed | guilherme-witkosky/MI66-T5 | /Lista 5/L5E09.py | 245 | 4.03125 | 4 | value = int(input("Informe um valor:"))
def reservo(value):
rever = 0
while value > 0:
rever *=10
rever += value % 10
value//=10
return rever
print("O reverso do valor informado é: ",reservo(value))
|
3b1e7a7c7b1e8267ff2874a1f7cace99feb43891 | guilherme-witkosky/MI66-T5 | /Lista 2/L2E17.py | 298 | 3.984375 | 4 | #Faça um Programa que peça um número correspondente a um determinado ano e
#em seguida informe se este ano é ou não bissexto.
ano = int(input("Informe o ano: "))
if ano % 100 != 0 and ano % 4 == 0 or ano % 400 == 0:
print("É ano bissexto")
else:
print("Não é ano bissexto") |
a48867d01dbbd259e0cddf2a0349d9a10b4b99fa | guilherme-witkosky/MI66-T5 | /Lista 2/L2E02.py | 258 | 4.15625 | 4 | #Faça um Programa que peça um valor e mostre
#na tela se o valor é positivo ou negativo.
#Exercício 2
num = float(input("Informe um numero: "))
if num >=0:
print("O numero digitado e positivo")
else:
print("O numero digitado e negativo") |
1f3efcc02d4df2da2abb98a0161ef23a4accfe15 | guilherme-witkosky/MI66-T5 | /Lista 2/L2E22.py | 297 | 3.9375 | 4 | #Faça um Programa que peça um número inteiro e determine se ele é par ou impar. Dica: utilize o operador módulo (resto da divisão).
#Exercicio 22
num = int(input("Digite um numero para ver se ele é par ou nao: "))
if (num % 2) == 0:
print(num, "eh par")
else:
print(num, "eh impar")
|
7df8038be3cbd4f3d80a266420efa8ff3ebd258f | guilherme-witkosky/MI66-T5 | /Lista 2/L2E10.py | 711 | 4.15625 | 4 | #Exercício 10
print("Informe o período em que você estuda:")
print("(M) Matutino")
print("(V) Vespertino")
print("(N) Noturno")
print("------------------------------------------")
p = input("Seu Período = ")
print("------------------------------------------")
periodo = p.upper()
print("=================================... |
a4cdc0398eeb2cd320b44853eed9a0e8ffdaa08a | guilherme-witkosky/MI66-T5 | /Lista 1/L1E13.py | 546 | 4.0625 | 4 | #Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando as seguintes fórmulas:
#Para homens: (72.7*h) - 58
#Para mulheres: (62.1*h) - 44.7
print("Digite sua altura:")
altura = input()
print("Digite H para homem ou M para mulher:")
genero = input()
... |
242f4e0d36978026ba5458e18defc7cb67668422 | guilherme-witkosky/MI66-T5 | /Lista 1/L1E11.py | 627 | 4.40625 | 4 | #Exercício 11
#Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# A) o produto do dobro do primeiro com metade do segundo.
# B) a soma do triplo do primeiro com o terceiro.
# C) o terceiro elevado ao cubo.
int1 = int(input('Informe um numero inteiro: '))
int2 = int(input('Informe outr... |
cbadf66f545420b16f50d1dd0496362185b1da0e | guilherme-witkosky/MI66-T5 | /Lista 4/L4E21.py | 628 | 3.65625 | 4 | i = 0
carro = []
consumo = []
maisEconomico = None
auxEconomico = 0
while i < 5:
print("Veiculo", (i+1))
carro.append(input("Nome: "))
consumo.append(float(input("Km por litro: ")))
if maisEconomico == None:
maisEconomico = i
auxEconomico = consumo[i]
if auxEconomico <=... |
46deca034d9b1048e58bac253150af52f96b56de | guilherme-witkosky/MI66-T5 | /Lista 5/L5E07.py | 1,793 | 3.84375 | 4 | #Faça um programa que use a função valorPagamento para determinar o valor
#a ser pago por uma prestação de uma conta.
#O programa deverá solicitar ao usuário o valor da prestação
#e o número de dias em atraso e passar estes valores para a função valorPagamento,
# que calculará o valor a ser pago e devolverá este... |
b2c8d209db76afe3959cb2a10117366c133f5008 | guilherme-witkosky/MI66-T5 | /Lista 2/L2E16.py | 1,214 | 4.1875 | 4 | #Exercicio 16
#Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e
#fazer as consistências, informando ao usuário nas seguintes situações: Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o
#pr... |
9e57dd670e6db3e1e088b4f81eb119de922843ea | guilherme-witkosky/MI66-T5 | /Lista 4/L4E17.py | 590 | 3.671875 | 4 | posicao = ["Primeiro","Segundo","Terceiro","Quarto","Quinto"]
salto= [0] * 5
media = 0
nome = " "
while nome != '':
nome = input("Atleta: ")
if nome =='':
break
for x in range(5):
print("%s Salto:"%(posicao[x]))
salto[x]= ((float(input())))
media = sum(salto)/len(salto... |
e7f40cd8505e56aac570d739189b4320ee5f7f59 | guilherme-witkosky/MI66-T5 | /Lista 2/L2E14.py | 971 | 3.84375 | 4 | #Faça um programa que lê as duas notas parciais obtidas por um aluno
#numa disciplina ao longo de um semestre, e calcule a sua média.
#A atribuição de conceitos obedece à tabela abaixo:
#Média de Aproveitamento Conceito
#Entre 9.0 e 10.0 A
#Entre 7.5 e 9.0 B
#Entre 6.0 e 7.5 C
#Entre 4.0 e 6.0... |
cfb9c4ef970460ca2ff947af7e309b857bc98d66 | guilherme-witkosky/MI66-T5 | /Lista 3/L3E17.py | 200 | 3.875 | 4 | num = int(input("informe um numero inteiro:"))
fatorial = 1
x = num
while x>=1:
print(x,".")
fatorial = fatorial*x
x -= 1
print("Valor total do Fatorial do %d = %d "%(num,fatorial)) |
8c180b5c53bc9a211ec88c7a4477987a307f0ed9 | guilherme-witkosky/MI66-T5 | /Lista 8/L8E05.py | 1,310 | 4.125 | 4 | #Classe Conta Corrente: Crie uma classe para implementar uma conta corrente.
#A classe deve possuir os seguintes atributos: número da conta, nome do correntista e saldo.
# Os métodos são os seguintes: alterarNome, depósito e saque; No construtor, saldo é opcional,
# com valor default zero e os demais atributos são... |
3b74fb42da7176354da23e83a4ac72467ecfc515 | guilherme-witkosky/MI66-T5 | /Lista 1/L1E08.py | 370 | 3.859375 | 4 | #Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
# Calcule e mostre o total do seu salário no referido mês.
print("Digite o valor hora:")
valorHora = input()
print("Digite as horas trabalhadas:")
horasTrabalhadas = input()
print("Valor total a receber: ", (fl... |
9d3f032818814ffe409eb8345176e31c87c29900 | rthompson1313/scheduler | /Shift_Tracker.py | 3,003 | 4.125 | 4 | '''
Written by Ryan Thompson.
Classes to define and manage the lists of shift objects
'''
class Shift:
'''defines the parameters of a shift object'''
def __init__(self):
self.ID = None
self.Day = None
self.Position = None
self.Employee = None
self.Start = None
s... |
d5f7b6cbab6a8cd5e0113375fd16b13488c5acbf | MarcoDC1990/CursoPython | /assert sqrt.py | 187 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 08:48:27 2021
@author: mdcor
"""
import math
x=float(input("Enter a number:"))
assert x>=0.0
x=math.sqrt(x)
print(x) |
602cb0a25d289a45af6b5dbe07dc1d42f0d6e93d | DUcepticons/Bangla-Handwriting | /Approach 2 - Letter 11 classes and Quality 4 classes/NPY Create Quality.py | 2,095 | 3.796875 | 4 | # Python program to create
# Image Classifier using CNN
# Importing the required libraries
import cv2
import os
import numpy as np
from random import shuffle
from tqdm import tqdm
'''Setting up the env'''
LOCATION = 'D:\Github Projects\Bangla-Handwriting\Datasets\Bangla Handwriting Dataset - Augmented'... |
8a0a9d68892f0dbac3b8e55eb69e82f1788cc05e | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-4-Partition.py | 1,801 | 4.3125 | 4 | # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "... |
9246b0c5bb0572e066c5df27178fe521d1587050 | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-7-Intersection.py | 1,439 | 4.03125 | 4 | # Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting
# node. Note that the intersection is defined based on reference, not value. That is, if the kth
# node of the first linked list is the exact same node (by reference) as the jth node of the second
# linked lis... |
e2a354f7de78bb119094313ee9b25118e374ca6c | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-8-Loop-Detection.py | 1,334 | 4.09375 | 4 | # Loop Detection: Given a circular linked list, implement an algorithm that returns the node at the
# beginning of the loop.
# DEFINITION
# Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so
# as to make a loop in the linked list.
# EXAMPLE
# Input: A -> B -> C ... |
916e56609b6740bc7b529d0013af642ac24d2f84 | Post-mega/My-VSCode | /dropEgg.py | 670 | 3.625 | 4 |
# 当前拥有的鸡蛋数K 需要测试的楼层数N
def superEggDrop(K, N):
memo = dict()
def dp(K, N):
# base case
if K == 1:
return N
if N == 0:
return 0
if (K, N) in memo:
return memo[(K, N)]
res = float('INF')
for i in range(1, N + 1):
... |
203974320beaa486eee4c160ff83df0d3aa00ec7 | mehdi-ahmed/python-introduction | /unpacking.py | 241 | 3.765625 | 4 | coordinates = (1, 2, 3)
# x = coordinates[0]
# y = coordinates[1]
# z = coordinates[2]
# Same result can be achieved with
x, y, z = coordinates
print(z) # 3
# works also with lists..
a_list = [5, 8, 9]
x2, y2, z2 = a_list
print(y2) # 8
|
2e647299d56411c95a3887bad6f308b831848b67 | mehdi-ahmed/python-introduction | /exceptions.py | 234 | 3.953125 | 4 | try:
age = int(input("Age ?: "))
income = 2000
risk = income / age
print(age)
except ValueError:
print('Invalid value, please insert Integers only')
except ZeroDivisionError:
print('Age should not equal to 0')
|
4b1ebd55b7d822ebc960ea8c224e08402e25e23c | jimsun25/python_practice | /guess_the_number/main.py | 1,204 | 3.984375 | 4 | import random
from art import logo
def compare(num):
global TARGET
if num == TARGET:
return True
elif num > TARGET:
print("Too large~XD")
return False
else:
print("Too small~www")
return False
print(logo)
print('Welcome to "Guess The Number"!')
print("Yourtarget is a number between 1 and 1... |
6c3b5c12c863b87a0c1d0cdb3ddc164caafb5862 | jimsun25/python_practice | /turtle_race/main.py | 927 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_pos = [-75, -45, -15, 15, 4... |
8b3fdcc4f18805475b7c3318ad94b05af3177808 | jimsun25/python_practice | /snake_game/scoreboard.py | 1,353 | 3.859375 | 4 | from turtle import Turtle
FONT = ("Arial", 12, "normal")
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.pencolor("White")
self.speed("fastest")
self.hideturtle()
self.penup()
self.goto(150, 288)
self.pendown()
se... |
42f925c5bebc10ccf49921f5c76b891c6291d61f | CodingFULr/Projects | /ToDoList.py | 1,167 | 4.09375 | 4 |
list = ""
num_of_errands = 1
hint_value = 3
print("\nWelcome to your To-Do List!\n\nPlease enter your errands one-by-one."
"\nType \"done\" when complete.\n")
answer = input("What do you want to do? ").capitalize()
while answer != "done":
if num_of_errands != hint_value:
list += answer
... |
73bf1bab9933becb8966173dfe1f5dad8fbd402b | BotaoFan/customers_loss | /base.py | 624 | 3.59375 | 4 | import pandas as pd
import numpy as np
def check_col_exist(df,col_name):
'''
Check is col_name is a name of df's columns
:param df: DataFrame
:param col_name: str
:return: None
'''
if col_name in df.columns:
return None
else:
raise KeyError("Data doesn't contain column n... |
f5bec7a1b43eef8e52f16ad86dac3fe98ac81999 | bowhua21/AdvancedCS-code | /recursion.py | 1,452 | 3.890625 | 4 |
def merge(li):
left = []
right = []
if len(li) != 1:
for i in range(0, len(li)//2):
left.append(li[i])
for i in range(len(li)//2, len(li)):
right.append(li[i])
else:
return li
left = merge(left)
right = merge(right)
for i in range(len(li)):
... |
f5f9dc8646c6e16b68dfed9ec46ef70328964ecd | jorge800/pythonLanguage | /arithmetic.py | 564 | 4.1875 | 4 | # Python Arithmetic Operators.
# Let x = 34 and y = 78, then find z;
x = 34 # Let x = 34
y = 78 # y = 78
z = (x + y) # Addition Operator
print("Addition:\n"+str(z))
z = (x - y) # Substraction Operator
print("Substraction:\n"+str(z))
z = (x * y) # Multiplication Operator
print("Multiplication:\n"+str(z))
z = (x / y) # ... |
b0f30c848c9fb38c7701ba1c38854405591fd7df | jorge800/pythonLanguage | /simpleCalculator.py | 340 | 3.984375 | 4 | # Python Simple Calculator
def add():
print("Enter first number: ")
num = float(input())
print("Enter another number: ")
var = float(input())
sum = float((num + var))
print("The sum is: "+str(sum)+".")
print("Do you want to exit?")
check = str(input())
if check == "Y" or check == 'y':
exit()
els... |
75b924d2cd3b4d9196e806e3edf97a422785bb23 | dotzo/AdventOfCode2019 | /Day7.py | 904 | 3.640625 | 4 | # https://adventofcode.com/2019/day/7
from util import filehelper as fh
from IntCode import IntComputer
from itertools import permutations
program = fh.csv_to_list('day7-input.txt')
def amplifyer(phase):
computers = []
for p in phase:
computers.append(IntComputer(program, inputs=[p], wait_for_input=T... |
1d576a673bffd1c5b70a779994f9d1657a8604a3 | JAaron93/cs-guided-project-python-ii | /src/task_5.py | 414 | 4 | 4 | # Given an array of integers, return the sum of all the positive integers in the array.
# Examples:
# csSumOfPositive([1, 2, 3, -4, 5]) -> 1 + 2 + 3 + 5 = 11
# csSumOfPositive([-3, -2, -1, 0, 1]) -> 1
# csSumOfPositive([-3, -2]) -> 0
# Notes:
# If the input_arr does not contain any positive integers, the default su... |
640c29360422140d29305d066f67a8b6cc12243a | lindongyuan/study2020 | /project/Chapter_09/c9-7_try.py | 1,205 | 3.921875 | 4 | class User():
def __init__(self,first_name,last_name,age):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.login_attempts = 100
def describe_user(self):
print("first name: " + self.first_name)
print("last name: " + self.last_name)
... |
8662ab19729cccfeb83258de93f5ac74a254a425 | lindongyuan/study2020 | /project/9-6-test.py | 1,416 | 3.921875 | 4 | #test 9-6
class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
#初始化属性restaurnt_name、cuisine_type
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.restaurant_name.title... |
9c478158e6a1e13a84e6bf0af269200d674fd3b8 | lindongyuan/study2020 | /project/7-8-test.py | 2,384 | 4.09375 | 4 | '''
#7-8 创建一个名为 sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为 finished_sandwiches的空列表。
#遍历列表 sandwich_orders,对于其中的每种三明治,都打印一条消息,如 I made your tuna sandwich,并将其移到列表finished_sandwiches。
#所有三明治都制作好后,打印一条消息,将这些三明治列出来。
sandwich_orders = ['Tuna','Chicken','Baconic','Beef','pastrami']
finished_sandwiches = []
while sandwich_ord... |
3a6e8404bf6fd03a2cacb86d9b7d91916d75df68 | lindongyuan/study2020 | /project/9-1-test.py | 1,154 | 3.796875 | 4 | #test 9-1
class Restaurant():
'''9-1 餐馆'''
def __init__(self,restaurant_name,cuisine_type):
'''初始化属性restaurnt_name、cuisine_type'''
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.restaurant_name.title())
... |
59f1fba9b1026bb0e67924f4884fd8b143e886d3 | lindongyuan/study2020 | /wangke.py | 7,584 | 3.53125 | 4 | """ 通过selenium 实现刷课程序
超星平台
url: http://passport2.chaoxing.com/login?fid=&refer=http://i.mooc.chaoxing.com
"""
from selenium import webdriver
import requests
import yun_code
import time
import random
import easygui as g
class chaoxing_spider():
def __init__(self, user_name, user_password, school_na... |
06022472f268b603c38a1106e89835f10c5cb6e6 | priyamsahoo/snmp-covert-chat | /caesar_cipher.py | 684 | 3.609375 | 4 | from globals import ALPHABET
# This class encrypts and decrypts the messages.
class CaesarCipher:
def __init__(self, shift):
self.alphabet = ALPHABET
self.encrypt_alphabet = self.alphabet[shift:] + self.alphabet[:shift]
self.decrypt_alphabet = self.alphabet[-shift:] + self.alphabet[:-shift]... |
9975a9ff9b7ae49726b0de3f3e2390b7a324cdf8 | Zabehalin/Python | /23.03.2020/23.03.2020.py | 5,238 | 3.953125 | 4 | # Протягом тижня вимірювали температуру повітря. Знайти кількість днів, коли температура перевищувала 10o С.
# exit = True
# while exit:
# for i in range(1, 8):
# if i == 1:
# Monday = int(input("Monday ℃ = "))
# elif i == 2:
# Tuesday = int(input("Tuesday ℃ = "))
# ... |
5ea55e33008331adc88711b066bb2de4c544c973 | Xiaoxiong-Liu/leetcode-easy | /string/isPalindrome.py | 877 | 3.984375 | 4 | """
验证回文字符串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/36/
"""
class Solution:
def isPalindrome(self, s):
... |
ebd918b4ba62d7cac2480b9535bdcdfdee4dd0f6 | Xiaoxiong-Liu/leetcode-easy | /array/rotate.py | 1,285 | 3.734375 | 4 | class Solution:
# def rotate(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: void Do not return anything, modify nums in-place instead.
# """
# if len(nums) == 0 or len(nums) == 1:
# return
# k = k%len(nums)
# self.re... |
bd97997f71f2124d32f65580e0f9f7be3c5224cb | Xiaoxiong-Liu/leetcode-easy | /linkedList/isPalindrome.py | 1,188 | 3.90625 | 4 | """
回文链表
请判断一个链表是否为回文链表。
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/45/
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
... |
bcbed9094751a49494bdeaf5b1e540015a5b350d | Xiaoxiong-Liu/leetcode-easy | /array/twoSum.py | 955 | 3.578125 | 4 | """
两数之和
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
... |
7911262c90dcddc92d57b7f2855a55e82763ed93 | Xiaoxiong-Liu/leetcode-easy | /sorting-and-searching/merge.py | 1,322 | 4.03125 | 4 | """
合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
https://leetcode-cn.com/explore/interview/card/top-interview-quest... |
c91d193ce1101e6a8b2490dfc1fbc19dd8c8ec98 | Amory0709/Python | /Data-Structure-and-Algorithm/BinaryTreeLevelOrderTraversal.py | 967 | 3.703125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def levelOrder(self, root):
# use preOrderTraverse and B... |
36dd42c1f3b049217f5a12afa0adef4cc28559b8 | Amory0709/Python | /Numpy/CreateDiagonalMatrixWithOffSet.py | 346 | 3.65625 | 4 | '''
To create a matrix look like this:
1 1 0 0 0 0 0
1 1 1 0 0 0 0
0 1 1 1 0 0 0
0 0 1 1 1 0 0
0 0 0 1 1 1 0
0 0 0 0 1 1 1
0 0 0 0 0 1 1
'''
import numpy as np
# generate matrix
a = np.zeros((7,7),int)
# change diag, fill_diagnoal generate inplace
np.fill_diagonal(a, 1)
np.fill_diagonal(a[1:], 1)
np.... |
b8ee4804c73a956a36f4b00d94d50551149a2ad5 | sdahal1/pythonoctober | /fundamentals/python_fun/bootleg_functionsbasic2.py | 1,213 | 4.65625 | 5 | # CountUP - Create a function that accepts a number as an input. Return a new list that counts up by 1, from 1 (as the 0th element) up to num (as the last element).
# Example: countup(5) should return [1,2,3,4,5]
# Print and Return - Create a function that will receive a list with three numbers. Print the second val... |
d7225927df5c261b552dd3851d8c8716cd6f9f01 | hilmanmakarim/fundamental-phyton | /python/2/Tugas1.py | 1,302 | 3.734375 | 4 |
hargaApel = 10000
hargaAnggur = 15000
hargaJeruk = 20000
qtyApel = 5
qtyAnggur = 7
qtyJeruk = 8
Apel = int(input('Berapa apel yang ingin dibeli ? '))
if Apel > qtyApel :
print ('Kesalahan dalam input karena stock yang ada hanya 5 apel')
while Apel > qtyApel :
Apel = int(input('Berapa apel yang ingin di... |
5c3ca65988e85ec4f66dd95a137c208f0c446384 | hilmanmakarim/fundamental-phyton | /python/4/cek.py | 2,688 | 3.71875 | 4 | # filter integer dari string
# filter_list([1,2,'a','b']) == [1,2]
# filter_list([1,'a','b',0,15]) == [1,0,15]
# filter_list([1,2,'aasf','1','123',123]) == [1,2,123]
# filter_list[1,2,'a','b']
# def filter_list(l):
# new_list = []
# for x in l:
# if type(x) == int:
# new_list.append(x)
# ... |
32934165d30254d225f30380000a4fa021e58c04 | hilmanmakarim/fundamental-phyton | /python/1/belajar1soal1.py | 1,361 | 3.859375 | 4 | # solve 1
solve1 = 'solve 1'
print(solve1)
import math
x = 4
y = 3
z = 2
w =((x+y*z)/(x*y))**z
print(w)
result = (x+y*z)/(x*y)
hasil = math.pow(result, z)
print(hasil)
next = input('tekan enter apabila ingin lanjut ke solve berikutnya')
# solve 2
solve2 = 'solve 2'
print(solve2)
# meminta input dari user, disimpan ... |
12ba61f64c3aa3756512670d926ab8450e09aaff | hilmanmakarim/fundamental-phyton | /python/1/belajar1soal1copy2.py | 886 | 3.640625 | 4 | # solve 6
# Jarak A dan B = 120 km
# A 60 km/jam
# B 40 km/jam
A = int (input('masukkan kecepatan A : '))
B = int (input("masukkan kecepatan B : "))
jarak = int(input('Masukkan jarak antara keduanya: '))
Tawal = input('masukkan waktu saat ini : ')
Tawal_jam = int(Tawal[0:2])
Tawal_menit = int(Tawal[3:5])
t=jarak/(A+B)
... |
40664328c72693d007d0961dd6e96ede386c7f71 | dangoldin/lawdiff | /n_gram_splitter.py | 2,882 | 3.65625 | 4 | # n-gram-splitter
""" Has a class called langmodel that takes a text and creates an NLTK FreqDist object
that has counts of unigrams, bigrams, and trigrams.
Example Usage:
s = "This is a test string. This is a test string. This is a test string. This is a test string. This is a test string. This is a tes... |
96385ef9e0676d24fdaccfded587b6583cf688a7 | VarunBhandia/Google-Maps-URL-Expander | /script.py | 2,644 | 3.59375 | 4 | import requests
import csv
import string
import random
# Print iterations progress
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
t... |
5fd1120bf5a2741d368bae3c7635b545e866c957 | sxz0/sentdexMLTutorial | /code/DeepLearningExample.py | 1,600 | 3.59375 | 4 | #Build a neural network to clasify handwritten digits
#
#First example->Deep Learning with Python
from keras.datasets import mnist
from keras import layers
from keras import models
from keras.utils import to_categorical
import matplotlib.pyplot as plt
from matplotlib.cm import cmap_d
import pandas as pd
from keras.laye... |
dcae794de1a9da9317c837ecd35dfffa7ba9d729 | CarsonML/Cheat-Game-and-AI | /cards.py | 1,220 | 3.78125 | 4 | from random import shuffle
import os
class Card():
def __init__(self, suite, number):
self.suite = suite
self.number = number
def __str__(self):
if self.number == 12:
return("king of " + self.suite)
if self.number == 11:
return("queen of " + self.suite)
if self.number == 10:
return("jack of " + se... |
50ea3e0cab3c75c22eaa9732785f44157eb22fb1 | dreese33/Robotic_Arm | /StepperMotorMultithreaded/RepeatedTimer.py | 791 | 3.84375 | 4 | # Repeated timer code using multithreading
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function):
self.timer = None
self.interval = interval
self.function = function
self.isRunning = False
self.start()
def _run(self):
s... |
6b605748d5be0c0cdc209bd28ceec2c0595ab9cb | dreese33/Robotic_Arm | /Ideas/shapes/Point.py | 298 | 3.96875 | 4 | import math
class Point:
"""
x - Position of x coordinate
y - Position of y coordinate
"""
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def distance(p1, p2):
return math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
|
19f224ab1b1edd89da7079dac79c6d161f4b5743 | bigbigfox/snoppyd | /yesefuhanshu.py | 803 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
def play(players,step,alive):
"""
Input:
players:参加游戏的人数;
step:数到step数字的人淘汰;
alive:幸存人数,即游戏结束。
Output:
返回一个列表,列表中元素为幸存者的编号
"""
A = [i for i in range(1,players+1)]
B = 0
while len(A)>alive:
i = 0
while i <le... |
eeb0e52074655c6e9e7c8adc635c11a549abe8ff | babar21/Deep_RL_Doom | /game_motor/utils.py | 612 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Useful functions (convert, plot...)
"""
def get_subkey(dict_of_dict):
""" return all the key of a dict of dict in a list """
new_key = []
for key, value in dict_of_dict.items():
new_key.extend(value)
return list(set(new_key))
def flatten_dic... |
45b4cde8d8fcfe5b91438d497d7d03810561bcbf | babar21/Deep_RL_Doom | /Bots/agent.py | 949 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Agent class
Everything needed for an agent to :
- get input from the environment
- choose an action according to a policy
"""
from abc import ABC, abstractmethod
class Agent(ABC):
"""
Abstract class, wrapping all the agents
"""
@abstract... |
1940d5c73cadc6409d47df22f7b34001265b81cb | AzerbaijanOpenSourceCommunity/neural-networks-and-machine-learning | /Linear-Regression/linear_regression_boston.py | 2,247 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sklearn
import seaborn as sns
sns.set(style="ticks", color_codes=True)
from sklearn.datasets import load_boston
# Importing dataset
boston = load_boston()
# Converting dataset type into DataFrame
bos = pd.DataFrame(boston.data)
# Exploring... |
59e38e21e0b6d0c91786dbffe8f53dbfd8083f71 | nancydemir/Coursera-Python-Programming-Courses | /copyoffindnumsgithub.py | 259 | 3.5 | 4 | import re
count=0
hand = open('testfileforassignment2.txt')
sum = 0
for line in hand:
line = line.rstrip()
x = re.findall('[0-9]+', line)
if len(x) > 0:
for item in x:
sum += int(item)
count+=1
print(sum,count)
|
e08a048484d63cfc466375194ba4909f9182c353 | nancydemir/Coursera-Python-Programming-Courses | /courseraquiz.py | 64 | 3.546875 | 4 | str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print (bob)
|
9992f387c4e4f9a58d5e578903a723c29c812b12 | nancydemir/Coursera-Python-Programming-Courses | /classtest.py | 304 | 3.5 | 4 | class My_Class:
def my_method(self, value1, value2):
"""Assumes its inputs are two values and does something."""
my_object = My_Class()
My_Class.my_method(my_object,1,2)
my_object.my_method(1,2)
#My_Class.my_object.my_method(1,2)
#my_method(my_object,1,2)
|
2bd09caae283a2faffa3a95bb6099c352f9b7289 | prariehill/stale-tales-slate | /aw.py | 6,331 | 3.65625 | 4 | import re
import sys
from string import ascii_lowercase
from collections import defaultdict
ag = defaultdict(str)
all_words = defaultdict(bool)
def on_off(a):
return ". Default=" + ['off', 'on'][a]
def usage():
print("-1/2 = see what happens with one or two letters removed")
print("-o/no = only anagram... |
894a2c7999f0d48e0969fde611a7d46509c5eccc | spacecase123/cracking_the_code_interview_v5_python | /array_strings/1.3string_permutation.py | 1,033 | 3.921875 | 4 | '''
Given two strings, write a method to decide if one is a permutation of the other.
'''
from collections import defaultdict
def is_perm(str1, str2):
if len(str1) != len(str2): return False
str1_chars = defaultdict(int)
str2_chars = defaultdict(int)
for i in range(len(str1)):
str1_chars[... |
1a03184e8ca72e019f6afc71915f90837ecf2c34 | spacecase123/cracking_the_code_interview_v5_python | /array_strings/1.2_reverse_string.py | 788 | 4.3125 | 4 | '''
Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string.
'''
def reverse(string):
'''reverse in place'''
string_len = len(string)
if string_len <= 1 : return string
last = string_len - 1
string = list(string)
for i in range(string_len / 2):
... |
f99469793b524b528f8afcda6159589f955a9a23 | spacecase123/cracking_the_code_interview_v5_python | /trees_graphs/4.2_route_between_nodes.py | 2,662 | 3.75 | 4 |
#lets make our graph a dictionary of nodes -> adjacent nodes
graph = {'a': ['b','c','d'],
'b' : ['a','c'],
'c' : ['a','b'],
'd' : ['e'],
'e' : ['d'],
}
def find_route(start, end, path=[]):
#be careful here, we need to create a new list
path = path + [start]
if start == ... |
7bd001f7f20aaf6dbd8764cbc46ac954c8ed6a57 | spacecase123/cracking_the_code_interview_v5_python | /chp17/17.7_int_to_string.py | 385 | 3.84375 | 4 | '''
Given any integer, print an English phrase that describes the integer (e.g., "One Thousand, Two Hundred Thirty Four").
'''
def int_to_string(num):
digit_words =["One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
... |
7684a5b73181267eb499c9258fac17ef90468314 | spacecase123/cracking_the_code_interview_v5_python | /linked_lists/2.1_remove_dups.py | 2,123 | 4.0625 | 4 | class Node(object):
'''
The individual pieces of a linked list are the
Nodes
'''
def __init__(self, data, next_node = None):
self.data = data
self.next = next_node
class LinkedList(object):
def __init__(self, root = None):
self.root = root
self.size = 0 if not r... |
dde6ff00f16358343df31841c6fcded9d59550da | AmaurySimoes12345/Project_Mark_C-_Python | /Scripts Python/Desligar_PC_1_hora-programada.py | 690 | 3.609375 | 4 | #Scripts Python - Amaury
import os.path
import time
import os
time_to_shutdown=sys.argv[1]
hours=time_to_shutdown.split(':')[0]
min=time_to_shutdown.split(':')[1]
text="""print("SAI JA' DO PC E VAI ESTUDAR!")
print("VE LA' SE NAO QUERES LEVAR COM O PAU!")
raw_input('<enter> para fechar do aviso')"""
x=0
while True:
... |
af5effde83cb6e69177d932eebb9b25274ecb044 | AmaurySimoes12345/Project_Mark_C-_Python | /Scripts Python/Menu de opções_Python2.py | 953 | 3.734375 | 4 | import os
import platform
import locale
print(locale)
menu=True
while menu:
print ("""
1.Informações da CPU
2.Informações da Memoria
3.Informações da Rede
4.Conexões Estabelecidas TCP
5.Usuários
6.Espaço livre no HDD
7.Hora atual
8.Registrar essas informações em um arquivo
""")
... |
973b0f85c4fc05e92fdacdbfd7c66aeb809c8bf7 | stephentigas/project-euler | /euler7.py | 319 | 3.953125 | 4 | '''Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
from module_prime import is_prime
primes = []
n = 2
while len(primes) < 10002:
if is_prime(n):
primes.append(n)
n += 1
print (primes[10000])
|
05b4df401f64144d9147a616b5ff5ac94d0b0eac | Howardman2/Hello-World | /13.py | 485 | 4.125 | 4 | print('Welcome to TRUE or FALSE')
print ('Please answer with yes or no')
Truth = input('Mr Gallo is the best: ')
if Truth !='yes':
print('wrong')
if Truth =='yes':
print('Correct!')
Falth = input('Coding is dumb: ')
if Falth =='yes':
print('WRONG')
if Falth !='yes':
print('Correct!')
Truce... |
3e66c697a8f1491026f6dd02cee395a000d2b3b7 | armando555/Analizadores-de-Expresiones | /AnalizadorPy1.1/Calculator.py | 809 | 3.640625 | 4 | from Parser import *
from Scanner import *
from Ast import *
class Calculator:
def __init__(self):
self.memory = 0
def eval(self, expr: str) -> float:
print("EVAL CALCULATOR")
parser = Parser(expr)
tree: AST = parser.parse()
print("YA EVALUAR EL ARBOL CREADO")
... |
85658b2dd1cb7478b13bc786708b9cb8e492a8cd | rtkjain97/attendance | /main_screen.py | 691 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 24 19:49:36 2020
@author: iiitb
"""
from tkinter import *
import os
root = Tk()
root.geometry('500x500')
def login():
os.system("python login.py")
def register():
os.system("python reg.py")
# create a Form label
Label(text="Choo... |
9586825e617728b2bc15946dd66c1425bea07532 | shivam1827/tathastu_week_of_code | /Day1/Program2.py | 108 | 3.921875 | 4 |
Value=float(input("enter the value: "))
SquareRoot=Value **0.5
print("SquareRoot value is: ", SquareRoot)
|
c04cc08d2f460a68d2aab32c40eb11018f9d9ada | enix223/nlp-course | /algorithm/merge_sort.py | 2,523 | 3.859375 | 4 | #!/usr/local/env python
"""
==========
Merge Sort
==========
MERGE(A, p, q, r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2 + 1] be new arrays
for i = 1 to n1
L[i] = A[p + i - 1]
for j = 1 to n2
R[j] = A[q + 1]
L[n1 + 1] = infinite
R[n2 + 1] = infinite
i = 1
j = 1
for k = p to r
if L[i] <= R[j]
... |
058358b1a5fbc622e7fe7273e5d3b75d71b3fa26 | anshika777/python-program | /factorial.py | 113 | 4.125 | 4 | print ("enter a number")
a=int(input())
n=1
for i in range (1,a+1):
n=n*i
print("factorial is:",n)
|
795e2b694c72498b4bd89cb8085b546e0012795b | devsg-gh/UCI-Homework | /homework3/Pypoll/main.py | 2,820 | 3.984375 | 4 | # This code will find unique candidate names, calcuate the %of vote, count of vote and the winner
import csv
import os
#provide the path and read the data from CSV
elec_path = os.path.join(".", "Resources", "election_data.csv")
with open (elec_path,newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter='... |
9f4347b933995c1be8b549d70843aee89b246df6 | OkavianusAuwdri/OktavianusAuwdri_I0320077_AdityaMahendra_Tugas3 | /I0320077_exercise3.4.py | 142 | 3.953125 | 4 | # Dictionary 3.4
dict = {'Name':'Oktavianus', 'Age':19, 'Class':'B'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age']) |
8f9f40ac670d818c69741229bcb54d995e4a2237 | Ana-Isabel-3802/prueba1 | /pruebapy.py | 944 | 3.78125 | 4 | import holamundo as h
import calculadoraLol as lol
#print "Hello cold word"
#cadena=raw_input("escribe algo para acabar ahora si el programa: ")
#entero=int(input("Escrbe un entero: "))
#decimal=float(input("Escrbe un decimal: "))
#print cadena
#print entero
#print decimal
#if entero <= 10:
# print "este numero sol... |
be1389756589e90afc9ff1e5b624e33d7a253bcc | ShaliniR8/Coursera-python-practice | /testing_practice/check.py | 169 | 3.625 | 4 | import re
my_txt = "An investment in knowledge pays the best interest."
def LetterCompiler(txt):
result = re.findall(r'([a-c]).', txt)
return result
|
c96badc4888fee61fdcd0099ac68db926cde550b | j2hongming/py-ds | /linked_list/double_linkedlist.py | 2,143 | 3.734375 | 4 | class ListNode:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoubleLinkedList:
def __init__(self):
self.head = None
self.trail = None
def insert_start(self, data):
"""Basic function"""
insert_node = ListNode(dat... |
f966e87d4853bf9b0374c0de48cfadf4a34da3f5 | lordzuko/Transformer-Stance-Detection | /readwrite/reader.py | 1,873 | 3.515625 | 4 | import io
import json
import numpy as np
def readTweetsOfficial(tweetfile, encoding='windows-1252', tweetcolumn=2, topic="all"):
"""
Read tweets from official files
:param topic: which topic to use, if topic="all", data for all topics is read
:param encoding: which encoding to use, official stance data... |
7a165762ebafde28afa3bc176443ca7a557c21da | EppalaMounika/DS290521E | /W09 D02/SELLER_FUNCTION (1).py | 6,083 | 3.71875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[20]:
import time,csv,random
def Signup(v):
if v == "Y":
time.sleep(1)
print('please login to continue')
time.sleep(2)
user_id = input("please enter your email id: ")
time.sleep(1)
password = input("please en... |
8dafaade26b5bb04ec5d1dfcd270025e68d5871e | EppalaMounika/DS290521E | /W09 D01/26 July Jupyter v1.py | 3,275 | 3.5625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[43]:
import time,csv
visitor = input("welcome! are you a customer? Are you a seller")
if visitor =='c':
print('Hello customer')
time.sleep(1)
print('please login to continue')
time.sleep(1)
user_id = input("please enter your email id: ")
... |
2fc3d05f42005193a318967ab445f8b0d674e0e6 | EppalaMounika/DS290521E | /W09 D02/27 July Jupyter.py | 3,382 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
import time,csv
class Product:
'Common base class for all Product'
prodCount = 0
prod_list=[]
H =[]
def __init__(self, PROD, MANF, PRICE, QUAN):
self.PROD = PROD
self.MANF = MANF
self.PRICE = PRICE
self.QUAN = QUAN
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.