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 |
|---|---|---|---|---|---|---|
f7eaadb3ee801b8011e2fddd03a055902f2da614 | sohanjs111/Python | /Week 3/For loop/Practice Quiz/question_2.py | 608 | 4.375 | 4 | # Question 2
# Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with
# the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all
# integers before it. For example, the fac... |
7a22126b7d66730558314ad8295c087559ee4b41 | sohanjs111/Python | /Week 4/Graded Assessment/question_1.py | 1,463 | 4.5 | 4 | # Question 1
# The format_address function separates out parts of the address string into new strings: house_number and street_name,
# and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the
# street name which may contain numbers, but never by themse... |
6adef0926886b9f6406f056fb9faef6640068338 | sohanjs111/Python | /Week 4/Lists/Practice Quiz/question_6.py | 957 | 4.40625 | 4 | # Question 6
# The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the
# sentence "Guest is X years old and works as __." for each one. For example, guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'),
# ('Amanda', 25, "Engineer")) should... |
9a07ac20493ab5ecf149fe852b9c953b27d634e9 | sohanjs111/Python | /Week 2/Module 2 Graded Assessment/question_8.py | 141 | 3.71875 | 4 | # Question 8
# What’s the output of this code?
def sum(x, y):
return(x+y)
print(sum(sum(1,2), sum(3,4)))
# Answer is 10
|
3918f8ff48585ae65b1949cc709a8da345d26b93 | sohanjs111/Python | /Week 4/Strings/Practice Quiz/question_2.py | 593 | 4.3125 | 4 | # Question 2
# Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y
# km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2km".
def convert_distance(miles):
km = miles * 1.6
... |
707b9df1653ab97599ee38d5cca68f9da3de9c58 | sohanjs111/Python | /Week 2/Conditionals/Practice Quiz/question_4.py | 337 | 4.0625 | 4 | # Question 4
# Is "A dog" smaller or larger than "A mouse"? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign in the
# following code to let Python check it for you and then answer.
print("A dog" < "A mouse")
print(9999+8888 < 100*100)
# Ans:
#
# True
# False
#
# -----... |
8fee9e7912fabf374b85ca6cb4210542bda5551b | rmperez/GDT-XTV | /xmltree.py | 3,108 | 3.734375 | 4 | #written for Python 2.7.3
#this will only work with the dblp format
#reads in dblpmini.xml and outputs graph.dot
import os
import xml.etree.ElementTree as ET
file = "dblpmini.xml"
stylesheet = "stylesheet.txt"
tree = ET.parse(file)
dblp = tree.getroot()
#styelsheet variables
elementShape = "box"
leafShape = "oval"
m... |
111cc7c50de65724992438bae8ae37869d0beec8 | PenneySoft/codecademy-projects | /games-python/games.py | 9,435 | 3.859375 | 4 | import random
money = 100
#Write your game of chance functions here
# Helper methods
# - - - - - - - -
def validBet(bet):
if bet <= 0:
print("Bet must be a positive amount!")
return False
if bet > money:
print("Insufficient funds! Max bet is " + str(money))
return False
r... |
a9c1374b83be24d8508e027efd0a0883e8cedf0c | hacktheinterview/hacktheinterview | /problems/63/Main.py | 584 | 3.546875 | 4 | from __future__ import print_function
import math
#--SPLIT--
#-class Solution:
# @param a : list of integers
# Modify the array a which is passed by reference.
#- def arrange(self, a):
#--SPLIT--
class Solution:
def arrange(self, a):
pass
#--SPLIT--
if __name__ == "__main__":
test_cases... |
615c579433bd2c31eacc75412eafb19a325f0306 | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-7 - Mamma Mia!/stem_comparacao.py | 1,356 | 4.28125 | 4 | # Se não me engano .title() retorna a string como se fosse um título, ou seja, a primeira letra maiuscula
def sobre_marie():
print("{0:^60}".format('Marie Curie'))
print('Cientista responsável por descrever os elementos químicos Polônio e o Rádio e primeira mulher a ganhar um Prêmio Nobel — Física (1903) e Quí... |
11e2d96faa001bcceb225b58f1121b8b4e2cd4ed | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-5 - Sem condições!/stem.py | 1,672 | 4.125 | 4 | acertou = 0
print(' JOGO DE ADIVINHAÇÃO DA MARIE CURIE')
print('Digite qual alternativa é verdadeira A, B ou C.')
pergunta_1 = input(' Pergunta 1 - Qual área ela trabalhou ?\n A - Engenharia\n B - Ciência\n C - Tecnologia\n Escolha uma alternativa: ')
pergunta_2 = input(' Pergunta 1 - A causa da morte de Marie Currie ... |
e34200e7aa655e007745ff77b1c58c6ce62b525d | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-14- Listas pra que te quero!/reverse-string.py | 536 | 4.1875 | 4 | def reverse_string(str):
str = str[::-1]
return (str)
str = ["1", "2", "3", "4"]
reverse_string (str)
'''O reverse de listas em Python reverte a lista in place, alterando os valores da lista ao invés de criar uma lista nova escrita ao avesso. Como strings em Python são imutáveis, não faz muito sentido qu... |
16c970b7674ea220d5284cdfc8e043b8032d5e23 | AlinesantosCS/vamosAi | /Módulo - 2/Módulo 2-1 - Qual é o significado/tuplas.py | 357 | 3.609375 | 4 | dicionario_telefones = {}
# é parecido com a lista,só mais simplificado
# chave(nome do local) - numero(valor)
# serve para relacionar formulário que refere pessoas com valores específicos
dicionario_telefones = {"João": 89666589,"maria": 1111111}
print(dicionario_telefones)
print("-------------------------------")
p... |
838632c00192ddd52a00f2f5cfb1794e57cd1424 | AlinesantosCS/vamosAi | /Módulo - 2/Módulo 2-8 - Cada um no seu quadrado!/modulo.py | 805 | 4.1875 | 4 | import math
from math import sqrt,floor
# Biblioteca random da classe random -
# Numéros aleátorios de 0 a 1 em float
import random
import emoji
num = int(input("Digite um numero: "))
"""
floor - arrendona para baixo
"""
# Raiz quadrada - Arrendona pra cima
raiz = math.sqrt(num)
print('A raiz de {} é igual a {}'... |
8a99ecb567725253701a8f4f53a11452d0087e87 | AlinesantosCS/vamosAi | /Módulo - 2/Módulo 2-1 - Qual é o significado/ordena_dicionario.py | 590 | 4.15625 | 4 | # dicionario = {"a": 2, "b": 3, "c": 1}
# # O método items() dos dicionários retorna o par (chave, valor)
# # como tuplas de tamanho 2
# print (dicionario.items())
# print(sorted(dicionario.items(), key=lambda x: x[1]))
# def ordena_dicionario(dicionario):
# # Implemente a lógica da função aqui
# ordena = (sort... |
158d57a6b1b3725a57a31536eae40a260828f8af | AlinesantosCS/vamosAi | /Módulo - 2/Módulo 2-7 - Amarrando tudo!/biologia.py | 1,157 | 4.03125 | 4 | # Boa prática colocar como subclasse o object
class Mamifero(object):
def __init__(self, cor_pelo, genero, andar):
self.cor = cor_pelo
self.genero = genero
self.num_pernas = andar
def falar(self):
print("Sou um mamífero!!De cor", self.cor)
def andar(self):
print("Es... |
c0dc618285c0a9b122f56d5e601a72f97477f278 | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-3 - É feijão ou sorvete/vidente.py | 629 | 3.84375 | 4 | nome = input('Qual é o seu nome ?')
filhos = input('Quantos filhos você quer ter?')
cidade = input('Onde gostaria de morar')
profissao = input('Qual é a sua profissão dos sonhos?')
print(' A vidente prevê:', nome,' terá', filhos, ' e viverá em', cidade, 'trabalhando como ',profissao, ' em 2023')
## Formas de fazer pr... |
6856e2c2b2a530b80b3014dcd0697ba7b7dddae1 | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-13 - Moça, pode repetir/while_simples.py | 118 | 3.671875 | 4 | jogar = input("QUER JOGAR ?\n")
while(jogar.lower() == "naoquero"):
jogar= input("Eai tu quer?\n ")
print('FIM') |
7a415664980b2bfb8cc2d3434ff7b0301c494b4b | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-13 - Moça, pode repetir/while_funcao.py | 281 | 3.8125 | 4 | print('MEME BREAKING BAD')
def SAYMYNAME():
say = input("SAY: ")
while say == "IDK":
say = input("SAY: ")
if say == "MYNAMEISWALTERWHITE":
print("YOU'RE GODDAMN RIGHT")
break
else:
print('WRONG')
SAYMYNAME()
|
93800bea6a87bbb79e805582e1b0ef130153dc2b | AlinesantosCS/vamosAi | /Módulo - 1/Módulo 1-3 - É feijão ou sorvete/mais_variaveis.py | 337 | 3.515625 | 4 | soma = 1024 + 2048
multiplique = 1024 * 2048
divida = 2048/1024
subtraia = 1024 - 2048
print('Soma ->',soma)
print('Multiplicação ->',multiplique)
print('Divisão ->',divida)
print('Subtraia ->',subtraia)
num1 = input('Entre com o 1º valor: ')
num2 = input('Entre com o 2º valor: ')
soma = (num1 + num2)
print ("A som... |
768b47b6910d63f54cc746d4d8ba9109c0bd5ab8 | ammar-aq/PIAIC-AI-NumPy-Assignments | /PIAIC109015_Assignment#2(Numpy Fundamentals).py | 3,018 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Numpy_Assignment_2::
# ## Question:1
# ### Convert a 1D array to a 2D array with 2 rows?
# #### Desired output::
# array([[0, 1, 2, 3, 4],
# [5, 6, 7, 8, 9]])
# In[2]:
import numpy as np
a=np.array([[0, 1, 2, 3, 4],[5, 6, 7, 8, 9]])
a
# ## Question:2
# ### H... |
cf5904ab74c56077e0c176816324c8ee836808af | nazhot/Project-Euler-Solved | /Project Euler, Solved, Problem 20, Factorial digit sum.py | 260 | 3.828125 | 4 | def factorial_digit_sum(n):
factorial=1
factorial_sum=0
for num in range(1,n+1):
factorial*=num
for digit in str(factorial):
factorial_sum+=int(digit)
return factorial, factorial_sum
print(factorial_digit_sum(100))
|
1f4b5737453e3a91b6789b92e9545559866c1830 | nazhot/Project-Euler-Solved | /Project Euler, Solved, Problem 26, Reciprocal cycles.py | 907 | 3.5 | 4 | from decimal import *
getcontext().prec = 2000
def reciprocal_cycles(n):
answer = [0,0]
for denom in range(2,n+1):
cycle = ""
fraction=Decimal(Decimal(1)/Decimal(denom))
for digit in range(2,len(str(fraction))):
if len(cycle) == 0:
if str(fraction)[... |
f4a7c0acc177615de2192f5cf9c003696b426584 | nazhot/Project-Euler-Solved | /Project Euler, Solved, Problem 7, 10001st prime.py | 145 | 3.546875 | 4 | num=1
while num<2000001:
num+=2
for b in range(2,num):
if num%b==0:
break
else:
print(num)
|
8500eb7ada69a5ba1b4555c1746c5dc4f9bc3cdd | nazhot/Project-Euler-Solved | /Project Euler, Solved, Problem 1, Multiples of 3 and 5 .py | 380 | 4.0625 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
import time
w=time.time()
total=0
for x in range(1,1000):
if x%3==0:
total+=x
elif x%5==0:
total+... |
92b538fdcfc9e46c483cfdc934aed752439e875e | Hamza122000/Python-projects | /hw7/hw7.py | 7,029 | 3.78125 | 4 |
#==========================================
# Purpose: (checks if there is a common variable between 3 different lists?)
# Input Parameter(s): (grades which represented the students that got goo grades,sleep which represents the students that got good sleep, life which represents the students that have a good socia... |
a532a6e2fd2146e87a49a34b7911c0605513cf24 | HILALOZTEMEL/image-processing | /goruntuİsleme/OpenCV Exercise 2/ResimDönüşümUygulaması(ImageTransition).py | 852 | 3.59375 | 4 | #resimleri birbirleri üzerine ekleyip onların ağırlıkları yoğunluklarını değiştirerel bi resim kaybolcak diğeri çıkacak
import cv2
def nothing(x):
pass
img=cv2.imread("aircraft.jpg")
img=cv2.resize(img,(640,480))
img2=cv2.imread("balls.jpg")
img2=cv2.resize(img2,(640,480))
#üst üste eklediğim değiş... |
244b9515789988292a9b25612e444bdde1d98cc8 | amah0491/FreeCell-with-Python | /deck.py | 2,529 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 11 12:27:09 2017
@author: Dell1
Deck is made up of Cards.The class is initialized by giving start_value,end_value and no.of suits
to be included in the game play.
"""
from cards import Card
import random
face_list=['Ace','2','3','4','5','6','7','8','9','10','Ja... |
beb66ab0fd7d03e14479037c4634da4e96a6ffb8 | vitorhenriquesilva/python-introduction | /zip.py | 357 | 4.25 | 4 | #Funo .zip
#Essa funo utilizada para a concatenao de duas ou mais listas
lista1 = [1, 2, 3, 4 ,5]
lista2 = ["abacate", "bola", "cachorro", "dinheiro", "elefante"]
lista3 = ["R$2,00", "R$5,00", "No tem preo", "No tem preo", "No tem preo"]
for numero, nome, valor in zip(lista1, lista2, lista3):
print(numero, n... |
5b522368cfcd36440bfed3c8d8c7905a00dc0e55 | wk-ff/my-leetcode-python | /23.Merge_k_sorted_lists.py | 1,235 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 3864ms, faster than 12.73%
# 15.6MB, less than 100%
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
i = 0
while i < len(lists):
... |
b926a3a1c767de086f59cfdfe8f09126b358f4ef | rayallen20/data_visualization | /scatter_squares.py | 1,802 | 3.828125 | 4 | # data visualization -- 绘制散点图
import matplotlib.pyplot as plt
# 每个点的X坐标值
x_values = list(range(1, 1001))
# 每个点的Y坐标值
# 下边这个是遍历一个list并将每个value改变后赋值给另外一个list的每个value一种简写
y_values = [x**2 for x in x_values]
# s=200 设置点的尺寸大小
# edgecolors = 'none' 删除数据点的边缘那圈黑色
# c=(红, 绿, 蓝) 其中 每个值均为0~1之间的小数值
# 或 c='red' 直接指定颜色
# 颜色映射: 从起始... |
c75cdf7af2bf932577eeb23addd7dc0ca6ac2f54 | bigalex95/tkinterExamples | /tkinter/tkinterExamples/lesson7/lesson7.py | 1,990 | 3.609375 | 4 | # https://www.tutorialspoint.com/python/tk_grid.htm
# https://www.tutorialspoint.com/python/tk_frame.htm
from tkinter import *
root = Tk()
# frm = Frame(root)
# frm.pack(pady=10)
# 1st Example
# btn7 = Button(frm, text='7', padx=10, pady=5).grid(row=0, column=0)
# btn8 = Button(frm, text='8', padx=10, pady=5).grid(r... |
d49cbdeae69b3cf543fbebe89de8094887361200 | kshama90/quantum-trial | /first.py | 291 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
print ('hey there')
print ('hey world')
c = 8;
a = 6;
b = 7;
d = a + b + c;
print (d)
print ('this file has been changed')
def add(a, b):
c = a + b
return c
s = "the sum of 14 and 565 is "
sum = add(14, 565)
print (s + str(sum))
|
1ed706b713b00745577b2d818118acb0ba897eb1 | Shin-MG/SWP2_AD_project | /code/shuffleWord.py | 1,766 | 3.640625 | 4 | from random import choice, shuffle, randint
from string import ascii_lowercase
class ShuffleWord:
def __init__(self, wordList):
self.word = wordList
self.word_reverse = [self.word[i] for i in range(3)]
for i in range(3, 6):
self.word_reverse.append(self.word[i][::-1])
s... |
4825854f6626acc22a4ac069e62af8886d6b5b8b | arai13/Advanced-Data-Structures-Labs | /Lab 7 (Hash Tables)/ash_lab7_part1.py | 1,568 | 3.921875 | 4 | """
Ashutosh Rai
CS 335, Lab 7: Part 1
ash_lab7_part1.py
"""
# Building of the dictionary, which is implemented using a hash table, for the use case
# Here, the key is the student ID number and the name is the value
student_log = {1434: 'Mark Ruffalo', 2123: 'Rob Stark', 4523: 'Jen Garner', 1246: 'Kina Grannis', 6321... |
0a425c792fcfbf7146881e0bc5b2754f3906e848 | arai13/Advanced-Data-Structures-Labs | /Lab 5 (Binomial Heaps)/tugii_ash_lab5.py | 7,455 | 3.765625 | 4 | """
Tugii and Ash
CS 335
Lab 5 (Binomial Heap)
File Description: The file contains the implementation of a binomial heap, as well as the tests
"""
import unittest
class PriorityQueue:
def peek(self):
raise NotImplementedError
def pop(self):
raise NotImplementedError
def insert(self, key... |
38be82f968354296055d5db29e20afae7805b008 | quadrant26/oldboy_py | /imooc/decorative/decorative2.py | 314 | 3.546875 | 4 | # -*- coding:utf-8 -*-
def deco(func):
def in_deco(x, y):
print('in deco')
func(x, y)
print('call deco')
return in_deco # 必须显示的返回
@deco
def bar(x, y):
print('in bar', x+y)
print(type(bar))
bar(1, 3) # 如果不给 in_deco 不传递参数 会报错,缺少参数 |
e52c79ca788816de3fcc3706da40edc0e61383bf | lukeclopez/CompanyCodingTest | /utils.py | 3,138 | 3.546875 | 4 | from datetime import timedelta, datetime
import iso8601
import constants as c
def get_entries_from_input_file(input_path):
"""
Since each entry is on a
separate line, split on line breaks.
"""
with open(input_path) as input_file:
entries_list = input_file.read().strip().split("\n")
r... |
2b681aa7600dce3bd106c7f293b2d7f5c54dc039 | vedaloliver/Bioinformatics-Rosalind-Problems | /B. Bioinformatics Stronghold/LEXF Enumerating k-mers lexicogaphically/Enumerating k-mers Lexicographically.py | 275 | 3.578125 | 4 | import itertools
from itertools import permutations
letters= 'ABCD'
n = 4
def perm(n, seq):
for i in itertools.product(seq, repeat=n):
print (str(i).replace(',', '').replace('(', '').replace(')', '').replace('\'', '').replace(' ', ''))
print (perm(n, letters)) |
75322530357e8ac71e89ffeace570da74c822c38 | thcyron/adventofcode | /2020/day16.py | 1,495 | 3.59375 | 4 | from math import prod
with open("day16.txt") as f:
blocks = f.read().split("\n\n")
def parse_rule(line):
field, rest = line.split(": ")
constraints = rest.split(" or ")
return (field, [[int(_) for _ in c.split("-")] for c in constraints])
rules = [parse_rule(line) for line in blocks[0].split("\n")]
... |
3799568ed0e8aa594d3a29209e8a4c207e937e70 | thcyron/adventofcode | /2020/day12.py | 1,665 | 3.5625 | 4 | BEARINGS = "NESW"
def move(inst, pos):
a, v = inst
x, y, b = pos
if a == "N":
return (x, y+v, b)
if a == "S":
return (x, y-v, b)
if a == "E":
return (x+v, y, b)
if a == "W":
return (x-v, y, b)
if a == "L":
turns = v // 90
b2 = BEARINGS[(BEARI... |
f2b4ef83953de0fdf78a55ce4634398d21cfa4f1 | Samridhi-88/Interview_Question | /mahasena.py | 523 | 3.796875 | 4 | def function():
soldier=int(input("enter the soldiers ="))
list1=[]
i=1
while i<=soldier:
weapens=int(input("enter the number of weapens ="))
list1.append(weapens)
i+=1
index=0
e_c=0
o_c=0
while index<len(list1):
if list1[index]%2!=0:
o_c+=... |
beb5de9b6eac53c25fe7d67c8470397fff94c3c2 | xjayleex/problem_solving | /hackerrank/shelock-and-array.py | 294 | 3.828125 | 4 | def balancedSums(arr):
# Write your code here
if len(arr) == 1:
print("YES")
return
s = sum(arr)
left = 0
for i, e in enumerate(arr):
s = s - e
if s == left :
print("YES")
left += e
print("NO")
balancedSums([1,2,3,3]) |
2d2ec7bcdb82d8c966c8eb43f745996d48c91670 | fraromesc/conceptos_raspberry | /motordc.py | 1,264 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time as t
GPIO.setmode(GPIO.BOARD)
#Pins 18 22 24 GPIO 24 25 8
Motor1E = 7 # Enable pin 1 of the controller IC
Motor1A = 5 # Input 1 of the controller IC
Motor1B = 3 # Input 2 of the controller IC
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setu... |
4c0a9a53dc382eb3480846ce3678d2146775d885 | sciking/makeyourleft | /myl.py | 5,324 | 3.5625 | 4 | #!/usr/bin/ python-
# -*- coding: utf-8 -*-
import os
import random
turno = 0
planzi = 31
ptua = 4
alpar = 65
spar = 1
coeff = 0
titin = 0
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def invio():
raw_input("Premi invio per continuare")
print """ Benvenuto in Make Your Left, il primo videogioco
nel q... |
145d6e0753890f0633b924b05b067df8f89f9283 | J-in-Japan/snippets | /daily/daily_20190507c.py | 786 | 3.765625 | 4 | # a more efficient approach to the scheduling rooms required problem
# put all the start and end times into an array and sort them
# +1 room for each start and -1 for each end
# max reached is required number of rooms
lectures = [ [13, 15], [11, 13], [4, 7], [1, 5], [3, 6] ]
# construct a action list:
# action[0] -> ... |
83ad107e8628a66b826ad2dbfb3eecda4ccf035c | J-in-Japan/snippets | /daily/map_reduce_filter_zip.py | 881 | 4 | 4 | # playing around with built-in python functions for processing sequences
# map
# apply a function to each element in the iterable
map( int, [ "10", "12", "14", 3.1415926, "5L" ] )
# >> [10, 12, 14, 3, 5]
# reduce
# apply a function to each element in the iterable to generate a cumulative result (can also supply an i... |
412abc6d2cfa356f61ddbca0067825c5034f4e92 | J-in-Japan/snippets | /daily/daily_20190520.py | 515 | 3.59375 | 4 | import math
value_stream = [2,1,5,7,11,3,3,7,12,1]
sorted = list()
print(sorted)
i = 0
for v in value_stream:
sorted.insert(i, v)
sorted.sort()
median = None
if len(sorted) == 1:
meidan = sorted[0]
elif len(sorted) == 2:
median = (sorted[0] + sorted[1]) / 2
elif len(sorted) ==... |
d3603755430699debce016996523069ba407d04c | J-in-Japan/snippets | /daily/daily_20190515.py | 954 | 3.78125 | 4 | # implement run-pass string encoding and decoding
# AAABCC = A3B1C2
def run_length_encode(s: str):
enc_str = ''
current_char = ''
current_char_count = 0
for i in range(len(s)):
if i == 0:
current_char = s[i]
current_char_count = 1
else:
if s[i] == cur... |
ea3efdc37211124dbf44427a52602bd13e9e36c0 | NCPCode/code-samples | /day1/starter.py | 1,951 | 4.09375 | 4 | # text adventure game for NCP code
# this isn't much now, but soon you will be able to make more advanced games
# it might seem like a lot of code, but it's made up of simple pieces
# next week, we can learn to simplify this a bit
print("You are in a forest with plentiful trees. To your left, you see a cave. To your ... |
9ef292734da1c77d8332ee2837cfb12272eb69ea | SenFuerte/dt211-3-cloud | /Euler/Sol_nr7.py | 462 | 3.84375 | 4 | def isprime(n):
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def main():
Switch = 1
number = 1
primes = 1
while Switch == 1:
... |
df5bc87af9dcd1f949a805830983c5b36b6a7d28 | csnake-org/CSnake | /src/csnListener.py | 2,386 | 3.515625 | 4 | ## @package csnListener
# Definition of observer pattern related classes.
class Event:
""" Generic event class. """
def __init__(self, code, source):
self.__code = code
self.__source = source
def GetCode(self):
return self.__code
def GetSource(self):
return self._... |
aa24c3795ee319d1c939f02d1e565e9562c05fdb | ZeLarpMaster/JDISAcademy | /examples/iterators.py | 503 | 3.8125 | 4 | class MonIterateur:
def __init__(self):
self.x = 0
def __iter__(self):
return self
def __next__(self):
self.x += 1
if self.x >= 10:
raise StopIteration()
return self.x
it = iter(MonIterateur())
print(it) # <__main__.MonIterateur object at ...>
assert ... |
ba47cbdd450985c93a29d7d4cdae7d853a06db08 | ZeLarpMaster/JDISAcademy | /examples/classes.py | 923 | 3.609375 | 4 | class Chose:
def __init__(self, x):
self.x = x
def get_x(self):
return self.x
chose = Chose(42)
print(type(chose)) # <class '__main__.Chose'>
print(dir(chose)) # [... méthodes spéciales ..., 'get_x', 'x']
AutreChose = type(
"Chose", (object,), {"get_x": Chose.get_x, "__init__": Chose.... |
8fee5945388ac7a4011f02709ae6e0e78cc410bb | varshinirajkumari/Sentiment-Analysis | /sentiment.py | 676 | 3.546875 | 4 | #How to perform sentiment analysis in python?
import nltk
nltk.download('vader_lexicon')
nltk.download('punkt')
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sid = SentimentIntensityAnalyzer()
message_text = '''kiddy is a good boy'''
print(message_text)
scores = sid.polarity_scores(message_text)
... |
d1fbfee902df6df0361b7160ff9d229baa05b439 | kmanadkat/ed-python-sde-prep | /Python For Programmers/Module 2 OOPs/01 Classes and Objects/01_class_basics.py | 280 | 3.53125 | 4 | class Employee:
def __init__(self, ID=None, salary=0, department=None) -> None:
self.ID = ID
self.salary = salary
self.department = department
Steve = Employee(128, 2500, 'Human Resource')
Mark = Employee()
print(Steve.__dict__)
print(Mark.__dict__)
|
898b3fbcb709edcb1b59797085587217a5418889 | kmanadkat/ed-python-sde-prep | /Python For Programmers/Module 2 OOPs/01 Classes and Objects/03_class_variables_2.py | 354 | 3.984375 | 4 | class Player:
# Class Variable
teamName = 'India'
teamPlayers = []
def __init__(self, name) -> None:
# Instance Variable
self.name = name
self.teamPlayers.append(self.name)
p1 = Player("Rohit")
p2 = Player("Rahul")
print(p1.__dict__, p1.teamName, p1.teamPlayers)
print(p2.__dic... |
a8e00329dbf7ae7460fdd2e6e5fa21277cd080de | manan-malhotra/LP3-CLoud- | /Q8.py | 119 | 3.59375 | 4 | n=int(input())
op=0
for x in range(0,n,2):
if(n-x>=0):
op+=(n-x)
print("sum_series("+str(n)+")->" +str(op)) |
b5ddb21b3f06e0574991987ccf8ec034a7b1dfa1 | KhalidVHS/BubbleBlaster | /BubbleBlast - With comments.py | 11,287 | 3.703125 | 4 | """
568789
Abdur Khalid
This is my pygame with the name of "Bubble Blast" The goal of the game is to avoid the incoming bullets, and if you get hit by it, then the bubble pops and you lose.
Ive used many different modules in order to make the game stylistic but as simple as possible and using the least amount of ... |
1aed5b282350d500e9828e50a75e0bdd743b3542 | Greeshma-DA/Data-Analytics_Projects | /Fake News Detection/DA_Project_Fake news detection.py | 1,447 | 3.53125 | 4 | #!/usr/bin/env python
# coding: utf-8
# FAKE NEWS DETECTION WITH PYTHON
# In[11]:
import numpy as np
import pandas as pd
import itertools
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import PassiveAggressiveClassifier
from... |
98b282da45e10ab01fcc4e7eeb0959fdd292b928 | Exileus/CIFO-TetriminoFitter | /library/hill_climbing/hc.py | 3,958 | 3.59375 | 4 | import random, copy
from library.main import BasePopulation, Individual
import numpy as np
def hill_climb(
pop: BasePopulation,
verbose: bool = False,
hardstop: int = 100,
) -> Individual:
"""Hill Climb on a population of individuals by giving the function and
fitness function and a function to ge... |
69fd417b735877ae844880c2f8ed10f80d33413a | khayes25/recursive_card_sorter | /merge_sort.py | 1,634 | 4.125 | 4 | """
Merge Sort Algorithm
"""
#Class Header
class Merge_Sort :
def merge_sort(list, left, right) :
if(left < right) :
middle = (left + right) / 2
merge_sort(list, left, middle)
merge_sort(list, middle + 1, right)
merge(list, left, middle, right)
de... |
229c166d793c2ed92d83f72f9c52e38392b69983 | ReDi-school-Berlin/lesson-4-examples | /range_example.py | 658 | 4.0625 | 4 | number = 10
if number < 10:
print("number is less than 10")
elif number < 20:
print("number is between 10 and 20")
elif number < 30:
print("number is between 20 and 30")
elif number < 40:
print("number is between 30 and 40")
elif number < 50:
print("number is between 40 and 50")
elif number < 60:
... |
96f8731cc5db198e5b52d383d2fd384c890702f8 | ilopezgazpio/UD_Intelligent_Systems | /1 - Introduction/first_steps_python.py | 5,174 | 3.90625 | 4 | '''
First steps with Python
Intelligent Systems - University of Deusto
Inigo Lopez-Gazpio
'''
#---------------------------------------------------------------------------
# This script aims to present the general sintax of Python briefly.
# It condenses common operations needed during the Subject
#-------------------... |
bcf09bb41bf2055c53bc9574b129779d3acdeae4 | magicbeans817/likememes | /Data_processor.py | 21,620 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# Data processor:
# In[3]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import matplotlib.patches as mpatches
# In[4]:
class Summary:
def __init__(self, data):
self.data = data
#define self.rele... |
946cfd36478d266baab9c7d712eb04042d47ff15 | sdbonin/SOQresearch | /dscrt_r-swap.py | 4,234 | 3.671875 | 4 | '''
Code synopsis:
This code takes some quaternion q, and rotates it (RqR_dag) with a random unit quaternion R.
These rotations are repeated with different random R's to build up a statistical
description of 'random quaternion rotations'. Ultimitely this code will show the distribution
of angles between the original q... |
05a382b493a8fabbe8204d17a296cc21daca49a9 | yevheniyku/Cloud-and-Big-Data | /MapReduce Programming/1.1. Distributed Grep/p11_mapper.py | 557 | 3.9375 | 4 | #!/usr/bin/python
import sys
import re
###################################################################
# Busca las lineas de texto donde aparece la palabra buscada
###################################################################
def mapper(w):
for line in sys.stdin:
line = re.sub( r'^\W+|\W+$', '',... |
e36278cecd327932cf31a32a9d03e5bde0c409f6 | yevheniyku/Cloud-and-Big-Data | /MapReduce Programming/1.2. Count URL Access Frequency/p12_reducer.py | 666 | 3.6875 | 4 | #!/usr/bin/python
import sys
###########################################################
# Recibe la entrada por stdin y calcula el numero de veces
# que una url ha sido accedida
###########################################################
def reducer():
previous = None
sum = 0
for line in sys.stdin:
... |
c65a5f380da249eae4db741f146d2cc6e983dc84 | Gopied/gauthier_aubert_python_exo | /alumettes.py | 396 | 3.625 | 4 | n=21
while n>0:
j=-1
while j<1 or j>3 or j>n:
j=int(input("Combien d'allumettes?"))
n=n-j
if n==0:
print("Dommage, perdu !")
else:
print("Il en reste ",n)
if n%4==3:
p=2
elif n%4==2:
p=1
elif n%4==0:
p=3
else:
p=1
print("Le bot en prends ",p)
n=n-p
... |
8c8fecc8d901058155572646e294a4557682cc41 | peteksu/internshipHomeworks | /Homework1/largestprimefactor/main.py | 401 | 4.0625 | 4 | import math
def prime_check(number):
is_prime = True
for i in range(2,int(math.sqrt(number))+1):
if number % i == 0:
is_prime = False
continue
return is_prime
enteredNumber = int(input("please enter a number:"))
largest_prime = 1
for i in range (2, int(math.sqrt(enteredNumber))):
if enteredN... |
eaf65acfeab94d73123328a4655e3e63dd5dbb81 | chukwudiMorganHezekiah/Python-Scripts | /copy_cut.py | 1,018 | 3.5 | 4 | import os
import shutil
def run():
current_dir =input('Enter the directory where the files can be found \n')
current_dir = current_dir.replace("\\",'/')
location = input('Enter the directory where the files should be copied to \n')
location = location.replace("\\",'/')
checking = input('What is th... |
898526d27dd7c2fef67e3f30a32b5540dd30d3d9 | Flynn-Tinker/Python_Practice | /password_checker.py | 324 | 3.828125 | 4 | import sys
MASTER_PASSWORD = "opensesame"
password = input("Please input password: ")
attempt_count = 1
while password != MASTER_PASSWORD:
if attempt_count > 3:
sys.exit("Too many attempts")
password= input("Invalid password, try again: ")
attempt_count += 1
print(attempt_count)
print("Welcom... |
3d91ab51836d93a066c59b42ebf999afbf118583 | chakrikaratra/textAdventure | /prom.py | 2,046 | 4.09375 | 4 | start = '''
You wake up one morning and notice that out of all your friends, you are the only one without a prom date.
"Should I snag a date?" you wonder.
'''
print(start)
print("Do you want to know your ideal prom date?")
print("Type 'yes' or 'no'.")
user_input = input()
if user_input == "no":
print... |
f513b01f77fdad1ce9dc13c7ea3d0cfdfcb60205 | pananer02/Python-3.7.3 | /งานส่ง/Ex1_3_6206021610021.py | 514 | 3.703125 | 4 | ''' ***************************
6206021610021
ปาณชัย เตชะไพศาลกุล
ตอน 1
**************************'''
#main program 3
int1 = input("Enter integer number 1 : ")
int2 = input("Enter integer number 2 : ")
int3 = input("Enter integer number 3 : ")
value1 = int(int1)
value2 = int(int2)
value3 = int(int3)
p... |
02a5660cf165020008cf85e1cfa1382291a23d5a | andrewlopez1/compilers | /Assignment1.py | 4,565 | 3.65625 | 4 | #Input: string containing any number of lexemes seperated by whitespace or separators
#Output: list of (token, lexeme) pairs for Identifier, Integer, Real, Keyword, Operator and Seperator tokens
import os
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
digits = '1234567890'
separators = '[]();:{},'
op... |
e76441c4e384ce8d9b1a5bf5059c227cc058cedb | tilenmiklavic/Dragon_Hack_Wadi_Rum | /predictionTree.py | 4,784 | 3.59375 | 4 | # Applying decision tree algorithm
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Importing the dataset
df = pd.read_csv("./bin/public/data.csv")
heart_data = df
# number of dead people in dataset
print(heart_data[heart_d... |
c92cb913b5561e3d8664f1305b8280b000d130f9 | Pruneyy/rpg | /classes.py | 3,727 | 3.578125 | 4 | # Classes for simple rpg
# Imports
import random
# Dice rolling function
def die(sides):
return random.randint(1, sides)
# Character super class
class Character:
# All characters have a name, hit chance, dodge change, inventory and exp
def __init__ (self, name, hp, hit, dodge, inv, exp)... |
ec92510dc864df7fe139ab92727c425bf391d810 | HackUCF/Alexa-Skill | /test/test_schedule.py | 3,142 | 3.578125 | 4 | from schedule import schedule
from datetime import datetime
import arrow
def test_get_next_event():
"""
get_next_meeting() should return a python dict containing the following
information, so we are going to check typing.
{
'name': 'General Meeting'
'date': '2019-11-01T00:00:00+00:00' ... |
4645d92ec3a2a6fba996bddf69a75d9064700cd7 | DenerBEM/DisasterResponse | /data/process_data.py | 3,771 | 3.546875 | 4 | # import libraries
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import sys
def load_data(messages_filepath, categories_filepath):
'''
Description: This function loads two datasets and makes
an inner merge using the column 'id' as key.
INPUT:
Two files paths in csv f... |
91664fcc28346615811824c481bb88091887748d | Triple-Z/LeetCode | /py3/14.py | 493 | 3.5 | 4 | class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
min_len, prefix = len(strs[0]), ""
for str in strs:
if len(str) < min_len:
min_len = len(str)
for i in range(min_len):
for j in range(len(strs)):
if j == len(... |
44bda06ab9d0f0b1f00950f1d570a64906c39e89 | Triple-Z/LeetCode | /py3/20.py | 787 | 3.734375 | 4 | class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
para_stack = list()
for char in s:
if char in ('(', '{', '['):
para_stack.append(char)
elif char in (')', '}', ']'):
para_pair = {
... |
b16802cea3e32892e7953167eb4932457c6e41bb | mr-akashjain/Basic-Python-Stuff-For-Fun | /pigLatin.py | 2,301 | 4.125 | 4 | from time import sleep
sentence = input("Hi, They call me latin pig translator. Enter a sentence to have fun with me:")
sleep(4)
print("Thanks for the input!! Fasten your seatbelt as you are about to enter into my world")
sleep(3)
print("I know my world is small, but it is mine!")
sleep(2)
say_something = inpu... |
2d08a0ff5d0a93a35d59586d3d53043b0b0222bb | shivangishuklas/patient_prioritizer | /patient_prior.py | 6,112 | 3.703125 | 4 | import pandas as pd
def calScore(name,age,gender,height,weight,spo2,heartrate,resprate,bodyt,cough,soret,breathdif,tiredness,pregnant,preexist):
gender = gender.strip()
pregnant = pregnant.strip()
preexist = preexist.strip()
body_mass_index = 0.0
death_rate_age = 0.0
bmi_weight = 0... |
45372d2305393a4430f3c8a0dcf2da7594e7559d | paulcijo/python-aimit-2k18 | /7.py | 191 | 3.671875 | 4 | # 7.py: Python lists
vals = [4, 5, 6, 1, 2, 4, 2, 44, 5]
sum = 0
for i in range(0, 9):
sum += vals[i]
print sum
vals.insert(0, 10)
print(vals)
print( 12 in vals)
vals.sort()
print vals |
2c3439ef1dba0e9c283275efb5ada1f479bfa561 | ab-gh/cs50w | /lectures/wk2/python.py | 485 | 3.875 | 4 | class point():
def __init__(self, x, y):
self.x = x
self.y = y
p = point(2, 8)
print(p.x)
print(p.y)
class Flight():
def __init__(self, capacity):
self.capacity = capacity
self.passengers = []
def add(self, passenger):
if not self.open_seats():
return F... |
2e8beb648ca0a9d196372668205dc32c959d90be | vickichowder/interview-cake | /delete-node/deletenode.py | 750 | 3.90625 | 4 | class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def delete_node(node):
if node.next is None:
node.value = None
else:
next_node = node.next
try:
node.value = next_node.value
node.next = next_node.next
... |
6ad4055a5fe48a2b89d7a5cba40e66977d1c51d3 | anusha4999/anusha | /python/pythonsamples/day2/aaa.py | 305 | 3.84375 | 4 | # a=[1,2,3,4]
# print(a.reverse())
# # a.reverse()
# # print(a)
# print(a.sort(reverse=True))
a=[i*i for i in range(1,10)]
print(a)
a=[]
b=[]
d={}
n=int(input("how many elements u want to add in dict"))
for i in range(1,n):
a=(int)(input("enter key"))
b=a*a
for i in a:
for j in b:
d[i]=j
print(d) |
3d1ca64aa02549f628d628cee046951cd08bf46c | anusha4999/anusha | /python/tasks/dictionaries/d6.py | 105 | 3.6875 | 4 | d={1:'anusha',4:'pavani',2:'pallavi',3:'geetha'}
for key in sorted(d):
print("%s: %s" % (key,d[key])) |
370cd04bf78cf506d98247ac955fee88079e36fa | anusha4999/anusha | /python/tasks/sets/s5.py | 123 | 3.875 | 4 | #s1={1,2,3,4}
# s1.add(5)
# print(s1)
s2={1,3,4,5}
for i in range(1,6):
n=int(input("enter n value"))
s2.add(n)
print(s2) |
2fec48bb07fb5007d1030e79e70df2a2401d31d4 | anusha4999/anusha | /python/tasks/list/l6.py | 80 | 3.875 | 4 | num=int(input('enter number'))
for i in range(1,21):
print(num,'*',i,'=',num*i) |
ee1933afe0689e2996a21d08c17eae18d5dc1762 | anusha4999/anusha | /python/tasks/sets/s2.py | 145 | 4 | 4 | string=set(str(input("enter the string")))
count=0
vowels=set('aeiou')
for i in string:
if i in vowels:
count+=1
print('the vowels are',count) |
2a04c96432ae769341e9cf6c8b98fd6957efb63e | anusha4999/anusha | /python/pythonsamples/day2/task1.py | 221 | 3.796875 | 4 | n=int(input("enter how many times u want"))
a=[]
b=[]
d={}
for i in range(1,n):
a=input('enter key')
b=input('enter value')
#a.append(b)
#d=a.append(b)
#c=dict(zip(a,b))
for i in a:
for j in b:
d[i]=j
print(d) |
5872ba739592e0f5239e39de077fb98b3f1d5fca | ficodegallo/dat-chapter-1 | /labs/exercise_3a/solution_3a.py | 483 | 3.90625 | 4 | #import the csv library
import csv
#read in the rock.csv file and save as rock_data
with open('rock.csv', 'rb') as rock_data:
#store rock_data into reader
reader = csv.reader(rock_data)
#count the amount of songs released in 1981
count = 0
for row in reader:
if row[2] =='1981':
count += 1
... |
70c4545afa20736c87286d18b318cb704a369190 | hgaziuddin/Baking | /MetricToUsConversions.py | 881 | 4.03125 | 4 | def milli_to_teaspoon(milli):
milli = float(milli)
teas = milli / 5
teas = str(teas)
milli = str(milli)
print(milli + " milliliter(s) equals " + teas + " teaspoon(s)")
def teaspoon_to_milli(teas):
teas = int(teas)
milli = teas * 5
milli = str(milli)
teas = str(teas)
print(teas ... |
b3e6c321fa6a686982a79cad29307fc2fbcd2343 | JariGitmanen/python-commands | /wordfind.py | 296 | 3.796875 | 4 | word=0
msg=input("Enter any message: ")
search=input("What word are you looking for?: ")
i=0
while i<len(msg):
if msg[i]==search[0]:
if msg[i:i+len(search)]==search:
word=word+1
i=i+len(search)-1
i=i+1
print("There are",word,"of the word","'",search,"'","in this sentence.")
|
0bf9cdf29be674112982ae7d6f7097e70a13c41c | JariGitmanen/python-commands | /result2.py | 290 | 3.90625 | 4 | physics=80
chemistry=100
math=95
total=physics+chemistry+math
per=total*100/450
print("physics: ",physics)
print("chemistry: ",chemistry)
print("math: ",math)
print("-----------------------")
print("total marks: ",total)
print("percentage: ",per)
print("-----------------------") |
540da655ca8df0395653b8f05b990d8ff582f6d2 | JariGitmanen/python-commands | /caplower.py | 123 | 3.8125 | 4 | A = input("Enter any letter: ")
if ord(A)>=65 and ord(A)<=90:
print(chr(ord(A)+32))
else:
print(chr(ord(A)-32)) |
f134ee0613c18c526f3a08a44c1aa95e4810878a | sexettin78/zipcrack | /sxzipcrack.py | 2,291 | 3.6875 | 4 | print("\033[92m")
print('''
.--------.
/ .------.
| |
_| |________| |_
.' |_| |_| '. Wordlistiniz var mı?
'._____ ____ _____.'
| .'____'. | (Yok seçeneği işaretlenirse program sizin için oluşturacak)
'.__.'.' '.'.__.'
'.__ |Sxtool| __.| 1-) Wordlistim var
| '.'.____.'.' |... |
84b35e76c7fd1c9206f27f3f19879bf3785ab8e0 | ricardostange/classes | /new_base.py | 507 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 23:57:14 2017
@author: Ricardo
"""
def new_base(number, base):
nNumber = [] #number will be represented as a list of numbers
assert ((number > 1) and (number%1) == 0)
while number > 0:
c = number % base
number -= c
... |
aee923eb0dbe70ddd6e452b94018c57327773bbe | ricardostange/classes | /sha_brute_force.py | 797 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 22:55:03 2017
@author: Ricardo
"""
import hashlib
import time
def hash_str(s):
assert type(s) == str
h = hashlib.sha256(s.encode('ascii'))
return h.hexdigest()
def find_8_numerals_pass(passHash):
for i in range(10**9):
p ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.