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 |
|---|---|---|---|---|---|---|
ef045cb0440d1fe1466a7fda39915e68db973872 | mwnickerson/python-crash-course | /chapter_9/cars_vers4.py | 930 | 4.1875 | 4 | # Cars version 4
# Chapter 9
# modifying an attributes vales through a method
class Car:
"""a simple attempt to simulate a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car"""
self.make = make
self.model = model
self.year = year
se... |
7e79127380cc86a94a1c4c5e836b8e00158481dc | mwnickerson/python-crash-course | /chapter_7/pizza_toppings.py | 321 | 4.28125 | 4 | # pizza toppings
# chapter 7 exercise 4
# a conditional loop that prompts user to enter toppings
prompt ="\nWhat topping would you like on your pizza?"
message = ""
while message != 'quit':
message = input(prompt)
topping = message
if message != 'quit':
print(f"I will add {topping} to your pizza!"... |
8b5ff94d3edf0eca7b35b1c67ea764816fe236aa | mwnickerson/python-crash-course | /chapter_6/cities.py | 623 | 4.125 | 4 | # Cities
# dictionaries inside of dictionaries
cities = {
'miami': {
'state': 'florida',
'sports team': 'hurricanes',
'attraction' : 'south beach'
},
'philadelphia': {
'state': 'pennsylvania',
'sports team': 'eagles',
'attraction': 'liberty bell'
},
'new york city': {
'state': 'new york',
'sports team': '... |
1520778db31a0b825694362dea70bd80327640d9 | mwnickerson/python-crash-course | /chapter_6/rivers.py | 605 | 4.5 | 4 | # a dictionary containing rivers and their country
# prints a sentence about each one
# prints river name and river country from a loop
rivers_0 = {
'nile' : 'egypt',
'amazon' : 'brazil',
'mississippi' : 'united states',
'yangtze' : 'china',
'rhine' : 'germany'
}
for river, country in rivers_0.ite... |
beb9bfc94e248c1b718c2ce8f01610f1e3456460 | mwnickerson/python-crash-course | /chapter_12/keys/keys.py | 1,385 | 3.984375 | 4 | # Keys
# chapter 12 exercise 5
# takes a keydown event
# prints the event.key attribute
import sys
import pygame
from settings import Settings
class KeyConverter:
"""overall class to manage program assets and behavior"""
def __init__(self):
"""initialize the program and create the resources"""
... |
3fb67a13e7194cdddc76ed12ffc867579dec68f3 | mwnickerson/python-crash-course | /chapter_10/number_writer.py | 240 | 3.828125 | 4 | # Number Writer
# Chapter 10: Storing Data
# using json.dump() and json.load()
# stores a list in a json
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'jsons/numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f)
|
94b3e3fff962a1311e9e02f1f653ddc75bea9ebb | mwnickerson/python-crash-course | /chapter_5/voting.py | 126 | 3.9375 | 4 | # if statement voting programs
age = 19
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
|
cb948a45e656ffd376acf055c8c5e58d50251f2e | mwnickerson/python-crash-course | /chapter_3/guest_changes.py | 582 | 3.53125 | 4 | # one of the guests cant make it, program removes them and invites someone else
guest = ['alexander the great', 'genghis khan', 'kevin mitnick', 'J.R.R Tolkien', 'John F. Kennedy']
print(f"Unfortunately, {guest[4].title()} can't make it to the party.")
guest[4] = 'babe ruth'
print(f"Dear {guest[0].title()}, \nPlease j... |
fea3809ec2bf488d0867160cf88fbd57d67f3e15 | mwnickerson/python-crash-course | /chapter_11/city_functions.py | 342 | 3.9375 | 4 | # City Functions
# Chapter 11 Exercise 2
# added a population function
def get_city_country(city, country, population=''):
"""Generate city country formatted"""
if population:
city_country = f"{city}, {country} - population {population}"
else:
city_country = f"{city}, {country}"
return c... |
02d3bcd27304830c1c4b1c11ef10139b2f0dcaf9 | mwnickerson/python-crash-course | /chapter_10/greet_user.py | 212 | 3.703125 | 4 | # Greet User
# Chapter 10: Storing Data
# reading user generated data
import json
filename = 'jsons/username.json'
with open(filename) as f:
username = json.load(f)
print(f"Welcome back, {username}!")
|
22bdf928b3a3d79e5dccd1361536f8fb7f0136f1 | mwnickerson/python-crash-course | /chapter_5/voting_vers2.py | 218 | 4.25 | 4 | # if and else statement
age = 17
if age >= 18:
print("You are able to vote!")
print("Have you registered to vote?")
else:
print("Sorry you are too young to vote.")
print("Please register to vote as you turn 18!")
|
cbe4ce4d644fcda766dfd72b095879a5ca2d2590 | mwnickerson/python-crash-course | /chapter_7/counting.py | 147 | 3.796875 | 4 | # Counting
# chapter 7
# the while loop in action
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
|
acefd9c2e8ff40edf60320a9ea1b18b5477b0afb | mwnickerson/python-crash-course | /chapter_6/alien_vers5.py | 184 | 4.25 | 4 | # Modifying values in a dictionary
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0 = {'color' : 'yellow'}
print(f"The alien is {alien_0['color']}.")
|
a934663927b79f54e0169eea362ad4e85ac9cbdf | mwnickerson/python-crash-course | /chapter_8/cities.py | 333 | 4.09375 | 4 | # Cities
# Chapter 8 exercise 5
# a function that take name and city and retruns a statement
# has a default city and country
def describe_city(city='Miami', country='U.S.A'):
print(f"{city.title()} is in {country.title()}")
describe_city()
describe_city('paris','france')
describe_city('philadelphia')
describe_cit... |
d44d5e2f17ffcb2e7966299ded7d054d7d05de7b | mwnickerson/python-crash-course | /chapter_8/t_shirt_vers2.py | 473 | 3.96875 | 4 | # T-Shirt Version 2
# Chapter 8 exercise 4
# take size and message and returns a statement
# large is the default size
def make_shirt(shirt_size='large', shirt_message='I love python'):
"""Takes a shrit size and message and printsmessage"""
"""default size is large"""
print(f"The shirt is {shirt_size} and ... |
9c94f5cb44b8a60ad3e9fe66a58546b624b2739f | mwnickerson/python-crash-course | /chapter_5/videogame_condtional.py | 1,486 | 3.6875 | 4 | # a series of conditional tests regarding video games
video_game = 'elden ring'
print("Is the video game Elden Ring?")
print( video_game == 'elden ring')
print("Is the video game Call of Duty?")
print( video_game == 'Call of Duty')
good_game = 'parkitect'
print("\nIs the good video game parkitect?")
print(good_game =... |
6fcb027e818ed15791490d49ffcfd6ffc9b146d7 | mwnickerson/python-crash-course | /chapter_5/alien_colors3.py | 658 | 3.75 | 4 | # If, elif, else alien color scoring
#round 1
alien_color = 'red' # 15 point score
if alien_color == 'green':
print('You scored 5 points')
elif alien_color == 'yellow':
print('You scored 10 points')
else:
print('You scored 15 points')
# round 2
alien_color = 'yellow' # 10 point score
if alien_color == 'green'... |
0db4acabc7715624030d1d0a257a4ae90c2034c7 | hangnguyen81/HY-data-analysis-with-python | /part02-e09_rational/rational.py | 1,097 | 4.03125 | 4 | #!/usr/bin/env python3
class Rational(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"{self.x}/{self.y}"
def __mul__(num1, num2):
return Rational(num1.x*num2.x, num1.y*num2.y)
def __truediv__(num1, num2):
return Ration... |
7393500c1f9e8b7d3e3ceafce7f4e923d9111ae1 | hangnguyen81/HY-data-analysis-with-python | /part02-e13_diamond/diamond.py | 703 | 4.3125 | 4 | #!/usr/bin/env python3
'''
Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape.
Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond.
Do this using the eye and concatenate functions of NumPy and array slicing... |
13b2ad577d87bdb7efff93a084208f42f71a359b | hangnguyen81/HY-data-analysis-with-python | /part01-e06_triple_square/triple_square.py | 432 | 4.09375 | 4 | #!/usr/bin/env python3
def triple(x):
#multiplies its parameter by three
x = x*3
return x
def square(x):
#raises its parameter to the power of two
x = x**2
return x
def main():
for i in range(1,11):
t = triple(i)
s = square(i)
if s>t:
break
... |
14f3fd6898259a53461de709e7dc409a28ba829f | hangnguyen81/HY-data-analysis-with-python | /part01-e07_areas_of_shapes/areas_of_shapes.py | 902 | 4.15625 | 4 | #!/usr/bin/env python3
import math
def main():
while 1:
chosen = input('Choose a shape (triangle, rectangle, circle):')
chosen = chosen.lower()
if chosen == '':
break
elif chosen == 'triangle':
b=int(input('Give base of the triangle:'))
h=int(in... |
81cc900e00edcbc8992a0f73fc3332b1e007b7bf | Iain-Forbes/static_dynamic | /part_2_code/specs/card_game_tests.py | 743 | 3.828125 | 4 | import unittest
from src.card import Card
from src.card_game import CardGame
class TestCardGame(unittest.TestCase):
def setUp(self):
self.ace = Card("Spades", 1)
self.card = Card("Clubs", 3)
self.card1 = Card("Hearts", 10 )
self.hand = [self.ace, self.card, self.card1]
self... |
554a21528be4e8dc0ecdd9635196766071c0e4a0 | Julian-Arturo/FundamentosTaller-JH | /EjercicioN9.py | 1,323 | 4.59375 | 5 | """Mostrar en pantalla el promedio
de un alumno que ha cursado 5 materias
(Español, Matemáticas, Economía, Programación, Ingles)"""
#Programa que calcula el promedio de un estudiantes que cursa 5 materias
print ("Programa que calcula el promedio de un estudiantes que cursa 5 materias")
matematicas = 45
español = ... |
a5df0217059401b9de8e2663b6034a7bb31bb220 | sage-kanishq/PythonFiles | /Advanced/Async/theory.py | 266 | 3.5 | 4 | class Employee:
def __init__(self,firstname,lastname):
self.firstname = firstname
self.lastname = lastname
self.email = firstname+"."+lastname+"@company.com"
def fullname(self):
return self.firstname+" "+self.lastname
|
dba05501c8942049adee9f14b93332c6c67147b2 | wangjiancheng-123/datascience | /数据分析/day01/demo06_stack.py | 360 | 3.5 | 4 | #demo06_stack.py 组合与拆分
import numpy as np
a = np.arange(1, 7).reshape(2, 3)
b = np.arange(7, 13).reshape(2, 3)
print(a)
print(b)
c = np.hstack((a, b))
print(c)
a, b = np.hsplit(c, 2)
print(a)
print(b)
c = np.vstack((a, b))
print(c)
a, b = np.vsplit(c, 2)
print(a)
print(b)
c = np.dstack((a, b))
print(c)
a, b = np.ds... |
6e41091d728a2a31ad0a425c5ce928aac4f6810a | saran1211/rev-num | /swapbit.py | 77 | 3.6875 | 4 | a=int(input('enter the num1'))
b=int(input('enter the num2'))
a^b
print(b,a)
|
c020ad42e860dfa378b7fde09f82f4867b71b3c2 | mari756h/The_unemployed_cells | /model/cnn.py | 4,129 | 3.625 | 4 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class TextCNN(nn.Module):
""" PyTorch implementation of a convolutional neural network for sentence classification [1].
Implementation is adapted from the following repository https://github.com/Shawn1993/cnn-text-... |
992707cb6fb0382334ec407204943e25577470e7 | lukeencinas/EjerciciosExtraPython | /Bucles.py | 95 | 3.65625 | 4 | contador = 10
while contador != 0:
print(contador)
contador -= 1
print("Lanzamiento")
|
040c7d6fa77e6a2677b713229a9db9cef7f93b83 | johnzhoudev/python-citations-helper | /citations/auto_table.py | 6,817 | 3.78125 | 4 | #! /opt/anaconda3/bin/python
import pyperclip
# Open file containing input and read
table_data_file = open('./table_data_file.txt', 'r')
table_data = table_data_file.readlines()
def append_heading_row(arr_words):
return_str = "\t\t<tr>\n\t\t\t"
for j in range(len(arr_words)):
arr_words[j] = arr_words[... |
980fc1829d7f099fdf1cdf3aa5050352fac455f4 | raphael-abrantes/exercises-python | /ex006.py | 141 | 3.84375 | 4 | x = int(input('Digite um valor: '))
print(f'O dobro de {x} é {2*x}\nO triplo de {x} é {3*x}\nA raíz quadrada de {x} é {x**(1/2):.2f}')
|
a97bf3bcc27ccbcbed0e6d8f66e202dbcddcceac | raphael-abrantes/exercises-python | /ex066.py | 222 | 3.671875 | 4 | soma = i = 0
while True:
num = int(input('Insira um valor [Digite 999 para parar!]: '))
if num == 999:
break
i = i + 1
soma = soma + num
print(f'A soma dos {i} valores digitados é {soma}')
|
dce0664a1145c05112586aad520ec2b1bd094884 | raphael-abrantes/exercises-python | /ex067.py | 291 | 3.890625 | 4 | print('Para encerrar, digite um valor negativo')
while True:
n = int(input('Quer a tabuada de qual valor? '))
if n < 0:
print('\nFim do programa!')
break
print('-' * 32)
for i in range(1, 11):
print(f'{n} x {i} = {n*i}')
print('-' * 32)
|
70cac53d7cccc7778a1f5edd7daa26a480d5b48a | raphael-abrantes/exercises-python | /ex065.py | 650 | 3.78125 | 4 | answer = 'S'
i = s = maior = menor = 0
while answer in 'YySs':
i = i + 1
n = int(input('Digite um valor: '))
answer = str(input('Deseja cotinuar [Y/N]? ')).upper().strip()[0]
if answer not in 'YySsNn':
while answer not in 'YySsNn':
answer = str(input('Opção inválida. Deseja c... |
90b1968bdccb773d613e89043145608b84027dac | raphael-abrantes/exercises-python | /ex096.py | 249 | 3.625 | 4 | def area(larg, comp):
a = larg * comp
print('-='*15)
print(f'A area de um terreno {larg}x{comp} é = {a:.1f}m²')
print('Área de Terreno')
print('-'*20)
area(float(input('Largura (m): ')),
float(input('Comprimento (m): ')))
|
e40488d5e910c6af7f852a5087b48f8b87bf9c82 | raphael-abrantes/exercises-python | /ex086.py | 296 | 3.71875 | 4 | aMatriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0, 3):
for j in range (0, 3):
aMatriz[i][j] = int(input(f'Digite um valor para [{i}, {j}]: '))
print('-'*32)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{aMatriz[i][j]:^7}]', end='')
print()
|
3f201f40b3d5ddc8dec9c8665271cf5a0b0c5723 | raphael-abrantes/exercises-python | /ex007.py | 161 | 3.71875 | 4 | n1 = float(input('Digite sua primeira nota: '))
n2 = float(input('Digite sua segunda nota: '))
print(f'A média de {n1} e {n2} é igual a {(n1 + n2)/2:.2f}')
|
d6ec64b000ca85a21b982dd995597837b6a70972 | raphael-abrantes/exercises-python | /ex085.py | 360 | 3.53125 | 4 | n = [[], []]
vValor = 0
for i in range (1, 8):
vValor = int(input(f'Digite o {i}° valor: '))
if vValor % 2 == 0:
n[0].append(vValor)
else:
n[1].append(vValor)
n[0].sort()
n[1].sort()
print('-'*50)
print(f'Todos os valores: {n}')
print(f'Os valores pares são: {n[0]}')
print... |
3dd0f77e6d97d184cb22c0be364c8e3197138088 | raphael-abrantes/exercises-python | /ex012.py | 116 | 3.59375 | 4 | preco = float(input('Qual o preço do produto? '))
print(f'O produto com 5% de desconto vale R${preco*0.95:.2f}')
|
dcb25dddc2d849f6d545c93328cc9ee2cb502d79 | raphael-abrantes/exercises-python | /ex016.py | 168 | 3.671875 | 4 | from math import trunc
#import math || from math import trunc
x = float(input('Digite um número Real: '))
print(f'A parcela inteira do número {x} é {trunc(x)}')
|
5633cff71b6fdfb99308df89b1be3fea2ad2c5ff | raphael-abrantes/exercises-python | /ex033.py | 454 | 4.0625 | 4 | n1 = int(input('Insira um valor: '))
n2 = int(input('Insira outro valor: '))
n3 = int(input('Insira o último valor: '))
menor = n1
maior = n1
#Verifica o menor
if n2 < n1 and n2 < n3:
menor = n2
elif n3 < n1 and n3 < n2:
menor = n3
#Verifica o maior
if n2 > n1 and n2 > n3:
maior = n2
elif n... |
9850e5de361b1f208eda6e0779e9db33ed8db7fb | raphael-abrantes/exercises-python | /ex008.py | 350 | 3.90625 | 4 | medida = float(input('Digite um valor em metros: '))
print(f'Para o valor de {medida}m, têm-se as seguintes conversões: ')
print('='*56)
print(f'{medida/1000:.2f}km')
print(f'{medida/100:.2f}hm')
print(f'{medida/10:.2f}dam')
print(f'{medida*1:.2f}m')
print(f'{medida*10:.2f}dm')
print(f'{medida*100:.2f}cm')
pri... |
ae386e8a7a2c0fa4d4178a374c08b0d2faa09468 | TimothyPolizzi/CMPT435 | /Assignments/AssignmentTwo/HashTable.py | 5,099 | 4.46875 | 4 | # An implementation of a hash table for CMPT435.
__author__ = 'Tim Polizzi'
__email__ = 'Timothy.Polizzi1@marist.edu'
from typing import List
class HashTable(object):
"""Creates a table with quick insertion and removal using a calculated value.
Calculates a hash value for every item added to the table. The... |
77a523e48e004fe5885af5d61916c4066f44f096 | TimothyPolizzi/CMPT435 | /Assignments/AssignmentThree/LinkedGraph.py | 4,209 | 4.25 | 4 | # A graph made of linked objects for Alan's CMPT435.
__author__ = 'Tim Polizzi'
__email__ = 'Timothy.Polizzi1@marist.edu'
from typing import List
class LinkedGraph(object):
class __Node(object):
""" An internal Node for the Linked Object model of the Graph
"""
def __init__(self, set_id... |
c0152d8c48c1b81c2e2fc72e12d200c60f90b3b9 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/all prime no between low limit to upper limit.py | 378 | 3.828125 | 4 | # print all prime nos between lower limit to upper limit
low = int(input("enter the lower limit"))
upp = int(input("enter the upper limit"))
for Number in range (low, (upp+1)):
flag = 0
for i in range(2, (Number // 2 + 1)):
if (Number % i == 0):
flag = flag + 1
break
if (fl... |
bc54b72db672fdc80f71246a06f295a97c9efa18 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/temp.py | 126 | 3.875 | 4 | temperature=int(input("enter the current temperature"))
if(temperature>30):
print("hot here")
else:
print("cool here") |
a97aa88d77825b5b9425c336aab72cd67b424b7e | keerthisreedeep/LuminarPythonNOV | /Flow_controls/sum_of_cubes of a number.py | 133 | 3.96875 | 4 | num=int(input("enter a number"))
result=0
while(num!=0):
temp=num%10
result=(result)+(temp**3)
num=num//10
print(result)
|
f86510558d0e668d9fc15fd0a3ff277ac93ec656 | keerthisreedeep/LuminarPythonNOV | /Functionsandmodules/function pgm one.py | 1,125 | 4.46875 | 4 | #function
#functions are used to perform a specific task
print() # print msg int the console
input() # to read value through console
int() # type cast to int
# user defined function
# syntax
# def functionname(arg1,arg2,arg3,.................argn):
# function defnition
#-----------------------------------------... |
c633e32b95ff636fd81833377687758e712d33a5 | keerthisreedeep/LuminarPythonNOV | /Flow_controls/pgm_to_check_prime no.py | 250 | 4.09375 | 4 | number=int(input("enter a number"))
flag=0
for i in range(2,number):
if(number%i==0):
flag=1
break
else:
flag=0
if(flag>0):
print("number is not a prime number")
else:
print("number is prime number")
|
ea9ce7533e3f40c0078f83d82f40fa98fd915417 | keerthisreedeep/LuminarPythonNOV | /List_demo/pairs.py | 670 | 3.609375 | 4 | #lst=[1,2,3,4] #6 (2,4) , #7 (3,4)
# lst=[1,2,3,4]
# pair = input("enter the element ")
# for item in lst:
#
# for i in lst:
# sum=0
# if(item!=i):
# sum=item+i
# if(pair==sum):
# print(item,',',i)
# break
#---------... |
e6a1ca5bfc03dd172f80ee3f24acc9d128db8588 | lenamv/Car_Price_Prediction | /feature_transformation.py | 3,961 | 3.609375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
from sklearn.base import TransformerMixin, BaseEstimator
import pandas as pd
import numpy as np
# Create a class to perform feature engineering
class FeatureEngineering(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self
... |
5ca2fa162d8fb0045e3677fdb92199fa0b453365 | dariagus/Homework | /task_02_01.py | 154 | 3.96875 | 4 | def is_palindrome(x):
x = str(x)
x = x.lower()
x = x.replace(' ', '')
if x == x[::-1]:
return True
else:
return False
|
550f9940e0d3646142ce07babd0cd9eff743ea7e | Venka97/Python-programs-15IT322E | /Prog 2.py | 133 | 3.8125 | 4 | def fact(x):
if x == 0:
return 1
else:
return x * fact(x - 1)
x = int(input())
print(fact(x),sep='',end='') |
0f9c55296b28a4cf6530a4e55921ffa02527961b | Venka97/Python-programs-15IT322E | /Ex 1.py | 207 | 3.53125 | 4 | z = [int(x) for x in input().split()]
def bubble(a):
for i in len((a - 1):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
print (a)
bubble(z) |
9af8a5a49a6878545c60df7b679b9f6b87ba9145 | vivek4svan/adventofcode2016 | /day_02_02.py | 1,271 | 3.53125 | 4 | # Day 2: Bathroom Security
# Part 2
def get_security_digit(code_line, i, j):
print line.strip()
for char in code_line:
if char == "R" and lock_panel[i][j+1] != "0":
j += 1
elif char == "L" and lock_panel[i][j-1] != "0":
j -= 1
elif char == "U" and lock_panel[i-1]... |
148b2404d2b3736a91e5a46a63fb43f69e175d69 | sethgoolsby/Lab03-sethgoolsby | /tcp_client.py | 1,077 | 3.765625 | 4 | """
Server receiver buffer is char[256]
If correct, the server will send a message back to you saying "I got your message"
Write your socket client code here in python
Establish a socket connection -> send a short message -> get a message back -> ternimate
use python "input->" function, enter a line of a few letters, s... |
a68904d3ec21021c485dea62a89588bd8bb68078 | eomcaleb/RateMyStocks | /.problems/strategy_tammy.py | 2,834 | 3.6875 | 4 | from os import close
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
def main():
#-----------------------------------
#1 - Get basic stock pricing on day-to-day basis
#-----------------------------------
startdate = dt.datetime(2021,1,1)
enddate = dt.datetime(202... |
89b5ceeca6934f590d58043ac74aa3b210a976c9 | charlie447/tech_development_interview | /data_structure_and_algorithm/scripts/tree.py | 13,959 | 3.953125 | 4 | import functools
import collections
def is_empty_tree(func):
@functools.wraps(func)
def wrapper(self):
if not self.root or self.root.data is None:
return []
else:
return func(self)
return wrapper
class Node(object):
def __init__(self, data=None, key=None, value... |
2750021796bb19068080d52a34e64182587bdbce | ze-dev/applied_programming | /maketxt.py | 775 | 3.65625 | 4 | def maketxt(filename):
'''Создает текстовый файл в директории запуска скрипта.
В консоли вызывать maketxt.py НужноеИмяФайла (БЕЗ пробелов)'''
import time, os
with open('%s.txt' % filename, 'w') as ff:
dirPath=os.getcwd()
fullPath = '%s\%s' % (dirPath, filename)
print('\nДи... |
4b6d03ff869820950c0d36c0a4edd8fbfec3c4f7 | Cvig/MyCodes | /Python/Practice_Problems/Array/Two Sum III - Data Structure Design.py | 1,606 | 4.09375 | 4 | '''
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers whose sum is equal to the value.
'''
class TwoSum(object):
def __init__(self):
"""
initialize you... |
68b3480708b70de1b8bb576e73aaf642e18cec93 | Cvig/MyCodes | /Python/Practice_Problems/Array/Intersection.py | 1,197 | 3.984375 | 4 | #find intersection of two lists of integers
#Cases: lists could be empty
#there could be duplicates in the list
#length may be different, in that case my list could not be bigger than that
class Solution(object):
def intersection(self, l1, l2):
"""
:type l1: list of integers
:type l2: list... |
b3cff1fe173d6371ab8a265716ebc47aac78e107 | Cvig/MyCodes | /Python/Practice_Problems/Lists/NestedListWeightSum.py | 734 | 3.8125 | 4 | #Given a nested list of integers, return the sum of all integers in the list weighted by their depth
#Each element is either an integer, or a list whose elements may also be integers or other lists
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
... |
29e6db95f9449ec3665a57762bf3d8e32aa0926c | sarnaizgarcia/Master-en-Programacion-con-Python_ed2 | /silvia/katas/pitagorasclases.py | 618 | 3.921875 | 4 | import math
class RightTriangle():
def __init__(self, leg_one, leg_two):
self.leg_one = leg_one
self.leg_two = leg_two
@property
def hypotenuse(self):
h = round(math.sqrt(pow(self.leg_one, 2) + pow(self.leg_two, 2)), 0)
return h
def __repr__(self):
return f'El... |
cb1e9921d2f54d3bc3e3cb8bf67ca3e2af019197 | mgeorgic/Python-Challenge | /PyBank/main.py | 2,471 | 4.25 | 4 | # Import os module to create file paths across operating systems
# Import csv module for reading CSV files
import csv
import os
# Set a path to collect the CSV data from the Resources folder
PyBankcsv = os.path.join('Resources', 'budget_data.csv')
# Open the CSV in reader mode using the path above PyBankiv
with open ... |
dc56e7a5a4fa8422088b3e0cba4b78d2a86a1be3 | roctbb/GoTo-Summer-17 | /day 1/6_words.py | 425 | 4.15625 | 4 | word = input("введи слово:")
words = []
words.append(word)
while True:
last_char = word[-1]
new_word = input("тебе на {0}:".format(last_char.upper())).lower()
while not new_word.startswith(last_char) or new_word in words:
print("Неверно!")
new_word = input("тебе на {0}:".format(last_char.upp... |
672c5c943f6b90605cf98d7ac4672316df20773a | vittal666/Python-Assignments | /Third Assignment/Question-9.py | 399 | 4.28125 | 4 | word = input("Enter a string : ")
lowerCaseCount = 0
upperCaseCount = 0
for char in word:
print(char)
if char.islower() :
lowerCaseCount = lowerCaseCount+1
if char.isupper() :
upperCaseCount = upperCaseCount+1
print("Number of Uppercase characters in the string is :", lowerCaseCou... |
168192647db4ab5dc7184877963cd38b43702527 | vittal666/Python-Assignments | /Third Assignment/Question-2.py | 500 | 3.84375 | 4 | input_list = []
n = int(input("Enter the list size : "))
print("\n")
for i in range(0, n):
print("Enter number", i+1, " : ")
item = int(input())
input_list.append(item)
print("\nEntered List is : ", input_list)
freq_dict = {}
for item in input_list:
if (item in freq_dict):
freq_dict[it... |
e64285d27bcf8652203793248a17089754a465d6 | naijnauj/FAQ | /DTFT/day3/class.py | 1,035 | 3.625 | 4 | class MyClass(object):
message = 'Hello, Developer'
def show(self):
print self.message
print 'Here is %s in %s!' % (self.name, self.color)
@staticmethod
def printMessage():
print 'printMessage is called'
print MyClass.message
@classmethod
def createObj(cls, name, color):
print 'Object will be... |
39237343d21c26559dea1979e1cea5a87c4227ba | shashankp/projecteuler | /45.py | 626 | 3.515625 | 4 | #Triangular, pentagonal, and hexagonal
import math
def isperfsq(i):
sq = math.sqrt(i)
if sq == int(sq): return True
return False
n = 533
c = 0
while True:
h = n*(2*n-1)
if isperfsq(8*h+1) and isperfsq(24*h+1):
t = (-1+math.sqrt(8*h+1))
p = (1+math.sqrt(24*h+1))
... |
6ae38ce4d29e307187be215b56b45d59c0dd2615 | shashankp/projecteuler | /5.py | 201 | 3.75 | 4 | #lcm
n = 20
def lcm(a,b):
c = a*b
while b>0:
a,b = b,a%b
return c/a
l = set()
for i in xrange(2, n):
if i%2 != 0: l.add(2*i)
else: l.add(i)
c = 1
for i in l:
c = lcm(c,i)
print c
|
d6aa1d2839b1d49189238e7d52233cd7bf6c1a88 | ywtail/Aha-Algorithms | /2_5.py | 555 | 3.515625 | 4 | # coding:utf-8
# 数组模拟链表,输入一个数插入正确的位置
# data存数据,right存(下一个数的)索引
data=map(int,raw_input().split())
right=[i for i in range(1,len(data))]+[0]
#print data
#print right
inpt=int(raw_input())
data.append(inpt)
def func():
for i in xrange(len(data)):
if data[i]>inpt:
break
i-=1
right.append(right[i])
right[i]=len(d... |
9840d8d6e3e2aab4ed89cfd405839f78b9d7d16e | ywtail/Aha-Algorithms | /2_2.py | 482 | 3.90625 | 4 | # coding:utf-8
# 桟(判断回文:先求中间,然后前半部分压入栈,弹出与后半部分对比。)
s=raw_input()
n=len(s)
def func():
if s==s[::-1]:
print "YES"
else:
print "NO"
#func()
if n==1:
print "YES"
else:
mid=n/2
mids=""
for i in xrange(mid):
mids+=(s[i])
if n%2==0:
nex=mid
else:
nex=mid+1
for j in xrange(nex,n):
if mids[i]!=s[j]... |
bf4eae907ed3fae20b59aeb828bee713bcf2b111 | ywtail/Aha-Algorithms | /7_4.py | 676 | 3.625 | 4 | # coding:utf-8
# 并查集:求一共有几个犯罪团伙
def getf(v):
if f[v]==v:
return v
else:
f[v]=getf(f[v]) #路径压缩,顺带把经过的节点改为祖先的值
return f[v]
def merge(v,u):
t1=getf(v)
t2=getf(u)
if t1!=t2:
f[t2]=t1
n,m=map(int,raw_input().split())
f=[i for i in range(n+1)]
for i in range(m):
x,y=map(int,raw_input().split())
merge(x,y)
... |
fd53e99695c452678c1af7f5e31a5f1d4fa0f91b | pyjones/python | /campaignWorking.py | 1,553 | 3.640625 | 4 | # A script to work out campaign values and metrics
from __future__ import division
prompt = ">>>"
def cost_per_unique(campaign_value, campaign_uniques):
cost_per_unique = campaign_value / campaign_uniques
return cost_per_unique
def cost_per_minute(campaign_value,dwell_time):
cost_per_minute = campaign_value / dw... |
1c6f4c6df2921e90d2ab8b5d58b0bcd2f8b7927b | skunwarc/Adv-Stats | /emea.py | 883 | 3.671875 | 4 | #!/usr/bin/env python2.7
# initiate a few variables
i = 0
Id=[]
Gdp= []
Fertrate= []
# read csv file and store data in arrays x and y
import csv
with open('emea.csv','rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
i += 1
#print i
emea = row
Id.append(int(emea[0]))
... |
8d3835871bc36c5af378d6136b25ffc8bd0f2f1b | cseoy73/Covid19-R-Web | /분석 및 시각화/graph3.py | 483 | 3.734375 | 4 | from matplotlib import pyplot as plt
month = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Employment = [26800, 27991, 26609, 26562, 26930, 27055, 27106, 27085, 27012, 27088, 27241]
Unemployment = [1153, 26838, 1180, 1172, 1278, 1228, 1138, 864, 1000, 1028, 967]
plt.plot(month, Employment, marker="o")
plt.plot(month, Unemploym... |
87989d135315dad70da7904a74791609c713276b | TahsinaSnow/TahsinaSnow | /5th.py | 123 | 4.25 | 4 | import math
degree = float(input("Enter an angle in degree:"))
radian = (degree*math.pi)/180
print(math.sin(radian))
|
a19f190af9c07707915d425973f295a7254a6811 | marcofrn23/Python | /Design of Computer Programs/floorpuzzle.py | 1,019 | 3.984375 | 4 | # Exercise 1 for lesson 2 in 'Design of Computer Program' course
from itertools import permutations
def is_adjacent(p1, p2):
if abs(p1-p2) == 1:
return True
return False
def floor_puzzle():
"""Resolves the given puzzle with the given constraints."""
residences = list(permutations([1,2,3,4,5],... |
1feae052372eba7dd2597ed2d06d191195687a02 | abhayparikh99/Practice_Programs | /helly_3_in_1_game_merge.py | 13,057 | 4.34375 | 4 | # Game zone....
import random
# Write a program for Rock_Paper_Scissors game.
# user/computer will get 1 point for winning, Play game until user/computer score=3 point.
class RPS():
user_score=0
computer_score=0
def __init__(self):
print("Welcome to 'Rock Paper Scissors'".center(130)) ;print()
... |
c15cb5b8683ddda1af31898a980e9badf67ddaac | Taylorbear3/Find-the-Murderer | /class animal.py | 264 | 3.546875 | 4 |
class Animal:
name = None
numoflegs = None
numofeyes = None
hasnose = False
#method can
def sayName()
print(self.name)
tiger = Animal()
tiger.name = "Pi"
tiger.numOflegs = 4
tiger.numofeyes = 2
tiger.nose = 1
print(self.name) |
537f13db14ebefff96b6ecb3308d1c3b4435a6cb | ziegs4life/pythonPractices | /Lists.py | 2,256 | 3.5625 | 4 | # a = range(10)
# b = sum(a)
# print b
#
#
# a = [1,2,3]
# print max(a)
#
# a = [1,2,3]
# print min(a)
#
# a = range(2,10,2)
# print a
# def pos_num():
# my_list = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#
# for i in range(len(my_list)):
# if my_list[i] > 0:
# print my_list[i... |
4d8345fb969ff1d9d544f0cc2027c9325eb42370 | josegonzah/PruebaTecnicaSofka | /ConsoleApp/Questions.py | 2,947 | 4.09375 | 4 | import random
import csv
class Questions:
def __init__(self):
##Questions object is basically a dictionary which keys are the rounds asociated to the bank of questions
#and the values are arrays that contains arrays, those inner arrays have, in order, the statement, the answer
#and the othe... |
7d133060d3601fb988fe143f3fff058b54d47b0e | austinread/adventofcode2020 | /solutions/9.py | 1,356 | 3.71875 | 4 | import sys
from helpers import inputs
raw = inputs.import_input(9)
numbers = raw.split("\n")
numbers = [int(n) for n in numbers]
preamble_length = 25
def is_valid(index):
number = numbers[index]
options = numbers[index-preamble_length:index]
valid = False
for o1 in options:
if valid:
... |
f8e1ece2012af7ee8c2ac873064e12fd01136317 | butuye08/Python | /ex33.py | 232 | 3.875 | 4 | i = 0
numbers = []
while i < 6:
print "At the top i is %d " % i
numbers.append (i)
i = i + 1
print "Numbers now", numbers
print "At the buttom i is %d " % i
print "The numbers: "
for num in numbers:
print num |
ed9bbe37e0e154e8fe47c772331a9a0786d36da8 | alu-rwa-dsa/summative-dirac_wanji_fiona | /High-Fidelity/main.py | 2,890 | 3.5625 | 4 | import sys
from users.signup.sign_up import sign_up
from login.login_module import login
from questions.questions_answers import Quiz
from users.search.search_one_user import get_the_user
# this is a function to call our main menu
def main_menu():
print("=" * 100)
print("Welcome! What would you like... |
407873321bdfe992b7ff8a86b323e9ae837ff504 | akaprosy/Miscellaneous-Hydraulic-tools-using-Python | /listcomprehensions.py | 651 | 3.640625 | 4 |
#Horsepower using list comprehensions
'''pressure = [value for value in range(100,3000,100)]
flow = [value for value in range(5,100,10)]
for i in flow:
for j in pressure:
hp = round((i*j)/1714)
print(f'Flow: {i} gpm, Pressure: {j} psi, Horsepower: {hp}')'''
#Torque lbs-ft gi... |
64d7d72990c223ea8a483120756a424195b2be54 | jolllof/bb_to_canvas_migration | /BlackboardLogin.py | 1,695 | 3.53125 | 4 | """time module is used to put pauses between each selenium action
as the website sometimes take a second to load"""
import time
from selenium import webdriver
class BlackboardLogin:
"""this class opens up firefox and logs into Blackboard Admin site"""
def __init__(self, username, password, site):
... |
14792c76f72fb72f811c3dfba25a4ce9953d3abb | tjshamhu/game-of-life | /game.py | 2,286 | 3.515625 | 4 | class Cell:
next_state = None
def __init__(self, state='-'):
self.state = state
def evolve(self):
if not self.next_state:
return
self.state = self.next_state
self.next_state = None
def start(coords, runs):
x_min = min([i[0] for i in coords])
x_max = ma... |
4b715877e24c3b1c5964625d40c54fcdad08d81c | sungjoonhh/leetcode | /7_reverse_integer.py | 682 | 3.890625 | 4 | # Definition for singly-linked list.
class Solution:
def reverse(self, x: int) -> int:
num = 0
if x>=0 :
while x > 0:
num = int(num*10) + int((x%10))
x = int(x/10)
return 0 if num > int(pow(2,31)) else num
else... |
b9386f91d02719835878a87d51535fe3c2f57018 | akatkar/python-training-examples | /day3/Rational.py | 928 | 3.734375 | 4 | class Rational:
counter = 0
def __init__(self,a,b):
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
cd = gcd(a,b)
self.a = a // cd
self.b = b // cd
Rational.counter += 1
def __add__(self, other):
a = self.a * ... |
bdb5d75b1c10dc1c9101468bdff355f91b4a0196 | akatkar/python-training-examples | /day4/02_BeautifulSoup/ex01_simpletable.py | 496 | 3.546875 | 4 | from bs4 import BeautifulSoup
with open("simpletable.html") as fp:
bs = BeautifulSoup(fp,"html.parser")
print(bs.title)
print(bs.title.text)
table = bs.find('table', "Simple Table")
# using iteration
# data = []
# for row in table.find_all("tr"):
# for col in row.find_all("td"):
# data.append(col.st... |
3886f317fe8006f8b66b1e4e938e3edb1aa07e82 | akatkar/python-training-examples | /day1/example_02.py | 462 | 3.796875 | 4 | def x(a):
return a ** 3
a = 3
b = x(3)
print(f"{a}^3 = {b}")
def isPrime(n):
if n < 2:
return False
for i in range(2,n):
if n % i == 0:
return False
return True
print(-2, isPrime(-2))
print(10, isPrime(10))
primes = []
for i in range(100):
if isPrime(i):
prime... |
01bb8c5920bc90d5250543a0fddd34625c322181 | akatkar/python-training-examples | /day3/class1.py | 175 | 3.84375 | 4 | # why do we need a class?
# Let's assume that we have to calculate rational numbers
a = 1
b = 2
c = 1
d = 3
e = a * d + c * b
f = b * d
print(f'{a}/{b} + {c}/{d} = {e}/{f} ') |
5e8dd2be609a00bbc9b39db690a55528f11284b9 | Rishabh450/PythonAutomation | /convertWeight.py | 204 | 3.640625 | 4 | weight = input('Enter Weight')
choice = input('(k) for killgram (p) for pounds')
if choice == 'k':
print(f'Weight in Pounds : {float(weight)*10}\n')
else:
print(f'Weight in Kg :{float(weight)*3}') |
dab19715b792e3874a5468b4af6eb79184b673e8 | Rishabh450/PythonAutomation | /removedublicate.py | 150 | 3.828125 | 4 | numbers = set([4, 2, 6, 4, 6, 3, 2])
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
|
c1b7ca7425fe164c693e91e5deec6811adb7941a | NITIN-ME/Python-Algorithms | /Stack.py | 1,273 | 3.796875 | 4 | class Empty(Exception):
def __init__(self, message):
print(message)
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
try:
if(self.is_empty()):
... |
9ee9da2e9502457358d27482a9273d3ebd27ed71 | NITIN-ME/Python-Algorithms | /closest_points.py | 1,673 | 3.78125 | 4 | from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(" + str(self.x)+", "+str(self.y)+")"
def compareX(a, b):
return a.x - b.x
def compareY(a, b):
return a.y - b.y
def distance(a, b):
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y) * (a.y - ... |
bc97f24ba8f725bfc6f0003a3efaea20efdce5b0 | NITIN-ME/Python-Algorithms | /linked.py | 1,427 | 3.953125 | 4 | """
use __slots__
__init__
__len__
is_empty
push
top
pop
"""
class Empty(Exception):
def __init__(self, message):
print(message)
class LinkedStack:
class _Node:
__slots__ = '_element', '_next'
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
self._h... |
863f2333082729f83a086ccbb135540df142d132 | DanisHack/stampify | /data_models/website.py | 1,781 | 3.96875 | 4 | """This script creates a class to store
information about to a website"""
from urllib.parse import urlparse
from utils import url_utils
class Website:
"""This class stores the information about a website"""
__LOGO_API = 'https://logo.clearbit.com/'
__LOGO_SIZE = 24
def __init__(self, url):
... |
c96f018296422b1a219700ee9511f5fa3ead8614 | shuchenliu/doch_backend | /resources/tweetify.py | 6,145 | 3.59375 | 4 | '''
note:
1, Query in the databse if we stored this user before
2.a, If not, we grab tweets from last 7 days as usual,
2.b, If so, we query the date of the last tweets we store.
- if it is still within 7 days, we used it as the since_id
- if it is beyond 7 days range, we go back to 2.a
side note:
1, Consider l... |
53a85cca879f97c96ac4e2bcbb0175ce6ef03894 | JohnTalamo/Python-training | /app.py | 163 | 3.75 | 4 | name = "John"
print(len(name))
len(name)
fname = "John"
lname = "Talamo"
full = fname + " " + lname
print(full)
print(len(full))
name = "bazinga"
print(name[2:6])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.