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
d57eddb31742854d91e57b48800436c98516e30f
scgagliardi2/Battleship-Game
/Player.py
3,594
3.875
4
import random import Ship import Board class Player: def __init__(self, player_type): self.ships_left = 5 self.carrier = Ship.Ship(5, "carrier", "A1", "A1") self.battleship = Ship.Ship(4, "battleship", "A1", "A1") self.cruiser = Ship.Ship(3, "cruiser", "A1", "A1") ...
36989a127acfbc6f1e53258bab42ff9578c82dfd
UliRoman0901/Programas-Python
/Ejercicio7.py
607
3.765625
4
# -*- coding: cp1252 -*- print ("-----programa 7- permita generar un intervalo de los cuadrados de n nmeros mayores a 100.--") print ("........................................................................") inicio=input("ingrese el inicio del intervalo") final=input("ingrese el final del intervalo") suma =0.0 final...
4f247571b9e29902cdfab301b0b2039e6c0e3d3b
lebronjames2008/python-invent
/w3schools/Scopes.py
799
4.375
4
# A variable is only available from inside the region it is created. This is called scope. def myfunc(): x = 300 print(x) myfunc() # A variable created inside a function is available inside that function x = 300 def myfunc(): print(x) myfunc() print(x) # Printing 2 300's x = 300 def myfunc(): x = 200 p...
469cf9247ced31818e7060426dfb7f1f67d91ad6
lebronjames2008/python-invent
/w3schools/Inheritance.py
1,945
4.34375
4
class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) # Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() #Use the pass keyword when...
a5a700f7fa77777ea9a3c65669d67f0fd4313dd0
lebronjames2008/python-invent
/chapter9/testlist1.py
706
4.34375
4
names_list = ['sibi', 'rahul', 'santha', 'scott', 'james'] # print all the elements in the list print(names_list) # print the 4th index of the list print(names_list[4]) print(names_list[-5]) thislist = ["apple", "banana", "cherry"] print(thislist) thislist[1] = "blackcurrant" print(thislist) thislist = ["apple", ...
6c28e3eabc7c92e4a90c5e87496fd80d4128a854
elioti/algo
/lcs.py
706
3.9375
4
# 718. Maximum Length of Repeated Subarray """ Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3, 2, 1]. """ def findLength(A, B): len_a = len(A) struct = [0 for _ in range(len_a + 1)] ans = 0 for b in B: tmp = 0 for index, a in...
7da6111a2ac0a3d281c0e615e69683aebcf6cae2
AlbertoLG1992/AprendiendoPython
/Ejemplos/3-TiposDeDatosNumericos/TipoDatosBooleanos.py
622
4.25
4
# Los operadores booleanos son: # or : || # and : && # not : para negar x = True y = False if(x and not y): print("ok") else: print("no") # Para comparar listas tenemos all y any # all(iterador) : Recibe un iterador, por ejemplo una lista, # y devuelve True si todos los elementos son verdaderos o el iterador e...
27e08ae25f106d0179bff869f02855717cd417dd
AlbertoLG1992/AprendiendoPython
/Ejemplos/5-TipoDatosSecuencia/Listas.py
1,152
4.4375
4
# Las listas ( list ) me permiten guardar un conjunto de datos que se pueden repetir y # que pueden ser de distintos tipos. Es un tipo mutable. ''' SLICE Para optener un rango dentro de una lista: lista[start:end] # Elementos desde la posición start hasta end-1 lista[start:] # Elementos desde la posición start hasta ...
dc947236c9227d85edfe5aa34984748a4ac94e0f
nshruti/python
/python_useful_snippets.py
3,852
3.796875
4
# string library to generate lowercase alphabets import string alpha= list(string.ascii_lowercase)[:10] #get list of alphabets print alpha #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] #zip example numbers= range(10) print numbers #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print zip(numbers,alpha) #[(0, 'a'), (1, '...
d92884536945b36a185358c5293ccd9311e3425d
royredman4/Chess_Game
/GUI.py
1,491
3.703125
4
#!/usr/bin/python try: # for Python2 from Tkinter import * except ImportError: # for Python3 from tkinter import * import Game_Initialization as GI import Chess_Movement as CM class ChessGame(Tk): def __init__(self): Tk.__init__(self) self.canvas = Canvas(self, width=480, height...
90f83c56954abd61760166c35ca85bc93d8cd809
Bogdanp/cursive_re
/cursive_re/exprs.py
7,257
3.859375
4
import re from typing import Optional, Pattern, Union def compile(expr: "expr", flags: int = 0) -> Pattern[str]: """Compile a cursive_re expression to a real regular expression. """ return re.compile(str(expr), flags) class expr: def __add__(self, other: "expr") -> "expr": return sequence(se...
65972867d97610a49056125e8b9a530bf81ed873
majdalkilany/pythonic-garage-band
/pythonic_garage_band/pythonic_garage.py
3,619
4.125
4
from abc import abstractclassmethod class Musician(): members= [] def __init__(self, name): self.name=name Musician.members.append(self) @abstractclassmethod def __str__(self) : ''' this str method from super class to make every sub class have str method ''' ...
a36976e9fa2420e2a4c39f231231935777c11b31
buingocquang/linux
/hamtinhtong.py
101
3.640625
4
#ham def tong(a,b): return a+b #main a = input('a = ') b = input('b = ') print 'tong = ',tong(a,b)
2d7836ec5329101e5c6a379915f84174866430bb
cheddalu/py4e
/2-4.py
265
3.890625
4
# assign the 2 variables, 1 int and 1 float value width = 17 height = 12.0 # width//2 # width/2.0 # height/3 # 1 + 2 * 5 print('width//2') print(width//2) print('width/2.0') print(width/2.0) print('height/3') print(height/3) print('1 + 2 * 5') print(1 + 2 * 5)
35ed87d3cae750904cd33a5d53765a0f3a04f7a0
cheddalu/py4e
/13_1.py
951
4.03125
4
"""Exercise 1: Change the socket program socket1.py to: - Prompt the user for the URL so it can read any web page. - Use split('/') to break the URL into its component parts so you can extract the host name for the socket connect call. - Use try and except to handle the condition where the user enters an impro...
0ad4d3eee4cf6c52b56d891dbd46fa4d85d3d471
sloria/TextBlob
/textblob/utils.py
1,526
3.875
4
# -*- coding: utf-8 -*- import re import string PUNCTUATION_REGEX = re.compile('[{0}]'.format(re.escape(string.punctuation))) def strip_punc(s, all=False): """Removes punctuation from a string. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ...
df2cb2e24205614c52aad47c9eaa42738f73bb57
Danil-python-it/-
/datatime/finction.py
1,954
3.90625
4
import json from datetime import * weeked = ["Понедельник","Вторник","Среда","Четверг","Пятница","Суббота","Воскресенье"] def woring(): NAME = input("введите название вещи что выходит\n") DAY = input("назовите день недели выхода(с большой буквы)\n") information[NAME] = DAY class data_qith(): ...
e5770486424392a17d0564d6b180edab51f16e42
pitikdmitry/hackerrank
/20.py
463
3.703125
4
# create array of common elements from array1 and array2 def same_elements(arr_1: [], arr_2: []) -> []: i, j = 0, 0 res = [] while i < len(arr_1) and j < len(arr_2): if arr_1[i] == arr_2[j]: res.append(arr_1[i]) i += 1 j += 1 elif arr_1[i] > arr_2[j]: ...
325877934bb99da8beb019883e56d00d018a08fb
pitikdmitry/hackerrank
/7.py
550
3.546875
4
class Solution: def canJump(self, nums) -> bool: """ :type nums: List[int] :rtype: bool """ res = self.jump(nums, 0) return res def jump(self, nums, index) -> bool: if index == len(nums) - 1: return True dist = nums[index] end...
263cfbc218516cca6443a0cff3061890422e55be
pochong/AutomaticCatLitterBox
/main_test.py
1,147
3.6875
4
# main_test # This is testing whether the state machine works as intended by # getting user inputs to substitute sensor input from state_machine import StateMachine from func_timeout import * import time states = StateMachine() timer = time.time() #used for substituting the time waiting part of the state machine def...
6305ae50e19a866384f085317d012bc6bc13cfc6
fionchen/learn-in-day1
/3.py
471
3.75
4
import turtle def draw_i(t, size): for i in range(5): t.forward(size) t.left(144) wn = turtle.Screen() wn.bgcolor("lightgreen") john = turtle.Turtle() john.color("pink") john.pensize(5) for i in range(5): draw_i(john, 50) john.penup() jo...
90db62e82ca3bc7adf925514ddf880196759d3ab
icottambbc/roman-to-arabic-py
/index.py
2,600
3.859375
4
translation = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } def sumTheAras(listOfArabics): theSum = 0 for arabic in listOfArabics: theSum = theSum + arabic return theSum # this is a bit weird but stay with me on this one... # we loop through all the arabic numbers backwa...
2a0f11ce77ceb78d63da31a6c85db8631fda0813
Blakimy/poei-python
/semaine_python/script.py
620
3.765625
4
#!/usr/bin/python3 def exo6(): response = int(input("Please enter your number: ")) while response < 10 and response < 20: print("ok") if response < 10: print("« Plus petit ! »") elif response > 20: print("« Plus grand ! »") #exo6() def exo10(): age = int(...
cbab2163ede805fc33bc5471d2738af3373265af
adit-sinha/Practice-Problems-2
/(5) Autocorrect System/(5) Autocorrect System.py
1,552
3.921875
4
#Autocorrect System word = input("Enter sentence: ") word = word.upper() #converting the sentence to uppercase for term in word.split(): if term.isalpha() == True: #for terms with only words file = open(f'{term[0]}.txt','r') for aw in file: if aw.strip() == t...
1359017dbe59463981a02293ed557dfe49501c8b
HongBeenKim/pams-skku
/thinkingo/parabola.py
599
3.671875
4
class Parabola: # y = a0 + a1 * x + a2 * x^2 def __init__(self, a0, a1, a2): self.a0 = a0 self.a1 = a1 self.a2 = a2 # 곡률 구하는 함수 def get_curvature(self, x): curvature = 2 * self.a2 / pow((1 + (self.a1 + 2 * self.a2 * x) ** 2), 1.5) return curvature # 기울기 구하는 ...
0d5711cc2d542d4770db0f7b5691a174e3c50657
tbarbazon/CS0ClassFiles
/HangmanFinished.py
4,084
3.6875
4
def wrapper(): import random wordList = [] lettersGuessed = [] strikes = [] art = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ ...
c59b4f35f19647e537c28c83044fff3a7f47c877
vlad-zankevich/LearningPython
/cities_1.py
411
4.03125
4
def run(): # example of construction with the loop while and command break prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " while True: city = input(prompt) if city == 'quit': break else: ...
71039d8b5847e341112b2194918eebe219589a40
vlad-zankevich/LearningPython
/album.py
1,222
4.1875
4
def run(): # Theme with function def make_album(singer_name, album_name, track_number=''): """This function will make the dictionary with your album""" # Album dictionary, empty in default album = {} # You can enter quantity of tracks in album if you want if track_numb...
c1d10ebacb914b6f75e63e2ee6c0a7c2ffcf213a
vlad-zankevich/LearningPython
/Lists/foods.py
591
3.96875
4
def run(): # module with examples of lists food_list = [ 'pizza', 'frighten eggs', 'ice cream', 'bananas', 'vegetables', 'fruits', 'milk', 'meat', 'hamburger', 'beans', 'tea' ] print("The first three items in the list are:") for food in food_list[:3]: print(food...
481f2dfd1d578a8733a23b63acf3f2966fd1b021
vlad-zankevich/LearningPython
/favorite_languages_2.py
1,323
3.796875
4
# construction that contains dictionary and method keys() def run(): favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby'], 'phil': ['python', 'haskell'] } for name, languages in favorite_languages.items(): if len(languages) > 1: ...
a900892c18dfd7679221269c3a7d8cfe3a1586a7
mblahay/blahay_standard_library
/regexp_tools.py
1,129
4.25
4
import re import itertools import blahay_standard_library as bsl def regexp_like(args, argp): ''' A simple wrapper around the re.search function. The result of that function will be converted to a binary True/False. This function will return a simple True or False, no match object. Parameters...
0d8a5cc4ee877b1fc5b471ce108bf1da4e1bcd5f
TaylorBelk1/Intro-Python-II
/src/item.py
1,615
3.546875
4
class Item: def __init__(self, name, description): self.name = name self.description = description def __str__(self): output = f'You have found {self.name}. \n' output += f'{self.description} \n' return output def inspect(self): output = f'{self.name} Attrib...
4fd0ff2099b8290f3909392dcaf0e72eb9d579eb
nithish2000/OSproject
/ucb.py
3,951
3.5625
4
from math import sqrt,log,floor import numpy as np import os class Priority_Agent(): def __init__(self): """ This function initialises all the class attributes. The reward and punishment for this model are by default 0.2 and 0.2 respectively """ self.item_count = 0 ...
75535af1646f516da2ce9d36173270adb30e7d98
anmouls/Wikipedia_InfoRetrieval
/Run.py
4,805
3.546875
4
import nltk #package used to extract tokens from the documents import os,io,glob #used to load all the text documents in the corpus and read them from nltk.corpus import stopwords #used to import the list of stopwords to be excluded from the dictionary import math #perform log operations from PorterStem import Port...
6d3b817e2787baa783ef68b138ab8da1dd14193b
zhangxc11/cvbase
/cvbase/format.py
337
3.765625
4
def int_list(in_list): """Convert a list of items to a list of int""" return list(map(int, in_list)) def float_list(in_list): """Convert a list of items to a list of float""" return list(map(float, in_list)) def str_list(in_list): """Convert a list of items to a list of str""" return list(ma...
71cf1ab3ed0e45183ae8c6021eb5f70188c83ab4
dalanmiller/Dungeon-Raider
/functions.py
2,450
3.96875
4
"""Functions for the game Dungeon Raider""" import random # GAME FUNCTIONS ============== def welcome(): welcome_msg = """Welcome to Dungeon Raider! A game written by Daniel Miller as he learns the Python programming language. Please follow the prompts and enjoy the game!""" print(welcome_msg) #d...
cd80ead0bc1c104b20e8e6768f806e7e0c85d17b
vitormcferreira/python-regex
/aula03_quantificadores.py
1,096
3.765625
4
# Metacaracteres: ^ $ \ ( ) # Quantificadores # é aplicado ao elemento à esquerda # * -> 0 ou n # + -> 1 ou n # ? -> 0 ou 1 # { } -> {n} # { } -> {min, max} # {10,} 10 ou mais # {,10} de zero a 10 # {10} especificamente 10 # {5,10} de 5 a 10 import re texto = ''' João trouxe flores para sua amada namorada em 10...
6e941b9b983b81763303e207160fcfc68addc359
InakiCejudo/theegg_ai
/nivel_1_tarea_24/nivel_1_tarea_24.py
1,034
3.8125
4
#DE NÚMERO EN DECIMAL A BINARIO num_10 = 23 #Este es el número en base decimal a calcular. Se puede editar para probar cualquier número. print(f'El número en base decimal es: {num_10}') restos = [] cociente = int(num_10 / 2) #si la división no es exacta se redondea hacia abajo para convertir en entero resto = nu...
1c1b314864d450ffdf97ca9c9775d7d551bc9c88
Jas1052/AdventOfCode-2020
/Joe/day4/day4.py
4,165
3.546875
4
def part1(): file = open("input.txt", "r") validCount = 0 currentEntry = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"] for line in file: if not line.strip(): if len(currentEntry) == 0 or currentEntry[0] == "cid": validCount += 1 currentEntry = [...
4e27b29327e4eec1e1034f8c18b7d4a0437ce97f
GeneRiabchenko/shapes
/shape.py
381
3.953125
4
""" This is an abstract class from which all shapes will be inherited """ __author__ = 'nshumakov' from abc import ABCMeta, abstractmethod, abstractproperty class Shape(): __metaclass__ = ABCMeta @abstractmethod def square(self) -> float: """ implementation of the method of calculati...
322747201ef9fe9aa660c5a8831e396266789520
Santhosh-27/Practice-Programs
/N_day_profit_sell_k_times.py
1,317
4.34375
4
''' Stock Buy Sell to Maximize Profit The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on...
1f3782dd6e5a16fbd4ebf91ac643fe5f60c991ea
muarshad01/ICPP_notes
/ICPP_notes/ICPP_ch15.py
21,474
3.921875
4
# -*- coding: utf-8 -*- """ ICPP Chapter 15 Stochastic Programs, Probability, and Distributions @author: Daniel J. Vera, Ph.D. """ import random import pylab #%% Stochastic Programs ===================================================== #def square_root(x, epsilon): # """Assumes x and epsilon are of type fl...
b2453f0e7a40a0c2665509c2cfde72129b05b968
muarshad01/ICPP_notes
/ICPP_notes/ICPP_ch10.py
8,154
4
4
# -*- coding: utf-8 -*- """ ICPP Chapter 10 Some Simple Algorithms and Data Structures @author: Daniel J. Vera, Ph.D. """ #%% Search Algorithms ====================================================== # e in L # def search(L, e): # """Assumes L is a list. # Returns True if e is in L and False otherwi...
a5c7eb515fcb2e1260e638c1f7c87d040713e6e3
muarshad01/ICPP_notes
/ICPP_notes/ICPP_ch06.py
5,504
3.765625
4
# -*- coding: utf-8 -*- """ ICPP Chapter 6 Testing and Debugging @author: Daniel J. Vera, Ph.D. """ #%% Testing ================================================================ # def is_bigger(x, y): # """Assumes x and y are ints # Returns True if x is less than y and False # otherwise.""" #...
d74ac38960660fbb6476ceed1ebfe5292877fd74
muarshad01/ICPP_notes
/ICPP_notes/ICPP_ch23.py
13,355
3.625
4
# -*- coding: utf-8 -*- """ ICPP Chapter 23 Clustering @author: Daniel J. Vera, Ph.D. """ import pylab import random import numpy as np #%% Class Cluster ========================================================== def minkowski_dist(v1, v2, p): """Assumes v1 and v2 are equal-length arrays of numbers ...
242f6f493761120ba972a59579c370836b1703bf
muarshad01/ICPP_notes
/ICPP_notes/ICPP_ch18.py
13,099
3.53125
4
# -*- coding: utf-8 -*- """ ICPP Chapter 18 Understanding Experimental Data @author: Daniel J. Vera, Ph.D. """ import pylab import numpy as np import math #%% The Behavior of Springs ================================================ def get_data(filename): data_file = open(filename, 'r') distances ...
095cf2d2b9c6d71f606901fc6c3aef5ab75b0ac7
bc-townsend/aco_example
/aco_example/path.py
2,145
4.40625
4
import pygame from math import sqrt class Path: """Represents a path object. These are connections between nodes. """ def __init__(self, color, node1, node2): """Initialization method for a path object. Args: color: The color of this path. node1: One of the nodes ...
96679bd69ee862332e91cf2493c85e106be6c4d4
super-goose/orbit
/space/planet.py
3,201
3.640625
4
import pygame import math class Planet: def __init__(self, surface, color, position, radius, center): self.radius = radius self.surface = surface self.color = color self.setPosition(position) self.center = center self.setOrbitOffset(0) self.setOrbitPeriod(1) ...
9163e5b356aa777c64151d0cb77dd76e464ba1a7
robertpvk/phyton-base
/lesson1/task1.py
1,958
4.15625
4
""" ЗАДАНИЕ 1 Человеко-ориентированное представление интервала времени Спросить у пользователя размер интервала (в секундах). Вывести на экран строку в зависимости от размера интервала: 1) до минуты: <s> сек; 2) до часа: <m> мин <s> сек; 3) до суток: <h> час <m> мин <s> сек; 4) сутки или больше: <d> дн <h> час <m> мин...
8fd16d1053d689bd3068035610b8250213ee3c45
robertpvk/phyton-base
/lesson3/task1.py
974
4.28125
4
""" 1. Написать функцию num_translate(), переводящую числительные от 0 до 10 c английского на русский язык. Например: >>> >>> num_translate("one") "один" >>> num_translate("eight") "восемь" Если перевод сделать невозможно, вернуть None. Подумайте, как и где лучше хранить информацию, необходимую для перевода: какой тип...
9e0fa6d797d2fbca19d47a0e717329c401670d54
leenapatil14/ComputerVision_project3
/task1.py
6,129
3.609375
4
""" K-Means Segmentation Problem (Due date: Nov. 25, 11:59 P.M., 2019) The goal of this task is to segment image using k-means clustering. Do NOT modify the code provided to you. Do NOT import ANY library or API besides what has been listed. Hint: Please complete all the functions that are labeled with '#to do'. You...
2151bfe23b40b6d01fdbf864f7fdf8e30c93a481
frgfm/dl-playground
/nn-basics/layer.py
1,869
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Building blocks of Artificial neural network ''' __author__ = 'François-Guillaume Fernandez' __license__ = 'MIT License' __version__ = '0.1' __maintainer__ = 'François-Guillaume Fernandez' __status__ = 'Development' import numpy as np class Layer: def __init_...
f44d3d224b070605ff9361f8585a176d45858c3f
NiteshKumar14/MCA_SEM_1
/Lab Practicals/Mathematical Techniques/Final_prac_1.py
4,705
4.03125
4
class Matrix: def __init__(self,*args): if(len(args)==0): print("Dimension(M,N):\t",end='') self.row,self.coloumn =int(input()),int(input()) self.row,self.coloumn =self.check_input(self.row,self.coloumn) self.space=[[0]*self.coloumn for _ in range(self.ro...
33901933c76acda3b74577e52e989c1e4d4e34a8
NiteshKumar14/MCA_SEM_1
/Assignments/OOPs pythonn/synonym_using_existing_dict.py
1,495
4.46875
4
# create an empty my_dictionary my_my_dict={ "sad":"sure", "depressed":"Sad", "Dejected":"Sad", "Heavy":"Sad", "Amused":"Happy", "Delighted":"Happy", "Pleased":"Happy", "Annoyed":"Angry", "Agitated":"Angry", "Mad":"Angry", "Determined":"Energized", "Creative":"Energized",...
b08167b84bd467cc501f5b59165ca3ef8c100f38
NiteshKumar14/MCA_SEM_1
/Assignments/OOPs pythonn/happy_sum_of_squares.py
2,261
4.125
4
def sum_of_squares(sqdnumber): #defining a function that take a string and return its elements sum sqdNumber_result=0 #initializing sum array for storing sum iteratator=len(sqdnumber)-1 #iterating till the length of string in desce...
1b532fa04816dc4f67493124a218b5e845a32234
NiteshKumar14/MCA_SEM_1
/Assignments/OOPs pythonn/list_sum.py
630
3.75
4
def sumTwoNum(x,y): z=x+y return z def sunList(list1,list2): sum=[0]*(len(list2)) #initializing list to length of upcoming list for row in range(len(list2)): #looping till the length of list (same length expected ) sum[row]+=list1[row]+list2[row] #taking element...
339662856102e6cf71c2bb28eccc7e53fc7c12e2
NiteshKumar14/MCA_SEM_1
/Assignments/OOPs pythonn/Discrete Mathematics/31_jan_programs.py
7,011
4.125
4
""" 1. Write a program to implement Binary search (Recursive and Iterative). 2. Write a program to implement tower of Hanoi (Recursive and Iterative). 3. Write a program to generate a Pascal’s triangle. 4. Write a program to implement the following laws: a. Identity laws b. Domination laws c. Double negation laws d. D...
586d0ab55f65e880b32923f69458052fdf09ffd0
dansidi2/teamShirts
/scratch.py
179
3.890625
4
def lower_case(name): #underscore = name.replace(" ", "_") #lower_case = underscore.lower() return name.replace(" ", "_").lower() print(lower_case("Manchester City"))
ccd0cbe9d4827a6da0c5b84e7746d89f7ee84d66
akilmarshall/discord-bot
/player.py
831
3.75
4
# file that defines the player class # players exist within the dnd channel such that various useful statistics can be tracked # dice roll history being one of these from random import choice def dice_roll(x: int): return choice(range(1, x + 1)) class Player(): """This class exists to facilitate dice rolli...
41e8a9a9fc498541db54e4fb6ee767e8f6b51c6f
BriantOliveira/Memory-Test
/binary_heap.py
4,903
4.28125
4
class HeapTree(object): def __init__(self, items=None): """Initialize the heap and insert the giving item""" self.items = [] if items: for item in items: self.insert(item) def __repr__(self): """Return a string representation of this heap""" ...
249aad011cbbfafee861c09741935ae95f884384
jackie-kinsler/Labs
/data-structures/cohort_data.py
7,480
4.5
4
"""Functions to parse a file containing student data.""" def generate_cohort_info_list(file): """Accept a text file of cohort info and return a list with student info. Each item in list is structured as [first_name, last_name, house, / adviser, cohort_name] """ cohort_data = open(file) cohort_list = [] ...
06d11e57f5d8daba7a704260dd144ea9c2f0ec9e
chop0/Dr_quine
/quine_c/quine_maker_c.py
2,062
3.65625
4
import sys replace = {'"':34, '\t':9, '\n':10} def usage(): """ Define the usage file """ print('Usage: python3 {} <filename>'.format(sys.argv[0])) print('The file must be a .c.quine') print('The file must have \'char *s = "";\' and \'printf(s);\'') exit() def quine_integration(code, quine_chr, quine_print, pri...
287ae627f528eb7d416890cf8b3c0c6e38a82483
IndieD3v/Create_Folder
/create folder.py
429
4.03125
4
import os from datetime import date import time today = date.today() print("Todays Date",today) def Folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print ('Error: Creating directory. ' + directory) print("Created ...
d50aee05506a8ac8b69964447fa45b99dddd0ea9
201410090/p1_201410090
/w8Main1.py
283
3.671875
4
def charcount(word): d=dict() for c in word: if c not in d: d[c]=1 else: d[c]=d[c]+1 print d def lab8(): charcount('hello') def main(): lab8() if __name__=="__main__": main() raw_input()
8f6acc7eadcdeb6ae66b09500214b892f919a48c
alexistshudy/CS0008-f2016
/Chapter Exercises/Chapter3-Exercises(book)/ch3_ex7.py
912
4.0625
4
# name: Alexis Tshudy # email: abt21@pitt.edu # date: sept 19 2016 # class: CS0008-f2016 # instructor : Max Novelli (man8@pitt.edu) # description: Starting with Python, Chapter 3, Exercise 7: Color Mixer #red&blue = purple, red&yellow = orange, blue&yellow = green #ask user to input 2 primary colors color_1 = input("...
6e0fa89aa1a7e33121d99a83977283990de43db5
alexistshudy/CS0008-f2016
/Chapter Exercises/Chapter3-Exercises(book)/ch3_ex6.py
470
4
4
# name: Alexis Tshudy # email: abt21@pitt.edu # date: sept 19 2016 # class: CS0008-f2016 # instructor : Max Novelli (man8@pitt.edu) # description: Starting with Python, Chapter 3, Exercise 5: Mass and Weight # ask for user inputs (day, month, year) month = int(input("Enter month: ")) day = int(input("Enter day: ")) ye...
690fc223ffcb55b25383fa957b665deefb1d151e
eszterbirophotography/my-first-blog
/challenge.py
906
3.90625
4
questions = [ { "question": "What keyword Python uses to star defining a function?", "possible_answer": [ '1. def\n' '2. fun\n' '3. dir\n' '4. function\n' ], "correct_answer": '1' }, { "question": "Which line Rep...
bfc74b61bda4ed8c7d9fa74708655f4a84dc288f
kazice/Python-Algorithm
/leetcode/triangle.py
686
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/2/3 13:06 # @Author : Aries # @Site : # @File : triangle.py # @Software: PyCharm class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows < 2: ...
4f71de083f27719357addc5411ad7491d539c4f6
N03139860/ELSpring2015
/code/homeworks/hw2/temperatureDatabase.py
547
3.828125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 class TemperatureDatabase: def __init__(self, path_to_database): self.conn = sqlite3.connect(path_to_database) self.cur = self.conn.cursor() def dataEntry(self, data, tableName): with self.conn: self.cur.execute("INSERT INTO " + tableNam...
0e9d8ae66bcdca539c7db87c67b71f9da834c7b9
jhutch4302/Ultimate-Tic-Tac-Toe
/main.py
3,151
3.625
4
moveNumber = 0 board = [] gameOver = False currentPlayer = "" # Populate Board list with all empty characters for i in range (0,9): board.append("-") # Asks and returns user input | int 0 - 8 def getMove(currentPlayer): x = input("Move: ") return x # If false game over def boardContainsEmp...
4eaf701470c01077f14e5491eecd6282bb0e61c8
freebrains/Python_basics
/Lesson_5.1.py
563
4.4375
4
""" Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка. Create with a program file in text format and write the data entered by the user line by line. An empty string indicates the end of data entry. """ fi...
5f5df0b3966bb1a5c613d0c4f6e4f524cee0c742
freebrains/Python_basics
/Lesson_3.3.py
580
4.3125
4
""" Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. Implement the my_func () function, which takes three positional arguments, and returns the sum of the largest two arguments. """ def my_func(var_1=int(input("Enter first number - ")), var_2=i...
a3b0f1df4ea0fefeba0f39fd5669d5a364d508da
freebrains/Python_basics
/Lesson_8.4.py
2,319
4.34375
4
""" Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад. А также класс «Оргтехника», который будет базовым для классов-наследников. Эти классы — конкретные типы оргтехники (принтер, сканер, ксерокс). В базовом классе определить параметры, общие для приведенных типов. В классах-наследниках ...
9dec69e9d104c4011702af47bd2cc816109852ff
freebrains/Python_basics
/Lesson1.4.py
664
4.21875
4
''' Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции. The user enters integer. Find the largest digit in the number. Use while cycle and arithmetic operations. ''' number = int(input("Enter the number - ")) a = number % 10...
f18334ed4716dc9ff35430c6ad97e38b3c27c6c2
freebrains/Python_basics
/Lesson_4.1.py
1,101
4.0625
4
""" Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. Implement a script that should provid...
4bba3b49aa0ed2f0392875f79b13b54b6801c1e9
Einlar/Matplotlib2LaTeX
/build/scripts-3.6/mpl2latex.py
6,971
3.53125
4
import matplotlib class Matplotlib2LaTeX(): """ Plot matplotlib figure in pgf for perfect LaTeX reports Class to plot matplotlib figures using the pgf backend, swapping easily between the two. All the commands that you would use with matplotlib to plot on axes can be used with this cla...
95b8d48c15b9be877f3564e189cd5ee950f47dc4
jkeller51/ECE448_MP2
/GUI.py
9,952
3.765625
4
#!usr/bin/env python3 # -*- coding:utf-8 -* #Gomoku GUI program #Can extend by adding menu item to allow you to choose difficulty level from tkinter import * from board import Board from alpha_beta import AlphaBeta from human import Human class GomokuButton(Button): """ Almost identical to tkinter bu...
927f4bc708c1ffb46ac5c4ef885d9c9198d30588
endoeduardo/snake
/objects.py
1,180
3.515625
4
import pygame from random import randint class Apple(): """Configurações da maçã""" def __init__(self, settings): self.settings = settings #Criando uma surface pra maçã self.skin = pygame.Surface((self.settings.apple_width, self.settings.apple_height)) self.skin.fill(self.sett...
bb5c1d8ffd171e3bd94a98fd7b016b19bb34da11
jamilcse13/python-and-flask-udemy
/11. stringFormatingOperator.py
287
3.5
4
#usng string formatting operator name = 'xyz' print('welcome %s' %name) age = 27 print('age=%d' %age) print('age is %s' %age) marks = 60 print('marks=%2f' %marks) print('marks=%0.2f' %marks) print('age in ortal %o' %age) print('age in hexadecimal %x' %age) print('age with exp %e' %age)
20874edae2f9d442255009e0f273e5c3bd5b1753
jamilcse13/python-and-flask-udemy
/18. nestedLoop.py
184
3.875
4
for i in range(1,11): for j in range(1,11): k=i*j print(k, end=" ") print() for i in range(1,6): for j in range(i): print("*", end=" ") print()
1d40d049794faa916c6f4a845d138e1b02ae8ef7
jamilcse13/python-and-flask-udemy
/16. whileLoop.py
598
4.1875
4
count = 0 while count<10: count += 1 print("count=", count) print("good bye!") ## while loop else statement count = 0 while count<10: print(count, "is less than 10") count += 1 else: print(count, "is not less than 10") print("good bye!") # single statement suits flag = 1 #it eill be an in...
6a088f39a8c257a5d5638de979c1f389b8beb1ac
Devendra48D/Code
/Knight's shortest path.py
884
3.515625
4
def isvalid(cell): return 1<=cell[0]<=8 and 1<=cell[1]<=8 def getneighbors(cell): offset = [(2, 1), (-2,1), (2, -1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2)] ret = [] for a in offset: if isvalid((cell[0]+a[0], cell[1]+a[1])): ret.append((cell[0]+a[0], cell[1]+a[1])) return ...
67fef04584aede0b1299ccb99e7dca0fba9f576e
concastor/FlappyBirdAi
/neuralNetwork.py
5,352
3.71875
4
import numpy as np import math as m import copy import random as rand # 3 layered neural network template # params: numInputs = the number of inputs that the Neural network will receive # numHidden = the number of hidden layer perceptrons to use # numOutput = the number of outputs the Neural net...
7375913451a7980e172ca04434d36b6573c15b91
marco-fiumara/learning-python-projects
/Hangman/main.py
1,957
3.828125
4
# Hangman Activity import random word_list = ['python', 'java', 'kotlin', 'javascript'] chosen_word = random.choice(word_list) word_list = list(chosen_word) letters_guessed = [] preview_list = [] word_set = set(chosen_word) def guess_check(g): if len(g) != 1: return "You should print a single letter" ...
70d8a528a99c1599b955146f76a6c9db09b9f3e8
TarunVenkataRamesh-0515/19A91A0515_IICSEA_IVSEM_PYTHONLAB_1_TO_3
/distance.py
368
4.125
4
""" Implement a python script to compute distance between two points taking inp from the user (Pythagorean Theorem) """ x1=int(input("enter x1 : ")) x2=int(input("enter x2 : ")) y1=int(input("enter y1 : ")) y2=int(input("enter y2 : ")) result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5) print("distance ...
adf085949b29894dc6f42d106ba777563e3f00e6
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/18.二叉树的镜像.py
1,581
3.765625
4
from collections import deque class TreeNode(object): def __init__(self, x): self.x = x self.left = None self.right = None class Tree(object): def __init__(self): self.root = None def construct_tree(self, values=None): if not values: return None ...
b49777fd4aba0a55c804acfc4169be6c602c9406
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/6.旋转数组中最小的数字.py
1,189
3.9375
4
""" 通过二分查找法找到最小数字,两个指针一个在头一个在尾。因为是旋转数组,所以尾部指针必定<=头部指针。接着看中间如果说中间那个数 大于头部说明最小数再后半部分,如果小于尾部,说明在前半部分,以此作为判断条件进行递归 """ # def search_min(arr): # if len(arr) == 1: # return arr[0] # l = 0 # r = len(arr) - 1 # mid = (l + r) // 2 # if arr[l] > arr[mid]: # search_min(arr[mid + 1:]) # el...
6a50b5dbed3af62798becd2af22883e06247e7a1
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/37.数字在排序数组中出现的次数.py
1,900
3.609375
4
""" 利用二分法的思想 设要统计的数是k 首先与中间的那个数比较,如果中间那个数比k要大,说明k在前半段,反之在后半段,只需要去相应的区间查找 如果此时中间那个数与k相等,那么就需要看这个数是否是开头的那一个,就看它前面的一个是不是k,如果是,记录索引,不是就继续在前半段找 同理,找到最后一个k,相差即为个数 """ def get_num_of_k(arr, k): left = 0 right = len(arr) - 1 mid = (left + right) // 2 def __get_left_index(arr, k, left, right): if left...
bcbaa2e10a0994b9fb4ae03c9f9441c4bdb7c843
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/43.翻转单词顺序列.py
468
3.796875
4
""" 两步反转,先反转 """ def reverse_words(s): # 将整个字符串反转 s = s.strip() s = s[::-1] print(s) ret = "" start = 0 for i in range(len(s)): if s[i] == " ": m = s[start:i] m = m[::-1] + " " ret += m start = i + 1 if i == len(s) - 1: ...
039948315f8a8bd6e392e7044baf7363fc14596e
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/13.调整数组顺序使奇数位于偶数前面.py
534
4.0625
4
""" 运用双指针 """ def is_odd(n): """ 判断一个数是不是奇数 :return:True for odd. """ return False if abs(n) % 2 == 0 else True def order(arr): length = len(arr) l = 0 r = length - 1 while l < r: while is_odd(arr[l]): l += 1 while not is_odd(arr[r]): r -= ...
d1dab21c9785462cf0f826f913bd37388bee9f36
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/58.按之字形顺序打印二叉树.py
1,412
3.796875
4
from collections import deque class TreeNode: def __init__(self, x): self.x = x self.left = None self.right = None class Tree: def __init__(self): self.root = None def construct_tree(self, values=None): if not values: return None self.root = T...
34fba42ec60b59d8971c072231624e6970e3f08c
jiangyuwei666/my-study-demo
/Algorithm/sword of offer/15.反转链表.py
1,530
4.09375
4
""" """ class ListNode: def __init__(self, x): self.x = x self.next = None def init_list(num_list): node_list = [] for i in num_list: node = ListNode(i) node_list.append(node) for j in range(len(node_list)): if j == len(node_list) - 1: return node...
08970420d0a50f9689ed6c8be9413e69d1d89a45
jiangyuwei666/my-study-demo
/DataAnalysis/homework10/xien.py
3,120
4.09375
4
""" 用修恩法解微分方程 跟欧拉法唯一的区别就在求斜率上 欧拉法使用前一点的斜率作为斜率,而修恩法用两个点之间的重点作为斜率 """ import numpy as np import matplotlib.pyplot as plt def get_integral(coefficient, x, y): """ 求积分 :param x: x,y 用于求常数c :param y: :param coefficient: 一个列表,一次表示常数项,一次项,二次项...如[1, 2, 3]表示1 + 2x + 3x^2 :return: 返回列表。表示每一项系数 ""...
dc08eb56d32c36ae1d49c206a27d4b420ce2a312
gogo1897/python-ch2.2
/operator_relation.py
317
4.03125
4
#복합 관계식 a = 6 print(0 < a and a < 10) print(0 < a < 10) #수치형 이외의 다른 타입의 객체 비교 print("abcd" > "abd") print((1, 2, 4) < (1, 3, 1)) print([1, 2, 4] < [1, 2, 0]) #동질성 비교: ==, 동일성 비교: is a = 10 b = 20 c = a print(a==b) print(a is b) print(a is c) print(a==c)
0635bee367447fc81531d4bb39818f592e5f60f4
jungwon1413/Tensorflow_Tutorials
/mnist_practice_deep.py
2,127
4.03125
4
from tensorflow.examples.tutorials.mnist import input_data # mnist is a lightweight class which stores # the training, validation, and testing sets as NumPy arrays. # It also provides a function for iterating through data minibatches. mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # Why use se...
82777b416906c05f7a464ef7d4fc12c88c1283e2
crookescout/unit_7
/daily_exercises.py
2,157
4.0625
4
# Scout Crooke, 11/06/19, This program works on unit 7 daily exercises # # # exercise 1 # # original = "abcdefghij" # first = original[0:4] # last = original[4:] # final = first + last # # print(final) # # # exercise 2 # # word = "Python" # for x in word: # print(x) # # # exercise 3 # # # def without_end(the_word):...
1bb7f99530483ef75197de64013202561f7ed2bb
Kavya333/hello-world
/intro8.py
269
4.0625
4
tuple1 = ('python', 'ruby','c','java') list1 = ['python','ruby','c','java'] list2=['xxx','yyy'] print (tuple1) print (list1) print (list1+list2) list1[1] = "windows" print (list1*2) print (tuple1[2:]) # Windows does not work here! tuple1[1] = "windows" print (tuple1)
834e397db50fb5f8ccde8fd93a7ae5d11ff887b5
Dvaleris/python_week_one
/calc.py
949
3.859375
4
# calculator print(1+2) print(3) print(10%2) print(11%2) for i in range(0,9): print("bitshift ", i, "times ", 1<<i) print('Hello, world!') print('') print('Good-bye.') print( 'I like' + 'chocolate cake.' ) print('I like ' + 'apple pie.') print('I like' + ' apple pie.') print('blink ' * 4) ...
54b8b9b9be1d12692909024eeb63535055a70268
piotrpasich/python_exercises
/zestaw8.py
2,152
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Piotr Pasich, Łukasz Wycisło WSB, Informatyka, Niestacjonarne, Programowanie w jezyku Python Zestaw 8 """ """ Zadanie 1. Napisz program zawierający instrukcję rysowania trójkąta równobocznego . """ import turtle def zadanie1(): t = turtle.Turtle() for i...
403ebefc094471462865629d50e062f8de8d941b
HydraCodes0831/PassWordPY
/Password.py
456
4.0625
4
user = input("Please enter a password: ") retries = 3 while user: user_input = input("Please enter your password: ") if user_input == user: print("Password Accepted: ") break else: if user_input != user: retries -= 1 if retries == 0: print("To many fai...