blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
9205b903f8c2460337f2e99c7e0f8f92c0946e74 | rockmichael45/CTI110 | /M3PopQuiz_JacksonGeorge.py | 362 | 4.0625 | 4 | #CTI 110
#M3 Pop Quiz
#George Jackson
#9/18/17
#ask the user for two numbers
firstNumber = float(input('Enter the first number: '))
secondNumber = float(input('Enter the second number: '))
#average the numbers
#average = (firstNumber + secondNumber) / 2
average = firstNumber + secondNumber
average = average / 2
#pr... |
63f525bb43a712fee842315d0db43506562ff74e | aniketwarang11/Python-Basics | /oops5.py | 959 | 3.71875 | 4 | class Employee :
no_of_leaves = 8
def __init__(self,aname,asalary,arole):
self.name = aname
self.salary = asalary
self.role = arole
@classmethod # can only access class variable
def change_leaves(cls,new_leaves): #we can access this by instance or by class
cls.no_of_leav... |
f7d8a9b4add491422cb5ff9b99a7ef4ab0cccc7b | Diego300591/PRACTICA-1 | /Ejercicio 1/Inciso d.py | 143 | 3.71875 | 4 | def suma2(num1,num2):
num1=str(num1)
num2=str(num2)
concat=num1+num2
return concat
A=raw_input()
B=raw_input()
suma2=suma2(A,B)
print suma2 |
75c116e8c89997037c1661d87578e9a0b3e73666 | daniel-reich/ubiquitous-fiesta | /hvPiBiwE9TfLnsfz4_3.py | 360 | 3.53125 | 4 |
def generate_word(n, initial=True, seq=[]):
if initial and n < 2:
return "invalid"
if initial:
if n == 2:
return "b, a"
seq = ["b", "a"]
return generate_word(n - 2, False, seq[:])
if n == 0:
return ", ".join(seq)
seq.append(seq[-2] + seq[-1])
retu... |
1080f6890e572fe1e1a5fed07d627ea0a4cd4edd | zubie7a/Algorithms | /CodeSignal/Arcade/Intro/Level_04/01_Alternating_Sums.py | 672 | 3.859375 | 4 | # https://app.codesignal.com/arcade/intro/level-4/cC5QuL9fqvZjXJsW9
from functools import reduce
def alternatingSums(nums):
n = len(nums)
# Create a list of tuples in which the first element will only
# contain the weights of the even positions and the second element
# will only contain the weights of ... |
479ce80cd5ad199eb3a79138dc0432d0ef42e8ca | nsylv/PrisonersDilemma | /game.py | 14,106 | 4.125 | 4 | ''' Play the cannonical prisoner's dilemma
\tYou and the other player have been imprisoned for
petty theft of a gas station. However, after you fled the
scene, a huge fire erupted. The police have ample evidence
that you two were behind the theft, but they also have
suspicions that you two are behind the arson... |
7e6ea3fd06300fbd91917b2741f5bc3d9176fa77 | Twishar/DataAnalysis | /Sentdex/JoiningMerging.py | 573 | 3.625 | 4 |
import pandas as pd
df1 = pd.DataFrame({'Year' : [2001, 2002, 2003, 2004],
'Int_rate':[2, 3, 2, 2],
'US_GDP_Thousands' : [50, 55, 65, 55]})
df3 = pd.DataFrame({'Year' : [2001, 2003, 2004, 2005],
'Unemployment' : [7, 8, 9, 6],
'Low_tier... |
2f4085b11a4913975c44a681f1eabdd43af5452f | marinaagafonova/OOP-Python | /task4/task4.py | 1,805 | 3.75 | 4 | import argparse
import re
def main():
parser = argparse.ArgumentParser()
parser.add_argument('fileTextName')
#parser.add_argument('fileVocabularyName')
args = parser.parse_args()
#text = open_file(args.fileTextName)
#text = open_file("text.txt")
#vocabulary = open_file("vocabulary.txt")
... |
f95504afed11de3996a7b1f799408012920875f4 | imriven/udemy | /python_megacourse/to_file.py | 250 | 3.75 | 4 | numbers = [1, 2, 3]
file = open("resources/to_file.txt", "w")
for i in numbers:
file.write(str(i) + "\n")
file.close()
myfile = open("resources/to_file.txt")
file = myfile.read()
file = file.splitlines()
for i in file:
print(i)
file.close() |
f3f213b4a9af19318cccf27c0f81065ff2f76892 | VinayakBagaria/Python-Programming | /Others/Introductions.py | 530 | 4.03125 | 4 | print('Hello World')
print(1,2,3,4,sep='*')
print(1,2,3,4,sep='#',end ='%')
x=5;y=10
print('\nThe value of x is {} and y is {}'.format(x,y))
print('{0} and {1}'.format('beer','wine'))
print('{1} and {0}'.format('beer','wine'))
print('Hello {name} and The Mate {love}'.format(name='Vinayak' , love='fifa'))
num1=i... |
0200b853733c6699a67b3ca8bd3ea75af7371383 | erik-engel/python_exam | /Dictionary/dictionary.py | 2,295 | 4.875 | 5 | # Creating a Dictionary
#
# Dictionaries can be created using the flower braces or using the dict() function.
# You need to add the key-value pairs whenever you work with dictionaries.
myDict = {} #empty dictionary
print(myDict)
# {}
myDict = {1: 'Python', 2: 'Java'}
print(myDict)
# {1: 'Python', 2: 'Java'}
# Changi... |
aa4ecbf36466d4cd0cc3d575b4c9bc2931a73a38 | mselig/game-of-life-python | /gol/test/test_cell.py | 2,066 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from gol.base import Cell
class TestCell(object):
def test_initialisation(self):
cell = Cell()
assert type(cell.is_alive) == bool
assert type(cell.neighbours) == int
assert cell.neighbours == 0
cell = Cell(1)
assert cell.is_alive ... |
79e68b72864e57e61bbcd8036a2b023aac5fc55b | uncleyao/Leetcode | /238. Product of Array Except Self.py | 747 | 3.921875 | 4 | """
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
"""
class Solution(object):
def productExceptSelf(self, nums... |
660f58374dee2624eca0c0cd5c1e13f98f880cbe | ASGithubaccount/my-repository | /dict_exercises.py | 6,313 | 4.46875 | 4 | # 1. Write a Python script to sort (ascending and descending) a dictionary by value
dict1 = {3: "dupa", 6: "dskal", 2: "g34"}
asc_dict = sorted(dict1.items(), key=lambda item: item[1], reverse=True)
print(asc_dict)
# 2. Write a Python script to add a key to a dictionary
dict2 = {'0': 10, 1: 20}
dict2[3] = 30
# 3. Wr... |
8c14c9e91a517d329732c45c0d6de6f619143e62 | bielabades/Bootcamp-dados-Itau | /Listas/Funcoes/03.py | 584 | 4.21875 | 4 | # Faça uma função para cada operação matemática básica (soma, subtração, multiplicação e divisão).
# As funções devem receber dois números e retornar o resultado da operação.
num_1 = 10
num_2 = 1
def soma(num_1, num_2):
soma = num_1 + num_2
return soma
def sub(num_1, num_2):
sub = num_1 - num_2
retu... |
b7de2f77141808965de070ba26801eda081a07c6 | zulkarnine/ds_algo | /ds.py | 1,559 | 3.71875 | 4 | class Node:
def __init__(self, value):
self.next = None
self.prev = None
self.val = value
class DoubleLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add(self, val):
node = Node(val)
if self.tail is None:
... |
f2e7491e38cf3a6bd5e2c6d2b189fc248dfadb37 | wldyslw/poit-labs | /huffman/compressor/huffmanCoder.py | 3,711 | 3.78125 | 4 | from queue import PriorityQueue
from collections import Counter
from functools import reduce
class HuffmanNode(object):
def __init__(self, symbol=None, weight=0, left=None, right=None):
self.left = left
self.right = right
self.symbol = symbol
self.weight = weight # used to compare ... |
95b99851b9d90c69541c4dc458174b23adf3b3d3 | MohanaPriya2537/pythonpracticeexamples | /clas n obj.py/accessing instance variable.py | 377 | 3.875 | 4 | class Test:
def __init__(self):
self.a=10
self.b=20
self.c=30
def m1(self):
self.d=40
def m2(self):
self.e=50
t=Test()
t.m1() #within class using self
print(t.__dict__)
# t1=Test()
# t1.m2()
# print(t1.__dict__)
t2=Test()
t2.m2()
t2.f=60 ... |
32b22832f0b32eddaff8b9572a61f7923ebccc63 | wilecoyote1/TripIntoDataStructuresAndAlgorithms | /isprime/isprime_demo.py | 141 | 3.921875 | 4 | from isprime import isprime
numbers = [1,3,5,10,15,41]
for number in numbers:
print(f"{number} is a prime number ? :{isprime(number)}") |
196dfcf991fb1912de2939f39170f2e5159121b5 | MeetWithRajat/Health-Management-System | /health_manaement_system_using_oops.py | 26,808 | 3.703125 | 4 | from datetime import datetime
import sqlite3
class ClientHandle:
"""This class for handling the client"""
def __init__(self):
"""Initializing the client list and client id from client info [f] and client id no [f]"""
conn = sqlite3.connect("health_management.db")
cr = conn.cursor()
... |
9e9c5d77f8c8aadaa204b9c01d1cd5c1c83988fa | MarkG208/comp110-21ss1-workspace | /exercises/ex01/hype_machine.py | 362 | 3.578125 | 4 | """The Hype Machine exercise is now completed."""
__author__: str = "730399808"
name: str = input("What is your name? ")
print("You entered: ")
print(name)
print(name + ", you are an amazing person, keep it up!")
print("Don't stop you're almost there " + name + ".")
print("You want to know something " + name + "....... |
e226a0253bcac4d8e43fdf7b4e475673c8ff21c3 | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/63/13783/submittedfiles/decimal2bin.py | 257 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
a=input('digite um numero:')
i=b
contador=0
while i>0:
i=i//10
contador+=1
j=contador
m=0
soma=0
while m<=(j-1):
r=a%10
a=a//10
d=r*(2**l)
soma+=d
m=m+1
print (soma) |
8cf5c02f8787d927390f025e1358164fcb9f7627 | betoalien/Python-Exercises | /Ejercicios.py | 3,337 | 4.21875 | 4 | # 10- Definir un histograma procedimiento() que tome una lista de números enteros e imprima un histograma en la pantalla.
# Ejemplo: procedimiento([4, 9, 7]) debería imprimir lo siguiente:
#
# ****
# *********
# *******
lista_histograma = [18, 37, 66, 48, 87, 55, 27]
def histograma(x):
for i in x:
... |
e6f7b4bd9042b86481f41b866ca27c1d60aa4758 | ChWeiking/PythonTutorial | /Python基础/day07(函数)/demo/03_函数的参数/05_命名关键字.py | 278 | 4.0625 | 4 | '''
命名关键字:
调用的时候,找到特定的参数赋值
'''
def f(name,age):
print('name=%s,age=%s'%(name,age))
f(age=18,name='老王')
def person(name, age ,city, *,job):
print(name, age, city, job)
person('老王',18,'河北',job='游手好闲')
|
d59e6fdf044fb5fdf589095bd823d6ea57ff6ec6 | rafaelperazzo/programacao-web | /moodledata/vpl_data/5/usersdata/112/1762/submittedfiles/atm.py | 263 | 3.859375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
valor=input('Digite quanto deseja sacar')
a=input(1)
b=input(2)
c=input(5)
d=input(10)
e=input(20)
if valor%a==0
r=valor//a
print('quantidade de notas%.2d' %r) |
b9638b14b5d9cd3af50630aa9dd66bdcdcb8b339 | jrsaavedra1022/jrsaavedra-python | /clase53-reto-convert-binary.py | 886 | 3.765625 | 4 |
def decryptBinary_word(binaryElement):
octetos = binaryElement.split(" ")
contenido = ''
for octeto in octetos:
letter = bytearray(int(bit, 2) for bit in octeto.split())
contenido += letter.decode(encoding="utf8")
newWord = contenido
print("La palabra o frase desencriptada es: ")
print(newWord)
def encrypt... |
ec15d62aa82419558ff4c25908e1d35f624be1d3 | carter144/Leetcode-Problems | /problems/20.py | 2,098 | 4.125 | 4 | """
20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also... |
6e17010eac2f9e1f051892da62bb86da8e5a0667 | lucasdmazon/CursoVideo_Python | /pacote-download/Exercicios/Desafio57.py | 499 | 3.921875 | 4 | '''
sexo = ''
while sexo != 'M' and sexo != 'F':
sexo = str(input('Digite seu sexo[M/F]: ')).upper().strip()[0]
if sexo != 'M' and sexo != 'F':
print('Houve um erro de digitação. Tente novamente')
print('Informação valida. Obrigado por colaborar!')
'''
sexo = str(input('Digite seu sexo[M/F]: ')).upper()... |
e579f280b75e58ae9a04aa629ab529af9b4135c8 | c0r4line/Practicas-y-entregas | /desafios/desafio4.py | 819 | 3.890625 | 4 | def ingreso_notas():
""" Esta función retorna un diccionario con los nombres y notas de estudiantes """
nombre = input("Ingresa un nombre (<FIN> para finalizar)")
dicci = {}
while nombre != "FIN":
nota = int(input(f'Ingresa la nota de {nombre}'))
dicci[nombre] = nota
nombre = in... |
d481b9bb793c5acd501622b8794fc52bcf7a81c4 | WillGhost/op | /exercise/Breadth_First.py | 473 | 4.125 | 4 | #/usr/bin/env python3
graph = {
1:[2,3,4],
2:[5,6],
5:[9,10],
4:[7,8],
7:[11,12],
}
def bfs(graph, start, end):
que = []
que.append([start])
while que:
path = que.pop(0)
node = path[-1]
if node == end:
return path
for adjacent in graph.get(node, []):
new_path = list(path)
ne... |
174b087c5cee4139c702a55a1ed1a9dd7601ad3f | Sebbenbear/tictactoe | /test_tic_tac_toe.py | 2,689 | 3.953125 | 4 | """
Tests for Tic Tac Toe module
"""
import unittest
import tic_tac_toe
class Testtic_tac_toe(unittest.TestCase):
# Test creation of the game grid
def test_create_game_grid(self):
expected = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
actual = tic_tac_toe.create_game_grid()
self.ass... |
1b4a84721553cbb11717a7073f60d83772a432c1 | faci2000/ASD | /sortings/radix_sort.py | 1,513 | 3.703125 | 4 | def counting_sort(Words,left,right,index):
Letters=[0 for i in range(25)]
for i in range(left,right+1):
Letters[ord(Words[i][index])-ord('a')]+=1
for i in range(1,len(Letters)):
Letters[i]+=Letters[i-1]
Words_copy=[' ' for i in range(left,right+1)]
for i in range(right,left-1,-1):... |
9fc1af649a8bd5fbf76f6dffb2cdc5a6af4d04d9 | andreifecioru/udacity | /data.struct.algo/lesson.700/min_platforms.py | 1,634 | 3.984375 | 4 | #!/usr/bin/env python
from collections import namedtuple
Interval = namedtuple('Interval', ['start', 'end'])
def min_platforms(arrival, departure):
"""
:param: arrival - list of arrival time
:param: departure - list of departure time
:return: the minimum number of platforms (int) required
so th... |
08304da67e91d5ad7ab0e22af968ad2c1c470e5e | JackLovel/excuise- | /effectivePython/tap11/tap11_1.py | 279 | 4.03125 | 4 | names = ['Cecilia', 'List', 'Marie']
letters = [len(n) for n in names]
longest_name = None
max_letters = 0
for i in range(len(names)):
count = letters
if count > max_letters:
longest_name = names[i]
max_letters = count
# print(letters)
print(longest_name)
|
8661d1b7d74af4d7ea99d2e71a8a3fdec9814d07 | thitima20/KE | /Multi3or5.py | 145 | 3.734375 | 4 | nums = [8,10]
utmost = int(input("number: "))
fruit = 0
for i in range(0,utmost):
if i %8 == 0 or i%10 == 0:
fruit += i
print(fruit)
|
32dd1085a0f332e2020beeef513000010548f60d | jay-chakalasiya/Competitive-Coding | /Cracking-The-Coding-Interview/01_02_check_permutation.py | 455 | 3.8125 | 4 | # check if one string is permutation of other
def check_permutation(str1, str2):
trig_ls = [0]*128
if len(str1)!= len(str2):
return False
for i in range(len(str1)):
trig_ls[ord(str1[i])]+=1
trig_ls[ord(str2[i])]-=1
for i in range(len(trig_ls)):
if trig_ls[i]!=0:
... |
bd8f3e7cdce4473eae744b665bcbfb9c27c611a7 | meghna093/CS6200-Information-Retrieval | /Assignment/HW1/crawler.py | 4,315 | 3.6875 | 4 | #This code is used to crawl wikipedia web pages
#The given seed is 'https://en.wikipedia.org/wiki/Tropical_cyclone'
#For problem statment please refer the below link:
#https://blackboard.neu.edu/bbcswebdav/pid-14487715-dt-content-rid-23461007_1/courses/CS6200.15344.201810/hw1.pdf
#Coded by Meghna Venkatesha
#libra... |
89746e20c80606efb546bb0dd561093bdcf5b7c8 | fsMateus/exerciciosPython | /fase2/exercicio6.py | 281 | 4.3125 | 4 | numeros = []
numeros.append(float(input('Digite o valor 1: ')))
maior = numeros[0]
for i in range(1,3):
numeros.append(float(input('Digite o valor {}: '.format(i+1))))
if maior < numeros[i]:
maior = numeros[i]
print('O maior valor informado foi {}'.format(maior)) |
bd1fb8228c99ae0b6d2d27f6593e07aae79e0d9d | fredfeng0326/LeetCode | /let500.py | 616 | 3.859375 | 4 | # 500. Keyboard Row
class Solution:
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
list1 = {'q','w','e','r','t','y','u','i','o','p'}
list2 = {'a','s','d','f','g','h','j','k','l'}
list3 = {'z','x','c','v','b','n','m'}
list... |
de084a71048e329b419122dc05986e4155cdcf21 | acrodeon/pythonInteractive-algos | /quickSort.py | 2,196 | 4.21875 | 4 | #################################################################################
# Quick Sort #
# A quick sort first selects a value, which is called the pivot value #
# The actual position where the pivot value belongs in the final sorted li... |
18501ce2d6382842b6ea547efcb90db37998c429 | thtl1999/jongman-book-training | /python practice/making list of list.py | 552 | 3.65625 | 4 |
list_size = 3
correct_list = [['*' for _ in range(list_size)] for _ in range(list_size)]
incorrect_list = [['*']*list_size]*list_size
print('These list looks same...')
print('Good', correct_list)
print('Bad!', incorrect_list)
print('Change 2nd list value')
correct_list[1][1] = ' '
incorrect_list[1][1] = ' '
print(... |
80f8aac8464805654712796b32bb2518d8f3f656 | vrsaljk0/DenverCrime | /formatiranje.py | 2,449 | 3.65625 | 4 | import csv
def sredi_datum(line):
if "AM" in line:
return line.replace(line, "night")
return line.replace(line, "day") #u slučaju da je dan, ali i ako se pošalje prazan string postaje dan bmk
def sredi_district(distric_id):
if(distric_id == "1"):
return "A"
elif(distric_id ==... |
7ff00c6f29cc131bd46004087d3c3f7a0b5b9c18 | concpetosfundamentalesprogramacionaa19/practica220419-LeonardoAV7 | /demo2.py | 435 | 3.78125 | 4 | import sys
"""
archivo: demo2.py
Ejemplo de lenguaje Python
autor; @LeonardoAV7
"""
nombre_archivo = sys.argv[0]
valor1 = sys.argv[1]
valor2 = sys.argv[2]
suma = int(valor1) + int(valor2) # aqui realizco la suma de variables
multiplicacion = int(valor1) * int(valor2) #aqui realizo la multiplicacion
print("variab... |
99130e57d05e32239851f98c56c7b7d27a79c6c3 | xaviergoby/Python-Data-Structure | /Excersise/SherlockSquares.py | 1,287 | 4.03125 | 4 | # Fromm HackerEarth
# Watson gives two integers ( and ) to Sherlock and asks if he can count the number of square integers between and (both inclusive).
#
# Note: A square integer is an integer which is the square of any integer. For example, 1, 4, 9, and 16 are some of the square integers as they are squares of 1, 2... |
6e45c50c45bf2c295dd5f5af1cf7697bc03bc51b | ssmi4th98/python_test_class | /setUp_class_employee.py | 1,403 | 3.78125 | 4 | import unittest
from employee import employee
## this shows how to use a class statement to go across the entire class now just each test setup.
## Note: cannot alter the value of the names because of its definition as class (not flexible)
class TestEmployee(unittest.TestCase):
@classmethod
def setUpClass(c... |
73badd971da609cdf8a8ce18758d430b6d0ac7ef | luizavitiello/luizavitiello-Algoritimos-II-2020-2 | /trabalhoretangulo.py | 2,343 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''Construa um algoritmo para implementar a classe Retângulo que possui os atributos: altura e largura.
A classe deve ter os seguintes métodos:
Método construtor
Método que calcula a área do retângulo ( altura * largura) e retorna o resultado
Método que imprime os val... |
d3f2dba3fc32655cefecff93095a8e8bfa80c576 | suryakants/Python-Program | /fileIO_RW.py | 546 | 3.78125 | 4 |
# Open a file
fo = open("foo11.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()
del fo;
# Open a file
fo = open("foo00.txt", "r+")
str = fo.read(10000);
print "Read String is : ", str
# Close opend file
fo.close()
del fo;
fo = open("foo.txt", "a");
fo.write("S... |
16e48ffc24f1153ebf88b5a0ab3cad82921e07f6 | zjingang/testdemo | /3rd/code18-复习7-函数的参数.py | 1,063 | 3.796875 | 4 |
# 1、位置参数(第一个实际参数传给第一个形式参数。。。。。。。)
def user_info(name, age, gender):
print(f'您的名字是{name},您的年龄是{age},您的性别是{gender}')
user_info('xiaoming',20,'男')
# 2、关键字参数
def user_info(name, age,gender):
print(f'您的名字是{name},您的年龄是{age},您的性别是{gender}')
user_info('xiaoming',age = 20, gender = '男')
user_info('rose', gender = '女',a... |
86c39de5677b76c4ac09487bb1d38375f9cf3a96 | Stevenr100/PERSONAL | /EJERCICIOS PYTHON/EJERCICIOS PYTHON/ejercicio15.py | 382 | 3.875 | 4 | print ("PROGRAMA PARA CONVERSIÓN DE UNIDADES DE TIEMPO")
horas= int (input("Escriba la cantidad de horas: "))
minutos= int (input("Escriba la cantidad de minutos : "))
segundos= int (input("Escriba la cantidad de segundos : "))
segundos += horas * 60 * 60
segundos += minutos * 60
print ("LA CANTI... |
6dbdd60cf66e5aa3052e53668d0b4714cfc0ad0c | mscaudill/Tutorials | /sql_zoo/5_SUM_and_COUNT.py | 2,127 | 4 | 4 | # --Matt Caudill
# world(name, continent, area, population, gdp)
#1 Show the population of the world
SELECT SUM(population) FROM world
#2. List all the continents just once
SELECT DISTINCT(continent) FROM world
#3. Find the total GDP of Africa
SELECT SUM(gdp) FROM world
WHERE continent = 'Africa'
#4. How many coun... |
99c6408a207f6d3b5f45eb734cfa6e803fcb93f2 | nakano0518/AtCoder-by-python | /ABC/208/A.py | 205 | 3.5625 | 4 | A, B = map(int, input().split())
if A > B:
print('No')
else:
if 6*A < B:
print('No')
elif 6*A == B:
print('Yes')
else:
if B-6*(A-1) <= 5:
print('Yes')
else:
print('No') |
d6471973d67b835105985a6783754a8a4b5e2296 | arizamoisesco/100daysofcodepython | /Day5/generador_contraseña.py | 1,693 | 3.9375 | 4 | #Password Generator Project
import random
letras = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numeros ... |
950f1ea94976b5976147cb841d7c663266569973 | WarDrummer/Advent-of-Code-2016 | /Python/day_03/day_3.py | 1,420 | 4.03125 | 4 |
class TriangleValidator:
@staticmethod
def is_valid(triangle_lengths):
return triangle_lengths[0] + triangle_lengths[1] > triangle_lengths[2] \
and triangle_lengths[0] + triangle_lengths[2] > triangle_lengths[1] \
and triangle_lengths[1] + triangle_lengths[2] > triangle_le... |
ed5273b38d45704cd164f2fafd939e8e57264a66 | Illugi317/forritun | /mimir/17/2.py | 1,432 | 4.125 | 4 | '''
2. Sentence
5 points possible
Implement a class called Sentence that has a constructor that takes a string, representing the sentence, as input. The class should have the following methods:
get_first_word(): returns the first word as a string
get_all_words(): returns all words in a list.
replace(inde... |
2ae2a9a2f65d93a1e4f02264f390f398838c2d2a | true-false-try/Python | /A_Byte_of_Python/OOP/class_/point/point_3D.py | 1,097 | 4.09375 | 4 | """
Создайте класс Point3D, который хранит координаты в виде списка. Пропишите у него конструктор для создания экземпляров
с локальными координатами. Также добавьте методы, позволяющие изменить координаты и получить их в виде кортежа.
"""
class Point3D:
def __init__(self, x, y, z):
self.__vector... |
368f516f210141bc2c35d7ad05fcb133986c9a16 | nirajgolhar/Python-core-fundamentals | /revision.py | 2,391 | 4.15625 | 4 | # fruits = ['grapes','apple','banana','pineapple','banana']
# fruits.sort()
# print(fruits)
# numbers = [5,2,4,1,3]
# numbers.sort()
# print(numbers)
# numbers = [5,2,4,1,3]
# print(sorted(numbers))
# fruits = ['grapes','apple','banana','pineapple','banana']
# print(sorted(fruits))
# fruits = ['grapes... |
2bb6b184d5da69b3e8c095414cd9d64b3b56e295 | dudarchikconnor/csec465 | /PortScanner.py | 3,005 | 3.796875 | 4 | # Zhi-Han Ling
# Python Port Scanner
import socket
import ipaddress
import os
import subprocess
def main():
"""
Main function that takes input of a range of IP Addresses and a range of ports
First checks if IP address are up then
Scans the range of IP Address with the Range of Ports
... |
510202fc334d5a1f42fc714dc49e198ccdd5b087 | Jeandcc/CS50 | /pset6/Redability/readability.py | 644 | 3.921875 | 4 | text = input("Text: ")
countletters = 0
countwords = 0
countsentences = 0
if text[0].isalpha:
countwords += 1
for i in range(len(text)):
if text[i].isalpha():
countletters += 1
if (text[i].isspace() or text[i] == '"') and (i+1 < len(text) and text[i+1].isalpha()):
countwords += 1
if t... |
fc9fd2ce00ec856ea996ca1ab47b2ee38525887a | WangYangLau/learnpython | /func_para2.py | 663 | 4.03125 | 4 | # -*- coding:utf-8 -*-
def calc(*number):
sum = 0
for n in number:
sum = sum + n*n
return sum
L = [1,2,3]
s = calc(1,2,3)
print("changeable_para calc(*number) 1 2 3:\n%d"%s)
s = calc(4,5)
print("changeable_para calc(*number) 4 5:\n%d"%s)
s = calc(*L)
print("L =",L)
print("changeable_para calc(*number) *L:\n%d"%... |
2fbe494957305eb753448e3578d79fa08ca7f734 | vinayselestin5/selestin5 | /greater lesser.py | 181 | 4.3125 | 4 | #FIND GREATEST OF TWO NUMBERS
a=int(input("enter value of a: "))
b=int(input("enter value of b: "))
if (a>b):
print("a is greater than b")
else:
print("b is greater than a") |
5911ba16fd5ce85ae25a159ba3e7f58f07a6bbc9 | ShubhamMadhavi99/Hackerrak_Python | /text_wrao.py | 339 | 3.90625 | 4 | import textwrap
def wrap(string, max_width):
x = len(string)
i = 0
a = ""
while i < x:
y = string[i:i+max_width]
i = i + max_width
print(y)
return a
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)... |
a4fa065541a5f25bcd47244e918601f2566b6db0 | UWPCE-PythonCert-ClassRepos/Sp2018-Accelerated | /students/Briadean/lesson07/html_render.py | 884 | 3.71875 | 4 | #!/usr/bin/env python3
"""
A class-based system for rendering html.
"""
# This is the framework for the base class
class Element:
tag = "html"
def __init__(self, content=None):
if content is None:
self.content = []
else:
self.content = [content]
def append(self,... |
dde81d5e200a0cbaaf1874a43f12b050e3e19c6e | PurityMaina/DS-Algos | /challanges/test.py | 584 | 3.953125 | 4 | # determine if there's a pair of elements that sums up to k
# output is yes or no
input = [1, 3, 7]
k = 8
#create 2 pairs of the array i.e i and j
#sum up the elements
#compare if the pair summation is equal to k
#return yes or no
def sum_of_pairs(input, k):
sum_set = set()
for i in range(0, len(input)):
... |
0e207fa989f7bc673cae936280857937b00ba590 | onthir/nicheCrawler | /formatter.py | 601 | 3.609375 | 4 | import os
def do_it(user):
u = str((user).lower()).replace(" ", "-")
file_to_read = (str(user).lower()) + "/" + str(u) + "-universities.txt"
file_to_write = (str(user).lower()) + "/formatted.txt"
with open(file_to_read, 'r') as file:
f = file.readlines()
for r in f:
... |
e1e9eff5b46872f9cc914954329d691f5d0b892d | asmitbhantana/Insight-Workshop | /PythonProgrammingAssignmentsI/Data Types/q45.py | 328 | 4.25 | 4 | """
45. Write a Python program to find the index of an item of a tuple.
"""
def find_item_index(user_tuple: tuple, item):
for i in range(len(user_tuple)):
if user_tuple[i] is item:
return i
return None
if __name__ == '__main__':
print(find_item_index((1, 2, 3, 4, 5, 2, 3, 5, 6, 15),... |
dc4c70f709f931c5e8c389f79cfbcac4eb25cb53 | JohannesBuchner/pystrict3 | /tests/expect-fail/recipe-54159.py | 1,058 | 4.28125 | 4 | #!/usr/bin/env python
# This demonstrates a binary search through sorted data using bisect.
# A large array of random numbers is generated and then sorted.
# The the application shows where a given number would be inserted
# in the random data list.
from bisect import bisect
from random import randrange
import sys
# ... |
1ed03f9487773ac7f83134a71c7650950686c55d | miaojiang1987/LeetCode | /Python/customSort.py | 598 | 3.5625 | 4 | class Solution:
def customSortString(self, S: str, T: str) -> str:
# dic[char] will be the number of occurrences of 'char' in T.
dic = {}
for c in T:
dic[c] = dic[c]+1 if c in dic else 1
# Write all characters that occur in S, in the order of S.
... |
5b2abf5b7ceef51e5b7f979eb1a916b4d7c2adbb | annguyentruong99/Python-Lessons | /3:Loops/loops.py | 1,008 | 4.3125 | 4 | # Loop are to iterate through data that are iteratable, those data consist of strings, integer, floats
# There are two types of loops:
# For loops
string = input("Enter your name: ") # Trang
for char in string:
print(char)
for i in range(5):
print(i)
# While loops
i = 10 # In a while loop, a counter variable is a... |
bfaaea8c27cb4268d8253ce0ec27f4b1baf2337f | Yobretaw/AlgorithmProblems | /EPI/Python/Greedy/18_4_load_balancing.py | 3,391 | 3.578125 | 4 | import sys
import math
"""
You have n users with unique hash code h_0 through h_{n-1}, and m servers.
The hash code are ordered by index, i.e., h_i < h_{i+1} for 0 <= i <= i - 2.
User i requires b_i bytes of storage. The values k_0 < k_1 < ..., k_{m-2} are
used to assign users to server. Specifically,... |
948ad9d917b36c1576b759257d754c96d38e1474 | Onenightcarnival/MapReduce | /milestone1/udf.py | 3,096 | 3.53125 | 4 | """
Test case 1: word count
"""
def test1_get_inputs():
import glob
return glob.glob('word_count_data\\*.txt')
def test1_map_funciton(file):
import json, re
print("Mapping file: ", file)
output = []
with open(file, 'r', encoding='UTF-8') as f:
for line in f:
line = line.lowe... |
b7bd80de8b5180a8e44ac0cb7ebdbf17c78a4f92 | blnblnbln/blnblnblnbln | /hggggggfd.py | 694 | 3.828125 | 4 | '''
Leer un valor por teclado (N)
Leer N valores por teclado y guardarlos en una lista
Calcular la suma de los valores de una lista
Calcular el promedio de los valores de una lista.
'''
N = int(input('Ingrese un valor para N= '))
lista = [ ]
for i in range (N):
valor = int(input('Ingrese un valor: '))
lista.ap... |
e449bf91b04c748e58b06d85e7c1c9aab1aded29 | PRKKILLER/Algorithm_Practice | /Company-OA/Robinhood/SpiralMatrixSort.py | 2,092 | 3.53125 | 4 | """
给定1个n*n的matrix, 这个矩阵会有层层边框,螺旋向内。
对这个矩阵中边框上的数字进行排序,然后再按照顺时针的顺序重新排在边框上
Example:
Input: [[1,4],[2,3]]
Output: [[1,2],[3,4]]
"""
import heapq
def solution(matrix):
m, n = len(matrix), len(matrix[0])
tmp = []
r_start, r_end = 0, m - 1
c_start, c_end = 0, n - 1
while r_start <= r_end and c_star... |
8a47926107681a907c101b8be5999b04888b26b8 | ScoJoCode/ProjectEuler | /problem30/main.py | 246 | 3.578125 | 4 | import time
start = time.time()
sum = 0
for i in range(2,5*9**5):
word = str(i)
s = 0
for j in range(0,len(word)):
n = int(word[j])
s+=n**5
if i == s:
sum+=i
end = time.time()
print sum
print 'time elapsed: ' + str(end-start)
|
9e06fbe690293e63cfffeed3dcb47294aaf748b7 | fdankhara/PyGettingStarted | /8. Fairy Dankhara What is YOUR Choice.py | 4,070 | 4.3125 | 4 | print("Welcome to: 'This Is YOUR Choice'")
choice6 = ""
choice2= ""
def choiceSix():
choice6 = input().upper()
if choice6 == "YES":
print("You pick up a stone from the ground and start to pick at the rocks. Minutes later, a diamond falls into your hands. You see your wolf run up to you with a ruby in it... |
3d7823c38d692fd3b5cea9184f8deb511e26e13a | SeanEGuy/Random_Comm_Towers_ECE143_SP18 | /plotcover.py | 690 | 4 | 4 | '''
Displays arrays in a graphical format for easier visualization.
'''
def plot_oneArray(inArray):
'''
Plots a single array representing coverage on an xy axes.
'''
import matplotlib.pyplot as plt
import numpy as np
plt.subplot(111)
plt.imshow(inArray, aspect='equal')
plt.show()
... |
59e59ea3bd0b7cc02ce24e7699ee63d92841ba98 | KishanLow/Python-Challenges | /AS/TOP TRUMPS.py | 3,237 | 3.75 | 4 | import random
print("NBA TOP TRUMPS")
player = []
number_of_cards1= 5
number_of_cards2 = 5
player.append(["Lebron James",27.1,7.4,7.4,38.4])
player.append(["Kevin Durant",27.0,4.1 ,7.1,36.9])
player.append(["Micheal Jordan",30.1,5.3,6.2,38.3])
player.append(["James Harden",25.2,6.3,5.3,34.3])
player.append(["Kobe ... |
eac78e64ee27687bd8dfdaafe280cbef1fae3e56 | davll/practical-algorithms | /LeetCode/29-divide_two_integers.py | 816 | 3.671875 | 4 | # https://leetcode.com/problems/divide-two-integers/
def div_int(x, y):
s = 0
q = 0
# find max s
while x >= (y << (s+1)):
s = s + 1
while s >= 0:
q = q << 1
if x >= (y << s):
q = q | 1
x = x - (y << s)
s -= 1
return q
class Solution:
... |
289cfb4f17537eff916b81990df8a67db951f964 | i-am-rohit/python | /rectangle.py | 312 | 3.953125 | 4 | a = int(input("enter length : "))
b = int(input("enter breadth : "))
class area:
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def rectangle(self):
return self.length * self.breadth
obj = area(a,b)
print(obj.rectangle())
|
cef501c85c67f9aa3fef5547b31f0629539151f7 | aviladiogo/Jogo-de-perguntas-Usando-request-HTTPs-e-API | /Anotações/HTTPRequests.py | 636 | 3.65625 | 4 | """
mandando requisições HTTP para API e uso de JSON
"""
import pip._vendor.requests as requests
import json
import pprint
r = requests.get("https://opentdb.com/api.php?amount=1&category=11&difficulty=easy&type=multiple") #pega as informações do site
pergunta = json.loads(r.text) #transforma as informações do site de... |
f73a83b9f0079bd3fb4b43659af2fef2103d7da4 | NishantLodhi/OpenCV-ImageProcessing-with-python- | /25-(img Gradient--Laplaces ,Sobel).py | 1,693 | 3.921875 | 4 | #Image Gradients
#We will see following functions : cv2.Sobel(), cv2.Scharr(), cv2.Laplacian() etc
#OpenCV provides three types of gradient filters or High-pass filters, Sobel, Scharr and Laplacian.
#Sobel and Scharr Derivatives
"""Sobel operators is a joint Gausssian smoothing plus differentiation operation, so... |
252ab9e30ba0a6ae7d41226f9d970ccae3f5a28b | gelizondomora/python_basico_2_2019 | /Semana 1/practica_4.py | 176 | 3.5625 | 4 | #cambios de tipo de dato
mi_variable = 10
print("El tipo es ",type(mi_variable), mi_variable)
mi_variable = "10"
print("El tipo es ",type(mi_variable), mi_variable) |
f6c387968a5cfd6d45099174e59a06780c4886fb | alikewater/awesome-pandas-practice | /lesson008/008.py | 679 | 3.59375 | 4 | import pandas as pd
def age_18_to_35(a):
return 18<=a<35;
def level_a(a):
return 85<=a<=100
students = pd.read_excel('Students.xlsx',index_col='ID')
# # print(students)
#
#
# # print(students['Age'].apply(age_18_to_35))
#
# students = students.loc[students['Age'].apply(age_18_to_35)]
# print(students['Scor... |
a0b0c64ed28199da28268cb48f74ebeda3e31526 | desrindamala/uin_modularization | /main.py | 745 | 3.546875 | 4 | nama = 'Desrinda Mala'
program = 'Gerak Lurus'
print (f'Program {program} oleh {nama}')
def hitung_kecepatan (jarak, waktu ):
kecepatan = jarak / waktu
print(f'jarak= {jarak / 1000}km ditempuh dalam waktu = {waktu / 60}')
print(f' Sehingga kecepatan = {kecepatan} m/s')
return jarak / waktu
# jarak... |
bf36b7c1f52f95f3c3335009058863554a58d6ae | K-Class/Her-Seviyeye-Uygun-Python-Egzersizleri | /05-Project Euler/02-Cevaplar/py/PE46-Cevap.py | 373 | 3.5625 | 4 | from sympy import isprime as asalMı
sayı = 2
while True:
if asalMı(sayı) or sayı % 2==0:
sayı += 1
continue
olurMu = False
n = 1
while sayı - 2 * n * n > 0:
if asalMı(sayı - 2 * n * n):
olurMu = True
break
n +=1
if olurMu == False:
pr... |
bedb31986e51c824b5511e399d2fd16080c3bbaf | S2KtheGeek/Learn_Python_Free_Professionally | /Day4/Day4.py | 2,410 | 4.40625 | 4 | '''
Hello guys so in todays class we will be learnig about:
Class
Object
attributes
behaviours
Self variable
constructor
Class is known as a user-defined datatype.
Variable - Instance and Class or Static
Types of methods - Instance, Class and Static
Passing members of one class to another - Advanced Concept Needed for ... |
c9ca3357abe783029faff704a20b3eaf95cc77b7 | sarthakjain07/Read_News | /Read_news.py | 1,474 | 3.609375 | 4 | from win32com.client import Dispatch # used to make pronounce function using sapi voice
import requests # used to request data from WEB
import json # used to convert strings in python datatypes
import datetime
def pronounce(str):
'''This function is used to make pronounce any string given to it'''
speak = Dispa... |
13691ef1236a0925b2a5699c03b9507365d186f2 | stjordanis/Hangman | /hangman.py | 1,438 | 4.03125 | 4 | #importing the time module
import time
import getpass
class Hangman():
def __init__(self, answer):
self.answer = answer
def play(self):
name = input("\nWhat is your name? ")
print("\nHello {}, Time to play hangman!".format(name))
time.sleep(1)
print("\nStart guess... |
afb38dc0c698d809fe7f42efb0bf0704ca0b48ea | vsocrates/deeplearning_cpsc663 | /SocratesV_assignment1/pytorchModels.py | 2,719 | 3.796875 | 4 | import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
class LinearFFN(nn.Module):
""" Simple feed forward network with one hidden layer."""
def __init__(self): # initialize the model
super(LinearFFN, self).__init__() # call for the parent class to initialize
... |
1e568a50866e3f518116134061342870cce98bd0 | Easterok/leetcode.problems | /add-two-numbers.py | 1,450 | 3.90625 | 4 | # 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 contains a single digit.
# Add the two numbers and return the sum as a linked list.
# You may assume the two numbers do not contain any leading zero, except the number 0 ... |
30525aa25b1b9a17705752c40e95738a9b7abd44 | dwtcourses/emora_stdm | /emora_stdm/state_transition_dialogue_manager/memory.py | 854 | 3.671875 | 4 |
from collections import deque
class Memory:
def __init__(self, n_OR_collection):
if isinstance(n_OR_collection, int):
self._data = deque([None] * n_OR_collection)
else:
self._data = deque(n_OR_collection)
self._init_vals = list(self._data)
def add(self, item)... |
4a2f03cbfc35016d6c30d853f993adbe64d97f4a | kazuhayase/study | /python/pro-con-python/ch2/sec1_Recur_DFS_BFS/fib.py | 321 | 3.515625 | 4 | '''
Created on 2016/11/26
@author: kazuyoshi
'''
memo=dict()
def fib(n):
if n <=1:
return n
elif n in memo:
return memo[n]
else:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
if __name__ == '__main__':
for i in range(100):
print("fib({})={}".format(i, fib(i)))... |
10f606d6afdf608dd51aa2641237550b75070466 | cryptogeekk/cryptography | /ceaser_encryption.py | 675 | 4.03125 | 4 | text=' ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key=3
def caesar_encrypt(plain_text):
cipher_text=''
plain_text=plain_text.upper()
for l in plain_text:
index=text.find(l)
index=(index+key)%len(text)
cipher_text=cipher_text+text[index]
return cipher_text
def caes... |
52dfc170d81fc297e63fd4aabc47ecf69da5996b | rakeshCoursera/AssignmentsMITPythonProgramming | /Week 2/ps1ex2.py | 144 | 3.75 | 4 | s = 'paeavivamu'
count = 0;
for x in s:
print x
if(x =='a' or x =='e' or x =='i' or x =='o' or x =='u'):
count += 1
print count
|
2307b028ab4a697d38946b283d7e501f85120b4a | hhas/htmltemplate | /sample/demo1alt_quote.py | 1,196 | 3.546875 | 4 | #!/usr/bin/env python3
# Demonstrates how to:
# - manually copy the original Template object, preserving the original for reuse
# - set HTML elements' contents
# - render the template.
from htmltemplate import Template
#################################################
# TEMPLATE
####################################... |
fdafa7cdb9a3f2438827e7a17eb9d211b937a075 | rishikeshpuri/Algorithms-and-Data-Structure | /linked_list/single linked list swap, length of list, delete, merge two llist, remove duplicate, Nth to last node, count occurence, palindrome, move tail to head, sum two list.py | 11,617 | 3.84375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print(self):
currentNode = self.head
if currentNode is None:
print('No node')
return
while currentNode ... |
95ad2471dad5dbbcf667c8368cec1719edf41e5d | mwilso17/python_work | /if statements/alien_colors_1.py | 418 | 4.1875 | 4 | # Mike Wilson 10 June 2021
# This program simulates an alien spaceship being shot down by the player
# and prints a message giving points based on the color of the spaceship.
alien_color = 'red' #this variable can be changed to green, yellow, or another color
if alien_color == 'green':
print("You earned 5 points!")... |
bb2194f0c4212588fcb4477352f5eb860a94818c | Meghashrestha/assignment-python | /7.py | 445 | 4.25 | 4 | #Write a Python function that takes a list of words and returns the length of the
# longest one.
list1 = []
n = int(input("enter number of words you want to enter:"))
for i in range(0, n):
element =str(input())
list1.append(element)
print(list1)
length =len(element)
max = len(list1[0])
temp = list1[0]
for i ... |
232060d9cf25ad680eb59ab61b81f5a1d97d18f4 | Tibisfly/firstExercisesOfPython | /exercises/22-Bottles-Of-Milk/app.py | 534 | 3.875 | 4 | def number_of_bottles():
for i in range(99, 1, -1):
print(f" {i} bottles of milk on the wall, {i} bottles of milk. Take one down and pass it around, {i-1} bottles of milk on the wall.")
for i in range(1):
print(f"{i} bottle of milk on the wall, {i} bottle of milk. Take one down and pass ... |
624b1fd9614b275456728e7763644b5eb2d38e4b | veekaybee/dailyprogrammer | /presidents.py | 672 | 3.734375 | 4 | """
Reddit Daily Programmer #257
Dead Presidents
http://bit.ly/1Xd2qqP
"""
# read CSV, parse birth and death year, append values to list
with open('presidents.csv','r') as f:
next(f) #skip header row
all_years = []
for line in f:
line = line.split(',')
b = int(line[1][-4:])
try:
d = int(line[3][-4:])
... |
5df01a469f9fc98e12aa565c6b1774cb81aa7f63 | zuigehulu/AID1811 | /pbase/day09/code/dict_keywords_give_args.py | 328 | 3.53125 | 4 | def myfun1(a,b,c):
print('a=',a,end =' ')
print(b,end=' ')
print('c=',c,end = ' ')
print()
d ={'a':1,'b':2,'c':3}
myfun1(**d)
myfun1(c=d['a'],b=d['c'],a=d['b'])
myfun1(100,*[200,300]) #正确的
myfun1(*(100,200),300) #正确
myfun1(*[100],*'ab') #正确
myfun1(*[100],200,*[300]) #正确
myfun1(2,b=1,c=3)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.