blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d4686acca2d88d7307d3ee688c718aa9812f217b | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /fillWithZeros.py | 460 | 3.859375 | 4 |
def main():
msg = "This program will take a number and change last 2 digits to zero if is greater than 99."
msg = msg + "\n Otherwise, the number will be returned without any particular change."
print(msg)
strAmount = input("Please type in your amout: ")
if int(strAmount) > 99:
print(f"New N... |
d7762178460e77a2d4a468fccf7ab93a1c63ed1d | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /AR_TURTLE.py | 528 | 3.6875 | 4 | import turtle
import random
colours = {
0: 'green',
1: 'gold',
2: 'orange',
3: 'blue',
4: 'navy',
5: 'violet',
6: 'cyan',
7: 'yellow',
8: 'red',
9: 'light blue',
}
t = turtle.Turtle()
s = turtle.Screen()
s.bgcolor('black')
t.pencolor('white')
a = 0
b = 0
t.speed(0)
t.penup(... |
e4550b3253ee04830024ad04a076e48b92354ba0 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /roman_numerals_helper.py | 1,883 | 3.515625 | 4 | romans_dict = {"IV": 4, "IX": 9, "XL": 40, "XC": 90, "CD": 400, "CM": 900,
"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def from_roman(roman_num):
try:
numeric_value = 0
roman_key = ""
roman_double_key = ""
for n in range(len(roman_num)):
... |
2c5248348bc7cfa59f6cac6887176bfe922f6b90 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /Working with text Files/textFiles.py | 1,795 | 4.09375 | 4 | # This function will generate a random string with a lenght based on user input number.
# This can be useful for temporary passwords or even for some temporary login tokens.
# The information is saved afterwards in a text file with the date and the username
# of the person who requested the creation of the new password... |
1e8270231129139869e687fbab776af985abdacb | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /guess_random_num.py | 871 | 4.34375 | 4 | # -------------------------------------------------------------------------
# Basic operations with Python 3 | Python exercises | Beginner level
# Generate a random number, request user to guess the number
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - June 4th, 2021
# JavaScript, Python and Web Development tip... |
e3ae1adfb9306b0d81504716aab521373f427a42 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /liam_birthday_cake.py | 657 | 3.5625 | 4 | import turtle as t
import math as m
import random as r
def drawX(a, i):
angle = m.radians(i)
return a * m.cos(angle)
def drawY(b, i):
angle = m.radians(i)
return b * m.sin(angle)
t.bgcolor("#d3dae8")
t.setup(1000, 800)
t.penup()
t.goto(150, 0)
t.pendown()
t.pencolor("white")
t.begin_fill()
for i... |
5913c4bf968dd46bbf3f0552a61c1855264a4782 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /TURTLE PROJECTS/TURTLE EXAMPLES/multi_circles.py | 462 | 3.5 | 4 | import turtle
import random
colours = {
0: 'green',
1: 'gold',
2: 'orange',
3: 'blue',
4: 'navy',
5: 'violet',
6: 'cyan',
7: 'yellow',
8: 'red',
9: 'light blue',
}
# t = turtle.Turtle()
#turtle.Screen().bgcolor("black")
#t.pensize(2)
# t.hideturtle()
# turtle.tracer(2)
# n... |
9fa15e00d4b8b91a607277992f09681deed7b89c | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /strips_input.py | 1,176 | 3.734375 | 4 | # Made with ❤️ in Python 3 by Alvison Hunter - December 31st, 2020
def find_solution(string, markers):
lst_rows = string.split("\n")
for index_num, elem in enumerate(lst_rows):
for marker in markers:
ind = elem.find(marker)
if (ind != -1):
elem = elem[:ind]
... |
2e515aa55f3994049bfa5e5da33753b927c54374 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /find_positive_neg_numbers.py | 944 | 4.03125 | 4 | # ---------------------------------------------------------------------------------------------
# Get 10 numbers, find out if they are all positive, minor or equal to 99 & if 99 was typed.
# Made with ❤️ in Python 3 by Alvison Hunter - May 17th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9h... |
5c92d100afaeff3c941bb94bd906213b11cbd0bd | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /tower_builder.py | 644 | 4.3125 | 4 | # Build Tower by the following given argument:
# number of floors (integer and always greater than 0).
# Tower block is represented as * | Python: return a list;
# Made with ❤️ in Python 3 by Alvison Hunter - Friday, October 16th, 2020
def tower_builder(n_floor):
lst_tower = []
pattern = '*'
width = (n_flo... |
9030b8aa3ca6e00f598526efe02f28e3cc8c8fca | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /user_details_cls.py | 2,565 | 4.28125 | 4 | # --------------------------------------------------------------------------------
# Introduction to classes using a basic grading score for an student
# Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -----------------------------... |
57214b69ac361ea4a28d62f1d9da29879a895215 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /bike_rental_payment.py | 1,728 | 3.796875 | 4 | # --------------------------------------------------------------------------------
# Bike rentals. 100 mins = 7xmin, 101 > 1440 = 50 x min, 1440 > 96000
# Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# ----------------------------... |
f229b5e567fb0243c3c8b32acc730c11dfcf3856 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /TURTLE PROJECTS/TURTLE EXAMPLES/spirograph_sphere.py | 694 | 3.640625 | 4 | # ---------------------------------------------------------------------------
# Let's built a multi-colored lines Spirograph using python and turtle module
# Made with ❤️ in Python 3 by Alvison Hunter - March 23th, 2022
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------... |
ea028ebf1fdb4f74028315e52ebf4e8658ceb927 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /people_in_your_life.py | 655 | 4.4375 | 4 | # --------------------------------------------------------------------------------
# Introduction to classes using a basic grading score for an student
# Made with ❤️ in Python 3 by Alvison Hunter - March 6th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# ------------------------------... |
2b586de4cf57c5cea9060af113a9d97d047952b4 | Ziles131/PyCourseStepik | /1.6_inheritance_class_3.py | 321 | 3.625 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(list, Loggable):
def append(self, v):
super(LoggableList, self).append(v)
super(LoggableList, self).log(v)
l = LoggableList()
print(l)
l.append(17)
l.append(1)
l.append(89)
l.append(9)
l.append(35)... |
e917dbbac09b04a21d97e7a322597eac8e86fa41 | Ziles131/PyCourseStepik | /Standard_Language_Facilities_2/Errors_and_exceptions_2.3.py | 214 | 3.53125 | 4 | class NonPositiveError(Exception):
pass
class PositiveList(list):
def append(self, x):
if int(x) > 0:
y = super(PositiveList, self).append(x)
return y
else:
raise NonPositiveError("incorrect number") |
13739cc96abe84a26a355655e16e5e4885bbbb33 | leofeen/Translator_Web | /translator/translator_web/translate.py | 16,771 | 3.96875 | 4 | def translate(input_data: str, language: str):
"""
Keywords are case insensitive.
Commands are case sensitive.
"""
output_data = ''
language_reference = get_language_reference(language)
# Every programm should have main block:
# starts with 'begin' token,
# ends with 'end' token - c... |
805e604bebdab27987ca0939a06dee8475e9bd82 | yellowsimulator/data-centric-software-application | /examples/3 - data-storage/database_operations.py | 1,873 | 3.8125 | 4 | """
Implemets databases operations such as
- creates database
- creates table
- inssert rows into a table
- drop a table
Uses local host by default.
"""
import psycopg2 as psg
from sql_queries import create_table_queries
from sql_queries import drop_table_queries
def connect_to_database():
"""Creates a connecti... |
9edc52e38c8638524b6d9174eefa07228892ec13 | Irziii-Hasan/ttd | /MainMenu.py | 3,738 | 3.984375 | 4 | """
Game rules:
-The goal of blackjack is to beat the dealer's hand without going over 21.
-Face cards are worth 10. Aces are worth 1 or 11, whichever makes a better
hand.
-Each player starts with two cards, one of the dealer's cards is hidden
until the end.
-To 'Hit' is to ask for another card. To 'Stand' is to hol... |
8d518deff2e20738be27d935dde0a2f63021c251 | gonium/statsintro | /Code3/pythonFunction.py | 817 | 3.84375 | 4 | '''Demonstration of a Python Function
author: thomas haslwanter, date: May-2015
'''
import numpy as np
def incomeAndExpenses(data):
'''Find the sum of the positive numbers, and the sum of the negative ones.'''
income = np.sum(data[data>0])
expenses = np.sum(data[data<0])
return (income, expenses... |
f2bc3ca82085bcc512b5a69c878c1c5159371267 | pyotel/tensorflow_example | /Day_02_02_slicing.py | 522 | 3.71875 | 4 | # Day_02_02_slicing.py
a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
print(a[0], a[-1])
print(a[3:7]) # 시작, 종료
print(a[0:len(a)//2])
print(a[len(a)//2:len(a)])
print(a[:len(a)//2])
print(a[len(a)//2:])
# 문제
# 짝수 번째만 출력해 보세요.
# 홀수 번째만 출력해 보세요.
# 거꾸로 출력해 보세요.
print(a[::])
print(a[::2])
print(a[1::2])
... |
f476ccc1026447d2f41ca07d5c5e6de5468018c6 | jonathf/adventofcode | /2019/06/run.py | 7,045 | 4.21875 | 4 | """
--- Day 6: Universal Orbit Map ---
You've landed at the Universal Orbit Map facility on Mercury. Because
navigation in space often involves transferring between orbits, the orbit maps
here are useful for finding efficient routes between, for example, you and
Santa. You download a map of the local orbits (your puzz... |
cf31bb2cfe70b1bb00ba4045a1482ac568f76fa5 | jonathf/adventofcode | /2019/04/run.py | 3,597 | 4.125 | 4 | """
--- Day 4: Secure Container ---
You arrive at the Venus fuel depot only to discover it's protected by
a password. The Elves had written the password on a sticky note, but someone
threw it out.
However, they do remember a few key facts about the password:
* It is a six-digit number.
* The value is within ... |
9a79519d12b3d7dbdbb68c14cc8f764b40db1511 | ChristianECG/30-Days-of-Code_HackerRank | /09.py | 1,451 | 4.40625 | 4 | # ||-------------------------------------------------------||
# ||----------------- Day 9: Recursion 3 ------------------||
# ||-------------------------------------------------------||
# Objective
# Today, we're learning and practicing an algorithmic concept
# called Recursion. Check out the Tutorial tab for learning... |
7405e9613731ccfdc5da27bf26cf12059e8b4899 | ChristianECG/30-Days-of-Code_HackerRank | /11.py | 1,745 | 4.28125 | 4 | # ||-------------------------------------------------------||
# ||---------------- Day 11: 2D Arrays --------------------||
# ||-------------------------------------------------------||
# Objective
# Today, we're building on our knowledge of Arrays by adding
# another dimension. Check out the Tutorial tab for learning... |
1723f2e6d0885e6abc7dadf890fef8fd63062ae4 | William-McKee/udacity-data-analyst | /Enron_Fraud_POI_Identifier/explore_dataset.py | 3,896 | 3.703125 | 4 | """
Explore basic information about the data set
"""
import numpy as np
def explore_basics(dataset):
'''Print basic statistics about dataset'''
print("Data Set Basics")
print("Number of employees/vendors? ", len(dataset))
print("Number of persons of interest (POIs)? ", get_feature_valid_poin... |
7af39c66eba7f0299a47f3674f199233923b4ba9 | abasired/Data_struct_algos | /DSA_Project_2/file_recursion_problem2.py | 1,545 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 19:21:50 2020
@author: ashishbasireddy
"""
import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also cont... |
7320949169efef2b15c71d9fcc44eb366b4fdc3c | JankovicNikola/python | /basics/settype.py | 312 | 3.53125 | 4 | s={10,20,30,'XYZ', 10,20,10}
print(s)
print(type(s))
s.update([88,99])
print(s)
#print(s*3)
s.remove (30)
print(s)
#nema duplikata, ne radi indexind, slicing, repetition ali rade update i remove1
f=frozenset(s)
f.update(20)
#frozenset ne moze update i remove, nema menjanja samo gledanje
|
ba3a81a69f5c609bdae6c134e0e08916f107cea6 | webappDEV0001/python_datetime_util | /utils.py | 622 | 3.546875 | 4 | from datetime import datetime, timedelta
def datetime_converter(value):
if isinstance(value, datetime):
return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
def normalize_seconds(seconds):
seconds = int(seconds)
(days, remainder) = divmod(seconds, 86400)
(hours, remainder) = divmod(remainder, 3600)... |
06788574fddaacde210956943be373cfaac91fa9 | zolars/dashboard-ocr | /packages/opencv/main.py | 11,746 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
import cv2
import numpy as np
import math
from datetime import datetime as dt
def avg_circles(circles, b):
avg_x = 0
avg_y = 0
avg_r = 0
for i in range(b):
# optional - average for multiple circles (can happen when a dashboard is at a slight angle)
avg_x = avg_... |
078782bd9138dd1d925474a07b829431101ac648 | vsehgal1/automate_boring_stuff_python | /ch7/strip.py | 589 | 3.921875 | 4 | # strip.py
# automatetheboringstuff.com Chapter 7
# Vikram Sehgal
import re
def strip(strn, chars):
if chars == '':
reg_space = re.compile(r'^(\s*)(\S*)(\s*)$') #regex for whitespace
new_strn = reg_space.search(strn).group(2)
return new_strn
else:
reg = re.compile(r'(^[%s]+)(.... |
782b07d8fc6ca8ee98695353aa91f9d6794ea9ca | Delrorak/python_stack | /python/fundamentals/function_basic2.py | 2,351 | 4.34375 | 4 | #Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
#Example: countdown(5) should return [5,4,3,2,1,0]
def add(i):
my_list = []
for i in range(i, 0-1, -1):
my_list.append(i)
... |
aa4f667f7f4dcb01282041cb3231caf2accaa0d3 | maheshphutane/stegonography | /stegonography.py | 998 | 3.765625 | 4 | from PIL import Image
import stepic
def encode():
img = input("Enter image name(with extension): ")
image = Image.open(img)
data = input("Enter data to be encoded : ")
if (len(data) == 0):
raise ValueError('Data is empty')
#converting string to bytes format
dat... |
06779614e3f152ca83124f26e610af400b21c1d0 | cegasa89/Python-Courses | /data/dataFrames.py | 885 | 3.5 | 4 | import numpy as np
import pandas as pd
A = [1, 2, 3, 4]
B = [5, 6, 7, 8]
C = [9, 0, 1, 2]
D = [3, 4, 5, 6]
E = [7, 8, 9, 0]
df = pd.DataFrame([A, B, C, D, E], ['a', 'b', 'c', 'd', 'e'], ['W', 'X', 'Y', 'Z'])
# create a new column
print("-----------------------------")
df['P'] = df['Y'] + df['Z']
# remove a row
prin... |
2d28873dbc86e5dbdac27ffac8e42c1c1d96524b | Chahbouni-Chaimae/Atelier1-2 | /python/fact.py | 341 | 3.953125 | 4 | def factorial(x):
if x==1:
return 1
else:
return(x*factorial(x-1))
num=5
print("le factorial de ", num, "est" , factorial(num))
def somme_factorial(s,x):
s=0
s=s+(factorial(x)/x)
n=int(input("entrez un nombre:"))
for x in range(0,n-1):
print("la somme des séries est:" ,... |
886c8f7719475fdf6723610d3fb07b1a6566e825 | Chahbouni-Chaimae/Atelier1-2 | /python/invr_chaine.py | 323 | 4.4375 | 4 | def reverse_string(string):
if len(string) == 0:
return string
else:
return reverse_string(string[1:]) + string[0]
string = "is reverse"
print ("The original string is : ",end="")
print (string)
print ("The reversed string is : ",end="")
print (reverse_string(string... |
be3cee09655a2fc4851125186fbb587d63f02f97 | cathoderay/gtsimulator | /util/geometry.py | 2,165 | 3.859375 | 4 | import random
class Element:
def __init__(self, center, size):
"""Basic element of the world.
Size zero is the special case where the element is a pixel."""
self.center = center
self.centerx = center[0]
self.centery = center[1]
self.left = center[0] - size
s... |
0913ec4362f45464137b5b06569c14aadd126034 | minjjjae/pythoncode | /sqlite/sqliteclass.py | 2,212 | 3.734375 | 4 | import sqlite3
class Book:
def create_conn(self):
conn=sqlite3.connect('sqlite/my_books.db')
return conn
def create_table(self):
conn = self.create_conn()
c = conn.cursor()
sql = '''
create table if not exists books(
title text,
... |
ce86f7c872f79a9aea96fff7dec144762f436d3e | sireesha98/siri | /siri.py | 210 | 3.875 | 4 | i=raw_input("")
p=['a','e','i','o','u','A','E','I','O','U']
if (i>='a' and i<='z' or i>='A' and i<='Z'):
if (i in p):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
941fe47ca8313a8f1329985bf58eda81771b8619 | ivanklimuk/py_crepe | /utils.py | 1,931 | 3.578125 | 4 | import string
import numpy as np
import pandas as pd
from keras.utils.np_utils import to_categorical
def load_train_data(path, labels_path=None):
'''
Load the train dataset with the labels:
- either as the second value in each row in the read_csv
- or as a separate file
'''
train_text = np.arr... |
a3035208563797b6d6e40fd0441b6bc51aba495b | PSY31170CCNY/Class | /Stephanie Bodden/Assignment 1.py | 661 | 3.609375 | 4 | class Person:
def __init__(self,firstname='', lastname='',email=''):
self.firstname = firstname
self.lastname = lastname
self.email = email
e=open("names.txt","r")
names=e.readlines()
for line in names:
#Decide if it's blank, name, or email line.
#If the length of line is ... |
d17f62b713eec8210603b4451bb656fe5b60d6fa | PSY31170CCNY/Class | /Daniel Coumswang/Assignment set 1 part 1.py | 305 | 3.796875 | 4 | #Assignment set 1 part 1
x = True
while x:
print("Please enter your information.")
A = input("Enter your first name:")
b = input("Enter your last name:")
c = input("Enter your Email:")
d = open('emaillist.csv','a')
e = '"'+A+'", "' +b+'", "'+c+"\n"
d.write(e)
|
ac6d6abe694e280fdf08930ec914e1b08fe75498 | PSY31170CCNY/Class | /Jamin Chowdhury/Assignment 1.py | 1,247 | 3.96875 | 4 | #Locate and Create
#----------------------------------------
Destination = "C:/Users/Jamin/Desktop/PythAss1/"
Filename = "Email List.csv"
File = Destination + Filename
#----------------------------------------
#Header
#----------------------------------------
z1 = ('First Name')
z2 = ('Last Name')
z3 ... |
0a0b49b0bbaf60cc0a85dcc877dea0f6bd44fa07 | PSY31170CCNY/Class | /Breona Couloote/assignment1.py | 2,751 | 4.0625 | 4 | #assignment
class Person:
def __init__(self,firstname='',lastname='',email=''):
self.firstname = firstname
self.lastname = lastname
self.email = email
def hello(self):
print("hi",self.name)
def askdata(self):
self.firstname = input("enter first na... |
b327a86ce9abee36e12397ef8de85a19217596fc | PSY31170CCNY/Class | /Jamin Chowdhury/Final Exam.py | 3,056 | 4.15625 | 4 |
#PSY31170 Winter Session 2019 Final Exam
1. Fix this expression without changing any numbers, so x evaluates to 28:
x = 7 * 2 **2
--------------------------------------
Answer: x = 7 * (2 **2)
#-----------------------------------------------------------------
2. initialize p correctly... |
9da6e7f67b9c9c6cb1ae477313bbd5faa3d39b63 | PSY31170CCNY/Class | /Ariell Lugo/Personclass.py | 3,906 | 4 | 4 | # Personclass.py
class Person:
def __init__(self,name=' ',address=' ',phone='',email=''):
self.name = name
self.address = address
self.phone = phone
self.email = email
def hello(self):
print("Hi there! My name is ",self.name)
Sally = Person('Sally','1 Any Way','123-45... |
d5f8ef92bfdaca49a9d3a6028b9f9cf79dec5ad6 | nathang21/CNT-4603 | /Project 6/Submission/Source/zipcode.py | 625 | 3.953125 | 4 | '''
Created on Dec 6, 2015
@author: Nathan Guenther
'''
import re
# Ask user for input file
fileName = input('Please enter the name of the file containing the input zipcodes: ')
# Read and save file contents
fileObj = open(fileName, 'r')
allLines = fileObj.readlines()
fileObj.close()
# Regular Expr... |
c0c4f7738c75c36dcecbce841d3c432d81530184 | zhengxiang1994/JIANZHI-offer | /test1/bubble_sort.py | 316 | 3.796875 | 4 | class Solution:
def bubblesort(self, L):
for i in range(len(L)-1):
for j in range(len(L)-i-1):
if L[j+1] < L[j]:
L[j], L[j+1] = L[j+1], L[j]
return L
if __name__ == "__main__":
s = Solution()
print(s.bubblesort([1, 3, 5, 7, 2, 4, 6]))
|
79af3c8cf80c6788daffeb7558688fd68326a4bd | zhengxiang1994/JIANZHI-offer | /test1/demo19.py | 784 | 3.84375 | 4 | # -*- coding:utf-8 -*-
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
# write code here
result = []
while matrix:
result += matrix[0]
if not matrix or not matrix[0]:
break
matrix.pop(0)
if matrix:
... |
2600e0f77da5149418d0211182bb74b7f1f0e954 | zhengxiang1994/JIANZHI-offer | /test1/demo32.py | 568 | 3.828125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
# 类似冒泡排序
for i in range(len(numbers)-1):
for j in range(len(numbers)-i-1):
if int(str(numbers[j])+str(numbers[j+1])) > int(str(numbers[j+1])+str(numbers[j])):
... |
accfb44d8e1b173c48550e18aa9d1845f181e996 | zhengxiang1994/JIANZHI-offer | /test1/demo22.py | 1,031 | 3.90625 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
ls = []
queue = []
if not root:
... |
7b7c9250218d1f36284181b38d93c2ce594a3837 | arvind2608/python- | /desktop background change app.py | 1,910 | 3.734375 | 4 | # import modules
from tkinter import *
from tkinter import filedialog
from wallpaper import set_wallpaper
# user define funtion
def change_wallpaper():
# set your wallpaper
try:
set_wallpaper(str(path.get()))
check = "DONE"
except:
check = "Wallpaper not... |
1d01da0f3867b5d86f5cabbacbdb505c50a137f4 | tobhuber/rateme | /core/Song.py | 1,332 | 3.578125 | 4 | class Song:
def __init__(self, name = "", album = None, raters = {}, rating = -1):
self.name = name
self.album = album
self.rating = rating
self.raters = raters
self.hash = f"{self.name}#{self.album.interpret[0]}"
self.updateRating()
def __str__(self):
r... |
a4d6aa8406a45aa04ec44f12bea28c132fc0adb5 | ZL-Zealous/ZL-study | /py_study_code/循环/while.py | 211 | 3.734375 | 4 | prompt='\n please input something:'
prompt+='\n enter "quit" to end\n'
message=''
active=True
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message) |
58c1b6b2a960dcedfa0317f9276b87daa6dc895e | ZL-Zealous/ZL-study | /py_study_code/文件与异常/json.number.py | 273 | 3.578125 | 4 | import json
filename='number.json'
try:
with open(filename) as f_obj:
a=json.load(f_obj)
print("i konw the number is "+a)
except:
number = input('enter your favorite number:\n')
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
|
fdad762c31dc9a9b52f9c0fe9f5e2fb333faa415 | gokulmurali/sicp_exercises | /sicp/1-17.py | 314 | 3.8125 | 4 |
def double(x):
return x + x
def halve(x):
return (x/2)
def even(x):
if x % 2 == 0: return True
else: return False
def mul(a, b):
if b == 0:
return 0
elif even(b):
return (double(a * halve(b)))
else:
return (a + (a * (b-1)))
print mul(2, 3)
print mul(2, 4)
|
a474bbf23356b820d0ec28c9d5616fc996c9a964 | gokulmurali/sicp_exercises | /sicp/1-18.py | 384 | 3.765625 | 4 |
def double(x):
return x + x
def halve(x):
return (x / 2)
def even(x):
if x % 2 == 0:return True
else:return False
def muliter(a, b, aa):
if b == 0:
return aa
elif even(b):
return muliter(double(a), halve(b), aa)
else:
return muliter(a, b-1, (aa + a))
def mul(a, ... |
6c77d7dc7e8f789dab2c2aefdf4f2f0f16ac9352 | luisfrancisco62/Transparent-Splash-Screen-Tk | /splash.py | 640 | 3.796875 | 4 | """
Splash Screen Demonstration
Author: Israel Dryer
Modified: 2020-05-22
"""
import tkinter as tk
# create the main window
root = tk.Tk()
# disable the window bar
root.overrideredirect(1)
# set trasparency and make the window stay on top
root.attributes('-transparentcolor', 'white', '-topm... |
3d2826426b2a6328fc4d5e63ca958c554d722cc2 | La-Ola/Year-10- | /driving.py | 897 | 3.984375 | 4 | print (" Welcome to DVLA driving test.")
print ("**************************************************************")
years = int(input("How many years have you been driving for?"))
points = int(input("How many penalty point do you have?"))
if years <=2 and points >=6: #engulfs numbers including and b... |
6f8cb30a116ef9a5ccaf5a33177ef512790e78ae | La-Ola/Year-10- | /ODDS AND EVENS.py | 367 | 4.03125 | 4 | #Odds and Evens
print ("*****ODDS AND EVENS BETWEEN YOUR CHOSEN NUMBER AND 50*****")
num = int(input("Choose a number between 1 and 50."))
print("****THE EVENS****")
x = num
while x < 50:
if x%2 == 0:
print (x)
x = x + 1
print("****AND NOW THE ODDS****")
x = num
while x < 50:
if ... |
9d364d2297350eb501de9c099b8f20c6b2502435 | WolfAuto/Maths-Pro | /NEA Programming/random.py | 3,204 | 3.78125 | 4 | import tkinter as tk # python3
TITLE_FONT = ("Helvetica", 18, "bold")
class SampleApp(tk.Tk): # create a class that takes in a parameter of a tkinter GUI screen
def __init__(self, *args, **kwargs): # instalise the class with the parameters self with
tk.Tk.__init__(self, *args, **kwargs)
# t... |
8de6eedf90b3c7fd5ff34e0780ee44240049d0ef | WolfAuto/Maths-Pro | /NEA Testing/remake_register.py | 9,940 | 3.65625 | 4 | from tkinter import messagebox # module for error messages on the tkinter page
import string
import re
import bcrypt
from validate_email import validate_email
import yagmail
from create_connection import cursor, cursor1, db
shared_data = {"firstname": "blank", # dictionary that stores the user register infor... |
9907161a049b3e6088bd04f1f807fc2b2664b087 | WolfAuto/Maths-Pro | /Maths-Pro-NEA-TESTING/NEA Testing/login page.py | 7,788 | 3.8125 | 4 | import sqlite3
import tkinter as tk
from tkinter import ttk
title_font = ("Times New Roman", 50)
medium_font = ("Times New Roman", 26)
class MathsPro(tk.Tk): # Creating a class that inherits from tk.Tk
def __init__(self, *args, **kwargs): # intialises the object
# intialises the object as a tkinter fr... |
00d264591a57a5b69b759be8d6ac75b603ee0a5f | WolfAuto/Maths-Pro | /Maths-Pro-NEA-TESTING/NEA Programming/Stage 1 Creating GUI/learning.py | 1,589 | 3.890625 | 4 | import random
import sqlite3
with sqlite3.connect("datalearn.db") as db:
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS details(userID INTEGER PRIMARY KEY, firstname VARCHAR(30) NOT NULL, surname VARCHAR(30) NOT NULL , age INTEGER NOT NULL, class VARCHAR(3) NOT NULL, school VARCHAR(20) NOT NULL, us... |
d57a13ede4aba6274abe58dc902d09d61261acfa | seansaito/Number-Theory | /pingala.py | 816 | 3.921875 | 4 | import sys
def main(argv):
a = int(argv[0])
e = int(argv[1])
m = int(argv[2])
print pingala(a,e,m)
# Computes a to the power of e in mod m context
def pingala(a,e,m):
# Converts the exponent into a binary form
e_base2 = bin(e)[2:]
# This keeps track of the final answer
answer = 1
# A for loop ... |
ac73ef5689da1cc08123d76dcb3d1edc31d05ec5 | drbuche/HackerRank | /Python/01_Introduction/005_Write_a_function.py | 355 | 3.921875 | 4 | # Problem : https://www.hackerrank.com/challenges/write-a-function/problem
# Score : 10 points(MAX)
def is_leap(year):
"""
:param year: Recebe um valor referente ao ano.
:return: Retorna se o ano é bissexto ou não em forma de boolean.
"""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0... |
70bb2017ba78e0cd36a3fc50e6dbd59403c20001 | drbuche/HackerRank | /Python/01_Introduction/001_Python_If_Else.py | 477 | 4.03125 | 4 | # Problem : https://www.hackerrank.com/challenges/py-if-else/problem
# Score : 10 points(MAX)
def wierd(n):
"""
:param n: Recebe um valor inteiro 'n'
:return: Retona um print contendo 'Weird' caso o numero seja impar ou esteja entre 6 e 20.
Caso contrario retorna 'Not Weird'.
"""
print... |
828b7b647572c21ef035b7fe77764ed99ca775a5 | drbuche/HackerRank | /Python/03_Strings/005_String_Validators.py | 1,313 | 4.1875 | 4 | # Problem : https://www.hackerrank.com/challenges/string-validators/problem
# Score : 10 points(MAX)
# O método .isalnum() retorna True caso haja apenas caracteres alfabéticos e numéricos na string.
# O método .isalpha() retorna True caso todos os caracteres sejam caracteres alfabéticos.
# O método .isdigit() retorna... |
18e86788373b6bbba4cbd1d8e2084caebcb9dee5 | drbuche/HackerRank | /Python/04_Sets/003_Set.add().py | 426 | 3.75 | 4 | # Problem : https://www.hackerrank.com/challenges/py-set-add/problem
# Score : 10 points(MAX)
loops = input() # Quantidade de valores que entrarão
grupo = [] # Grupo para alocar esses valores
[grupo.append(input()) for i in range(int(loops))] # para cada loop adicione a palavra no grupo dist
print(len(set(grupo)))... |
98cf8b7d7a5f6c0753fc8812a38eb3e7a8b52590 | dsiah/Villanova-Python-Workshop | /scripts/maleGenerator.py | 628 | 3.90625 | 4 | """
A male first name generator.
The program sifts through a list of about 3,800 male names from
english speaking countries. User is asked to enter the (integer)
number of first names they would like to have generated.
Credit for the list of names goes to Grady Ward (Project Gutenberg)
See the aaPG-Readme.txt in the ... |
7f0539c1b232551296487c24c5a1885a73c8b42a | dsiah/Villanova-Python-Workshop | /Python-Exercises/regex.py | 951 | 3.953125 | 4 | import re
"""
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print 'Found "%s"\nin "%s"\nfrom %d to %d("%s")' %\
(match.re.pattern, match.string, s, e, text[s:e])
regexes = [re.compile(p)
for p in ["this", "that"]
... |
b4bc00af23adb5e933ca8429a6ef53e079ac3b86 | dsiah/Villanova-Python-Workshop | /scripts/howto.py | 669 | 3.984375 | 4 | # how to snippets of code that serve as patterns to use when programming
condition = True
condition2 = False
#if
if (condition):
#do stuff
print "Stuff"
#if/elif/else
if (condition):
print condition
elif (condition2):
print condition2
else:
print "Catch all"
#defining functions
def nameofFunc (argument):
#... |
207404ca1e3a25f6a9d008ddbed2c7ca827c789b | eigenric/euler | /euler004.py | 763 | 4.125 | 4 | # author: Ricardo Ruiz
"""
Project Euler Problem 4
=======================
A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import itertools
def is_pal... |
e8042f82196ee8eaecf800fc86ab3e04c788510a | yangahh/daliy-algorithm | /week04/answer04.py | 171 | 3.5 | 4 | def maxSubArray(nums):
dp = [0] * len(nums)
dp[0] = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1] + nums[i], nums[i])
return max(dp)
|
f71257aa717a5d2684f65505c488f1d9b6262e67 | yangahh/daliy-algorithm | /week05/answer03.py | 124 | 4 | 4 | def reverseString(str):
if len(str) == 1:
return str
else:
return str[-1] + reverseString(str[:-1])
|
25e1b8449981327950a7895d0f16d56c4a045065 | Vkomini/cs181-s18-homeworks | /T3/code/problem2.py | 1,464 | 3.515625 | 4 | # CS 181, Harvard University
# Spring 2016
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as c
from Perceptron import Perceptron
# Implement this class
class KernelPerceptron(Perceptron):
def __init__(self, numsamples):
self.numsamples = numsamples
# Implement this!
# def fit(self, ... |
d4d673ef94eca4ddfd5b6713726e507dad1849d6 | abhaj2/Phyton | /sample programs_cycle_1_phyton/13.py | 285 | 4.28125 | 4 | #To find factorial of the given digit
factorial=1
n=int(input("Enter your digit"))
if n>0:
for i in range(1,n+1):
factorial=factorial*i
else:
print(factorial)
elif n==0:
print("The factorial is 1")
else:
print("Factorial does not exits")
|
047d6aa0dd53e1adaf6989cd5a977f07d346c73c | abhaj2/Phyton | /sample programs_cycle_1_phyton/11.py | 235 | 4.28125 | 4 | #to check the entered number is +ve or -ve
x=int(input("Enter your number"))
if x>0:
print("{0} is a positive number".format(x))
elif x==0:
print("The entered number is zero")
else:
print("{0} is a negative number".format(x)) |
afad18bd31239b95dd4fd00ea0b8f66c668fd1a6 | abhaj2/Phyton | /sample programs_cycle_1_phyton/12.py | 374 | 4.1875 | 4 | #To find the sum of n natural numbers
n=int(input("Enter your limit\n"))
y=0
for i in range (n):
x=int(input("Enter the numbers to be added\n"))
y=y+x
else:
print("The sum is",y)
#To find the sum of fist n natural numbers
n=int(input("Enter your limit\n"))
m=0
for i in range (1,n):
m=m+i
else:
... |
16631b78995f655cf7a84b6628f19c067d42680e | abhaj2/Phyton | /cycle-2/19.py | 164 | 3.890625 | 4 | import math
num1=int(input("Enter the 1st number\n"))
num2=int(input("Enter the 2st number\n"))
g=math.gcd(num1,num2)
print("The greatest common divisor is", g) |
daa95e1d0332847f4d8352cd704faa809e55ab8a | abhaj2/Phyton | /sample programs_cycle_1_phyton/17.py | 124 | 4.0625 | 4 | #To count the number of digits in an integer
c=0
x=int(input("Enter the digit"))
while x!=0:
x=x//10
c=c+1
print(c) |
5bd43106071a675af17a6051c9de1f0cee0e0aec | abhaj2/Phyton | /cycle-2/3_c.py | 244 | 4.125 | 4 | wordlist=input("Enter your word\n")
vowel=[]
for x in wordlist:
if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x):
vowel.append(x)
print(vowel)
|
b1369e3aa1af6e9af13e8376f8955bd1d4a64419 | abhaj2/Phyton | /sample programs_cycle_1_phyton/16.py | 218 | 3.984375 | 4 | x=int(input("Enter the first number\n"))
y=int(input("Enter the first number\n"))
if (x>y):
min=x
else:
min=y
while (1):
if(min%x==0 and min%y==0):
print("LCM of two numbers is",min)
break
min=min+1 |
460436876ac4dbeafc3b4e7abc9ba4bb0b211ac5 | abhaj2/Phyton | /cycle-2/20.py | 115 | 3.859375 | 4 | integer=[2,0,1,5,41,3,22,10,33]
list=[]
for x in integer:
if(x%2!=0):
list.append(x)
print(list)
|
11eba6924a3dd4c84b02172ba5335e918b6af738 | juliaviolet/Python_For_Everybody | /Chapter_9/Exercise_9.4_Final.py | 509 | 3.578125 | 4 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
emails = handle.read()
words=list()
counts=dict()
maximumvalue = None
maximumkey = None
for line in handle:
if not line.startswith('From: '): continue
line = line.split()
words.append(line[1])
for word in words:
... |
a1a9fc369a0b994c99377dc6af16d00612a68f3b | juliaviolet/Python_For_Everybody | /Overtime_Pay_Error.py | 405 | 4.15625 | 4 | hours=input("Enter Hours:")
rate=input("Enter Rate:")
try:
hours1=float(hours)
rate1=float(rate)
if hours1<=40:
pay=hours1*rate1
pay1=str(pay)
print('Pay:'+'$'+pay1)
elif hours1>40:
overtime=hours1-40.0
pay2=overtime*(rate1*1.5)+40.0*rate1
pay3=str(pay2)
... |
7320b834151d83c83268ecb7d9d5a72ca64fbccc | AdilAsanbekov/homework | /laboratory_work.py | 1,107 | 3.5 | 4 | from random import randint
from abc import ABC, abstractmethod
from math import floor
class Characted(ABC):
def __init__(self, name,level=1, strength=8, dexterity=8, intelligence=8, wisdom=8, charisma=8,constitution=8):
self.level = level
self.strength = strength
self.dexterity = dexterity
self.physi... |
a48f5fdb04a1ad05b3613fef58f605c5b02ecc3b | abdiazizf/Chexers | /convert_json_to_board_dict.py | 799 | 3.859375 | 4 | # Converts a JSON into a dictionary of tuples(board co-ordinates) as keys with values to be printed
# e.g {[0,2]: 'R',[0,0]:'BLK'}
def convert_json_to_board_dict(file):
# Reads colour from the JSON, compares it to a dictionary of values and
# sets the correct symbol
colour_dict = {'red' : 'R','... |
ddc84b9fe6cd1914fcaf55063d7df0dc9c8f7443 | rajvseetharaman/Hackerrank---Data-Structures-and-Algorithms | /Tries-Contacts.py | 1,161 | 3.59375 | 4 | class Node:
def __init__(self,children,endofword,countofword):
self.children=children
self.endofword=endofword
self.countofword=countofword
def contact_add(contact,root):
pointer=root
for i,letter in enumerate(contact):
if letter not in pointer.children.keys():
... |
8f5b0df594cd45f91cb61f6afbcb6e9aa2edcafa | saintcoder14/JARVIS | /jarvis.py | 2,252 | 3.5 | 4 | import pyttsx3 #for output voice kinda
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
# Imp function used to convert a tex... |
360b8fda90ac1651976268e9cf4205d7ec59f687 | ikhebgeenaccount/MusicBeeStats | /mbp/tagtracker.py | 4,884 | 4.09375 | 4 | class TagTracker:
"""A TagTracker tracks a certain tag.
Arguments:
tag - the tag to be tracked, can be either a str or a function which takes a Track and outputs some value
tag_data - the data tag to be tracked grouped under tag, can be either a str or a function which takes a Track and outputs some value
unique -... |
4bdaa4b30be65fa22cbf64265123484375d2c924 | Juttiz/cs50 | /pset6/vigenere.py | 1,096 | 3.828125 | 4 | from cs50 import get_string
from sys import argv
import sys
def main():
while True:
if len(sys.argv) ==2:
break
print("usage: python crack.py keyword")
exit(1)
cipher = []
n = 0
for i in range(len(argv[1])):
# cipher[i] =
if argv[1][i].isupper():
... |
565e52b6beea00de278a0a46d24237839419748f | Juanma1909/scientific-computing | /Entrega Diferenciacion e Integracion/labdif.py | 7,693 | 4.15625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from time import time
def printA(f,x):
"""
Entrada: una funcion f y un arreglo x de números reales
Salida: un arreglo y de numeros reales correspondientes a la evaluacion de f(x)
Funcionamiento: se realiza un ciclo iterando por cada valor dentro del arregl... |
b0ac70b3510ec9bab0f2ca5b49abdf9d2ccabc23 | gutsergey/PythonSamples | /Fedorov/5 Strings/strings1.py | 910 | 3.59375 | 4 | def strings1():
a = "qwerty"
b = 'qwerty123'
c = '''comment1
text1
text2
text3
---- text 4 end of comment1-------
'''
d = """comment 2
text 1
text2
text3
----- end of comment 2 ---------
'''
"""
e = " somebody says: 'Hello' "
f = ' somebody says: "Hello" '
print (a)
print (b)
pri... |
28fe9d2012c336a30119abc523ecd17c5dc41aed | gutsergey/PythonSamples | /Fedorov/4/averageofthreenumbers2.py | 184 | 3.578125 | 4 | def averageofthreenumbers2(a=2, b=4, c=7):
return (a + b + c)/3
print(averageofthreenumbers2())
print(averageofthreenumbers2(5, 7, 2))
print(averageofthreenumbers2(c=3, a=4))
|
687453f6803bea6331dc6513208bc8c7de45bf22 | yeraydiazdiaz/lunr.py | /lunr/vector.py | 5,295 | 4.125 | 4 | from math import sqrt
from lunr.exceptions import BaseLunrException
class Vector:
"""A vector is used to construct the vector space of documents and queries.
These vectors support operations to determine the similarity between two
documents or a document and a query.
Normally no parameters are requi... |
65ff4a78f9cc6d7254418df1489c95eb0acbe98f | cfung/machine-learning | /projects/smartcab/smartcab/agent.py | 11,289 | 3.71875 | 4 | import random
import math
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
from collections import defaultdict
from helper import calculate_safety, calculate_reliability, evaluate_results
class LearningAgent(Agent):
""" An agent that learns to drive in the... |
d387a110a9578f1fcf92811f2efc64161feddbf4 | faisalsupriansyah/praxis-academy | /novice/01-02/data_type_convertion/arrayvlist.py | 1,164 | 3.53125 | 4 | import numpy as np
arr_a = np.array([3, 6, 9])
arr_b = arr_a/3 # Performing vectorized (element-wise) operations
print(arr_b)
arr_ones = np.ones(4)
print(arr_ones)
multi_arr_ones = np.ones((3,4)) # Creating 2D array with 3 rows and 4 columns
print(multi_arr_ones)
stack = [1,2,3,4,5]
stack.append(6) # Bottom -> 1 ... |
6995eed67a401cd363dcfa60b2067ef13732becb | ha1fling/CryptographicAlgorithms | /3-RelativePrimes/Python-Original2017Code/Task 3.py | 1,323 | 4.25 | 4 | while True: #while loop for possibility of repeating program
while True: #integer check for input a
try:
a= input ("Enter a:")
a= int(a)
break
except ValueError:
print ("Not valid, input integers only")
while True: #integer check ... |
bd1db01726f5373dadb80c3da3f29b4ec1f8ad88 | TiagoArrazi/Python-HOME | /FileProcessor.py | 588 | 3.59375 | 4 | import os
import csv
def main():
arq = input('Insira o nome do arquivo ')
name, ext = os.path.splitext(arq)
if ext == '.txt':
processaTxt(arq)
elif ext == '.csv':
processaCsv(arq)
else:
print('ERRO!')
def processa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.