blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
66f892f6decc05f0441de5373b17b8797e29cfb6
janina3/Python
/CS 1114/rec11.py
1,704
3.71875
4
#!/usr/bin/python ''' cs1114 Submission: rec11 Programmer: Janina Soriano Username: js7817 The purpose of this program is to work with HTML files. Assumptions: Depends on the function Constraints: None This program creates an HTML file. ''' import random def openMyFile(): '''Opens and returns my HTML file'...
7065987287e1aafef1b7a319606234249075378d
survivor-rommel/Tarea2_ALN_GRUPOA
/CODIGOS_GRUPO-A/Paredes Escobedo, Fernanda/VandermondeMatrix.py
1,292
3.671875
4
## Itera sobre cada número en el vector de entrada n veces, siendo n el número de columnas en la matriz op y la salida ## un vector intermedio. Utilice una fórmula de orden diferencial basada en la condición creciente y decreciente. ## Reforma el vector intermedio usando el tamaño del vector de entrada (filas) yn (co...
f93708033c5f19e6d445aa77105d59b121449400
survivor-rommel/Tarea2_ALN_GRUPOA
/CODIGOS_GRUPO-A/Carhuas Heredia, Arodi Sotil/condiciones.py
1,492
3.515625
4
import numpy as np def show_matriz(A): for i in A: for j in i: print(j,end=" ") print(" ") def matVander(x): v=[] for i in range(x): print("Ingrese numero de la fila ",i,end=" ") a = int(input()) au = [] for j in range(x): au.append(pow(a,j)) pass v.append(au) pass v=np.fliplr(v) show_m...
72c147a607227967de281566b3b7aa6e302d1874
mondracode/AlgorithmsUN2021I
/Lab8/Code/7_last_digit_of_the_sum_of_fibonacci_numbers_again/fibonacci_partial_sum.py
517
3.765625
4
# Uses python3 import sys def fibonacci_partial_sum_fast(from_, to): if(to < from_): return -1 fib = [] fib.append(0) fib.append(1) sum = 0 for i in range(2, 60): fib.append(fib[-1] + fib[-2]) from_ = from_ % 60 to = to % 60 if(to < from_): to += 60 ...
c1af9095cac5f003e2e6a32f31ae00c634a85d03
akshairajendran/Game-of-Life
/main.py
851
3.515625
4
__author__ = 'arajendran' import numpy as np from matplotlib import pyplot as plt from matplotlib import animation #create demo array Z = np.random.randint(0,2,(256,512)) def genarray(r,c): return np.random.randint(0,2,(r,c)) def neighbors(Z): N = np.zeros(Z.shape, dtype=int) N[1:-1,1:-1] += (Z[:-2, :-2...
e133a078a76f99e03d5e5b09ba6267d4776c87e5
ElisevanderPol/grid_world
/treasure_hunt.py
7,677
3.65625
4
import numpy as np class TreasureHunt(object): """ Simple toy problem with the goal to find the rewarding state, while avoiding the states that give punishment """ def __init__(self, n_states=4, grid_shape=(2, 2), slip=0.1): """ Initialize the toy problem by specifiying the number ...
4243bbad593690a6c33cade523d52121653eedbd
trivedimargiv9/My_codes
/Tic_tec_toe.py
4,186
3.8125
4
#from IPython.display import clear_output board_list = [' '] * 10 def displsy_board(board_list): # clear_output() print(board_list[7] + ' | ' + board_list[8] + ' | ' + board_list[9]) print(board_list[4] + ' | ' + board_list[5] + ' | ' + board_list[6]) print(board_list[1] + ' | ' + board_list[2] +...
60959205416be9d4000ca434436e8060fddc7b8d
Naif18/PythonCourse
/Secondweek/Eleventh.py
158
4
4
x = 5 print(x > 8 or x ) #printed False x=["Apple" , "Banan"] y=["Apple" , "Banan"] print (x is y) #printed true x=["Apple" , "Banan"] y=x print (x is y)
56ee3ae3117a52d2888d5f3a526a1c62d93fda24
Naif18/PythonCourse
/fifthweek/Thirtieth.py
430
3.90625
4
#ٌrange Function: set of code a specified number of time for x in range(8): print(x) for z in range(4 , 11): print(z) #Also you can sspecify the number of incrases for z in range(4 , 60 , 10): print(z) else: print("Finally finished!") #nested loops. ... col=["Red" , "White" , "Green" , "Yellow"] ...
4b58dad16a37ac08f2a63dde4fb8d6a6aa8e85a1
Naif18/PythonCourse
/ThirdWeek/Sixteenth.py
274
4.34375
4
tuplee=(3) print(tuplee) complextuple=(5,4,3,77,"Python") print(complextuple) print(complextuple[4]) #You cann't change tuple items. it's unchangeble #You cann't also inser or delete items (: for t in complextuple: print(t) del tuplee print (complextuple[2:5])
02f997b67063e263c0390d56d6682abc09383bde
jkooy/Python-programming
/encrypt_message.py
3,477
3.953125
4
import collections import string import re import random def encrypt_message(message,fname): ''' Given `message`, which is a lowercase string without any punctuation, and `fname` which is the name of a text file source for the codebook, generate a sequence of 2-tuples that represents the `(line number, ...
1b3a577ce3acee3e8437b91b08da3320b1d38dac
jkooy/Python-programming
/threshold_values.py
4,667
4.25
4
def map_bitstring(bitstrings): ''' Write a function map_bitstring that takes a list of bitstrings (i.e., 0101) and maps each bitstring to 0 if the number of 0s in the bitstring strictly exceeds the number of 1s. Otherwise, map that bitstring to 1. The output of your function is a dictionary of the ...
920c0a5a2a145e7523a3bb006af3437ff62fd082
jkooy/Python-programming
/testpoly.py
9,175
3.875
4
import math class Polynomial(object): ''' Class to solve polynomial problem ''' def __init__(self, the_dict=None): # check that what is passed in is a dictionary assert isinstance(the_dict, dict) # check that values are type int for index, value in the_dict.items(): ...
0616b23a9ecaa7c77fb9c3cc7bac4e34ef4b7f4e
jkooy/Python-programming
/Grid Path Searching.py
1,088
4.1875
4
def count_paths(m,n,blocks): ''' This functiom starts at the upper left and only moving downwards and rightwards, find the number of connected paths between the top-left square and the bottom right square by traversing only the intermediate squares with the . symbol. The start and end positions are never be mar...
a8fa6cd79db8b5c0f7400a7a8780a6feb8cc5db3
wecnor/2.1.2
/cook_book.py
1,749
3.5625
4
def read_json(): import json with open('cook_book.json', encoding='utf8') as f: cook_book = json.load(f) return cook_book def read_yaml(): import yaml with open('cook_book.yml', encoding='utf8') as f: cook_book = yaml.load(f) return cook_book def get_shop_list_by_dishes(cook_...
290e94b23543e2b932dfb4c70dd8b31abb19092b
kingjo47/scikit-image
/doc/examples/filters/plot_threshold_minimum.py
904
4.03125
4
""" ================================== Minimum Algorithm For Thresholding ================================== The minimum algorithm takes a histogram of the image and smooths it repeatedly until there are only two peaks in the histogram. Then it finds the minimum value between the two peaks. After smoothing the histo...
06e0e3807ec9cb8a6530cff64747f4aeaa954031
NickBarty/Python-Interactive-Kivy-Project
/test_song.py
1,072
4.21875
4
""" Tests each method of the Song class and shows how each of the attributes work at an individual level """ from song import Song # test empty song (defaults) song = Song() print(song) assert song.artist == "" assert song.title == "" assert song.year == 0 assert song.required # test initial-value song song2 = Song("...
9f927c6da0f37f0fc983d79c196d56ea0dd24121
PreethiD15/program
/vowelorconsonant.py
160
3.921875
4
string=input() li=['a','e','i','o','u'] if(string>='a'and string<='z'): if(string in li): print("Vowel") else: print("Consonant") else: print("Invalid")
b8d27a088b0b63ea42417691bafd77a9c3f0b1dd
artur-oganesyan/python_basics
/lesson_2/task_4.py
129
3.71875
4
words = input('Enter a few words: ') for n, w in enumerate(words.split(), 1): print(f'{n}. {w if len(w) <= 10 else w[:10]}')
14e13ac3431355e41ff25c96113c18d10c9d85f5
artur-oganesyan/python_basics
/lesson_8/task_7.py
307
3.78125
4
class Complex: def __init__(self, number): self.complex = complex(number) def __add__(self, other): return self.complex + other.complex def __mul__(self, other): return self.complex * other.complex c_1 = Complex(5) c_2 = Complex(7) print(c_1 + c_2) print(c_1 * c_2)
1bdf02edf6f75411fce84f1563885ec2583a044b
artur-oganesyan/python_basics
/lesson_6/task_5.py
740
3.515625
4
class Stationery: def __init__(self, title=None): self.title = title def draw(self): message = "Start drawing" if self.title is not None: print(message, "with", self.title) else: print(message) class Pen(Stationery): def draw(self): print("S...
1cb897ea38dd2a8c2e23dd59321eda096b19e78f
artur-oganesyan/python_basics
/lesson_3/task_1.py
470
4.03125
4
def divide(dividend, divisor): """ Quotient rounded to two decimal places """ try: dividend = float(dividend) divisor = float(divisor) result = round(dividend / divisor, 2) except ZeroDivisionError: result = "Division by zero is impossible" except ValueError: ...
7c1b5f6dd9e59d769c5da45a517a372fe44ecad1
artur-oganesyan/python_basics
/lesson_7/task_1.py
623
3.796875
4
class Matrix: def __init__(self, matrix): self.matrix = matrix def __str__(self): return "".join(" ".join(map(str, row)) + "\n" for row in self.matrix) def __add__(self, other): result = list() for self_row, other_row in zip(self.matrix, other.matrix): new_row =...
995f8f013a619c3be0d614e0ed3797c3778950a4
sukli/EEB177-Final-Question3
/problem3-1.py
1,178
3.828125
4
#! /usr/bin/python from bs4 import BeautifulSoup from urllib import urlopen # given the url, fetch and return the html source using urlopen def get_page_source(url): f = urlopen(url) source = f.read() f.close() return source # use BeautifulSoup to extract headlines from the raw html def extract_news...
9c8e3fddeee2b6316287c967ab77fe60f4495d40
dahaihu/start
/leetcode/并查集.py
4,148
4
4
# 130. 被围绕的区域 # 给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 #   # # 示例 1: # # # 输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]] # 输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] # 解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被...
a0db4d6ad20b0d6200116dbbefffcdb71fdaee43
dahaihu/start
/leetcode/全排列.py
1,029
3.5625
4
class Permute: def __init__(self): self.result = [] def permute(self, nums): self._permute(nums, []) return self.result def _permute(self, nums, internal_result): if len(nums) == 1: self.result.append(internal_result + [nums[0]]) return for i...
b1056b0f4606fabd10f9110a9189c298390c54e3
xiaolinangela/cracking-the-coding-interview-soln
/Ch1-ArraysAndStrings/1.2-CheckPermutation.py
506
4.25
4
def check_permutation(str1, str2): if len(str1) != len(str2): return False else: return sorted(str1) == sorted(str2) if __name__ == "__main__": if check_permutation("geeksforgeeks", "forgeeksgeeks"): print("str1 is permutation of str2") else: print("str1 is n...
6a6a0ea7ad53dbe4bc7b4ecab1d1396f43d5ad9a
xiaolinangela/cracking-the-coding-interview-soln
/Ch4-TreesAndGraphs/4.1-RouteBetweenNodes.py
848
3.859375
4
from collections import defaultdict import queue class Graph: def __init__(self): self.graph = defaultdict(list) def addEdge(self,u,v): self.graph[u].append(v) def BFS(self,s,t): q = queue.Queue() q.put(s) visited = set() visited.add(s) whil...
48d1ff596f5cff2082a383a569ab875a9af89c19
xiaolinangela/cracking-the-coding-interview-soln
/Ch1-ArraysAndStrings/1.8-ZeroMatrix.py
1,551
3.6875
4
def zero_matrix(matrix): set_row = set() set_column = set() for i in range(0, len(matrix)): for j in range(0, len(matrix[i])): if j in set_column and matrix[i][j] != 0: matrix[i][j] = 0 elif matrix[i][j] == 0: set_row.add(i) ...
71950428fb43953ab58f023c63d0514152bcf63a
xiaolinangela/cracking-the-coding-interview-soln
/Ch8_RecursionDP/8.10-FloodFill.py
699
3.515625
4
def floor_fill(image, sr, sc, newColor): original_color = image[sr][sc] if original_color == newColor: return image def helper(sr, sc): if image[sr][sc] == original_color: image[sr][sc] = newColor if sr - 1 >= 0: helper(sr-1, sc) if sr + 1...
c274794ab48e74a7fe01efbf5191ee85f829cdef
xiaolinangela/cracking-the-coding-interview-soln
/Ch1-ArraysAndStrings/1.9-StringRotation.py
472
3.96875
4
def is_substring(s1, s2): for i in range(len(s1)): if s1[i] == s2[0]: s1_sub = s1[i:(i+len(s2))] if s1_sub == s2: return True return False def string_rotation(s1, s2): length = len(s1) if length == len(s2) and length != 0: s1s1 = s1 +...
e437a465488f48dded96ae809e323bdb69ccaba0
xiaolinangela/cracking-the-coding-interview-soln
/Ch8_RecursionDP/8.4-PowerSet.py
201
3.5
4
def power_set(nums): output = [[]] for num in nums: output += [curr + [num] for curr in output] return output if __name__ == "__main__": s = [1, 2, 3] print(power_set(s))
7655490aec82d7f4e2c07ba668b0d9ba9eaeb2dd
xiaolinangela/cracking-the-coding-interview-soln
/Ch8_RecursionDP/8.11-Coins.py
575
3.59375
4
def coins_change(coins, amount): table = [float('inf') for x in range(amount+1)] table[0] = 0 for i in range(1, amount+1): if i in coins: table[i] = 1 else: temp = [float('inf')] * len(coins) for j in range(len(coins)): if i > coins[j]: ...
24d943e8855e1f8956353b80ecd563bff31940ae
asiahbennettdev/Code-Wars
/digitize.py
337
3.953125
4
#Given a non-negative integer, return an array / a list of the individual digits in order. #Examples: #123 => [1,2,3] #1 => [1] #8675309 => [8,6,7,5,3,0,9] def function(num): list = [] if num == 0: return[0] while num: num, x = divmod(num, 10) list.append(x) list.reverse() ...
07572fdbb511178e7a1781de40b274e50f332c5b
BenSisserman/ECE470_catkin
/src/lab6pkg_py/scripts/blob_search.py
6,203
3.5
4
#!/usr/bin/env python import cv2 import numpy as np # ============================= Student's code starts here =================================== # Params for camera calibration theta = 0 beta = 740.0 tx = -0.245662162162 ty = -0.0609054054054 # Function that converts image coord to world coord def IMG2W(x,y): ...
c6905221bc0c4906f068215e6a09922c84ec2c16
sanju20000/Alien_Forces_proj
/scoreboard_module.py
2,684
3.515625
4
import pygame.font from pygame.sprite import Group from rocket_module import Rocket class ScoreBoard(): """A class to report scoring information""" def __init__(self, setting_obj, screen, stat_obj): """Initialize scorekeeping attribute""" self.screen = screen self.screen_rect = screen.g...
7b36c1d91529d4b5081a49ee67ee0eb25451dc43
Crakshoot/password_generator
/password_generator.py
5,017
4.0625
4
''' Demonstrates the ability to randomly insert characters into a string that meets specific password requirements. Input: Command Line Argument Optional Length Generate a password ( of a given length if provided) that meets the password requirements from Project 1 Output: A Valid Password Example: U:\private\genera...
465312c78760402750146ab05826b87ac23e728f
Mak-maak/Python-Fundamentals
/if and elif statements.py
615
4.25
4
#individual if bodies if species == "cat": print("Yep, it's cat.") if species != "cat": print("Nope, not cat.") #if and else statements if species == "cat": print("Yep, it's cat.") else: print("Nope, not cat.") #if elif and else statements together if donut_condition == "fresh": buy_score ...
e3fb8df0767d675c57a13a08427a6359639112dc
Mak-maak/Python-Fundamentals
/functions.py
295
3.765625
4
#Functions #piece of code to be executed multiple times firstNumber = 2 secondNumber = 3 total = firstNumber + secondNumber print(total) #function definition def AddNumber(): firstNum = 2 secondNum = 3 total = firstNum + secondNum print(total) #invoke AddNumber() AddNumber()
cecbe854a85ecb156c728d540993c6e396837eae
Mak-maak/Python-Fundamentals
/changingCase.py
638
4.5
4
#Changing case cleanest_cities = ["Cheyenne", "cheyenne", "Santa Fe", "santa fe", "Tucson", "tucson", "Great Falls", "great falls", "Honolulu", "honolulu"] # input string from user city_to_check = input("Enter your city: ") #changing its case using pre-built function .lower city_to_check = city_to_check.lower() ...
cf518e98d1e17e2ff638593339fa30dee24df169
Mak-maak/Python-Fundamentals
/Dictionaries picking out information.py
255
3.53125
4
#Dictionary: How to pick information form dictionaries customer_29876 = {"first name": "David", "last name": "Elliott", "address": "4803 Wellesley St."} #accessing the dictionary values by passing its key to print its value print(customer["firstName"])
5198152a013d5b4e3e721114d30e6630663295fc
coltonneil/IT-FDN-100
/Assignment 7/hw7.py
3,118
3.5625
4
#!/usr/bin/env python3 """ requires Python3 and BeautifulSoup4 this script takes two arguments from the command line, a url and an html tag type, and returns all of the attributes of the requested tag type from the given urls response content, if two arguments are not given at the command line the script will ask the...
dca49b2d57afdf2a8b8944c2ede55c83afb36d08
navink/Kaggle-Best_Buy_Hackathon
/VectorSpaces.py
2,926
3.5
4
from Parser import Parser from sets import Set from numpy import dot from numpy.linalg import norm class VectorSpaces: """ A algebraic model for representing text documents as vectors of identifiers. A document is represented as a vector. Each dimension of the vector corresponds to a separate term. If a term occ...
4fdc5390a6e5a4d6332eff99979ea9f0a83a3c76
aafeliz/twitter
/President_Project/SentimentAnalysis.py
3,558
3.65625
4
from nltk import tokenize import nltk.data import urllib as url #nltk.download() # READ ME ''' - using pip install nltk - You need to download https://github.com/japerk/nltk-trainer repo - install it using following command: python setup.py install - open up python, import nltk, then do nltk.download(), download all ...
9584abd8ca2c5f7dd7740b2781a21b165d94d854
SerhiiMart/freeCodeCamp-Python-courses-projects
/Probability Calculator/prob_calculator.py
1,238
3.5625
4
import copy import random # Consider using the modules imported above. class Hat: def __init__(object, **balls): object.balls = dict(balls) object.contents = [] for colour, number in object.balls.items(): for i in range(number): object.contents.append(colour) de...
05d584fd2754e077bcba58ada0ab0d305388478e
aelhor/carProblem
/car.py
1,517
3.5625
4
''' [ ['x', 'x', 'x', 'x', 'x', 'x'], ['x', ' ', ' ', ' ', ' ', 'x'], ['x', ' ', ' ', 'S', ' ', 'x'], ['x', ' ', ' ', ' ', '#', 'x'], ['x', ' ', ' ', ' ', ' ', 'x'], ['x', 'x', 'x', 'x', 'x', 'x'] ] ''' import random def getDirection(x, y, n) : dirctions...
05b13e9f55c448fb7cbc4505af6847a8e9eb9607
elliebui/technical_training_class_2020
/data_structures/weekly_project/task_3.py
3,988
3.9375
4
import sys from queue import PriorityQueue from collections import defaultdict class HeapNode: def __init__(self, char, freq): self.char = char self.freq = freq self.left = None self.right = None def __lt__(self, other): return self.freq < other.freq def get_frequenc...
d55fa4bded0a28f4eb09e3966d8e122f7326452e
elliebui/technical_training_class_2020
/data_structures/trees/height.py
861
4.1875
4
# Write a function to find the height of this binary tree! # A # / \ # B C # / \ # D E # \ # F def find_height(tree): """ Find the height of a binary tree Args: tree(object): Input binary tree Returns: int: The height of the tree """ if not tree: ...
0f51c9fc3785085818dd49eac6718e8f6248408b
elliebui/technical_training_class_2020
/data_structures/trees/bst_lowest_common_ancestor.py
1,711
4.21875
4
# Find the lowest common ancestor of two nodes in the tree. # # Lowest common ancestor is the loweest node in which the two provided nodes are decendents. For example in the tree below the selected nodes of 1 and 6 give us a lowest common ancestor of 5 as its the lowest amount in which both nodes are decendents. # # Gi...
698464decbfa754a76ea842ef8695488999d629c
elliebui/technical_training_class_2020
/introduction/P0/Task4.py
2,300
4.15625
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) # Lists to store numbers that are sending a...
df705d6344fd847b9402332abd547210241f21cd
elliebui/technical_training_class_2020
/data_structures/recursion/recursion_reverse_string.py
712
4.5625
5
def reverse_string(input): """ Return reversed input string Examples: reverse_string("abc") returns "cba" Args: input(str): string to be reversed Returns: a string that is the reverse of input """ n = len(input) if n <= 1: return input else: r...
99d1f9850718e28bf59833e687a1d5663cf13634
elliebui/technical_training_class_2020
/data_structures/arrays_and_linked_lists/strings/anagram_checker.py
937
4.46875
4
def anagram_checker(str1, str2): """ Check if the input strings are anagrams Args: str1(strings),str2(strings): Strings to be checked if they are anagrams Returns: bool: If strings are anagrams or not """ # Remove all spaces in both strings and make all characters lowercase ...
9a65b4ec15d4bf6f1706f958c3556b8e9537f1d3
elliebui/technical_training_class_2020
/data_structures/arrays_and_linked_lists/linked_lists/detecting_loops.py
1,501
4.34375
4
from data_structures.arrays_and_linked_lists.linked_lists.model.linked_list import LinkedList def iscircular(linked_list): """ Determine wether the Linked List is circular or not Args: linked_list(obj): Linked List to be checked Returns: bool: Return True if the linked list is circular,...
48aca82bb5f1f0ea0cf59b7e21e93dc1cc0f159b
elliebui/technical_training_class_2020
/basic_algorithms/basic/binary_search_practice.py
2,754
4.46875
4
def binary_search(array, target): '''Write a function that implements the binary search algorithm using iteration args: array: a sorted array of items of the same type target: the element you're searching for returns: int: the index of the target, if found, in the source -1: if t...
b635ff28becafdd9e7af004a21a61553fce52518
wansook0316/problem_solving
/210708_백준_ROT13.py
452
3.90625
4
import string a = input() alphabet_lower = string.ascii_lowercase alphabet_upper = string.ascii_uppercase ret_string = "" for char in a: if char in alphabet_lower: pos = alphabet_lower.find(char) char = alphabet_lower[(pos + 13) % len(alphabet_lower)] elif char in alphabet_upper: pos =...
f5e0a4d925eb39f7b324bebab494decb83b00a50
TAardemae/adventure-game
/Adventure_game.py
4,112
3.96875
4
import time import random enemies = ['pirate', 'dragon', 'wicked fairie', 'troll', 'gorgon'] def print_pause(message_to_print, pause): print(message_to_print) time.sleep(pause) def intro(enemy): print_pause('You find yourself standing in an open field, filled with ' 'grass and yellow wi...
8ac3856c9c0167904997d110308ccf519677895e
Slambaa/project1
/start.py
410
3.671875
4
with open('countries.txt', 'r') as f: countrylist = [line.strip() for line in f] correctans = [] score = 0 while score < 196: answer = input("country name") if answer.lower() in countrylist: countrylist.remove(answer) correctans.append(answer) print("correct") ...
9993b32b14b73871aaacf06a1a6fb308d01b61cf
Percygu/algorithm
/leetcode/unduplicated_number.py
567
3.609375
4
''' 寻找数组里只出现一次的数字 ''' from typing import List class Solution: def singleNUmber(self,nums: List[int])->int: no_duplicated_table = {} for i in nums: try: no_duplicated_table.pop(i) except: no_duplicated_table[i] = 1 #no_duplicate...
25169654e6d286e6d2d56c12b59114eeab3d8e40
Percygu/algorithm
/leetcode/longestPalindrome.py
5,737
4.03125
4
''' 求字符串中的最长回文子串 ''' #中心扩散法 class Solution1: #中心扩散 def CenterPread(self,s,size,left,right): """ left = right 的时候,此时回文中心是一条线,回文串的长度是奇数,从一个相同的字符开始往两边扩散 right = left + 1 的时候,此时回文中心是任意一个字符,回文串的长度是偶数,从两个不同的字符开始往两边扩散 """ l = left r = right while l>=0 and r < s...
12e31d1def4586d127266ef2bdc7356ece55eb98
ethana1234/senior-project-MARL
/tictactoe/tttenv/envs/ttt_env.py
3,069
3.515625
4
import numpy as np import gym from gym import spaces BOARD_ROWS,BOARD_COLS = 3,3 TOTAL_BOARD_SPACES = BOARD_ROWS*BOARD_COLS COORD_TO_INDEX = lambda x : (x[0] * BOARD_ROWS) + x[1] # Class that implements the Gym Environment Interface class TicTacToeEnv(gym.Env): '''Class that implements the Gym Environment Interf...
84eb87771175e5f0b173c6069213fce9179afab3
demsp/python
/SnakeGame.py
1,449
3.5
4
from pygame import * from random import randint init() N, M=30, 20 Scale=25 w,h=Scale*N, Scale*M screen = display.set_mode((w,h)) Snake=[(5,5),(5,4),(5,3),(5,2),(5,1)] Apple=[(23,6),(9,15),(14,7),(2,11)] FIELD=Surface((w,h)) FIELD.fill((255,255,150)) for i in range(0,w,Scale): draw.line(FIELD,(0,0,0),(i,0),(...
5019ea92295ca24803c7b09dba8c6d5aaf5c537e
IHaoMing/LearnTensorflow
/creating_and_manipulating_tensors3.py
526
3.53125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 6 10:13:17 2018 @author: watec """ import tensorflow as tf with tf.Graph().as_default(): # Create a six-element vector (1-D tensor). primes = tf.constant([2, 3, 5, 7, 11, 13]) # Create a constant scalar with value 1. ones = tf.constant(1, dtype=tf....
a4d8efe6951f356d9e9ccb7dae060141afca4007
CreativeNob/Programing_Tasks
/Python/Average.py
216
4.1875
4
n=int(input("Enter the number of elements you want to insert in list: ")) a=[] for i in range(0,n): elem=int(input("Enter element: ")) a.append(elem) avg=sum(a)/n print("Average of elements of the list",avg)
205db3797dc536a217ea84af71396fa466486104
Mandhularajitha/function
/function.question.py
603
3.578125
4
# n=int(input("enter num")) # i=0 # sum=0 # x=[] # k=[] # while i<n: # n1=int(input("enter num1")) # n2=int(input("eter num2")) # x.append(n1) # k.append(n2) # p=x[i]+k[i] # sum=sum+p # i=i+1 # print(x) # print(k) # print(sum) # n=int(input("enter num")) # i=0 # sum=0 # sum1=0 # x=[] # k=[...
4b63a71086baacab1b40467b867733570b5e5e9d
terrellhu/python100day
/day04/guess_the_number.py
313
3.65625
4
import random answer = random.randint(1, 100) counter = 0 while True: counter += 1 number = int(input('number=')) if number > answer: print('有点大') elif number < answer: print('有点小') else: print('success!') break print('total count=%d' % counter)
5efa6f64b36ff0197328eaa5e9ec6d1b2c50ddc8
terrellhu/python100day
/day06/is_prime.py
247
3.9375
4
def is_prime(num): if num < 4: return True for x in range(2, num): if num % x == 0: return False return True num = int(input("num = ")) if is_prime(num): print('is prime') else: print('not prime')
c10988122c190d97596bdec6514f4b7b01359648
Kolynes/PredictCGPA
/ANN/matrix/vector.py
2,128
3.875
4
class IVector: pass class Vector(IVector): __value: list def __init__(self, value: list): self.__value = value @property def length(self) -> int: return len(self.__value) @classmethod def zero(self, length: int) -> IVector: assert length > 0 ...
7dbd6e077fb9632c9bcd90219c05a711c01a6ada
Ramonta-Lee/Data-Structures
/doubly_linked_list/doubly_linked_list.py
7,229
4.375
4
"""Each ListNode holds a reference to its previous node as well as its next node in the List.""" class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next """Wrap the given value in a ListNode and insert it after this node...
51a0866018d1b6956c050b970c869b688e5e3667
kuanzi/tracking-lstm
/rnn_demo/LSTM_train.py
3,754
3.5625
4
# -*- coding:utf-8 -*- import tensorflow as tf import numpy as np from tensorflow.contrib import rnn from tensorflow.examples.tutorials.mnist import input_data #GPU config config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) #data mnist = input_data.read_data_sets('MNIST_d...
314c9ec91cb29967675f4e4f3e6ce6860b93f35f
frochet/IA-INGI2261
/Assignement2/Code/heuristic.py
460
3.546875
4
''' Created on 16 oct. 2012 @author: Florentin ''' import math def make_combi(goals,size): i = 0;j = 0 listCombi = [] while i < math.factorial(size): swapper(goals,j,j+1) listCombi.extend(goals) j+=1 if j == size-1: j=0 i+=1 return listCombi def swap...
28d510a2bb6869677674b9b94cbd5fe1cf11242e
denis-beurive/python-notes
/code/closure.py
757
3.84375
4
import typing # This function returns a closure. # The value of "x" is "enclosed". def enclose1(x: int) -> typing.Callable[[], int]: def func() -> int: return 2 * x return func c1: typing.Callable[[int], int] = enclose1(2) print(f'exec c1 -> {c1():d}') # Using a defined (multiline) function def...
0c5fb828d591b785c4ae2f6e75e3f9e6e3ab75d8
denis-beurive/python-notes
/code/re_match_anchor_begin.py
590
3.5625
4
import re from typing import Pattern, Match, Optional reg1 = re.compile('abc') reg2 = re.compile('^abc') tests = [ 'abcd', '.abcd' ] for test in tests: m1: Optional[Match] = reg1.match(test) m2: Optional[Match] = reg2.match(test) print(f"reg1.match('{test}') => {'matches' if m1 is not None else '...
e20c63c6291bba07f830414160a0aa6e1b529b7e
mklibano/ml-experimentation
/Assignment2/gradient.py
586
4.09375
4
import numpy as np from Assignment2.sigmoid import sigmoid def gradient(theta, X, y): """ Computes gradient for a logistic regression algorithm :param X: The feature matrix :param y: The output vector :param theta: the parameter vector """ theta = np.matrix(theta) X = np.matrix(X) ...
117b1a77f37824cb04039e7f1e2efc98c20459af
mklibano/ml-experimentation
/Assignment2/cost_function.py
520
3.875
4
import numpy as np from Assignment2.sigmoid import sigmoid def cost_function(theta, X, y): """ Computes the cost for a logistic regression algorithm :param X: The feature matrix :param y: The output vector :param theta: the parameter vector """ theta = np.matrix(theta) X = np.matrix...
32b0376a248af27f7bb23165755ff2343d744ad4
Jay-davisphem/Turtle
/TurtleMultiplicationTable.py
832
3.796875
4
from turtle import * speed(1) def ugd(x, y): color("red") up() goto(x, y) pd() ugd(-150, 200) color("green") write("Multiplication Table", font=("Times", 11, "bold")) x = -172 for k in range(1,10): ugd(x, 170) write(f"{k:3d}", font=("Times", 8, "bold")) x += 40 ugd(-225, 160); color("b...
55c69b8771f8662b2da1e927d8419ed26849d144
vincentnti/vincent_sinclair_TE19C
/Programmering1/Programmeringsövningshäfte/if-sats uppgifter/if_uppgift10.py
294
3.875
4
import math #a = 1 #b = -1 #c = -2 a = float(input("A: ")) b = float(input("B: ")) c = float(input("C: ")) #1*x**2-1*x-2 symmetri = (b * -1) / 2 difference = math.sqrt((b/2)**2 + (c)*-1) svar1 = symmetri + difference svar2 = symmetri - difference print(svar1, svar2) #INTE KLAR MED UPPGIFT
87b5480a96162ad6ed3474d33d92f875509c1c57
vincentnti/vincent_sinclair_TE19C
/Programmering1/Övningsprov 2021/upg6.py
3,784
3.640625
4
""" Todo list: --------- List random problems CHECK Let user set difficulty through time CHECK A Timer CHECK Score CHECK Title screen CHECK Use Classes CHECK Optional extras: Live countdown/Display countdown Set timer instance as attribute directly if that is possible Move things in play_game() into seperate function...
8ff2eedfb6797068b712bf6379a7d46faa909ae1
vincentnti/vincent_sinclair_TE19C
/Programmering1/Programmeringsövningshäfte/while-sats uppgifter/while_uppgift1.py
89
3.5625
4
i = 0 #iterator s = 0 #sum while i <= 100: print(s, end=" ") i += 1 s = s + i
66b0d2e018a62eef06e3ef2e8ebc7de284801e97
vincentnti/vincent_sinclair_TE19C
/Other/tictactoe.py
1,990
3.953125
4
#TicTacToe import random random.seed() # Set new seed for a real random experience grid = [1,2,3,4,5,6,7,8,9] # Board positions playerOneMark = "X" playerTwoMark = "O" def drawBoard(): print("—————————————————————————") print(f"| {grid[0]} | {grid[1]} | {grid[2]} |") print("————————————————————...
f80e0e4830a7284843962e66f74d07b1cbe4a792
vincentnti/vincent_sinclair_TE19C
/Programmering1/Programmeringsövningshäfte/Räkna med Python/uppgift4.py
333
3.703125
4
#Uppgift 4 import math #A """ x1 = 2 y1 = 3 x2 = -2 y2 = 2 """ # Svar= 4.123105625617661 #B """ x1 = 2 y1 = 1 x2 = 1 y2 = 0 """ # Svar= 1.4142135623730951 #C x1 = float(input("X1: ")) y1 = float(input("Y1: ")) x2 = float(input("X2: ")) y2 = float(input("Y2: ")) #Alla answer = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) ...
05fc2c445bda0f295b4180234a293eb777995098
dancingninjacoder/DataStructres-Fall2019
/LAB5-cs2302/MaxHeap.py
4,768
3.734375
4
# Implementation of max heap # Programmed by Olac Fuentes # Last modified October 20, 2019 import matplotlib.pyplot as plt import math class node: def __init__(self, word, count): self.word = word self.count = count class MaxHeap(object): # Constructor def __init__(self): self.tr...
e896e59455abf004ecc7b681ceda88f2b97cbacb
dancingninjacoder/DataStructres-Fall2019
/LAB4/RBTree.py
3,474
3.609375
4
class RBNode(object): def __init__(self, word = "", key = 0, left = None, parent = None, right = None, color = -1): self.word = word #added attribute self.key = 0 self.left = None self.parent = None self.right = None self.color = -1 #colors use 1 and 0s instead of strings. class RedBlack(object): #0...
e62e456910a36e37619dbf08dc0f4ec37bbf463d
icemanblues/advent-of-code
/2017/day20/day20.py
2,267
3.609375
4
from typing import List, Dict, Set day_num = "20" day_title = "particle swarm" class Particle: def __init__(self, pos: List[int], vel: List[int], acc: List[int]): self.pos = pos self.vel = vel self.acc = acc def tick(self): for i in range(3): self.vel[i] += self.a...
5089b30a6f0cb21161250e6646f3700d15552006
BanQiaoGeXia/Python-Study
/closure.py
938
3.765625
4
#coding=utf_-8 ''' counter是一个闭包函数 调用这个函数时 他声明他的内部函数 并把这个内部函数以返回值的形式返回 返回的这个内部函数相当于一个实例化的对象 他对counter内部变量的操作不会与其他函数冲突 孤认为十分神奇 ''' def counter(start = 0): #这是一个闭包函数 count = [start] #相当于 counter类 有一个成员变量counter def incr(): #有一个incr方法 count[0] += 1 re...
a15301a8961754d909dc58bf688a26c178c38ad8
DeadFishEyes/cardcount-training
/Omega II.py
2,000
3.6875
4
import os import random import time print '########################' print '# #' print '# Omega II #' print '# #' print '########################' cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] deck = cards * 4 values = ...
f0402b180883c5886bda31bd295f8d9adecd7db8
edsouz/Python
/prog0.py
808
4.1875
4
a = int(input("Digite um número inteiro: ")) b = int(input("Digite um outro número inteiro: ")) def soma(x,y): return x + y s = soma(a,b) print(" ") print(" ======================================== ") print("o primeiro número digitado foi %d\n" %a) print("O segundo número digitado foi %d\n" %b) print("A soma dos...
313af1d2460455f97998638595f2e5bdc5d59bc8
xushubo/learn-python
/learn21.py
3,519
4.125
4
#map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素, #并把结果作为新的Iterator返回。 def f(x): return x * x r = map(f,[1, 2, 3, 4, 5, 6, 7, 8, 9]) #map()传入的第一个参数是f,即函数对象本身。 print(list(r)) #由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。 #map()作为高阶函数,事实上它把运算规则抽象了, #因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数, #比如,把这...
4d3bd8322e1e28a8e75e465196cfa2358698ae87
xushubo/learn-python
/learn26.py
976
3.890625
4
#当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。 #关键字lambda表示匿名函数,冒号前面的x表示函数参数。 #匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。 #用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。 #此外,匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数: f = lambda x: x * x print(f(5)) #同样,也可以把匿名函数作为返回值返回,比如: def build(x, y): return lambda: x * x + y * y def cacl(): L = [] ...
cf666926ccbf160c0a110d53fb3167b63f2199f9
xushubo/learn-python
/itertools-learn.py
1,363
3.609375
4
import itertools natuals = itertools.count(1) #count()会创建一个无限的迭代器 for i in natuals: print(i) if i >= 10: break cs = itertools.cycle('ABC') #cycle()会把传入的一个序列无限重复下去 n = 0 for i in cs: print(i) n = n + 1 if n >= 10: break ns = itertools.repeat('a', 5) #repeat()负责把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数 for i in ns:...
012a1f303122eae2504ce3394174412ddd306bf5
xushubo/learn-python
/learn25.py
2,328
3.875
4
#高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。 #实现一个可变参数的求和,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数: def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum #当我们调用lazy_sum()时,返回的并不是求和结果,而是求和函数: f = lazy_sum(1, 3, 5, 7, 9) print(f) #调用函数f时,才真正计算求和的结果: print(f()) #我们在函数lazy_sum中又定...
5feac9d941ebf9c9e815e8c21cb12587636a601f
xushubo/learn-python
/learn33.py
3,820
4.03125
4
访问限制 阅读: 160291 在Class内部,可以有属性和方法,而外部代码可以通过直接调用实例变量的方法来操作数据,这样,就隐藏了内部的复杂逻辑。 但是,从前面Student类的定义来看,外部代码还是可以自由地修改一个实例的name、score属性: >>> bart = Student('Bart Simpson', 98) >>> bart.score 98 >>> bart.score = 59 >>> bart.score 59 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问,所...
ee1901c2a9eb458fa3e672b23872e755597de48b
xushubo/learn-python
/learn18.py
3,191
4.03125
4
#如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢? #这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator #要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator: L = [x * x for x in range(10)] print(L) g = (x * x for x in range(10)) print(g) print(next(g)) #如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值:...
0a62fa9b0204b720c49309a31449ba18ebcb704c
zlzlovezl/mdht
/mdht/test/utils.py
2,355
3.84375
4
""" Various classes/functions commonly used in testing this package """ class Clock(object): """ A drop in replacement for the time.time function >>> import time >>> time.time = Clock() >>> time.time() 0 >>> time.time.set(5) >>> time.time() 5 >>> """ def __init__(self)...
458ff6dc5057a909fd08f2934fa594bb77ef3434
KylieLAnglin/docsim
/linguistic features/verb_tense.py
2,478
3.859375
4
import nltk # nltk.download('averaged_perceptron_tagger') # %% def determine_tense_input(sentence): text = nltk.word_tokenize(sentence) tagged = nltk.pos_tag(text) tense = {} tense["future"] = len([word for word in tagged if word[1] == "MD"]) tense["present"] = len( [word for word in tagg...
84841bf12859700431b85baeb51f8455149fe29c
nick-hsiao/Leetcode-Solutions
/scholarship_eligibility.py
2,652
3.75
4
class Questionnaire: def __init__ (self): self.answers = ['yes','no'] self.age_req = False self.residency_req = False self.work_req = False self.parent_req = False self.volunteer_req = False self.household_req = False def run(self): print('Hello, welcome to the scholarship eligibility questionnaire!...
b1f33f71bb48134f68fa7a4dcf15d0bee5fc40c5
juanlopezrolando/pdsnd_github
/bikeshare.py
6,466
4.3125
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
8498942fcc8b5e8b9edc5d3f0f3752f4db82853b
CsBigDataHub/MyPyhton3Training
/Exercise_Files/07 Loops/for.py
412
3.8125
4
#!/usr/bin/python3 # for.py def main(): fh = open('Exercise_Files/02 Quick Start/lines.txt') for line in fh.readlines(): print(line,end='') for index, line in enumerate(fh.readlines()): print(index,line,end='') s = 'this is a string' for i,c in enumerate(s): print(i,c)...
9e4b9200f0fcce8592d78369b4dde52634d3fafc
CsBigDataHub/MyPyhton3Training
/Exercise_Files/12 Classes/classes-accesorMethods-copy.py
415
3.859375
4
#!/usr/bin/python3 # classes.py class Duck: def __init__(self, color='green'): self._color=color def get_color(self): return self._color def set_color(self,color): self._color=color def main(): donald = Duck() print(donald.get_color()) ...
bf17dfbb3c3c21a2015782a424e801005c25d28c
srinivas-github/pythonExcerise
/fgrepwc.py
686
4.21875
4
#!/usr/bin/env python "fgrepwc.py -- searches for string in text file" import sys import string def usage(): print "usage: fgrepwc [-i] string filename" sys.exit(1) def fileFind(word, filename): count = 0 try: fh = open(filename, 'r') except: print filename, ":", sys.exc_info() ...
3528c32496c11a677ebf446698dfee62391f553b
Joseph-Lux/Project-Euler-1
/Problem42.py
1,475
3.859375
4
# The nth term of the sequence of triangle numbers is given by, # tn = ½n(n+1); so the first ten triangle numbers are: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # By converting each letter in a word to a number corresponding to its # alphabetical position and adding these values we form a word value. # For exampl...