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
c4f7ff33799bf4d121b11d97b9c2841c54513d97
soulforever/CorePythonProgramming
/chapter6/functions.py
12,989
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Home work of chapter 6. """ __author__ = 'guti' def sort_nums(num_str): """ Problem 6-3, sort a number string :param num_str: number string, use space to split :return: list, sorted desc """ # # --------------------------- # # Problem 6-3...
f69fe2846739de4db4c3536ba835b3e67b7914b3
soulforever/CorePythonProgramming
/chapter13/MoneyFmt.py
1,107
3.9375
4
# -*- coding: utf-8 -*- """ Homework for chapter 13 """ __author__ = 'guti' class MoneyFmt(float): """ Problem 13-3, convert float to str """ def __init__(self, value=0.0): super(MoneyFmt, self).__init__() self.value = float(value) def update(self, value=None): if value ...
2b92ba48a25a796a6ec07c323d769fc864c0fa85
soulforever/CorePythonProgramming
/chapter6/idcheck.py
1,091
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Problem 6-2 Check if a input string is valid for variable """ __author__ = 'guti' import string import keyword alphas = string.letters + '_' nums = string.digits print 'Welcome to the Identifier Checker v1.1' # change version ^_^ print 'Testees must be at least 2 c...
4c997e1581cf51e851d1a89fca0a7cb76f320de2
elias403/URI-Games
/URI online judge/1 - iniciante/1010_nv3.py
330
3.5625
4
peca1 = input() val1 = peca1.split(' ') a1=int(val1[1]) a2=float(val1[2]) peca2 = input() val2 = peca2.split(' ') b1=int(val2[1]) b2=float(val2[2]) calc = a1*a2 + b1*b2 print(f'VALOR A PAGAR: R$ {calc:.2f}') ''' lista = input().split(' ') a = lista[0] b = lista[1] c = lista[2] print(a) print(b) pri...
2b11221a58ddff3101a95aa892b0ed5ab4997f80
5h3rr1ll/LearnPythonTheHardWay
/ex15.py
1,076
4.375
4
#importing the method argv (argument variable) from the library sys into my code from sys import argv """now I defining which two arguments I want to have set while typing the filename. So you are forced to type: python ex15.py ArgumentVariable1 ArgumentVariable2""" script, filename = argv #since the filename is give...
069ea58adff72648ca541ced66553ce543ad12bd
HuylenbroeckFlorent/BA3_Compilation_Projet
/code/Espace2Travail - Copie/poubelleinstant.py
649
3.65625
4
from abc import ABC, abstractmethod """ Created on Sun May 5 06:19:03 2019 @author: Alfatta """ class X(ABC): @abstractmethod def execute(self): pass class A(X): def __init__(self,data): self.data=data def execute(self): print("niBBa") return self.data ...
6b4374f4a85255a744d1acd968838c6ec8919f67
Dazmen/CS-Build-Week-2
/day_1/add_two_LL/add_two_LL.py
2,497
3.890625
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next ''' create an list to store the summed digits - add the head of l1/l2 together, push the value into the digits list - continue to traverse l1/l2 summing the values and ...
0867bb46c88dbf25402e96630bf82ba27b771fb4
scarlet-chariot/CSCI107
/Thomas_submit.py
5,379
4.0625
4
#---------------------------------------------- # Author: Alex Tseng # For: CSCI107, Rance Harmon # Last Updated: February 2, 2018 #---------------------------------------------- # This script will attempt to make a character # from Thomas the Tank Engine using Turtle # graphics from python. # Note: This creates the c...
923f3195c107b00af146fc842d79c87b447156ee
papakofifog/Assignment-1
/Rectangl.py
1,719
3.734375
4
class Point: def __init__(self): self.point=(0,0) def set_point(self,x,y): self.point=(x,y) return self.point class Rectangle(Point): def __init__(self,top_right,bottom_corner): Point.__init__(self) self.p1=top_right self.p2=bottom_corner se...
132b0430059e424d205f8bbf35132606ad5f12f8
saforbes99/workshop2
/app.py
1,449
3.640625
4
from banking_pkg import account def atm_menu(name): print("") print(" === Automated Teller Machine === ") print("User: " + name) print("------------------------------------------") print("| 1. Balance | 2. Deposit |") print("------------------------------------...
a4877ed3f2bb5586e5143b85119eeb1f75efeb6c
kmjawadurrahman/python-interactive-mini-games
/guess_the_game.py
2,176
4.40625
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random which_range = "" # helper function to start and restart the game def new_game(): # initialize global variables used in your code...
696fabffe2a6d588514746c7adeb4530769b35f6
snaeni/PCA-Project
/coinchangeNaiveRecurssion.py
1,365
3.59375
4
import time totalRuns = 5 changeTomake = 57 def getNumWays(changeTomake, coinValueList, allowedcoinsIndex): numOfWays = 0 # We have reached base case, empty set is a combination. So return 1 if changeTomake == 0: return 1 if allowedcoinsIndex <= 0: return 0 ...
6f2a75b374874c7dcdfebc8bc6ac4ddf72e77ce6
NamanJain1902/Recursion-Problems
/String_Reverse.py
164
4.0625
4
def strev(s): if(len(s) == 0): return s return strev(s[1:]) + s[0] s=input("Enter a string:") print("Reversed string is",strev(s),sep='->')
a06ce182086f0bda1518deb2c77fc3d589ebc137
Bhavana123sai/python1
/test2.py
367
3.703125
4
import math def abundant(n): a=0 for i in range(1,n): if n%i==0: a=a+i print("a:",a) if a>n: return 1 else: return 0 n=int(input()) if(abundant(n)==1): print("Abundant Number") els...
30b7c8bdc04703d6664c9e3e7a18f98fdb10e36e
Zakiya435/c99
/onee.py
197
3.734375
4
def f1(fileName): o = open(fileName,"r") c = 0 for i in o: o2 = i.split() c+=len(o2) print(c) fileName = input("Enter name of file") f1(fileName)
986fc64c1cbfa08cc47f6da4ae96c7bcdf570506
AbhishekAOne/Programming-Codes
/python/itertools.py
146
3.734375
4
from itertools import accumulate, takewhile numbers = list(accumulate(range(8))) print(numbers) print(list(takewhile(lambda x: x <= 10,numbers)))
66b8e01158c5b612d76c7a82d02e0b58a4cfff39
AbhishekAOne/Programming-Codes
/python/python/factorial.py
135
4
4
def fact(n): i=1 fact=1; while(i<=n): fact=fact*i; i+=1; print("factorial of ",n," is ",fact); fact(5)
fc9efed85e24a84bdc8c28cf68ed4e3909c27fe8
AbhishekAOne/Programming-Codes
/python/python/Inheritance.txt.py
542
4
4
#INheritance: #when one class aquare class aquire property of another class withdraw redining known as inheritance class student: def set(self,n,r): self.name=n; self.rollno=r; def show(self): print(self.name); print(self.rollno); ...
6a5e30e8a69d6f3d90720b2e20d53868a9f1aa37
GLayton-TX/Delivery_application
/Package.py
5,374
3.578125
4
# Package class for creating package objects import csv import HashTable import Location import Utility filename = "package_list.csv" # package object used to represent the packages for delivery class Package: # default constructor, assigns all info into the new object # time_space complexity...
454fa3a88430d5082f04644fbaf64b71ba8da5db
pukkapies/drummer-tf
/utils/sampling.py
3,381
3.671875
4
import numpy as np import scipy.misc def uniform_sample(x): """ Samples from a list with uniform probability :param x: List of elements :return: A randomly sampled element from x under uniform distribution """ return np.random.choice(x) def binary_sample(x): """ Takes an array of float...
9daf178dcf33f90f333f9db258cbfb00d925b935
vskemp/OOP_py_practice
/cat.py
3,137
4.625
5
# How do we store a single value? # variable # several values? # list # details about a single value? # dictionary # repeat a piece of code, indefinitely? # while loop # Work through a list? # for loop # Repeat a piece of "configurable" code. returning a value? # function!!! # Classes are for: # bundling related ...
175c7ef5c18a53fbbad8e04b1c3af6280074ce25
bernardodr/Deep_Neural_Network
/Binary_Classification_Neural_Network.py
2,464
3.5
4
#Neural Network with one hidden layer to classify lables in a non linearly separable dataset (Binary classfication) #functions in google colab import numpy as np import matplotlib.pyplot as plt import keras from sklearn import datasets from keras.models import Sequential from keras.layers import Dense from keras.optim...
03b61fc9d421b7b62d30828e53a41fea65e77a16
tanviredu/using_python_to_access_web_data
/week2/assignment2.py
862
3.671875
4
## this is some basic socket programming ## its verty easy ## it start with importing socket import socket import time def main(): ## create the socket object mysock = socket.socket() ## connect to the server ## the address and the port must be a tuple mysock.connect(('data.pr4e.org',80)) ##...
8ba3236467de34897c6f12d2d0120a5cae42f21c
WenYHsieh/DSA-Course
/Restaurants.py
4,085
4.0625
4
import functools from typing import List class Restaurant(object): # construct restaurant object def __init__(self, id :int, rate :int, price :int, distance :int): self.Id = id self.Rate = rate self.Price = price self.Distance = distance def getID(self) -> int: return ...
9b8e15a01538409fab3cc46d857f475bb984953f
petarpetarpetar/perfect-cell
/world.py
1,029
3.5
4
#!/usr/bin/env python3 import cell import food import string import random width = 0 height = 0 cells = [] foods = [] cellCount = 0 def randomDNK(size): chars = string.ascii_lowercase return ''.join(random.choice(chars) for i in range(size)) ## initialization # # def init(w, h, nc, nf): global cellCount ...
2f9244a128a57c95799b804b1611f0756fabeea6
jisie/student-backlog-creator
/query.py
1,085
3.625
4
#!/usr/bin/env python3 import sys def username(question): # Reserve this are in case I want to prevent special characters etc in the future return input(question) def password(question): import getpass return getpass.getpass(question) # Taken from http://code.activestate.com/recipes/577058-query-yesno/ # with ...
8c6a31134918767ec7c58d9b0b1ac214bd986b10
Rockysunny/Python-Data-mining-Homework
/Day-07/Exercise-08-徐昭.1.py
224
3.5625
4
import time import datetime time1=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print("现在时间:",time1) time.sleep(1) time2=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print("暂停一秒:",time2)
4396e20080fe13fc155dca9462ecfcffb58175e4
Spaceman007/Fractal
/python/Sierpinski_carpet.py
1,089
3.609375
4
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import matplotlib.figure ''' 谢尔宾斯基地毯(Sierpinski carpet) ''' # A,B 是对角点 def plot_rectangle(A, B): x = [A[0],B[0],B[0],A[0]] y = [A[1],A[1],B[1],B[1]] ax = plt.gca() ax.fill(x, y, color='g') #ax.fill(x, y) def plot_Sierpinski_carpet(A, B)...
041dc68b74c995f013c2cc68dc23cc0b043e8838
Punmanat/Web_Programming
/Django_Example/python.py
596
3.6875
4
class Car: def __init__(self): self._color = "" self._model = "" def drive(self): print("Bruuuuuuu") @property def getColor(self): return self.color def setColor(self, color): self.color = color @property def getModel(self): return self.mod...
7615d2d1b9f35c00b52c64a5756cc97472029df4
Starkxim/code
/python/kp2/5.py
651
3.59375
4
a = float(input('enter a=')) b = float(input('enter b=')) n = int(input('enter n=')) eps = float(input('enter eps=')) h = (b - a) / n m = int(n / 2) r1 = 0 r2 = 0 r3 = 0 r4 = 0 def func(x): return -(x ** 2) for i in range(1, m + 1): x = a + (2 * i - 1) * h r1 += func(x) for i in range(1, m): x = a +...
78612c3a6eea0bafaa319748bd8efc74bae978a1
Starkxim/code
/python/kp1/1.py
413
3.921875
4
print('you can use Yes,yes,Y,y,Yeah,1,да to say agree') print('you can use No,no,N,n,0,нет to say disagree') a=input('Будет ли на ужине вегетарианец?') b=input('Будет ли на ужине веганец?') c=input('Будет ли на ужине приверженец безглютеновой диеты?') if a in ('Yes','yes','Y','y','Yeah','1','да'): x=1 if a in()
41d37715e6698ae2c3d005db93f781bffbeb7194
Starkxim/code
/python/hw2/hw2.4.py
175
4.03125
4
print('enter a') a=int(input()) print('enter b') b=int(input()) even=0 odd=0 while a<=b: if a%2==0: even+=1 else: odd+=1 a+=1 print('even is',even,'odd is',odd)
585275762db86dec3a03d6542e97e8ac8ba12c3c
Starkxim/code
/python/hw3/6.py
186
3.875
4
a=int(input("a=")) b=int(input("b=")) c=int(input("c=")) if(a==b and b==c): print("равносторонним") if(a==b or b==c or a==c): print("равнобедренным")
1159547b49f1b9da4e7c164ef447a54c5e4f1833
Starkxim/code
/python/kp2/1.py
154
3.59375
4
ls1=[] sum=0 for i in range(20): a=float(input('enter number=')) sum+=a ls1.append(a) print(min(ls1)) print(max(ls1)) print(sum) print(sum/20)
bfb6aad7e3269b18036f32dd619cd7f8bd0b4099
Starkxim/code
/python/hw12/1.py
287
3.578125
4
def fifth(): num = 0 flname = input('ener filename:') with open(flname) as infile: for line in infile: try: if num < 5: print(line) num += 1 except: print('error') fifth()
1b7d369dd2bbf50001b5079dc58f4ebcc0349f34
Starkxim/code
/python/hw1/hw1.3.py
178
3.875
4
print('enter a') a=float(input()) print('enter b') b=float(input()) print('enter c') c=float(input()) p=(a+b+c)/2 s=(p*(p-a)*(p-b)*(p-c))**0.5 r=s/p print('answer is',r**2,'pi')
82bead79b7898f5ce35e7228ebdfb3bd042ca4d6
xiangliang-zhang/newcode_test
/中级班/第三章/class5.py
686
3.9375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/6/23 17:22 # @Author : 一条很咸很咸的咸鱼 def maxLength(arr): if not arr: return length = len(arr) max_length = 0 for i in range(length): set = [] for j in range(i, length): if arr[j] in set: brea...
9c2ecb1bbc5aa238ca78ad41abd7d5f059abb7b0
xiangliang-zhang/newcode_test
/基础班/thirdClass.py
10,036
3.5
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/7/17 16:30 # @Author : 一条很咸很咸的咸鱼 # 比较器 # 例子:定义一个学生类,对学生排序 import functools from inspect import stack class Student(object): def __init__(self, name, age, id): self.name = name self.age = age self.id = id def __str__(self...
63a703304aee0747e824583b7090dca53851b1ac
xiangliang-zhang/newcode_test
/基础班/fourthClass.py
19,997
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/7/21 15:45 # @Author : 一条很咸很咸的咸鱼 # 题目四:猫狗队列 class Pet: def __init__(self, type): self.type = type def getPetType(self): return self.type class Dog(Pet): def __init__(self): super().__init__('dog') class Cat(Pet): ...
7fdb1a6c78f4df2f543363e9856f442b59bc1ca3
xiangliang-zhang/newcode_test
/中级班/第一章/class1_2.py
1,054
3.609375
4
from 中级班.第一章.class1_1 import Node # 带头尾节点的双向链表结构 class NodeDoubleLinkedList: def __init__(self): self.head = Node() self.tail = Node() self.head.next = self.tail self.tail.before = self.head def addNode(self, node): if node.value == None: return else...
d74aa6b2512108afced8c504a7cbbe2590c2e03b
ee08b397/cod
/leetcode/021-Merge-Two-Sorted-Lists/Merge2SortedLs_001.py
801
3.828125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def mergeTwoLists(self, l1, l2): dumpy = ListNode(0) p1 = l1 ...
336752945fd20ad86c8fef8d7fe7c319675385bd
prakrutivaghasiya/Python-programs
/Fibo.py
266
4.125
4
def Fibonacci(n) : if n<0 : print('Incorrect Input') elif n == 1 : return 0 elif n==2 : return 1 else : return Fibonacci(n-1) + Fibonacci(n-2) print('Enter number : ') number = int(input()) print (Fibonacci(number))
3c407887e10b91faf36ff3aaf2760884e50e605f
apoorvabatra50/doubts
/cusin.py
4,045
3.921875
4
# User function Template for python3 class Node: def __init__(self, val): self.data = val self.left = None self.right = None # Returns true if the nodes with values 'a' and 'b' are cousins. Else returns false def isSibling(root, a, b): # Base Case if root is None: ...
57c357bdaad22bd0f33f4ab775eaccd050a8fccb
joaquinm19/practicas_python
/suma esp.py
203
3.90625
4
print("esto es una suma") numero_uno=2.5 numero_dos=4 resultado=numero_uno+numero_dos print("el resultado de la suma es: ", resultado) print("el tipo de dato numero_1 es",type(numero_uno))
6d9c233823ab0a4c1c5e0b888f81c110ca2fc3b8
Surya0705/Python_Clock
/Main.py
852
4
4
from tkinter import Tk # Importing the tkinter module. from tkinter import Label # Importing the tkinter module. import time # Importing the time module for our Clock's time. import sys # Importing the sys module. Root = Tk() # Defining the root. Root.title("Python Clock") # Giving the title to our tkinter windo...
6452ecb4a2a9bd6b81b1638b5eefeade11f96afd
Allahho/A-simplified-client-server-solution-for-file-management
/Server/UserModel.py
1,724
3.9375
4
""" This module contains the class User, A data model class to store attributes of a user. """ class User: """ A simple structure for snake. This is a collection of the block objects that make up snake Attributes: ----------------- username: string username with which the ...
fd6965e8299b196b73f4b4d168d6094e8cda0067
manojadhav/AlgorithmPrep
/3. Binary search. Binary search.py
477
3.875
4
def binarySearch(array, target): return binarysearchhelper(array,target, 0, len(array)-1) def binarysearchhelper(array, target, left, right): if left > right : return -1 middle = (left + right)//2 potentialmatch = array [middle] if target == potentialmatch: return middle elif target < potentialma...
fa97d03c2f5b432c5efd2c5cc1635506da381fa6
alansmathew/Algorithms-with-py
/lab programs/4.py
183
4.21875
4
print("Bitwise operators") a=int(input("Input two numbers:")) b=int(input()) print('a&b',a&b,'\na|b ', a|b, '\n~a ' ,~a, '\n~b ' ,~b, '\na^b ' ,a^b, '\na<<b ' ,a<<b, '\na>>b ' ,a>>b)
f3396d3b2313eb740b663f68dccbf3ff2f183405
alansmathew/Algorithms-with-py
/lab programs/III12.py
253
3.90625
4
course=['mca','mba',30,40] course.append('pgdca') print(course) course.extend(('mca','mba','4a','4b')) print(course) print(course.index('mba')) print(course.count('mba')) print(course) print(course.pop()) print(course) course.remove('4a') print(course)
c2fb0b319ca02b390f558614a89ac080a3b93a26
alansmathew/Algorithms-with-py
/lab programs/rt/16.py
285
3.75
4
def moderateDays(): lst=[] dic={"monday":68,"tuesday":70,"wednessday":73,"thursday":69,"friday":65,"saturday":71,"sunday":72} for key in dic.keys(): if dic.get(key)>=70 and dic.get(key)<=79 : lst.append(key) return lst print(moderateDays())
aa0bd810d4b741484601f14ca6d0ba3d31c79167
RaviKiranDev/Python-Exercises
/StringsAndLists/StringsAndLists/6.py
185
3.8125
4
number1 = int(input("Enter a number:")) number2 = int(input("Enter a divisor:")) l=[] for number2 in range(1,number1+1): if number1%number2==0: l.append(number2) print(l)
cad643eabe0abb36b3d014fb11acd0509448cdbd
RaviKiranDev/Python-Exercises
/Functions/Functions/Advanced4.py
385
4.03125
4
n=int(input("Please enter a numberrr: ")) def ReturnAllPrimes(n): p=0 if n<=0: return 'Please pass in a positive number' else: for i in range(1,n+1): p=0 for j in range(1,i+1): if i%j==0: p += 1 if p==2...
e03c7539bdf77c9504780b9565aa378690a76230
RaviKiranDev/Python-Exercises
/Classes/Classes/Dice.py
1,253
3.6875
4
# Nouns: bag, dice, game # # Verbs: roll, draw, sum import random class Die: def __init__(self, num_sides): if num_sides > 20: raise ValueError("You can't have more than a 20 sided die!") if num_sides % 2 != 0: raise ValueError("Y...
886e69407a09a3afa2306540f33b2d0f219fc027
RaviKiranDev/Python-Exercises
/TuplesDictsSets/TuplesDictsSets/sets2.py
168
3.90625
4
words = input("Please enter a series of words separated by commas") words_list = words.split(',') result = set(words_list) string = ',' .join(result) print (string)
7c0d5b6e2a34573515eeefa8451ec93e94aecded
RaviKiranDev/Python-Exercises
/LogicAndLoopsExercise/LogicAndLoopsExercise/ifelse2.py
233
4.4375
4
x=int(input("Enter a number")) if x%2==0: if x%3==0: print("even and divisible by 3") else: print("even") else: if x%3==0: print("odd and divisible by 3") else: print("odd")
d1bbf1fb9eaf7a7500f6686f916c730f0fa3cd88
rahul-goel/SpaceRace
/obstacle_enemy.py
1,312
3.5625
4
import pygame import random import config from config import config_settings as cs pygame.init() def random_enemy(new_speed): enemy_list = [] for i in range(1, 6, 1): # using random function to get random direction of movement direction = 1 if bool(random.getrandbits(1)) else -1 # rand...
34322b174312934b1f54e5face220321a5760f34
jaybruce1998/Chess
/Chess.py
9,341
3.703125
4
import sys class Square(object): def becomes(self, c, t): self.color=c self.type=t self.moved=0 self.specialMoved=False def turnsInto(self, s): self.color=s.color self.type=s.type self.moved=s.moved self.specialMoved=s.specialMoved def reset(sel...
f95c90cefc62f8a1531c8a0d32ddc4e91a3dbc86
Otumian-empire/python-oop-blaikie
/05. Advanced Features/0505.py
604
4.15625
4
# With context # open file and close it fp = open('Hello.txt', '+a') print('I am a new text file', file=fp) fp.close() # We don't have to close it with open('Hello.txt', '+a') as op: print('I am a new line in the Hello.txt file', file=op) # seems like not a valid python3 code # class MyWithClass: # def __e...
725de33d16e9e639fab41a8c84cbd55bb9c96a9f
Otumian-empire/python-oop-blaikie
/04. Inheritance And Polymorphism/0404.py
526
3.96875
4
# Inheriting the constructor of a class import random class Animal: def __init__(self, name): self.name = name def eat(self, food): print(f"{self.name} is eating {food}") class Dog(Animal): def __init__(self, name): # super(Dog, self).__init__(name) super().__init__(n...
cd43c84150d223e30f9e2e6812480b8f31918b0a
Otumian-empire/python-oop-blaikie
/03. Classes/0303.py
406
3.921875
4
class Joe: greeting = "Hello there, joe" big_joe = Joe() print(big_joe.greeting) # create a method class JoeMethod: # this is an instance method - because the instance is passed the first # argument when the method is called def call_me(self): print('I am the call_me method from the JoeMeth...
0ce8101be0c881b23a0a5f8e9d621f76f8b9e398
thomasbrockmeier/learn_more_python_the_hard_way
/exercise_7_grep/grep.py
1,336
3.71875
4
""" grep """ import argparse import re def outer_grep(args): for filename in args.filenames: if len(args.filenames) > 1: print(filename, end='\n\n') grep(filename, args.pattern) def grep(filename, pattern): with open(filename, 'r') as fh: for line in fh.readlines(): ...
506d8ffae7536670d8952a1e43d57b5047aa3757
darcosubin/4parthpyth
/range.py
97
3.796875
4
#!/usr/bin/env python a=['1st','2nd','3rd','4th','5th'] for i in range(len(a)): print i, a[i]
79985d3960e700f1aa2ac78b4f50cf33a9b74acc
WendingLin/Leetcode
/035_Search Insert Position.py
358
3.734375
4
#35. Search Insert Position class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ pos=0 while pos<len(nums): if target<=nums[pos]: return pos else: ...
e31c872d555958b9c5d987b62bfe792a265a775f
WendingLin/Leetcode
/057_Insert Interval.py
3,838
4
4
#57.Insert Interval # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval ...
3e6ebe03859d8e8c9c508df7192ce22c08f35a60
MccDev260/File_Sort
/script.py
608
3.515625
4
import os.path import shutil folder_path = " " # Invert slashes in folder path files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))] for file in files: folder_name = file.split(' ')[0] # Use this to choose how to sort files new_path = os.path.join(folder_path, folder_n...
566946645bd44e94bafe916c9e2f0aeadd4b1cb5
mjayfinley/Conditions_and_Functions
/EvenOdd/EvenOdd.py
220
4.3125
4
numberInput = int(input("Please enter a number: ")) if numberInput == 0: print("This number is neither odd or even.") elif numberInput %2 == 0: print("This number is even") else: print("This number is odd")
48043fe0b1ae5a8c178fad6657b168463b8535c3
rowillia/advent2020
/python/day1/day1.py
857
4.09375
4
import math import sys from typing import Iterable from typing import Iterator from typing import Tuple def two_sum(values: Iterable[int], target: int) -> Iterator[Tuple[int, int]]: values_as_set = set() for value in values: if target - value in values_as_set: yield value, target - value ...
41aa06a709d4b9b4d7a2175951474821bba8bb5a
JacobMacInnis/blackjack
/deck.py
525
3.53125
4
import random from variables import suits, ranks from card import Card class Deck: def __init__(self): self.deck = [] for suit in suits: for rank in ranks: # Create the Card Object created_card = Card(suit,rank) self.deck.append(cre...
12e5c3c6934960555e7149081a4eea705a87d9b0
ManojShankar86/first-gui-code
/calcy.py
3,068
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon May 4 13:40:27 2020 @author: Vinay """ #creating a calcy from tkinter import * import parser root = Tk() root.title("manoj_calcy") #adding entry display = Entry(root) display.grid(row=1, columnspan=6, sticky=W+E) #getting input from user i = 0 d...
75b15782490362266f21ca535379443c90744428
adahan12/home_works
/lesson2.py
1,005
3.828125
4
#Условные конструкции и Операторытсравнения, Циклы # svetofor = 'off' # # if svetofor == 'green': # print('Go') # elif svetofor == 'yellow' or 'red': # print('attention') # else: # 'look at situation' # if 0: # print("этот обьект правда") #and or not a = 2 and 3 print(a) #number = 100 cleaned_roo...
fa78555a935bbb5d7989e9d87a1b4a6057be4bbc
sarahwan/cc_tools
/part_2_read_test_json.py
1,176
3.625
4
import test_data import json #Creates and returns a GameLibrary object(defined in test_data) from loaded json_data def make_game_library_from_json( json_data ): #Initialize a new GameLibrary game_library = test_data.GameLibrary() # Iterates through each game within json_data for key in json_data: ...
222ea5650f62c19504934c075a6dbf4c0580bf72
ThreatConnect-Inc/threatconnect-playbooks
/apps/TCPB_-_Expressions/src/smartdict.py
2,260
3.59375
4
# -*- coding: utf-8 -*- """Smartdict -- smart dictionary for formatting strings""" from string import Formatter from attrdict import AttrDict __notfound__ = object() class SmartDict: """Smart dictionary object""" def __init__(self, namespace: object, valuedict: dict = None, default=__notfound__): "...
13e33de7db1512bd4d62abc820ff2766efee7f5a
IbiliAze/Code
/test2.py
354
3.84375
4
def multiply(a, b): x =a*b # print(x) multiply(5, 6) class Human: gender = '' age = '' height = '' def eat(self): print('i can eat') def walk(self): pass insan1 = Human() insan1.gender = 'female' insan1.height = '2m' insan1.eat() x=1 # while x > 0: # x = x+1 # print(x) def te...
3ed11587bb9984c9329bd2ab3f75b01e0d052c3f
freekklein/ProjectEuler
/Problem25.py
292
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 26 20:23:03 2018 @author: Freek """ temp = [] temp.append(1) temp.append(1) while len(str(temp[-1]))<1000: temp.append(temp[-1]+temp[-2]) print('Index of first term in Fibonacci sequence to contain 1000 digits: %s' %str(temp[-1])[0])
7d0db52529c398cfdb9dc79c5f9a0dc488359c3c
freekklein/ProjectEuler
/Problem80.py
523
3.75
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 2 20:33:23 2018 @author: Freek """ import decimal decimal.getcontext().prec = 101 def square_root(n): return sum(decimal.Decimal(n).sqrt().as_tuple()[1][0:100]), len(decimal.Decimal(n).sqrt().as_tuple()[1]) temp = [] for i in range(1,101): sum_sqrt_i, len_sqrt...
e543c9f82cdda52353ce7b8c2ed00ac6047c110d
Nikll1010/MyPython
/Mylesson/python基础练习/005.py
353
3.5
4
class A: def __init__(self, size=10): self.size = size # return self.size def getsize(self): return self.size def setsize(self, value): self.size = value def delsize(self): del self.size x = property(getsize, setsize, delsize) temp = A(10) temp = int(input(...
be888ab8fe274243816a546cc63904e1abd1e369
willliu1995/ud120-projects
/outliers/outlier_cleaner.py
1,162
3.828125
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
513ceb69214365a083143108accc5e6a1f05523f
MuriloACassiano/Graphs
/1000.py
4,218
3.765625
4
from random import * #classe generica para trabalhar com fila #o espaço em memoria alocado cresce de acordo com o uso class QUEUE: sizeDefault = 2 def __init__(self): self.queue = [None]*QUEUE.sizeDefault self.size = 0 self.front = 0 def leng(self): return self.size def is_empty(self): return self....
a73f1008e48dfa6d13e7481ebb4f795e272fa773
artliou/ucb
/cs61a/lab/lab01/lab01_extra.py
738
4.21875
4
"""Coding practice for Lab 1.""" # While Loops def factors(n): """Prints out all of the numbers that divide `n` evenly. >>> factors(20) 20 10 5 4 2 1 """ "*** YOUR CODE HERE ***" a = n while a > 0: if n % a == 0: print(a) a = a - 1 def fal...
a842a47c178a57c5199af578d82ae76a4f5dd19a
gulamrabbanii/Box-Colouring-Puzzle
/Col-Puzzle.py
956
3.90625
4
def summer(a,b,c): result = a+b+c return result def minPrice(cost): List = [] n = len(cost[0]) print "Please confirm that the number of columns in your input is -", n for i in range(n): for j in range(n): if (i == j): continue else : ...
e87a79a8126118ae26f7a60c8bb1dd703b6c3164
nicolasque/mi-primer-programa
/wile.py
236
3.875
4
numero_inicia = 2000000 while numero_inicia > 0: print(numero_inicia) if numero_inicia % 2 == 0: print("este numero es par") else: print("este numero es inpar") numero_inicia -= 1 print("he terminado")
c53218c751be719a252aa543699c12709dcc7722
nicolasque/mi-primer-programa
/Lista_de_tipos.py
324
3.90625
4
lista_datos = [3,4,4,"hola",8,"como","estas"] lista_string = [] lista_numeros = [] for dato in lista_datos: if type(dato) == str: lista_string.append(dato) else: lista_numeros.append(dato) print("la lista de letras es{}".format(lista_string)) print("la lista de numeros es{}".format(lista_numer...
694eaf0d045c223750d779469f95fe3b4aabbc91
rehammetwally/Chicken-Swarm-Optimization
/CSOAlgo.py
23,026
4.375
4
import numpy as np import math import random ''' The Fitness Function Defines The Fitness of the indiviual in the Group. The Group's Leader ie Rooster is the most Fittest in The Group to Which it Accounts as the Reason ''' # Defining the Total Noumber of Features in the Dataset Dn = 32 def fitness_function (x): ...
e4fac1b8e64801e91d0be5bd6ef1a44ee49d8425
mcmachado/gridworld-lib
/gridworld.py
13,418
3.578125
4
# Author Marlos C. Machado import sys import numpy as np class GridWorld: _str_mdp = '' _num_rows = -1 _num_cols = -1 _num_states = -1 _matrix_mdp = None _adj_matrix = None _reward_function = None _use_negative_rewards = False _curr_x = 0 _curr_y = 0 _start_x = 0 _sta...
0455377f465308123226192f7d2bb8fafdb496bd
tomclose/prescons
/example.py
111
3.515625
4
print("hello world") def fn(x): if x > 0: print(x) else: raise Exception fn(1) fn(-1)
4bf95784f9344a328e8032c2a9339693cb4c6ee6
Coliverfelt/Aulas_Python
/Aula007.py
810
4.15625
4
n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro: ')) soma = n1 + n2 subtracao = n1 - n2 multiplicacao = n1 * n2 divisao = n1 / n2 divisaointeira = n1//n2 exponenciacao = n1**n2 resto = n1 % n2 print('A soma entre os valores {} e {} vale {}'.format(n1, n2, soma), end='. ') print('A subtração entre os...
9de5e307d1be244862dff905d7a605acff612209
MilkShakeYoung/LoanCalculator
/loan_calculator.py
667
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 7 21:22:31 2018 @author: zhuyue """ # HouseLoanCalculator/Unit: Ten Thousand import numpy as np Loan_year = 30 Price_house = 278 Price_agency = 1.3 Price_DownPayment = 200 Area = 94 Rate_NotOnyOne = 1/100 Rate_loan = 4.9/100 Price_tot...
5efaebf6d33dfe10e000441df41c8456e6312bae
pbmchc/scientific-computing-projects
/01-arithmetic-formatter/arithmetic_arranger.py
2,325
3.640625
4
from constants import ADDITION_OPERATOR from arithmetic_problem_validator import validate_arithmetic_problems ARRANGEMENT_OPERATOR_PART_LENGTH = 2 ARRANGEMENT_PROBLEM_SEPARATOR = ' ' ARRANGEMENT_RESULT_SEPARATOR = '-' def arithmetic_arranger(problems, evaluate_problems=False): error = validate_arithmetic_prob...
ae317e21587bde506ae5c5c58a5d2b9448c13be6
Nereya/ca216
/CA216_OS/sleepingBarberTemplate.py
1,729
3.71875
4
import threading import time import random CUSTOMERS = 256 BARBERS = 3 CHAIRS = 15 ARRIVAL_WAIT = 0.5 def wait(): time.sleep(ARRIVAL_WAIT * random.random()) class Barber(threading.Thread): condition = threading.Condition() customers = [] should_stop = threading.Event() def run(self): whi...
d8caad591e046fd47bbbe1a630244d8c72c690c6
mzhang00/SoftDevWork
/fall/18_db-nmcrnch/stu_mean.py
2,420
3.890625
4
#Hong Wei Chen and Michael Zhang (Team Nonprofit) #SoftDev pd1 #K18 -- Average #Oct 10 2019 import sqlite3 #enable control of an sqlite database import csv #facilitate CSV I/O DB_FILE="discobandit.db" db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create c = db.cursor() command = "CREATE TABL...
8997a9aaec1536ed1ee513a5680c368bc6f059d1
Kaurdim/python-labs
/L04_Math/L10_04_6.py
329
3.984375
4
def all_sum(): sum = 0 a = 0 while True: a = int(input('a=')) if a == 0: break sum += a print('Сумма =', sum) def all_sum2(): sum = 0 a = 1 while a != 0: a = int(input('a=')) sum += a print('Сумма =', sum) # all_sum() all_sum2()
882a2bd5e0ab761353286e9c0ba1a0e3cf11694f
rouzbeh/billboards
/billboard.py
4,287
4.28125
4
from sys import argv class Billboard: def __init__(self, line): fields = line.split(' ') self.width = int(fields[0]) self.height = int(fields[1]) # We only need to care about lengths of words self.word_lengths = [len(s.rstrip()) for s in fields[2:]] def __fits(self, fon...
b5b75640b6b5ed578661047de14a5ab9f0847f5f
shashank793/Python-3-BootCamp-Solution
/OOP Challenge/bank_account.py
834
3.671875
4
class Account(): def __init__(self,owner,balance): self.owner = owner self.balance = balance def deposite(self,amount): self.balance = self.balance+amount return print("Deposite Accepted") def withdrawl(self,amount): if amount <= self.balance: self.balan...
457385162d107437a82f0d3586af72f3d042463e
shashank793/Python-3-BootCamp-Solution
/challenging problems/countprimes.py
430
3.84375
4
def count_primes(num): print("Here") count = 0 for val in range(1,num+1): if val > 1: if val == 2: count+=1 for n in range(2,val//2+2): # print(n) if (val%n) == 0: break else: ...
330ff60fc2ced6d8bc78c2f7f989d41eb101e079
shashank793/Python-3-BootCamp-Solution
/statement solution/2ndqn.py
76
3.5
4
print([i for i in range(0,11) if i%2 == 0]) #or print(list(range(0,11,2)))
9e860dd6d3d4ff21feeeb1be329c70587d1392ef
mayukh45/note_maker
/note_maker.py
491
3.546875
4
import pyperclip from file_writer import makenotes def main(): print("Enter name of the file :") name_of_file = input() f = open(name_of_file + ".txt", 'w') f.close() pyperclip.copy("") print("Press CTRL+C to stop") #fun() boo=True try: while boo: boo = makenot...
284a9aa926915f180b1dd3639cf616b06d32c665
sherryyjiang/sea-c34-python
/students/SherryJiang/session04/mailroom.py
1,781
4.0625
4
#Mail Assignment: pseudocode donation_amount = {'Anna': 300, 'Michael':200, 'Kevin':200} donation_times = {'Anna': 4, 'Michael':2, 'Kevin':1} answer = raw_input("Choose 'Send a Thank You' or Create a Report' ") if answer == "Send a Thank You": full_name == raw_input("Please input a Full Name") if full_name =...
c08ff7b603ec356785eb7fcadad618f81891db01
npkfrolov/Python_homework
/Основы_Python_Мария_Андреева/lesson6/homework_6_1.py
1,328
4
4
"""Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). Атрибут реализовать как приватный.В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый. Время перехода между режимами должно составлять 7 и 2 секунды. Проверить работу пример...
9a253e5a2439e99c1451d6476a5776712d348cd8
npkfrolov/Python_homework
/Основы_Python_Мария_Андреева/lesson6/homework_6_5.py
1,368
4.03125
4
"""Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер). В каждом из классов реализовать переопределение метода draw. Для каж...
6ad40b731d340dca1c0debec8befd3b0838e19af
npkfrolov/Python_homework
/lesson5/homework5_5.py
820
3.90625
4
"""Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. """ my_list = [1231, 345, 567, 788] with open("homework5.txt", "w") as file: file.write(" ".join(map(str, my_list))) with open("homework5...