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 |
|---|---|---|---|---|---|---|
d08dc3d077d17a04da1ebc27c8d88666fffb9253 | nirajp786/Python-Lessons | /Pandas/Getting Started.py | 899 | 3.734375 | 4 | #better to use ipython for this file helps with visulization of data
#in cmd do ipython and run these commands
import pandas
df1 = pandas.DataFrame([[2,4,6], [10,20,30]])
print(df1, end="\n\n")
# 0 1 2
# 0 2 4 6
# 1 10 20 30
df1 = pandas.DataFrame([[2,4,6],[10,20,30]], columns=["Price", "Age", "Value... |
825180decbe595ad5ec6b84511f97661ae28a121 | NANGSENGKHAN/cp1404practicals | /prac02/exceptions_demo.py | 1,046 | 4.53125 | 5 | try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
while denominator == 0:
print("Denominator cannot be zero")
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueErro... |
8e4c6ef6dba3c6b584b699adfb73a951670d912c | YujingTse/python | /filter.py | 92 | 3.53125 | 4 | def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd,[1,2,4,5,6,9,10,15]))) |
22906af2520ce40a9e15afdaf18f9f8f64f0e2db | YujingTse/python | /str2num.py | 292 | 3.5625 | 4 | from functools import reduce
DIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2num(s):
def fn(x,y):
return 10 * x + y
def char2num(s):
return DIGITS[s]
return reduce(fn,map(char2num,s))
print(str2num('13579'))
|
41dfde60a9a58e0354a8a7def3b23b3c179d7aa9 | YujingTse/python | /fact.py | 195 | 3.65625 | 4 | def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)
# print(fact(0))
print(fact(1))
# print(fact(-1))
print(fact(6))
# print(fact(-6))
# print(fact(1.4)) |
a0b434f7ffc4289219ecbedec5a33e6d838cbe1c | SebFernandez/Learning-TensorFlow | /tensorflow-2.py | 1,145 | 3.671875 | 4 | #tf.estimator
import numpy as np # NumPy is often used to load, manipulate and preprocess data.
import tensorflow as tf
feature_columns = [tf.feature_column.numeric_column ("x", shape = [1])]
# An estimator is the front end to invoke training (fitting) and evaluation (inference).
estimator = tf.estimator.LinearRegre... |
ca47756b135861c303f03af2485337632e2e4784 | auretsky1/BasicPuzzleGame | /PuzzleGenerator.py | 4,285 | 4.15625 | 4 | """ This module can be called to generate a trigger list for any sized puzzle map. It stores the trigger list
as a one-dimensional list of tuples where each tuple stores the cubes which that valued cube lights up. """
import random
def generate_trigger_list(size=3):
# Seed the random number generator
rand... |
c5f2c3ab2c8b6a6458bb67a559f36784e95e4c34 | Kalaiselvan-S/Statistics-Fundamentals-with-Python | /Introduction to Linear Modeling in Python/Chapter 2 - Building Linear Models.py | 6,810 | 4.09375 | 4 |
#Chapter 2 - Building Linear Models
#-----------------------------------------------------------------------------------#
#Model Components
# Define the general model as a function
def model(x, a0=3, a1=2, a2=0):
return a0 + (a1*x) + (a2*x**2)
# Generate array x, then predict y values for specific... |
b7d213893262af8280660bb10b4dd14c2c11465b | cicorias/njit-algs-play | /src/tests/bst_test.py | 1,046 | 3.609375 | 4 | import unittest
from src.algs.trees.BST import BST, BSTNode
class Test_Bst(unittest.TestCase):
def setUp(self) -> None:
self.root = BSTNode(4)
# '''
# 4
# / \
# / \
# 2 6
# / \ / \
# 1 3 5 7
# '''
def make_tree(self) -> BSTNode:
root = BSTNode(4)
... |
9ac5ec423256abc74722ccf876114310e87aad6b | emanchas/Python | /Python/exam1IST140_Ed Manchas.py | 1,160 | 4.21875 | 4 | print ('This program converts fahrenheit to celsius \n')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
while user_temp < 0:
print ('Error! Temperature must be greater than 0 degrees!')
user_temp = int(input('Please input a temperature in Fahrenheit:'))
print ('')
print ('Fahrenheit... |
ead5c78e306808c41f604d71c91350ea8941fb96 | Gruschwick/ECG_PLATFORM | /Framework/Sketch/Procedures/Abstract/ProcedureBase.py | 921 | 3.59375 | 4 | """
Abstract base class for Procedures, public methods implement interface for other classes
"""
class Base(object):
#return list of atributes required by Run() (and Function indirectly)
def requiredDataFields(self):
pass
#called by Comparator, if requiredDataFields differ from ones given by used Loader
def At... |
bdbd1db11c31ad9b579d008f122c90571a86469b | nwvh/Python-Projects | /Age Calculator/agecalc.py | 105 | 4.0625 | 4 |
age = int(input("Enter Your birth month: "))
result = 2021 - age
print("You're", +result, "years old!")
|
fc8be4ce511261bdf6a197fc6e69d3c8687bc1bc | szemannp/trial-exam-python-2016-06-06 | /3.py | 796 | 3.84375 | 4 | # Create a class that represents a cuboid:
# It should take it's three sizes as constructor parameters (numbers)
# It should have a method called `getSurface` that returns the cuboid's surface
# It should have a method called `getVolume` that returns the cuboid's volume
class Cuboid():
def __init__(self, width, ... |
7d97e5ded230b80db0f5665fa78f51146b064de5 | amisha-w/CSC510Grp8 | /greeter/daytime_greeter.py | 501 | 3.90625 | 4 | #This function greets the user based on the time of the day
import datetime
class DaytimeGreeter:
def give_greeting(name):
if not name:
return "Please enter your name"
currentTime = datetime.datetime.now()
ct = currentTime.hour
if ct < 12:
greeting = "Goo... |
b595d6d95e1639f84c7b4ac34345af337f9181b6 | cristianokair/python | /utfpr_20200801.py | 2,651 | 3.953125 | 4 | #08-Funções de Alta Ordem
# def soma(a, b):
# return a + b
# minha_soma = soma
# print(minha_soma)
# print(soma)
def filtro2(fn, it):
it2 = list()
it3 = list()
for valor in it:
if fn(valor):
it2.append(valor)
else:
it3.append(valor)
return it2, it3
lista1 ... |
80393bd41001d6845b0d5d095da40fdc6776b741 | Shivani-01/Python-Assignment | /Python-Asignment/Module 1/exercise5/add_one.py | 135 | 3.65625 | 4 | n=int(input("Enter 5 digit number"))
i=0
a=0
while(i<5):
r=n%10
r+=1
a+=((r%10)*(10**i))
n//=10
i+=1
print(a)
|
b6bb9a40df4251a78ce1e42f4ec951ab6049c0ec | Shivani-01/Python-Assignment | /Python-Asignment/Module 2/exercise5/discount_demo.py | 388 | 3.765625 | 4 | n=int(input("Enter number of packages purchased"))
d=0
if(n>=10 and n<=19):
d=0.1*99
elif(n>=20 and n<=49):
d=0.2*99
elif(n>=50 and n<=99):
d=0.3*99
elif(n>=100):
d=0.4*99
amt=99
da=amt-d
da*=n
if(d>0):
print("Amount of discount: $",d*n)
print("Total amount of purchase after disc... |
ead5340377ca5cf9e4cae2c2ae1da8e9ac0a1ffb | arydwimarta/python3-dummie | /lat6.py | 372 | 4.28125 | 4 | course = 'Python for Beginners 123'
print (len(course)) #menghitung jumlah huruf
print (course.upper())
print (course.lower())
#print(course)
print (course.find('o')) #find string become index
#print (course.replace('for','untuk'))
print (course.replace('o', 'a'))
print ('Python' in course) #in operator
print (course.t... |
5e57f8d6c187d4baca012568753155e46d7e43ae | nathanforester/python | /legal_ages_python.py | 946 | 4.09375 | 4 | while True:
import sys
print("please enter your age")
age = int(input())
# - You can vote
if age < 18:
print("you are too young to vote")
elif age >= 18:
print("you are old enough to vote")
# - You can driver
if age < 16:
print("you are too young to drive")
elif ... |
ac3f4a6ce4f57b4d4804708e2de6441e358dcfe7 | nathanforester/python | /Example.py | 1,133 | 4.0625 | 4 | # print('hello world')
#
# box_variable = "books and stuff"
# print(box_variable)
#
# box_variable = "more stuff"
# print(box_variable)
#
# box_variable = 14
# print(box_variable)
#
# print(type(box_variable))
#
# favourite_team = "Game's been called off"
# favourite_colour = "Black"
# favourites = favourite_team + ' '... |
2b3104ec9e029a3089636ee4a61878ed19581fc8 | Hexirost/maze_generator | /Cell.py | 564 | 3.78125 | 4 | class Cell:
def __init__(self, x, y):
self.x = x
self.y = y
self.visited = False
self.current = False
self.empty = False # Wall(False) or Empty(True)
self.name = "["+str(x)+","+str(y)+"]"
def get_name(self):
return self.name
def marked(self):
self.empty=False
def current_vist(self):
se... |
59a148da54042ea74438605d57b95666ae0ec178 | moacirescorcio/Atividade-Sem07-T2 | /Questão 03.py | 442 | 3.828125 | 4 | def eh_impar(n):
if n <= 9 or n >= 100:
return
else:
u = n % 10
n = n // 10
d = n % 10
if u % 2 != 0 and d % 2 !=0:
print('Os dois dígitos são ímpares.')
elif u % 2 != 0 or d % 2 != 0:
print('Apenas um dígito é ímpar.')
else:
... |
43d89d724a95e067991d9f55762bf94455ad8942 | speedy-souris/perso1 | /gamePack/game_class.py | 6,615 | 3.71875 | 4 | """
MacGyver's Labyrinth Game Class
"""
# internal librairies
from random import *
# external libraries
import pygame as pg
from pygame.locals import *
# local libraries
from gamePack import game_constant as constancy
class Level:
"""class to create a level"""
# initialization of the persona at the start of t... |
1986b45b07eb19397255a4dde239d42542efe096 | pqpo/pythonPractice | /mapreduce.py | 488 | 3.578125 | 4 | def add(x,y):
return x+y
def plus(x,y):
return x*y
def power(x):
return x**2
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2num(str):
return map(char2num, str)
def fn(x,y):
return x*10+y
def str2int(str):
return reduce (lambda x,y:x*10... |
253252450b925d032e8c627b6d5fda05a06f1ad2 | filias/algo-class-f-p | /quicksort.py | 1,478 | 3.953125 | 4 | # encoding:utf-8
comparisons = 0
def median(array, l, r):
n = r - l
middle = n / 2 + l
elems = [(array[l], l), (array[middle], middle), (array[r], r)]
median = sorted(elems)[1][1]
return median
def partition(array, l, r):
global comparisons
comparisons += r - l
#pi = l
#pi = r
... |
a2208f8def5bb106a39510b7c0e70f4a81142621 | LightDvlpr/RideShare | /Project Aaron and Shuvo-2.py | 2,181 | 4 | 4 | get_ipython().system(u'pip install pint')
# Configure Jupyter so figures appear in the notebook
get_ipython().magic(u'matplotlib inline')
# Configure Jupyter to display the assigned value after an assignment
get_ipython().magic(u"config InteractiveShell.ast_node_interactivity='last_expr_or_assign'")
# import function... |
2399303e56317fc168bc1a83bd29cc94be21fc64 | emptymalei/forest-confidence-interval | /examples/plot_mpg.py | 1,982 | 3.5 | 4 | """
======================================
Plotting Regression Forest Error Bars
======================================
This example demonstrates using `forestci` to calculate the error bars of
the predictions of a :class:`sklearn.ensemble.RandomForestRegressor` object.
The data used here are a classical machine lear... |
749613fc70d7d9a0c636f9cd7cd644d267d8ab98 | elguerandrea/CS241 | /teamActivites/ta04/date.py | 479 | 3.9375 | 4 | """
CS241 Team Activity 4
Written by Chad Macbeth
"""
class Date:
### Initialize the Date object
def __init__(self):
self.day = 1
self.month = 1
self.year = 2000
### Prompt the user for the date
def prompt(self):
self.day = int(input("Day: "))
self.month = int(input("Month:... |
13ba89901bb08b6b452577b9f2b99430d2edda31 | elguerandrea/CS241 | /checkpoints/check04a.py | 1,009 | 3.9375 | 4 | """
CS241 Checkpoint 4A
Written by Chad Macbeth
"""
class Person:
### Initialize a Person object
def __init__(self):
self.name = "anonymous"
self.year = "unknown"
### Display a person
def display(self):
print("{} (b. {})" .format(self.name, self.year))
class Book:
### Initialize a... |
3b1c8b11861ba1687a993d9e3d3d3b6af19a3dad | Lee2907/test-of-oop | /main.py | 1,168 | 4.0625 | 4 | class Shapes:
def __init__(self, name, side):
self.name = name
self.side = side
def Area(self):
print("I am a: " + self.name + "\n"+ "I have " + self.side + " sides")
obj_shape=Shapes("shape", "so many")
obj_shape.Area()
class Rectangle(Shapes):
def __init__(self, len1,wid1):
... |
d2b96ee2c3b8a4b170873ccf7221a594f7618749 | AkiraKane/DataScience | /Data_Analysis.py | 6,927 | 4.125 | 4 | ##### Part 1 #####
from __future__ import division
import pandas as pd
# 1. read in the yelp dataset
yelp = pd.read_csv('../hw/optional/yelp.csv')
# 2. Perform a linear regression using
# "stars" as your response and
# "cool", "useful", and "funny" as predictors
from sklearn.linear_model import LinearRegression
fea... |
a00317d13d595277102b01f62efe171649635f55 | Olya145/HSE- | /bonus/bonus_5.py | 179 | 3.640625 | 4 | words = input()
s = ["e", "y", "u", "i", "o", "a"]
for i in words:
if i == i in s:
print(i, end = "")
else:
print(i + "aig", end = "")
|
e4d68b7207dc2c686c74fca0dc89d784ba97aa14 | natoftheboonies/advent-of-code-2019 | /day22/day22.py | 2,845 | 3.578125 | 4 |
# deal into new stack
#sample.reverse()
#print(sample)
def deal_new(stack):
new_stack = stack[:]
new_stack.reverse()
return new_stack
def deal(stack, inc):
new_stack = stack[:]
y = 0
for x in range(0,len(stack)*inc,inc):
new_stack[x%len(stack)] = stack[y]
y+=1
return new_stack
def cut(stack, top):
ret... |
d3e061d9b70870f70900259eca6ee626d3ba5c0e | natoftheboonies/advent-of-code-2019 | /day3/day3.py | 3,636 | 3.5 | 4 |
def printgrid(grid):
for x in range(len(grid)):
print(grid[x])
# https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
def doesntwork(seg,seg2):
A = seg[0]
B = seg[1]
C = seg2[0]
D = seg2[1]
E = B[0]-A[0],B[1]-A[1]
F = D[0]-C[0],D[1]-C[1]
P = -1*E[1],E[0]
hAminusC =... |
e2fae40e5493e7be2eca5937e5be6aa2d4dd803a | yokubol/python-mini-projects | /play.py | 105 | 3.640625 | 4 | def turtle(s):
print(f"I {s} turtle.")
return 'baby'
number = turtle('haha')
turtle(f"love {number}") |
467f7d3b530f2e9dc4ed6ee275be89ff54370c4d | yokubol/python-mini-projects | /ex17.py | 640 | 3.90625 | 4 | # Import argument variable argv from sys module.
from sys import argv
# Unpack the argument variable 'argv'.
script, from_file, to_file = argv
# Tell user that program is going to copy all contents from
# the original file to the newly created file.
print(f"Copying from {from_file} to {to_file}")
# Open file. Then re... |
831677cd2312311f61eb28b00eac17a9bd4904af | yokubol/python-mini-projects | /lineprinter.py | 280 | 3.71875 | 4 | """This program prints out line number of a comment line.
This program is not complete."""
from sys import argv
script, filename = argv
find_string = '#'
target = open(filename, 'r')
lines = target.readlines()
for line in lines:
if find_string in line:
print(target.line)
|
93a1a252c7c4f0c8cb7bbfd8b4f58b0dbf877ad7 | Lance-Wong/advent_of_code_2020 | /day4.py | 2,435 | 3.5 | 4 | #TODO: learn a little more about validation and testing- answer was achieved but code is sloppy. Specifically about exception handling
#Would also want to break out each individual data test rather than have one huge function
def passport_valid_test(data):
if 'cid' in data.keys() and len(data.keys()) == 8:
... |
3bf6d539fd6caa11b92aff398b5a49668ee276dc | renzhang1212/digit_recognizer | /mnist_recognizer_gpu.py | 8,239 | 3.84375 | 4 |
# coding: utf-8
# ### Put all import statement here
# In[22]:
import os
import imageio
import matplotlib.pyplot as plot
import numpy as np
import seaborn as sns
from keras.utils.np_utils import to_categorical
from IPython.display import Image
from keras.preprocessing.image import ImageDataGenerator
from keras.m... |
f2bb01ca9899788ebfdeeb6b6fc2b6bd9695e43b | KnightSlayerTsorig/mega_casino | /user.py | 839 | 3.671875 | 4 | from game_machine import GameMachine
from random import randint
class User:
def __init__(self, name, money):
self.name = name
self.money = money
def play(self, money, casino):
# метод який симулює гру в game_machine
if self.money <= 0:
print('''You can't play with... |
3cbab2f32c6b083a1d8b07fb78c30b5440ecafa9 | hoklavat/beginner-python | /14_While.py | 86 | 4.03125 | 4 | #14- While
x = 1
while x <= 10:
print(x)
x = x+1
else:
print("Loop End.") |
bb2d1c3adf98151634c3069238574149df227010 | hoklavat/beginner-python | /09_Range.py | 102 | 3.515625 | 4 | #09- Range
r = range(5, 10)
print(r)
print(list(r))
print(list(r)[2:5])
print(r[1])
print(r.index(7)) |
782af31d67c20f4b3b7d03b4ad283df4baa296fb | hoklavat/beginner-python | /08_Tuple.py | 344 | 4.125 | 4 | #08- Tuple
tuple1 = ()
print(type(tuple1))
tuple1 = (9)
print(type(tuple1))
tuple1 = (1, 2, 3, 4, 5)
print(type(tuple1))
print(tuple1[1])
#tuple1[1] = 0 Error: unmutable elements
(a, b, c, d, e) = tuple1
print(a)
print(len(tuple1))
print(max(tuple1))
print(min(tuple1))
print(tuple1 + (1 ,2 ,3))
print(tuple1 * 2)
print... |
31f3db3194fab896e192be3a82f0fdee78d3c891 | catliaw/hb_skillsassessment_w1functions | /assessment.py | 7,851 | 4.375 | 4 | # PART ONE
# 1. We have some code which is meant to calculate an item cost
# by adding tax. Tax is normally 5% but it's higher in
# California (7%).
# Turn this into a function. Your function will pass in
# the default tax amount (5%), a state abbreviation, and the
# cost amount as parameters.
# If... |
5c5fc89120ca6b1be618613bb12db769644fc70c | brunoliveira8/computer-networks | /socket-programming/UDPClient.py | 785 | 3.671875 | 4 | ''' UDPClient.py
usage: python UDPClient.py HOSTNAMEorIP PORT
Reads text from user, sends to server, and prints answer
Modified by Dale R. Thompson, 2/10/15
'''
import sys
# Import socket library
from socket import *
# Set hostname or IP address from command line
serverName = sys.argv[1]
# Set port number by conver... |
bdc953455dc1ff24a4ac0b1696624a7812f64f80 | noxser/netology | /2.2 HomeWork/2-2 HomeWork _json.py | 2,311 | 3.703125 | 4 | def read_cook_book_from_json_file():
"""
данные берем из json файла
"""
import json
with open('cook_book.json', encoding='utf8') as f:
data = json.load(f)
cook_book_load = data
return cook_book_load
def validation_cook_book(cook_book_load):
"""
пробегаем и выравниваем высоту... |
8ace7a0c0bcfb2b36e9d16879c9a7e0b094cb81b | Palombredun/Projet3 | /Projet3/app/movements.py | 5,620 | 3.875 | 4 | #!/usr/bin/env python3
# -*-coding:Utf-8 -*
from pygame.locals import *
from app import labyrinth as lb
class Movements(lb.Labyrinth):
"""
This class is in charge of the movements of the character in the list
labyrinth, before displaying them on the screen.
When an event is detected (supposing it is o... |
fb80c96b9ea3a455cc9e5fe3daac41c59e64672b | EQ4/amplify | /src/amplify/utils.py | 643 | 4.46875 | 4 | import re
def natural_sort(string):
'''
This function is meant to be used as a value for the key-argument in
sorting functions like sorted().
It makes sure that strings like '2 foo' gets sorted before '11 foo', by
treating the digits as the value they represent.
'''
# Split the string int... |
a25994b5e12cce8d7dc4772ae89e990774dc38e3 | Jack-Gooding/Jack-Gooding.github.io | /Projects/Programming/Python Scripts/test.py | 811 | 3.84375 | 4 | from random import randint
s1r = 1
s1c = 1
s1r2 = 1
s1c2 = 2
ship1 = []
ship1.append(s1r)
ship1.append(s1c)
ship2 = []
ship2.append(s1r2)
ship2.append(s1c2)
s2r = 1
s2c = 1
ship3 = []
ship3.append(s2r)
ship3.append(s2c)
def checkr(r,c):
if ship3 == ship2 or ship3 == ship1:
r = randint(1,2)
chec... |
941efaa2bcf13eef26c6e2aafa4e1706a3c52e96 | mark-selyaeff/CS102 | /Lab/gameoflife1.py | 4,733 | 3.640625 | 4 | import pygame
from pygame.locals import *
import random
from pprint import pprint as pp
class GameOfLife:
def __init__(self, width = 640, height = 480, cell_size = 10, speed = 30):
self.width = width
self.height = height
self.cell_size = cell_size
# Устанавливаем размер окна
... |
c3dd38c577f94db971f3ca3bcdde25347c4b9c12 | KirstensGitHub/Python_EdX | /Python_Edx/exercises/function_fun.py | 1,386 | 4 | 4 | #Function assignment, week2
#function 0
def tpl(x):
""" output: tpl returns thrice its input
input x: a number (int or float)
"""
return 3*x
#function 1
def sq(x):
""" output: sq returns square of input
input x: a number (int or float)
"""
return x*x
#function 2
def interp(l... |
1d466e943c8301028d3a31b007023fb30b7a2ce2 | KirstensGitHub/Python_EdX | /Python_Edx/exercises/factorial_recursion.py | 98 | 3.734375 | 4 | def fac(N):
"""calculate N! using recursion"""
if N ==0:
return 1
else:
return N * fac(N-1) |
599ff97346be71193c24c5818e5f2daf99cd6e04 | cfascina/python-learning | /exercices/built-in-functions/lambda-expression/main.py | 764 | 4.5625 | 5 | # Lambda expressions are anonymous functions that you will use only once.
# The following square() function will be converted into a lambda expression,
# step by step.
# Step 1:
# def square(number):
# result = number ** 2
# return result
# Step 2:
# def square(number):
# return number ** 2
# Step 3:
# d... |
fcc1953ee3654a511604f77b4d8ef530d70738ea | cfascina/python-learning | /exercices/advanced-modules/collections-module/named-tuple.py | 557 | 4.0625 | 4 | from collections import namedtuple
dog = namedtuple('dog', 'name age breed')
rex = dog(name = 'Rex', age = 2, breed = 'Golden Retriever')
liz = dog(name = 'Liz', age = 3, breed = 'German Shepherd')
sam = dog(name = 'Sam', age = 5, breed = 'Bulldog')
print("List of dogs:")
print("-------------")
print("\nName: " + r... |
15b734f149a394bc083ba9d4a82502f070fde233 | cfascina/python-learning | /exercices/blackjack.py | 6,163 | 3.5625 | 4 | import random
from os import system, name
# Global Variables
suits = (
'Hearts',
'Diamonds',
'Spades',
'Clubs')
symbols = (
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'J',
'Q',
'K',
'A')
values = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
... |
d0ee3567a381d1850be0ffac7e8dcfea96a11cb2 | cfascina/python-learning | /exercices/built-in-functions/exercises/6.py | 308 | 4.03125 | 4 | # Use enumerate() and other skills to return the count of the number of items in
# the list whose value equals its index.
def count_match_index(numbers):
return len([number for index, number in enumerate(numbers) if index == number])
result = count_match_index([0, 2, 2, 1, 5, 5, 6, 10])
print(result)
|
b0fcb6a3e2bf19c55ca177f8c97a8516dc744472 | cfascina/python-learning | /exercices/advanced-oop/4-super.py | 377 | 3.6875 | 4 | class A():
def truth(self):
return "class A(): The number is even."
class B(A):
pass
class C(A):
def truth(self):
return "class C(): The number is odd."
class D(B, C):
def truth(self, num):
if num % 2 == 0:
return A.truth(self)
else:
return supe... |
17585456e32b9c62c088380047e0fef6980a522d | grand-coder/stmicro2 | /3_oo.py | 714 | 3.671875 | 4 | class Person:
def __init__(self, n, h, w):
self.name = n
self.height = h
self.weight = w
def getbmi(self):
return self.weight / (self.height / 100) ** 2
def __str__(self):
return self.name
def __repr__(self):
return "/" + self.name + "/"
def __int... |
a4205c4a4e5ffd85fa2fdcaf09e503b42635d74f | psahire/Git-Tutorial-Devops | /checkItemList.py | 200 | 3.828125 | 4 | def chkElement(k):
t = list(range(2,5))
for i in t:
if i == k:
print("found")
else:
print("not found")
n = int(input("Enter the number"))
chkElement(n) |
635129ce4cbd72a5d0ea6ff62fcd6b6ef1078f71 | arminrm/python-practice | /readability.py | 914 | 3.828125 | 4 | def average_letters(sentence):
letters = 0
words = 0
for letter in sentence:
if letter.isalpha() == True:
letters += 1
for word in sentence.split():
words+= 1
return (letters * (100 / words))
def average_sentences(sentence):
sentences = 0
words = 0
for ... |
ee4f50efcfb983282db6c7a1bedf8116508ebf55 | MDCGP105-1718/portfolio-Ellemelmarta | /Python/ex11.py | 780 | 4.1875 | 4 | from random import randint
x = int(randint (1,100))
#make user guess a number with input
guess = int(input("Guess a number between 1 - 100: "))
num_guesses = 1
#tell them higher or lower
while guess != x:
if guess > x and guess != x:
print ("wrong, too high")
guess = int(input("Guess again: "))
... |
b59bf1444ea96d25bb3aa233600e298f41df21e9 | ssavann/Python-Hangman-game | /Hangman.py | 1,754 | 4.34375 | 4 | #Build a hangman game
import random
import HangmanArt
import HangmanWords
#print ASCII art from "stages"
print(HangmanArt.logo)
end_of_game = False
#List of words
word_list = HangmanWords.word_list
#Let the computer generate random word
chosen_word = random.choice(word_list)
#to count the number of letter in th... |
a87e4c4946c43db813cd9060de604ab019db4dcb | Bensrhin/Recognizing-Digits-using-Neural-Networks | /src/test/test.py | 1,049 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
# load the model
from keras.models import load_model
classifier = load_model("../cnn.h5py")
# import the input image
from keras.preprocessing import image
import cv2
# On a 3 images on choisit une.
def predict(path_image)... |
7dad1a0f71fa58342791aba5420f58ed7bf9926f | LukeKelly1995/pytorch-tutorial | /backprop.py | 1,118 | 3.96875 | 4 | """Backpropagation basics in pytorch
"""
import torch
x = torch.tensor(1.0)
print(f"Input value: {x}")
y = torch.tensor(2.0)
print(f"Target value: {y}")
w = torch.tensor(1.0, requires_grad=True)
print(f"Initialised weight value: {w}")
print()
print("Forward pass...")
y_predicted = w * x
print(f"Predicted target (w ... |
40139855c83eb27e635ba657b3e4e21adb7091ce | samiran163/Helloworld | /Operators.py | 606 | 4.40625 | 4 | #Arithmetic operators
num1 =10
num2 =20
print("num1+num2=",num1 + num2)
print("num1-num2=",num1 - num2)
print("num1*num2=",num1 * num2)
print("num1/num2=",num1 / num2)
print('5^3 =',5**3)
print("20 % 3 =", 20%3)
print("22/7=", 22//7)
print('3.8//2', 3.8//2)
#Assignment operator
num3 = num1 +num2
print(num3)
num3+=nu... |
7b032b06082cdda9f8eea84bb17bf48990e7392a | niranjanganesan/Roman_Numeral_Converter | /roman_python_terminal.py | 517 | 4 | 4 | import roman_convert
def main():
print('Please enter Roman Numeral(s): ')
string = str(input())
result = roman_new.fromRoman(string)
Blank_Input = result[1]
Invalid_Input = result[2]
output = result[0]
if Invalid_Input:
print('Invalid Roman numeral: ' +"'"+ string +"'"+ '.... |
dea1d8f9cb2fb7daa6ecd9080ea2b30423351020 | chae-eun-kim/study_python | /game/rock-paper-scissors.py | 949 | 3.84375 | 4 | def rsp(x):
import random
computer = random.randint(0, 2)
if computer == 0:
computer_rsp = "가위"
elif computer == 1:
computer_rsp = "바위"
else:
computer_rsp = "보"
print("컴퓨터 :", computer_rsp)
if x == "가위":
if computer_rsp == "바위":
print("컴퓨터 승리")
... |
942821dcf8548b1411c9c5da0cc7af8cf36f71e2 | benley/mysos | /src/mysos/executor/task_control.py | 1,804 | 3.5 | 4 | from abc import abstractmethod
from twitter.common.lang import Interface
class TaskControlProvider(Interface):
@abstractmethod
def from_task(self, task, sandbox):
pass
class TaskControl(Interface):
"""
This class encapsulates commands that control the MySQL task process.
Implementation NOTEs:
... |
019a32e40d6063dd01e292986c7d407560890786 | lord-lloyd/puzzle-tools | /puzzletools/amino.py | 6,689 | 4 | 4 | '''
Utilities for working with nucleotide and amino acid sequences.
'''
import re
def amino_encode(s):
'''
Convenience function for converting a DNA or RNA string into an amino
acid sequence.
'''
return str(NucleotideSequence(s).to_amino())
base_pair={ 'A' : 'T', 'C' : 'G', 'G' : 'C', 'T' : 'A' }... |
77f22ce39b1fee400eaf29861a4a5eca82ebf9a4 | LuiSteinkrug/Python-Design | /wheel.py | 1,400 | 4.21875 | 4 | import turtle
turtle.penup()
def drawCircle(tcolor, pen_color, scolor, radius, mv):
turtle.pencolor(pen_color) # not filling but makes body of turtle this colo
turtle.fillcolor(tcolor) # not filling but makes body of turtle this colo
turtle.begin_fill()
turtle.right(90) # Face South
... |
f91ea710e87c577b3857794a751d6f78c9376912 | davidthechihuahua/cssi-labs | /python/labs/functions-cardio/myfunction.py | 433 | 3.6875 | 4 | def count_spaces(s):
return s.count(" ")
def count_vowels(s):
numA = s.count("a")
numE = s.count("e")
numI = s.count("i")
numO = s.count("o")
numU = s.count("u")
sumVowles = numA + numE + numO + numI + numU
return sumVowles
def count_totals(s):
return count_spaces(s) + count_vowels(... |
21cebeb734c965b43779e5ec5e4bf02caf97ac2f | pratikdk/ctci_dsa_solutions | /LinkedList/1_remove_duplicates.py | 2,231 | 3.828125 | 4 | from linked_list import nodelist_builder, printNodes
from linked_list import LinkedList, linkedList_builder
def remove_duplicates(node):
map = {}
previous = None
while(node != None):
if node.data not in map:
map[node.data] = 1
if previous:
previous.next = nod... |
920ff394abb29b7f4d92f1e2571ae11660078dab | pratikdk/ctci_dsa_solutions | /trees_graphs/5_validate_bst_inorder_2.py | 545 | 3.984375 | 4 | from tree_node import TreeNode
def check_bst(root, last_printed):
if root == None: return True
if not check_bst(root.left, last_printed): return False
if last_printed != None and root.value <= last_printed: return False
last_printed = root.value
if not check_bst(root.right, last_printed): retur... |
d387301f1ab827f836bbf5503e4ce0bb4ca44c0e | pratikdk/ctci_dsa_solutions | /trees_graphs/5_validate_bst_inorder.py | 591 | 3.78125 | 4 | from tree_node import TreeNode
def check_bst(root):
array = []
copy_bst(root, array)
for i in range(1, len(array)):
if array[i] < array[i-1]:
return False
return True
def copy_bst(root, array):
if root == None: return
copy_bst(root.left, array)
array.append(root.value)
... |
cee4fce68f207b0489d2637c435081f7ac954730 | pratikdk/ctci_dsa_solutions | /String/1_is_unique/is_unique_binary.py | 749 | 3.9375 | 4 | import unittest
def is_unique(string):
checker = 0
for char in string:
char_ord = ord(char) # ord(char) - ord('a')
if (checker & (1 << char_ord)) > 0:
return False
checker |= (1 << char_ord)
return True
class Test(unittest.TestCase):
dataT = ["ghyu", "yuio"]
da... |
8f5136031e899e3662030a08fe9f11a1983bfc0b | pratikdk/ctci_dsa_solutions | /LinkedList/linked_list.py | 1,141 | 4.15625 | 4 | class Node():
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList():
def __init__(self):
self.head = self.tail = None
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def link... |
e39ccb656297672875b48b67e365615caca2b6d6 | pratikdk/ctci_dsa_solutions | /trees_graphs/6_successor.py | 716 | 3.703125 | 4 | from tree_node import TreeNode
def inorder_succ(n):
if n == None: return None
if n.right != None: # if has right subtree
return get_leftmost_child(n.right)
else:
q = n
x = n.parent
while x and x.left != q:
q = x
x = x.parent
return x
def get... |
e79fb5be83ccd875cdf13cba55f439d93392e455 | pratikdk/ctci_dsa_solutions | /trees_graphs/10_is_subtree.py | 793 | 3.96875 | 4 | from tree_node import TreeNode
def contains_tree(t1, t2):
if t2 == None: return True
return is_subtree(t1, t2)
def is_subtree(r1, r2):
if r1 == None: return False
if r1.value == r2.value and matchtree(r1, r2):
return True
return is_subtree(r1.left, r2) or is_subtree(r1.right, r2)
def matc... |
27c30c0db4aae6f35239f9370a7e39820b0a9707 | abaek/rate-things-backend | /clear_db_content.py | 359 | 3.515625 | 4 | # Connect to the database.
import pymysql
conn = pymysql.connect(
db='example',
user='root',
passwd='hello123',
host='localhost')
c = conn.cursor()
# Insert some example data.
c.execute("DELETE FROM movies")
conn.commit()
# Print the contents of the database.
c.execute("SELECT * FROM movies")
print([(... |
eb0b0e30409ee45b4bce2aa9c9f803ab4a2503c6 | philipstubbs13/python-tips-tricks-and-challenges | /automate_boring_stuff_with_python/strings_vs_lists.py | 197 | 3.765625 | 4 | # list('Hello')
# name = 'Zophie'
# name[0]
# name[1:3]
# name[-2]
# 'Zo' in name
# 'xxx' in name
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam) |
325f52227fcdd352295be2352731b33cedaf2ba4 | urantialife/AI-Crash-Course | /Chapter 2/Functions/homework.py | 715 | 4.1875 | 4 | #Exercise for Functions: Homework Solution
def distance(x1, y1, x2, y2): # we create a new function "distance" that takes coordinates of both points as arguments
d = pow(pow(x1 - x2, 2) + pow(y1 - y2, 2), 0.5) # we calculate the distance between two points using the formula provided in the... |
139f3db404b2397422a5b81e60c7bf29c78ba2af | iamDio/python_Trivia | /game.py | 614 | 3.84375 | 4 | questions= [
{
'question': 'who is the president of the USA?',
'answers': ['Barack Obama','donald trump','Mike Pence','Joe Biden'],
'correct': 'donald trump'
},
{'question': 'Who is the quarterback for the New England Patriots?',
'answers': ['Peyton Manning','Chad Pennington','tom brady','Mark Sanchez'],
'correct': '... |
620e67fc5d1c5c970d5d96d4a4fa774f2b4b7bd6 | saifsafsf/Semester-1-Assignments | /Lab 08/task 3.py | 1,942 | 4 | 4 | import MaxMin # Importing module for task (b)
import AscendSort as AscSort #Importing module for task (d)
input_list = list()
inp = str() # To enter while loop
while inp != 'E':
print('Enter N to enter the numbers again.')
print('Enter M for max. & min. numbers in this list.')
print('En... |
ffbd00fdd98bd32c205092d4a763a78bf0bfb41f | saifsafsf/Semester-1-Assignments | /Lab 03/task 1.py | 177 | 4.3125 | 4 | num = int(input("Enter an integer: ")) # Taking Integer
if num % 2 == 0: # Displaying Output
print(f"{num} is an even number.")
else:
print (f"{num} is an odd number.")
|
6993f804ebd81a8fac2c2c2dcc7ba5a96d37e62d | saifsafsf/Semester-1-Assignments | /Lab 11/Modules2.py | 1,894 | 4.4375 | 4 | def strength(password):
'''Takes a password.
Returns its strength out of 10.'''
pass_strength = 0
# If length of password is Good.
if 16 >= len(password) >= 8:
pass_strength += 2
# If password has a special character
if ('$' in password) or... |
ce44b33c8e5d4c26ec7f67d09fff55e8d4623d9c | saifsafsf/Semester-1-Assignments | /Lab 08/task 1.py | 419 | 4.21875 | 4 | math_exp = input('Enter a mathematical expression: ') # Taking Input
while math_exp != 'Quit':
math_exp = eval(math_exp) # Evaluating Input
print(f'Result of the expression: {math_exp:.3}\n')
print('Enter Quit to exit the program OR') # Taking input for next iteration
math_exp = input('Ent... |
7196fac0553a675a33fe3cc7816876f40fa2966e | saifsafsf/Semester-1-Assignments | /Lab 08/AscendSort.py | 533 | 4.15625 | 4 | def ascend_sort(input_list):
'''ascend_sort([x])
Returns list sorted in ascending order.'''
for i in range(1, len(input_list)): # To iterate len(list)-1 times
for j in range((len(input_list))-i):
if input_list[j] > input_list[j+1]: # Comparing two consecutive values
... |
bdf165162078678430c7db868bb38f2894b27f63 | saifsafsf/Semester-1-Assignments | /Assignment 3/Task 1.py | 780 | 4.1875 | 4 | import Maxim
import Remove # Importing modules
import Reverse
nums = input('Enter a natural number: ') # Taking input
if int(nums) > 0:
largest_num = str() # Defining variable before using in line 9
while nums != '':
max_num = Maxim.maxim(nums) # Using Maxim module
large... |
36b242dc24f827ec5127723d0f98af2bccea810a | saifsafsf/Semester-1-Assignments | /Lab 10/task 2.py | 1,845 | 3.890625 | 4 | import Enc_Dec # Importing module
def frequency(text, option): # To find frequency
'''Returns frequency of rules used.'''
used_rules = []
rules = {
'a' : 'i',
'e' : 'o',
'i' : 'u',
'o' : 'a',
'u' : 'e',
... |
c8731926e2de6806cbe1040c73e9fec7f37b18ba | saifsafsf/Semester-1-Assignments | /Lab 12/task 2.py | 921 | 3.78125 | 4 | # Importing module
from tkinter import *
# Making window
window = Tk()
# Title
window.title('Calculator')
# Textbox
txt_box = Entry(window, width=70)
txt_box.grid(row=0, column=0, sticky = 'nswe', columnspan = 5)
# All the texts on buttons
txts = ['Cls', 'Back', ' ', 'Close',
7, 8, 9, '/',
... |
d1798cc1f36252a27c7a3a3908d61a515d1a6226 | ridinhome/Python_Fundamentals | /03_more_datatypes/2_lists/03_07_duplicates.py | 140 | 3.59375 | 4 | '''
Write a script that removes all duplicates from a list.
'''
list_ = [1, 2, 3, 4, 3, 4, 5]
new_list = set(list_)
print (new_list)
|
ba2c1f8c3440bbcc652276ea22c025fdc6fae4d6 | ridinhome/Python_Fundamentals | /07_classes_objects_methods/07_01_car.py | 862 | 4.4375 | 4 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and dem... |
3ca0df53a0db382f61549d00923829d0dc3b00be | ridinhome/Python_Fundamentals | /08_file_io/08_01_words_analysis.py | 1,565 | 4.4375 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
my_dict = {}
shortest_list = []
longest_list = []
def shortestword(input_dic... |
51f7ad6f0f7c9be93b64c93a8a91adacb24245ce | ridinhome/Python_Fundamentals | /02_basic_datatypes/1_numbers/02_03_runner.py | 388 | 4.03125 | 4 | '''
If a runner runs 10 miles in 30 minutes and 30 seconds,
What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km)
'''
run_distance = 10
run_time_mins = 30
run_time_sec = 30
total_mins = run_time_mins + (run_time_sec / 60)
speed = run_distance / total_mins
speed_mph = speed * 60
speed_kmh = sp... |
e7b7f67b910752eb673dfe6715ec089ab650158b | ridinhome/Python_Fundamentals | /08_file_io/08_02_writing.py | 418 | 3.96875 | 4 | '''
Write a script that reads in the contents of words.txt and writes the contents in reverse
to a new file words_reverse.txt.
'''
my_list = []
with open("words.txt","r") as fin:
for word in fin.readlines():
word = word.rstrip()
my_list.append(word)
reversed_list = reversed(my_list)
with open("w... |
b644aa4a1d7e9d74a773a5e2b4dc095fac236ee2 | ridinhome/Python_Fundamentals | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 970 | 4.375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
Note: This lab might be challenging! Make sure to discuss it with your me... |
916c20052c18261dd5ef30d421b0e17b0e92d443 | ridinhome/Python_Fundamentals | /02_basic_datatypes/1_numbers/02_05_convert.py | 568 | 4.375 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
value_a = 90
value_b = 11.... |
e99bc833887b06773ff224eddd4d3f5acc595442 | lucky-star-king/javaInternet | /作业1/Dayup.py | 168 | 3.6875 | 4 | #假定初始值为1
a=1
n=1
while n<=365:
a=a*1.01
n+=1
print("累计进步",a)
a=1
n=1
while n<=365:
a=a*0.99
n+=1
print("累计剩下",a) |
8508a8c1935328e41d35f35b414e75ce89da68cb | Dimert010/raad-eens | /raad eens.py | 1,022 | 3.671875 | 4 | import random
score = 0
round = []
for x in range(1,21):
number = random.randint(1,1000)
round = ('this round: {}'.format(x))
print(round)
for i in range(0,10):
user = int(input('geuss the number: '))
if abs(user - number)<= 50 and abs(user - number) >20:
print('u... |
2f898b33d32fbe60b56c8b39bdeb5a18e44b2bb5 | ChaseReineke/underscore_lib | /underscore.py | 1,537 | 3.921875 | 4 | class Underscore:
def map(self, iterable, callback):
for i in range(0, len(iterable)):
iterable[i] = callback(iterable[i])
print(iterable)
return iterable
def find(self, iterable, callback):
for i in range(0, len(iterable)):
if callback(iterable[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.