blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8a33360f625abb7f53e12265bef0f5040c5a0b29
Frijke1978/LinuxAcademy
/Python a consise introduction/Module 2/ProblemSet2_6.py
495
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 10 15:27:19 2018 @author: Frijke """ import random def problem2_6(): """ Simulates rolling 2 dice 100 times """ # Setting the seed makes the random numbers always the same # This is to make the auto-grader's job easier. random.seed(431) # d...
fdd668609fcd5bf054e8888d5da465a1a971089a
Frijke1978/LinuxAcademy
/Python 3 Scripting for System Administrators/Working with Environment Variables.py
1,809
4.21875
4
Working with Environment Variables By importing the os package, we’re able to access a lot of miscellaneous operating system level attributes and functions, not the least of which is the environ object. This object behaves like a dictionary, so we can use the subscript operation to read from it. Let’s create a simple...
9de0982fb20f721568401203f94afbcaed95e9fb
belteshassar/AoC-2016
/21/solution.py
1,805
3.65625
4
from itertools import permutations import re def swap_pos(s, x, y): x, y = map(int, [x, y]) x, y = sorted([x, y]) return s[:x] + s[y] + s[x+1:y] + s[x] + s[y+1:] def swap_letters(s, x, y): x, y = sorted([s.index(l) for l in [x, y]]) return swap_pos(s, x, y) def rotate_steps(s, d, steps): ste...
0e7e9e1cfea23a826405a05df0baa5eeef46654f
belteshassar/AoC-2016
/15/solution.py
1,185
3.609375
4
class Disc: def __init__(self, num_pos, start_pos=0): self.n = num_pos self.pos = start_pos % self.n def rotate(self, step=1): self.pos = (self.pos + step) % self.n def __repr__(self): return 'Disc({}, {})'.format(self.n, self.pos) class Sculpture: def __init__(self, ...
7dee2da310e3d673a374eb7a53b75f031efc4be3
zhangyuo/dataStruct
/search_10/bfs.py
1,283
3.8125
4
#!/usr/bin/env python # coding:utf-8 """ # @Time : 2021-02-23 11:08 # @Author : Zhangyu # @Email : zhangycqupt@163.com # @File : bfs.py # @Software : PyCharm # @Desc : 广度优先搜索:先搜索邻居,搜索完邻居再搜邻居的邻居。 """ from tree_3.tree_build.tree_node import TreeNode """ 两个思想: 1、队列不为空,则循环 2、将未访问的邻接点压入队列后面,然后从前面依次访问 图: 0 ...
ae4f4dd83035a836ee69a5ea30ea2b1f976070a7
Complexio/Vistelius_1995_OCR
/_ANALYSIS/qapf/cipw.py
4,540
3.921875
4
import pandas as pd def convert_to_CIPWFULL_format(df, path, dataset_name="Dataset", index_prefix=None, rock_type="P", rock_suite_column=None, normalization=False, return_resulting_df=False): """Converts a pandas DataFram...
5685c738e8a1877d8a713d365ea26fc3d2e8a888
TTwelves/Data-structure-and-algorithm
/1.两数之和.py
1,034
3.671875
4
# # @lc app=leetcode.cn id=1 lang=python3 # # [1] 两数之和 # # @lc code=start ''' 语法 以下是 enumerate() 方法的语法: enumerate(sequence, [start=0]) 参数 sequence -- 一个序列、迭代器或其他支持迭代对象。 start -- 下标起始位置。 返回值 返回 enumerate(枚举) 对象。 实例 以下展示了使用 enumerate() 方法的实例: >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(sea...
747f94f62c9f931bdb9d5856ab846c9bd7fc56d6
dsridhar2012/HelloAI
/NeoMatrix.py
665
3.625
4
#!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(s): firstlast =s.split(" ") first1 = firstlast[0] last1 = firstlast[1] if(first1[0].isalpha()): f1 = first1[0].upper() else : f1 = first1[0] ...
ab524ef086c2b3ba1038af8c5716fef4aa70a753
dgntkn/dgntkn_eski
/python temelleri/cisco/argv.py
304
3.703125
4
import sys numArg = len(sys.argv) - 1 #print (numArg) print (" ") print ("There are " + str(numArg) + " arguments") print (" ") if str(sys.argv[1]) == "-help": print ("this is help message") print ("enter a string, any string") print (" ") else: a = str(sys.argv[2]) print (a)
9c5aff244a7ea01efc495ac0ae6079857e4892d1
faran20/Deep-Learning
/Matrix Arithmetic.py
693
3.71875
4
import numpy as np import time # 10,000 guassian variables in an array with random values a = np.random.rand(10000) b = np.random.rand(10000) # timer value before statement tic = time.time() # vectorized way of matrix multiplication c = np.dot(a,b) # timer value after statement toc = time.time() # output Matrix m...
e7c1e57d0061f37a815fa05ea988deef32bf1bc0
jeen-jos/PythonPrograms
/Code/test.py
709
4.375
4
# Follwoing code shows how to print msg = "Hello world" print(msg) print(msg.capitalize()) print(msg.split()) # Taking inputs from user name = input("enter your name : ") print("Hello ",name) # eval() converts entered text into number to evaluate expressions num= eval(input("Enter the number : ")) print(" The value i...
15e62bb3ecccb67f23b8590b48c383ef361f3a5e
17erca/programacion57
/Sin título14.py
210
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 19 12:30:00 2021 @author: ERCA """ x=int(input('Ingrese el # al que debo contar: ')) y=1 while True: print(y) y+=1 if y>x: break
19800aab13964bf7761b8fb397b464640414c791
17erca/programacion57
/Taller de Variables y Conversiones Python ejercicio 2.py
1,102
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 17 20:53:55 2021 @author: ERCA """ #se pide al usuario que ingrese el tiempo que ha transcurrio t=float(input('Ingrese el tiempo en horas de conducción actual: ')) #Se pide al usuario que ingrese la velocidad actual v=float(input('Ingrese el valor de la velocidad...
2f96946d597fa4bf812d74f7b093cf38ef72a2e3
santilaguna/EDD-alumno
/T4/E.py
818
3.71875
4
from math import inf # As seen at: https://es.wikibooks.org/wiki/Optimizaci%C3%B3n_del_Producto_de_Matrices N = int(input()) sizes = tuple(int(input()) for _ in range(N)) memo = {(i, i): 0 for i in range(1, N + 1)} min_ = inf for diagonal in range(1, N): for row in range(1, N - diagonal): ## mínimo dp ...
82ad7f41debe496d964727796bfa5161ce3b34fe
oksanayolkina/Pulse_rest
/models/book.py
601
3.859375
4
class Book: def __init__(self, title=None, author=None, id=None): self.title = title self.author = author self.id = id def __repr__(self): return "{}:{}:{}".format(self.id, self.title, self.author) def set_id(self, id): self.id = id def get_id(self): r...
eb082d6b77de1fc7442b73bea911b3d3fe20696b
Javaman1138/highland-website
/highland/events/templatetags/tag_lib.py
1,627
3.546875
4
from django import template from django.template.defaultfilters import stringfilter import datetime register = template.Library() TODAY = 'Today' TONIGHT = 'Tonight' YESTERDAY = 'Yesterday' LAST_NIGHT = 'Last Night' TOMORROW = 'Tomorrow' TOMORROW_NIGHT = 'Tomorrow Night' @register.filter(name='human_date') @stringf...
26fee0f2c20d00c6de154cce24f9db61b2466b52
stidf/leet-code-problems
/zigzag-conversion.py
1,134
3.609375
4
numRows = 1 s = "ABC" StringPositionCounter = 0 # reconrds position along input string IndexPosition = 0 # records position in index array for placement of letters DirectionBool = True #true is down, false is up temp = [] output = str() for i in range(numRows): temp.append([]) # creates empty array of numRow s...
b0ebf7f193987eee33b6a645a07e64459c6e16f5
arsummers/madlibs-py
/madlibs/madlibs.py
1,579
3.515625
4
def greeting(): print(""" ********* Hello! Are you ready to play a game of madlibs? ********* """) def get_keys(path): with open(path, 'r') as file: contents = file.read() keys = [] end = None #exists here to be reassigned below bracket_count = contents.count('{'...
a9c7bb5f18b5b109b924e0bd5eb0bc2386e6d0eb
rajiarazz/task-2
/day2/day2.py
343
4.3125
4
#1 ) Consider i = 2, Write a program to convert i to float. i=2 print(float(i)) #2 )Consider x="Hello" and y="World" , then write a program to concatinate the strings to a single string and print the result. x="Hello " y="World" print(x+y) #3 ) Consider pi = 3.14 . print the value of pie and its type. pi=3....
dce0e3ca1db9d2b724153ac366f675c9e5d63ba1
deepakdashcode/file_handling
/Binary_Files/appending.py
883
3.546875
4
import pickle def write(): records = [] try: with open('student_data.dat', 'rb') as f: records = pickle.load(f) except: pass with open('student_data.dat', 'wb') as f: while True: name = input('Enter your name\n') marks = int(input('Enter your...
ec2b30ae0d75366709ee2f0519d946a1702aca07
Eliomar-Julian/noticias
/app/models.py
2,621
3.515625
4
import sqlite3 from sqlite3.dbapi2 import SQLITE_SELECT import typing import os class SQL: def __init__(self): path = os.path.realpath(os.path.dirname(__file__)) path_full = os.path.join(path, "db/database.db") self.conn = sqlite3.connect(path_full, check_same_thread=False) self.cu...
944469b3af2436ce62b11e22ee43f8bf2a6c0e87
akarnoski/data-structures
/python/data_structures/binheap.py
1,845
4.125
4
"""Build a binary min heap object.""" from math import floor class BinaryHeap(object): """Create a Binary Heap object as a Min Heap.""" def __init__(self): """Initialize the heap list to be used by Binary Heap.""" self._heap_list = [] def push(self, val): """Add new value to heap...
a32fc4f194acd34c21ef5a5bcfcb3bf9f5d34bc1
akarnoski/data-structures
/python/data_structures/trie_tree.py
2,265
4.1875
4
"""Create a trie tree.""" class Node(object): """Build a node object.""" def __init__(self, val=None): """Constructor for the Node object.""" self.val = val self.parent = None self.children = {} class TrieTree(object): """Create a trie tree object.""" def __init__(s...
7f8a04763227ff1b5e467cfa094709371bd2350f
akarnoski/data-structures
/python/sorting_algorithms/insertion_sort.py
963
4.09375
4
"""Create an insertion sort algorithm.""" def insertion_sort(input): """Sort a given input with insertion sort.""" for index in range(1, len(input)): value = input[index] prev = index - 1 while prev >= 0: if value < input[prev]: input[prev + 1], input[prev] ...
0927de7b023d96a01db8047c1955aedfdcd2a9a1
hillarymonge/class-samples
/fancyremote.py
856
4.25
4
import turtle from Tkinter import * def circle(myTurtle): myTurtle.circle(50) # create the root Tkinter window and a Frame to go in it root = Tk() frame = Frame(root) # create our turtle shawn = turtle.Turtle() # make some simple but fwd = Button(frame, text='fwd', command=lambda: shawn.forward(50)) left = Button...
38dd6e613817e2aeaf6c035e05ea91d83631ec23
reza-asad/Coding-Challenge
/src/word_count.py
1,670
3.90625
4
# word_count() # # Description: # - Takes the text files in the directory wc_input and sorts # them alphabetically by their names into a list called FILES. # - Iterates over lines of all the text files and counts the # frequency of each word. # - At the end, sorts the words alphabetically and prints each word ...
06fbc36a1a8a186fe3ad868fccfe3eb611f40031
Spiralwise/workshop
/python/scrapbook/pendu_func.py
4,204
3.84375
4
#-*- coding:utf-8 -*- """This module contains functions for the "pendu" game. Launch this module to generate the score.dat file if not exists. """ from os.path import exists from random import randrange from words import * import pickle # Parameters filepath_score = "score.dat" # Data scores = {} current_player = "n...
9451016a28d177bba33de74e082028bc2e47e6a0
dr1012/medNLP
/extractor.py
6,023
3.515625
4
import PyPDF2 from nltk.tokenize import word_tokenize from stopwords import stop_word_list import docx import nltk import flask from flask import session def extract(filename): ''' Extracts text from a given file and parses it. Parameters ---------- filename : str Path of file in the ...
20089a15611b6bc071bf6fc3cad0e95a4fc8b306
dr1012/medNLP
/stopwords.py
800
3.859375
4
from spacy.lang.en.stop_words import STOP_WORDS import nltk #STOP_WORDS.add("your_additional_stop_word_here") def stop_word_list(): ''' Computes a list of stopwords. The NLTK and Spacy libraries both have pre-defined lists of stopwords. These are combined to make a larger set of possible english stopw...
2bd5ad94315e743fca1667e4d2eacffff86e8c06
Alea4jacta6est/reaching_optimal
/scripts/sum_options.py
494
3.546875
4
"""Each number in the input.txt is added to the next number, eg: in the input file with numbers 1,2,3,4….., the result will look like 3,5,7,9….""" from scripts.tracker import timeit @timeit def sum_next_nums(input, save_out=True): result = [num+input[i+1] for i, num in enumerate(input) if i < len(input)-1] if...
9e2cbb737a7aaaa7ec2eac90a37b47c33371b173
iceyokuna/Kattis-Solution
/Solution/Trik.py
530
3.765625
4
def main(): cup_list = [1,0,0] swap_sequence = input() for i in swap_sequence: if(i == 'A'): temp = cup_list[0] cup_list[0] = cup_list[1] cup_list[1] = temp elif(i == 'B'): temp = cup_list[1] cup_list[1] = cup_list[2] ...
31a0b69725d7aa6c394a1c135df4da0e1adb7196
iceyokuna/Kattis-Solution
/Solution/Pot.py
231
3.65625
4
def main(): num_line = eval(input()) answer = 0 for i in range(num_line): num_input = input() answer += int(num_input[:-1]) ** int(num_input[-1]) print(answer) if __name__ == "__main__": main()
c05925ef5e8a227ee8c56bb669fa6838c3317b03
ShresthaRujal/python_basics
/oop/notes.py
224
3.953125
4
class Circle(): pi = 3.14 def __init__(self,radius =1): self.radius = radius def area(self): return self.radius**2 * Circle.pi myCircle = Circle(3) print(myCircle.radius) print(myCircle.area())
2868818bbaaef980a57267f34e8cec8bd6574018
ShresthaRujal/python_basics
/strings.py
340
4.28125
4
#name = "rujal shrestha"; #print(name); #print(name[0]); #indexing #print(name[3:]) # prints all string after 3rd character #print(name.upper()) #print(name.lower()) #print(name.split(s)) #default is white space #print formatting print("Hello {}, your balance is {}.".format("Adam", 230.2346)) x = "Item One : {}".for...
440ae94fa20e0078afbee669bc765469b924dffc
just-a-chemist/DEV236x-
/shirt_stocker.py
776
3.859375
4
# initial quantities small = 0 medium = 0 large = 0 sc = 10 mc = 12 lc = 15 while True: shirt_size = input('Enter a shirt size or exit to finish. ') if shirt_size.lower().startswith("s"): small = small + 1 print(small) elif shirt_size.lower().startswith("m"): medium += 1 el...
7582c39cba68d1c20da751772db955c4a70fd5f2
just-a-chemist/DEV236x-
/familar_name.py
317
4.03125
4
def familiar_name(name): while True: if name.isalpha(): print("Hello",name.title(),"wassup!") break else: name = input("Not a familar name.\nPlease enter a familiar name. ") familiar_name(input("Enter a familiar name. "))
e4c045569b65046809a4c6d3bba3564397bbbb68
Denzaaaaal/python_crash_course
/Chapter_5/no_users.py
310
3.625
4
usernames = [] if usernames: for username in usernames: if username == "admin": print (f"\nHello {username}, would you like to see a status report?") else: print (f"\nHello {username}, thank you for loggin on again!") else: print ("We need to find some users!")
e77d4069f418a8293fb7878fac228476cfaeffb8
Denzaaaaal/python_crash_course
/Chapter_4/players.py
159
3.734375
4
players = ['charles', 'martina', 'michael', 'florance', 'eli'] print ("Here is for the first 3 players:") for player in players[:3]: print (player.title())
a34e33ff866f065228418cd1667d8c5e8db1cb55
Denzaaaaal/python_crash_course
/Chapter_4/foods.py
251
3.53125
4
my_foods = ['pizza','falafel','carrot cake'] friends_foods = my_foods [:] my_foods.append('rice') friends_foods.append('ice cream') print ("\nMy favorite foods are:") print (my_foods) print ("\nMy friends favorite foods are:") print (friends_foods)
728fd3b79a72e36f4d02b8fc1bae8564f26184cd
Denzaaaaal/python_crash_course
/Chapter_4/pizza.py
185
3.546875
4
pizzas = ['pepperoni', 'meatfeast', 'hot & spicy'] for pizza in pizzas: print (f"One of my favorite pizza flavours is {pizza}") print ("\nThese are my favourite flavours of pizza")
1f8975b5b315aa287404ef91c968a3039274215a
Denzaaaaal/python_crash_course
/Chapter_8/user_album.py
644
4.1875
4
def make_album(name, title, no_of_songs=None): if no_of_songs: album = { 'artist_name': name, 'album_title': title, 'number_of_songs': no_of_songs, } else: album = { 'artist_name': name, 'album_title': title, } retur...
1a3efe04ecd4959d39d8420cd24b33cb2e3f8bfc
Denzaaaaal/python_crash_course
/Chapter_5/alien_colours_2.py
170
3.6875
4
alien_colour = "red" if alien_colour == "green": print ("You have just earned 5 points!") elif alien_colour != "green": print ("You have just earned 10 points!")
bb1eef8f10a456d560abba511f81c169acacbd5f
Denzaaaaal/python_crash_course
/Chapter_6/cities.py
751
4.34375
4
cities = { 'london': { 'country': 'england', 'population': 8.98, 'fact': 'london is the smallest city in england' }, 'tokyo': { 'country': 'japan', 'population': 9.27, 'fact': 'tokyo for fromally known as "edo" in the 20th century', }, 'malmo': { ...
d921a93d0bb8f9d8cdba4a65b9425f8030f2ac2f
Denzaaaaal/python_crash_course
/Chapter_6/polling.py
312
3.65625
4
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } people = ['frank', 'jen', 'denzel', 'jordon', 'phil'] for person in people: print (f"\nHi {person.title()}") if person in favorite_languages.keys(): print ("Thanks for taking our poll")
abc5e309424069e700a517c1da9ebdb384e5602b
Lanovas/PythonMasterclass
/Course Code/Part V. Data Analysis.py
1,451
3.65625
4
# Pandas and Series import pandas as pd se = pd.Series([1, 3, 5, 7, 9]) se se[1] se = pd.Series([100, 300, 500, 700, 900], index=["a", "b", "c", "d", "e"]) se se["a"] # Converting dictionaries to Series salary = {"John": 3000, "Tim": 4500, "Rob": 5600} salary salary_series = pd.Series(salary) sal...
f49987a033adefb18a7e9f3b77c9beb9d7128063
Miguelro123/holbertonschool-higher_level_programming
/0x03-python-data_structures/6-print_matrix_integer.py
260
3.90625
4
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for y in range(len(matrix)): for z in range(len(matrix[y])): if z != 0: print(" ", end='') print("{:d}".format(matrix[y][z]), end='') print()
b8734ddba7184071335c6b0d2e32184ba05bcb80
Miguelro123/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/100-weight_average.py
237
3.71875
4
#!/usr/bin/python3 def weight_average(my_list=[]): if my_list is None or len(my_list) <= 0: return 0 weight = 0 sumtot = 0 for x, y in my_list: weight += y sumtot += y * x return sumtot/weight
a0c4d946c078cab0a89ac5f89775eca444fe7a83
Miguelro123/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/4-print_hexa.py
95
3.75
4
#!/usr/bin/python3 for number in range(0, 99): print("{0:d} = 0x{0:x}".format(number))
28de644e7af6bdb8c0cd5ffc79fca5d7f0a6aae9
JustinKnueppel/UsefulCreations-py
/factorial.py
552
4.03125
4
import math def get_factorial(n): assert n >= 0 if n == 1 or n == 0: return 1 return n * get_factorial(n-1) def get_n(x, num): """given value of x and a value you must be greater than, give n for x^n/n! > 1/num""" n = 1 while (x**n / get_factorial(n)) > 1/num: n += 1 return n def get_2n_1(x, num): """give...
1ec89eb4c276e6f69e05afe7a641fca63fb89935
veerabio/tic-tac-toe
/board_printer.py
1,436
3.65625
4
import sys class BoardPrinter: def __init__(self): self.columns = ["A", "B", "C"] self.mapping = { "A": 0, "B": 1, "C": 2 } def print_board(self, board): print("") for r in range(board.size): for c in range(board.size): ...
7bda31ff571188bf03b0cc836ecd3aa24175d6a9
hye00525/CV-WindowBasedSteroMatching
/Main.py
6,546
3.671875
4
"""Problem Set 3: Geometry.""" import numpy as np import cv2 import os from ps3 import * input_dir = "input" output_dir = "output" def normalize_and_scale(img_in): """Maps values in img_in to fit in the range [0, 255]. This will be usually called before displaying or saving an image. Args: img...
bf3a0c7fb441b13eede0a26ad0a5dca6b7417ec8
sosuperic/w0rdplay
/garbage_detector.py
4,864
3.640625
4
# Detect whether a word does not look like an English word, e.g. mwoeirp # These are called 'garbage' words, as opposed to 'nonsense' words that look like real words, e.g. 'flomker' # Notes / Considerations: # 1) Length of string # - Currently, the probability is normalized by the length of the string. This is # ...
b10a11995230719283e113e6563ffa647a370d88
Jwilson1172/DS-Unit-4-Sprint-3-Deep-Learning
/recipes.py
2,549
4.03125
4
#! /opt/conda/envs/intro_nn/bin/python # rnn and lstm # looking at how the models work at a high level. # using ltsm and rnn to generate text after processing it. # sequence based modeling, similar to time seris, basicly where the order of anylisi matters # python list's are a good example of squence # nural networks a...
327d84612884faff0752b263699e49dd5abd3b14
anya92/learning-python
/4.TuplesAndSets/tuple_methods.py
304
4.09375
4
t = (3, 4, 1, 12, 5, 3, 1, 4, 1) # count - returns the number of times a specified value occurs in a tuple print(t.count(1)) # 3 print(t.count(0)) # 0 # index - searches the tuple for a specified value and returns the position of where it was found print(t.index(1)) # 2 print(t.index(3, 2)) # 5
e0365c7a1f848c14fc109b05a8e297b38d766eca
anya92/learning-python
/Programs/kms_to_miles_converter.py
151
4.15625
4
print("Enter kilometers:") kilometers = float(input()) miles = kilometers / 1.609344 miles = round(miles, 2) print(f"That is equal to {miles} miles.")
69e63f2a0d4745bcc73eaf2a5e760fcc1e1f310e
anya92/learning-python
/12.FileIO/reading_csv_files.py
806
3.734375
4
from csv import reader, DictReader # reader with open('countries.csv') as file: csv_data = reader(file) # iterator (next()) print(csv_data) # <_csv.reader object at 0x002A8D70> for row in csv_data: print(row) # each row is a list # ['country', 'latitude', 'longitude', 'name'] # ...
ccc9a226774cc6527f7ffd0212f06c066eda6949
anya92/learning-python
/1.Basics/numbers_and_operators.py
542
4.21875
4
# Numeric types in Python: # - int # - float # - complex 1 # int 3.2 # float print(type(-1)) # <class 'int'> print(type(0.5)) # <class 'float'> # operator | name | example # + | addition | 1 + 2 # 3 # - | subtraction | 15 - 4 # 11 # * | multiplication | 3 * 2 # 6 # ...
9b0cc55c888e5d5f17d0fa12690a1fd97aad4bfb
anya92/learning-python
/8.OOP/mro.py
922
3.734375
4
# Method Resolution Order - the order in which base classes are searched when looking for a method (multiple inheritance) class A: def who_am_I(self): print("I am an A") class B(A): def who_am_I(self): print("I am a B") super().who_am_I() class C(A): def who_am_I(self): ...
111ffdb3196935deeb663340f0f320a6d3eb07b8
Raidren/LabaFiles
/7-Zadanie.py
360
3.65625
4
#Дан файл и две строки. Все вхождения первой строки в файл (в том числе в качестве подстроки) заменить второй строкой. with open('test3.txt','r') as a: a = a.read().split() print(a) a1 = a[0] a2 = a[1] m = ' '.join(a) zamena = (m.replace(a1, a2)) print(zamena)
e54115652e94d94fd515b170c91aa70699c58427
Raidren/LabaFiles
/12 - Zadanie.py
680
3.59375
4
#Имеются два файла (размеры файлов могут не совпадать). # Переписать элементы первого файла во второй, второго – в первый. Использовать вспомогательный файл. with open('test5.txt','r') as f1: f1=f1.read() with open('test6.txt','r') as f2: f2=f2.read() a = f1 b = f2 with open('test56.txt','w') as f3: f3 = ...
9f1c3222be27c9a888bf552b6545d8b050ace2ce
pip-services3-python/pip-services3-commons-python
/pip_services3_commons/random/RandomBoolean.py
1,545
3.90625
4
# -*- coding: utf-8 -*- """ pip_services3_commons.random.RandomBoolean ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RandomBoolean implementation :copyright: Conceptual Vision Consulting LLC 2018-2019, see AUTHORS for more details. :license: MIT, see LICENSE for more details. """ import random...
7b8ff26b213063dbc613279f59100d3b6cbfeaa9
udoyen/andela-homestead
/codecademy/anti_vowel.py
212
4.03125
4
def anti_vowel(text): vowels = 'aeiouAEIOU' l = list(text) for v in vowels: for i in l: if v in l: l.remove(v) return "".join(l) anti_vowel('Hey look Words!')
5523bdf0039a9d1b2c5a03e00aa8e3a48f6b73d3
udoyen/andela-homestead
/codecademy/advanced_topics/dictionary/sample.py
528
4.15625
4
movies = { "Monty Python and the Holy Grail": "Great", "Monty Python's Life of Brian": "Good", "Monty Python's Meaning of Life": "Okay" } for key in movies: print(key, movies[key]) print("===================================") for key, value in movies.items(): print([(key, value)], end=' ') # pri...
99bae2cec584ce6f95222c58a5bce782d836dea9
udoyen/andela-homestead
/test_folder/bankaccount.py
1,657
3.875
4
class BankAccount: def __init__(self): pass def withdraw(self, amount): pass def deposit(self, amount): pass class SavingsAccount(BankAccount): def __init__(self): BankAccount.__init__(self) # minimum balance self.balance = 500 def deposit(self, a...
c758572c72e9d64a5b75414c7c67edc50e55904b
udoyen/andela-homestead
/codecademy/meal/supermarket.py
568
3.96875
4
shopping_list = ["banana", "orange", "apple"] stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # Write your code below! def compute_bill(food): total = 0 for item in food: for s in stock: ...
1cb5f98782367a2a516086c3b3a9e84c1bc3391f
udoyen/andela-homestead
/basic-datastructures/programing_exercises_227/f6_queue_experiment.py
2,328
3.8125
4
########################################################################################################## # Experiment to determine the differences between a list # # implemented queue and the 'queue' ADT (abstract data type) #...
a9a3691ad3f41fe8c23aae6819e8d5e328bb1bbb
udoyen/andela-homestead
/test_folder/test_5.py
155
4.0625
4
def factorial(number): num = 0 if number == 0: return 1 num += 1 print(num) return number * factorial(number-1) factorial(5)
98eda14c758b0aa31e44b56acd549a24c499e72a
Sombat/Python-Stack
/python_stack/flask/flask_fundamentals/assignment/dojo_survey/dojo.py
1,041
3.640625
4
# Assignment: Dojo Survey # Objectives: # 1. Practice creating a server with Flask from scratch # 2. Practice adding routes to a Flask app # 3. Practice having the client send data to the server with a form # 4. Practice having the server render a template using data provided by the client from flask import Flask, ren...
ecb27c7716d22c480ac6dc14aca69b6fd25c9d5a
Sombat/Python-Stack
/python_stack/python/OOP/users_with_bank_accounts.py
2,220
4.25
4
# Assignment: Users with Bank Accounts # Objectives: # Practice writing classes with associations class BankAccount: def __init__(self, int_rate=.01, balance=0): self.interest_rate = int_rate self.account_balance = balance def deposit(self, amount): self.account_balance += amount ...
293acf3d092969b2a73b917d8ea04694518d636b
codecreation01/frequent-string-charecter
/frequent charecters.py
199
3.671875
4
test_str="mississippi" all_freq={} for i in test_str: if i in all_freq: all_freq[i]+=1 else: all_freq[i]=1 print("count of all charecters in mississippi is:\n"+str(all_freq))
e62299ce0a604b4dd8bd970f72f0e88490fae337
Gaurav-808/python_Project
/temp.py
2,399
3.5
4
import random import socket import time import sys response='NORMAL' def random_number(response): '''This Function is to produce Random Value Which indicates the temprature''' if response == 'NORMAL': time.sleep(2) else: time.sleep(1) global temp temp=str(random.randint(5,59)) ...
c8d48164f816facd706343f37068493c56d06823
Maxic/advent2019
/day1/problem2.py
412
3.65625
4
def main(): fuel_sum = 0 with open("input.txt", "r+") as file: content = file.readlines() for line in content: mass = int(line) fuel_sum += calc_fuel(mass) print(fuel_sum) def calc_fuel(mass): fuel = 0 while mass > 0: mass = mass // 3 - 2 if...
3557ad75fa7d164795c6076e85da9345fb239237
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio34.py
769
4.09375
4
#Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. #Para salários superiores a R$1.250, calcule um aumento de 10%. #Para os inferiores ou iguais, o aumento é de 15%. print(f"""{cores['azul']}==================================================================== ...
f2f0db831c3442abbc0f748c98e583e26519d711
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio02.py
456
3.640625
4
import emoji cores = {'azul':'\033[1;34m','semestilo':'\033[m'} print(f"""{cores['azul']}==================================================================== CHALLENGE 02 ===================================================================={cores['semestilo']}""") nome = input('Digite o se...
0f7dd31e446694a909b524ee9379144d5307f0b6
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio03.py
832
3.734375
4
cores = {'VermelhoBold':'\033[1;31m', 'VerdeBold':'\033[1;32m', 'AmareloBold':'\033[1;33m', 'AzulBold':'\033[1;34m', 'LilasBold':'\033[1;35m', 'VerdepiscinaBold':'\33[1;36m', 'CinzaBold':'\033[1;37m', 'Semestilo':'\033[m', 'FundoBranco':'\033[1;40m...
0390536aadf4e563e3e8de60fc26b0ea5fec6cae
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio27.py
758
4.1875
4
#Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro nome e o último nome separadamente. #ex: Ana Maria de Souza # primeiro = Ana # último = Souza cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m', 'lilas':'\033[1;35m', 'amarelo...
ee88cecfa2c567a8f0a5c65ad31e9b6b6d57277c
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio23.py
796
3.921875
4
#Challenge 23 - Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados. #Ex: Digite um número: 1834 #unidade:4 #dezena:3 #centena:8 #milhar:1 cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[m', 'vermelho':'\033[1;31m', 'lilas':'\033[1;35m', 'amarelo':...
99edaf310f340ee8612570e49f4945e8c3092a80
loumatheu/ExerciciosdePython
/Mundo 1/Exercicio22.py
1,015
4.40625
4
#Challenge 22 - Crie um programa que leia o nome completo de uma pessoa e mostre: #•O nome com todas as letras maiúsculas; #•O nome com todas as letras minúsculas; #•Quantas letras ao todo (sem considerar espaços); #Quantas letras tem o primeiro nome; cores = {'azul':'\033[1;34m','verde':'\033[1;32m','semestilo':'\033[...
40bb0869e6a902cdcca02c679c993d72ff16849c
tim-first/app_banking_concept
/acc.py
810
3.609375
4
class Account: """docstring for Account - oop principles used""" def __init__(self, filepath): super(Account, self).__init__() self.filepath = filepath with open(self.filepath, 'r') as file: self.balance = int( file.read() ) def withdraw(self, amount): self.balance = self.balance - amount def deposit(s...
a625ddb577807927556b33a014604b6a14ad41b3
rollinginsanity/zoneage
/zoneage/config.py
4,054
3.546875
4
"""This module includes the Config class, which holds the config loaded from a config file.""" import json from zoneage.exceptions import MissingConfigFileException, InvalidConfigFormatFoundException, MissingConfigElementException import pkg_resources # used to load meta-config-format file. class Config: config_fi...
7c750fbc981d9f47db9cc7925527ca9a56a9e9bd
moosahassan/grove
/app/find_store.py
2,311
3.984375
4
#!/usr/bin/env python """ Find Store find_store will locate the nearest store (as the crow flies) from store-locations.csv, print the matching store address, as well as the distance to that store. Usage: find_store --address="<address>" find_store --address="<address>" [--units=(mi|km)] [--output=text|json]...
edc8bf1c2d93ada42e4c5144d2fa226f23e39885
lgrabowski/std-number-validation
/std_number_validation/tests/validators/boolean_validator_test.py
2,203
3.53125
4
import unittest from std_number_validation import validators from std_number_validation import algorithms from std_number_validation import exceptions class LuhnAlgorithmTestCase(unittest.TestCase): BOOLEAN_VALIDATOR_CLASS = validators.BooleanValidator LUHN_ALGORITHM = algorithms.LuhnAlgorithm ...
87c3ba11855ff1caacc4154f87f33e01a13564d5
bpiyush/covid-whatsapp-bot
/utils/pandas.py
545
3.703125
4
"""Utility functions for pandas operations""" import numpy as np import pandas as pd def apply_filters(df: pd.DataFrame, filters: dict, reset_index=False): """ Filters df based on given filters (key-values pairs). """ X = df.copy() for col, values in filters.items(): if isinstance(values,...
4caa7b676fc537f93ebb525cad2311cf4a37e49f
shreyshah02/Video_Processing
/SHREY_SHAH_EECE_5354_2019S_Assignment_1_code.py
18,648
3.53125
4
# Name : Shrey Shah # Course: EECE 5354 Computer Vision # Assignment No. : 01 # Date : 01/27/2019 #!/usr/bin/env python ''' Example code for live video processing Also multithreaded video processing sample using opencv 3.4 Usage: python testcv_mt.py {<video device number>|<video file name>} Use this code as ...
ac0f8e969fdf7c3c455e5cdb575b3f68b4d32a47
MuazZulkarnain/DSA_SC_1813593
/Test.py
4,606
3.875
4
class Node(object): """docstring for Node""" def __init__(self, data=None, next_node=None): self.data = data self.next_node = None # end of Class Note # get and set data/link function def get_data(self): return self.data def set_data(self, d): self.data = d ...
d41eb706453249b2fc8e33d9e48f1651dc1efd9a
a01747686/Mision-04
/Rectangulos.py
1,582
3.796875
4
#Autor: Samantha Martínez Franco A01747686 #Calcular area y perímetro de dos rectangulos #función que calcula area def calcularArea(altura,ancho): area=altura*ancho return area #función que calcula perímetro def calcularPerímetro(altura,ancho): perimetro=2*altura+2*ancho return perimetro ...
b38d119487dc3317e653f95056b5df4798c38589
ThomasBriggs/python-examples
/BinaryTree/binTree.py
2,067
4.03125
4
class Tree: class __Node: def __init__(self, val): self.val = val self.left = None self.right = None def __init__(self, data=[]): self.root = None if data is not []: for i in data: self.add(i) def add(self, val): ...
e7b028c64ca4fb48618d9a41eea2d80b30e62495
ThomasBriggs/python-examples
/Calculator/Calculator.py
287
4.28125
4
def calc(num, num2, operator): if operator == "+": print (num + num2) elif operator == "-": print (num - num2) elif operator == "*": print (num * num2) elif operator == "/": print (num / num2) else: print ("Invalid operator")
7ff677debff7934ff3c498a09cec34c9a4074b84
ktlp/SudokuSolver
/Solver.py
2,075
3.9375
4
import numpy as np def plot_sudoku(arr): for i in range(0,9,1): for j in range(0,9,1): print(arr[i,j] ), print def solve(arr): for i in range(0,9,1): for j in range(0,9,1): if arr[i][j] == 0: #empty space found, save position po...
c8aaf9f08fbead122c3a1a509c18586e8079a729
glenliu/py_examples
/input.py
267
3.84375
4
def Text_1_answer(text, answer): print(text) while True: space = input("Input answer:") if space != answer: print("Wrong, input again!") else: print("Yes go!") break; Text_1_answer("test","abc")
36c1856456e6a04b7b13aca9226d4043a8b8c3be
JesusGuadiana/Nansus
/structures/quad.py
1,032
4
4
# ----------------------------------------------------------------------------- # Juan Fernando and Jesus’ Programming Language # quad.py # Last edit: 14/11/2018 # ----------------------------------------------------------------------------- #Class Name class Quad(): #Constructor for the Quadruple Class ...
39002ea0d3628e9bef3915592f18259d2be815b9
farhad324/Basic-Efiicient-Codes-Python
/Move all zeroes to right.py
573
3.53125
4
def moveZeroes1(nums): i, position = 0, 0 while i < len(nums): if nums[i] == 0: position += 1 else: if position > 0: nums[i], nums[i-position] = nums[i-position], nums[i] i += 1 return nums def moveZeroes2(nums): l = len(nums) ...
82b0c1b0bd9c52d9f69ffc10781d3c7692bcd39c
pyconca/2013-eventmobi-import
/util/spreadsheet.py
428
3.515625
4
#!/usr/bin/env python """Helpers for working with Excel spreadsheets.""" import xlwt def write_spreadsheet(data, sheet_name, out_file): """Write a list of lists into a spreadsheet.""" workbook = xlwt.Workbook() worksheet = workbook.add_sheet(sheet_name) for row in range(len(data)): for col i...
19e601d5412d580dfbde1ba8de36005a689ac7c1
fluoridepsychosis/sent_gen
/fancy_noun.py
2,047
3.71875
4
import ornate_noun import random def main(): with open("prepositions.txt") as prepositionfile, open("relpronouns.txt") as relpronounsfile, open("verbs.txt") as verbsfile: # Creating empty sentence string for words to be appended to sentence = "" prepositionlist = [] for line in pre...
098a39bbd01feb1060b1c0c83df0b54fd8792078
svmldon/IE_507_Modelling_lab
/LAB 07/Other file/lab07ex10.py
925
3.75
4
# -*- coding: utf-8 -*- """ Created on Wed Sep 20 14:38:43 2017 @author: svmldon """ import numpy as np import random def mat(m,n): A=[[random.randint(1,m) for j in range(n)] for i in range(m)] for i in range(0,m): maxcl=A[i][i] maxrow=i for k in range(i+1,m): ...
2c4cb9a628f31dfa57916ee7a43945e9315adca5
svmldon/IE_507_Modelling_lab
/LAB 04/lab04ex3.py
394
3.90625
4
print ("please enter an array of 5 elements") x1=float(input("1st number")) x2=float(input("2nd number")) x3=float(input("3rd number")) x4=float(input("4th number")) x5=float(input("5th number")) list1=[x1,x2,x3,x4,x5] for i in range(0,5): for j in range(0,5): if (list1[i]>list1[j]): temp=l...
42db31f4a097ff0c8b38af894441bd4ffe75aa8f
jovyn/100-plus-Python-challenges
/100-exercises/ex16.py
442
4.25
4
''' Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,9,25,49,81 ''' num_lst = input("Enter a sequence of nos. comma separated: ") num_lst = n...
26f591629929ebde1c91cb58131848de693cbed5
jovyn/100-plus-Python-challenges
/small-exercises/guess_game.py
485
3.6875
4
''' Write a program to take 2 nos as input and the program will return a prompt to guess a value. if the no. matches the random generated no. we get a point. ''' import random import sys val = random.randint(int(sys.argv[1]),int(sys.argv[2])) #print(val) # Cheating print("Guess a no. between "+ sys.argv[1] + " and "...
4fe0ca4e389139c38f979a35a86543b4b08e1856
jovyn/100-plus-Python-challenges
/100-exercises/ex17.py
778
3.71875
4
''' Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200 D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should ...
52bdee1e48b1e04565e350c5227db664729b1cf7
prashantravishshahi/pdsnd_github
/User_Input.py
2,512
4.375
4
#definition of input month function. def get_month(): '''Asks the user for a month and returns the specified month. Args: none. Returns: (tuple) Lower limit, upper limit of month for the bikeshare data. ''' months=['january','february','march','april','may','june'] while True: ...