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
a62dd74d4b095956ba8bb19fb55fe7b336df7c11
wenyaowu/leetcode
/algorithm/swapNodesInPairs/swapNodesInPairs.py
707
3.96875
4
# Swap Nodes in Pairs """ Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. """ # Definition for si...
e44cebbea031123f134004c0cf41effb835e1dae
wenyaowu/leetcode
/algorithm/validParentheses/validParentheses.py
864
4
4
# Valid Parentheses """ Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. """ class Solution: # @param {string} s # @return {boolean} ...
9e709402d44699947c7934febe198ccc2f55d1cf
wenyaowu/leetcode
/algorithm/nQueens/nQueens.py
1,335
3.890625
4
# N-Queens """ The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both ind...
bc8cab306a5c13eb063336a46464b3f29bc03e26
wenyaowu/leetcode
/algorithm/maximumSubArray/maximumSubarray.py
525
4.15625
4
# Maximum Subarray """ Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. """ class Solution: # @param {integer[]} nums # @return {integer} ...
3bfe490ced270299d618ae3bce36dc5bf93bed6b
gonzaloquiroga/neptunescripts
/dnacalc3.py
1,583
4.25
4
#! /usr/bin/env python # Ponemos env python para que lo encuentre en cualquier ordenador, # sea donde sea que este instalado. #DNASeq = raw_input ("Enter a DNA sequence: ") #Prompts you to write stuff DNASeq = "ATCACGAGCTTTATTCGGGC" DNASeq = DNASeq.upper() #Takes DNASeq and creates a new string with an uppercase ve...
718385711d1030e3e37936cdb8243a4f62d8434c
ParkerCS/programming2-assignments-JMaling
/loops_and_random.py
2,123
4.09375
4
# LOOPS (16pts TOTAL) import random # PROBLEM 1 (Fibonacci - 4pts) ## The Fibonacci sequence is a sequence of numbers that starts with 1, followed by 1 again. # Every next number is the sum of the two previous numbers. # I.e., the sequence starts with 1, 1, 2, 3, 5, 8, 13, 21,... # Write a program that calculates and ...
e02a06155c71117dd210e57c5cf0e0d3c4ff9987
mzimecki/MyPythonRepo
/binary_tree_walk.py
1,615
4.25
4
class Node: rightNode = None leftNode = None name = None def __init__(self, l, r, n): self.rightNode = r self.leftNode = l self.name = n # a # / \ # b e # /\ # c d # # Reversed: # a # / \ # e b #...
ba4c47cae4c90f8d2f7353dcca53cbee5039049e
ghydric/05-Python-Programming
/Class_Practice_Exercises/Serialization/hangman_exercise.py
11,429
4.59375
5
""" Task: Your task is to implement the Hangman game in Python. ​ Program Specifications: 1) Output a brief description of the game of hangman and how to play 2) Ask the user to enter the word or phrase that will be guessed (have a friend enter the phrase for you if you want to be surprised) 3)...
6c1af79866f6e74500b78fbc1bae00e005ed66dc
ghydric/05-Python-Programming
/Class_Practice_Exercises/Lists/List_Functions_Review/append_list.py
673
4.53125
5
## Append to list # This function demonstrates how the append method # can be usesd to add items to a list def main(): # initialize empty list name_list = [] # create a variable to control our loop again = 'y' # add some names to the list while again == 'y': # get a name from the user...
b2c495513f454f4c992e7c6b89f0a8cb79b7ea69
ghydric/05-Python-Programming
/Class_Practice_Exercises/Advanced_Functions/map_func.py
593
4.4375
4
# map() function # calls the specified function and applies it to each item of an iterable def square(x): return x*x numbers = [1, 2, 3, 4, 5] sqrList = map(square, numbers) # print(next(sqrList)) # print(next(sqrList)) # print(next(sqrList)) # print(next(sqrList)) # print(next(sqrList)) # print(next(sqrList)) ...
c7a909a3c8f7ca3c3a11f66212994a7c73409a88
ghydric/05-Python-Programming
/Class_Practice_Exercises/Classes/Inheritance/car_demo.py
533
4.03125
4
# this program demonstrates the Car class import vehicles def main(): # create a Car object # The car is a 2007 Audi with 12,500 miles, # priced at $21,500.00, and has 4 doors user_car = vehicles.Car('Audi','A3',12500, 21500.00, 4) # display the car's data print('Make:', user_car.get_make()) ...
643dc0c7f87421eac8ee5e124dd038f9f1c6a57f
ghydric/05-Python-Programming
/Class_Practice_Exercises/Classes/Inheritance/car_truck_suv_demo.py
1,269
4.25
4
# This program creates a Car, Truck, and SUV object import vehicles def main(): # create Car object car = vehicles.Car('Bugatti', 'Veyron', 0, 3000000, 2) # create a Truck object truck = vehicles.Truck('Dodge', 'Power Wagon', 0, 57000, '4WD') # create a SUV object suv = vehicles.SUV('Jeep', ...
dbbfec55fae84308c068d8b2db6f5502c6ef29a3
ghydric/05-Python-Programming
/Class_Practice_Exercises/Advanced_Functions/iter.py
485
4.34375
4
# Python iterator #old way: myList = [1,2,3,4] for item in myList: print(item) # what is actually happening using iterators def traverse(iterable): it = iter(iterable) while True: try: item = next(it) print(item) except StopIteration: break L1 = [1,2,3]...
8450a626f5b9179e35e75c4a6296c036913eb583
ghydric/05-Python-Programming
/Class_Practice_Exercises/Classes/Classes_Exercises_2.py
2,739
4.75
5
""" 2. Car Class Write a class named Car that has the following data attributes: • __year_model (for the car’s year model) • __make (for the make of the car) • __speed (for the car’s current speed) The Car class should have an __init__ method that accept the car’s year model and make...
d7e180b0c1f1df1ad39e9fc835b0075b40f93cce
ghydric/05-Python-Programming
/Class_Practice_Exercises/Classes/In_Class_Examples/superHeros.py
1,458
3.8125
4
# create a SuperHero Class class SuperHero: # __init__ method takes in hero name, real name, power list, and color list as arguments def __init__(self, h_name, r_name, list_obj_powers, list_obj_colors): self.__hero_name = h_name self.__real_name = r_name self.__powers = list_obj_powers ...
d1c58217477c8057cd556400640fb6ab4114967b
ShruthiShankar2512/halma-game-player-minimax
/random_move_picker.py
16,900
3.578125
4
import copy from math import sqrt import random #Reading contents from the file. Returns a list of all the lines as strings def readFile(fileName) -> list: file = open(fileName,"r") lines = file.readlines() lines = [i.strip('\n') for i in lines] file.close() return lines #Understandin...
fc94ffcf29a0f4754eee94f30f4065138c4d8fa2
wiegandt/week_3
/animals and legdós.py
129
3.96875
4
chickens = int(input("Numer of chickens: ")) pigs = int(input("Number of pigs: ")) print("Legs in total: ", chickens*2 + pigs*4)
8de62e2152e34ff05023dcf69a6585f89d2a59c2
Renien/big-data-analytics-demo
/python-demo/featureFrequency/mapper.py
645
3.65625
4
__author__ = 'renienj' #!/usr/bin/env python import sys def read_input(file): for line in file: # split the line into words yield line.split('\r') # Add default count to each word def name_count(data): for words in data: for word in words: value = word.split('\t')[-1] ...
679154f4340225e10a6dce151354fd1a1588df40
bhavyajain190/Guess
/un.py
553
4.125
4
import random print('Hey what is your name?') name = input() print('Welcome ' + name + ' I am thinking of a number between 1 and 10') Num = random.randint(1,10) for guessesTaken in range(1,3): print('Take a guess') guess = int(input()) if guess < Num: print('Your guess is a lttle low') el...
70597484549c3581aa9b1e6cec535f40b37a68c9
akshatasawhney/Graph-2
/Problem1.py
1,989
3.578125
4
""" // Time Complexity : o(v+e) // Space Complexity : o(v) // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no // Your code here along with comments explaining your approach """ class Solution(object): def build_graph(self, cons): #building adjecenecy list from the...
4ac84c9eec3442353409e68473914cf98ed336ce
jocelyngallardo/data-practice
/datapractice.py
1,178
3.75
4
dict={'Jan':'1', 'Feb':'2', 'Mar':'3', 'Apr':'4', 'May':'5', 'Jun':'6', 'Jul':'7', 'Aug':'8', 'Sep':'9', 'Oct':'10', 'Nov':'11', 'Dec':'12'} #print(dict['Dec']) for month in dict: if month.startswith('M'): print(month) naomiDict={'name':'Naomi', 'age':16, 'classes':{'0':'The Farm', '1st': 'APUSH', '2nd':...
486b1dc0ae648c9511b4114730c9a3b874d7ef82
nixx78/python
/sandbox/lv/nixx/poc/domain/classes.py
541
3.515625
4
class Person: def __init__(self, pers_id: int, name: str, surname: str): self.txnId = pers_id self.name = name self.surname = surname def __str__(self): return str(self.__dict__) def __repr__(self): return str(self.__dict__) def __lt__(self, other): re...
7cb85b87561667e1a11037c459c41c251d8782ac
ramvijay/VivaManagementSystem
/util/UserType.py
403
3.6875
4
""" Types of the users in the system. """ from enum import Enum class UserTypes(Enum): """ Various types of the users throughout the system """ SuperAdmin = 1, VivaCoordinator = 2, Tutor = 3, HOD = 4, CourseCoord = 5 """ The type of the tutor will be stored separately in another field...
2018b85801fb06a3001e38c32a02978c57aaf2a8
Jhon-G/lesson1
/types.py
608
4.28125
4
''' Практика ''' #Float a = 2 b = 0.5 print(a + b) #string name = 'Иван' print(f'Привет, {name}!') #Приктика числа v = int(input('Введите число от 1 до 10: ')) #Ввод целого числа print(v + 10) #Строки name = input('Введите имя: ') name = name.capitalize() #Делаем первую букву большой print(f'Привет, {name}! Как дела?'...
1e7121325ee17b6397257e8b006edcde51f865a5
Kernelko/malinka
/other/lumens.py
784
3.90625
4
import RPi.GPIO as GPIO import time #GPIO MODE GPIO.setmode(GPIO.BCM) #Pins a_pin = 2 b_pin = 3 #discharge function for reading cap data def discharge(): GPIO.setup(a_pin, GPIO.IN) GPIO.setup(b_pin, GPIO.OUT) GPIO.output(b_pin, False) time.sleep(0.005) #create time function for capturing analog cou...
50ecebac03e051093d9292810ec741ec3b1cf41c
nathan7402/MikeandNathan
/p4_code/code/rrt/util.py
5,150
3.765625
4
import random from math import sqrt,cos,sin,atan2 class Util: ######################################## # Mandatory functions for the rrt # ######################################## mind = 99999 # Tests if the new_node is close enough to the goal to consider it a goal def winCondition(self,...
43e81064120fa4c6e01c460c268b17362d96d98c
nomgon/quarto-python
/src/game/turn.py
298
3.625
4
class Turn: """Definition of a turn of game: - player_one_active [True/False] It is False when it's player 2 turn - selected_piece [between 0 to 16] It has 0 when no piece is selected yet""" def __init__(self): self.player_one_active = True self.selected_piece = 0
beb638e706dd5ff5f9daf113e486d33300bb9470
Jacob-Sunny/cognixia-python
/MoreFunctions.py
313
4.09375
4
def greetFreind(name,greeting,sentence): output = "{2},{0}!,{1}".format(greeting,name,sentence) return(print(output)) greeting = greetFreind("Jacob","Hello","Today is nice") def greet_user(greeting): user = input("Enter Your name ") print("{},{}!".format(greeting,user).upper) greet_user("Hello")
955f2dc58f1b88079944f81597e2230579f8138e
hyeonho88/supersuper
/firstgit/Machine/MNIST/differentiation.py
548
3.5
4
import numpy as np import matplotlib.pylab as plt def numerical_diff(f,x): h = 1e-4 return (f(x+h)-f(x-h))/(2*h) def function_1(x): return 0.01*x**2 + 0.1*x x=np.arange(0.0,20.0,0.1) y=function_1(x) '''plt.xlabel('X') plt.ylabel('f(x)') plt.plot(x,y) plt.show() ''' print(numerical_diff(function_1,5)) pri...
a58a80b9f1415f3b4e461a8b1492234e684b940a
charlenechin/zendesk-parking-lot-exercise
/src/models/parking_lot.py
4,280
3.5
4
""" src.models.parking_lot ~~~~~~~~~~~~~~~~~~~~~~ This module contains the objects that will model the carpark. """ import math from dataclasses import dataclass from typing import Dict, List, Optional, Tuple from src.constants import ParkingFee, VehicleTypes from src.models.vehicle import Vehicle """ Carpark obje...
75df037a3564e30b1c2ed8b11598ea52bfdf2fc7
01FE16BME072/TensorflowBasics
/Tensor_handling3.py
1,279
4.40625
4
''' TensorFlow is designed to handle tensors of all sizes and operators that can be used to manipulate them. In this example, in order to see array manipulations, we are going to work with a digital image. As you probably know, a color digital image that is a MxNx3 size matrix (a three order tensor), whose components ...
8ec76988298cfd6ded4c4d67d4158ab8971bc731
embern33/ListReadAndWrite
/ListReadAndWrite.py
685
4.0625
4
from random import randint import random print("Hello, this program currently adds to a list and prints a random item from that list.") samples = [] placeholder = "Y" print("What would you like to add (If you want to get a random number, input RN)") while placeholder.upper() == "RN": add_name = str(inp...
8d1d69b2606b0b5fc2e06b907271525a27ef7d6e
maniac-tech/Web-scraping-using-php-and-RSS-feeds
/testFiles/dictonaries.py
290
4.40625
4
dict = { "key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4" } #iterating over keys: # for x in dict.iterkeys(): # print (x) #iteraing over values: # for x in dict.itervalues(): # print(x) #iterating over values using keys: for x in dict.iterkeys(): print(dict[x])
863b8447daa0a03bbf3ea29bfdebde059149ffa4
Ninaheglund/smarteSystemer
/Krystian/login.py
1,922
3.75
4
import sqlite3,time import facerec def login(): while True: user_id = facerec.Facerec() #username = raw_input("Please enter your username: ") with sqlite3.connect("database.db") as db: cursor = db.cursor() find_user = ("SELECT * FROM users WHERE ID = ?") cursor....
7b9381bced845c56d9fc79c8159c541acc260658
BohanHsu/developer
/nlp/assign1/python_code/number.py
2,129
3.625
4
dict1 = {} dict1[0] = '' dict1[1] = 'one' dict1[2] = 'two' dict1[3] = 'three' dict1[4] = 'four' dict1[5] = 'five' dict1[6] = 'six' dict1[7] = 'seven' dict1[8] = 'eight' dict1[9] = 'nine' dict1[10] = 'ten' dict1[11] = 'eleven' dict1[12] = 'twelve' dict1[13] = 'thirteen' dict1[14] = 'fourteen' dict1[15] = 'fifteen' dict1...
176313e02cb527f58beefa6a979118618da5446e
BohanHsu/developer
/python/io/ioString.py
1,776
4.78125
5
#in this file we learn string in python s = 'Hello, world.' #what str() deal with this string print(str(s)) #what repr() deal with this string print(repr(s)) #repr() make a object to a string for the interpreter print(str(1/7)) print(repr(1/7)) #deal with some transforming characters hello = 'hello, world\n' helloS...
e1be98d672f2925301e0c273a5c00a69c3d30213
BohanHsu/developer
/nlp/assign1/hw1-files/my_regexs.py
655
4.1875
4
import re import sys # the first argument is a regular expression # from the second argument are file path pattern = sys.argv[1] files = sys.argv[2:] # reg_find : regular_expression, list_of_file_path -> list of words # return a list of words which match the regular expression # this method will concatenate all the l...
36feafffe07f545ed76810f7ba86e4b6f44382f9
richajoy/Python
/break.py
1,089
4.09375
4
for i in range(0, 4): if i == 2: break print(i) print("Finished with i =", str(i)) for i in range(0, 5): if i == 2: continue print(i) print("Finished with i =",str(i)) phrase = " There is no capital x in this word" for letter in phrase: if letter == "X": print("There is X ...
b1c504dd05738f12d86491a634562577f5ed0fc0
richajoy/Python
/events_calc_probabilities.py
931
3.84375
4
''' Find the average heads and tails with tails as 0 and heads as 1''' from random import randint heads = 0 tails = 0 for trails in range(0, 11): while randint(0, 1) == 0: tails = tails + 1 heads = heads + 1 print("Total number of heads is {} and tails is {}".format(heads,tails)) print("heads/tails"...
e9881ca2e14ec20a71caf55f2a7743873545c6db
richajoy/Python
/factors.py
225
4.09375
4
user_input = int(input("Enter a positive integer: ")) for i in range(1, user_input + 1): factor = user_input % i if factor: continue else: print("{} is a divisor of {}".format(i,user_input))
5930e046cc9147ccf94ec1c47edfbe0a740323e8
KalininSaveliy/Arkanoid
/arkanoid_main.py
10,433
3.5
4
"""Главный модуль""" import tkinter as tk import time from arkanoid_level import * from arkanoid_block import * from arkanoid_ball import * from arkanoid_platform import * class Game: def __init__(self, tk, width, height): self.tk = tk self.width = width self.height = height se...
c305f960cf4c94bfbf0183a639d13b12724bf469
ScottRMalley/intro-programming
/examples/object_example.py
486
4
4
import datetime class Day: def __init__(self, month, year, day_of_week): self.month = month self.year = year self.day_of_week = day_of_week def tomorrow(self): if self.day_of_week == 'Wednesday': return Day(self.month, self.year, 'Thursday') if __name__ == '__mai...
e34f84cde46004033576eca3f188734edfa91f46
ScottRMalley/intro-programming
/lessons/lesson-5/hangman.py
4,729
3.546875
4
# These are all the imports we will be using. You don't have to # change any of the methods in util.py as they have been provided import utils import numpy as np class HangmanGame: ### # This is the initialization function. It can be called by: # # hangman_game = HangmanGame(filename) # # wher...
e21b93f377e44ed3ca5c340a7b992cf6567ece9b
ScottRMalley/intro-programming
/examples/math_command_line_example.py
249
3.828125
4
import sys arguments = sys.argv if len(arguments) > 3: if arguments[1] == 'add': print(int(arguments[2]) + int(arguments[3])) if arguments[1] == 'multiply': print(int(arguments[2]) * int(arguments[3])) else: print("List not long enough")
2a905616b2a35f6a01c8e408e982eb284b62c14c
dry-python/returns
/returns/interfaces/unwrappable.py
1,602
3.671875
4
from abc import abstractmethod from typing import Generic, TypeVar _FirstType = TypeVar('_FirstType') _SecondType = TypeVar('_SecondType') _UnwrappableType = TypeVar('_UnwrappableType', bound='Unwrappable') class Unwrappable(Generic[_FirstType, _SecondType]): """ Represents containers that can unwrap and re...
3ce6fbb33823fb0aeb535460c177e67633ee8e73
dry-python/returns
/returns/_internal/pipeline/pipe.py
1,016
3.859375
4
from returns._internal.pipeline.flow import flow def pipe(*functions): """ Allows to compose a value and up to 7 functions that use this value. We use a custom ``mypy`` plugin to make sure types are correct. Otherwise, it is currently impossible to properly type this function. Each next function...
3a27c346d86741df9728ca916a8a094fbf055348
isabelcachola/IE
/read_data.py
997
3.671875
4
import csv def count_txt(): #word_file = open("bad-words.txt","r") #944,484 word_file = open("isabelswords.txt","r") # 61,320 words = [] for line in word_file: words.append(line.strip()) words = words[1:] with open('Sentiment Analysis Dataset.csv') as f: count = 0 reade...
3c69c45899d8b808aad5c9c8c1288d0c98ab75a3
nasaae2014/Self-Taught_Coding_Progress
/simple_calculatorv1.1_12-20-20.py
3,219
3.984375
4
from tkinter import* window = Tk() window.title("Simple Calculator") #window.minsize(300,300) frame = Frame(window) frame.grid(row=0, column=0) operator = "" temp_results = "" text_input = StringVar() key_list = ["C","/","*","D",7,8,9,"-",4,5,6,"+",1,2,3,"=",0,"."] btn_dict = {} def center_window(win): win.upd...
56e6d7ed7ed56bc62e7d5571f41365dc518282da
eidelen/viCNN
/shabel/ShabelModel.py
1,150
3.65625
4
""" This module contains CNN models """ import torch.nn as nn import torch.nn.functional as F class ConvNet(nn.Module): """Convolutional neural network - 2 conv layer, 3 fully connected""" def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(1, 8, 5) self.conv2 =...
b8e2a125b0ee60899ef0c9924350d5579695ef70
TTVMrWang/Edabit-Python-Answers
/Centered Hexagonal Number/solution.py
192
3.546875
4
def hex_lattice(n): n = (3 + (12 * n - 3) ** .5) / 6 if n % 1: return "Invalid" n = int(n) R = list(range(n, 2 * n)) return '\n'.join((i * 'o ').center(4 * n - 1) for i in R + R[-2::-1])
21c4e659911742ca77bfb449a515c7ce82e8c008
TTVMrWang/Edabit-Python-Answers
/Is the Last Character an N?/solution.py
91
3.9375
4
def is_last_character_n(word): if word.endswith('n'): return True else: return False
2ddd8409852729382b26a309fec7ebcac1efe33b
beepscore/python_play
/tests/test_tuples.py
806
3.84375
4
#!/usr/bin/env python3 import unittest from collections import namedtuple class TestTuples(unittest.TestCase): def test_types(self): # tuple self.assertEqual(type((1, 'a')), tuple) # namedtuple # https://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python#2970722...
1d8964bb70c460668487c812f5cae1c5f1c6aa19
beepscore/python_play
/python_play/arguments_default.py
1,668
3.828125
4
#!/usr/bin/env python3 """ generally avoid parameter with mutable default # Default Parameter Values in Python http://effbot.org/zone/default-values.htm # “Least Astonishment” and the Mutable Default Argument https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument?rq=1 "... e...
97354fee80d19aeee9a33aca0ecf1f787dcaee08
ribhuswatgov/GFG-RECURSION
/Power_using_Recursion.py
128
3.796875
4
def RecursivePower(n,p): if p == 1: return n return n * RecursivePower(n,p-1) print(RecursivePower(2,9))
78c4fc5a3affb54f47226d1fc681274e9f38383e
ribhuswatgov/GFG-RECURSION
/permutation_of_strings.py
375
3.84375
4
def permutation_of_String(s, l, r): new_list= [] if l == r: print(s) for index in range(l,r+1): ls = list(s) ls[l],ls[index] = ls[index],ls[l] new_string = "".join(ls) new_list.append(new_string) for index in new_list: permutation_of_String...
4739f2dcad276d9967f2f0d36479e217db737356
himIoT19/python3_assignments
/assignment_1/Q4.py
328
4.4375
4
# reverse string def reverse(a_str: str) -> str: """ Function used for reversing the string :param a_str: String :return: String """ string_1 = a_str[::-1] return string_1 # String to work on s = "I love python" print("Old string : {}".format(s)) print(f"New string after reversal: {revers...
6d0d05a6f1bcab33d8f32e33f38461e9a5417ffe
himIoT19/python3_assignments
/assignment_1/Q19.py
187
3.90625
4
#Write a Python program to access a function inside a function def fun(): print ("Hello from outer function") def f2(): print ("Hello from inner function") f2() fun()
2a265e3e2c87e8e7d7bc86c4ee8960cbb2ff7e9c
seefs/Source_Insight
/node/Pythons/py_test/test_if.py
408
3.59375
4
#!/usr/bin/python import sys; x1 = 'runoob'; sys.stdout.write(x1 + '\n') x="a" y="b" # 换行输出 print(x) print(y) print('---------') # 不换行输出 print(x,) print(y,) # 不换行输出 print(x,y) if x=="a" : print('x="b"') elif x=="b" : print('x="b"') else : print('x="unknow"') # // runoob # // a # // ...
014c4247f563ba43e78dd5cc4d3f4f0e19cd41ed
seefs/Source_Insight
/node/Pythons/py_test/test_while.py
371
4.15625
4
#!/usr/bin/python count = 0 while (count < 9): print ('The count is:', count) count = count + 1 for j in range(9): print ('The j is:', j) #// The count is: 0 #// The count is: 1 #// The count is: 2 #// The count is: 3 #// The count is: 4 #// The count is: 5 #// The count is: 6 #// The count is: 7 #// The ...
34ef325f6a7d6316065d0740b86cd394f1502d43
seefs/Source_Insight
/node/Pythons/py_test/keras/Keras_ly_input.py
322
3.875
4
 现有的层不能满足需求,需要自己写个自定义层。需要多个参数为输入。 仅适用于没有参数更新的自定义层。 def multi_input(input): input1 = input[0] input2 = input[1] input3 = input[3] x = Lambda(multi_input)([q,y,z]) 之后input1 = q , input2 = y, input3 = z
50fa0e9be4d7dadc0aad8eada7de2ecb362e3ba0
seefs/Source_Insight
/node/Pythons/py_test/test_list_trans.py
1,163
4.25
4
 dict = {'name': 'Zara', 'age': 7, 'class': 'First'} # 字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'} print type(str(dict)), str(dict) # 字典可以转为元组,返回:('age', 'name', 'class') print tuple(dict) # 字典可以转为元组,返回:(7, 'Zara', 'First') print tuple(dict.values()) # 字典转为列表,返回:['age', 'name', 'class'] p...
c4445e511f263facc56920d74bc150b935b0a3c4
chinatsui/DimondDog
/algorithm/exercise/binary_tree/binary_tree_maximum_path_sum.py
994
3.796875
4
""" LeetCode-124 Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Inpu...
fa46530a341a5da922e5da44ae9f46cca6662e4a
chinatsui/DimondDog
/algorithm/exercise/dp/house_robber_iii.py
2,667
3.796875
4
""" LeetCode-337 The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically ...
ebc7df4ae328899ca1299f18f329afa56c3e2bc9
chinatsui/DimondDog
/algorithm/exercise/stack/evaluate_reverse_polish_notation.py
1,872
3.9375
4
""" LeetCode-150 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would...
eddb8f91cea6cdf36c06fff8584ab053e5d4ba25
chinatsui/DimondDog
/algorithm/exercise/dp/best_time_to_buy_and_sell_stock_iii.py
1,635
3.984375
4
""" LeetCode-123 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). ...
3179a99c384c7f4a7dee5bfed72216b4ccab1f40
chinatsui/DimondDog
/algorithm/exercise/matrix/surrounded_regions.py
5,120
4.0625
4
""" LeetCode-130 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. Example: X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X E...
5f55a65e992f66c403bf1a931b6a2c95c1a826bf
chinatsui/DimondDog
/algorithm/exercise/binary_search/find_min_in_rotated_sorted_array_ii.py
851
3.671875
4
""" LeetCode-154 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. The array may contain duplicates. Example 1: Input: [1,3,5] Output: 1 Example 2: Input: [2,2,2,0,1] Output: 0 Note: Thi...
745e92fd2ac9939f033ced663279eedcc0420e40
chinatsui/DimondDog
/algorithm/exercise/bfs/word_ladder.py
2,213
3.984375
4
""" LeetCode-127 Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed...
44a7f324bf07cd9c1d09a583f8b7f60d049e0821
chinatsui/DimondDog
/algorithm/exercise/stack/find_first_large_num.py
696
3.984375
4
""" Given an array of integers arr1, return an array arr2 in which arr2[i] happens to be the first num larger than arr1[i]. Example: Input: [1, 3, -4, 6, 5] Output: [3, 6, 6, 6, 5] """ class Solution: @staticmethod def find_first_larger_nums(nums): if not nums: return nums res = ...
576d5aa5b5f35bc8d58ad5d994a4ff2c33a41239
chinatsui/DimondDog
/algorithm/exercise/hash_table/contains_duplicate_ii.py
755
3.5
4
""" LeetCode-219 Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Out...
1a438abdb928d2eb6b667804cc1d707f412b21c5
chinatsui/DimondDog
/algorithm/exercise/bst/delete_node_in_bst.py
2,305
3.8125
4
""" LeetCode-450 Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexi...
4bea2aa9f65dc46094022529b2666bd0ebd4a252
chinatsui/DimondDog
/algorithm/exercise/hash_table/find_two_squares_sum.py
943
4.3125
4
""" Given a number 'num', find another two numbers 'a' and 'b' to make pow(a,2) + pow(b,2) = num, then return [a,b] If there doesn't exist such a pair of numbers, return an empty array. Example 1: Input: 58. Output: [3, 7] Explanation: 3^2 + 7^2 = 58 Example 2: Input: 12. Output: [] Explanation: There doesn't exist a...
9e9759515ab669fa97e36d2608565f191c654698
chinatsui/DimondDog
/algorithm/exercise/bst/construct_bst_from_preorder.py
1,013
3.75
4
""" LeetCode-1008 Return the root node of a binary search tree that matches the given preorder traversal. """ from algorithm.core.binary_tree import BinaryTree, TreeNode class Solution: def bst_from_preorder(self, preorder) -> TreeNode: return self._construct(preorder, 0, len(preorder) - 1) def _con...
622bf19bd00c4c31f4d72ba42500b8ba1345db5d
chinatsui/DimondDog
/algorithm/exercise/binary_search/find_the_duplicate_number.py
1,893
3.921875
4
""" LeetCode-287 Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: [1,3,4,2,2] Output: 2 Example 2: Input: [3,1,3,4,2] Output: ...
49d820ebaf0324b2768548380103b17b516f3f3e
chinatsui/DimondDog
/algorithm/exercise/greedy/uncrossed_time_range_at_most.py
787
3.734375
4
""" Given multiple time ranges: [l1, r1], [l2, r2], [l3, r3], find the uncrossed time ranges at most between start_time and end_time. Example: Given: ranges = [6,8], [2,4], [3,5], [1,5], [5,9], [8,10], start_time = 1, end_time = 10 Result: [2,4], [6,8], [8,10] """ class Solution: @staticmethod def find_at_m...
ad3d3c1391285da2edb8d8e3093bdf42b6229ab7
chinatsui/DimondDog
/algorithm/exercise/binary_search/find_smallest_letter_greater_than_target.py
2,151
4.03125
4
""" LeetCode-744 Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. ...
079df767f942e053cc7c3da2ac52b214e2f76dd9
chinatsui/DimondDog
/algorithm/exercise/dfs/flatten_binary_tree_to_linked_list.py
1,324
4.21875
4
""" LeetCode-114 Given a binary tree, flatten it to a linked list in-place. For example, given the following tree: 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 """ from algorithm.core.binary_tree import Bin...
877454c704f63209cf9add36afad084a48d4a833
chinatsui/DimondDog
/algorithm/exercise/arr_str/minimum_size_subarray_sum.py
970
3.59375
4
""" LeetCode-209 Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem c...
f09a9ff30ce51ce649cde7d8dccb90c1b5b3c536
chinatsui/DimondDog
/algorithm/exercise/arr_str/three_sum_closest.py
1,456
3.890625
4
""" LeetCode-16 Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that...
8cc0098cb8f8632608a151d3b7767d43fd5bd03b
pacheco-andres/nuevos-archivos-
/venta_libros.py
912
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- books = {"matematicas": 100, "espaniol": 90, "biologia": 70, "historia": 80, "fisica":110} def show_books(): counter = 1 print("VENTA DE LIBROS") for book in books.keys(): print ('%s.- %s') %(counter, book) counter += 1 def get_input(): tr...
072c4a38e860aa17c3d63d3bc822beddf6dc5d45
TomaszekB/Python-Codes
/Bubble.py
368
3.828125
4
def sort(list): x = len(list) while x > 1: change = False for i in range(0, x - 1): if list[i] > list[i + 1]: list[i], list[i + 1] = list[i + 1], list[i] change = True x -= 1 print(list) if not change: break ...
39b43518f6f7aa0705f0f6c914de4fd9fa709fcd
jpnahuelpan/algorithms
/ReadFileInts.py
316
3.5
4
from typing import List class ReadInts(): def __init__(self, file: str) -> None: self._file = file def read(self) -> List: f = open(self._file, "r") list_ints: List[int] = [] for line in f: list_ints.append(int(line)) f.close() return list_ints
7b77bc49c356778eddff57598b23036f585b411b
A01374496/Tarea-04
/venta de software.py
876
3.65625
4
# encoding UTF-8 # Autor: Andrea Montero Rivas, A01374496 # Descripcion: Convierte numero decimal a romano. def calcularDescuento(precio, cantidad): if cantidad >= 10 and cantidad<= 19: precioConDescuento = precio - precio * 0.20 return precioConDescuento if cantidad >= 20 and cantidad<= 49: ...
9e222c55f96f099f3ce3da32b07f6579782c67c8
cyc19950621/python--
/质数判定01.py
411
3.796875
4
#输入数据 n = int(input('输入大于1的整数:')) #if判定是否为大于一的整数 if type(n) == int and n > 1: #判定质数 for i in range(2,n): if (n % i)==0: print(n,"不是质数") break else: print(n,"是质数") else: print("请输入大于1的整数") #当输入2 时无对应值,且输入带小数点的整数无法正确识别
78e0f229c36e49ac520f770c692e03b554849249
olga-fomicheva/codeWarsMySolutions
/5Kyu/MovingZerosToTheEnd.py
190
3.8125
4
def move_zeros(array): zeros = [x for x in array if x == 0 and type(x) == int or type(x) == float] non_zeros = [x for x in array if x != 0 or x is False] return non_zeros + zeros
05608bcf2a85a0502d8f8f654abf2355b45cf696
olga-fomicheva/codeWarsMySolutions
/6Kyu/FindTheMissingLetter.py
516
4.0625
4
def find_missing_letter(chars): abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] upper = chars[0].isupper() chars = [x.lower() if upper == True else x for x in chars] letter_position = abc.index((chars[0])) abc_cut = abc[letter_position:...
2babc323f1ff7b55a22ba89029f08dce78974535
ShuailingZhao/toolsPy
/reNameImages.py
736
3.75
4
# -*- coding: utf-8 -*- #python3 import os import sys def rename(): path = input("路径(例如D:\\\\picture):") name = input("新文件开头名:") startNumber = input("起始数字:") fileType = input("文件类型(如 .jpg、.txt等等):") count = 0 filelist = os.listdir(path) filelist.sort() for file in filelist: ...
7fba688e38fd71770a82e5fd1b679b3310b07eb0
JeremyJMoss/NumberGuessingGame
/main.py
837
4.125
4
import random print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100") randomNum = random.randint(1, 101); difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") if difficulty == "easy": attempts = 10 else: attempts = 5 game_over = False while game_over == False...
c907b392e1ee740c0f8d88935014170850865099
award96/teach_python
/B-variables.py
1,489
4.53125
5
""" Variables are necessary to keep track of data, objects, whatever. Each variable in Python has a name and a pointer. The name is how you call the variable ('a' in the lines below) and the pointer 'points' to the object in memory. The pointer can change as you reassign the variable (as I do below) This is import...
e3ad92a2eab93eb351c52ebe4d8cc289cad272ec
ni-ela/uri-exercicios
/lista1/1116-divisionxy.py
554
3.765625
4
# com N vezes de entrada, imprimir a divisao do par x por y, se erro, printar "divisao impossivel". #le N (qtde) n = int(input()) # inicializa lista vazia para servir como print final result = [] for i in range(0, n): x, y = map(float, input().split()) #verifica se y é 0, se nao, divide normalmente, em amb...
0edbc7bbe7325481751179459482acd19b46518a
ni-ela/uri-exercicios
/lista1/1133-rest.py
678
3.90625
4
# ler int X e Y e imprimir todos os números entre X e Y que dividido por 5 o resto é igual a 2 ou igual a 3 # recebe inicio e fim do intervalo x =int(input()) y =int(input()) # com operador ternário, verfifica qual o inicio e fim na ordem crescente i = (x if x<y else y) f = (y if x<y else x) # O percorre, verifica v...
fe3972ea9ed1f5aa304224b39a650659a0ffc906
shibeebit/CSB04
/XO.py
587
4.03125
4
def new_board(): new_board = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] return new_board def print_board(board): for row in range(3): print(row + 1, end=' ') for col in range(3): if board[row][col] == 0: print('| ', end = ' ') ...
30c652fb98125a4108aa66ba514cd70e29983d12
Beaudon/ml-python
/ch01/linear-scikit.py
2,153
3.546875
4
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import linear_model # Load the data oecd_bli = pd.read_csv("/Users/ferro/trainings/ml-python/datasets/lifesat/oecd_bli_2015.csv", thousands=',') # Pay attention to the different properties we can set while reading th...
22a150a0376fd45039382884af457d5793987ac0
sharp30/Ping-Pong
/code/Score.py
492
3.546875
4
import config class Score: def __init__(self): self.left = 0 self.right = 0 #change score def inc_score(self,side): if side: self.right += 1 print("Right ++") else: self.left += 1 print("Left ++") #return list ...
bc3847ae090e44e87a9579de0a4c51e6eee78278
iGordongwb/daily_practice
/0001/0001.py
487
3.75
4
# -*- coding: UTF-8 -*- import random """ num 48-57 upperC 65-90 lowerC 97-112 """ Length = 10 Num = 5 def create_key(): key = "" for i in range(Length): x = random.randint(0,61) if x < 10: x = x + 48 elif x < 36: x = x + 55 else: x = x ...
b212405e5f0be9ab24ed7f28805db87b28631508
inwk6312fall2017/programming-task-final-kr4165835
/task1.py
796
3.859375
4
file1=open("Book1.txt" , 'r') file2=open("Book2.txt" , 'r') file3=open("Book3.txt" , 'r') #read Book1 , book2 , book3 read1=file1.read() readword1=read1.split() read2=file2.read() readword2=read2.split() read3=file3.read() readword3=read3.split() maxlen=0 def findA(readword) for word in readword: if len(word)>maxl...
60ba10f04d9227a901a11a164c91b0922260607b
surgeboris/python-playground
/measure.py
332
3.5625
4
import time def measure(fn, times=1): start = time.time() result = [fn() for _ in range(times)][0] end = time.time() return end - start, result if __name__ == "__main__": seconds, result = measure((lambda: 2 + 2), times=1000000) print(f"\n\n\nResult is {result}. Average time is {seconds} seco...
a947759e177d2e6834cc234b1ded1f46d739abba
juanlucode/development_mindmaps
/python/ejemplos/triangulo.py
723
3.890625
4
#! /usr/bin/env python class Triangulo(object): numero_de_lados = 3 def __init__(self, angulo1, angulo2, angulo3): self.angulo1 = angulo1 self.angulo2 = angulo2 self.angulo3 = angulo3 def revisar_angulos(self): if self.angulo1 + self.angulo2 + self.angulo3 == 18...
cb980b25cf917cd7ba456ded8e0d8f9e70a05af0
JohnCalhoun/dotfiles
/visible/bin/otl2md
989
3.84375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # """ convert vim outliner files to markdown """ import sys def count_indent(line): """count indentation level will be used later to create headings/sections""" count = 0 for character in line: if character == "\t": count += 1 ...
4fe73f58ddfbce10d3dedc3fc163b044578f1678
Greens-Theorem/Green-Pastures
/isPalindromeGUI.py
1,116
3.609375
4
#Author Cowen M. Hames | June 2021 | Project #13: Palindrome GUI | Version 0.2 from tkinter import * def isPalindrome(): val = word_entry.get() val.strip() forward_val = [] rval = '' for i in val: forward_val.append(i) forward_val.reverse() for i in forward_val: ...