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
08cba609d5049f44779b75663fc92469255035a6
Kirill96/python_lab_2
/build/lib/task4/vector.py
3,596
3.65625
4
import math class Vector(object): def __init__(self, *args): self.sum = 0 self.length = 0 self._list = [] for arg in args: self._list.append(arg) def __add__(self, obj): vect = Vector() if len(self._list) < len(obj): for elem in range(l...
c114bdb112f8ad6e217275e9f996165632529887
nphdang/FCGP
/read_data.py
4,952
3.59375
4
import numpy as np import pandas as pd # read data from file def from_file(dataset, sensitive): df = pd.read_csv("./data/{}.csv".format(dataset), header=0, sep=",") if dataset == "adult": numerical_var_names = ["age", "education-num", "capital-gain", "capital-loss", "hours-per-week"] categorica...
81a470aba1e69794f9449629d534a75afeaec4bf
NSnietol/hacker-rank
/Python/itertools/combinations.py
635
4.03125
4
""" https://www.hackerrank.com/challenges/itertools-combinations/problem Task You are given a string S. Your task is to print all possible combinations, up to size K, of the string in lexicographic sorted order. Input Format A single line containing the string S and integer value K separated by a space. Constraint...
58fa940a8edceeea01d3562ab6d1f3c7ab598676
NSnietol/hacker-rank
/Python/numpy/concatenate.py
792
3.859375
4
""" You are given two integer arrays of size N X P and M X P ( N & M are rows, and P is the column). Your task is to concatenate the arrays along axis 0 . Input Format The first line contains space separated integers N , M and P. The next N lines contains the space separated elements of the P columns. After that, ...
3690ab99200c1c8f36b2537c14ccd338566e4fa2
glissader/Python
/ДЗ Урок 6/main2.py
1,125
4.25
4
# Реализовать класс Road (дорога). # - определить атрибуты: length (длина), width (ширина); # - значения атрибутов должны передаваться при создании экземпляра класса; # - атрибуты сделать защищёнными; # - определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # - использовать формулу: длина*шир...
f7bef01bc72af50b1ccbe2f3cbc9304265598628
glissader/Python
/ДЗ Урок 2/main3.py
608
3.96875
4
# Пользователь вводит месяц в виде целого числа от 1 до 12. # Сообщить, к какому времени года относится месяц (зима, весна, лето, осень). # Напишите решения через list и dict. n = 0 while n not in range(1, 13): n = int(input("Введите месяц от 1 до 12 ").strip()) seasons = {"зима": [12, 1, 2], "весна": [3, 4, 5], "...
c0e8fc2921970a9a20c0a57dca991a89239e4627
glissader/Python
/ДЗ Урок 7/main1.py
1,424
3.78125
4
# Реализовать класс Matrix (матрица). # Обеспечить перегрузку конструктора класса (метод __init__()), который должен принимать данные (список списков) для формирования матрицы. # Следующий шаг — реализовать перегрузку метода __str__() для вывода матрицы в привычном виде. # Далее реализовать перегрузку метода __add__() ...
bbb3e32758d4ed03841e25ee69d829436011cf8d
glissader/Python
/ДЗ Урок 3/main5.py
1,391
3.59375
4
# Программа запрашивает у пользователя строку чисел, разделённых пробелом. # При нажатии Enter должна выводиться сумма чисел. # Пользователь может продолжить ввод чисел, разделённых пробелом и снова нажать Enter. # Сумма вновь введённых чисел будет добавляться к уже подсчитанной сумме. # Но если вместо числа вводится ...
a4940b1a2c2bcebe1e6c1dddc832e55fbb679868
Jian-Lei/LeetCodeExercise
/example/exercise_205.py
991
3.875
4
#!/usr/bin/env python # coding=utf-8 """ Auther: jian.lei Email: leijian0907@163.com 给定两个字符串 s 和 t,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身 https://leetcode-cn.com/problems/isomorphic-strings """ def is_isomorphic(s, t): """ :param s: str :pa...
eceeeb18fb41636815f138b55602cd3956e1ff3b
Jian-Lei/LeetCodeExercise
/example/exercise_9.py
835
4.1875
4
#!/usr/bin/env python # coding=utf-8 """ Auther: jian.lei Email: leijian0907@163.com 给你一个整数 x ,如果 x 是一个回文整数,返回 ture ;否则,返回 false 。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。 https://leetcode-cn.com/problems/palindrome-number """ def is_palindrome(x): result = False if -1 < x < 2 ** 31 - 1: ...
224295119c7e37e8f9f3185b8887c1973c08f0d7
henkkah/pathfinding
/src/data_for_app.py
1,739
3.796875
4
def data_for_app(): """Reads base data for the app (city and highway data) and stores it in appropriate format for the app. Args: no arguments - reads data from csv files which need to be in data folder in order for the application to work Returns: tuple of (cities, coordinates, sp...
96dab68da3e72854058f6aaa7e69f000e4bcbf56
Coles484/2020-computer-science
/anagram_solver.py
781
4.09375
4
import itertools #get the dictionary file with open('all_the_words.txt') as file: contents = file.read() #ask for input things = int(input("How many things are there? ")) print("Okay, there are ", things, "number of things") #creating a variable to keep track of the number of words words_Ive_entered = 0 #som...
d07f8d3ae500f5aefc1e03accc48d230ce4b4edd
adibhatnagar/my-github
/NIE Python/Third Code/Further Lists.py
1,629
4.3125
4
list_1=['Apple','Dell','HP','LG','Samsung','Acer','MSI','Asus','Razer'] #declares list containing names of laptop makers as strings list_2=[1,2,3,3,3,4,5,5,6,7,8,8,8,8,9] #declares list containing integers #Remember list elements have index starting from 0 so for list_1 the element 'Apple' has index 0 #If you store an...
08239ff82211616306c413721a3f7d6a9ee0068d
nmichiels/cifDataset
/convertToNumpy_rotInvariant.py
3,303
3.859375
4
""" This script will allow the user to convert HDF5 to numpy dataset. IMPORTANT: The dataset is augmented with multiple rotations of the data Args: inputFile (str): Input hdf5 file outputFile (str): Output npy file. img_size (int): Target resolution of the images. All images are cropped, centered and pad...
4a6e319525b2caad6fcf3e357e26469f8bef6ca5
komalkri-dev/character-o-graph
/T_to_Z.py
2,558
3.71875
4
import turtle def draw_T(offset): # draws alphabet p t = turtle.Turtle() t.speed(4) t.color('pink') t.up() t.forward(offset) t.down() t.left(90) t.up() t.forward(70) t.down() t.right(90) t.forward(42) t.backward(21) t.right(90) t.forward(70) t.hidet...
83bb4fb72d1a19eceb7f8bc21dcdf4f6854a4b96
matthew-sessions/algoexpert
/zigzag.py
650
3.703125
4
def zigzagTraverse(array): # Write your code here. height = len(array) - 1 width = len(array[0]) - 1 res = [] row, col = 0,0 down = True while not bounds(row, col, height, width): res.append(array[row][col]) if down: if col == 0 or row == height: down = False if row == height: col +=...
3f7f22166f14c9ea0187abea65e3d5147983bcb2
matthew-sessions/algoexpert
/powerset.py
171
3.609375
4
def powerset(array): # Write your code here. sub = [[]] for val in array: for i in range(len(sub)): cursub = sub[i] sub.append(cursub + [val]) return sub
5770281964fbc5ca4943acac25065799fe0a6f0f
matthew-sessions/algoexpert
/compresstring.py
1,162
3.9375
4
test = 'aaabbccceeeeeeedd' # Run time O(n) def compress_string(string): # this variable allows me to know if I have # started counting the letters or not state = False # reverse the string backwards so I do not have # to keep track of the length of the array in a while loop for i in reversed(r...
8536c784ab2621119945d89a2be1700902f9875a
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[589]N叉树的前序遍历.py
471
3.59375
4
from typing import List # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def preorder(self, root: Node) -> List[int]: def dp(root, ans): if root: ans.append(root.val) ...
ff2f4afe0bb5071ca74f7b35e056e9b699ea13bd
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[124]二叉树中的最大路径和.py
668
3.625
4
# Definition for a binary tree node. from typing import Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def maxPathSum(self, root: Optional[TreeNode]) -> int: def helper(root): ...
c8d520afe23499a8223c598983ca200f9e072ff8
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[738]单调递增的数字.py
924
3.609375
4
import heapq """文档字符串测试 袁宇 2020.12.15 """ class Solution: """A class with standard leetcode solution templete """ def monotoneIncreasingDigits(self, N: int) -> int: """返回一个不小于 N 的递增数字 使用贪心算法 Args: N: An integer Returns: An i...
4d59e18cc15928b7e8bee89e6f31eace73e67e31
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[212]单次搜索Ⅱ.py
2,009
3.59375
4
from typing import List from itertools import product class TrieNode(dict): def __init__(self, parent=None, val=None) -> None: super().__init__() self.word = False self.val = val self.parent = parent self.count = 0 class Solution: def findWords(self, board: List[Lis...
9e5ba9c0a2f3ef6ce4fd91bea7c11b9fa5e2678f
Yuan98Yu/solutions-to-leetcode-cn
/solutions/[367]有效的完全平方数.py
349
3.53125
4
class Solution: def isPerfectSquare(self, num: int) -> bool: l, r = 1, num+1 while l < r: mid = (l+r) // 2 pow = mid ** 2 if pow < num: l = mid + 1 elif pow > num: r = mid else: return True ...
40f09780ceec23805de5bb0d7881bc12195ee4d9
Akshatt/Leetcode-challenges
/August-Leetcode/day11.py
547
3.890625
4
''' H-Index Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers hav...
e34a70df7a508008baa135f19dda44ed7d2c289e
Akshatt/Leetcode-challenges
/June-Leetcode/day17.py
1,085
3.75
4
''' Surrounded Regions Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. ''' class Solution: def solve(self, board: List[List[str]]) -> None: m = len(board) n = len(board[0]...
2b65ddec9e789e5e68c16fc7463cde10501c17a5
Akshatt/Leetcode-challenges
/August-Leetcode/day29.py
1,038
4.0625
4
''' Pancake Sorting Given an array of integers A, We need to sort the array performing a series of pancake flips. In one pancake flip we do the following steps: Choose an integer k where 0 <= k < A.length. Reverse the sub-array A[0...k]. For example, if A = [3,2,1,4] and we performed a pancake flip choosing k = 2, w...
7049906838c86a3cdecb995009b645ecff55abbb
Akshatt/Leetcode-challenges
/July-leetcode/day16.py
424
3.59375
4
''' Pow(x, n) Implement pow(x, n), which calculates x raised to the power n. ''' class Solution: def myPow(self, x: float, n: int) -> float: if abs(x) < 1e-40: return 0 if n == 0: return 1 if n < 0: return self.myPow(1/x, -n) lower = self.myPow(x, n//2) if n % 2 == 0: retur...
4a0252ca9eb47cc102c21501ba3f182146787dc2
Akshatt/Leetcode-challenges
/August-Leetcode/day22.py
1,312
3.625
4
''' Random Point in Non-overlapping Rectangles Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles. Note: An integer point is a point that has integer coordinates. A point on the perimeter of...
0a8cb8a46531252feb547b1244af0d3e71e7a895
Akshatt/Leetcode-challenges
/July-leetcode/day5.py
636
4.0625
4
''' Hamming Distance The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. ''' class Solution: def hammingDistance(self, x: int, y: int) -> int: a, b = bin(x)[2:], bin(y)[2:] d...
023c039e7c990f148abd074f4cb79bdefa40a0c2
Akshatt/Leetcode-challenges
/June-Leetcode/day12.py
1,085
3.796875
4
''' Insert Delete GetRandom O(1) Design a data structure that supports all following operations in average O(1) time. insert(val): Inserts an item val to the set if not already present. remove(val): Removes an item val from the set if present. getRandom: Returns a random element from current set of elements. Each ele...
581bdab0a79245bd5e6b9b7f45b9a33d71fa3d1a
Akshatt/Leetcode-challenges
/July-leetcode/day27.py
799
4.03125
4
''' Construct Binary Tree from Inorder and Postorder Traversal Given inorder and postorder traversal of a tree, construct the binary tree. ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # sel...
30e2ebb02fd668e8c05e064fc3eac7c6add18fdb
Akshatt/Leetcode-challenges
/June-Leetcode/day7.py
580
3.625
4
'''Coin Change 2 You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. ''' class Solution: def change(self, amount: int, coins: List[int]) -> in...
02832755ecd1b89ff39a7d663e3f8d07635cf58d
LONG-XI/Tensorflow-Tutorials
/003-activation-function.py
1,590
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 5 19:47:21 2019 @author: xilong """ # In this tutorial, we import plt to plot. import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # fake data x_data = np.linspace(-6, 6, 100) # x data, shape=(100, 1) print(x_data) # f...
7fca76e3ea5a720ddec48f3047a265746a25840a
RichXan/LearnPython
/python_practice/5-7.py
192
4.03125
4
foods = ['peal','straberry','watermelon','banana','apple'] favorite_food =['apple','banana','peal'] for food in favorite_food: if food in foods: print("You are really like "+ food)
7177720bf6238ced0178e3e7d5581ceedfeeb530
RichXan/LearnPython
/python_practice/7-1.py
458
4.0625
4
# 7-1 car = input("Which car would you like to rent? ") print("Let me see if I can find you a "+ car) # 7-2 people = input("How many peoples do you hava? ") people = int(people) if people >8: print("Sorry,we don't have such big table.") else: print("This way,please.") # 7-3 number = input("Please input a...
321ae694ce3dd4eb0d1f4bf4a2a90cf08e219d4d
RichXan/LearnPython
/python_practice/8-9.py
555
3.859375
4
def show_magicians(Magicians_name): print("================") for magician in Magicians_name: print(magician.title()) def make_great(Magicians_name1,Magicans_name2): #歌手名前加The Great while Magicians_name1: Magicians = Magicians_name1.pop() Magicians = "The Great " + Magic...
4eb0ad817cd12d6e52a8442f387a84e7a2326777
RichXan/LearnPython
/python_practice/remember_me.py
380
3.65625
4
import json filename = "user_name.json" try: with open(filename) as file_object: username = json.load(file_object) except FileNotFoundError: username = input("Please enter your name : ") with open(filename,'w') as file_object: json.dump(username,file_object) print("We will welcome yo...
7b18503ea4ff58f428207e3f6bbce055e306a543
RichXan/LearnPython
/python_practice/6-9.py
341
3.828125
4
favourite_places = { "Xan" : ['France','Paris','Ireland'], "else" : ['None'] } for name,places in favourite_places.items(): if len(places) > 1: print(name + "'s favouriter places are") for place in places: print(place) else: print(name + "'s favouriter place is ") ...
5c83c90667fd24c2eca53231f7de17244006da4b
juandiazp/IoT2020
/Area.py
644
3.78125
4
#Creando clase area: AreaTrapecio.PY class Area: def _init_(self): self.h = 0 self.a = 0 self.b = 0 self.r = 0 def areatrapecio(self): self.r = ((self.a+self.b)*self.h)/2 def areatriangulo(self): self.r = (self.b*self.h)/2 def areacircul...
68a48a935260c7119937ee4bb29ccec2a6be9130
SahilSalma/Multi-Class-Program
/Doctor.py
1,553
3.6875
4
#Name: Sahil Salma #Student Number: 201733334 from Employee import Employee #imports Class Employee class Doctor(Employee): #constructor with parameters for the Person, Employee and Doctor attributes def __init__(self, name = "", address = "", DOB = "", employeeNumber = "", \ dateOfHire = "",...
f72befd0c7407ba6d4df6302db1d25bbf9984422
charlottewk/csci396_pset1
/routing.py
1,592
3.859375
4
# File: routing.py """ This module defines a routing table for the ARPANET routing assignment. Your job in this assignment is to implement the RoutingTable class so its methods implement the functionality described in the comments. """ class RoutingTable: """ This class implements a routing table, which keep...
d5caf9c78466b31dc59dcd9a027abcb140dd4ccb
rwik19/PythonBasics
/coders week1/q2.py
1,079
3.78125
4
N = int(input("N(greater than 2) = ")) def valid(node, N): #check if square is inside board if node[0]<=N and node[1]<=N and node[0]>=1 and node[1]>=1: return True else: return False def knight_shortest(start=(1,1), end=(N,N), N=N): moves = [(1,-2), (1,2), (-1,2), (-1,-2), (-...
1cf8081580327dab7cd024cb33d0a53ce05c9299
RPGgrenade/Tarea-3-Big-Data
/output_to_csv.py
219
3.5
4
import csv def make_csv(output_name, dictionary): with open(output_name + '.csv', 'w') as f: w = csv.writer(f) for key,value in dictionary.items(): w.writerow([key, value[0], value[1]])
3df2209d0b09b27f3d8de6e9bf9efd9f41764565
LUKELIEM/leader
/xteams_env.py
41,466
3.5625
4
import collections import itertools import os.path import tkinter as tk import gym import gym.envs.registration import gym.spaces import numpy as np """ 04-20-2019 CROSSING is an environment where the agents are organized by teams with a "Us" versus "Them" mentality. Crossing accept teams with multiple roles - leade...
834150869dafb9aad8526e06b7dda6008eee983f
Ars-Linguistica/mlconjug3
/mlconjug3/feature_extractor/feature_extractor.py
2,389
3.625
4
""" This module declares the feature extractors for verbs. A custom vectorizer optimized for extracting verb features, including n-grams of verb endings and beginnings, verb length, number of vowels and consonants, and ratio of vowels to consonants. """ import re from mlconjug3.constants import ALPHABET def extract...
d8c7cfb65dc392a2d3b7ab9170ac117f044b3e79
Yancey2126/Numerical-Analysis-
/py-code/hw2_Q4(Illi).py
1,581
3.53125
4
import numpy as np from matplotlib import pyplot as plt tol = 1e-12 # If the "residual" |f(x_k)| < tol, stop iteration printouts = True def f(x): #return np.exp(x) - x - 2 return x**2 - 2 def Illi(x0, x1): if x0 > x1: print 'Initial interval not exist!' if f(x0)*f(x1) > 0: print...
58ece6f2201bbfe7db094cd339bbfd0c250b5907
marcusj3/Knowledge-Based-AI
/main.py
726
3.5
4
from enum import Enum class Requested(Enum): DUE_DATE = 1 RELEASE_DATE = 2 WEIGHT = 3 PROCESS = 4 DURATION = 5 if __name__ == '__main__': main() def main(): userSentence = input() transformedSentence = userSentence.lower() userSentenceObject = getObject(transformedSentence) us...
212e16cd5c0221a6d7b2965ec527884f0db71f9a
carlspangrude/Gravity-Waves-2020
/CalculatePBL.py
14,013
3.53125
4
from io import StringIO import numpy as np # Numbers (like pi) and math import os # File reading and input import WaveDetectionFunctions as fun import pandas as pd ########## Function definitions, to be used later ########## def pblRI(vpt, u, v, hi): # The RI method looks for a Richardson number between 0 and ...
45d60e8738a90b37895a300ad27bc65d03725efb
jihungen/LearnPythonTheHardWay
/ex11.py
429
3.671875
4
print "How old are you?", # I use input so that I do not have to see single-quote that surrounds the input values. age = input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "What do you like?", # input() may cause the error when it is string favorite = raw_...
e5e227509210a211bbbd4c9c4a7e3fcc9dd23a96
gagande90/Data-Structures-Python
/Comprehensions/comprehension_list.py
562
4.25
4
# list with loop loop_numbers = [] # create an empty list for number in range(1, 101): # use for loop loop_numbers.append(number) # append 100 numbers to list print(loop_numbers) # list comprehension comp_numbers = [ number for number in range(1, 101) ] # create a new li...
9f63b82e2667cb5bbf501b8957a6c2cc34a883f5
rebecabramos/Course_Exercises
/Week 6/Hacking_version_4.py
3,400
3.5
4
# Hacking version 4 # This is a graphical password guessing game that displays a # list of possible computer passwords. the player is allowed # 4 attempt to guess the password, when the player only has 1 try a lock message will appear. # The game indicates whether the player guessed the password successfully or not. f...
bbd9d9f89619a93c37c79c269f244d899b047394
rebecabramos/Course_Exercises
/Week 6/search_and_replace_per_gone_in_list.py
1,123
4.375
4
# The program create a list containing the integers from (1 to 10) in increasing order, and outputs the list. # Then prompt the user to enter a number between 1 and 10, replace this number by the str object (gone) and output the list. # If the user enters a string that does not represent an integer between 1 and 10, ...
23aed0b18c33addf4ed34a8a25f206b826239b9c
rebecabramos/Course_Exercises
/Week 6/split_str_space-separated_and_convert_upper.py
308
4.46875
4
# The program performs space-separated string conversion in a list # and then cycles through each index of the list # and displays the result in capital and capital letters string = input('Enter some words >') list_string = string.split() print(list_string) for x in list_string: print(x, x.upper())
55d17e71907e95e85c59c7b73a6b578e5344c538
KenmogneThimotee/PythonCode
/table_de_mult.py
390
3.75
4
"""module multipli contenant la fonction table""" import os def table(nb, max=10): """Fonction affichant la table de multiplication par nb de 1 * nb jusqu'à max * nb""" for i in range(max) : ch = i + 1 mult = ch * nb print(ch , "*" , nb , "=" ,mult) # test de la fonction if __name__ == "__main__": table...
7e3bf50acddbec29609dd1dae38b6a83ca6c4ec5
sangdon1984/python_chap05
/Cal3.py
1,066
3.78125
4
#-*-coding:utf-8 class Calculator: def setNumber(self, first, second): self.first = first # 멤버변수 선언 self.second = second def plus(self): return self.first + self.second def minus(self): return self.first - self.second def multi(self): return self.first * self.sec...
0fbc0beb8ed348f4fb1b318e28e09c39fdb04f47
mdkallick/FinalProject
/boxcars-master.py
1,053
3.609375
4
__author__ = 'leilaselchaif' from Tkinter import * win = Tk() win.title('Boxcars') #import random lettlist = ['W''O''B''O''W''O''B''O''W''O''B''O''W''O''B'] def buttonClicked(event): print(int(button.cget("text"))) lettlist[int(button.cget("text"))], lettlist[int(button.cget("text")) + 1] = lettlist[int(butt...
537c415a1ae04f1f3c9772b8690a09f892ba3d55
chrome-rpg/pyglet_rpg
/lib/share/mathlib.pyx
2,034
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # #!/usr/bin/env python # -*- coding: utf-8 -*- # from math import hypot, floor from config import * from cpython cimport bool cdef class Point: "класс точек и векторов" def __init__(self, int x, int y): self.x = x self.y = y def __richcmp__(...
90b16e936287d75407c16f4411b0a2edc25e501b
forgxyz/cs50x
/pset6/bleep.py
935
4
4
#!/rsr/bin/env python3 from sys import argv def main(): # check command line argument - accept just one if len(argv) != 2: print("usage: python bleep.py dictionary.txt") exit(1) dictionary = argv[1] # open the dictionary file and write the banned words to a set ban...
be39a033b9fc3907bfbd8f8dc0b851088d1e678d
theGreenJedi/practicepy
/assert.py
269
3.796875
4
chars = [ 'Alpha' , 'Beta' , 'Gamma' , 'Delta' , 'Epsilon' ] def display( elem ) : assert type( elem ) is int , 'Argument Must Be Integer!' print( 'List Element' , elem , '=' , chars[ elem ] ) elem = 4 display( elem ) elem = elem / 2 display( elem )
107b8831d601e115bd90292ae27d770af4388ef6
bshee/aoc2017
/day4/high_entropy_passphrases_1.py
299
3.890625
4
#!/usr/bin/env python3 filename = input('Input the filename: ') if not filename: filename = 'input' with open(filename) as f: valid_count = 0 for line in f: words = line.split() distinct_words = set(words) if len(words) == len(distinct_words): valid_count += 1 print(valid_count)
06e679ca3048d5230cc9f4b9e28c126f705539c8
kamilhabrych/python-semestr5-lista10
/zad10_3.py
548
3.671875
4
def bezpowt(sl): #Check duplicates in dictionary if len(sl) == len(set(sl)): #Compare len of list and set(set removes duplicates) return 1 #Return 1 if dictionary hasn't duplicates else: return 0 #Return 0 if dictionary has duplicates sl1 = { 'Color1': 'Black', 'Color2': 'White', '...
a35804b62484f269d44c0e7caac680fb9432fa64
stiley/pyimage-work
/module1/contours-advanced-quiz.py
1,989
3.59375
4
# import the necessary packages ################################################################ # See this page for discussion https://gurus.pyimagesearch.com/quizzes/advanced-contour-properties-quiz/ ################################################################ # import the necessary packages import numpy as np ...
f2768f25bb8d8cf918fe759c835bc0b66ed31116
brod-cris/hello-bestie
/Day3_(10-12-2020)/appb.py
638
4
4
# input('Enter the student name:') # input('Enter their marks following:') # Mark_1 = eval(input('Mark_1:')) # Mark_2 = eval(input('Mark_2:')) # Mark_3 = eval(input('Mark_3:')) # Mark_4 = eval(input('Mark_4:')) # Mark_5 = eval(input('Mark_5:')) # total = Mark_1+Mark_2+Mark_3+Mark_4+Mark_5 # print(f'{Mark_1} + {Mark_2} ...
b3548c4258713c77903f2f73693d395f4cce1301
brod-cris/hello-bestie
/Day3_(10-12-2020)/app.py
1,228
3.8125
4
# good # a = 10 # b = 5 # c = a + b # print(f'{a} + {b} = {c}') # a + b = c => 10 + 5 = 15 # good # a = eval(input('Enter a value for a:')) # b = eval(input('Enter a value for b:')) # c = a + b # print(f'{a} + {b} = {c}') # good # a,b = eval(input('Enter the value of a,b:')) # print(f'{a} + {b} = {a+b}') # testing #...
a50d1b4cae1a821587a70212725b81a658ec0bf6
ZhouyaoXie/DisjointSet
/disjointSet.py
1,063
4.09375
4
class disjointSet: def __init__(self, n): """ Initialize a disjoint set object. params: n: size of the disjoint set """ self.rank = [1 for _ in range(n)] self.parent = list(range(n)) def union(self, x, y): """ Un...
0f8cc167c0447ed209bb00b04ebdb2cb3053b2fb
hm06063/OSP_repo
/py_lab/aver_num.py
282
4.28125
4
#!/usr/bin/python3 if __name__ == '__main__': n = int(input("How many numbers do you wanna input?")) sum = 0 for i in range(0,n): num = int(input("number to input: ")) sum += num mean = sum/n print("the mean of numbers is {}".format(mean))
c021462560faa5590f7fb909e61a7100bdf76d26
33marvil/OOP2-en-Python-3--Bird-Class
/test_bird.py
859
3.640625
4
import unittest from bird import Bird class BirdTests(unittest.TestCase): def setUp(self): self.func = Bird("Billy") def test_name_returns_name_of_bird(self): self.assertEqual(self.func.name, "Billy") def test_jump_sends_message_when_jump(self): self.assertEqual(self.func.jump(), "Saltando...") def test...
1d261767c57f3c4558b3cd2d0b34542103483538
Jason8955/python
/user_bank.py
1,526
3.890625
4
class BankAccount: def __init__(self, int_rate, balance): self.int_rate = 0.02 self.balance = 0 def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): self.balance -= amount return self def displ...
26d40f1edbc5f88ce1ca02dc4e62f5c15c0fe948
slubambo/SLC-UG
/how_to_make_an_egg_for_breakfast.py
1,062
3.96875
4
print("How to make an egg for breakfast") print("Get your eggs and smash them into a container") print("mix them up hard with also the preffered ingredients") print("Put in a frying pan that has ready oil") print("turn it around til ready") your_breakfast = "~ ~ ~ You can now have your yummy egg breakfast ~ ~ ~" ...
083eecd8421f3cf0b21b3ad28a9a53337a6d3423
ome94/budget
/budget.py
495
3.625
4
class Budget: def __init__(self, category, amount): self.category = category self.amount = amount def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def transfer(self, amount, category): self.withdraw(amount) category.deposit(amount) food ...
a438e6fc5969eb10854a1e5e43b08b9c4ab58029
wang-sj16/Intro2DL
/homework-2/homework_2.py
7,082
3.6875
4
# coding: utf-8 # # Homework-2: MLP for MNIST Classification # # ### **Deadline: 2018.11.04 23:59:59** # # ### In this homework, you need to # - #### implement SGD optimizer (`./optimizer.py`) # - #### implement forward and backward for FCLayer (`layers/fc_layer.py`) # - #### implement forward and backward for Sigm...
69b6834da1c1fc50aeaf0648d8ca4b82cc334e6d
janiosl/python.ds
/fundamentos/programa02.py
437
3.90625
4
print('Python DS - Lógica Condicional') print('=' * 40) nome = input('Digite o seu nome: ') print(f'Olá {nome}!') print('-' * 40) primeiroNum = int(input('Digite um número inteiro: ')) segundoNum = int(input('Digite outro número interiro: ')) print('-' * 40) soma = primeiroNum + segundoNum print(f'Resultado: {soma}...
757422e755c10a99632eaa453f46db7d567388e7
janiosl/python.ds
/fundamentos/IntroPython.py
600
3.765625
4
nome = 'Janio' ano_nascimento = 1981 tem_filhos = True idade = 2021 - ano_nascimento print('Relatório:') print('Nome:', nome) print('Idade:', idade, 'anos') if tem_filhos == True: print('Tem filhos') else: print('Não tem filhos') print('Tipos das variáveis') print(type(nome), type(ano_nascimento...
5778fd4417f41c9b830f3bc7dde9f4419d90e123
janiosl/python.ds
/RPA/so_intro.py
1,360
3.8125
4
""" #RPA PYTHON – INTRODUÇÃO À INTERAÇÃO E CONTROLE DO SISTEMA OPERACIONAL #Python DS Tutorial para uso do código: https://youtu.be/KsXIjCl1S5g """ import os #Alterar diretório de trabalho e conferir #Substituir pelo caminho desejado caminho = r'D:\Python' os.chdir(caminho) os.getcwd() #Criar um diretó...
038d88c055421deaad3d8fd1c7d875164d0d370c
janiosl/python.ds
/pySelfDS/ler_csv.py
692
3.9375
4
import csv def ler_csv(filename): """ Função para leitura de dados de um arquivo csv e registro em listas para utlização em análises. Argumentos: filename = arquivo .csv a ser analisado OBSERVAÇÃO: A primeira linha deve ter os dados de tempo (meses, anos, etc.) e a segunda deve ...
3e831739549405839fbdbd6121ea2f9f63a363f7
janiosl/python.ds
/fundamentos/funcoes01.py
277
3.953125
4
""" Programa cria uma função simples para realizar contagem regressiva e em seguida a executva. Canal Python DS Aula de Fundamentos de Python Criação de função simples sem argumentos """ def regressiva(): for k in range(10, -1, -1): print(k) regressiva()
424dc4700b12587a3504836abb4fd7dcb36f8731
janiosl/python.ds
/RPA/navegar.py
1,375
3.8125
4
""" * Programa navega em opções em uma página web, mas poderia ser adaptado para uma aplicação. * Após chegar em um formulário digita um termo para busca e pressiona a tecla enter. * Em seguida acessa o primeiro resultado da busca e copia a primeira palavra do título. * O resultado da cópia é gravado em uma variável e ...
127a526ba32dc3bec70666555dd1669112ab580d
cantus145/InvoiceTool_Python
/invoice_tool.py
1,030
3.859375
4
########################################################## # 106 11 - 12 title = "\n 106年 11-12 月" allinvos = [ "343","249","891","491","437"] ########################################################## # 判斷3位數 def isValidInput(str): return len(str) == 3 def printGoal(invo): idx = 5 while idx >...
2944200c6b9da30beacfd34d42063fa9297d11ac
veronicz/ML-MNIST
/code/utils.py
3,274
3.5625
4
import os.path import matplotlib.pyplot as plt import numpy as np from scipy import stats from scipy.optimize import approx_fprime from scipy.spatial import distance def mode(y): """Computes the element with the maximum count Parameters ---------- y : an input numpy array Returns ------- ...
fef5d74c772b75ba6e976e83a848233649484fce
yc-xiao/interview
/design/design_pattern/builder.py
1,452
4.1875
4
""" 建造者模式(Builder Pattern)将一个复杂对象分解成多个相对简单的部分,然后根据不同需要分别创建它们,最后构建成该复杂对象。 汽车 = 发动机 + 底盘 + 车身 产品 = 模块A(模块a1, 模块a2, ...) + 模块B(模块b1, 模块b2, ...) + 模块C(模块c1, 模块c2, ...) 组合使用,Python Logging 使用场景: Logging 组合选择 """ class Engine(): def __str__(self): return f'Engine' class E...
958af8020826be805c859bdbdc0c0b67361a8478
topherPedersen/coco.py
/coco.py
4,850
3.890625
4
import sys # Check Python Version Number (Python Version 3+ Required) if sys.version_info[0] < 3: print("ERROR: 'pmode' Module Requires Python Version 3.0 or Higher") exit() # kill script else: # Import the Tkinter & Turtle Graphics Modules import tkinter import turtle screen = turtle.Screen() scr...
9eb992681ac152a19044c8856ae228e046feb00f
zatserkl/learn
/python/plot_err_asym.py
760
3.859375
4
# Introduction to Python for Engineers and Scientists.pdf import matplotlib.pyplot as pl import numpy as np x = np.arange(0, 4, 0.2) # generated data point from 0 to 4 with step of 0.2 y = 2*x # y = e^(-x) print x #[0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4 3.6 3.8] err...
86b2340e9602b2aa3eab5c4fd4fd3dc1b9b9cf9a
zatserkl/learn
/python/numpy_matrix_solve.py
1,756
4.28125
4
################################################# # See the final solution in the numpy_matrix.py # ################################################# import numpy as np """ Solve equation A*x = b where b is represented by ndarray or matrix NB: use matmul for the multiplication of matrices (or arrays). """ def solv...
cf44c9820ab6c0e5c8ae0c270c5f097cd6c79550
zatserkl/learn
/python/class_set.py
1,286
4.15625
4
class Set: """Implementation of set using list """ def __init__(self, list_init=None): """constructor""" self.list = [] if list_init is not None: for element in list_init: self.list.append(element) """From http://stackoverflow.com/questions/1436703/differ...
1ed37cff2ecb671c36dfda6926afbc503e22e423
zatserkl/learn
/python/fit_gauss.py
5,290
3.75
4
"""Gaussian fit demo. Andriy Zatserklyaniy <zatserkl@fnal.gov> Feb 6, 2017 """ import math import random import matplotlib.pyplot as plt from collections import Counter import numpy as np # arrays for fit from scipy.optimize import curve_fit # fitting routine def flat_distribution(N=100): ...
12ee22a307609371327570b547986799ea95ceec
zatserkl/learn
/python/central_limit_theorem.py
1,783
3.875
4
"""Illustration of the Central Limit Theorem Andriy Zatserklyaniy <zatserkl@fnal.gov> Feb 4, 2017 """ from __future__ import division import random, math import matplotlib.pyplot as plt N = 10000 # the number of sums n = 12 # the number of randoms in each sum # # Central Limit Theorem # --------------...
62cbd1bb70a63056c31bf7eb173481b151060d0b
zatserkl/learn
/python/plot.py
849
4.1875
4
"""See Python and Matplotlib Essentials for Scientists and Engineers.pdf """ import matplotlib.pyplot as plt x = range(5) y = [xi**2 for xi in x] plt.figure() # fig = plt.figure() # create a figure pointed by fig # fig.number # get number of the figure pointed by fig # plt.gcf().number # get numb...
821e0a1793c5fb08e85102dfe2f73d3744f24589
zatserkl/learn
/python/generator_comprehension.py
481
4.3125
4
# modified example from https://wiki.python.org/moin/Generators nmax = 5 # Generator expression: like list comprehension doubles = (2*n for n in range(nmax)) # parenthesis () instead of brackets [] # print("list of doubles:", list(doubles)) while True: try: number = next(doubles) # raises StopIterat...
2e449b4aeae7d9409d28e6ff4ae686b58ab315b5
zatserkl/learn
/python/numpy_matrix.py
1,614
4.375
4
################################################################### # This is the final solution: use array for the matrix operations # ################################################################### """ See https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html NumPy matrix operations: use arrays ...
a2006a17a7dcbe8da282bb0327aeaff2d74bf6f2
rodrigor/IntroProgramacao-Code
/ExemploListaNomesFuncao.py
413
4
4
def ler_continua(): opcao = "" while True: opcao = input("Continua? [s/n]") if opcao == "s": return True elif opcao == "n": return False else: print("Opção inválida!") continua = True nomes = [] while continua: nome = input("Digite o n...
bbfa8595002901875ce4e6dd72babcf52921757f
rodrigor/IntroProgramacao-Code
/2014.2-Prova1/prova1-solucao2.py
2,495
4.25
4
# Resolução da prova1: Solução 01 # Prof. Rodrigo Rebouças # [Uma lista, sem função, sem validação] # Nesta solução usamos uma lista para armazenar # o nome e a média do aluno. O nome do aluno # fica armazenado na primeira posição de cada elemento # e a média do aluno fica armazenado na segunda posição NOME = 0 # Va...
d5dbeb875734ee56b83dab6d5fb34fce0012a061
missTanya/device_health_check
/parser.py
493
4.09375
4
# /usr/bin/python #parser_csv-to-dict.py import csv import pprint def csv_in_parser(file): """This accepts passed file in csv format """ print('PARSER saying hello...') with open(file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for line in csv...
77edd2237e10cee3807d4a570282acf0e731e21e
rupakg/programming_for_kids
/code/chapter_better_maze/better_maze.py
3,662
3.515625
4
# -*- coding: utf-8 -*- import pygame class Maze: start = ( 0, 0 ) end = ( 0, 0 ) user = ( 0, 0 ) maze = [] moves = 0 dirty = [] user_surface = None maze_surface = None def __init__ ( self, maze_file ): self.load_maze( maze_file ) def load_maze ( self, maze_file ): self.maze = [] f = open( maze_...
6cd2c77ddab011715fcedf231ce4b7c77bf1ec29
RuchaCB/SSW_567_HW02
/TestTriangle.py
2,078
4.09375
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html ha...
3ee0c0cbe58cef983379ed830bf3c1788aa1c2d9
jpasqui/Text-Snake
/snake.py
3,342
3.78125
4
import time import os import keyboard from random import choice def GameOver(score): print("Game Over!") print(f"Score: {score}") print("Press the R key to retry or Q to quit.") while True: if keyboard.is_pressed("R"): GameLoop() return if keyboard.i...
78fcdf0176b37439574703f39efcf2feb2a8a226
seapp/seapp
/interpreter/interpreter/grammar/arguments_rules.py
3,876
3.5
4
""" Grammar rules for (ASL) arguments of primitives. Author: + Alessandro Pischedda <alessandro.pischedda@gmail.com> + Marco Tiloca <marco.tiloca84@gmail.com> + Francesco Racciatti <racciatti.francesco@gmail.com> Maintainer: + Francesco Racciatti <racciatti.francesco@gmail.com> """ # Import the le...
77ac719d12cac6de5a4b33b21267d62c0f2a1dc9
AjaySabareeshB/COMP-PROJECT
/movies.py
4,608
4.125
4
#movies #the date and timing function shd come before the seat type...define and make changes #make variables like date,movie and all global import random n=0 movie="" date="" price=0 cost=0 type='' nu=0 l=['SHAWSHANK REDEMPTION','INCEPTION','INTERSTELLAR','FORD VS FERRARI'] def dates(): global movie ...
b02955a662cd3093d93d4783334982e507492132
liyangwill/python_repository
/plot.py
1,395
4.15625
4
# Print the last item from year and pop print(year[-1]) print(pop[-1]) # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Make a line plot: year on the x-axis, pop on the y-axis plt.plot(year,pop) plt.show() # Print the last item of gdp_cap and life_exp print(gdp_cap[-1]) print(life_exp[-1]) # Make...
3a38ba0651b181c58610a456815a2752457923ba
uraboer/Data-Structure-and-Algorithm-notes
/demo03.py
3,929
3.953125
4
# coding:utf-8 # Binary Tree :二叉树 # 二叉树是每个节点最多有两个子树的树结构,子树有左右之分,二叉树常被用于实现二叉查找树和二叉堆 # 二叉树的第i层至多有2^(i-1)个结点;深度为k的二叉树至多有2^k-1个结点;对任何一颗二叉树T,如果其终端结点树为n_0,度为2的结点数为n_2,则n_0=n_2+1。因为度为1的节点对度为0的节点数目不会有影响,而每增加一个度为2的节点总的来说会相应增加以个度为0的节点 # 一棵深度为k,且有2^k-1个节点称之为满二叉树;深度为k,有n个节点的二叉树,当且仅当每一个节点都与深度为k的满二叉树中序号为1至n的节点对应时,称之为完全二叉树。完全二叉树中重在...
9e3ea5f3b6e71703862e0b66131ac22695e978da
khushalchaudhari/SnakeWaterGunGame
/hry,snakeWaterGun.py
1,914
3.8125
4
import random ref=['s','w','g'] chance=7 no_chance=0 co_point=1 your_point=1 print("snake water gun game \n s for snake \n w for water \n g for gun \n if you enter different choice you loss") while no_chance<chance: human=input("\n") computer=random.choice(ref) if human==computer: print(...