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 |
|---|---|---|---|---|---|---|
7af27b0f76dd9c466cb1d5d5dc58d99381be6f10 | ksamala/k_python | /scripts/17_opn_clse.py | 774 | 3.703125 | 4 | #Open and close file in one line.
with open('/Users/kalyansamala/Downloads/test.txt') as open_instance:
print(open_instance.read())
#Open and write contents in a file
with open('/Users/kalyansamala/Downloads/test.txt', mode='a') as afile:
afile.write('new line added \n')
with open('/Users/kalyansamala/Downloa... |
01cb6d73ca5ebd12fb69157668da2365e5a327e6 | ksamala/k_python | /scripts/23_for_continue.py | 220 | 4.09375 | 4 | name = 'malayalam'
for letter in name:
if letter == 'a':
continue
print(letter)
print("Check break statment")
name = 'malayalam'
for letter in name:
if letter == 'a':
break
print(letter) |
18c07f03236f4d5b8294f843aba0ba1a53ce8b03 | ksamala/k_python | /scripts/3_area.py | 326 | 4.03125 | 4 | # Use functions to caluculate area
def gather_details():
lnt = int(input("Enter length"))
brt = int(input("Enter breadth"))
return (lnt, brt)
def compute(lnth, brth):
area = lnth*brth
return area
while True:
ln, br = gather_details()
area = compute(ln, br)
print(f"Area is {a... |
8a8bcb8b2060791d4e257a5fee7e6d551ea4f38e | ksamala/k_python | /scripts/32_handle_incorrect_input.py | 165 | 3.609375 | 4 | def ask():
try:
a = int(input("Enter integer "))
return a
except:
print("Enter Integer only")
while True:
z = ask()
print(z) |
23579f6ff0e1b600c90c90b1618e6b9cb8e0e2d5 | mukobi/pozyx-clone | /house_code/main_programs/PSUPozyx/modules/file_writing.py | 35,702 | 3.546875 | 4 | from .data_functions import DataFunctions as DataFunctions
class SensorDataFileWriting:
@staticmethod
def write_sensor_data_header_to_file(file,
header=("Index,Time,Difference,Hz,AveHz,"
"Pressure,"
... |
63d67329e94978a29fcdf6bd2ee3a1d200660cbf | pyjune/python3_doc | /2_4.py | 555 | 4.125 | 4 | # 사칙연산
a = 3
b = 5
print(a+b)
print(a+10)
print(a-b)
print(a*b)
print(b*6)
print(a/b)
print(a/10)
# 정수형 나눗셈
print(3//2)
print(5//2)
# 모드 연산
print(a%2) #a를 2로 나눈 나머지
print(b%a) #b를 a로 나눈 나머지
# 거듭 제곱
print(a**2)
print(a**3)
print(b**a)
# 비교연산
a = 3
b = 5
print(a>0)
print(a>b)
print(a>=3)
print(b<10)
print(b<=5)
print... |
1a94a3de903e70d1b8c7c263beebcd1e4fb8268c | pyjune/python3_doc | /5_2.py | 958 | 3.859375 | 4 | menu = ['','Americano', 'Latte', 'Espresso', 'Mocha', '식혜', '수정과']
price = [0,1500, 2000, 1700, 2500, 2000, 1900]
# 메뉴 보이기
i = 1
#while i <= 6:
while i< len(menu):
print(i, menu[i], price[i])
#print("%d. %-10s %5d"% (i, menu[i], price[i]))
i = i+1
# 음료 선택
n = int(input("음료를 선택하세요 : "))
total = price[n]
... |
c0559f619307150cfccbfe7337230fcab9da3abe | priyash555/Automation-Bots | /KS/MAIN APP/dol_extractor.py | 492 | 3.59375 | 4 | import pytz
import date_extractor
def extract_dol(lines):
'''take list as input
break it into lines and
extract date from each lines
if present
'''
dates_arr = []
for line in lines:
dates = date_extractor.extract_dates(line)
for date in dates:
dates_arr.append(date.date())
return d... |
5a91714dc26aae0d9398fdd3ea4bffa11693ca6f | SamirIngley/CS1.1 | /backwards_poetry.py | 569 | 4.09375 | 4 | poem1 = ["hello", "whatsup", "go"]
def lines_printed_backwards(poem):
''' returns text words in backwards order. takes a list of strings. '''
# get the poem , be able to access each element. access the last one. append it to new list.
backwards = []
length = len(poem) - 1
enum_poem = [(word) for... |
e50bdbb27ed6cb65eeaaf4752b349aac3839be41 | coding-hamster/Udacity-Programming-Foundations-with-Python | /turtle_scripts.py | 549 | 3.546875 | 4 | import turtle
window = turtle.Screen()
window.bgcolor('red')
def draw_square():
brad = turtle.Turtle()
for i in range(1, 5):
brad.forward(100)
brad.right(90)
draw_square()
def draw_circle():
window = turtle.Screen()
angie = turtle.Turtle()
angie.shape('arrow')
... |
92af7504ba29fb231a94e3d623e73e86a8d12e6d | contactpunit/python_sample_exercises | /ds/ds/martiniq.py | 308 | 3.5 | 4 | def get_index_different_char(chars):
alnum = []
special = []
for index, char in enumerate(chars):
if str(char).isalnum():
alnum.append(index)
else:
special.append(index)
if len(alnum) == 1:
return alnum[0]
else:
return special[0]
|
7386ce12bbf8da0b9bc87978528ff3ebe0aa63df | contactpunit/python_sample_exercises | /ds/ds/password_validate.py | 1,169 | 3.65625 | 4 | import string
from collections import defaultdict
PUNCTUATION_CHARS = list(string.punctuation)
used_passwords = set('PassWord@1 PyBit$s9'.split())
def validate_password(password):
if not len(password) >= 6 and not len(password) <= 12:
return False
if password in used_passwords:
return False
... |
471bb7458f78b94190321bdcbaa0dce295cdb3f9 | contactpunit/python_sample_exercises | /ds/ds/mul_table.py | 1,088 | 4.21875 | 4 | class MultiplicationTable:
def __init__(self, length):
"""Create a 2D self._table of (x, y) coordinates and
their calculations (form of caching)"""
self.length = length
self._table = {
(i, j): i * j
for i in range(1, length + 1)
for j in range(... |
21f4ed0a79f4a0f826cad6224de312a2f0d7469d | contactpunit/python_sample_exercises | /ds/ds/length_convertor.py | 671 | 3.59375 | 4 | import numbers
import decimal
def convert(value: float, fmt: str) -> float:
#TODO: Complete this
"""Converts the value to the designated format.
:param value: The value to be converted must be numeric or raise a TypeError
:param fmt: String indicating format to convert to
:return: Float rounded t... |
2f11dedc0c3c5e393b0ad0228ca82171f5797f9a | contactpunit/python_sample_exercises | /ds/ds/averager.py | 266 | 3.71875 | 4 | def averager():
count = 0
total = 0
avg = 0
while True:
num = yield avg
total += num
count += 1
avg = total/count
a = averager()
print(a)
print(next(a))
print(a.send(20))
print(a.send(10))
print(a.send(12))
a.close() |
fe5b3f647a9a1cba98baf36b5e799fe0045d8a6a | contactpunit/python_sample_exercises | /ds/ds/count_dirs.py | 430 | 3.9375 | 4 | import os
def count_dirs_and_files(directory='.'):
"""Count the amount of of directories and files in passed in "directory" arg.
Return a tuple of (number_of_directories, number_of_files)
"""
countd, countf = 0, 0
for (dirpath, dirnames, filenames) in os.walk(directory):
countd += len(d... |
963384575a80de01b2c87d8ad911db047bb90e2b | raipier8818/PyTorch | /2_LinearRegression/Autograd.py | 400 | 3.53125 | 4 | import torch
w = torch.tensor(2.0, requires_grad = True)
y = w**2
z = 2*y + 5
z.backward()
print('{}'.format(w.grad))
w = torch.tensor(2.0, requires_grad = True) # 기울기 저장
b = torch.tensor(1.0, requires_grad = True)
z = (b*w)**2 + b**2
z.backward() # z를 미분한 다음 각 값(w = 2.0, b = 1.0)을 대입하여 w.grad와 b.grad에 저장
pr... |
10f2d2d007005edc0a52585ed89893217cb49b79 | EduardoCostaEXE/Calculadora_Simples | /calculadora.py | 464 | 3.84375 | 4 | class Calculadora:
def __init__(self, num1, num2) :
self.a = num1
self.b = num2
def soma(self):
return self.a + self.b
def subtracao(self):
return self.a - self.b
def multiplacacao(self):
return self.a * self.b
def divisao(self):
return self.a / sel... |
b0aca5370c680946127c5792b4957e37f9df67e8 | CrRaul/AvoidBlocksNN | /Matrix.py | 4,221 | 3.84375 | 4 | import random
# Class Matrix contain number of rows, number of columns, data of matrix and operation with matrix
class Matrix():
# Desc:
# In:
# Out:
def __init__(self, rows, cols):
self.__rows = rows
self.__cols = cols
self.__data = []
for i in range(0,... |
5355734d9c928e1fddbc49437bd5f8d545581e76 | vijaymaddukuri/rest_api_project | /utils/service/restlibrary.py | 1,586 | 3.515625 | 4 | from requests.sessions import Session
class RestLib(Session):
"""
Library for REST API Calls
"""
def get(self, url, **kwargs):
"""Sends a GET request. Returns :class:`Response` object.
Args:
:param url: URL for the new :class:`Request` object.
:param kwargs: Option... |
5a782b26a97db6c36626fb332c310d8560a73185 | jtcressy/oop-final-project-spring-2018 | /gamepad/mouse.py | 375 | 3.5625 | 4 |
class Mouse:
BUTTON_LEFT = 1
BUTTON_RIGHT = 2
BUTTON_MIDDLE = 3
BUTTON_FORWARD = 4
BUTTON_BACK = 5
BUTTON_4 = BUTTON_FORWARD
BUTTON_5 = BUTTON_BACK
def click(self, button):
"""Click mouse button"""
def move(self, x, y):
"""move mouse to absolute"""
def move_re... |
22513ff4531ecdca739376893b289f061e33f544 | debargha12/MNIST_Keras | /MNIST_Keras.py | 1,752 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import keras
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
import matplotlib.pyplot as plt
# import the data
from keras.datasets import mnist
# read the data
(X_train, y_train), (X_test, y_test) = mnist.load_... |
d727cc2970a57f8343b1d222cae1a626727431ad | helong20180725/CSCE580-Projects | /machinelearning/helloTest.py | 753 | 4.125 | 4 | #note
#1. Strings
"""
print("helloworld")
capital="HI, YOU ARE CAPITAL LETTERS"
print(capital.lower())
print(capital.isupper())
print(capital[4])
print(capital.index("T"))
print(capital.replace("ARE","is"))
print("\"")
"""
#2. numbers
"""
a =10
b = 3
c = -19
d = 4.23
print(10%3)
#error print("the number is "+a)
pr... |
340e343b09e5903ef146d19cbce86781899d0244 | kesterallen/surlyfritter-appspot | /scripts/wordle.py | 1,412 | 3.671875 | 4 | # TODO: can't specify two locations for a "yes" letter, e.g. "L" in swill
BAD_LETTERS = "dieshorjoinsoldforge"
LETTERS = dict(
a=dict(yes=1, no=[]),
p=dict(yes=2, no=[]),
u=dict(yes=3, no=[]),
t=dict(yes=4, no=[]),
)
def get_words():
words = []
with open("/usr/share/dict/american-english") as ... |
d8c454028e3c65b07acd2cc95bb91ab357eabee4 | officialyenum/CS50 | /pset6/readability/readability.py | 630 | 3.796875 | 4 | from cs50 import get_string
import re
import math
#declare count variables
letter = 0
word = 0
sentence = 0
text = get_string("Text: ")
#iterate through text
for i in text:
if i.isalpha():
letter+= 1
#use regex to findall words and return the length
word=len(re.findall(r'\w+', text))
#use regex to findal... |
6a9037fda33b82e8b7abae2f798d8a1e297be938 | drewthayer/methods-and-functions | /SignalProcessing/Preprocessing.py | 1,277 | 3.6875 | 4 | import numpy as np
''' functions for pre-processing digital signals '''
def clip_signal_start(signal, index):
return signal[index:]
def clip_signal_both_ends(signal, clip_pcnt=0.05):
clip_length = int(len(signal)*clip_pcnt)
return signal[clip_length: -1*clip_length]
def cutoff_threshold_from_signal_ma... |
448310e4307a91ed2ba7b7755840b621b5f7bddd | chooco/2017sum_wiet_kol2 | /kol2.py | 1,220 | 3.828125 | 4 | # Class diary
#
# Create program for handling lesson scores.
# Use python to handle student (highscool) class scores, and attendance.
# Make it possible to:
# - Get students total average score (average across classes)
# - get students average score in class
# - hold students name and surname
# - Count total attendance... |
7ed946e0cd092c710d2c32fdb0c0a7aafd57f452 | Roboyantriki-SNU/Python_Workshop | /OOP/Inheritance2.py | 556 | 4.03125 | 4 | class Computers:
def processor(self,name):
self.processor_name = name
def memory(self,capacity):
self.memory_capacity = capacity
def showSpecs(self):
print(self.processor_name+" "+self.memory_capacity+" "+self.screen_size) #Even though the base class doesn't have screen size, the der... |
41aad46fa18d56b77474294cbd7bfc1e0713c0ac | sztxr/JetBrains_Projects | /Coffee Machine/Problems/The mean/task.py | 121 | 3.765625 | 4 | numbers = []
x = input()
while x != '.':
numbers.append(int(x))
x = input()
print(sum(numbers) / len(numbers))
|
b1cb1dc20c3f46e9147e84aff2f6e1c37307e567 | Abdulrauf-alhariri/Intermidate_level | /calculator.py | 3,352 | 3.75 | 4 | from tkinter import *
from operator import add, mul, sub, truediv
import string
import math
root = Tk()
root.title("My Calculate")
equation = StringVar()
expression = " "
e = Entry(root, textvariable=equation, width=60, borderwidth=7)
e.grid(row=0, column=0, columnspan=4, pady=15, padx=5)
def button... |
c535dfc204b22ca27597680773e056713fb6ab1f | Iliya-Yeriskin/Learning-Path | /Python/Class_work/L10_Functions/L10.4 No input Yes output.py | 260 | 4.03125 | 4 | def calculating():
num1 = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
sum = num1 * num2
print("Your new number is: " + str(sum))
return sum
a = calculating() + 5
print("Post function number: " + str(a))
|
94d359f111fed2d732ecc9890a2deb5956e751d3 | Iliya-Yeriskin/Learning-Path | /Python/Class_work/L9_While/L9.1.py | 155 | 4.15625 | 4 | #While loops
#while = if+for together
num=int(input("Enter a number: "))
while(num!=7) :
print(num*400)
num = int(input("Enter a number: ")) |
c06217c63dd9a7d955ae6f2545773486d84158b0 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/4.py | 266 | 4.40625 | 4 | '''
4. Write a Python program to accept a filename from the user and print the extension of that.
Sample filename : abc.java
Output : java
'''
file=input("Please enter a file full name: ")
type=file.split(".")
print("Your file type is: " + repr(type[-1]))
|
a65b5ff8cc9f556dcfad4bce1864f3e807579fa5 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/13.py | 173 | 4.0625 | 4 | '''
13. Write a Python program to sum all the items in a list.
'''
my_list=[1,2,3,4,5,6,7]
sum=0
for i in range((len)(my_list)):
sum=sum+my_list[i]
print(sum) |
0d19a4381c7c94180999bc78613aecdf65cf04a0 | Iliya-Yeriskin/Learning-Path | /Python/Projects/Rolling Cubes.py | 2,517 | 4.1875 | 4 | '''
Cube project:
receive an input of player money
every game costs 3₪
every round we will roll 2 cubes,
1.if cubes are the same player wins 100₪
2.if the cubes are the same and both are "6" player wins 1000₪
3.if the cubes different but cube 2 = 2 player wins 40₪
4.if the cubes different but cube 1 = 1 player ... |
aa255b7fcbedd6c9498f6415597c46d7b7196d8f | Iliya-Yeriskin/Learning-Path | /Python/Exercise/End Exercise/5.py | 305 | 4 | 4 | '''
Write a Python program to calculate the sum of three given numbers, if
the values are equal then return three times of their sum.
'''
def summery(a, b, c):
sum = a + b + c
if a == b == c:
sum = sum * 3
return sum
print(summery(1, 2, 3))
print(summery(2, 2, 2))
|
d54a45eb4727576c684d76e643f236d4a2b04c13 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/End Exercise/6.py | 385 | 4.09375 | 4 | '''
Write a Python program to sum of two given integers. However, if the sum
is between 15 to 20 it will return 20.
'''
def summery(x,y):
sum = x + y
if sum in range(15, 20):
sum = 20
return sum
print(summery(3,7))
print(summery(11,7))
print(summery(12,14))
print(summery(11,4))
... |
5736199cbc797c8ae7d2cc6d8fc09da59023d5e2 | Iliya-Yeriskin/Learning-Path | /Python/Exercise/Mid Exercise/10.py | 306 | 4.3125 | 4 | '''
10. Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string.
Sample string : 'Net4U'
Expected output: {'N': 1, 'e': 1, 't': 2, '4': 1, 'U': 1}
'''
word=input("Please enter a word: ")
dict={i:word.count(i) for i in word}
print(dict)
|
22b12e7b0d842a0430852b5213f9b78826971f62 | MHieu128/exercise_python | /Exercise_1.py | 99 | 3.703125 | 4 | a = int(input("input number a: "))
b = int(input("input number b: "))
print(f'{a} ^ {b} = {a**b}')
|
cae8ae844248ac65925e97ee6672de2fa1659607 | isaiah279/kivy_basics | /inputs.py | 319 | 3.921875 | 4 | from tkinter import *
root = Tk()
e = Entry(root, width=50, bg="maroon", fg="white")
e.insert(0,"Enter your name")
e.pack()
# borderwidth=50
def clickme():
name=e.get()
mylabel = Label(root, text=name)
mylabel.pack()
button = Button(text="click me", command=clickme)
button.pack()
root.mainloop()
|
e09832ba59dde120d54dde56fc68560c552bad76 | cleversokol/python_sber | /module1/1_6_9.py | 659 | 3.53125 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
# Реализуйте класс LoggableList, отнаследовав его от классов list и Loggable таким образом,
# чтобы при добавлении элемента в список посредством метода append в лог отправлялось сообщение,
# состоящее из тол... |
deef94120340b3395b95196edc70d6f0562313c1 | cleversokol/python_sber | /module2/2_4_5.py | 841 | 3.5 | 4 | import os
import os.path
import shutil
# Print current directory
print(os.getcwd())
# List all files in current directory
print(os.listdir())
# Check if dir/file exists in FS
# Return True/False respectively
print(os.path.exists("some/destination/here"))
# Check if path if a file/directory
print(os.pat... |
3ae72fce672cdc964b8af5ff038ce969583abfc6 | cleversokol/python_sber | /module3/3_2_12.py | 386 | 3.609375 | 4 | import re
import sys
pattern = re.compile(r'human')
for line in sys.stdin:
line = line.rstrip()
line = re.sub(pattern, "computer", line)
print(line)
#string = "I need to understand the human mind"
#string = "humanity"
#
#if re.search(pattern, string) != None:
# string = re.sub(pattern, "... |
fea00a738c0ad95e10063a78ee6e8ce835849ad3 | cleversokol/python_sber | /module1/1_4_9.py | 1,662 | 3.875 | 4 | # namespaces is dict of pairs namespace:parent
namespaces = {}
# variables is dict of pairs namespace:[list of variables]
variables = {"global":[]}
def create(namespace, parent):
namespaces.update({namespace:parent})
variables.update({namespace:[]})
def add (namespace, var):
variables[namespace]... |
7261b319e11b125b64d3e2bcff780e1337a0921f | cleversokol/python_sber | /module2/2_3_5.py | 361 | 3.796875 | 4 | import itertools
def primes():
number = 1
while True:
divisors = 0
number += 1
for i in range(1, number+1):
if number % i == 0:
divisors += 1
if divisors < 3 :
yield number
print(list(itertools.takewhile(lambda x : x <= 31, primes())))
# ... |
a01b945ef2c4ec1391b0bdf315a0413f84cbcf41 | Alemani29/CBT | /CBT.py | 11,771 | 3.65625 | 4 | #Import files
import intro
import time
import random
import pygame
from pygame.locals import *
#Pinya Colada Song
pygame.mixer.init()
#Variables
pinya = 0
pinyapelada = 0
poma = 0
money = 0
ganivet = 0
ganivetma = 0
zona = 1
CBT = False
Barra = False
#Zones
# ?.CBT
# 0.End
# 1.Bosc
# 2.Ciu... |
621a2421b18dad2c135788e201de171493a79fe0 | Typical-dev/C-97-Python-project | /NumberGuessingGame.py | 986 | 4.03125 | 4 | Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
============================================================================================================== RESTART: Shell ==================... |
8146be5d85020e6b965d2c4caf1991678677e410 | Balgeum-Cha/vscode | /class.py | 796 | 4.3125 | 4 | #%%
a = [1,2,3,4,]
a.append(5)
print(a)
# %%
def test():
pass
class Person:
pass
bob = Person()
cathy = Person()
a = list()
b = list()
# %%
# 생성자
class Person:
def __init__(self):
print(self,'is generated')
self.name = 'Kate'
self.age = 10
p1 = Person()
p2 = Person()
p1.name = '... |
e7f74aeb6375b5d5b847552a649091aee4ed8115 | ICTSoEasy/Write-Your-Own-Adventure-Games | /Files/Week 2/main2.py | 515 | 4 | 4 | #import the classes we have written
from GAME import Game
from ROOM import Room
#Create (instantiate) an instance of Game, called game
game = Game()
#Create a room (we used room 1 for an example, and it currently does not
# contain anything)
room = Room(1,'Starboard Bows',None,None)
#Add the room to the game
print('... |
eb5a3d9e105deeb1f742198a6c5ec21ce44ee6c7 | theawesomestuff/codingchallenge | /glasses.py | 1,880 | 3.625 | 4 | class TriangularGlassStack:
"""
A triangular stack of glasses, where you can pour liquid on the glasses
"""
def __init__(self):
self.glass_capacity = 250 # glass capacity in ml
self.rows = [] # Contains glass capacity of each glasses in each row
def add_liquid(self, amount):
... |
a55b30511787064e1c9b85619116d9fa3b08c681 | songkunhuang/Python_Learn | /dowhile.py | 557 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 7 15:43:36 2017
@author: Song
"""
"""
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nThank you! "
message = input(prompt)
print(message)
"""
"""
current_number = 1
while current_number <= 5:
print(current_number)
current_num... |
dbcbe5ef4c2d402da10aef85537a82acc36cd167 | season101/Math4009-Project_1 | /Question4_Handled.py | 545 | 3.78125 | 4 | from ciphertext import cipher;
import string;
#To count chars and its count
inputChars = []
for each in cipher:
inputChars.append(chr(each+65))
#print(len(inputChars))
'''
for j in range(65,91):
print(str(chr(j))+" : "+str(inputChars.count(chr(j))))
'''
inputChars = str(inputChars)
#print(inputChars)
#onl... |
9d6ab0f6e472bbfac8acb5c367c144a266a22ecb | tanaychaulinsec/AlgorithmsAndDataStructure | /Python/DataStructure/TreeDS/levelOrderTreeTravarsal.py | 686 | 4.0625 | 4 | #Title:-Level Order Traversal
#Author : Tanay Chauli
import queue
class newNode:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
self.next=None
def LevelOrder(root):
q=[root]
res=[]
while q:
n=q.pop(0)
res.append(n.val)
if n.le... |
fab1c90fdd937fae97c1259d241395c2ec8d0d80 | zykt/pyglet_game_of_life | /main.py | 2,699 | 3.71875 | 4 | import pyglet
from board import Board
class Cell:
DEAD = 0
ALIVE = 1
def neighbors(board: Board, x: int, y: int) -> int:
"""Count neighbors of x, y on board"""
n = 0
def border_check(x_, y_):
"""Helper for determining whether given x_ and y_ are valid"""
return 0 <= x_ < board.w... |
03a72365c3d05751de58a9e973736dd925ea6bb2 | Stefan1502/Practice-Python | /exercise 13.py | 684 | 4.5 | 4 | #Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
#Take this opportunity to think about how you can use functions.
#Make sure to ask the user to enter the number of numbers in the sequence to generate.
#(Hint: The Fibonnaci seqence is a sequence of numbers where the n... |
252901028a8feadeb4070b57ff330d2c2751757c | Stefan1502/Practice-Python | /exercise 9.py | 894 | 4.21875 | 4 | #Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
#(Hint: remember to use the user input lessons from the very first exercise)
#Extras: Keep the game going until the user types “exit” Keep track of h... |
b831314d05f1b2a996e687d3f43f046ef46eab0d | Stefan1502/Practice-Python | /exercise 28.py | 421 | 4.375 | 4 | # Implement a function that takes as input three variables, and returns the largest of the three.
# Do this without using the Python max() function!
# The goal of this exercise is to think about some internals that Python normally takes care of for us.
# All you need is some variables and if statements!
... |
22de4e1e29760b9cde35221ced9f35d2a2f5954b | Stefan1502/Practice-Python | /exercise 11.py | 474 | 4.0625 | 4 | #Ask the user for a number and determine whether the number is prime or not.
#(For those who have forgotten, a prime number is a number that has no divisors.).
#SOLUTION BELLOW
def prim(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
print("not a pri... |
1fee179b3526076819536510e1626cbc9a5bd991 | rishitc/Codechef_Hacktoberfest-2021 | /Codechef-2019/FEB19B/PRDRG.py | 562 | 3.71875 | 4 | from fractions import Fraction
A = list(map(int, input().split()))
T = A[0]
list_1 = A[1:]
my_list = []
for i in range(T):
p = list_1[i]
if p == 1 or p == 2:
val = ((1/2)**(list_1[i]))
value = int(1/val)
my_list.append(1)
my_list.append(value)
else:
mean = [1/2, 1/4]
... |
b01731d3d25bf551e82deaeb445bcfbc3191ee16 | DaphneKouts/NCWIT | /TicTacToe_Skeleton.py | 5,412 | 4.125 | 4 | '''
Created on March 15, 2017
@author: KJHolmes
'''
## This function takes in the list and prints the tictactoe board
# board: the list that represents the tictactoe board
def print_TTT(board):
print('''__''' + board[0][0] + '''___l___''' + board[0][1] + '''___l___''' + board[0][2] + '''__
... |
e6cf6be5dd4d4809c90088f965290fcb6a4dc8b1 | DaphneKouts/NCWIT | /Branching and output corrections.py | 515 | 4.09375 | 4 | def letter_in_word(guess,word):
'''Returns true if guess is one of the letters in the word.
Otherwise, it returns false'''
if guess in word:
print(True)
else:
print(False)
def hint(color,secret):
'''Returns whether or not the color is in the secret''... |
1a2daaf3670f34d0b145132e69d0aad2b2b1ba75 | TroyJeffrey/Inventory-Control-System | /stack.py | 247 | 3.515625 | 4 | # Troy Jeffrey Amegashie
# Stack
# 03/05/2020
from LinkedLists import LinkedList
class Stack:
def __init__(self):
self.mystack = []
def push(self,data):
self.mystack.append(data)
def pop(self):
return self.mystack.pop()
|
d0fdd8537fc6e96de145f6c409cc166699a51ee1 | ericrommel/codenation_python_web | /Week01/Chapter04/Exercises/ex_4-10.py | 1,171 | 4.34375 | 4 | # Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right
# by 144, put the pen down, and draw the next star. You’ll get something like this:
#
# _images/five_stars.png
#
# What would it look like if you didn’t pick up the pen?
import turtle
def make_wind... |
7fcd55b167623ad4139ebe7d9eab75f958c78fb2 | ericrommel/codenation_python_web | /Week01/Chapter04/Exercises/ex_4-09.py | 694 | 4.53125 | 5 | # Write a void function to draw a star, where the length of each side is 100 units. (Hint: You should turn the turtle
# by 144 degrees at each point.)
#
# _images/star.png
import turtle
def make_window(color="lightgreen", title="Exercise"):
win = turtle.Screen()
win.bgcolor(color)
win.title(title)
... |
f4aeba34d229b94abb230c2d9607b8f39570fede | ericrommel/codenation_python_web | /Week01/Chapter03/Exercises/ex_3-06.py | 871 | 4.3125 | 4 | # Use for loops to make a turtle draw these regular polygons (regular means all sides the same lengths, all angles the same):
# An equilateral triangle
# A square
# A hexagon (six sides)
# An octagon (eight sides)
import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Exercise 6")
tria... |
80628bffd69f711dba4887a74db2c7b005dd0e19 | ericrommel/codenation_python_web | /Week01/Chapter03/herd_of_turtles.py | 762 | 3.90625 | 4 | import turtle
# bg_color = input("Write a background color for the window: ")
wn = turtle.Screen()
wn.bgcolor("lightgreen")
wn.title("Tess and Alex")
# turtle_color = input("Write a color for the turtle: ")
# pen_size = int(input("Write a size for the turtle: "))
tess = turtle.Turtle()
tess.color("hotpink")
tess.pensi... |
e6066fc636848204cd6d5740a5a78fc23b6d4637 | ifryed/navigation_algo | /Exercises/ex1_histogram_filter/main.py | 442 | 3.640625 | 4 | ##
# Main function of the Python program.
#
##
from histogram import *
def main():
Map = [['G', 'G', 'G'],
['G', 'R', 'R'],
['G', 'G', 'G']]
measurements = ['R','R']
motions = [[0,0],[0,1]]
sensor_right = .8
p_move = 1.0
ans = histogram_localization(Map, measurements, moti... |
10440f62b0dfacf1baba831661d59c401218eb5a | emeceerre/m02_keep_0 | /p1.py | 277 | 3.515625 | 4 | def sumatodos(limitTo):
resultado = 0
for i in range(0, limitTo+1):
resultado += i
return resultado
def sumatodosLosCuadrados(limitTo):
resultado = 0
for i in range(limitTo+1):
resultado += i*i
return resultado
print(sumaTodos(100))
print(sumatodosLosCuadrados(3))
|
9d2b810bfc5d1efe9139c383f786ad7b15686067 | cpm02/python-gui-with-data-base | /book_front.py | 2,369 | 3.6875 | 4 | from tkinter import *
from PIL import ImageTk,Image
import sqlite3
root=Tk()
root.geometry("1000x1000")
canvas=Canvas(root,width=1000,height=1000)
image =ImageTk.PhotoImage(Image.open('lib.jpg'))
canvas.create_image(0,0,anchor=NW,image=image )
canvas.pack()
#_________________database_____________________
text1=StringV... |
89d6b8bf63e9a6aa50b9063ee02acdd8d6153c9f | ohassa/code-eval | /p082.py | 177 | 3.53125 | 4 | import sys
for n in [line.rstrip() for line in open(sys.argv[1])]:
digitSum = 0
numDigits = len(n)
for i in n:
digitSum += int(i) ** numDigits
print(str(digitSum) == n) |
5f277302bc8e52e87c9e9701159aa14ea96f28df | ohassa/code-eval | /p139.py | 2,800 | 3.5625 | 4 | import sys
MONTH_NAME_TO_NUMBER_MAP = {
'Jan': '01',
'Feb': '02',
'Mar': '03',
'Apr': '04',
'May': '05',
'Jun': '06',
'Jul': '07',
'Aug': '08',
'Sep': '09',
'Oct': '10',
'Nov': '11',
'Dec': '12'
}
def dateDiff(date1String, date2String):
'''
Parameters
----------
date1String:str
Date in format "YYY... |
35da7c155a1d54f1e941e58340e43121a898e006 | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe16.py | 1,294 | 4.40625 | 4 | """Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá
pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
- Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não dev... |
4c938991598211f2149d3628ac7caf1d8d9cd2bd | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe26.py | 1,212 | 4.03125 | 4 | """Um posto está vendendo combustíveis com a seguinte tabela de descontos:
Álcool:
até 20 litros, desconto de 3% por litro
acima de 20 litros, desconto de 5% por litro
Gasolina:
até 20 litros, desconto de 4% por litro
acima de 20 litros, desconto de 6% por litro
Escreva um algoritmo que leia o número de litros vendidos... |
5760b3a9d3a22ff5c9fd0065db155cf87d873abf | Elton86/ExerciciosPython | /ExerciciosListas/Exe13.py | 618 | 4.1875 | 4 | """Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Após isto, calcule
a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram
(mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . )."""
mes = []
media = 0
fo... |
b1a8fc48cef00b4dc443de2f2292e46576bd5e45 | Elton86/ExerciciosPython | /EstruturaDeRepeticao/Exe14.py | 370 | 3.953125 | 4 | """Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de
números impares."""
par = impar = 0
for i in range(10):
num = int(input("Digite um numero: "))
if num % 2 == 0:
par += 1
else:
impar += 1
print("Total de pares: {}".format(par))... |
bc7321cb0a9bb06e00df001975f0772fcfeb13be | Elton86/ExerciciosPython | /ExerciciosListas/Exe15.py | 1,511 | 4.125 | 4 | """Faça um programa que leia um número indeterminado de valores, correspondentes a notas, encerrando a entrada de
dados quando for informado um valor igual a -1 (que não deve ser armazenado). Após esta entrada de dados, faça:
Mostre a quantidade de valores que foram lidos;
Exiba todos os valores na ordem em que foram i... |
0cf837e2723157e30c5708ce5a867ebb8c1c3fea | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe18.py | 591 | 4.0625 | 4 | """Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida."""
data = str(input("Digite a data: "))
if len(data) != 10:
print("Data invalida!")
exit()
data_dia = int(data[0:2])
data_mes = int(data[3:5])
data_ano = int(data[6:10])
# Depois validar corretamente de aco... |
5de87c8f9022f227208214470e78d6cb200dff8a | Elton86/ExerciciosPython | /ExerciciosComStrings/Exe04.py | 281 | 4.25 | 4 | """Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada.
F
FU
FUL
FULA
FULAN
FULANO"""
nome = input("Digite o nome: ")
for i in range(1, len(nome) + 1):
for j in range(0, i):
print(nome[j], end=" ")
print(" ")
|
9f35127cd417cd6d1e90e3387b2f01887f950a5f | Elton86/ExerciciosPython | /EstruturaDeRepeticao/Exe24.py | 288 | 4.09375 | 4 | """Faça um programa que calcule o mostre a média aritmética de N notas."""
soma = cont = 0
while True:
nota = float(input("Digite a nota: [-1 para sair] "))
if nota == -1:
break
else:
soma += nota
cont += 1
print("Media = {}".format(soma / cont))
|
81dab0084e763e0a4c367fe3ab139f69faf82c26 | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe17.py | 328 | 3.96875 | 4 | """Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe se
este ano é ou não bissexto."""
ano = int(input("Digite o ano: "))
if (ano % 4 == 0 or ano % 400 == 0) and ano % 100 != 0:
print("{} eh ano bissexto!".format(ano))
else:
print("{} Nao eh ano bissexto!".format(ano... |
5f8d04547f72564b308b9645c73f192b12a4c2b1 | Elton86/ExerciciosPython | /ExerciciosFuncoes/Exe09.py | 236 | 4.3125 | 4 | """Reverso do número. Faça uma função que retorne o reverso de um número inteiro informado. Por exemplo: 127 -> 721.
"""
def inverte_num(num):
return num[::-1]
numero = input("Digite o numero: ")
print(inverte_num(numero))
|
42c303f65b898acf24cfba091cae42212ff6d355 | Elton86/ExerciciosPython | /ExerciciosListas/Exe17.py | 1,222 | 3.984375 | 4 | """Em uma competição de salto em distância cada atleta tem direito a cinco saltos. O resultado do atleta será
determinado pela média dos cinco valores restantes. Você deve fazer um programa que receba o nome e as cinco
distâncias alcançadas pelo atleta em seus saltos e depois informe o nome, os saltos e a média dos sal... |
09ba9986b624fd74ed77eeec11c5c2272e4ce74b | Elton86/ExerciciosPython | /ExerciciosListas/Exe06.py | 635 | 3.90625 | 4 | """Faça um Programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno,
imprima o número de alunos com média maior ou igual a 7.0."""
notas_medias = []
for i in range(10):
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
... |
a162b0d81c04f48b892668b25d8a7c86307d12ef | Elton86/ExerciciosPython | /EstruturaDeDecisao/Exe13.py | 693 | 4.03125 | 4 | """Faça um Programa que leia um número e exiba o dia correspondente da semana.
(1-Domingo, 2- Segunda, etc.), se digitar outro valor deve aparecer valor inválido."""
numero = int(input("Digite um numero de 1 a 7: "))
if numero == 1:
print("{} - Domingo.".format(numero))
elif numero == 2:
print("{} - Segunda."... |
1a668b82b4ff825596621fcc92cd01a82bdba461 | Elton86/ExerciciosPython | /ExerciciosListas/Exe10.py | 627 | 4.0625 | 4 | """Faça um Programa que leia dois vetores com 10 elementos cada. Gere um terceiro vetor de 20 elementos,
cujos valores deverão ser compostos pelos elementos intercalados dos dois outros vetores."""
vetor_intercalado = []
vetor1 = []
vetor2 = []
for i in range(10):
vetor1.append(input("Digite o elemento para o vet... |
d28b390190aaabc5337d48153e746f12a78ebe77 | reacktor/RTR105 | /dgr_20181105.py | 1,980 | 3.734375 | 4 | Python 3.6.5 (default, Apr 1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "copyright", "credits" or "license()" for more information.
>>> str1 = "Hello"
>>> str2 = 'there'
>>> bob = str1 + str2
>>> print(bob)
Hellothere
>>> str3 = '123'
>>> str3 = str3 + 1
Traceback (most recent call last):
File "<pyshell#5>", line 1,... |
7b9c08b5275f6cb606e9b3367baf9a9abf1daf4d | austinszeng/qna-study | /qna_study.py | 3,470 | 3.828125 | 4 | import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def press_enter():
enter_key = input('(Press enter to continue...)')
# wrong_key = True
# while wrong_key:
# enter_key = input('(Press enter to continue...)')
# if enter_key == '':
# wrong_k... |
a09141fca6646cbfa9626d147119189ab7b216d7 | aspineonxyz/Hackerrank-Challenge | /Python/Regex and Parsing/Hex Color Code Working Copy.py | 2,267 | 3.734375 | 4 | """CSS colors are defined using a hexadecimal (HEX) notation for the combination of Red, Green, and Blue color values (RGB).
Specifications of HEX Color Code
■ It must start with a '#' symbol.
■ It can have 3 or 6 digits.
■ Each digit is in the range of 0 to .F (1,2,3,4,5,6,7,8,9,0,A,B,C,D,E and F).
■ A-F lett... |
19b73d3ae56b3e0d25bdf866ee26c4e815ad07de | francis2001tw/BasicPython | /SourceCode/02_Flow Control/02_Loop/continue.py | 211 | 3.8125 | 4 | # continue
myString = 'My name is Frank'
index = -1
while index < 16:
index = index + 1
if index % 2 == 0:
# [POINT 1]
continue
else:
print(myString[index] + '-', end='')
|
4cf139f3855d30f7ddad5c38fbb27b84809a24cc | francis2001tw/BasicPython | /SourceCode/01_Basic Concepts/08_String/concatenation.py | 269 | 3.90625 | 4 | # concatenation
# [POINT 1]
string1 = 'My '
string2 = 'name '
string3 = 'is '
string4 = 'Frank'
print(string1+string2+string3+string4)
# [POINT 2]
string4 = '{0} + {1} = {2}'.format('2', '3', '5')
string5 = '%s + %s = %s' % (2, 3, 5)
print(string4)
print(string5)
|
945786723aac202753c4584e2c6500e0f33f584b | francis2001tw/BasicPython | /SourceCode/02_Flow Control/02_Loop/while.py | 149 | 3.625 | 4 | # while loop
myString = 'My name is Frank'
index = 0
# [POINT 1]
while index < 16:
print(myString[index] + '-', end='')
index = index + 1
|
67185cd525c4eb67b4223a5c8d2eb6cf0ec4d8aa | francis2001tw/BasicPython | /SourceCode/03_Data Structure/01_List/comprehension.py | 372 | 3.734375 | 4 | # comprehension
data1 = list()
for num in range(0, 10):
if num % 2 == 0:
data1.append(num)
print(data1)
# [POINT 1]
data2 = [num for num in range(0, 10) if num % 2 == 0]
print(data2)
# [POINT 2]
pairs2D = [(x, y) for x in range(2) for y in range(2)]
print(pairs2D)
pairs3D = [(x, y, z) for x in range(2) ... |
89b5918192fae2cf42cfb4afcf92b345a7ed7c42 | francis2001tw/BasicPython | /SourceCode/02_Flow Control/01_Conditional/euqal.py | 92 | 3.53125 | 4 | # equal Conditional
a = float(100)
b = float(100)
# [POINT 1]
print(a is b)
print(a == b)
|
024fb158327c3a10094ba2cc1010abdccf3b6638 | calliope-pro/Matplotlib_ | /基本_描画.py | 557 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# シード固定
np.random.seed(0)
# 変数x・y
x = np.linspace(0, 1, 10)
y = 2 * x + 0.1 * np.random.randn(10)
print(y)
# 折れ線(テンプレ)
# plt.figure(figsize=(10, 7)) # figsize=(width, height)
# plt.plot(x, y)
# plt.show()
# 折れ線(汎用)
fig = plt.figure() # グラフ領域の... |
0b7126b33d6e297c905dd98c63bedb1b15c435e9 | fwar34/DataStruct | /mine/circlequeue/queue.py | 1,902 | 3.765625 | 4 | import logging
class QError(BaseException):
def __init__(self, value, message):
self.value = value
self.message = message
def __str__(self):
# return repr(self.message)
return self.message
class Queue:
def __init__(self, capacity):
self.queue = []
... |
141e4194e10e9004093dfa2fb3ba21ce31746d13 | mwnuk/PythonCode | /Pycharm_Syntax/StringsNum.py | 3,351 | 4.34375 | 4 | # These are called modules
import random
import sys
import os
# Hello world is just one line of code
# print() outputs data to the screen
print("Hello World")
'''
This is a multi-line comment
'''
# A variable is a place to store values
# Its name is like a label for that value
name = "Derek"
print(name)
# A variabl... |
e9ad53744bce611675534a83e93cb475b07b2d62 | AlexWanyoike/Password_PythonIP | /user.py | 1,353 | 3.796875 | 4 | import pyperclip
import random, string
class User:
'''
Create a new User with both Username and Password
'''
user_list = []
@classmethod
def __init__(self, user_name, password):
self.user_name = user_name
self.password = password
def save_user(self):
'''
... |
d2a04ec1a49d26a0a15361524a226e918a8435f5 | arabindamahato/personal_python_program | /programming_class_akshaysir/eliminate_last_digit.py | 153 | 4.03125 | 4 | print('To eliminate the last digit of any number')
n=int(input('Enter your no : '))
o=n//10
print('After eliminating last digit of {} is {}'.format(n,o)) |
5326bd592b7cdaa500d1f5809ffed190de7b6257 | arabindamahato/personal_python_program | /class_object/atm_issue.py | 627 | 3.78125 | 4 | class Bank:
bank_name = 'Bank of Boroda'
ifsc_code = 'BARBAMUND'
def __init__(self, name, age, ph_no, atm = False):
self.name = name
self.age = age
self.ph_no = ph_no
self.atm = atm
def atminfo(self):
if self.atm == True:
print('Atm already iss... |
1661637a1221678a1a6bd61dce3336ff7ca569c1 | arabindamahato/personal_python_program | /inheritance/has-a_relationship.py | 298 | 3.953125 | 4 | ''' example of has-a relationship'''
class A:
def m1(self):
print('def m1')
class B(A):
oa=A() #object created in child class
def m2(self):
print('def m2')
ob=B() # creating object for object B
ob.m2()
ob.oa.m1() # calling m1() function from object A inside object B
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.