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
f695ffe5b88b3741045726c2eb462ec77e0ca15d
austinbrodeur/526_a2
/test_enroll.py
3,389
3.625
4
from unittest import TestCase from enroll import Enroll class TestEnroll(TestCase): enroll = Enroll() def test_check_username_valid(self): """ This test checks various usernames to ensure they're being properly checked. """ self.assertTrue(self.enroll.check_username...
9f60c2a26e4ea5bf41c310598568ea0b532c167b
Rajeshinu/bitrm11
/4.Stringcount.py
231
4.25
4
"""Write a program that asks the user for a string and returns an estimate of how many words are in the string""" string=input("Please enter the string to count the number of words in the string\n") c=string.count(" ") print(c+1)
27ddeff64180b9294795aa3434cf55dc5fd674ee
Rajeshinu/bitrm11
/13.Listsorting.py
915
4.0625
4
"""Write a program that:1) reads integers from the user and 2) stores them in a list. 3) Your program should continue reading values until the user enters 0. 4) Then it should display all of the values entered by the user (except for the 0) in the same line 5) display all of the values entered by the user in order fro...
42bd0e1748a8964afe699112c9d63bc45cd421f3
Rajeshinu/bitrm11
/8.Numbersformat.py
347
4.125
4
"""Write a program that asks the user for a large integer and inserts commas into it according to the standard American convention for commas in large numbers. For instance, if the user enters 1000000, the output should be 1,000,000""" intnum=int(input(print("Please enter the large integer number : "))) fnum=format(...
e388eff4922fd282ee1eac24380cf591c9da00f9
cloudjyk/GIT_R2L
/defFun.py
395
3.890625
4
# -*- coding: utf-8 -*- def my_abs(x): if not isinstance(x, (int, float)): #参数检查 raise TypeError('bad operand type') if x >= 0: return x else: return -x print(my_abs(-2),my_abs(1)) import math def move(x, y, step, angle): nx = x + step * math.cos(angle) ny = y + step * math...
ee69295918ff8d04c3f79e00443f5378be5ad1b0
cloudjyk/GIT_R2L
/4test.py
383
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Student(object): """docstring for Student""" def __init__(self, name): # super(Student, self).__init__() self.name = name def __str__(self): return 'Why do you wake me up? I\'m %s' % self.name __repr__ = __str__ if __name_...
e1ef1866519e852ee2917d25391a7ff8cbd4e19d
cloudjyk/GIT_R2L
/defHSG.py
456
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class HSG(object): """docstring for HSG""" def __init__(self): self.x = 9 def power(self): return self.x * self.x a=HSG() print(hasattr(a,'x')) print(hasattr(a,'y')) setattr(a,'y',12) print(hasattr(a,'y')) print(getattr(a,'x')) print(getattr(a,'...
537f861c889724af3cadd7bd0c71aedb76a526e4
cloudjyk/GIT_R2L
/HW_week.py
1,926
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class WEEK(object): """d*nametring for WEEK""" def __init__(self, name, members, *n): # super(WEEK, self).__init__() # if isinstance(name,int): # print(list(self.__members__.keys())[name]) # return self.name=name ...
0d6d1a2b6d7f2a0c79983cbd2b8763a603cb90cd
cloudjyk/GIT_R2L
/checkPeoperty.py
1,229
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # class Student(object): #rgular one #rgular one # def get_score(self): # return self._score # def set_score(self, value): # if not isinstance(value, int): # raise ValueError('score must be an integer!') # if value < 0 or value...
d2b22c1fcd17c534d31174bd40857fc2d6add07b
cloudjyk/GIT_R2L
/test9.py
537
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # import pickle # d = dict(name='Bob', age=20, score=88) # print(pickle.dumps(d)) # with open('test.txt','wb') as f: # pickle.dump(d,f) # with open('test.txt','rb') as f: # c=f.read() # print(c) # print(pickle.loads(c)) import json class Stu(object): "...
50531ecdd319b058d9c2fe98b17a76a1392f85bf
Aqib04/tathastu_week_of_code
/Day4/p1.py
306
4.21875
4
size = int(input("Enter the size of tuple: ")) print("Enter the elements in tuple one by one") arr = [] for i in range(size): arr.append(input()) arr = tuple(arr) element = input("Enter the element whose occurrences you want to know: ") print("Tuple contains the element", arr.count(element), "times")
bef3a1c4e409e8cb4a839bbc029c0544e7c5b672
Aqib04/tathastu_week_of_code
/Day3/3.py
118
4.0625
4
s = input('Enter the string:') f = '' for i in s: if i not in f: f += i print("After remove duplicate",f)
4d39b4b1e0d28374f5dbdf455db1e223aa48dc3a
petrewoo/Trash
/ex_iterator/p1.py
439
4.125
4
#!/usr/bin/env python # -*- encoding: utf-8 -*- class reverse_iter: def __init__(self, l): self._l = l def __iter__(self): return self def next(self): if len(self._l): return self._l.pop() else: raise StopIteration if __name__ == '__main__': ...
3189c51536b8c0f065dcbcedc80afc3d1058902a
jskescola/calc_Viagem
/viagem.py
366
3.59375
4
print('----Calculo Tempo de Viagem de Automovel----') dist = float(input('Insira a Distancia a ser Percorrida: ').replace(',', '.')) vel = float(input('Insira a velocidade media: ').replace(',', '.')) tempo = dist / vel min = (round(tempo % 1, 2)) min = (min * 60) print('O tempo esperado da viagem é de {:.0...
71e27b6a361c4a1cc04149a5c147ffc5010bf8ed
leGenious/Virtualization-Project
/DBSide/DB/min_shell.py
680
3.640625
4
# A minimal SQLite shell for experiments import sqlite3 import pprint con = sqlite3.connect("data.db") con.isolation_level = None cur = con.cursor() buff = "" print("Enter your SQL commands to execute in sqlite3.") print("Enter a blank line to exit.") while True: line = input() if line == "": break...
66d32047d9bc3417e8432637e93859e8a9c9bcc8
rainman011118/python
/matrix.py
249
3.984375
4
import numpy as np a = int(input("Enter the no. rows: ")) b = int(input("Enter the no. cols: ")) print("Enter the no. in a single line separated by space: ") val = list(map(int, input().split())) matrix = np.array(val).reshape(a,b) print(matrix)
f393e5d83832c85971bc2f3798d73b48c6448b03
rainman011118/python
/ppp.py
522
4.09375
4
tuple1 = ('a', 'p', 'p', 'l', 'e') print(tuple1) print(tuple1.count('p')) my_list = list(tuple1) print(my_list) tuple2 = tuple(my_list) print(tuple2) #unpacking ########## name_tuple = "Jonny", 37, "London" a, b, c = name_tuple # Can be done directly also (without the need for 'name_tuple') print(a, b, c) #NOTE: th...
c99ebc26aea2e6b3914b76ab6e2ef1724f63195c
rainman011118/python
/fileread.py
729
3.671875
4
"""Using the 'with' statement which automatically closes files. I have added a try/except block too which adds more checks to it. """ try: with open("/home/rain/cfolder/file.txt", "r") as file: #print out all lines(includes \n): #for line in file.readlines(): # print(line) #Str...
39966783180a9741b16b00959e128ae38131fb05
rainman011118/python
/fileread2.py
584
3.5
4
with open("/home/rain/Testfolder/BBB.txt", "r") as file: # 'file.read' and 'line in file' are both very similar ############################## # contents = file.read() # print(contents) # for line in file: # line = line.strip()# gets rid of the '\n' # print(line) # 'readlines' turns it into a...
f01029c42df49220108966f7603d34e16b6a3e29
nbstrauli/allele_frequency_trajectory_sim
/scripts/get_sim_parameters_foreach_allele_cluster.py
11,580
3.703125
4
import sys import os import itertools import math def make_catalogue(allele_freq_matrix_dirpath, output_dirpath): """ This script simply takes the matrices of allele frequencies and takes each entry in the matrix and turns those entries into a long catalogued list of alleles and their frequency information. Ea...
c460fe991dcd2c9777727fa33464b4a0962d5426
vikfer/Rubik-s-Cube
/rubixtreesearch.py
623
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 20 16:49:15 2019 @author: vpfernandez """ """ searchtree goal: if 2 possibilités 0 = [] 1 = [1] 2 = [2] 3 = [1,1] 4 = [1,2] 5 = [2,1] 6 = [2,2] 7 = [1,1,1] .... """ import math import numpy as np def logn(x,base): try: return math.l...
658f7df261c3892c83909a4c0f6e20ad1a00640f
sriwiwat/python
/18_สอนไพธอน Python 3 การใช้คำสั่ง if ในการตรวจสอบเงื่อนไข ตอนที่ 2/condition2.py
918
3.8125
4
def ticket(age): if age <= 5 : return 0 else: return 100 def ticket2(age): if age <= 5 or age >= 60 : return 0 else: return 100 def ticket2a(age): return 0 if age <= 5 or age >= 60 else 100 #ternary def ticket3(age, is_local): if (age <= 5...
81e2d3e2905b05ba596135a3ac9d7bb153740ea1
royluo123/techstudy
/pathon/test/io.py
935
4.03125
4
#!/usr/bin/python # Filename: using_file.py import pickle as p #import pickle as p shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = open(shoplistfile, 'w') p.dump(shoplist, f) # dump the object to a file f.close() del ...
50279e49d5da2067745efc4a1f8dd305251f378b
royluo123/techstudy
/pathon/test/geturl.py
1,858
3.5
4
#导入urllib库,python访问网页必须库 import urllib import urllib.request #时间类库 import time #定义一个URL数组用来存放捕获的URL地址,也就是需要爬的文字地址路径 url = [''] * 50 #定义link变量,用来记录第几个URL地址 link = 1 #循环捕获博客目录第一页所有的文章链接,并下载 #定义con变量来存储urllib.urlopen打开韩寒博客的目录地址,特别注意下'+str(page)+',用来变化每一页目录地址的 con = urllib.request.urlopen('http://blog.sina.com.cn/s/art...
8752f9e01f91ffec9a48108bd23bc61551dfb803
lalitgarg12/MITDeepLearning
/Getting Started with Tensorflow 2/Week1 - Sequential API/02HandDigit.py
4,234
3.890625
4
#Package Imports import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.layers import Dense,Flatten,Conv2D,MaxPooling2D from tensorflow.keras.models import Sequential mnist_data = tf.keras.datasets.mnist (train_images, train_labels),(test_images,test_labe...
d683fa61c0bdf82d366a615e0fe001b26ca2d556
xhnatiuk/Sorting_Visualized
/src/graph_strategy.py
4,763
4
4
import math import random from typing import List from abc import ABC, abstractmethod class GraphStrategy(ABC): """ Interface that declares contract for concrete graph strategy classes. """ @abstractmethod def generate_values(self, quantity: int, maximum: int) -> List[int]: """ Ge...
058d1ae6fa21662f7bac3d3e05ef0aedfdbe14b2
gneelimavarma/practicepython
/C-1.19.py
340
4.4375
4
##C-1.19 Demonstrate how to use Python’s list comprehension syntax to produce ##the list [ a , b , c , ..., z ], but without having to type all 26 such ##characters literally. ##ascii_value = ord('a') ##print(ascii_value) i=0 start = 97 ##ascii of 'a' result = [] while(i<26): result.append(chr(start+i)) i+=1 p...
c616cf1c5294f96d61a46ea4fc3c33f4ae4fdf44
AndreaPepe/algoritmi-studio
/Data Structures/Calendar Queue/LinkedList.py
1,056
3.78125
4
from OrderedList import OrderedList from ListNode import ListNode class SinglyLinkedOrderedList(OrderedList): def __init__(self): self.head = None self.size = 0 def insert(self, prio, element): current_node = self.head previous_node = None node = ListNode(prio, element)...
3d32c7dca70b48823ab57061e3d43e677b2c54b6
AndreaPepe/algoritmi-studio
/Data Structures/single_List.py
3,367
3.5625
4
from collections.abc import Container from collections.abc import MutableSequence class ListNode(Container): def __init__(self,data): self._data=data self.next=None # unico puntatore al successivo nodo @property def data(self): return self._data @data.setter def data...
cfbcfbce5caf18b9fd8e72ccac386d3fb08cd7f5
AndreaPepe/algoritmi-studio
/Graphs/graph_test.py
374
3.515625
4
from Graph_dictionary import Graph graph=Graph() for u,v,w in [('a','b',3), ('a','d',2), ('b','c',5), ('c','d',9), ('c','e',1), ('d','e',4)]: graph.insertEdge(u,v,w) graph.insertNode('f') for u in graph.vertices(): print(u,"-->",graph.adj(u)) graph.removeEdge('a','d') graph.deleteNode('e') print('\n') for u...
effe70fb4b85d123a588b0d42b69ed8b99d8c94d
xavierpinho23/Music_DataBase
/Part2/Trabalho1_parte2_BDAI/Entry.py
958
3.828125
4
import User import datetime def loggin(): print("Logging in\n") username = input("Username: ") password = input("Password: ") user = User.search_user(user_name=username) try: if user[2] == password: return user else: return None except Exception as erro...
47ed93f911025925d87b8566f9a9596b3a7051de
dariox2/CADL
/session-4/l4b01-deepdreaming.py
35,874
4.28125
4
# # Lecture 4 - Visualizing Representations # # Deep Convolutional Networks # Deep Dreaming # # # Introduction # # So far, we've seen that a deep convolutional network can get very # high accuracy in classifying the MNIST dataset, a dataset of # handwritten digits numbered 0 - 9. What happens when the number # of ...
e5b48f4c87fc618b35f946deb519e112f075dd25
BenHesketh21/QA-Academy-Training
/List_Dictionarys.py
423
3.53125
4
sports = ["football", "rugby", "cricket", "darts"] sports.append("basketball") sports.append("baseball") sports.insert(0, "softball") del sports[4] print(sports[0:5]) string = "We will be the best Python Developers the world has ever seen!" new_string = string.replace("Python Developers", "Cloud Engineers") c...
e0d9894638d0428c986b3211b1f57798468d8915
BenHesketh21/QA-Academy-Training
/Powers.py
163
4.125
4
number1 = float(input("First Number: ")) sqr = number1 ** 2 print(sqr) number2 = float(input("To the power of: ")) answer = number1 ** number2 print(answer)
3dd10ef918bd3d61340062ef4676a8b50bcc4556
BenHesketh21/QA-Academy-Training
/Near.py
805
3.8125
4
word1 = input("First Word: ") word2 = input("Second Word: ") def near(string0, string1): for j in string0: if string0.count(j) == 1: new = string0.replace(j, "") print(new) if new == string1: return True else: cont...
f61f0bc1d93533b41c786239e09ab016d0d55e3c
jg76379/Weather-forecast-project
/forecast.py
524
3.546875
4
class Forecast: """A class to create forecasts""" def __init__(self, forecast_source, date_of_forecast, date, high, low): self.forecast_source = forecast_source self.date_of_forecast = date_of_forecast self.date = date self.high = high self.low = low class Historic_observations: """A clas...
043785422cc7d54e373dc4df62c043bf1711dd65
randiaz95/Learn-Python-the-Hard-Way
/server.py
1,502
3.609375
4
from os.path import exists from os import makedirs class Server(object): def __init__(self, content, command): if not exists("data"): makedirs("data") self.filename, *data = content.split("-") self.filename = 'data\\'+self.filename self.data = ''.join(data) ...
551d1a391431bc80d83e02eb5b91242d924e0ef9
lcchiang/Artificial-Intelligence-Course
/Lab 0/lab0.py
8,441
3.65625
4
# MIT 6.034 Lab 0: Getting Started # Written by jb16, jmn, dxh, and past 6.034 staff from point_api import Point #### Multiple Choice ########################################################### # These are multiple choice questions. You answer by replacing # the symbol 'None' with a letter (or True or False), corres...
b6f9a0ddc8ed97c84c91747f4b7ccb8218c2283a
lcchiang/Artificial-Intelligence-Course
/Lab 5/lab5.py
8,272
3.609375
4
# MIT 6.034 Lab 5: Bayesian Inference # Written by 6.034 staff from nets import * #### Part 1: Warm-up; Ancestors, Descendents, and Non-descendents ############## def get_ancestors(net, var): "Return a set containing the ancestors of var" ancestors = net.get_parents(var) if ancestors != {}: ...
c4293f543850649dd6e39e1d24d276aaf3e068f2
victenna/Multiple-Turtles
/Multiple Turtle2.py
585
3.53125
4
import turtle,time turtle.bgcolor('red') turtle.tracer(2) t1 = turtle.Turtle('turtle') t2 = turtle.Turtle('turtle') def multiple(turtle,clr,size): turtle.color(clr) turtle.shapesize(size) turtle.pensize(4) turtle.left(90) turtle.speed(10) multiple(t1,'blue',2) multiple(t2,'gold',1) X=10 ...
944e1bb78c3e5010c396f9182a303022386cb109
umairtariq00/AI-UmairT
/Assignment 2 - Umair Tariq (1).py
2,499
3.828125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: 8 + 34 / 5 - 7 + 45 * 4**5 + 12 /35 + (23 -12) * 34 + 98 **3 - 23 - 98 / 32 * (2 * 7) - 22 + 21 * 45 - 2 - 1 # In[12]: a = 3 if a > 12: print('yes greater value') else: print('less value') # In[ ]: # In[13]: a = 3 if a < 12: print('yes greater ...
e826f572a3949735a288678ae8e87eea283c315c
bokal2/algoexpert-python
/1.4. doubly- linked-list-construction.py
8,914
3.578125
4
# Feel free to add new properties and methods to the class. # noinspection PyPep8Naming class Node: def __init__(self, value): self.value = value self.next = None self.prev = None def __repr__(self): return str(self.value) def get_prev_value(self): if self.prev is N...
b74ae29f0d627def17db23aa938bc7ce560a0ddf
bokal2/algoexpert-python
/3.4. shifted-binary-search.py
1,398
3.765625
4
def shiftedBinarySearch(array, target): # Write your code here. pivot = find_pivot(array, 0, len(array) - 1) if target == array[pivot]: return pivot elif target < array[0]: array = array[pivot + 1:] idx = binary_search(array, 0, len(array) - 1, target) if idx != -1: ...
7e4de8afd445b47ee227ae17ade8f7efddd9bdb9
bokal2/algoexpert-python
/3.3. reverse-linked-list.py
284
3.765625
4
def reverseLinkedList(head): # Write your code here. previous = None current = head while current: nxt = current.next current.next = previous previous = current if nxt is None: break current = nxt return current
4195b70fb68c585767702cf31041ee98535aea48
ianbel263/geekbrains_python
/lesson_1/task_5.py
920
4.125
4
company_income = int(input('Введите прибыль фирмы: ')) company_costs = int(input('Введите издержки фирмы: ')) if company_income > company_costs: print('Фирма работает с прибылью') company_profit = company_income - company_costs profitability = round(company_profit / company_income * 100, 2) print(f'Рен...
17ccf4eb726a260cc4617a828874ab3b70b0faf4
ianbel263/geekbrains_python
/lesson_7/task_3.py
4,741
3.6875
4
# 3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка. В его конструкторе # инициализировать параметр, соответствующий количеству клеток (целое число). В классе должны быть реализованы методы # перегрузки арифметических операторов: сложение (__add__()), вычитание (__sub__()), умнож...
76901ff6d6d2bc75a9363cd8b6ec03b3d4294c33
ianbel263/geekbrains_python
/lesson_6/task_3.py
1,936
3.921875
4
# 3. Реализовать базовый класс Worker (работник), в котором определить атрибуты: name, surname, position (должность), # income (доход). Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы: оклад и премия, # например, {"wage": wage, "bonus": bonus}. Создать класс Position (должность) на ...
69b360462b331694bb0a08d81af770c49cca8460
nehashekhar/bioinformatics-practice-python
/NucleotideUtils/NucleotideUtils.py
532
3.625
4
def reversestrand(strand): i = len(strand)-1 sr = '' while i>=0: sr = sr + strand[i] i = i-1 return sr def complementstrand(strand): strant = str(strand) sc = '' for nucleotide in strand: sc = sc + complementnucleotide(nucleotide) return sc def complemen...
d461657f9136135edd128144c1e45a5c2904acc0
yc9z/Google-Foobar
/level 1 - re id.py
1,810
3.859375
4
""" e-ID ===== There's some unrest in the minion ranks: minions with ID numbers like "1", "42", and other "good" numbers have been lording it over the poor minions who are stuck with more boring IDs. To quell the unrest, Commander Lambda has tasked you with reassigning everyone new, random IDs based on her Completely ...
2505d09641375db2f1fd6877aa5df40867e4746b
maxwell-sterner/my-projects
/bfs-dfs-rivercrossing/RiverCrossing.py
4,866
4.09375
4
from copy import deepcopy # NOTE: python's default behavior on the assignment operator for objects and dictionaries is to make a shallow copy # (i.e., add a pointer). This is not ideal for what we're doing here. Use deepcopy to make your life easier. class RiverCrossingProblem: def __init__(self): self....
b005319900d958562e4fdd011674135b91054501
JorritWillaert/OptimalConnectFour
/game_functions.py
7,536
3.859375
4
from board import Board from random import randint import cpu class Game(): def __init__(self, player1, player2, size_horizontal, size_vertical): self.player1 = player1 self.player2 = player2 self.size_horizontal = size_horizontal self.size_vertical = size_vertical ...
b141df29527bfe8c7bf61f4532f08829a049bc67
leo-bao47/iteration-1
/iteration.py
1,276
3.828125
4
# Make a local change # Make a local change again # iteration pattern # This is change [a] from home # [1, 5, 7 ,8 , 4, 3] def iterate(list): # standard for loop with range # for i in range(0, len(list)): # print list[i] # for each loop for item in list: print item def add_one(list): for i in range(0, len(...
915ac87382bd85a5f42f7bb24c73ac0666343f4e
denopas/ImageProcessing
/imageprocessing/3.ImageProcessing/3.2.Translation.py
609
3.578125
4
''' # ============================================================================= # Translation # ============================================================================= Translation is the shifting of object’s location. You can take make it into a Numpy array of type np.float32 and pass it into cv2.warpAffine...
a1d90ebaea4c9df0aafe47ca5361e54b2eae019a
denopas/ImageProcessing
/imageprocessing/1.GUIFeaturesInOpenCV/2.Videos_1.py
1,306
3.6875
4
import numpy as np import cv2 ''' # ============================================================================= # CAPTURE VIDEO FROM CAMERA # ============================================================================= Often, we have to capture live stream with camera. OpenCV provides a very simple interface to t...
c8275614a9349a8594c2a07c723e38030145eafa
kamaligeetha/kamaligeetha
/6666.py
169
3.625
4
itr=int(input()) if(itr>1): for k in range (2,itr): if(itr%k)==0: print("no") break else: print(yes) else: print(no)
0396e783aca5febe373e32fc544dead5a5817760
marbor92/checkio_python
/index_power.py
367
4.125
4
# Function finds the N-th power of the element in the array with the index N. # If N is outside of the array, then return -1. def index_power(my_list, power) -> int: pos = 0 index = [] for i in my_list: index.append(pos) pos += 1 if power not in index: ans = -1 else: ...
ed15f0a4cbe60bdb6a8ffa07537e2a6bf261efeb
marbor92/checkio_python
/is_majority.py
242
3.828125
4
# Function checks if the majority of elements are true. def is_majority(items: list) -> bool: t = items.count(True) f = items.count(False) if len(items) == 0 or f == t or f > t: return False else: return True
2c455ec9c2bbd31d79aa5a3b69c4b9b17c25b7a7
whalenrp/IBM_Challenge
/SimpleLearner.py
1,584
4.125
4
import sys import math import csv from AbstractLearner import AbstractLearner class SimpleLearner(AbstractLearner): """ Derived class implementation of AbstractLearner. This class implements the learn() and classify() functions using a simple approach to classify all as true or false """ def __init__(self, trai...
a92e35ab66f340a9a23610109f3852294194e2aa
Tomoschuck/Learning_Python
/Lists_in_Python/List4.py
147
3.5625
4
# Changing values is indexes spam = ['cat', 'bat', 'rat', 'elephant'] spam[1] = 'aardvark' print(spam) spam[2] = spam[1] print(spam)
8d34db2cfaa1469887cea66fd8a39820235a695a
WillDera/Algorithms_In_Python
/strictly_increasing.py
569
3.59375
4
list1 = [1, 3, 2, 4] list2 = [1, 3, 1, 5, 6] def wrong_pair(sequence, k): if 0 < k < len(sequence) - 1: if sequence[k-1] >= sequence[k+1]: return k-1 for i in range(k+1, len(sequence)-1): if sequence[i] >= sequence[i+1]: return i return -1 def strictlyIncreasing(s...
5fe7c8e306b14a70f104324d7d6567dfe96d122e
ammadkhalid31/Python
/reading_file.py
366
3.53125
4
import sys def main(): file_name = "dummy_text.txt" try: file1 = open(file_name,"r") except IOError as e: print("There was an error reading file '{}'.".format(file_name)) print(e.strerror) sys.exit() file_text = file1.read() file1.close() print(file...
f5ed3356e50fbe3589b9c8d24f8dcec7ff5cf534
judeaugustinej/Python3
/Python3_Homework01/zipcheck.py
653
3.6875
4
''' zipcheck.py: validation function for US zip code ''' def zip_errors(z): """ Validate z as either NNNNN or NNNNN-NNNN. :param z: US zip code which is a string :returns: return_type -- description of the return value :returns: None for a valid zip code :raises: Attrib """ l = len...
b476f0b40818a695a1dcc9b6cc0f50ac2bf65650
pammacdotnet/FFRepo
/kepler.py
1,249
3.640625
4
# Ejercicio basado en https://docs.sympy.org/latest/modules/physics/units/examples.html#equation-with-quantities # Sobre Kepler https://en.wikipedia.org/wiki/Johannes_Kepler from sympy import solve, symbols, pi, Eq # Cargamos objetos directos de Sympy # Unidades S.I. from sympy.physics.units import meter, kilogram, s...
2998176aea176d849b5f6034bd91eea1357febba
asrianijainudin/pgame
/pgame-16001/tugas_code7.py
679
3.8125
4
d="Ini Merupakan Perulangan While" # perulangan “while” print(d) x = 0 while (x < 5): # jika x lebih kecil dari 5 maka ulangi # x = x + 1 x += 1 # x + 1 print(" Asriani ") j="Ini Merupakan Perulangan For" # perulangan “for” print(j) for x in range(5): print("Asriani") a="Ini Merupakan Fungsi / Function" # Fun...
0b674904da40b1017b1478e03ea5168e28fe3188
WestonVincze/PythonProjects
/CompleteThePattern/complete_pattern_solution.py
355
4.09375
4
def pattern(n): """Generates a multiline string pattern up to n. Args: n: the stopping point/number of rows for the pattern. Returns: A single string pattern up to 'n'. """ ret = '' for i in range(1, n + 1): ret += ''.join([str(i)] * i) if not i == n: ...
a9532bb9f9ef6515685ad6c7c2170e0627fb0cc8
gaoxizhi/python_practice
/th/area.py
1,213
3.953125
4
# !/usr/local/bin/ python # -*- coding:utf-8 -*- from functools import total_ordering from math import pi """ 类参数校验 """ class Circle(object): def __init__(self, radius): # self.radius = radius self.setRadius(radius) def getRadius(self): return self.radius def setRadius(self,...
cf95564ff2496cd33914d17ae1ad41d7f09c5186
gaoxizhi/python_practice
/read_file.py
441
3.59375
4
""" f = open("D:/nihao.txt") print(len(f.read())) f = open("D:/nihao.txt",'a') f.write("\n结束:高羲之") f = open('D:/nihao.txt') print(len(f.read())) print(f.read()) """ # 使用python库爬取网页并存储在本地 from urllib import request f2 = open("D:/baidu.html", "wb") data = request.urlopen("http://www.baidu.com") # pri...
bcda1f6f442b5219ce52c10c0bf51f59122f212c
benjie13/benjie-lattao
/loops_lattao.py
508
4.25
4
print ("2 to 10") for x in range (2,12,2): print(x) print ("3 to 15") for y in range(3,18,3): print(y) print ("4 to 20") for z in range (4,24,4): print(z) print ("12 to 36") for a in range (12,48,12): print(a) #nested loop sample print ("Multiplication") for y in range (1,11): for z ...
18e4f8c2efe43e9098d436e0dbf02bfc7bf5419f
endremborza/teach-rajk-prog1-2019f
/members/bence/egg-drop.py
722
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[19]: from jkg_evaluators import eggdrop_100floor_2egg # In[26]: def my_solution2(breaks): floor=14 step=13 while breaks(floor)==False: floor=floor+step step=step-1 floor=floor-step+1 while breaks(floor)==False: floor=floor+1 ...
dac06087852b4fb217827bd5c9f9178bbc893b63
ashril/AlgoritmaPermrograman
/16.MaxMin.py
362
3.859375
4
#Input Bilangan array = [] ok = "y" while (ok=="y"): array.append(input("Masukkan Bilangan: ")) ok = raw_input("Lanjut? (y/n) : ") print "Bilangan dalam array adalah: ",array # Cari Max Min max = array[0] min = array[0] for i in range(len(array)): if array[i]>max: max=array[i] if array[i]<min: min=array[i] p...
8b7db1b772c393e027596764c56149f742bbee12
ashril/AlgoritmaPermrograman
/1.Prima.py
239
3.71875
4
bilangan = int(input('Masukkan bilangan = ')) cek = 1 for i in range (2,bilangan): if (bilangan%i==0): cek = 0 if (cek == 0 or bilangan<2): print bilangan,"BUKAN bilangan PRIMA" else: print bilangan,"adalah bilangan PRIMA"
7c41a598abf11eff88eeae72e3b5af7c79ef5e3d
ashril/AlgoritmaPermrograman
/7.CekGanjilGenap.py
150
3.796875
4
bilangan = input("Masukkan bilangan:") if (bilangan%2==0): print bilangan, "adalah bilangan GENAP" else: print bilangan,"adalah bilangan GANJIL"
f34ff3499a7793d3b123f2323a0031fa1ea8cb1f
marsunique/LeetCodeOJ
/CountingBits.py
396
3.515625
4
class Solution(object): def countBits(self, num): List=[] for number in range(num+1): count = 0 while number: remainder = number%2 number = number/2 if remainder: count = count+1 List.append(count...
31c71e18fae03fa4ae4358cc1bffe02936f0c0d6
marsunique/LeetCodeOJ
/ExcelSheetColumnTitle.py
425
3.59375
4
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ res = '' while n: r = n % 26 if r == 0: res = 'Z' + res n = (n-1) / 26 else: res = chr(ord('A') + ...
24b0a69c6711f42e1de040eaeab62b8af8e563ed
marsunique/LeetCodeOJ
/ReverseString.py
882
3.765625
4
class Solution(object): def reverseString(self, s): slist = list(s) l = len(s) for i in range(0,l/2): # temp = slist[i] # print 'temp: ', temp # slist[i] = slist[l-1-i] # print slist[i] # slist[l-1-i] = temp slist[i] = c...
2b5b15b60d7e675542dd71161311dee9681c470c
marsunique/LeetCodeOJ
/BinaryTreeMaximumPathSum.py
692
3.6875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.maximum...
c1cdf908501bb5a1220cc8757371cd3e84e794f5
marsunique/LeetCodeOJ
/FindPeakElement.py
818
3.671875
4
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return None return self.helper(0, len(nums)-1, nums) def helper(self, l, r, nums): mid = (l+r)/2 if (mid-1 < 0 or nums[...
a24b668bc749c7fe1de509351ed64d5616d28854
marsunique/LeetCodeOJ
/ValidParentheses.py
862
4
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ stack = [] for bracket in s: if bracket == '(' or bracket == '{' or bracket == '[': stack.append(bracket) elif stack == []: # facing a '(', '[' or...
4921f45ed1c7a90b87bebfc7bc182afd16783fe2
marsunique/LeetCodeOJ
/ZigZagConversion.py
470
3.671875
4
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ res = [''] *numRows index = 0 for c in s: res[index] += c if index == 0: step = 1 if index ==...
39e49c0cbb7d86b24239bf1866d8751c42db61bb
marsunique/LeetCodeOJ
/SearchInsertPosition.py
812
3.890625
4
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ # Variant of binary search if not nums: return 0 return self.helper(nums, 0, len(nums)-1, target) def hel...
74b32385b7babb0d753ab793182919fb20848e2b
marsunique/LeetCodeOJ
/Subsets.py
600
3.515625
4
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # res = [[]] # for num in nums: # temp = [[],[num]] # res = [sub+s for sub in res for s in temp] # return res res = [[]] ...
4b4a6c2c23258e3a234bcdd0644e11705c273280
marsunique/LeetCodeOJ
/MajorityElement.py
516
3.625
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ # Boyer-Moore Majority Vote Algorithm flag = 0 majority = None for num in nums: if flag == 0: majority = num ...
6f48721005ac6dc248f2378c7aa9d2b83c2a443b
marsunique/LeetCodeOJ
/NumberOfAtoms.py
2,121
3.703125
4
class Solution(object): def countOfAtoms(self, formula): """ :type formula: str :rtype: str """ elements = self.helper(formula) res = '' for key in sorted(elements.keys()): if elements[key] == 1: res = res + key else: ...
cb20b3a1b2b6e74ed2f89cad28a9b5e2fe1bf278
marsunique/LeetCodeOJ
/ChangingCoins.py
1,070
3.71875
4
# Case1: the given amount is 0, the smallest possible number of coins is 0 # Case2: the given amount is smaller than c[i], look up the smallest possible number of coins without using c[i] # Case3: the given amount is greater than or equal to c[i] and changing coins with c[i] # Case4: the given amount is greater than or...
76691ec3f45dd1ccd226a5411a7ca3855d3bba60
pjohalloran/texture-atlas-generator
/src/math/math.py
485
3.8125
4
def is_power_of_two(number): return ((number & (number - 1)) == 0) and number != 0 def next_power_of_two(number): p = 1 while (p <= number): p *= 2 return p # Returns 0 if the two intervals i1 and i2 are disjoint, or the length of their overlap otherwise. def common_interval_length(one_sta...
e41dd6dc633dd3a1e03b04bf53a6db67359784fd
onoGor/GB_python
/task_3_1(2).py
794
4.0625
4
dict_num = { 'zero': 'ноль', 'one': 'один', 'two': 'два', 'three': 'три', 'four': 'четыре', 'five': 'пять', 'six': 'шесть', 'seven': 'семь', 'eight': 'восемь', 'nine': 'девять', 'ten': 'десять' } def num_translate(num_word): num_new = num_word.lower() if num_new in ...
19f2e8921b8d42f1ef12bfb74a366eb14a82c61c
Martyna-Tu/python_example
/GUI.py
1,283
3.65625
4
import tkinter as tk from Data import Stan, Ksiazka class Window(): def __init__(self): self.stan = Stan() self.result = '0' def initWindow(self): window = tk.Tk() title = tk.Label(master=window,text='Witaj w bibliotece!') book_no_label = tk.Label(master=...
d272fde739325284f99d1f148d1603d739d24721
ganesh28gorli/Fibonacci-series
/fibonacci series.py
678
4.4375
4
#!/usr/bin/env python # coding: utf-8 # # fibonacci series # In[15]: # n is the number of terms to be printed in fibonacci series # In[16]: n = int(input("enter number of terms: ")) # In[17]: # assigning first two terms of the sequence # In[18]: a=0 b=1 # In[19]: #checking if the number of terms of...
aef6477c03006ff40a937946213ea05c1ec11106
ta11ey/algoPractice
/algorithms/linkedList_insertionSort.py
1,088
4.3125
4
# Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head. # The steps of the insertion sort algorithm: # Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. # At each iteration, insertion sort removes one element...
61a00b06f3372dedf2e92a37f8109b4bb3496b5b
AkshayGyara/Two-Pointers-2
/removeDuplicates.py
872
3.546875
4
#80. Remove Duplicates from Sorted Array II #Time Complexity : O(n). # Space Complexity : O(1) #Did this code successfully run on Leetcode : Yes #intialised i and j to index 1. then checked if prev element and current are equal if yes incremeant count by 1 else make count as 1 . Then if the count is less than 2 wi...
de223465ab5acb816e9950e6d44596e91d4aeb64
pritishyuvraj/SOC-PMI-Short-Text-Similarity-
/wordSim.py
963
3.5625
4
import math P = "Many consider Maradona as the best player in soccer history" R = "Maradona is one of the best soccer player" def wordSim(P = P, R = R): #P = P.strip().split() #R = R.strip().split() if len(R) > len(P): P, R = R, P common = {} count = 1 for i in P: if i in R: common.setdefault...
1980ed202baa7484a9beefd86d94dd80f65ebb25
howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files
/Livro/cap2/ex2.3.py
123
3.640625
4
h = raw_input("Enter Hours: ") r = raw_input("Enter Rate: ") hours = float(h) rate = float(r) pay = hours*rate print pay
94fc4e9e374bd2aa68e47bb5ad7fef754e713d7c
howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files
/Funções/functions6.py
236
4
4
num = raw_input("Type a number: ") number = int(num) def cube(number): return number ** 3 def by_three(number): if number % 3 == 0: print cube(number) else: print "PEEEEE" by_three(number)
8b9ac54cf15648e5c5bb315fbd2e2d3bcffb5b9c
howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files
/Básicos/PygLatin.py
775
4.4375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #o objetivo deste programa é mover a primeira letra da palavra para o final e adicionar ay. #Dessa forma, a palavra Batata vira atatabay pyg = 'ay' #primeiro define-se ay original = raw_input('Escolha uma palavra: ') #deixa um espaço para colocar uma palavra if len(ori...
bd5436e08499145f809edab802aeeed843f5e07b
howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files
/Funções/functions5.py
195
4.09375
4
phrase = raw_input("Say something please! ") def shout(phrase): if phrase == phrase.upper(): print "YOU ARE SHOUTING" else: print "Can you speak up?" shout(phrase)
307225e7c2100dcc11bf6023dc58613eea9ba1eb
ksyukaksyu/zen_of_python
/main.py
93
3.5
4
mass = range(100) squares = [x**3 for x in mass if x % 3 == 0 and x % 4 == 0] print(squares)
d6ca102b12d1fa15e3ba3157f1ba3c2051c7bfc0
ltsdw/Uri-Online-Judge
/python/iniciante/1133.py
216
4
4
''' title: Resto da Divisão number of the problem: 1133 date: 11/03/2018 author: ltsdw ''' x = int(input()) y = int(input()) if x > y: x, y = y, x for i in range(x, y): if i % 5 == 2 or i % 5 == 3: print(i)
b70a06ef2e7177e90a86ec88326083bcdb6d9b94
ltsdw/Uri-Online-Judge
/python/iniciante/1115.py
405
3.53125
4
''' title: Quadrante number of the problem: 1115 date: 09/03/2018 author: ltsdw ''' while True: x, y = map(int, input().split()) if x and y: if x > 0 and y > 0: print('primeiro') if x < 0 and y > 0: print('segundo') if x < 0 and y < 0: print('terceir...
24eb36adc0f236d5deb0b31acb5bedc82ceb815a
ltsdw/Uri-Online-Judge
/python/ad-hoc/1091.py
639
3.53125
4
''' title: Divisão da Nlogônia number of the problem: 1091 date: 03/05/2018 author: ltsdw ''' while(True): n_casos = int(input()) if n_casos == 0: break else: cord_n, cord_m = map(int, input().split()) for i in range(n_casos): x, y = map(int, input().split()) if x ==...
23d69d6d8d7687a52637bea1dd9ee15fa0a2cc34
NirmalVatsyayan/data_science_pipeline
/data_visualization/matplotlib_examples/03_bar_chart.py
449
4
4
''' A simple bar chart both x and y axis are data input from user If you dont select a color then default color will be used with both bar which will e confusing ''' import matplotlib.pyplot as plt plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one") plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')...